hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
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
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6631e5fe03301e322585f6155b9d652a9c169a1
| 15,337
|
hpp
|
C++
|
pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp
|
robfalck/pyoptsparse
|
c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d
|
[
"CNRI-Python"
] | 26
|
2020-08-25T16:16:21.000Z
|
2022-03-10T08:23:57.000Z
|
pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp
|
robfalck/pyoptsparse
|
c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d
|
[
"CNRI-Python"
] | 90
|
2020-08-24T23:02:47.000Z
|
2022-03-29T13:48:15.000Z
|
pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp
|
robfalck/pyoptsparse
|
c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d
|
[
"CNRI-Python"
] | 25
|
2020-08-24T19:28:24.000Z
|
2022-01-27T21:17:37.000Z
|
/*-------------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */
/* */
/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */
/* Charles Audet - Ecole Polytechnique, Montreal */
/* Gilles Couture - Ecole Polytechnique, Montreal */
/* John Dennis - Rice University, Houston */
/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */
/* Christophe Tribes - Ecole Polytechnique, Montreal */
/* */
/* funded in part by AFOSR and Exxon Mobil */
/* */
/* Author: Sebastien Le Digabel */
/* */
/* Contact information: */
/* Ecole Polytechnique de Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* phone : 1-514-340-6053 #6928 */
/* fax : 1-514-340-5665 */
/* */
/* This program is free software: you can redistribute it and/or modify it under the */
/* terms of the GNU Lesser General Public License as published by the Free Software */
/* Foundation, either version 3 of the License, or (at your option) any later */
/* version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */
/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */
/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License along */
/* with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*-------------------------------------------------------------------------------------*/
/**
\file utils.hpp
\brief Utility functions (headers)
\author Sebastien Le Digabel
\date 2010-03-23
\see utils.cpp
*/
#ifndef __UTILS__
#define __UTILS__
#ifdef USE_MPI
#include <mpi.h>
#endif
#include <cctype>
#include <vector>
#include <set>
#include <list>
#include <iomanip>
#include <cmath>
// use of 'access' or '_access', and getpid() or _getpid():
#ifdef _MSC_VER
#include <io.h>
#include <process.h>
#else
#include <unistd.h>
#endif
#include "defines.hpp"
namespace NOMAD {
/// Convert a string into a NOMAD::bb_input_type.
/**
\param s The string -- \b IN.
\param bbit The NOMAD::bb_input_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_bb_input_type ( const std::string & s , NOMAD::bb_input_type & bbit );
/// Convert a string into a NOMAD::bb_output_type.
/**
\param s The string -- \b IN.
\param bbot The NOMAD::bb_output_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_bb_output_type ( const std::string & s , NOMAD::bb_output_type & bbot );
/// Convert a string into a NOMAD::hnorm_type.
/**
\param s The string -- \b IN.
\param hn The NOMAD::hnorm_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_hnorm_type ( const std::string & s , NOMAD::hnorm_type & hn );
/// Convert a string into a NOMAD::TGP_mode_type.
/**
\param s The string -- \b IN.
\param m The NOMAD::TGP_mode_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_TGP_mode_type ( const std::string & s , NOMAD::TGP_mode_type & m );
/// Convert a string into a multi_formulation_type.
/**
\param s The string -- \b IN.
\param mft The NOMAD::multi_formulation_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_multi_formulation_type ( const std::string & s ,
NOMAD::multi_formulation_type & mft );
/// Convert a string with format "i-j" into two integers i and j.
/**
If s=="*" and if n is defined, then i=0 and j=*n-1.
\param s The string -- \b IN.
\param i The first integer \c i -- \b OUT.
\param j The second integer \c j -- \b OUT.
\param n Number of variables; use \c NULL if unknown
-- \b IN -- \b optional (default = \c NULL).
\param check_order A boolean indicating if \c i and \c j are to be compared
-- \b IN -- \b optional (default = \c true).
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_index_range ( const std::string & s ,
int & i ,
int & j ,
int * n = NULL ,
bool check_order = true );
/// Convert a string in {"QUADRATIC","TGP"} to a \c NOMAD::model_type.
/**
\param s The string -- \b IN.
\param mt The NOMAD::model_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool string_to_model_type ( const std::string & s , NOMAD::model_type & mt );
/// Convert a string in {"YES","NO","Y","N","0","1","TRUE","FALSE"} to a boolean.
/**
\param s The string -- \b IN.
\return An integer equal to \c 0 for \c false, \c 1 for \c true,
and \c -1 if the conversion failed.
*/
int string_to_bool ( const std::string & s );
/// Interpret a list of strings as a direction type.
/**
\param ls The list of strings -- \b IN.
\param dt The NOMAD::direction_type -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool strings_to_direction_type ( const std::list<std::string> & ls ,
NOMAD::direction_type & dt );
/// If a NOMAD::bb_output_type variable corresponds to a constraint.
/**
\param bbot The NOMAD::bb_output_type -- \b IN.
\return A boolean equal to \c true if \c bbot corresponds to a constraint.
*/
bool bbot_is_constraint ( NOMAD::bb_output_type bbot );
/// If a NOMAD::direction_type variable corresponds to a MADS direction.
/**
\param dt The NOMAD::direction_type -- \b IN.
\return A boolean equal to \c true if \c dt corresponds to a MADS direction.
*/
bool dir_is_mads ( NOMAD::direction_type dt );
/// If a NOMAD::direction_type variable corresponds to a GPS direction.
/**
\param dt The NOMAD::direction_type -- \b IN.
\return A boolean equal to \c true if \c dt corresponds to a GPS direction.
*/
bool dir_is_gps ( NOMAD::direction_type dt );
/// If a NOMAD::direction_type variable corresponds to a LT-MADS direction.
/**
\param dt The NOMAD::direction_type -- \b IN.
\return A boolean equal to \c true if \c dt corresponds to a LT-MADS direction.
*/
bool dir_is_ltmads ( NOMAD::direction_type dt );
/// If a NOMAD::direction_type variable corresponds to a random direction.
/**
\param dt The NOMAD::direction_type -- \b IN.
\return A boolean equal to \c true if \c dt corresponds to a random direction.
*/
bool dir_is_random ( NOMAD::direction_type dt );
/// If a NOMAD::direction_type variable corresponds to a Ortho-MADS direction.
/**
\param dt The NOMAD::direction_type -- \b IN.
\return A boolean equal to \c true if \c dt corresponds to a Ortho-MADS direction.
*/
bool dir_is_orthomads ( NOMAD::direction_type dt );
/// If a NOMAD::direction_type variable corresponds to a Ortho-MADS direction using XMesh.
/**
\param dt The NOMAD::direction_type -- \b IN.
\return A boolean equal to \c true if \c dt corresponds to a Ortho-MADS direction using XMesh.
*/
bool dir_is_orthomads_xmesh ( NOMAD::direction_type dt );
/// Check if a set of directions include Ortho-MADS direction.
/**
\param dir_types Set of direction types -- \b IN.
\return A boolean equal to \c true if at
least one direction in the set is
of type Ortho-MADS.
*/
bool dirs_have_orthomads ( const std::set<NOMAD::direction_type> & dir_types );
/// Check if a set of directions include Ortho-MADS direction using XMesh.
/**
\param dir_types Set of direction types -- \b IN.
\return A boolean equal to \c true if at
least one direction in the set is
of type Ortho-MADS+XMesh.
*/
bool dirs_have_orthomads_xmesh ( const std::set<NOMAD::direction_type> & dir_types );
/// Check if a set of direction types include Ortho-MADS N+1 direction.
/**
\param dir_types Set of direction types -- \b IN.
\return A boolean equal to \c true if at
least one direction in the set is
of type Ortho-MADS N+1.
*/
bool dirs_have_orthomads_np1 ( const std::set<NOMAD::direction_type> & dir_types );
/// Construct the n first prime numbers.
/**
\param n The integer \c n-- \b IN.
\param primes An integer array of size \c n for the prime numbers;
must be previously allocated -- \b OUT.
*/
void construct_primes ( int n , int * primes );
/// Decompose a string (sentence) into a list of strings (words).
/**
\param sentence The sentence -- \b IN.
\param words The words -- \b OUT.
*/
void get_words ( const std::string & sentence , std::list<std::string> & words );
/// Check if a file exists and is executable.
/**
\param file_name A string corresponding to a file name -- \b IN.
\return A boolean equal to \c true if the file is executable.
*/
bool check_exe_file ( const std::string & file_name );
/// Check if a file exists and is readable.
/**
\param file_name A string corresponding to a file name -- \b IN.
\return A boolean equal to \c true if the file exists and is readable.
*/
bool check_read_file ( const std::string & file_name );
/// Get the process id (pid); useful for unique random seeds.
/**
\return An integer corresponding to the pid.
*/
int get_pid ( void );
/// Called at the beginning of NOMAD.
/**
\param argc Number of command line arguments.
\param argv Command line arguments.
*/
void begin ( int argc , char ** argv );
/// Called at the end of NOMAD.
void end ( void );
/// Transform an integer into a string.
/**
\param i The integer -- \b IN.
\return The string.
*/
std::string itos ( int i );
/// Transform a unsigned long (size_t) into a string.
/**
\param i The unsigned long -- \b IN.
\return The string.
*/
std::string itos ( size_t i );
/// Put a string into upper cases.
/**
\param s The string -- \b IN/OUT.
*/
void toupper ( std::string & s );
/// Put a list of strings into upper cases.
/**
\param ls The list of strings -- \b IN/OUT.
*/
void toupper ( std::list<std::string> & ls );
/// Convert a string into an integer.
/**
\param s The string -- \b IN.
\param i The integer -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool atoi ( const std::string & s , int & i );
/// Convert a character into an integer.
/**
\param c The character -- \b IN.
\param i The integer -- \b OUT.
\return A boolean equal to \c true if the conversion was possible.
*/
bool atoi ( char c , int & i );
/// Search a list of string inside a string.
/**
\param s The string -- \b IN.
\param ls The list of strings -- \b IN.
\return A boolean equal to \c true if one of the string of ls is in s.
*/
bool string_find ( const std::string & s , const std::list<std::string> & ls );
/// Search a string into another string.
/**
\param s1 A string -- \b IN.
\param s2 A string -- \b IN.
\return A boolean equal to \c true if \c s2 is in \c s1.
*/
bool string_find ( const std::string & s1 , const std::string & s2 );
/// Search if a string matches an element in a list of string.
/**
\param s A string -- \b IN.
\param ls A list of strings -- \b IN.
\return A boolean equal to \c true if \c s matches an element in \c ls.
*/
bool string_match ( const std::string & s , const std::list<std::string> & ls );
/// SVD decomposition.
/**
- The \c mxn \c M matrix is decomposed into \c M=U.W.V'.
\param error_msg Error message when the function returns \c false -- \b OUT.
\param M The input \c mxn matrix; Will be replaced by \c U -- \b IN/OUT.
\param W The output \c nxn diagonal matrix -- \b OUT.
\param V The output \c nxn matrix -- \b OUT.
\param m Number of rows in M -- \b IN.
\param n Number of columns in M -- \b IN.
\param max_mpn Maximum allowed value for \c m+n; ignored if \c <=0 -- \b IN
-- \b optional (default = \c 1500).
\return A boolean equal to \c true if the decomposition worked.
*/
bool SVD_decomposition ( std::string & error_msg ,
double ** M ,
double * W ,
double ** V ,
int m ,
int n ,
int max_mpn = 1500 );
// Get rank of a matrix using SVD decomposition
/**
- The \c mxn \c M matrix is decomposed into \c M=U.W.V'. The rank equals the size of W
\param M The input \c mxn matrix -- \b IN.
\param m Number of rows in M -- \b IN.
\param n Number of columns in M -- \b IN.
\return The rank>0 if the decomposition worked else 0.
*/
int get_rank(double **M,
size_t m,
size_t n);
}
#endif
| 39.528351
| 101
| 0.539936
|
robfalck
|
b667ce76b759e26185617e0e079688bbd23bc02c
| 10,723
|
cpp
|
C++
|
test/systemtest/common/distributedpermission/distributed_permission_duid_transform_test/bundle_grant.cpp
|
openharmony-sig-ci/security_permission
|
50f01f7890efa8a967178b4b9553e86254854db9
|
[
"Apache-2.0"
] | null | null | null |
test/systemtest/common/distributedpermission/distributed_permission_duid_transform_test/bundle_grant.cpp
|
openharmony-sig-ci/security_permission
|
50f01f7890efa8a967178b4b9553e86254854db9
|
[
"Apache-2.0"
] | null | null | null |
test/systemtest/common/distributedpermission/distributed_permission_duid_transform_test/bundle_grant.cpp
|
openharmony-sig-ci/security_permission
|
50f01f7890efa8a967178b4b9553e86254854db9
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2021 Huawei Device Co., 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 <cstdio>
#include <fstream>
#include <sstream>
#include <chrono>
#include <gtest/gtest.h>
#include <mutex>
#include <iostream>
#include <thread>
#include "system_test_distributed_permission_util.h"
#include "distributed_permission_kit.h"
#include "bundle_info.h"
#include "permission_definition.h"
#include "parameter.h"
#include "permission_kit.h"
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::Security::Permission;
using namespace OHOS::STPermissionUtil;
using std::string;
namespace {
static const std::string permission_wifi = "ohos.permission.GET_WIFI_INFO";
static const std::string permission_network = "ohos.permission.GET_NETWORK_INFO";
static const std::string permission_location = "ohos.permission.LOCATION_IN_BACKGROUND";
static const std::string permission_camera = "ohos.permission.CAMERA";
static const std::string permission_microphone = "ohos.permission.MICROPHONE";
static const std::string permission_myself1 = "ohos.permission.MYPERMISSION_1";
static const std::string permission_myself2 = "ohos.permission.MYPERMISSION_2";
} // namespace
class BundleGrant : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void BundleGrant::SetUpTestCase(void)
{}
void BundleGrant::TearDownTestCase(void)
{}
void BundleGrant::SetUp(void)
{}
void BundleGrant::TearDown(void)
{}
/**
* @tc.number : DPMS_BundleGrant_0100
* @tc.name : BundleGrant
* @tc.desc : THIRD_INCLUDE_USE_BY_lOCAL_BUNDLE_NAME_ADD_V1
*/
HWTEST_F(BundleGrant, DPMS_BundleGrant_0100, TestSize.Level1)
{
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0100 start";
STDistibutePermissionUtil::Install(THIRD_INCLUDE_USE_BY_lOCAL_HAP_NAME_ADD_V1);
std::string bundleName = THIRD_INCLUDE_USE_BY_lOCAL_BUNDLE_NAME_ADD_V1;
std::vector<OHOS::Security::Permission::PermissionDef> permDefList;
// system grant
OHOS::Security::Permission::PermissionDef permissionDef_network = {.permissionName = permission_network,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_wifi = {.permissionName = permission_wifi,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_location = {.permissionName = permission_location,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
// user grant
OHOS::Security::Permission::PermissionDef permissionDef_camera = {.permissionName = permission_camera,
.bundleName = bundleName,
.grantMode = 0,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_microphone = {.permissionName = permission_microphone,
.bundleName = bundleName,
.grantMode = 0,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
// custom grant
OHOS::Security::Permission::PermissionDef permissionDef_myself1 = {.permissionName = permission_myself1,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_myself2 = {.permissionName = permission_myself2,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
permDefList.emplace_back(permissionDef_network);
permDefList.emplace_back(permissionDef_wifi);
permDefList.emplace_back(permissionDef_location);
permDefList.emplace_back(permissionDef_camera);
permDefList.emplace_back(permissionDef_microphone);
permDefList.emplace_back(permissionDef_myself1);
permDefList.emplace_back(permissionDef_myself2);
PermissionKit::AddDefPermissions(permDefList);
// system grant
std::vector<std::string> permList_system;
permList_system.push_back(permission_network);
permList_system.push_back(permission_wifi);
permList_system.push_back(permission_location);
permList_system.push_back(permission_myself1);
permList_system.push_back(permission_myself2);
PermissionKit::AddSystemGrantedReqPermissions(bundleName, permList_system);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_network);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_wifi);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_location);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_myself1);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_myself2);
// user grant
std::vector<std::string> permList_user;
permList_user.push_back(permission_camera);
permList_user.push_back(permission_microphone);
PermissionKit::AddUserGrantedReqPermissions(bundleName, permList_user, 0);
PermissionKit::GrantUserGrantedPermission(bundleName, permission_camera, 0);
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0100 end";
}
/**
* @tc.number : DPMS_BundleGrant_0200
* @tc.name : BundleGrant
* @tc.desc : SYSTEM_INCLUDE_USE_BY_lOCAL_HAP_NAME_ADD_V1
*/
HWTEST_F(BundleGrant, DPMS_BundleGrant_0200, TestSize.Level1)
{
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0200 start";
std::string bundleName = SYSTEM_INCLUDE_USE_BY_lOCAL_BUNDLE_NAME_ADD_V1;
std::vector<OHOS::Security::Permission::PermissionDef> permDefList;
// system grant
OHOS::Security::Permission::PermissionDef permissionDef_network = {.permissionName = permission_network,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_wifi = {.permissionName = permission_wifi,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_location = {.permissionName = permission_location,
.bundleName = bundleName,
.grantMode = 1,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
// user grant
OHOS::Security::Permission::PermissionDef permissionDef_camera = {.permissionName = permission_camera,
.bundleName = bundleName,
.grantMode = 0,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
OHOS::Security::Permission::PermissionDef permissionDef_microphone = {.permissionName = permission_microphone,
.bundleName = bundleName,
.grantMode = 0,
.availableScope = 1 << 0,
.label = "test label",
.labelId = 9527,
.description = "test description",
.descriptionId = 9528};
permDefList.emplace_back(permissionDef_network);
permDefList.emplace_back(permissionDef_wifi);
permDefList.emplace_back(permissionDef_location);
permDefList.emplace_back(permissionDef_camera);
permDefList.emplace_back(permissionDef_microphone);
PermissionKit::AddDefPermissions(permDefList);
// system grant
std::vector<std::string> permList_system;
permList_system.push_back(permission_network);
permList_system.push_back(permission_wifi);
permList_system.push_back(permission_location);
PermissionKit::AddSystemGrantedReqPermissions(bundleName, permList_system);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_network);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_wifi);
PermissionKit::GrantSystemGrantedPermission(bundleName, permission_location);
// user grant
std::vector<std::string> permList_user;
permList_user.push_back(permission_camera);
permList_user.push_back(permission_microphone);
PermissionKit::AddUserGrantedReqPermissions(bundleName, permList_user, 0);
PermissionKit::GrantUserGrantedPermission(bundleName, permission_camera, 0);
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0200 end";
}
/**
* @tc.number : DPMS_BundleGrant_0300
* @tc.name : BundleGrant
* @tc.desc : THIRD_MORETHAN_MAXPERMISSION_HAP_NAME
*/
HWTEST_F(BundleGrant, DPMS_BundleGrant_0300, TestSize.Level1)
{
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0300 start";
STDistibutePermissionUtil::Install(THIRD_MORETHAN_MAXPERMISSION_HAP_NAME);
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0300 end";
}
/**
* @tc.number : DPMS_BundleGrant_0400
* @tc.name : BundleGrant
* @tc.desc : THIRD_EQ_MAXPERMISSION_HAP_NAME
*/
HWTEST_F(BundleGrant, DPMS_BundleGrant_0400, TestSize.Level1)
{
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0400 start";
STDistibutePermissionUtil::Install(THIRD_EQ_MAXPERMISSION_HAP_NAME);
GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0400 end";
}
| 40.617424
| 114
| 0.71687
|
openharmony-sig-ci
|
b668260f577763c195ed675b033a0508f6143c98
| 2,095
|
hpp
|
C++
|
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
|
Mechap/ODFAEG
|
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
|
[
"Zlib"
] | null | null | null |
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
|
Mechap/ODFAEG
|
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
|
[
"Zlib"
] | 1
|
2020-02-14T14:19:44.000Z
|
2020-12-04T17:39:17.000Z
|
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
|
Mechap/ODFAEG
|
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
|
[
"Zlib"
] | 2
|
2021-05-23T13:45:28.000Z
|
2021-07-24T13:36:13.000Z
|
#ifndef ODFAEG_PARTICLES_UPDATER_HPP
#define ODFAEG_PARTICLES_UPDATER_HPP
#include "../Physics/particuleSystem.h"
#include "../Graphics/world.h"
#include "export.hpp"
/**
*\namespace odfaeg
* the namespace of the Opensource Development Framework Adapted for Every Games.
*/
namespace odfaeg {
namespace graphic {
/**
* \file entitiesUpdater.h
* \class EntitiesUpdater
* \brief update all the entities in the world which are in the current view with a thread.
* \author Duroisin.L
* \version 1.0
* \date 1/02/2014
*/
class ODFAEG_CORE_API ParticleSystemUpdater : public core::EntitySystem {
public :
ParticleSystemUpdater() : EntitySystem() {}
/**
* \fn void onUpdate ()
* \brief update all the entities which are in the current view.
*/
void addParticleSystem(Entity* ps) {
particleSystems.push_back(ps);
}
void removeParticleSystem (Entity* ps) {
std::vector<Entity*>::iterator it;
for (it = particleSystems.begin(); it != particleSystems.end();) {
if (*it == ps) {
it = particleSystems.erase(it);
} else {
it++;
}
}
}
std::vector<Entity*> getParticleSystems() {
return particleSystems;
}
void onUpdate () {
for (unsigned int i = 0; i < particleSystems.size(); i++) {
//std::cout<<"update particle"<<std::endl;
particleSystems[i]->update();
if (odfaeg::core::Application::app != nullptr)
particleSystems[i]->update(odfaeg::core::Application::app->getClock("LoopTime").getElapsedTime());
}
//World::changeVisibleEntity(nullptr, nullptr);
}
private :
std::vector<Entity*> particleSystems;
};
}
}
#endif
| 35.508475
| 122
| 0.521718
|
Mechap
|
b6688abaa85db28771b30ef347123aa7d8eef7b2
| 589
|
cpp
|
C++
|
Chapter07/Source_Code/fifth.cpp
|
ngdzu/CPP-Reactive-Programming
|
e1a19feb40be086d47227587b8ed3d509b7518ca
|
[
"MIT"
] | 98
|
2018-07-03T08:55:31.000Z
|
2022-03-21T22:16:58.000Z
|
Chapter07/Source_Code/fifth.cpp
|
ngdzu/CPP-Reactive-Programming
|
e1a19feb40be086d47227587b8ed3d509b7518ca
|
[
"MIT"
] | 1
|
2020-11-30T10:38:58.000Z
|
2020-12-15T06:56:20.000Z
|
Chapter07/Source_Code/fifth.cpp
|
ngdzu/CPP-Reactive-Programming
|
e1a19feb40be086d47227587b8ed3d509b7518ca
|
[
"MIT"
] | 54
|
2018-07-06T02:09:27.000Z
|
2021-11-10T08:42:50.000Z
|
#include "rxcpp/rx.hpp"
#include "rxcpp/rx-test.hpp"
#include <iostream>
#include <array>
int main() {
auto values = rxcpp::observable<>::range(1); // infinite (until overflow) stream of integers
auto s1 = values.
take(3).
map([](int prime) { return std::make_tuple("1:", prime);});
auto s2 = values.
take(3).
map([](int prime) { return std::make_tuple("2:", prime);});
s1.
concat(s2).
subscribe(rxcpp::util::apply_to(
[](const char* s, int p) {
printf("%s %d\n", s, p);
}));
}
| 19.633333
| 93
| 0.521222
|
ngdzu
|
b66acee2264e702e72c3a5d8f328a6aabaeff3be
| 1,780
|
hpp
|
C++
|
test/testutil/literals.hpp
|
soramitsu/kagome
|
d66755924477f2818fcae30ba2e65681fce34264
|
[
"Apache-2.0"
] | 110
|
2019-04-03T13:39:39.000Z
|
2022-03-09T11:54:42.000Z
|
test/testutil/literals.hpp
|
soramitsu/kagome
|
d66755924477f2818fcae30ba2e65681fce34264
|
[
"Apache-2.0"
] | 890
|
2019-03-22T21:33:30.000Z
|
2022-03-31T14:31:22.000Z
|
test/testutil/literals.hpp
|
soramitsu/kagome
|
d66755924477f2818fcae30ba2e65681fce34264
|
[
"Apache-2.0"
] | 27
|
2019-06-25T06:21:47.000Z
|
2021-11-01T14:12:10.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_TEST_TESTUTIL_LITERALS_HPP_
#define KAGOME_TEST_TESTUTIL_LITERALS_HPP_
#include <libp2p/multi/multiaddress.hpp>
#include <libp2p/multi/multihash.hpp>
#include <libp2p/peer/peer_id.hpp>
#include "common/blob.hpp"
#include "common/buffer.hpp"
#include "common/hexutil.hpp"
using namespace kagome::common::literals;
inline kagome::common::Hash256 operator"" _hash256(const char *c, size_t s) {
kagome::common::Hash256 hash{};
std::copy_n(c, std::min(s, 32ul), hash.rbegin());
return hash;
}
inline std::vector<uint8_t> operator"" _v(const char *c, size_t s) {
std::vector<uint8_t> chars(c, c + s);
return chars;
}
inline std::vector<uint8_t> operator""_unhex(const char *c, size_t s) {
if (s > 2 and c[0] == '0' and c[1] == 'x')
return kagome::common::unhexWith0x(std::string_view(c, s)).value();
return kagome::common::unhex(std::string_view(c, s)).value();
}
inline libp2p::multi::Multiaddress operator""_multiaddr(const char *c,
size_t s) {
return libp2p::multi::Multiaddress::create(std::string_view(c, s)).value();
}
/// creates a multihash instance from a hex string
inline libp2p::multi::Multihash operator""_multihash(const char *c, size_t s) {
return libp2p::multi::Multihash::createFromHex(std::string_view(c, s))
.value();
}
inline libp2p::peer::PeerId operator""_peerid(const char *c, size_t s) {
// libp2p::crypto::PublicKey p;
auto data = std::vector<uint8_t>(c, c + s);
libp2p::crypto::ProtobufKey pb_key(std::move(data));
using libp2p::peer::PeerId;
return PeerId::fromPublicKey(pb_key).value();
}
#endif // KAGOME_TEST_TESTUTIL_LITERALS_HPP_
| 31.22807
| 79
| 0.688764
|
soramitsu
|
b66c3580439d08af4319f8072336ef728b6ec2b6
| 7,276
|
cpp
|
C++
|
gme/src/v20180711/model/CreateAppRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 43
|
2019-08-14T08:14:12.000Z
|
2022-03-30T12:35:09.000Z
|
gme/src/v20180711/model/CreateAppRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 12
|
2019-07-15T10:44:59.000Z
|
2021-11-02T12:35:00.000Z
|
gme/src/v20180711/model/CreateAppRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 28
|
2019-07-12T09:06:22.000Z
|
2022-03-30T08:04:18.000Z
|
/*
* Copyright (c) 2017-2019 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 <tencentcloud/gme/v20180711/model/CreateAppRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Gme::V20180711::Model;
using namespace std;
CreateAppRequest::CreateAppRequest() :
m_appNameHasBeenSet(false),
m_projectIdHasBeenSet(false),
m_engineListHasBeenSet(false),
m_regionListHasBeenSet(false),
m_realtimeSpeechConfHasBeenSet(false),
m_voiceMessageConfHasBeenSet(false),
m_voiceFilterConfHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
string CreateAppRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_appNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AppName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_appName.c_str(), allocator).Move(), allocator);
}
if (m_projectIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProjectId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_projectId, allocator);
}
if (m_engineListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EngineList";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_engineList.begin(); itr != m_engineList.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_regionListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RegionList";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_regionList.begin(); itr != m_regionList.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_realtimeSpeechConfHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RealtimeSpeechConf";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_realtimeSpeechConf.ToJsonObject(d[key.c_str()], allocator);
}
if (m_voiceMessageConfHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VoiceMessageConf";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_voiceMessageConf.ToJsonObject(d[key.c_str()], allocator);
}
if (m_voiceFilterConfHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VoiceFilterConf";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_voiceFilterConf.ToJsonObject(d[key.c_str()], allocator);
}
if (m_tagsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tags";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateAppRequest::GetAppName() const
{
return m_appName;
}
void CreateAppRequest::SetAppName(const string& _appName)
{
m_appName = _appName;
m_appNameHasBeenSet = true;
}
bool CreateAppRequest::AppNameHasBeenSet() const
{
return m_appNameHasBeenSet;
}
uint64_t CreateAppRequest::GetProjectId() const
{
return m_projectId;
}
void CreateAppRequest::SetProjectId(const uint64_t& _projectId)
{
m_projectId = _projectId;
m_projectIdHasBeenSet = true;
}
bool CreateAppRequest::ProjectIdHasBeenSet() const
{
return m_projectIdHasBeenSet;
}
vector<string> CreateAppRequest::GetEngineList() const
{
return m_engineList;
}
void CreateAppRequest::SetEngineList(const vector<string>& _engineList)
{
m_engineList = _engineList;
m_engineListHasBeenSet = true;
}
bool CreateAppRequest::EngineListHasBeenSet() const
{
return m_engineListHasBeenSet;
}
vector<string> CreateAppRequest::GetRegionList() const
{
return m_regionList;
}
void CreateAppRequest::SetRegionList(const vector<string>& _regionList)
{
m_regionList = _regionList;
m_regionListHasBeenSet = true;
}
bool CreateAppRequest::RegionListHasBeenSet() const
{
return m_regionListHasBeenSet;
}
RealtimeSpeechConf CreateAppRequest::GetRealtimeSpeechConf() const
{
return m_realtimeSpeechConf;
}
void CreateAppRequest::SetRealtimeSpeechConf(const RealtimeSpeechConf& _realtimeSpeechConf)
{
m_realtimeSpeechConf = _realtimeSpeechConf;
m_realtimeSpeechConfHasBeenSet = true;
}
bool CreateAppRequest::RealtimeSpeechConfHasBeenSet() const
{
return m_realtimeSpeechConfHasBeenSet;
}
VoiceMessageConf CreateAppRequest::GetVoiceMessageConf() const
{
return m_voiceMessageConf;
}
void CreateAppRequest::SetVoiceMessageConf(const VoiceMessageConf& _voiceMessageConf)
{
m_voiceMessageConf = _voiceMessageConf;
m_voiceMessageConfHasBeenSet = true;
}
bool CreateAppRequest::VoiceMessageConfHasBeenSet() const
{
return m_voiceMessageConfHasBeenSet;
}
VoiceFilterConf CreateAppRequest::GetVoiceFilterConf() const
{
return m_voiceFilterConf;
}
void CreateAppRequest::SetVoiceFilterConf(const VoiceFilterConf& _voiceFilterConf)
{
m_voiceFilterConf = _voiceFilterConf;
m_voiceFilterConfHasBeenSet = true;
}
bool CreateAppRequest::VoiceFilterConfHasBeenSet() const
{
return m_voiceFilterConfHasBeenSet;
}
vector<Tag> CreateAppRequest::GetTags() const
{
return m_tags;
}
void CreateAppRequest::SetTags(const vector<Tag>& _tags)
{
m_tags = _tags;
m_tagsHasBeenSet = true;
}
bool CreateAppRequest::TagsHasBeenSet() const
{
return m_tagsHasBeenSet;
}
| 27.456604
| 104
| 0.708356
|
suluner
|
b66fd0f8780dc04af689585987afb0d94d5036cc
| 421
|
cpp
|
C++
|
docker/cytnx/src/utils/is.cpp
|
j9263178/Cytnx
|
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
|
[
"Apache-2.0"
] | 11
|
2020-04-14T15:45:42.000Z
|
2022-03-31T14:37:03.000Z
|
docker/cytnx/src/utils/is.cpp
|
j9263178/Cytnx
|
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
|
[
"Apache-2.0"
] | 38
|
2019-08-02T15:15:51.000Z
|
2022-03-04T19:07:02.000Z
|
docker/cytnx/src/utils/is.cpp
|
j9263178/Cytnx
|
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
|
[
"Apache-2.0"
] | 7
|
2019-07-17T07:50:55.000Z
|
2021-07-03T06:44:52.000Z
|
#include "utils/is.hpp"
namespace cytnx{
bool is(const Tensor &L, const Tensor &R){
return (L._impl == R._impl);
}
bool is(const Storage &L, const Storage &R){
return (L._impl == R._impl);
}
bool is(const Bond &L, const Bond &R){
return (L._impl == R._impl);
}
bool is(const Symmetry &L, const Symmetry &R){
return (L._impl == R._impl);
}
}
| 17.541667
| 50
| 0.534442
|
j9263178
|
b6743871ee08c8b53fa206d97ec911fbcce81f84
| 307
|
cpp
|
C++
|
kmerInput/Statistic.cpp
|
Lw-Cui/kmer-exp
|
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
|
[
"MIT"
] | null | null | null |
kmerInput/Statistic.cpp
|
Lw-Cui/kmer-exp
|
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
|
[
"MIT"
] | null | null | null |
kmerInput/Statistic.cpp
|
Lw-Cui/kmer-exp
|
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
|
[
"MIT"
] | null | null | null |
#include <cstring>
#include <map>
#include <cstdio>
using namespace std;
int main() {
map<int, int> count;
int num;
while (scanf("%*s%d", &num) != EOF)
count[num]++;
for (map<int, int>::iterator p = count.begin();
p != count.end(); p++)
printf("%5d: %10d\n", p->first, p->second);
return 0;
}
| 18.058824
| 48
| 0.586319
|
Lw-Cui
|
b67541f04f69aeaa74a34629e928bf51df5a3ca3
| 273
|
hpp
|
C++
|
include/cpu/cpu.hpp
|
anthony-benavente/chip8emu
|
5ffe96ac252d15bfe0242fc6e1a550844510b31b
|
[
"MIT"
] | null | null | null |
include/cpu/cpu.hpp
|
anthony-benavente/chip8emu
|
5ffe96ac252d15bfe0242fc6e1a550844510b31b
|
[
"MIT"
] | null | null | null |
include/cpu/cpu.hpp
|
anthony-benavente/chip8emu
|
5ffe96ac252d15bfe0242fc6e1a550844510b31b
|
[
"MIT"
] | null | null | null |
#ifndef CPU_H
#define CPU_H
#include "program/program.hpp"
class Cpu {
public:
bool drawFlag;
Cpu() : drawFlag(false) {}
virtual void emulateCycle() = 0;
virtual unsigned char getPixel(int x, int y) = 0;
virtual void loadProgram(program_t *program) = 0;
};
#endif
| 16.058824
| 50
| 0.703297
|
anthony-benavente
|
b679acd2c820753b72efd9f2494a17c0b9797a10
| 250
|
cpp
|
C++
|
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
|
hackerlank/SourceCode
|
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
|
[
"MIT"
] | 4
|
2021-07-31T13:56:01.000Z
|
2021-11-13T02:55:10.000Z
|
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
|
shacojx/SourceCodeGameTLBB
|
e3cea615b06761c2098a05427a5f41c236b71bf7
|
[
"MIT"
] | null | null | null |
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
|
shacojx/SourceCodeGameTLBB
|
e3cea615b06761c2098a05427a5f41c236b71bf7
|
[
"MIT"
] | 7
|
2021-08-31T14:34:23.000Z
|
2022-01-19T08:25:58.000Z
|
#include "StdAfx.h"
#include "CGAskActiveTimeUpdate.h"
uint CGAskActiveTimeUpdateHandler::Execute( CGAskActiveTimeUpdate* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
return PACKET_EXE_CONTINUE ;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR ;
}
| 17.857143
| 93
| 0.808
|
hackerlank
|
b67a171f12c52a9659fcb57e4c506286c0195d73
| 1,337
|
cpp
|
C++
|
Source/KPokemon_DX11/KSpriteEffect.cpp
|
jiwonchoidd/PokemonDP_DX11
|
828ef195c7c66b4c5489944e930acee96940c816
|
[
"BSD-2-Clause"
] | 1
|
2022-03-25T08:55:53.000Z
|
2022-03-25T08:55:53.000Z
|
Source/KPokemon_DX11/KSpriteEffect.cpp
|
jiwonchoidd/PokemonDP_DX11
|
828ef195c7c66b4c5489944e930acee96940c816
|
[
"BSD-2-Clause"
] | null | null | null |
Source/KPokemon_DX11/KSpriteEffect.cpp
|
jiwonchoidd/PokemonDP_DX11
|
828ef195c7c66b4c5489944e930acee96940c816
|
[
"BSD-2-Clause"
] | null | null | null |
#include "KSpriteEffect.h"
bool KSpriteEffect::Init(ID3D11DeviceContext* context, std::wstring vs, std::wstring ps, std::wstring tex, std::wstring mask)
{
m_pContext = context;
m_Current_Index=0;
m_Timer=0.0f;
m_bEnd = false;
m_Color = { 1,1,1,1 };
m_cbData.vLightDir = m_Color;
K2DAsset::CreateObject_Mask(vs,ps,tex,mask);
return true;
}
bool KSpriteEffect::Frame()
{
if (m_bEnd)
{
Reset();
return false;
}
else
{
m_Change_Time = m_pSprite->m_anim_time / m_pSprite->m_anim_array.size();
m_Timer += g_fSecPerFrame;
if (m_Timer >= m_Change_Time)
{
m_Current_Index++;
if (m_Current_Index >= m_pSprite->m_anim_array.size())
{
m_Current_Index = 0;
}
m_Timer -= m_Change_Time;
SetRectSource(m_pSprite->m_anim_array[m_Current_Index]);
/*SetRectDraw({ 0,0,
m_pSprite->m_anim_array[m_Current_Index].right,
m_pSprite->m_anim_array[m_Current_Index].bottom });*/
AddPosition(KVector2(0, 0));
if (m_Current_Index == m_pSprite->m_anim_array.size()-1)
{
m_bEnd = true;
}
}
m_cbData.vLightDir= m_Color;
}
return true;
}
bool KSpriteEffect::Render(ID3D11DeviceContext* pContext)
{
KObject::Render(pContext);
return true;
}
bool KSpriteEffect::Release()
{
KObject::Release();
return true;
}
void KSpriteEffect::Reset()
{
m_Current_Index = 0;
m_Timer = 0.0f;
}
| 19.955224
| 125
| 0.694091
|
jiwonchoidd
|
b67bd357593d19a2c531c0b73853cd0237def5e6
| 8,693
|
cpp
|
C++
|
geocoding/src/geocoding/RevGeocoder.cpp
|
farfromrefug/mobile-carto-libs
|
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
|
[
"BSD-3-Clause"
] | 6
|
2018-06-27T17:43:35.000Z
|
2021-06-29T18:50:49.000Z
|
geocoding/src/geocoding/RevGeocoder.cpp
|
farfromrefug/mobile-carto-libs
|
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
|
[
"BSD-3-Clause"
] | 22
|
2019-04-10T06:38:09.000Z
|
2022-01-20T08:12:02.000Z
|
geocoding/src/geocoding/RevGeocoder.cpp
|
farfromrefug/mobile-carto-libs
|
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
|
[
"BSD-3-Clause"
] | 5
|
2019-03-12T10:25:20.000Z
|
2021-12-28T10:18:56.000Z
|
#include "RevGeocoder.h"
#include "FeatureReader.h"
#include "ProjUtils.h"
#include "AddressInterpolator.h"
#include <functional>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <sqlite3pp.h>
namespace carto { namespace geocoding {
bool RevGeocoder::import(const std::shared_ptr<sqlite3pp::database>& db) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
Database database;
database.id = "db" + std::to_string(_databases.size());
database.db = db;
database.bounds = getBounds(*db);
database.origin = getOrigin(*db);
_databases.push_back(database);
return true;
}
std::string RevGeocoder::getLanguage() const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return _language;
}
void RevGeocoder::setLanguage(const std::string& language) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_language = language;
_addressCache.clear();
}
unsigned int RevGeocoder::getMaxResults() const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return _maxResults;
}
void RevGeocoder::setMaxResults(unsigned int maxResults) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_maxResults = maxResults;
}
bool RevGeocoder::isFilterEnabled(Address::EntityType type) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return std::find(_enabledFilters.begin(), _enabledFilters.end(), type) != _enabledFilters.end();
}
void RevGeocoder::setFilterEnabled(Address::EntityType type, bool enabled) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto it = std::find(_enabledFilters.begin(), _enabledFilters.end(), type);
if (enabled && it == _enabledFilters.end()) {
_enabledFilters.push_back(type);
}
else if (!enabled && it != _enabledFilters.end()) {
_enabledFilters.erase(it);
}
}
std::vector<std::pair<Address, float>> RevGeocoder::findAddresses(double lng, double lat, float radius) const {
std::lock_guard<std::recursive_mutex> lock(_mutex);
std::vector<std::pair<Address, float>> addresses;
for (const Database& database : _databases) {
if (database.bounds) {
// TODO: -180/180 wrapping
cglib::vec2<double> lngLatMeters = wgs84Meters({ lng, lat });
cglib::vec2<double> point = database.bounds->nearest_point({ lng, lat });
cglib::vec2<double> diff = point - cglib::vec2<double>(lng, lat);
double dist = cglib::length(cglib::vec2<double>(diff(0) * lngLatMeters(0), diff(1) * lngLatMeters(1)));
if (dist > radius) {
continue;
}
}
_previousEntityQueryCounter = _entityQueryCounter;
QuadIndex index(std::bind(&RevGeocoder::findGeometryInfo, this, std::cref(database), std::placeholders::_1, std::placeholders::_2));
std::vector<QuadIndex::Result> results = index.findGeometries(lng, lat, radius);
for (const QuadIndex::Result& result : results) {
float rank = 1.0f - static_cast<float>(result.second) / radius;
if (rank > 0) {
Address address;
std::string addrKey = database.id + std::string(1, 0) + std::to_string(result.first);
if (!_addressCache.read(addrKey, address)) {
address.loadFromDB(*database.db, result.first, _language, [&database](const cglib::vec2<double>& pos) {
return database.origin + pos;
});
_addressCache.put(addrKey, address);
}
addresses.emplace_back(address, rank);
}
}
}
std::sort(addresses.begin(), addresses.end(), [](const std::pair<Address, float>& addrRank1, const std::pair<Address, float>& addrRank2) {
return addrRank1.second > addrRank2.second;
});
if (addresses.size() > _maxResults) {
addresses.erase(addresses.begin() + _maxResults, addresses.end());
}
return addresses;
}
std::vector<QuadIndex::GeometryInfo> RevGeocoder::findGeometryInfo(const Database& database, const std::vector<std::uint64_t>& quadIndices, const PointConverter& converter) const {
std::string sql = "SELECT id, features, housenumbers FROM entities WHERE quadindex in (";
for (std::size_t i = 0; i < quadIndices.size(); i++) {
sql += (i > 0 ? "," : "") + std::to_string(quadIndices[i]);
}
sql += ")";
if (!_enabledFilters.empty()) {
std::string values;
for (const Address::EntityType type : _enabledFilters) {
values += (values.empty() ? "" : ",") + std::to_string(static_cast<int>(type));
}
sql += " AND (type IN (" + values + "))";
}
std::vector<QuadIndex::GeometryInfo> geomInfos;
std::string queryKey = database.id + std::string(1, 0) + sql;
if (_queryCache.read(queryKey, geomInfos)) {
return geomInfos;
}
sqlite3pp::query query(*database.db, sql.c_str());
for (auto qit = query.begin(); qit != query.end(); qit++) {
auto entityId = qit->get<unsigned int>(0);
EncodingStream featureStream(qit->get<const void*>(1), qit->column_bytes(1));
FeatureReader featureReader(featureStream, [&database, &converter](const cglib::vec2<double>& pos) {
return converter(database.origin + pos);
});
if (qit->get<const void*>(2)) {
EncodingStream houseNumberStream(qit->get<const void*>(2), qit->column_bytes(2));
AddressInterpolator interpolator(houseNumberStream);
std::vector<std::pair<std::uint64_t, std::vector<Feature>>> idFeatures = interpolator.readAddressesAndFeatures(featureReader);
for (std::size_t i = 0; i < idFeatures.size(); i++) {
std::uint64_t encodedId = (idFeatures[i].first ? static_cast<std::uint64_t>(i + 1) << 32 : 0) | entityId;
std::vector<std::shared_ptr<Geometry>> geometries;
for (const Feature& feature : idFeatures[i].second) {
if (feature.getGeometry()) {
geometries.push_back(feature.getGeometry());
}
}
geomInfos.emplace_back(encodedId, std::make_shared<MultiGeometry>(std::move(geometries)));
}
}
else {
std::vector<std::shared_ptr<Geometry>> geometries;
for (const Feature& feature : featureReader.readFeatureCollection()) {
if (feature.getGeometry()) {
geometries.push_back(feature.getGeometry());
}
}
geomInfos.emplace_back(entityId, std::make_shared<MultiGeometry>(std::move(geometries)));
}
}
_entityQueryCounter++;
_queryCache.put(queryKey, geomInfos);
return geomInfos;
}
cglib::vec2<double> RevGeocoder::getOrigin(sqlite3pp::database& db) {
sqlite3pp::query query(db, "SELECT value FROM metadata WHERE name='origin'");
for (auto qit = query.begin(); qit != query.end(); qit++) {
std::string value = qit->get<const char*>(0);
std::vector<std::string> origin;
boost::split(origin, value, boost::is_any_of(","), boost::token_compress_off);
return cglib::vec2<double>(std::stod(origin.at(0)), std::stod(origin.at(1)));
}
return cglib::vec2<double>(0, 0);
}
std::optional<cglib::bbox2<double>> RevGeocoder::getBounds(sqlite3pp::database& db) {
sqlite3pp::query query(db, "SELECT value FROM metadata WHERE name='bounds'");
for (auto qit = query.begin(); qit != query.end(); qit++) {
std::string value = qit->get<const char*>(0);
std::vector<std::string> bounds;
boost::split(bounds, value, boost::is_any_of(","), boost::token_compress_off);
cglib::vec2<double> min(std::stod(bounds.at(0)), std::stod(bounds.at(1)));
cglib::vec2<double> max(std::stod(bounds.at(2)), std::stod(bounds.at(3)));
return cglib::bbox2<double>(min, max);
}
return std::optional<cglib::bbox2<double>>();
}
} }
| 44.352041
| 184
| 0.579317
|
farfromrefug
|
b67d83c5ba68070fd07f4d78be656de6227e3c02
| 1,291
|
cpp
|
C++
|
src/main/cpp/lemon/test/runner.cpp
|
lemonkit/lemon
|
ad34410586659fc650898b60d7e168797a3d9e5b
|
[
"MIT"
] | 1
|
2018-01-12T05:13:58.000Z
|
2018-01-12T05:13:58.000Z
|
src/main/cpp/lemon/test/runner.cpp
|
lemonkit/lemon
|
ad34410586659fc650898b60d7e168797a3d9e5b
|
[
"MIT"
] | null | null | null |
src/main/cpp/lemon/test/runner.cpp
|
lemonkit/lemon
|
ad34410586659fc650898b60d7e168797a3d9e5b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <lemon/log/log.hpp>
#include <lemon/test/unit.hpp>
#include <lemon/test/macro.hpp>
#include <lemon/test/runner.hpp>
namespace lemon {namespace test{
runner& runner::instance()
{
static runner global;
return global;
}
void runner::run() {
runner::instance().done();
}
void runner::done() {
auto & logger = log::get("test");
for(auto unit : _units)
{
try
{
unit->run();
lemonI(logger,"test(%s) ... ok",unit->name().c_str());
}
catch(const assert & e)
{
lemonE(logger,"test(%s) -- failed\n\terr :%s\n\tfile :%s(%d)",unit->name().c_str(),e.what(),e.file().c_str(),e.lines());
}
catch(const std::exception &e)
{
lemonE(logger,"test(%s) -- failed\n\terr :%s\n\tfile :%s(%d)",unit->name().c_str(),e.what(),unit->file().c_str(),unit->lines());
}
catch(...)
{
lemonE(logger, "test(%s) -- failed\n\terr :unknown exception\n\tfile :%s(%d)", unit->name().c_str(), unit->file().c_str(), unit->lines());
}
}
}
void runner::add(runnable *unit)
{
_units.push_back(unit);
}
}}
| 23.053571
| 144
| 0.490318
|
lemonkit
|
b67dade3529bdcf9a4f95aabe4a68bc55561f546
| 3,298
|
cpp
|
C++
|
src/CBrowserRenderer.cpp
|
colinw7/CBrowser
|
d6aaaf536aa2f2bab0575439b75cf83a6d033db9
|
[
"MIT"
] | 1
|
2021-12-23T02:21:28.000Z
|
2021-12-23T02:21:28.000Z
|
src/CBrowserRenderer.cpp
|
colinw7/CBrowser
|
d6aaaf536aa2f2bab0575439b75cf83a6d033db9
|
[
"MIT"
] | null | null | null |
src/CBrowserRenderer.cpp
|
colinw7/CBrowser
|
d6aaaf536aa2f2bab0575439b75cf83a6d033db9
|
[
"MIT"
] | 2
|
2017-05-04T05:38:49.000Z
|
2019-04-01T13:23:55.000Z
|
#include <CBrowserRenderer.h>
#include <CBrowserWindowWidget.h>
#include <CQUtil.h>
#include <CQPenUtil.h>
#include <CQBrushUtil.h>
#include <CQFontUtil.h>
#include <CQImageUtil.h>
#include <QPainter>
CBrowserRenderer::
CBrowserRenderer(CBrowserWindowWidget *w) :
w_(w), pixmap_(0), painter_(0)
{
pixmap_width_ = 0;
pixmap_height_ = 0;
}
CBrowserRenderer::
~CBrowserRenderer()
{
}
void
CBrowserRenderer::
startDoubleBuffer(int width, int height)
{
if (width != pixmap_width_ || height != pixmap_height_) {
pixmap_width_ = width;
pixmap_height_ = height;
pixmap_ = new QPixmap(pixmap_width_, pixmap_height_);
pixmap_->fill(Qt::black);
}
if (! painter_)
painter_ = new QPainter;
painter_->begin(pixmap_);
}
void
CBrowserRenderer::
endDoubleBuffer()
{
painter_->end();
QPainter painter(w_);
painter.drawPixmap(QPoint(0, 0), *pixmap_);
}
void
CBrowserRenderer::
clear(const CRGBA &bg)
{
painter_->fillRect(QRect(0, 0, pixmap_width_, pixmap_height_),
QBrush(CQUtil::rgbaToColor(bg)));
}
void
CBrowserRenderer::
drawRectangle(const CIBBox2D &bbox, const CPen &pen)
{
painter_->setPen(CQPenUtil::toQPen(pen));
painter_->setBrush(Qt::NoBrush);
painter_->drawRect(CQUtil::toQRect(bbox));
}
void
CBrowserRenderer::
fillRectangle(const CIBBox2D &bbox, const CBrush &brush)
{
painter_->fillRect(CQUtil::toQRect(bbox), CQBrushUtil::toQBrush(brush));
}
void
CBrowserRenderer::
fillPolygon(const std::vector<CIPoint2D> &points, const CBrush &brush)
{
std::vector<QPoint> qpoints;
qpoints.resize(points.size());
for (std::size_t i = 0; i < points.size(); ++i)
qpoints[i] = QPoint(points[i].x, points[i].y);
painter_->setPen(QPen(Qt::NoPen));
painter_->setBrush(CQBrushUtil::toQBrush(brush));
painter_->drawPolygon(&qpoints[0], qpoints.size());
}
void
CBrowserRenderer::
drawCircle(const CIPoint2D &c, int r, const CPen &pen)
{
painter_->setPen(CQPenUtil::toQPen(pen));
painter_->setBrush(Qt::NoBrush);
painter_->drawEllipse(QRect(c.x - r, c.y - r, 2*r, 2*r));
}
void
CBrowserRenderer::
fillCircle(const CIPoint2D &c, int r, const CBrush &brush)
{
painter_->setPen(Qt::NoPen);
painter_->setBrush(CQBrushUtil::toQBrush(brush));
painter_->drawEllipse(QRect(c.x - r, c.y - r, 2*r, 2*r));
}
void
CBrowserRenderer::
drawLine(const CIPoint2D &p1, const CIPoint2D &p2, const CPen &pen)
{
painter_->setPen(CQPenUtil::toQPen(pen));
painter_->drawLine(CQUtil::toQPoint(p1), CQUtil::toQPoint(p2));
}
void
CBrowserRenderer::
drawText(const CIPoint2D &p, const std::string &str, const CPen &pen, const CFontPtr &font)
{
painter_->setPen (CQPenUtil::toQPen(pen));
painter_->setFont(CQFontUtil::toQFont(font));
QPoint qp = CQUtil::toQPoint(p);
if (font->isSubscript())
qp.setY(qp.y() + font->getCharAscent()/2);
else if (font->isSuperscript())
qp.setY(qp.y() - font->getCharAscent()/2);
painter_->drawText(qp, str.c_str());
}
void
CBrowserRenderer::
drawImage(const CIPoint2D &p, const CImagePtr &image)
{
drawImage(p, CQImageUtil::toQImage(image));
}
void
CBrowserRenderer::
drawImage(const CIPoint2D &p, const QImage &image)
{
if (painter_)
painter_->drawImage(CQUtil::toQPoint(p), image);
}
void
CBrowserRenderer::
setFont(CFontPtr font)
{
font_ = font;
}
| 20.358025
| 91
| 0.700121
|
colinw7
|
b67ea9453867e82b38a780ba2df51899ae01d5ea
| 10,108
|
hpp
|
C++
|
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: BeatmapDataSO
#include "GlobalNamespace/BeatmapDataSO.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.Runtime.CompilerServices.IAsyncStateMachine
#include "System/Runtime/CompilerServices/IAsyncStateMachine.hpp"
// Including type: System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1
#include "System/Runtime/CompilerServices/AsyncTaskMethodBuilder_1.hpp"
// Including type: BeatmapDifficulty
#include "GlobalNamespace/BeatmapDifficulty.hpp"
// Including type: System.Runtime.CompilerServices.TaskAwaiter`1
#include "System/Runtime/CompilerServices/TaskAwaiter_1.hpp"
// Including type: System.Runtime.CompilerServices.TaskAwaiter
#include "System/Runtime/CompilerServices/TaskAwaiter.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IReadonlyBeatmapData
class IReadonlyBeatmapData;
// Forward declaring type: EnvironmentInfoSO
class EnvironmentInfoSO;
// Forward declaring type: PlayerSpecificSettings
class PlayerSpecificSettings;
}
// Forward declaring namespace: BeatmapSaveDataVersion3
namespace BeatmapSaveDataVersion3 {
// Forward declaring type: BeatmapSaveData
class BeatmapSaveData;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2, "", "BeatmapDataSO/<GetBeatmapDataAsync>d__2");
// Type namespace:
namespace GlobalNamespace {
// WARNING Size may be invalid!
// Autogenerated type: BeatmapDataSO/<GetBeatmapDataAsync>d__2
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
struct BeatmapDataSO::$GetBeatmapDataAsync$d__2/*, public ::System::ValueType, public ::System::Runtime::CompilerServices::IAsyncStateMachine*/ {
public:
public:
// public System.Int32 <>1__state
// Size: 0x4
// Offset: 0x0
int $$1__state;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<IReadonlyBeatmapData> <>t__builder
// Size: 0xFFFFFFFF
// Offset: 0x8
::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*> $$t__builder;
// public BeatmapDifficulty beatmapDifficulty
// Size: 0x4
// Offset: 0x20
::GlobalNamespace::BeatmapDifficulty beatmapDifficulty;
// Field size check
static_assert(sizeof(::GlobalNamespace::BeatmapDifficulty) == 0x4);
// public System.Single beatsPerMinute
// Size: 0x4
// Offset: 0x24
float beatsPerMinute;
// Field size check
static_assert(sizeof(float) == 0x4);
// public System.Boolean loadingForDesignatedEnvironment
// Size: 0x1
// Offset: 0x28
bool loadingForDesignatedEnvironment;
// Field size check
static_assert(sizeof(bool) == 0x1);
// public EnvironmentInfoSO environmentInfo
// Size: 0x8
// Offset: 0x30
::GlobalNamespace::EnvironmentInfoSO* environmentInfo;
// Field size check
static_assert(sizeof(::GlobalNamespace::EnvironmentInfoSO*) == 0x8);
// public PlayerSpecificSettings playerSpecificSettings
// Size: 0x8
// Offset: 0x38
::GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings;
// Field size check
static_assert(sizeof(::GlobalNamespace::PlayerSpecificSettings*) == 0x8);
// public BeatmapDataSO <>4__this
// Size: 0x8
// Offset: 0x40
::GlobalNamespace::BeatmapDataSO* $$4__this;
// Field size check
static_assert(sizeof(::GlobalNamespace::BeatmapDataSO*) == 0x8);
// private BeatmapDataSO/<>c__DisplayClass2_0 <>8__1
// Size: 0x8
// Offset: 0x48
::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0* $$8__1;
// Field size check
static_assert(sizeof(::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0*) == 0x8);
// private System.Runtime.CompilerServices.TaskAwaiter`1<BeatmapSaveDataVersion3.BeatmapSaveData> <>u__1
// Size: 0xFFFFFFFF
// Offset: 0x50
::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*> $$u__1;
// private System.Runtime.CompilerServices.TaskAwaiter <>u__2
// Size: 0x8
// Offset: 0x58
::System::Runtime::CompilerServices::TaskAwaiter $$u__2;
// Field size check
static_assert(sizeof(::System::Runtime::CompilerServices::TaskAwaiter) == 0x8);
public:
// Creating value type constructor for type: $GetBeatmapDataAsync$d__2
constexpr $GetBeatmapDataAsync$d__2(int $$1__state_ = {}, ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*> $$t__builder_ = {}, ::GlobalNamespace::BeatmapDifficulty beatmapDifficulty_ = {}, float beatsPerMinute_ = {}, bool loadingForDesignatedEnvironment_ = {}, ::GlobalNamespace::EnvironmentInfoSO* environmentInfo_ = {}, ::GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings_ = {}, ::GlobalNamespace::BeatmapDataSO* $$4__this_ = {}, ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0* $$8__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*> $$u__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter $$u__2_ = {}) noexcept : $$1__state{$$1__state_}, $$t__builder{$$t__builder_}, beatmapDifficulty{beatmapDifficulty_}, beatsPerMinute{beatsPerMinute_}, loadingForDesignatedEnvironment{loadingForDesignatedEnvironment_}, environmentInfo{environmentInfo_}, playerSpecificSettings{playerSpecificSettings_}, $$4__this{$$4__this_}, $$8__1{$$8__1_}, $$u__1{$$u__1_}, $$u__2{$$u__2_} {}
// Creating interface conversion operator: operator ::System::ValueType
operator ::System::ValueType() noexcept {
return *reinterpret_cast<::System::ValueType*>(this);
}
// Creating interface conversion operator: operator ::System::Runtime::CompilerServices::IAsyncStateMachine
operator ::System::Runtime::CompilerServices::IAsyncStateMachine() noexcept {
return *reinterpret_cast<::System::Runtime::CompilerServices::IAsyncStateMachine*>(this);
}
// Get instance field reference: public System.Int32 <>1__state
int& dyn_$$1__state();
// Get instance field reference: public System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<IReadonlyBeatmapData> <>t__builder
::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*>& dyn_$$t__builder();
// Get instance field reference: public BeatmapDifficulty beatmapDifficulty
::GlobalNamespace::BeatmapDifficulty& dyn_beatmapDifficulty();
// Get instance field reference: public System.Single beatsPerMinute
float& dyn_beatsPerMinute();
// Get instance field reference: public System.Boolean loadingForDesignatedEnvironment
bool& dyn_loadingForDesignatedEnvironment();
// Get instance field reference: public EnvironmentInfoSO environmentInfo
::GlobalNamespace::EnvironmentInfoSO*& dyn_environmentInfo();
// Get instance field reference: public PlayerSpecificSettings playerSpecificSettings
::GlobalNamespace::PlayerSpecificSettings*& dyn_playerSpecificSettings();
// Get instance field reference: public BeatmapDataSO <>4__this
::GlobalNamespace::BeatmapDataSO*& dyn_$$4__this();
// Get instance field reference: private BeatmapDataSO/<>c__DisplayClass2_0 <>8__1
::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0*& dyn_$$8__1();
// Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter`1<BeatmapSaveDataVersion3.BeatmapSaveData> <>u__1
::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*>& dyn_$$u__1();
// Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter <>u__2
::System::Runtime::CompilerServices::TaskAwaiter& dyn_$$u__2();
// private System.Void MoveNext()
// Offset: 0x136D500
void MoveNext();
// private System.Void SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine stateMachine)
// Offset: 0x136D868
void SetStateMachine(::System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine);
}; // BeatmapDataSO/<GetBeatmapDataAsync>d__2
// WARNING Not writing size check since size may be invalid!
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::MoveNext
// Il2CppName: MoveNext
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::*)()>(&GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::MoveNext)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::SetStateMachine
// Il2CppName: SetStateMachine
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::*)(::System::Runtime::CompilerServices::IAsyncStateMachine*)>(&GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::SetStateMachine)> {
static const MethodInfo* get() {
static auto* stateMachine = &::il2cpp_utils::GetClassFromName("System.Runtime.CompilerServices", "IAsyncStateMachine")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2), "SetStateMachine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{stateMachine});
}
};
| 58.767442
| 1,111
| 0.757618
|
RedBrumbler
|
b68060e67087fb74d7b0d88cd62ff5cce855465a
| 1,237
|
hpp
|
C++
|
src/graphics/TypeNames.hpp
|
Sam-Belliveau/MKS66-Graphics-Library
|
4ccf04f977a15007e32bdb5a238704eaaff0c895
|
[
"MIT"
] | null | null | null |
src/graphics/TypeNames.hpp
|
Sam-Belliveau/MKS66-Graphics-Library
|
4ccf04f977a15007e32bdb5a238704eaaff0c895
|
[
"MIT"
] | null | null | null |
src/graphics/TypeNames.hpp
|
Sam-Belliveau/MKS66-Graphics-Library
|
4ccf04f977a15007e32bdb5a238704eaaff0c895
|
[
"MIT"
] | null | null | null |
#pragma once
/**
* Copyright (c) 2022 Sam Belliveau
*
* 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.
*/
#include <cstdint>
namespace SPGL
{
/* Floats */
using Float80 = long double;
using Float64 = double;
using Float32 = float;
using Float = Float64;
using FloatMax = Float80;
/* Integers */
using Size = std::size_t;
using UIntMax = std::uintmax_t;
using IntMax = std::intmax_t;
using UInt64 = std::uint64_t;
using Int64 = std::int64_t;
using UInt32 = std::uint32_t;
using Int32 = std::int32_t;
using UInt16 = std::uint16_t;
using Int16 = std::int16_t;
using UInt8 = std::uint8_t;
using Int8 = std::int8_t;
}
| 26.891304
| 81
| 0.689572
|
Sam-Belliveau
|
b683049cc1444a2f3f1fc814d6788c56abee532f
| 32,602
|
cpp
|
C++
|
src/shape.cpp
|
yenyi/kicadPcb
|
f624156f59829554cb9fbf9b0438e7b84a42ee94
|
[
"BSD-3-Clause"
] | 6
|
2020-02-08T07:29:42.000Z
|
2020-11-25T03:09:13.000Z
|
src/shape.cpp
|
yenyi/kicadPcb
|
f624156f59829554cb9fbf9b0438e7b84a42ee94
|
[
"BSD-3-Clause"
] | 2
|
2019-12-23T17:19:41.000Z
|
2020-01-09T00:10:50.000Z
|
src/shape.cpp
|
yenyi/kicadPcb
|
f624156f59829554cb9fbf9b0438e7b84a42ee94
|
[
"BSD-3-Clause"
] | 5
|
2020-10-16T23:59:42.000Z
|
2021-04-28T05:49:22.000Z
|
#include "shape.h"
points_2d rotateShapeCoordsByAngles(const points_2d &shape, double instAngle, double padAngle)
{
auto cords = points_2d{};
auto rads = fmod((instAngle + padAngle) * -M_PI / 180, 2 * M_PI);
auto s = sin(rads);
auto c = cos(rads);
for (auto &p : shape)
{
auto px = double(c * p.m_x - s * p.m_y);
auto py = double(s * p.m_x + c * p.m_y);
cords.push_back(point_2d{px, py});
}
return cords;
}
points_2d roundrect_to_shape_coords(const point_2d &size, const double &ratio)
{
double legalRatio = 0.5;
if (ratio < 0.5)
{
legalRatio = ratio;
}
auto cords = points_2d{};
auto width = size.m_x / 2;
auto height = size.m_y / 2;
auto radius = std::min(width, height) * legalRatio * 2;
auto deltaWidth = width - radius;
auto deltaHeight = height - radius;
auto point = point_2d{};
for (int i = 0; i < 10; ++i)
{ //10 points
point.m_x = deltaWidth + radius * cos(-9 * i * M_PI / 180);
point.m_y = -deltaHeight + radius * sin(-9 * i * M_PI / 180);
//std::cout << point.m_x << " " << point.m_y << std::endl;
cords.push_back(point);
}
for (int i = 10; i < 20; ++i)
{ //10 points
point.m_x = -deltaWidth + radius * cos(-9 * i * M_PI / 180);
point.m_y = -deltaHeight + radius * sin(-9 * i * M_PI / 180);
//std::cout << point.m_x << " " << point.m_y << std::endl;
cords.push_back(point);
}
for (int i = 20; i < 30; ++i)
{ //10 points
point.m_x = -deltaWidth + radius * cos(-9 * i * M_PI / 180);
point.m_y = deltaHeight + radius * sin(-9 * i * M_PI / 180);
//std::cout << point.m_x << " " << point.m_y << std::endl;
cords.push_back(point);
}
for (int i = 30; i < 40; ++i)
{ //10 points
point.m_x = deltaWidth + radius * cos(-9 * i * M_PI / 180);
point.m_y = deltaHeight + radius * sin(-9 * i * M_PI / 180);
//std::cout << point.m_x << " " << point.m_y << std::endl;
cords.push_back(point);
}
point.m_x = deltaWidth + radius * cos(0 * M_PI / 180);
point.m_y = -deltaHeight + radius * sin(0 * M_PI / 180);
//std::cout << point.m_x << " " << point.m_y << std::endl;
cords.push_back(point);
return cords;
}
// Ongoing work
// TODO: all coords must be in CW (follow the rules of Boost Polygon of Rings)
// TODO: parameters for #points to Circle
points_2d shape_to_coords(const point_2d &size, const point_2d &pos, const padShape shape, const double a1, const double a2, const double ratio, const int pointsPerCircle)
{
auto coords = points_2d{};
switch (shape)
{
case padShape::CIRCLE:
{
auto radius = size.m_x / 2;
auto point = point_2d{};
double angleShift = 360.0 / (double)pointsPerCircle;
for (int i = 0; i < pointsPerCircle; ++i)
{
point.m_x = pos.m_x + radius * cos(-angleShift * i * M_PI / 180);
point.m_y = pos.m_y + radius * sin(-angleShift * i * M_PI / 180);
coords.push_back(point);
}
// Closed the loop
point.m_x = pos.m_x + radius * cos(0 * M_PI / 180);
point.m_y = pos.m_y + radius * sin(0 * M_PI / 180);
coords.push_back(point);
break;
}
// case padShape::OVAL:
// {
// auto width = size.m_x / 2;
// auto height = size.m_y / 2;
// auto point = point_2d{};
// double angleShift = 360.0 / (double)pointsPerCircle;
// for (int i = 0; i < pointsPerCircle; ++i)
// {
// point.m_x = pos.m_x + width * cos(-angleShift * i * M_PI / 180);
// point.m_y = pos.m_y + height * sin(-angleShift * i * M_PI / 180);
// coords.push_back(point);
// }
// // Closed the loop
// point.m_x = pos.m_x + width * cos(0 * M_PI / 180);
// point.m_y = pos.m_y + height * sin(0 * M_PI / 180);
// coords.push_back(point);
// break;
// }
case padShape::OVAL:
case padShape::ROUNDRECT:
{
double legalRatio = 0.5;
if (ratio < 0.5)
{
legalRatio = ratio;
}
if (shape == padShape::OVAL)
{
// OVAL is the roundrect with ratio = 0.5
legalRatio = 0.5;
}
auto width = size.m_x / 2;
auto height = size.m_y / 2;
auto radius = std::min(width, height) * legalRatio * 2;
auto deltaWidth = width - radius;
auto deltaHeight = height - radius;
auto point = point_2d{};
int pointsPerCorner = pointsPerCircle / 4;
double angleShift = 360.0 / (double)(pointsPerCorner * 4);
for (int i = 0; i < pointsPerCorner; ++i)
{
point.m_x = pos.m_x + deltaWidth + radius * cos(-angleShift * i * M_PI / 180);
point.m_y = pos.m_y - deltaHeight + radius * sin(-angleShift * i * M_PI / 180);
coords.push_back(point);
}
for (int i = pointsPerCorner; i < 2 * pointsPerCorner; ++i)
{
point.m_x = pos.m_x - deltaWidth + radius * cos(-angleShift * i * M_PI / 180);
point.m_y = pos.m_y - deltaHeight + radius * sin(-angleShift * i * M_PI / 180);
coords.push_back(point);
}
for (int i = 2 * pointsPerCorner; i < 3 * pointsPerCorner; ++i)
{
point.m_x = pos.m_x - deltaWidth + radius * cos(-angleShift * i * M_PI / 180);
point.m_y = pos.m_y + deltaHeight + radius * sin(-angleShift * i * M_PI / 180);
coords.push_back(point);
}
for (int i = 3 * pointsPerCorner; i < 4 * pointsPerCorner; ++i)
{
point.m_x = pos.m_x + deltaWidth + radius * cos(-angleShift * i * M_PI / 180);
point.m_y = pos.m_y + deltaHeight + radius * sin(-angleShift * i * M_PI / 180);
coords.push_back(point);
}
// Closed the loop
point.m_x = pos.m_x + deltaWidth + radius * cos(0 * M_PI / 180);
point.m_y = pos.m_y - deltaHeight + radius * sin(0 * M_PI / 180);
coords.push_back(point);
break;
}
default:
case padShape::TRAPEZOID:
case padShape::RECT:
{
auto width = size.m_x / 2;
auto height = size.m_y / 2;
auto point = point_2d{};
point.m_x = pos.m_x + width;
point.m_y = pos.m_y + height;
coords.push_back(point);
point.m_y = pos.m_y - height;
coords.push_back(point);
point.m_x = pos.m_x - width;
coords.push_back(point);
point.m_y = pos.m_y + height;
coords.push_back(point);
// Closed the loop
point.m_x = pos.m_x + width;
point.m_y = pos.m_y + height;
coords.push_back(point);
break;
}
}
return rotateShapeCoordsByAngles(coords, a1, a2);
}
void printPolygon(const points_2d &coord)
{
std::cout << "Polygon(";
for (size_t i = 0; i < coord.size(); ++i)
{
std::cout << coord[i];
if (i < coord.size() - 1)
std::cout << ", ";
}
std::cout << ")" << std::endl;
}
void printPolygon(const polygon_t &poly)
{
std::cout << "Polygon(";
for (auto it = boost::begin(bg::exterior_ring(poly)); it != boost::end(bg::exterior_ring(poly)); ++it)
{
auto x = bg::get<0>(*it);
auto y = bg::get<1>(*it);
//use the coordinates...
std::cout << "(" << x << ", " << y << ")";
if (++it == boost::end(bg::exterior_ring(poly)))
{
break;
}
else
{
std::cout << ", ";
}
--it;
}
std::cout << ")" << std::endl;
}
void printPoint(point_2d &p)
{
std::cout << "Point({" << p.m_x << "," << p.m_y << "})" << std::endl;
}
void testShapeToCoords()
{
// points_2d circle32 = shape_to_coords(point_2d{10, 10}, point_2d{20, 20}, padShape::CIRCLE, 0, 0, 0, 32);
// printPolygon(circle32);
// points_2d circle48 = shape_to_coords(point_2d{10, 10}, point_2d{20, 20}, padShape::CIRCLE, 0, 0, 0, 48);
// printPolygon(circle48);
// points_2d oval32 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::OVAL, 0, 0, 0, 32);
// printPolygon(oval32);
// points_2d oval48 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::OVAL, 0, 0, 0, 48);
// printPolygon(oval48);
points_2d rr32 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 32);
printPolygon(rr32);
points_2d rr48 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 48);
printPolygon(rr48);
points_2d rr3208 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.8, 32);
printPolygon(rr3208);
points_2d rr4803 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.3, 48);
printPolygon(rr4803);
points_2d rr4003 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.3, 40);
printPolygon(rr4003);
points_2d rr4005 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 40);
printPolygon(rr4005);
points_2d rr4008 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.8, 40);
printPolygon(rr4008);
// points_2d rrr4008 = roundrect_to_shape_coords(point_2d{16, 10}, 0.8);
// printPolygon(rrr4008);
// points_2d rrr4005 = roundrect_to_shape_coords(point_2d{16, 10}, 0.5);
// printPolygon(rrr4005);
// points_2d rrr4003 = roundrect_to_shape_coords(point_2d{16, 10}, 0.3);
// printPolygon(rrr4003);
// points_2d rect = shape_to_coords(point_2d{10, 10}, point_2d{10, 5}, padShape::RECT, 0, 0, 0, 48);
// printPolygon(rect);
// points_2d trapezoid = shape_to_coords(point_2d{15, 15}, point_2d{-5, -10}, padShape::TRAPEZOID, 0, 0, 0, 48);
// printPolygon(trapezoid);
}
/////////////////////////////////
// [1] [0]
// |--------|
// | s |
// | |
// |________|
// [2] [3]
/////////////////////////////////
points_2d segment_to_rect(const points_2d &point, const double &w)
{
auto cords = points_2d{};
auto p = point_2d{};
auto width = w / 2;
//vertical
if (point[0].m_x == point[1].m_x)
{
if (point[0].m_y > point[1].m_y)
{
p.m_x = point[0].m_x + width;
p.m_y = point[0].m_y + width;
cords.push_back(p);
p.m_x = point[0].m_x - width;
cords.push_back(p);
p.m_x = point[0].m_x - width;
p.m_y = point[0].m_y - width;
cords.push_back(p);
p.m_x = point[0].m_x - width;
cords.push_back(p);
}
else
{
p.m_x = point[0].m_x + width;
p.m_y = point[1].m_y + width;
cords.push_back(p);
p.m_x = point[0].m_x - width;
cords.push_back(p);
p.m_x = point[0].m_x - width;
p.m_y = point[0].m_y - width;
cords.push_back(p);
p.m_x = point[0].m_x + width;
cords.push_back(p);
}
}
//horizontal
else if (point[0].m_y == point[1].m_y)
{
if (point[0].m_x > point[1].m_x)
{
p.m_x = point[0].m_x + width;
p.m_y = point[0].m_y + width;
cords.push_back(p);
p.m_x = point[1].m_x - width;
cords.push_back(p);
p.m_y = point[0].m_y - width;
cords.push_back(p);
p.m_x = point[0].m_x + width;
cords.push_back(p);
}
else
{
p.m_x = point[1].m_x + width;
p.m_y = point[0].m_y + width;
cords.push_back(p);
p.m_x = point[0].m_x - width;
cords.push_back(p);
p.m_y = point[0].m_y - width;
cords.push_back(p);
p.m_x = point[1].m_x + width;
cords.push_back(p);
}
}
//45degree
else if ((point[0].m_x > point[1].m_x) && (point[0].m_y > point[1].m_y))
{
p.m_x = point[0].m_x + sqrt(2) * width;
p.m_y = point[0].m_y;
cords.push_back(p);
p.m_x = point[0].m_x;
p.m_y = point[0].m_y + sqrt(2) * width;
cords.push_back(p);
p.m_x = point[1].m_x - sqrt(2) * width;
p.m_y = point[1].m_y;
cords.push_back(p);
p.m_x = point[1].m_x;
p.m_y = point[1].m_y + sqrt(2) * width;
cords.push_back(p);
}
else if ((point[0].m_x < point[1].m_x) && (point[0].m_y < point[1].m_y))
{
p.m_x = point[1].m_x + sqrt(2) * width;
p.m_y = point[1].m_y;
cords.push_back(p);
p.m_x = point[1].m_x;
p.m_y = point[1].m_y + sqrt(2) * width;
cords.push_back(p);
p.m_x = point[0].m_x - sqrt(2) * width;
p.m_y = point[0].m_y;
cords.push_back(p);
p.m_x = point[0].m_x;
p.m_y = point[0].m_y + sqrt(2) * width;
cords.push_back(p);
}
//135degree
else if ((point[1].m_x < point[0].m_x) && (point[1].m_y > point[0].m_y))
{
p.m_x = point[1].m_x;
p.m_y = point[1].m_y + sqrt(2) * width;
cords.push_back(p);
p.m_x = point[1].m_x - sqrt(2) * width;
p.m_y = point[1].m_y;
cords.push_back(p);
p.m_x = point[0].m_x;
p.m_y = point[0].m_y - sqrt(2) * width;
cords.push_back(p);
p.m_x = point[0].m_x + sqrt(2) * width;
p.m_y = point[0].m_y;
cords.push_back(p);
}
else if ((point[1].m_x > point[0].m_x) && (point[1].m_y < point[0].m_y))
{
p.m_x = point[0].m_x;
p.m_y = point[0].m_y + sqrt(2) * width;
cords.push_back(p);
p.m_x = point[0].m_x - sqrt(2) * width;
p.m_y = point[0].m_y;
cords.push_back(p);
p.m_x = point[1].m_x;
p.m_y = point[1].m_y - sqrt(2) * width;
cords.push_back(p);
p.m_x = point[1].m_x + sqrt(2) * width;
p.m_y = point[1].m_y;
cords.push_back(p);
}
return cords;
}
points_2d via_to_circle(const point_2d &pos, const double &size)
{
auto radius = size / 2;
auto coords = points_2d{};
auto point = point_2d{};
for (int i = 0; i < 40; ++i)
{ //40 points
point.m_x = pos.m_x + radius * cos(-9 * i * M_PI / 180);
point.m_y = pos.m_y + radius * sin(-9 * i * M_PI / 180);
coords.push_back(point);
}
point.m_x = pos.m_x + radius * cos(0 * M_PI / 180);
point.m_y = pos.m_y + radius * sin(0 * M_PI / 180);
coords.push_back(point);
return coords;
}
points_2d viaToOctagon(const double &size, const point_2d &pos, const double &clearance)
{
auto _size = point_2d{size / 2, size / 2};
auto coords = points_2d{};
auto point = point_2d{};
double r = _size.m_x + clearance;
//[0]
point.m_x = pos.m_x + r * tan(22.5 * M_PI / 180);
point.m_y = pos.m_y + r;
coords.push_back(point);
//[1]
point.m_x = pos.m_x + r;
point.m_y = pos.m_y + r * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[2]
point.m_x = pos.m_x + r;
point.m_y = pos.m_y - r * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[3]
point.m_x = pos.m_x + r * tan(22.5 * M_PI / 180);
point.m_y = pos.m_y - r;
coords.push_back(point);
//[4]
point.m_x = pos.m_x - r * tan(22.5 * M_PI / 180);
point.m_y = pos.m_y - r;
coords.push_back(point);
//[5]
point.m_x = pos.m_x - r;
point.m_y = pos.m_y - r * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[6]
point.m_x = pos.m_x - r;
point.m_y = pos.m_y + r * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[7]
point.m_x = pos.m_x - r * tan(22.5 * M_PI / 180);
point.m_y = pos.m_y + r;
coords.push_back(point);
return coords;
}
/////////////////////////////////
// [7] [0]
// [6] /------\ [1]
// | pin |
// [5] \______/ [2]
// [4] [3]
/////////////////////////////////
//RELATIVE COORDS TO PIN!!
points_2d pinShapeToOctagon(const point_2d &size, const point_2d &pos, const double &clearance, const double &instAngle, const double &pinAngle, padShape type)
{
auto coords = points_2d{};
auto point = point_2d{};
if (type == padShape::CIRCLE)
{
//[0]
point.m_x = (size.m_x / 2 + clearance) * tan(22.5 * M_PI / 180);
point.m_y = size.m_y / 2 + clearance;
coords.push_back(point);
//[1]
point.m_x = size.m_x / 2 + clearance;
point.m_y = (size.m_y / 2 + clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[2]
point.m_x = size.m_x / 2 + clearance;
point.m_y = (-size.m_y / 2 - clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[3]
point.m_x = (size.m_x / 2 + clearance) * tan(22.5 * M_PI / 180);
point.m_y = -size.m_y / 2 - clearance;
coords.push_back(point);
//[4]
point.m_x = (-size.m_x / 2 - clearance) * tan(22.5 * M_PI / 180);
point.m_y = -size.m_y / 2 - clearance;
coords.push_back(point);
//[5]
point.m_x = -size.m_x / 2 - clearance;
point.m_y = (-size.m_y / 2 - clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[6]
point.m_x = -size.m_x / 2 - clearance;
point.m_y = (size.m_y / 2 + clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[7]
point.m_x = (-size.m_x / 2 - clearance) * tan(22.5 * M_PI / 180);
point.m_y = size.m_y / 2 + clearance;
coords.push_back(point);
}
else
{
//[0]
point.m_x = size.m_x / 2 + (clearance * tan(22.5 * M_PI / 180));
point.m_y = size.m_y / 2 + clearance;
coords.push_back(point);
//[1]
point.m_x = size.m_x / 2 + clearance;
point.m_y = size.m_y / 2 + (clearance * tan(22.5 * M_PI / 180));
coords.push_back(point);
//[2]
point.m_x = size.m_x / 2 + clearance;
point.m_y = -size.m_y / 2 - (clearance * tan(22.5 * M_PI / 180));
coords.push_back(point);
//[3]
point.m_x = size.m_x / 2 + (clearance * tan(22.5 * M_PI / 180));
point.m_y = -size.m_y / 2 - clearance;
coords.push_back(point);
//[4]
point.m_x = -size.m_x / 2 - (clearance * tan(22.5 * M_PI / 180));
point.m_y = -size.m_y / 2 - clearance;
coords.push_back(point);
//[5]
point.m_x = -size.m_x / 2 - clearance;
point.m_y = -size.m_y / 2 - (clearance * tan(22.5 * M_PI / 180));
coords.push_back(point);
//[6]
point.m_x = -size.m_x / 2 - clearance;
point.m_y = size.m_y / 2 + (clearance * tan(22.5 * M_PI / 180));
coords.push_back(point);
//[7]
point.m_x = -size.m_x / 2 - (clearance * tan(22.5 * M_PI / 180));
point.m_y = size.m_y / 2 + clearance;
coords.push_back(point);
}
return rotateShapeCoordsByAngles(coords, instAngle, pinAngle);
}
points_2d segmentToOctagon(const points_2d &point, const double &w, const double &clearance)
{
auto cords = points_2d{};
auto p = point_2d{};
auto width = w / 2;
//vertical
if (point[0].m_x == point[1].m_x)
{
if (point[0].m_y > point[1].m_y)
{
p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + width + clearance;
cords.push_back(p);
p.m_x = point[0].m_x + width + clearance;
p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + width + clearance;
p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - width - clearance;
p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - width - clearance;
p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + width + clearance;
cords.push_back(p);
}
else
{
p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + width + clearance;
cords.push_back(p);
p.m_x = point[1].m_x + width + clearance;
p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + width + clearance;
p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - width - clearance;
p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - width - clearance;
p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + width + clearance;
cords.push_back(p);
}
}
//horizontal
else if (point[0].m_y == point[1].m_y)
{
if (point[0].m_x > point[1].m_x)
{
p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + width + clearance;
cords.push_back(p);
p.m_x = point[0].m_x + width + clearance;
p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + width + clearance;
p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - width - clearance;
p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - width - clearance;
p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + width + clearance;
cords.push_back(p);
}
else
{
p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + width + clearance;
cords.push_back(p);
p.m_x = point[1].m_x + width + clearance;
p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + width + clearance;
p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - width - clearance;
p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - width - clearance;
p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + width + clearance;
cords.push_back(p);
}
}
//45degree
else if ((point[0].m_x > point[1].m_x) && (point[0].m_y > point[1].m_y))
{
p.m_x = point[0].m_x + sqrt(2) * width + clearance;
p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + sqrt(2) * width + clearance;
p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
//2
p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
//3
p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - sqrt(2) * width - clearance;
p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - sqrt(2) * width - clearance;
p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
}
else if ((point[0].m_x < point[1].m_x) && (point[0].m_y < point[1].m_y))
{
p.m_x = point[1].m_x + sqrt(2) * width + clearance;
p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + sqrt(2) * width + clearance;
p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
//2
p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
//3
p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - sqrt(2) * width - clearance;
p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - sqrt(2) * width - clearance;
p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
}
//135degree
else if ((point[1].m_x < point[0].m_x) && (point[1].m_y > point[0].m_y))
{
p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
p.m_x = point[0].m_x + sqrt(2) * width + clearance;
p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + sqrt(2) * width + clearance;
p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - sqrt(2) * width - clearance;
p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x - sqrt(2) * width - clearance;
p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
}
else if ((point[1].m_x > point[0].m_x) && (point[1].m_y < point[0].m_y))
{
p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[0].m_y + sqrt(2) * width + clearance;
cords.push_back(p);
p.m_x = point[1].m_x + sqrt(2) * width + clearance;
p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + sqrt(2) * width + clearance;
p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180));
p.m_y = point[1].m_y - sqrt(2) * width - clearance;
cords.push_back(p);
p.m_x = point[0].m_x - sqrt(2) * width - clearance;
p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
p.m_x = point[0].m_x - sqrt(2) * width - clearance;
p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180));
cords.push_back(p);
}
return cords;
}
points_2d segmentToRelativeOctagon(const points_2d &point, const double &w, const double &clearance)
{
auto coord = relativeStartEndPointsForSegment(point);
return segmentToOctagon(coord, w, clearance);
}
points_2d viaToRelativeOctagon(const double &size, const double &clearance)
{
auto _size = point_2d{size / 2, size / 2};
auto coords = points_2d{};
auto point = point_2d{};
//[0]
point.m_x = (_size.m_x + clearance) * tan(22.5 * M_PI / 180);
point.m_y = _size.m_y + clearance;
coords.push_back(point);
//[1]
point.m_x = _size.m_x + clearance;
point.m_y = (_size.m_y + clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[2]
point.m_x = _size.m_x + clearance;
point.m_y = -1 * (_size.m_y + clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[3]
point.m_x = (_size.m_x + clearance) * tan(22.5 * M_PI / 180);
point.m_y = -1 * _size.m_y - clearance;
coords.push_back(point);
//[4]
point.m_x = -1 * (_size.m_x + clearance) * tan(22.5 * M_PI / 180);
point.m_y = -1 * _size.m_y - clearance;
coords.push_back(point);
//[5]
point.m_x = -1 * _size.m_x - clearance;
point.m_y = -1 * (_size.m_y + clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[6]
point.m_x = -1 * _size.m_x - clearance;
point.m_y = (_size.m_y + clearance) * tan(22.5 * M_PI / 180);
coords.push_back(point);
//[7]
point.m_x = -1 * (_size.m_x + clearance) * tan(22.5 * M_PI / 180);
point.m_y = _size.m_y + clearance;
coords.push_back(point);
return coords;
}
points_2d relativeStartEndPointsForSegment(const points_2d &p)
{
auto pRelative = point_2d{};
auto coords = points_2d{};
pRelative.m_x = (p[0].m_x - p[1].m_x) / 2;
pRelative.m_y = (p[0].m_y - p[1].m_y) / 2;
coords.push_back(pRelative);
pRelative.m_x = (p[1].m_x - p[0].m_x) / 2;
pRelative.m_y = (p[1].m_y - p[0].m_y) / 2;
coords.push_back(pRelative);
return coords;
}
| 33.995829
| 171
| 0.518833
|
yenyi
|
b686fe89416d5388886f05cde0320c1fbbec8d63
| 2,136
|
cpp
|
C++
|
poincare/src/frac_part.cpp
|
VersiraSec/epsilon-cfw
|
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
|
[
"FSFAP"
] | 1,442
|
2017-08-28T19:39:45.000Z
|
2022-03-30T00:56:14.000Z
|
poincare/src/frac_part.cpp
|
VersiraSec/epsilon-cfw
|
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
|
[
"FSFAP"
] | 1,321
|
2017-08-28T23:03:10.000Z
|
2022-03-31T19:32:17.000Z
|
poincare/src/frac_part.cpp
|
VersiraSec/epsilon-cfw
|
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
|
[
"FSFAP"
] | 421
|
2017-08-28T22:02:39.000Z
|
2022-03-28T20:52:21.000Z
|
#include <poincare/frac_part.h>
#include <poincare/layout_helper.h>
#include <poincare/serialization_helper.h>
#include <poincare/simplification_helper.h>
#include <poincare/rational.h>
#include <cmath>
namespace Poincare {
constexpr Expression::FunctionHelper FracPart::s_functionHelper;
int FracPartNode::numberOfChildren() const { return FracPart::s_functionHelper.numberOfChildren(); }
Layout FracPartNode::createLayout(Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const {
return LayoutHelper::Prefix(FracPart(this), floatDisplayMode, numberOfSignificantDigits, FracPart::s_functionHelper.name());
}
int FracPartNode::serialize(char * buffer, int bufferSize, Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const {
return SerializationHelper::Prefix(this, buffer, bufferSize, floatDisplayMode, numberOfSignificantDigits, FracPart::s_functionHelper.name());
}
Expression FracPartNode::shallowReduce(ReductionContext reductionContext) {
return FracPart(this).shallowReduce(reductionContext);
}
template<typename T>
Complex<T> FracPartNode::computeOnComplex(const std::complex<T> c, Preferences::ComplexFormat, Preferences::AngleUnit angleUnit) {
if (c.imag() != 0) {
return Complex<T>::RealUndefined();
}
return Complex<T>::Builder(c.real()-std::floor(c.real()));
}
Expression FracPart::shallowReduce(ExpressionNode::ReductionContext reductionContext) {
{
Expression e = SimplificationHelper::defaultShallowReduce(*this);
if (!e.isUninitialized()) {
return e;
}
}
Expression c = childAtIndex(0);
if (c.type() == ExpressionNode::Type::Matrix) {
return mapOnMatrixFirstChild(reductionContext);
}
if (c.type() != ExpressionNode::Type::Rational) {
return *this;
}
Rational r = static_cast<Rational &>(c);
IntegerDivision div = Integer::Division(r.signedIntegerNumerator(), r.integerDenominator());
assert(!div.remainder.isOverflow());
Integer rDenominator = r.integerDenominator();
Expression result = Rational::Builder(div.remainder, rDenominator);
replaceWithInPlace(result);
return result;
}
}
| 36.20339
| 143
| 0.767322
|
VersiraSec
|
b687f2f402173eb1b7d32c6a6085eb022306d9a1
| 17,558
|
cc
|
C++
|
src/driver/parser.cc
|
cforall/resolv-proto
|
4eb7c0b9f4e75b940205e808e14fa57f13541246
|
[
"BSD-3-Clause"
] | 2
|
2019-05-13T10:26:02.000Z
|
2019-05-13T15:04:42.000Z
|
src/driver/parser.cc
|
cforall/resolv-proto
|
4eb7c0b9f4e75b940205e808e14fa57f13541246
|
[
"BSD-3-Clause"
] | null | null | null |
src/driver/parser.cc
|
cforall/resolv-proto
|
4eb7c0b9f4e75b940205e808e14fa57f13541246
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in
// the file "LICENCE" distributed with this repository.
#include "parser.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include "args.h"
#include "parser_common.h"
#include "ast/decl.h"
#include "ast/expr.h"
#include "ast/forall.h"
#include "ast/input_expr_visitor.h"
#include "ast/type.h"
#include "data/clock.h"
#include "data/debug.h"
#include "data/list.h"
#include "data/mem.h"
#include "data/option.h"
#include "data/stats.h"
#include "resolver/func_table.h"
#include "resolver/resolver.h"
/// Parses a name (lowercase alphanumeric ASCII string starting with a
/// lowercase letter), returning true, storing result into ret, and
/// incrementing token if so. token must not be null.
bool parse_name(char const *&token, std::string& ret) {
const char *end = token;
if ( ('a' <= *end && *end <= 'z')
|| '_' == *end
|| '$' == *end ) ++end;
else return false;
while ( ('A' <= *end && *end <= 'Z')
|| ('a' <= *end && *end <= 'z')
|| ('0' <= *end && *end <= '9')
|| '_' == *end ) ++end;
ret.assign( token, (end-token) );
token = end;
return true;
}
/// Parses a named type name (hash followed by ASCII alphanumeric string
/// starting with a letter or underscore), returning true, storing result
/// (not including hash) into ret, and incrementing token if so.
/// token must not be null
bool parse_named_type(char const *&token, std::string& ret) {
const char *end = token;
if ( ! match_char(end, '#') ) return false;
if ( ('A' <= *end && *end <= 'Z')
|| ('a' <= *end && *end <= 'z')
|| '_' == *end
|| '$' == *end ) ++end;
else return false;
while ( ('A' <= *end && *end <= 'Z')
|| ('a' <= *end && *end <= 'z')
|| ('0' <= *end && *end <= '9')
|| '_' == *end ) ++end;
ret.assign( token+1, (end-token-1) );
token = end;
return true;
}
/// Parses a polymorphic type name (lowercase alphanumeric ASCII string
/// starting with an uppercase letter), returning true, storing result into
/// ret, and incrementing token if so. token must not be null.
bool parse_poly_type(char const *&token, std::string& ret) {
const char *end = token;
if ( 'A' <= *end && *end <= 'Z' ) ++end;
else return false;
while ( ('A' <= *end && *end <= 'Z')
|| ('a' <= *end && *end <= 'z')
|| ('0' <= *end && *end <= '9')
|| '_' == *end ) ++end;
ret.assign( token, (end-token) );
token = end;
return true;
}
/// Parses a type name, returning true, appending the result into out, and
/// incrementing token if so. Concrete types will be canonicalized according
/// to types and polymorphic types according to forall. token must not be null.
bool parse_type(char const *&token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out);
/// Parses an angle-bracket surrounded type list for the paramters of a generic named type
bool parse_generic_params(char const *&token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out) {
const char *end = token;
if ( ! match_char(end, '<') ) return false;
match_whitespace(end);
if ( ! parse_type(end, resolver, args, types, forall, out) ) return false;
while ( match_whitespace(end) ) {
if ( ! parse_type(end, resolver, args, types, forall, out) ) break;
}
if ( ! match_char(end, '>') ) return false;
token = end;
return true;
}
/// Parses a function type, returning true, appending the result into out, and
/// incrementing token if so. Concrete types will be canonicalized according
/// to types and polymorphic types according to forall. token must not be null
bool parse_func_type(const char*& token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out ) {
List<Type> returns, params;
const char* end = token;
// match opening token
if ( ! match_char(end, '[') ) return false;
match_whitespace(end);
// match return types
while ( parse_type(end, resolver, args, types, forall, returns) ) {
match_whitespace(end);
}
// match split token
if ( ! match_char(end, ':') ) return false;
match_whitespace(end);
// match parameters
while ( parse_type(end, resolver, args, types, forall, params) ) {
match_whitespace(end);
}
// match closing token
if ( ! match_char(end, ']') ) return false;
match_whitespace(end);
out.push_back( new FuncType{ move(params), move(returns) } );
token = end;
return true;
}
bool parse_type(char const *&token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out) {
int t;
std::string n;
if ( parse_int(token, t) ) {
auto it = get_canon<ConcType>( types, t );
if ( it.second && ! args.metrics_only() ) resolver.addType( it.first );
out.push_back( it.first );
return true;
} else if ( parse_named_type(token, n) ) {
List<Type> params;
parse_generic_params( token, resolver, args, types, forall, params );
auto it = get_canon( types, n, move(params) );
if ( it.second && ! args.metrics_only() ) resolver.addType( it.first );
out.push_back( it.first );
return true;
} else if ( parse_poly_type(token, n) ) {
if ( ! forall ) { forall.reset( new Forall{} ); }
out.push_back( forall->add( n ) );
return true;
} else if ( parse_func_type(token, resolver, args, types, forall, out) ) {
return true;
} else return false;
}
/// Parses a type assertion, returning true and adding the assertion into
/// binding if so. Concrete types will be canonicalized according to types.
/// token must not be null.
bool parse_assertion(char const *&token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, unique_ptr<Forall>& forall) {
const char* end = token;
// look for type assertion
if ( ! match_char(end, '|') ) return false;
// parse return types
List<Type> returns;
match_whitespace(end);
while ( parse_type(end, resolver, args, types, forall, returns) ) {
match_whitespace(end);
}
std::string name;
// try for variable assertion
if ( match_char(end, '&') ) {
if ( ! parse_name(end, name) ) return false;
if ( ! forall ) { forall.reset( new Forall{} ); }
forall->addAssertion( new VarDecl{ name, move(returns) } );
token = end;
return true;
}
// function assertion -- parse name
if ( ! parse_name(end, name) ) return false;
// parse parameters
List<Type> params;
match_whitespace(end);
while ( parse_type(end, resolver, args, types, forall, params) ) {
match_whitespace(end);
}
if ( ! forall ) { forall.reset( new Forall{} ); }
forall->addAssertion( new FuncDecl{ name, move(params), move(returns) } );
token = end;
return true;
}
/// Parses a declaration from line; returns true and adds the declaration to
/// funcs if found; will fail if given a valid func that does not consume the
/// whole line. line must not be null.
bool parse_decl( char const *line, Resolver& resolver, CanonicalTypeMap& types,
Args& args, Metrics& metrics ) {
List<Type> returns;
std::string name;
std::string tag = "";
unique_ptr<Forall> forall;
// parse return types
match_whitespace(line);
while ( parse_type(line, resolver, args, types, forall, returns) ) {
match_whitespace(line);
}
// check for variable decl
if ( ! returns.empty() && match_char(line, '&') ) {
if ( ! parse_name(line, name) ) return false;
// optionally parse tag
if ( match_char(line, '-') ) {
if ( ! parse_name(line, tag) ) return false;
}
// check line consumed
if ( ! is_blank(line) ) return false;
if ( ! args.metrics_only() ) {
resolver.addDecl( new VarDecl{ name, tag, move(returns) } );
}
metrics.mark_decl( name );
return true;
}
// parse function decl
List<Type> params;
if ( ! parse_name(line, name) ) return false;
// optionally parse tag
if ( match_char(line, '-') ) {
// might have been subsequent negative-valued type
if ( ! parse_name(line, tag) ) { --line; }
}
// parse parameters
match_whitespace(line);
while ( parse_type(line, resolver, args, types, forall, params) ) {
match_whitespace(line);
}
// parse type assertions
while ( parse_assertion(line, resolver, args, types, forall) );
// check line consumed
if ( ! is_empty(line) ) return false;
// complete declaration
if ( forall ) {
metrics.mark_decl( name, forall->assertions().size() );
} else {
metrics.mark_decl( name );
}
if ( ! args.metrics_only() ) {
resolver.addDecl(
new FuncDecl{ name, tag, move(params), move(returns), move(forall) } );
}
return true;
}
/// Parses a concrete type name, returning true, appending the result into out, and
/// incrementing token if so. Concrete types will be canonicalized according
/// to types and polymorphic types forbidden. token must not be null.
bool parse_conc_type(char const *&token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, List<Type>& out);
/// Parses an angle-bracket surrounded type list for the paramters of a concrete generic named type
bool parse_conc_generic_params(char const *&token, Resolver& resolver,
Args& args, CanonicalTypeMap& types, List<Type>& out) {
const char *end = token;
if ( ! match_char(end, '<') ) return false;
match_whitespace(end);
if ( ! parse_conc_type(end, resolver, args, types, out) ) return false;
while ( match_whitespace(end) ) {
if ( ! parse_conc_type(end, resolver, args, types, out) ) break;
}
if ( ! match_char(end, '>') ) return false;
token = end;
return true;
}
bool parse_conc_type(char const *&token, Resolver& resolver, Args& args,
CanonicalTypeMap& types, List<Type>& out) {
int t;
std::string n;
if ( parse_int(token, t) ) { // ConcType
auto it = get_canon<ConcType>( types, t );
if ( it.second && ! args.metrics_only() ) resolver.addType( it.first );
out.push_back( it.first );
return true;
} else if ( parse_named_type(token, n) ) { // concrete NamedType
List<Type> params;
parse_conc_generic_params( token, resolver, args, types, params );
auto it = get_canon( types, n, move(params) );
if ( it.second && ! args.metrics_only() ) resolver.addType( it.first );
out.push_back( it.first );
return true;
} else if ( match_char(token, '[') ) { // concrete FuncType
match_whitespace(token);
// match return types
List<Type> returns;
while ( parse_conc_type(token, resolver, args, types, returns) ) {
match_whitespace(token);
}
// match split token
if ( ! match_char(token, ':') ) return false;
match_whitespace(token);
// match parameters
List<Type> params;
while ( parse_conc_type(token, resolver, args, types, params) ) {
match_whitespace(token);
}
// match closing token
if ( ! match_char(token, ']') ) return false;
match_whitespace(token);
// return type
out.push_back( new FuncType{ move(params), move(returns) } );
return true;
} else return false;
}
/// Parses a subexpression; returns true and adds the expression to exprs if found.
/// line must not be null.
bool parse_subexpr( char const *&token, List<Expr>& exprs, Resolver& resolver,
Args& args, Metrics& metrics, CanonicalTypeMap& types ) {
const char *end = token;
// Check for a concrete type expression
List<Type> cty;
if ( parse_conc_type( end, resolver, args, types, cty ) ) {
exprs.push_back( new ValExpr( cty.front() ) );
metrics.mark_sub();
token = end;
return true;
}
// Check for name expression
if ( match_char(end, '&') ) {
std::string name;
if ( ! parse_name(end, name) ) return false;
match_whitespace(end);
exprs.push_back( new NameExpr( name ) );
metrics.mark_sub();
token = end;
return true;
}
// Check for function call
std::string name;
if ( ! parse_name(end, name) ) return false;
match_whitespace(end);
if ( ! match_char(end, '(') ) return false;
// Read function args
metrics.start_subs();
List<Expr> eargs;
match_whitespace(end);
while ( parse_subexpr(end, eargs, resolver, args, metrics, types) ) {
match_whitespace(end);
}
metrics.end_subs();
// Find closing bracket
if ( ! match_char(end, ')') ) return false;
match_whitespace(end);
exprs.push_back( new FuncExpr( name, move(eargs) ) );
metrics.mark_sub();
token = end;
return true;
}
/// Per-instance input metrics
struct InputMetrics {
unsigned max_depth = 0;
unsigned max_params = 0;
unsigned n_subexprs = 0;
unsigned max_overloads = 0;
};
/// Calculates metrics on input expression
class InputExprMetrics : public InputExprVisitor<InputExprMetrics, InputMetrics> {
const Metrics& ftab;
public:
using Super = InputExprVisitor<InputExprMetrics, InputMetrics>;
using Super::visit;
InputExprMetrics(const Metrics& ftab) : ftab(ftab) {}
bool visit( const ValExpr*, InputMetrics& m ) {
++m.max_depth;
++m.n_subexprs;
return true;
}
bool visit( const NameExpr* e, InputMetrics& m ) {
++m.max_depth;
++m.n_subexprs;
// update max overloads
unsigned n_decls = ftab.n_decls_for( e->name() );
if ( n_decls > m.max_overloads ) { m.max_overloads = n_decls; }
return true;
}
bool visit( const FuncExpr* e, InputMetrics & m ) {
++m.n_subexprs;
// update max params
unsigned n_params = e->args().size();
if ( n_params > m.max_params ) { m.max_params = n_params; }
// update max depth
unsigned local_d = ++m.max_depth;
unsigned max_d = local_d;
for ( const Expr* arg : e->args() ) {
visit( arg, m );
if ( m.max_depth > max_d ) { max_d = m.max_depth; }
m.max_depth = local_d;
}
m.max_depth = max_d;
// update max overloads
unsigned n_decls = ftab.n_decls_for( e->name() );
if ( n_decls > m.max_overloads ) { m.max_overloads = n_decls; }
return true;
}
};
/// Parses an expression from line; returns true and adds the expression to
/// exprs if found; will fail if given a valid expr that does not consume the
/// whole line. line must not be null.
bool parse_expr( unsigned n, char const *line, Resolver& resolver, Args& args,
Metrics& metrics, CanonicalTypeMap& types ) {
match_whitespace(line);
List<Expr> exprs;
if ( parse_subexpr(line, exprs, resolver, args, metrics, types) && is_empty(line) ) {
assume( exprs.size() == 1, "successful expression parse results in single expression" );
if ( ! args.metrics_only() ) {
if ( args.per_prob() ) {
volatile std::clock_t start, end;
InputMetrics m = InputExprMetrics{metrics}( exprs[0] );
args.out() << n << ","
<< m.max_depth << ","
<< m.max_params << ","
<< m.n_subexprs << ","
<< m.max_overloads << ",";
#ifdef RP_STATS
crnt_pass = Resolve;
#endif
start = std::clock();
resolver.addExpr( exprs[0] );
end = std::clock();
#ifdef RP_STATS
crnt_pass = Parse;
#endif
args.out() << "," << (end-start)/*microseconds*/ << std::endl;
} else {
#ifdef RP_STATS
crnt_pass = Resolve;
#endif
resolver.addExpr( exprs[0] );
#ifdef RP_STATS
crnt_pass = Parse;
#endif
}
}
metrics.mark_expr();
return true;
} else {
metrics.reset_expr();
return false;
}
}
/// Mode for echo_line -- declarations are echoed for Filtered verbosity, expressions are not
enum EchoMode { EXPR, DECL };
/// Echos line if in appropriate mode
void echo_line( std::string& line, Args& args, EchoMode mode = EXPR ) {
if ( args.verbosity() == Args::Verbosity::Verbose
|| ( args.verbosity() == Args::Verbosity::Filtered && mode == DECL ) ) {
args.out() << line << std::endl;
}
}
/// Parses a scope from a series of lines (excluding opening "{" line if in block),
/// continuing until end-of-input or terminating "}" line is found.
/// Prints an error and exits if invalid declaration or expression found
void parse_block( std::istream& in, unsigned& n, unsigned& scope, Resolver& resolver,
CanonicalTypeMap& types, Args& args, Metrics& metrics ) {
std::string line;
// parse declarations and delimiter
while ( std::getline( in, line ) ) {
++n;
if ( is_blank( line ) ) {
echo_line( line, args, DECL );
continue;
}
// break when finished declarations
if ( line_matches( line, "%%" ) ) {
echo_line( line, args, DECL );
break;
}
bool ok = parse_decl( line.data(), resolver, types, args, metrics );
if ( ! ok ) {
std::cerr << "Invalid declaration [" << n << "]: \"" << line << "\"" << std::endl;
std::exit(1);
}
echo_line( line, args, DECL );
}
while ( std::getline( in, line ) ) {
++n;
if ( is_blank( line ) ) {
echo_line( line, args );
continue;
}
// break when finished block
if ( line_matches( line, "}" ) ) {
--scope;
resolver.endScope();
metrics.end_lex_scope();
break;
}
// recurse when starting new block
if ( line_matches( line, "{" ) ) {
++scope;
resolver.beginScope();
metrics.begin_lex_scope();
parse_block( in, n, scope, resolver, types, args, metrics );
continue;
}
// parse and resolve expression
if ( args.line_nos() ) { args.out() << n << ": " << std::flush; }
bool ok = parse_expr( n, line.data(), resolver, args, metrics, types );
if ( ! ok ) {
std::cerr << "Invalid expression [" << n << "]: \"" << line << "\"" << std::endl;
std::exit(1);
}
echo_line( line, args );
}
}
void run_input( std::istream& in, Resolver& resolver, Args& args, Metrics& metrics ) {
CanonicalTypeMap types;
unsigned n = 0, scope = 0;
parse_block(in, n, scope, resolver, types, args, metrics);
if ( scope != 0 ) {
std::cerr << "Unmatched braces" << std::endl;
std::exit(1);
}
}
| 28.319355
| 99
| 0.650644
|
cforall
|
b692bd9f43bf79f36ad69388ce178bf388749810
| 873
|
cpp
|
C++
|
examples/priority_queue.cpp
|
miachm/STL-Threadsafe
|
08b2d9e7f487121088a817071d1d42b2736996e9
|
[
"Apache-2.0"
] | 9
|
2017-07-25T23:22:54.000Z
|
2021-07-06T06:24:46.000Z
|
examples/priority_queue.cpp
|
miachm/STL-Threadsafe
|
08b2d9e7f487121088a817071d1d42b2736996e9
|
[
"Apache-2.0"
] | null | null | null |
examples/priority_queue.cpp
|
miachm/STL-Threadsafe
|
08b2d9e7f487121088a817071d1d42b2736996e9
|
[
"Apache-2.0"
] | 3
|
2020-12-11T03:02:35.000Z
|
2021-08-22T17:01:28.000Z
|
#include <iostream>
#include <thread>
#include "priority_queue-threadsafe.hpp"
int main(){
std::threadsafe::priority_queue<int> bids;
std::thread producer([&]{
int randomBids[20] = {3,19,11,2,4,12,1,20,14,5,18,10,15,8,17,6,16,7,9,13};
for (int i = 0;i < 20;i++){
bids.push(randomBids[i]);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
try{
int out;
while (true){
bids.wait_pop(out,std::chrono::milliseconds(100));
std::cout << "Checking new bids" << std::endl;
std::cout << "\tBid: " << out << std::endl;
while (bids.try_pop(out)){
std::cout << "\tBid: " << out << std::endl;
}
std::cout << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3));
}
}
catch (std::threadsafe::Time_Expired e){
std::cout << "No more bids coming, shutting down..." << std::endl;
}
producer.join();
}
| 22.973684
| 76
| 0.610538
|
miachm
|
b699379d09377d60e623f06ea2d6dbdfac24156e
| 2,339
|
cpp
|
C++
|
day2/main.cpp
|
fardragon/AdventOfCode2021
|
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
|
[
"MIT"
] | 1
|
2021-12-02T14:11:37.000Z
|
2021-12-02T14:11:37.000Z
|
day2/main.cpp
|
fardragon/AdventOfCode2021
|
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
|
[
"MIT"
] | null | null | null |
day2/main.cpp
|
fardragon/AdventOfCode2021
|
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
|
[
"MIT"
] | null | null | null |
#include "shared.hpp"
#include <iostream>
#include <numeric>
#include <chrono>
std::uint32_t SolvePart1(const std::vector<std::pair<std::string, std::uint16_t>> &input);
std::uint32_t SolvePart2(const std::vector<std::pair<std::string, std::uint16_t>> &input);
//std::uint16_t SolvePart2(const std::vector<uint16_t> &input);
int main(int argc, char **argv)
{
if (argc < 2)
{
throw std::runtime_error("Not enough input arguments");
}
const auto begin = std::chrono::steady_clock::now();
const auto lines = LoadLines(argv[1]);
const auto input = LinesToStrUint16(lines);
const auto beginSolving = std::chrono::steady_clock::now();
const auto part1Result = SolvePart1(input);
const auto part2Result = SolvePart2(input);
const auto end = std::chrono::steady_clock::now();
const auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();
const auto elapsedSolving = std::chrono::duration_cast<std::chrono::microseconds>(end - beginSolving).count();
std::cout << "Part 1 result: " << part1Result << "\r\n";
std::cout << "Part 2 result: " << part2Result << "\r\n";
std::cout << "Time: " << elapsed << "us \r\n";
std::cout << "Time (without reading and parsing): " << elapsedSolving << "us \r\n";
return 0;
}
std::uint32_t SolvePart1(const std::vector<std::pair<std::string, std::uint16_t>> &input)
{
std::uint32_t position{}, depth{};
for (const auto &[command, argument]: input)
{
switch(command.front())
{
case 'f':
{
//forward
position += argument;
break;
}
case 'u':
{
// up
depth -= argument;
break;
}
case 'd':
{
// down
depth += argument;
break;
}
default:
throw std::runtime_error("Invalid command");
}
}
return position * depth;
}
std::uint32_t SolvePart2(const std::vector<std::pair<std::string, std::uint16_t>> &input)
{
std::uint32_t position{}, depth{};
std::int32_t aim{};
for (const auto &[command, argument]: input)
{
switch(command.front())
{
case 'f':
{
//forward
position += argument;
depth += (aim * argument);
break;
}
case 'u':
{
// up
aim -= argument;
break;
}
case 'd':
{
// down
aim += argument;
break;
}
default:
throw std::runtime_error("Invalid command");
}
}
return position * depth;
}
| 22.066038
| 111
| 0.626764
|
fardragon
|
b69cadb7957bd91901a1abec8d2f2851c06e2d19
| 1,199
|
cpp
|
C++
|
vespalib/src/vespa/vespalib/io/mapped_file_input.cpp
|
amahussein/vespa
|
29d266ae1e5c95e25002b97822953fdd02b1451e
|
[
"Apache-2.0"
] | 1
|
2018-12-30T05:42:18.000Z
|
2018-12-30T05:42:18.000Z
|
vespalib/src/vespa/vespalib/io/mapped_file_input.cpp
|
amahussein/vespa
|
29d266ae1e5c95e25002b97822953fdd02b1451e
|
[
"Apache-2.0"
] | 1
|
2021-01-21T01:37:37.000Z
|
2021-01-21T01:37:37.000Z
|
vespalib/src/vespa/vespalib/io/mapped_file_input.cpp
|
amahussein/vespa
|
29d266ae1e5c95e25002b97822953fdd02b1451e
|
[
"Apache-2.0"
] | 1
|
2020-09-03T11:39:52.000Z
|
2020-09-03T11:39:52.000Z
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "mapped_file_input.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
namespace vespalib {
MappedFileInput::MappedFileInput(const vespalib::string &file_name)
: _fd(open(file_name.c_str(), O_RDONLY)),
_data((char *)MAP_FAILED),
_size(0),
_used(0)
{
struct stat info;
if ((_fd != -1) && fstat(_fd, &info) == 0) {
_data = static_cast<char*>(mmap(0, info.st_size,
PROT_READ, MAP_SHARED, _fd, 0));
if (_data != MAP_FAILED) {
_size = info.st_size;
madvise(_data, _size, MADV_SEQUENTIAL);
}
}
}
MappedFileInput::~MappedFileInput()
{
if (valid()) {
munmap(_data, _size);
}
if (_fd != -1) {
close(_fd);
}
}
bool MappedFileInput::valid() const
{
return (_data != MAP_FAILED);
}
Memory
MappedFileInput::obtain()
{
return Memory((_data + _used), (_size - _used));
}
Input &
MappedFileInput::evict(size_t bytes)
{
_used += bytes;
return *this;
}
} // namespace vespalib
| 21.035088
| 118
| 0.597164
|
amahussein
|
b69fcc70e50199b0bb9e54a0c8a70a9541a46b7e
| 172
|
hpp
|
C++
|
Engine/Include/FishEngine/Path.hpp
|
ValtoGameEngines/Fish-Engine
|
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
|
[
"MIT"
] | 240
|
2017-02-17T10:08:19.000Z
|
2022-03-25T14:45:29.000Z
|
Engine/Include/FishEngine/Path.hpp
|
ValtoGameEngines/Fish-Engine
|
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
|
[
"MIT"
] | 2
|
2016-10-12T07:08:38.000Z
|
2017-04-05T01:56:30.000Z
|
Engine/Include/FishEngine/Path.hpp
|
yushroom/FishEngine
|
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
|
[
"MIT"
] | 39
|
2017-03-02T09:40:07.000Z
|
2021-12-04T07:28:53.000Z
|
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
namespace FishEngine
{
using Path = boost::filesystem::path;
}
| 21.5
| 38
| 0.796512
|
ValtoGameEngines
|
b6a13a7a5065dffa2991612f340a13fa50cd7192
| 3,157
|
cc
|
C++
|
src/main/cc/estimation/estimators.cc
|
world-federation-of-advertisers/any-sketch
|
728588eb4b02b6f0cd049cf8902dfa148e32560d
|
[
"Apache-2.0"
] | 1
|
2021-03-29T16:50:52.000Z
|
2021-03-29T16:50:52.000Z
|
src/main/cc/estimation/estimators.cc
|
world-federation-of-advertisers/any-sketch
|
728588eb4b02b6f0cd049cf8902dfa148e32560d
|
[
"Apache-2.0"
] | 2
|
2021-04-14T00:35:09.000Z
|
2021-07-07T13:47:47.000Z
|
src/main/cc/estimation/estimators.cc
|
world-federation-of-advertisers/any-sketch
|
728588eb4b02b6f0cd049cf8902dfa148e32560d
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 The Cross-Media Measurement Authors
//
// 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 "estimation/estimators.h"
#include <cmath>
#include <cstdint>
#include <functional>
#include "absl/base/macros.h"
#include "absl/functional/bind_front.h"
namespace wfa::estimation {
namespace {
// Get the expected number of legionaries activated for given cardinality
uint64_t GetExpectedActiveRegisterCount(double decay_rate,
uint64_t num_of_total_registers,
uint64_t cardinality) {
ABSL_ASSERT(decay_rate > 1.0);
ABSL_ASSERT(num_of_total_registers > 0);
if (cardinality == 0) return 0;
double exponential_of_decay = std::exp(decay_rate);
double t = cardinality / static_cast<double>(num_of_total_registers);
double negative_term =
-std::expint((-decay_rate * t) / (exponential_of_decay - 1));
double positive_term = std::expint((-decay_rate * exponential_of_decay * t) /
(exponential_of_decay - 1));
return (1 - (negative_term + positive_term) / decay_rate) *
num_of_total_registers;
}
// Calculate the invert of a monotonic increasing function using binary search
uint64_t InvertMonotonic(const std::function<uint64_t(uint64_t)>& function,
uint64_t target) {
uint64_t f0 = function(0);
ABSL_ASSERT(f0 <= target);
uint64_t left = 0;
uint64_t right = 1;
// Find a region that contains the solution
while (function(right) < target) {
left = right;
right *= 2;
}
uint64_t mid = (right + left) / 2;
while (right > left) {
uint64_t f_mid = function(mid);
if (f_mid > target) {
right = mid - 1;
} else {
left = mid + 1;
}
mid = (right + left) / 2;
}
return mid;
}
double GetCardinality(
std::function<uint64_t(uint64_t)> inverse_cardinality_estimator,
uint64_t active_register_count) {
return InvertMonotonic(inverse_cardinality_estimator, active_register_count);
}
} // namespace
int64_t EstimateCardinalityLiquidLegions(double decay_rate,
uint64_t num_of_total_registers,
uint64_t active_register_count) {
std::function<uint64_t(uint64_t)> get_expected_active_register_count =
absl::bind_front(GetExpectedActiveRegisterCount, decay_rate,
num_of_total_registers);
ABSL_ASSERT(active_register_count < num_of_total_registers);
return GetCardinality(get_expected_active_register_count,
active_register_count);
}
} // namespace wfa::estimation
| 35.47191
| 79
| 0.679126
|
world-federation-of-advertisers
|
b6a26a510f6b78583d7ef149fb455db65ac8d300
| 458
|
hpp
|
C++
|
tools/stopwatch.hpp
|
matumoto1234/library
|
a2c80516a8afe5876696c139fe0e837d8a204f69
|
[
"Unlicense"
] | 2
|
2021-06-24T11:21:08.000Z
|
2022-03-15T05:57:25.000Z
|
tools/stopwatch.hpp
|
matumoto1234/library
|
a2c80516a8afe5876696c139fe0e837d8a204f69
|
[
"Unlicense"
] | 102
|
2021-10-30T21:30:00.000Z
|
2022-03-26T18:39:47.000Z
|
tools/stopwatch.hpp
|
matumoto1234/library
|
a2c80516a8afe5876696c139fe0e837d8a204f69
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include "./base.hpp"
#include <chrono>
namespace tools {
struct Stopwatch {
chrono::high_resolution_clock::time_point start;
Stopwatch() { restart(); }
void restart() { start = chrono::high_resolution_clock::now(); }
chrono::milliseconds::rep elapsed() {
auto end = chrono::high_resolution_clock::now();
return chrono::duration_cast<chrono::milliseconds>(end - start).count();
}
};
} // namespace tools
| 22.9
| 78
| 0.665939
|
matumoto1234
|
b6a8407a1c18fbf1f8a711a92f2ee4e12327aa21
| 20,315
|
cpp
|
C++
|
ICG/src/tracker.cpp
|
XiaoJake/3DObjectTracking
|
c1fbf9241a0cd1ce450a1d6b86c67613025e1836
|
[
"MIT"
] | 1
|
2022-03-17T08:17:47.000Z
|
2022-03-17T08:17:47.000Z
|
ICG/src/tracker.cpp
|
0smile/3DObjectTracking
|
c1fbf9241a0cd1ce450a1d6b86c67613025e1836
|
[
"MIT"
] | null | null | null |
ICG/src/tracker.cpp
|
0smile/3DObjectTracking
|
c1fbf9241a0cd1ce450a1d6b86c67613025e1836
|
[
"MIT"
] | null | null | null |
// SPDX-License-Identifier: MIT
// Copyright (c) 2022 Manuel Stoiber, German Aerospace Center (DLR)
#include <icg/tracker.h>
namespace icg {
Tracker::Tracker(const std::string &name, int n_corr_iterations,
int n_update_iterations, bool synchronize_cameras,
const std::chrono::milliseconds &cycle_duration,
int visualization_time, int viewer_time)
: name_{name},
n_corr_iterations_{n_corr_iterations},
n_update_iterations_{n_update_iterations},
synchronize_cameras_{synchronize_cameras},
cycle_duration_{cycle_duration},
visualization_time_{visualization_time},
viewer_time_{viewer_time} {}
Tracker::Tracker(const std::string &name,
const std::filesystem::path &metafile_path)
: name_{name}, metafile_path_{metafile_path} {}
bool Tracker::SetUp(bool set_up_all_objects) {
set_up_ = false;
if (!metafile_path_.empty())
if (!LoadMetaData()) return false;
AssembleDerivedObjectPtrs();
if (set_up_all_objects) {
if (!SetUpAllObjects()) return false;
} else {
if (!AreAllObjectsSetUp()) return false;
}
set_up_ = true;
return true;
}
bool Tracker::AddOptimizer(const std::shared_ptr<Optimizer> &optimizer_ptr) {
set_up_ = false;
if (!AddPtrIfNameNotExists(optimizer_ptr, &optimizer_ptrs_)) {
std::cerr << "Optimizer " << optimizer_ptr->name() << " already exists"
<< std::endl;
return false;
}
return true;
}
bool Tracker::DeleteOptimizer(const std::string &name) {
set_up_ = false;
if (!DeletePtrIfNameExists(name, &optimizer_ptrs_)) {
std::cerr << "Optimizer " << name << " not found" << std::endl;
return false;
}
return true;
}
void Tracker::ClearOptimizers() {
set_up_ = false;
optimizer_ptrs_.clear();
}
bool Tracker::AddDetector(const std::shared_ptr<Detector> &detector_ptr) {
set_up_ = false;
if (!AddPtrIfNameNotExists(detector_ptr, &detector_ptrs_)) {
std::cerr << "Detector " << detector_ptr->name() << " already exists"
<< std::endl;
return false;
}
return true;
}
bool Tracker::DeleteDetector(const std::string &name) {
set_up_ = false;
if (!DeletePtrIfNameExists(name, &detector_ptrs_)) {
std::cerr << "Detector " << name << " not found" << std::endl;
return false;
}
return true;
}
void Tracker::ClearDetectors() {
set_up_ = false;
detector_ptrs_.clear();
}
bool Tracker::AddRefiner(const std::shared_ptr<Refiner> &refiner_ptr) {
set_up_ = false;
if (!AddPtrIfNameNotExists(refiner_ptr, &refiner_ptrs_)) {
std::cerr << "Refiner " << refiner_ptr->name() << " already exists"
<< std::endl;
return false;
}
return true;
}
bool Tracker::DeleteRefiner(const std::string &name) {
set_up_ = false;
if (!DeletePtrIfNameExists(name, &refiner_ptrs_)) {
std::cerr << "Refiner " << name << " not found" << std::endl;
return false;
}
return true;
}
void Tracker::ClearRefiners() {
set_up_ = false;
refiner_ptrs_.clear();
}
bool Tracker::AddViewer(const std::shared_ptr<Viewer> &viewer_ptr) {
set_up_ = false;
if (!AddPtrIfNameNotExists(viewer_ptr, &viewer_ptrs_)) {
std::cerr << "Viewer " << viewer_ptr->name() << " already exists"
<< std::endl;
return false;
}
return true;
}
bool Tracker::DeleteViewer(const std::string &name) {
set_up_ = false;
if (!DeletePtrIfNameExists(name, &viewer_ptrs_)) {
std::cerr << "Viewer " << name << " not found" << std::endl;
return false;
}
return true;
}
void Tracker::ClearViewers() {
set_up_ = false;
viewer_ptrs_.clear();
}
bool Tracker::AddPublisher(const std::shared_ptr<Publisher> &publisher_ptr) {
set_up_ = false;
if (!AddPtrIfNameNotExists(publisher_ptr, &publisher_ptrs_)) {
std::cerr << "Publisher " << publisher_ptr->name() << " already exists"
<< std::endl;
return false;
}
return true;
}
bool Tracker::DeletePublisher(const std::string &name) {
set_up_ = false;
if (!DeletePtrIfNameExists(name, &publisher_ptrs_)) {
std::cerr << "Publisher " << name << " not found" << std::endl;
return false;
}
return true;
}
void Tracker::ClearPublishers() {
set_up_ = false;
publisher_ptrs_.clear();
}
void Tracker::set_name(const std::string &name) { name_ = name; }
void Tracker::set_metafile_path(const std::filesystem::path &metafile_path) {
metafile_path_ = metafile_path;
set_up_ = false;
}
void Tracker::set_n_corr_iterations(int n_corr_iterations) {
n_corr_iterations_ = n_corr_iterations;
}
void Tracker::set_n_update_iterations(int n_update_iterations) {
n_update_iterations_ = n_update_iterations;
}
void Tracker::set_synchronize_cameras(bool synchronize_cameras) {
synchronize_cameras_ = synchronize_cameras;
}
void Tracker::set_cycle_duration(
const std::chrono::milliseconds &cycle_duration) {
cycle_duration_ = cycle_duration;
}
void Tracker::set_visualization_time(int visualization_time) {
visualization_time_ = visualization_time;
}
void Tracker::set_viewer_time(int viewer_time) { viewer_time_ = viewer_time; }
bool Tracker::RunTrackerProcess(bool execute_detection, bool start_tracking) {
if (!set_up_) {
std::cerr << "Set up tracker " << name_ << " first" << std::endl;
return false;
}
tracking_started_ = false;
quit_tracker_process_ = false;
execute_detection_ = execute_detection;
start_tracking_ = start_tracking;
for (int iteration = 0;; ++iteration) {
auto begin{std::chrono::high_resolution_clock::now()};
if (!UpdateCameras(execute_detection_)) return false;
if (execute_detection_) {
if (!ExecuteDetectionCycle(iteration)) return false;
tracking_started_ = false;
execute_detection_ = false;
}
if (start_tracking_) {
if (!StartModalities(iteration)) return false;
tracking_started_ = true;
start_tracking_ = false;
}
if (tracking_started_) {
if (!ExecuteTrackingCycle(iteration)) return false;
}
if (!UpdateViewers(iteration)) return false;
if (quit_tracker_process_) return true;
if (!synchronize_cameras_) WaitUntilCycleEnds(begin);
}
return true;
}
void Tracker::QuitTrackerProcess() { quit_tracker_process_ = true; }
void Tracker::ExecuteDetection(bool start_tracking) {
execute_detection_ = true;
start_tracking_ = start_tracking;
}
void Tracker::StartTracking() { start_tracking_ = true; }
void Tracker::StopTracking() { tracking_started_ = false; }
bool Tracker::ExecuteDetectionCycle(int iteration) {
if (!DetectBodies()) return false;
return RefinePoses();
}
bool Tracker::StartModalities(int iteration) {
for (auto &start_modality_renderer_ptr : start_modality_renderer_ptrs_) {
if (!start_modality_renderer_ptr->StartRendering()) return false;
}
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->StartModality(iteration, 0)) return false;
}
return true;
}
bool Tracker::ExecuteTrackingCycle(int iteration) {
for (int corr_iteration = 0; corr_iteration < n_corr_iterations_;
++corr_iteration) {
int corr_save_idx = iteration * n_corr_iterations_ + corr_iteration;
if (!CalculateCorrespondences(iteration, corr_iteration)) return false;
if (!VisualizeCorrespondences(corr_save_idx)) return false;
for (int update_iteration = 0; update_iteration < n_update_iterations_;
++update_iteration) {
int update_save_idx =
corr_save_idx * n_update_iterations_ + update_iteration;
if (!CalculateGradientAndHessian(iteration, corr_iteration,
update_iteration))
return false;
if (!CalculateOptimization(iteration, corr_iteration, update_iteration))
return false;
if (!VisualizeOptimization(update_save_idx)) return false;
}
}
if (!CalculateResults(iteration)) return false;
if (!VisualizeResults(iteration)) return false;
return UpdatePublishers(iteration);
}
bool Tracker::DetectBodies() {
for (auto &detector_ptr : detector_ptrs_) {
if (!detector_ptr->DetectBody()) return false;
}
return true;
}
bool Tracker::RefinePoses() {
for (auto &refiner_ptr : refiner_ptrs_) {
if (!refiner_ptr->RefinePoses()) return false;
}
return true;
}
bool Tracker::UpdateCameras(bool update_all_cameras) {
if (update_all_cameras) {
for (auto &camera_ptr : all_camera_ptrs_) {
if (!camera_ptr->UpdateImage(synchronize_cameras_)) return false;
}
} else {
for (auto &camera_ptr : main_camera_ptrs_) {
if (!camera_ptr->UpdateImage(synchronize_cameras_)) return false;
}
}
return true;
}
bool Tracker::CalculateCorrespondences(int iteration, int corr_iteration) {
for (auto &correspondence_renderer_ptr : correspondence_renderer_ptrs_) {
if (!correspondence_renderer_ptr->StartRendering()) return false;
}
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->CalculateCorrespondences(iteration, corr_iteration))
return false;
}
return true;
}
bool Tracker::VisualizeCorrespondences(int save_idx) {
bool imshow_correspondences = false;
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->VisualizeCorrespondences(save_idx)) return false;
if (modality_ptr->imshow_correspondence()) imshow_correspondences = true;
}
if (imshow_correspondences) {
if (cv::waitKey(visualization_time_) == 'q') return false;
}
return true;
}
bool Tracker::CalculateGradientAndHessian(int iteration, int corr_iteration,
int update_iteration) {
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->CalculateGradientAndHessian(iteration, corr_iteration,
update_iteration))
return false;
}
return true;
}
bool Tracker::CalculateOptimization(int iteration, int corr_iteration,
int update_iteration) {
for (auto &optimizer_ptr : optimizer_ptrs_) {
if (!optimizer_ptr->CalculateOptimization(iteration, corr_iteration,
update_iteration))
return false;
}
return true;
}
bool Tracker::VisualizeOptimization(int save_idx) {
bool imshow_pose_update = false;
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->VisualizeOptimization(save_idx)) return false;
if (modality_ptr->imshow_optimization()) imshow_pose_update = true;
}
if (imshow_pose_update) {
if (cv::waitKey(visualization_time_) == 'q') return false;
}
return true;
}
bool Tracker::CalculateResults(int iteration) {
for (auto &results_renderer_ptr : results_renderer_ptrs_) {
if (!results_renderer_ptr->StartRendering()) return false;
}
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->CalculateResults(iteration)) return false;
}
return true;
}
bool Tracker::VisualizeResults(int save_idx) {
bool imshow_result = false;
for (auto &modality_ptr : modality_ptrs_) {
if (!modality_ptr->VisualizeResults(save_idx)) return false;
if (modality_ptr->imshow_result()) imshow_result = true;
}
if (imshow_result) {
if (cv::waitKey(visualization_time_) == 'q') return false;
}
return true;
}
bool Tracker::UpdatePublishers(int iteration) {
for (auto &publisher_ptr : publisher_ptrs_) {
if (!publisher_ptr->UpdatePublisher(iteration)) return false;
}
return true;
}
bool Tracker::UpdateViewers(int iteration) {
if (!viewer_ptrs_.empty()) {
for (auto &viewer_ptr : viewer_ptrs_) {
viewer_ptr->UpdateViewer(iteration);
}
char key = cv::waitKey(viewer_time_);
if (key == 'd') {
execute_detection_ = true;
} else if (key == 'x') {
execute_detection_ = true;
start_tracking_ = true;
} else if (key == 't') {
start_tracking_ = true;
} else if (key == 's') {
tracking_started_ = false;
} else if (key == 'q') {
quit_tracker_process_ = true;
}
}
return true;
}
const std::string &Tracker::name() const { return name_; }
const std::filesystem::path &Tracker::metafile_path() const {
return metafile_path_;
}
const std::vector<std::shared_ptr<Optimizer>> &Tracker::optimizer_ptrs() const {
return optimizer_ptrs_;
}
const std::vector<std::shared_ptr<Detector>> &Tracker::detector_ptrs() const {
return detector_ptrs_;
}
const std::vector<std::shared_ptr<Refiner>> &Tracker::refiner_ptrs() const {
return refiner_ptrs_;
}
const std::vector<std::shared_ptr<Viewer>> &Tracker::viewer_ptrs() const {
return viewer_ptrs_;
}
const std::vector<std::shared_ptr<Publisher>> &Tracker::publisher_ptrs() const {
return publisher_ptrs_;
}
const std::vector<std::shared_ptr<Modality>> &Tracker::modality_ptrs() const {
return modality_ptrs_;
}
const std::vector<std::shared_ptr<Model>> &Tracker::model_ptrs() const {
return model_ptrs_;
}
const std::vector<std::shared_ptr<Camera>> &Tracker::main_camera_ptrs() const {
return main_camera_ptrs_;
}
const std::vector<std::shared_ptr<Camera>> &Tracker::all_camera_ptrs() const {
return all_camera_ptrs_;
}
const std::vector<std::shared_ptr<RendererGeometry>>
&Tracker::renderer_geometry_ptrs() const {
return renderer_geometry_ptrs_;
}
const std::vector<std::shared_ptr<Body>> &Tracker::body_ptrs() const {
return body_ptrs_;
}
const std::vector<std::shared_ptr<Renderer>>
&Tracker::start_modality_renderer_ptrs() const {
return start_modality_renderer_ptrs_;
}
const std::vector<std::shared_ptr<Renderer>>
&Tracker::correspondence_renderer_ptrs() const {
return correspondence_renderer_ptrs_;
}
const std::vector<std::shared_ptr<Renderer>> &Tracker::results_renderer_ptrs()
const {
return results_renderer_ptrs_;
}
int Tracker::n_corr_iterations() const { return n_corr_iterations_; }
int Tracker::n_update_iterations() const { return n_update_iterations_; }
bool Tracker::synchronize_cameras() const { return synchronize_cameras_; }
const std::chrono::milliseconds &Tracker::cycle_duration() const {
return cycle_duration_;
}
int Tracker::visualization_time() const { return visualization_time_; }
int Tracker::viewer_time() const { return viewer_time_; }
bool Tracker::set_up() const { return set_up_; }
bool Tracker::LoadMetaData() {
// Open file storage from yaml
cv::FileStorage fs;
if (!OpenYamlFileStorage(metafile_path_, &fs)) return false;
// Read parameters from yaml
int i_cycle_duration;
ReadOptionalValueFromYaml(fs, "n_corr_iterations", &n_corr_iterations_);
ReadOptionalValueFromYaml(fs, "n_update_iterations", &n_update_iterations_);
ReadOptionalValueFromYaml(fs, "synchronize_cameras", &synchronize_cameras_);
ReadOptionalValueFromYaml(fs, "cycle_duration", &i_cycle_duration);
ReadOptionalValueFromYaml(fs, "visualization_time", &visualization_time_);
ReadOptionalValueFromYaml(fs, "viewer_time", &viewer_time_);
cycle_duration_ = std::chrono::milliseconds{i_cycle_duration};
fs.release();
return true;
}
void Tracker::WaitUntilCycleEnds(
std::chrono::high_resolution_clock::time_point begin) {
auto elapsed_time{std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - begin)};
if (elapsed_time < cycle_duration_)
std::this_thread::sleep_for(elapsed_time - cycle_duration_);
else
std::cerr << "Tracker too slow: elapsed time = " << elapsed_time.count()
<< " ms > " << cycle_duration_.count() << " ms" << std::endl;
}
void Tracker::AssembleDerivedObjectPtrs() {
modality_ptrs_.clear();
main_camera_ptrs_.clear();
all_camera_ptrs_.clear();
model_ptrs_.clear();
start_modality_renderer_ptrs_.clear();
results_renderer_ptrs_.clear();
correspondence_renderer_ptrs_.clear();
renderer_geometry_ptrs_.clear();
body_ptrs_.clear();
// Assemble objects from detectors
for (auto &detector_ptr : detector_ptrs_) {
AddPtrIfNameNotExists(detector_ptr->camera_ptr(), &all_camera_ptrs_);
AddPtrsIfNameNotExists(detector_ptr->body_ptrs(), &body_ptrs_);
}
// Assemble required objects from refiner
for (auto &refiner_ptr : refiner_ptrs_) {
for (auto &optimizer_ptr : refiner_ptr->optimizer_ptrs()) {
for (auto &modality_ptr : optimizer_ptr->modality_ptrs()) {
AddPtrsIfNameNotExists(modality_ptr->camera_ptrs(), &all_camera_ptrs_);
}
}
}
// Assemble objects from viewers
for (auto &viewer_ptr : viewer_ptrs_) {
AddPtrIfNameNotExists(viewer_ptr->camera_ptr(), &main_camera_ptrs_);
AddPtrIfNameNotExists(viewer_ptr->camera_ptr(), &all_camera_ptrs_);
AddPtrIfNameNotExists(viewer_ptr->renderer_geometry_ptr(),
&renderer_geometry_ptrs_);
}
// Assemble objects from optimizer
for (auto &optimizer_ptr : optimizer_ptrs_) {
AddPtrsIfNameNotExists(optimizer_ptr->modality_ptrs(), &modality_ptrs_);
}
// Assemble objects from modalities
for (auto &modality_ptr : modality_ptrs_) {
AddPtrsIfNameNotExists(modality_ptr->camera_ptrs(), &main_camera_ptrs_);
AddPtrsIfNameNotExists(modality_ptr->camera_ptrs(), &all_camera_ptrs_);
AddPtrIfNameNotExists(modality_ptr->model_ptr(), &model_ptrs_);
AddPtrsIfNameNotExists(modality_ptr->start_modality_renderer_ptrs(),
&start_modality_renderer_ptrs_);
AddPtrsIfNameNotExists(modality_ptr->correspondence_renderer_ptrs(),
&correspondence_renderer_ptrs_);
AddPtrsIfNameNotExists(modality_ptr->results_renderer_ptrs(),
&results_renderer_ptrs_);
AddPtrIfNameNotExists(modality_ptr->body_ptr(), &body_ptrs_);
}
// Assemble objects from models
for (auto &model_ptr : model_ptrs_) {
AddPtrIfNameNotExists(model_ptr->body_ptr(), &body_ptrs_);
}
// Assemble objects from renderers
for (auto &start_modality_renderer_ptr : start_modality_renderer_ptrs_) {
AddPtrIfNameNotExists(start_modality_renderer_ptr->renderer_geometry_ptr(),
&renderer_geometry_ptrs_);
AddPtrsIfNameNotExists(start_modality_renderer_ptr->referenced_body_ptrs(),
&body_ptrs_);
}
for (auto &correspondence_renderer_ptr : correspondence_renderer_ptrs_) {
AddPtrIfNameNotExists(correspondence_renderer_ptr->renderer_geometry_ptr(),
&renderer_geometry_ptrs_);
AddPtrsIfNameNotExists(correspondence_renderer_ptr->referenced_body_ptrs(),
&body_ptrs_);
}
for (auto results_renderer_ptr : results_renderer_ptrs_) {
AddPtrIfNameNotExists(results_renderer_ptr->renderer_geometry_ptr(),
&renderer_geometry_ptrs_);
AddPtrsIfNameNotExists(results_renderer_ptr->referenced_body_ptrs(),
&body_ptrs_);
}
// Assemble objects from renderer geometry
for (auto &renderer_geometry_ptr : renderer_geometry_ptrs_) {
AddPtrsIfNameNotExists(renderer_geometry_ptr->body_ptrs(), &body_ptrs_);
}
}
bool Tracker::SetUpAllObjects() {
return SetUpObjectPtrs(&body_ptrs_) &&
SetUpObjectPtrs(&renderer_geometry_ptrs_) &&
SetUpObjectPtrs(&all_camera_ptrs_) &&
SetUpObjectPtrs(&start_modality_renderer_ptrs_) &&
SetUpObjectPtrs(&correspondence_renderer_ptrs_) &&
SetUpObjectPtrs(&results_renderer_ptrs_) &&
SetUpObjectPtrs(&model_ptrs_) && SetUpObjectPtrs(&modality_ptrs_) &&
SetUpObjectPtrs(&optimizer_ptrs_) && SetUpObjectPtrs(&viewer_ptrs_) &&
SetUpObjectPtrs(&refiner_ptrs_) && SetUpObjectPtrs(&detector_ptrs_) &&
SetUpObjectPtrs(&publisher_ptrs_);
}
bool Tracker::AreAllObjectsSetUp() {
return AreObjectPtrsSetUp(&body_ptrs_) &&
AreObjectPtrsSetUp(&renderer_geometry_ptrs_) &&
AreObjectPtrsSetUp(&all_camera_ptrs_) &&
AreObjectPtrsSetUp(&start_modality_renderer_ptrs_) &&
AreObjectPtrsSetUp(&correspondence_renderer_ptrs_) &&
AreObjectPtrsSetUp(&results_renderer_ptrs_) &&
AreObjectPtrsSetUp(&model_ptrs_) &&
AreObjectPtrsSetUp(&modality_ptrs_) &&
AreObjectPtrsSetUp(&optimizer_ptrs_) &&
AreObjectPtrsSetUp(&viewer_ptrs_) &&
AreObjectPtrsSetUp(&refiner_ptrs_) &&
AreObjectPtrsSetUp(&detector_ptrs_) &&
AreObjectPtrsSetUp(&publisher_ptrs_);
}
} // namespace icg
| 32.194929
| 80
| 0.704209
|
XiaoJake
|
b6a95c64cfaa3b62665f75129a8ddd8523dfcb24
| 1,402
|
hpp
|
C++
|
src/ivorium_graphics/Rendering/Shader.hpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | 3
|
2021-02-26T02:59:09.000Z
|
2022-02-08T16:44:21.000Z
|
src/ivorium_graphics/Rendering/Shader.hpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | null | null | null |
src/ivorium_graphics/Rendering/Shader.hpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "../OpenGL/GlTexture.hpp"
#include "../OpenGL/GlProgram.hpp"
#include "../OpenGL/gl.h"
#include "GlSystem.hpp"
#include <ivorium_systems/ivorium_systems.hpp>
#include <ivorium_core/ivorium_core.hpp>
namespace iv
{
/**
To create shader using VirtualResourceProvider method, construct it from a path which has fragment shader source at path+".frag" and vertex shader source at path+".vert".
*/
class Shader
{
public:
ClientMarker cm;
Shader( Instance * inst, ResourcePath const & path );
~Shader();
Instance * instance() const;
void status( iv::TableDebugView * view );
//--------------------- loading ----------------------
void LoadProgram();
void BindAttribute( GLuint location, const char * attrib_name );
void PositionAttributeName( const char * name );
void LinkProgram();
void UnloadProgram();
void DropProgram();
//--------------------- usage ------
GlProgram const * gl_program() const;
GLint GetUniformLocation( const char * name ) const;
private:
Instance * inst;
ResourcePath _src_path;
GlProgram _gl_program;
};
}
| 29.208333
| 174
| 0.524964
|
ivorne
|
b6ad33a4e32cc545c631d299f020d045489c281c
| 686
|
cpp
|
C++
|
src/DesignerPlugin/SARibbonPluginCollection.cpp
|
EMinsight/SARibbon
|
4c211e961dfdf3e953b4f89bdd9acf25db1e3da6
|
[
"MIT"
] | 374
|
2017-12-27T01:08:45.000Z
|
2022-03-30T16:16:36.000Z
|
src/DesignerPlugin/SARibbonPluginCollection.cpp
|
EMinsight/SARibbon
|
4c211e961dfdf3e953b4f89bdd9acf25db1e3da6
|
[
"MIT"
] | 33
|
2017-12-07T09:24:31.000Z
|
2022-03-29T07:53:51.000Z
|
src/DesignerPlugin/SARibbonPluginCollection.cpp
|
EMinsight/SARibbon
|
4c211e961dfdf3e953b4f89bdd9acf25db1e3da6
|
[
"MIT"
] | 161
|
2017-11-24T03:12:29.000Z
|
2022-03-26T04:11:48.000Z
|
#include "SARibbonPluginCollection.h"
#include "SARibbonMainWindowDesignerPlugin.h"
#include "SARibbonBarDesignerPlugin.h"
#include "SARibbonCategoryDesignerPlugin.h"
#include "SARibbonPannelDesignerPlugin.h"
using namespace SA_PLUGIN;
SARibbonPluginCollection::SARibbonPluginCollection(QObject *p) : QObject(p)
{
m_widgets.append(new SARibbonMainWindowDesignerPlugin(this));
m_widgets.append(new SARibbonBarDesignerPlugin(this));
m_widgets.append(new SARibbonCategoryDesignerPlugin(this));
m_widgets.append(new SARibbonPannelDesignerPlugin(this));
}
QList<QDesignerCustomWidgetInterface *> SARibbonPluginCollection::customWidgets() const
{
return (m_widgets);
}
| 34.3
| 87
| 0.817784
|
EMinsight
|
b6ada5a29317a14bb626e6073fd0c5781baeabff
| 1,899
|
cpp
|
C++
|
Array/Snail Sort/main.cpp
|
pratikj697/hacktoberfest-competitiveprogramming
|
3b392edf61d2bd284bd5714af72abd76ff049340
|
[
"MIT"
] | 22
|
2021-10-02T13:18:58.000Z
|
2021-10-13T18:27:06.000Z
|
Array/Snail Sort/main.cpp
|
pratikj697/hacktoberfest-competitiveprogramming
|
3b392edf61d2bd284bd5714af72abd76ff049340
|
[
"MIT"
] | 96
|
2021-10-02T14:14:43.000Z
|
2021-10-09T06:17:33.000Z
|
Array/Snail Sort/main.cpp
|
pratikj697/hacktoberfest-competitiveprogramming
|
3b392edf61d2bd284bd5714af72abd76ff049340
|
[
"MIT"
] | 112
|
2021-10-02T14:57:15.000Z
|
2021-10-15T05:45:30.000Z
|
#include <bits/stdc++.h>
using namespace std;
vector<int> snail(const vector<vector<int>> &snail_map)
{
vector<vector<int>> input = snail_map;
//check if the vector size is greater than 1
if (input.size() > 1)
{
vector<int> answer;
// push the first row in the answer vector
for (int j = 0; j < input[0].size(); j++)
{
answer.push_back(input[0][j]);
}
// remove first row from the input
input[0].erase(input[0].begin(), input[0].end());
input.erase(input.begin());
// insert the last element from other all the rows
for (int j = 0; j < input.size(); j++)
{
answer.push_back(input[j].back());
// remove the element
input[j].pop_back();
}
// iterate the last row
for (int j = input[input.size() - 1].size() - 1; j >= 0; j--)
{
answer.push_back(input[input.size() - 1][j]);
}
input[input.size() - 1].erase(input[input.size() - 1].begin(), input[input.size() - 1].end());
input.erase(input.end());
reverse(input.begin(), input.end());
for (int i = 0; i < input.size(); i++)
{
answer.push_back(input[i][0]);
input[i].erase(input[i].begin());
}
if (input.size() > 0)
{
reverse(input.begin(), input.end());
vector<int> add = snail(input);
answer.insert(answer.end(), add.begin(), add.end());
}
return answer;
}
else
{
return snail_map[0];
}
}
//main function
int main()
{
vector<vector<int>> v = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}};
// feed the input to the function
vector<int> ans = snail(v);
cout << "Output" << endl;
// print the final output
for (int &ele : ans)
{
cout << ele;
}
}
| 24.662338
| 102
| 0.493418
|
pratikj697
|
b6b4d64f46c26a28f0216235aade202182e0cfe5
| 15,740
|
cpp
|
C++
|
src/Organism.cpp
|
Sn0wFox/ot3-pro2017
|
889dcbb1ad0203a916e7431c6525fded49ef57dd
|
[
"MIT"
] | 1
|
2017-11-13T07:23:52.000Z
|
2017-11-13T07:23:52.000Z
|
src/Organism.cpp
|
Sn0wFox/ot3-pro2017
|
889dcbb1ad0203a916e7431c6525fded49ef57dd
|
[
"MIT"
] | null | null | null |
src/Organism.cpp
|
Sn0wFox/ot3-pro2017
|
889dcbb1ad0203a916e7431c6525fded49ef57dd
|
[
"MIT"
] | null | null | null |
//
// Created by arrouan on 28/09/16.
//
#include "Organism.h"
#include "DNA.h"
#include "Common.h"
#include <map>
void Organism::translate_RNA() {
RNA* current_rna = nullptr;
for (auto it = dna_->bp_list_.begin(); it != dna_->bp_list_.end(); it++) {
if ((*it)->type_ == (int)BP::BP_Type::START_RNA) {
current_rna = new RNA((*it)->binding_pattern_,
(*it)->concentration_);
} else if ((*it)->type_ == (int)BP::BP_Type::END_RNA) {
if (current_rna != nullptr) {
rna_list_.push_back(current_rna);
current_rna = nullptr;
}
} else if (current_rna != nullptr) {
current_rna->bp_list_.push_back(new BP((*it)));
}
}
}
void Organism::translate_protein() {
float binding_pattern = -1;
int rna_id = 0;
for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) {
for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) {
if ((*it_j)->type_ == (int) BP::BP_Type::START_PROTEIN) {
binding_pattern = (*it_j)->binding_pattern_;
} else if ((*it_j)->type_ == (int) BP::BP_Type::END_PROTEIN) {
binding_pattern = -1;
} else if (((*it_j)->type_ ==
(int) BP::BP_Type::PROTEIN_BLOCK) && (binding_pattern != -1)) {
bool current_float = false; // true == next value if op arith else float
bool first_value = true; // current_value is initialized or not
float current_value = -1;
int current_arith_op = -1;
for (auto it_k = (*it_j)->protein_block_->bp_prot_list_.begin();
it_k < (*it_j)->protein_block_->bp_prot_list_.end();
it_k++) {
if ((*it_k)->type_ ==
(int) BP_Protein::BP_Protein_Type::ARITHMETIC_OPERATOR) {
if (current_float) {
current_arith_op = (*it_k)->op_;
current_float = false;
}
} else if ((*it_k)->type_ ==
(int) BP_Protein::BP_Protein_Type::FLOAT_NUMBER) {
if ((!current_float) && first_value) {
current_value =
(*it_k)->number_;
current_float = true;
first_value = false;
} else if ((!current_float) && (!first_value)) {
float value = (*it_k)->number_;
current_float = true;
if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::ADD) {
current_value+=value;
} else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::MODULO) {
current_value=std::fmod(current_value,value);
} else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::MULTIPLY) {
current_value*=value;
} else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::POWER) {
current_value=std::pow(current_value,value);
}
}
}
}
int type = -1;
if (current_value < 0.8) {
type = (int) Protein::Protein_Type::FITNESS;
} else if (current_value >= 0.8 && current_value < 0.9) {
type = (int) Protein::Protein_Type::TF;
} else if (current_value >= 0.9 && current_value < 0.95) {
type = (int) Protein::Protein_Type::POISON;
} else if (current_value >= 0.95 && current_value < 1.0) {
type = (int) Protein::Protein_Type::ANTIPOISON;
}
Protein* prot = new Protein(type,binding_pattern,current_value);
prot->concentration_ = (*it)->concentration_base_;
if ( protein_list_map_.find(current_value) == protein_list_map_.end() ) {
protein_list_map_[current_value] = prot;
if (type == (int) Protein::Protein_Type::FITNESS) {
protein_fitness_list_.push_back(prot);
} else if (type == (int) Protein::Protein_Type::TF) {
protein_TF_list_.push_back(prot);
} else if (type == (int) Protein::Protein_Type::POISON) {
protein_poison_list_.push_back(prot);
} else if (type == (int) Protein::Protein_Type::ANTIPOISON) {
protein_antipoison_list_.push_back(prot);
}
} else {
protein_list_map_[current_value]->concentration_+=(*it)->concentration_base_;
delete prot;
}
rna_produce_protein_.push_back(current_value);
}
}
rna_id++;
}
}
void Organism::translate_pump() {
bool within_pump = false;
for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) {
for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) {
if ((*it_j)->type_ ==
(int) BP::BP_Type::START_PUMP) {
within_pump = true;
} else if ((*it_j)->type_ ==
(int) BP::BP_Type::END_PUMP) {
within_pump = false;
} else if (((*it_j)->type_ ==
(int) BP::BP_Type::PUMP_BLOCK) && (within_pump)) {
for (auto it_k=(*it_j)->pump_block_->bp_pump_list_.begin(); it_k < (*it_j)->pump_block_->
bp_pump_list_.end(); it_k++) {
Pump* pump = new Pump((*it_k)->in_out_,(*it_k)->start_range_,
(*it_k)->end_range_,(*it_k)->speed_);
pump_list_.push_back(pump);
}
}
}
}
}
void Organism::translate_move() {
bool within_move = false;
for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) {
for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) {
if ((*it_j)->type_ ==
(int) BP::BP_Type::START_MOVE) {
within_move = true;
} else if ((*it_j)->type_ ==
(int) BP::BP_Type::END_MOVE) {
within_move = false;
} else if (((*it_j)->type_ ==
(int) BP::BP_Type::MOVE_BLOCK) && (within_move)) {
for (auto it_k=(*it_j)->move_block_->
bp_move_list_.begin(); it_k < (*it_j)->move_block_->
bp_move_list_.end(); it_k++) {
Move* move = new Move((*it_k)->distance_,(*it_k)->retry_);
move_list_.push_back(move);
}
}
}
}
}
void Organism::compute_next_step() {
// Activate Pump
activate_pump();
// Compute protein concentration for X steps
compute_protein_concentration();
}
void Organism::activate_pump() {
for (auto it = pump_list_.begin(); it != pump_list_.end(); it++) {
if ((*it)->in_out_) {
for (auto prot : protein_list_map_) {
if ((*it)->start_range_ >= prot.second->value_ &&
(*it)->end_range_ <= prot.second->value_) {
float remove = prot.second->concentration_*((*it)->speed_/100);
prot.second->concentration_ -= remove;
if ( gridcell_->protein_list_map_.find(prot.second->value_) == gridcell_->protein_list_map_.end() ) {
Protein* prot_n = new Protein(prot.second->type_, prot.second->binding_pattern_, prot.second->value_);
prot_n->concentration_ = remove;
gridcell_->protein_list_map_[prot.second->value_] = prot_n;
} else {
gridcell_->protein_list_map_[prot.second->value_]->concentration_ += remove;
}
}
}
} else {
for (auto prot : gridcell_->protein_list_map_) {
if ((*it)->start_range_ >= prot.first && (*it)->end_range_ <= prot.first) {
float remove = prot.second->concentration_*((*it)->speed_/100);
prot.second->concentration_ -= remove;
if ( protein_list_map_.find(prot.first) == protein_list_map_.end() ) {
Protein* prot_n = new Protein(prot.second->type_, prot.second->binding_pattern_, prot.second->value_);
prot_n->concentration_ = remove;
protein_list_map_[prot_n->value_] = prot_n;
} else {
protein_list_map_[prot.first]->concentration_ += remove;
}
}
}
}
}
}
void Organism::init_organism() {
translate_RNA();
translate_protein();
translate_pump();
translate_move();
}
void Organism::compute_protein_concentration() {
current_concentration_compute();
delta_concentration_compute();
}
// TODO: the critical call everyone !
void Organism::delta_concentration_compute() {
for (int rna_id = 0; rna_id < rna_produce_protein_.size(); rna_id++) {
rna_list_[rna_id]->current_concentration_ -= Common::Protein_Degradation_Rate * protein_list_map_[rna_produce_protein_[rna_id]]->concentration_;
rna_list_[rna_id]->current_concentration_ *= 1/(Common::Protein_Degradation_Step);
protein_list_map_[rna_produce_protein_[rna_id]]->concentration_+=rna_list_[rna_id]->current_concentration_;
}
}
bool Organism::dying_or_not() {
// Compute if dying or not
double concentration_sum = 0;
for (auto prot : protein_fitness_list_) {
concentration_sum+=prot->concentration_;
}
for (auto prot : protein_TF_list_) {
concentration_sum+=prot->concentration_;
}
if (concentration_sum > 10.0 && concentration_sum <= 0.0) {
return true;
}
double poison=0,antipoison=0;
for (auto prot : protein_poison_list_) {
poison+=prot->concentration_;
}
for (auto prot : protein_antipoison_list_) {
antipoison+=prot->concentration_;
}
if (poison-antipoison>0.1) {
return true;
}
std::binomial_distribution<int> dis_death(1024,Common::Random_Death);
int death_number = dis_death(gridcell_->float_gen_);
bool death = (bool) death_number % 2;
return death;
}
void Organism::try_to_move() {
for (auto it = move_list_.begin(); it != move_list_.end(); it++) {
if ((*it)->distance_ > 0) {
bool move = false;
int retry = 0;
std::uniform_int_distribution<uint32_t> dis_distance(0,(*it)->distance_);
while (retry < (*it)->retry_ && !move) {
int x_offset=dis_distance(gridcell_->float_gen_);
int y_offset=dis_distance(gridcell_->float_gen_);
int new_x,new_y;
if (gridcell_->x_+x_offset >= gridcell_->world_->width_) {
new_x = gridcell_->world_->width_-1;
} else {
new_x = gridcell_->x_+x_offset;
}
if (gridcell_->y_+y_offset >= gridcell_->world_->height_) {
new_y = gridcell_->world_->height_-1;
} else {
new_y = gridcell_->y_+y_offset;
}
if (gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]->organism_ != nullptr) {
move = true;
move_success_++;
gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]->organism_ = this;
gridcell_ = gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y];
gridcell_->organism_ = nullptr;
}
}
}
}
}
void Organism::compute_fitness() {
life_duration_++;
for (int i = 0; i < Common::Metabolic_Error_Precision; i++)
metabolic_error[i] = 0.0;
for (auto prot : protein_fitness_list_) { //.begin(); it != protein_fitness_list_.end(); it++) {
int index = prot->value_*Common::Metabolic_Error_Precision;
float concentration = prot->concentration_;
for (int j = index - Common::Metabolic_Error_Protein_Spray;
j <= index + Common::Metabolic_Error_Protein_Spray; j++) {
if (j < Common::Metabolic_Error_Precision && j >= 0) {
if (j < index) {
metabolic_error[j] +=
(index - j) * Common::Metabolic_Error_Protein_Slope * concentration;
} else if (j > index) {
metabolic_error[j] +=
(j - index) * Common::Metabolic_Error_Protein_Slope * concentration;
} else {
metabolic_error[j] += concentration;
}
}
}
}
sum_metabolic_error = 0;
for (int i = 0; i < Common::Metabolic_Error_Precision; i++) {
sum_metabolic_error+=std::abs(gridcell_->environment_target[i]-metabolic_error[i]);
}
sum_metabolic_error=sum_metabolic_error/Common::Metabolic_Error_Precision;
fitness_ = std::exp(-Common::Fitness_Selection_Pressure*sum_metabolic_error);
}
void Organism::mutate() {
old = this;
std::binomial_distribution<int> dis_switch(dna_->bp_list_.size(),Common::Mutation_Rate);
std::binomial_distribution<int> dis_insertion(dna_->bp_list_.size(),Common::Mutation_Rate);
std::binomial_distribution<int> dis_deletion(dna_->bp_list_.size(),Common::Mutation_Rate);
std::binomial_distribution<int> dis_duplication(dna_->bp_list_.size(),Common::Mutation_Rate);
std::binomial_distribution<int> dis_modification(dna_->bp_list_.size(),Common::Mutation_Rate);
int nb_switch = dis_switch(gridcell_->float_gen_);
int nb_insertion = dis_insertion(gridcell_->float_gen_);
int nb_deletion = dis_deletion(gridcell_->float_gen_);
int nb_duplication = dis_duplication(gridcell_->float_gen_);
int nb_modification = dis_modification(gridcell_->float_gen_);
std::uniform_int_distribution<uint32_t> dis_position(0,dna_->bp_list_.size());
for (int i = 0; i < nb_deletion; i++) {
int deletion_pos = dis_position(gridcell_->float_gen_);
while (deletion_pos >= dna_->bp_list_.size()) {
deletion_pos = dis_position(gridcell_->float_gen_);
}
dna_->bp_list_.erase(dna_->bp_list_.begin() + deletion_pos);
}
for (int i = 0; i < nb_switch; i++) {
int switch_pos_1 = dis_position(gridcell_->float_gen_);
while (switch_pos_1 >= dna_->bp_list_.size()) {
switch_pos_1 = dis_position(gridcell_->float_gen_);
}
int switch_pos_2 = dis_position(gridcell_->float_gen_);
while (switch_pos_2 >= dna_->bp_list_.size()) {
switch_pos_2 = dis_position(gridcell_->float_gen_);
}
BP* tmp = dna_->bp_list_[switch_pos_1];
dna_->bp_list_[switch_pos_1] = dna_->bp_list_[switch_pos_2];
dna_->bp_list_[switch_pos_2] = tmp;
}
for (int i = 0; i < nb_duplication; i++) {
int duplication_pos = dis_position(gridcell_->float_gen_);
while (duplication_pos >= dna_->bp_list_.size()) {
duplication_pos = dis_position(gridcell_->float_gen_);
}
int where_to_duplicate = dis_position(gridcell_->float_gen_);
while (where_to_duplicate >= dna_->bp_list_.size()) {
where_to_duplicate = dis_position(gridcell_->float_gen_);
}
dna_->bp_list_.insert(dna_->bp_list_.begin()+where_to_duplicate,
new BP(dna_->bp_list_[duplication_pos]));
}
for (int i = 0; i < nb_insertion; i++) {
int insertion_pos = dis_position(gridcell_->float_gen_);
while (insertion_pos >= dna_->bp_list_.size()) {
insertion_pos = dis_position(gridcell_->float_gen_);
}
dna_->insert_a_BP(insertion_pos,gridcell_);
}
for (int i = 0; i < nb_modification; i++) {
int modification_pos = dis_position(gridcell_->float_gen_);
while (modification_pos >= dna_->bp_list_.size()) {
modification_pos = dis_position(gridcell_->float_gen_);
}
dna_->modify_bp(modification_pos,gridcell_);
}
}
Organism* Organism::divide() {
Organism* new_org = new Organism(this);
return new_org;
}
Organism::Organism(Organism* organism) {
dna_ = new DNA(organism->dna_);
for(auto prot : organism->protein_list_map_) {
Protein* new_prot = new Protein(prot.second);
new_prot->concentration_ = new_prot->concentration_/2;
prot.second->concentration_ = prot.second->concentration_/2;
}
}
Organism::~Organism() {
for (auto rna : rna_list_)
delete rna;
delete dna_;
rna_produce_protein_.clear();
for (auto prot : protein_list_map_) {
delete prot.second;
}
protein_fitness_list_.clear();
protein_TF_list_.clear();
protein_poison_list_.clear();
protein_antipoison_list_.clear();
protein_list_map_.clear();
for (auto pump : pump_list_) {
delete pump;
}
pump_list_.clear();
for (auto move : move_list_) {
delete move;
}
move_list_.clear();
}
| 33.99568
| 148
| 0.621283
|
Sn0wFox
|
b6b5fe4613ca8b0c02dd1317846a4aa778714896
| 8,263
|
cxx
|
C++
|
Temporary/itkDijkstrasAlgorithm.cxx
|
KevinScholtes/ANTsX
|
5462269c0c32e5d65560bae4014c5a05cb02588d
|
[
"BSD-3-Clause"
] | null | null | null |
Temporary/itkDijkstrasAlgorithm.cxx
|
KevinScholtes/ANTsX
|
5462269c0c32e5d65560bae4014c5a05cb02588d
|
[
"BSD-3-Clause"
] | null | null | null |
Temporary/itkDijkstrasAlgorithm.cxx
|
KevinScholtes/ANTsX
|
5462269c0c32e5d65560bae4014c5a05cb02588d
|
[
"BSD-3-Clause"
] | 1
|
2019-10-06T07:31:58.000Z
|
2019-10-06T07:31:58.000Z
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
=========================================================================*/
#ifndef _itkDijkstrasAlgorithm_cxx_
#define _itkDijkstrasAlgorithm_cxx_
#include "itkDijkstrasAlgorithm.h"
namespace itk
{
template <typename TGraphSearchNode>
DijkstrasAlgorithm<TGraphSearchNode>::DijkstrasAlgorithm()
{
m_Graph = GraphType::New();
m_QS = DijkstrasAlgorithmQueue<TGraphSearchNode>::New();
m_MaxCost = vnl_huge_val(m_MaxCost); // not defined for unsigned char
this->m_TotalCost = 0;
};
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::SetGraphSize(GraphSizeType Sz)
{
for( int i = 0; i < GraphDimension; i++ )
{
m_GraphSize[i] = Sz[i];
}
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::InitializeGraph()
{
m_GraphRegion.SetSize( m_GraphSize );
m_Graph->SetLargestPossibleRegion( m_GraphRegion );
m_Graph->SetRequestedRegion( m_GraphRegion );
m_Graph->SetBufferedRegion( m_GraphRegion );
m_Graph->Allocate();
GraphIteratorType GraphIterator( m_Graph, m_GraphRegion );
GraphIterator.GoToBegin();
NodeLocationType loc;
while( !GraphIterator.IsAtEnd() )
{
typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = nullptr;
GraphIterator.Set(G);
++GraphIterator;
/*
m_GraphIndex = GraphIterator.GetIndex();
//std::cout << " allocating " << m_GraphIndex << std::endl;
///GraphSearchNode<PixelType,CoordRep,GraphDimension>::Pointer G=
G=TGraphSearchNode::New();
G->SetUnVisited();
G->SetTotalCost(m_MaxCost);
for (int i=0; i<GraphDimension; i++) loc[i]=m_GraphIndex[i];
G->SetLocation(loc);
G->SetPredecessor(nullptr);
m_Graph->SetPixel(m_GraphIndex,G);*/
m_Graph->SetPixel( GraphIterator.GetIndex(), nullptr); // USE IF POINTER IMAGE defines visited
}
m_SearchFinished = false;
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::InitializeQueue()
{
int n = m_QS->m_SourceNodes.size();
GraphIteratorType GraphIterator( m_Graph, m_GraphRegion );
m_GraphSize = m_Graph->GetLargestPossibleRegion().GetSize();
GraphIterator.GoToBegin();
m_GraphIndex = GraphIterator.GetIndex();
NodeLocationType loc;
// make sure the graph contains the right pointers
for( int i = 0; i < n; i++ )
{
typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = m_QS->m_SourceNodes[i];
G->SetPredecessor(G);
m_QS->m_Q.push(G);
loc = G->GetLocation();
for( int d = 0; d < GraphDimension; d++ )
{
m_GraphIndex[d] = (long int)(loc[d] + 0.5);
}
m_Graph->SetPixel(m_GraphIndex, G);
}
for( int i = 0; i < m_QS->m_SinkNodes.size(); i++ )
{
typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = m_QS->m_SinkNodes[i];
G->SetPredecessor(nullptr);
loc = G->GetLocation();
for( int d = 0; d < GraphDimension; d++ )
{
m_GraphIndex[d] = (long)loc[d];
}
m_Graph->SetPixel(m_GraphIndex, G);
}
m_SearchFinished = false;
if( m_EdgeTemplate.empty() )
{
InitializeEdgeTemplate();
}
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::InitializeEdgeTemplate
(vector<unsigned int> UserEdgeTemplate, unsigned int R)
{
for( int i = 0; i < GraphDimension; i++ )
{
m_Radius[i] = R;
}
m_EdgeTemplate = UserEdgeTemplate;
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::InitializeEdgeTemplate()
{
int MaxIndex = 1;
for( int i = 0; i < GraphDimension; i++ )
{
m_Radius[i] = 1;
}
for( int i = 0; i < GraphDimension; i++ )
{
MaxIndex = MaxIndex * (2 * m_Radius[i] + 1);
}
MaxIndex = MaxIndex - 1;
// int Center = MaxIndex/2;
for( unsigned int i = 0; i <= MaxIndex; i++ )
{
// if (i != Center)
m_EdgeTemplate.insert(m_EdgeTemplate.end(), i);
}
}
/**
* Compute the local cost using Manhattan distance.
*/
template <typename TGraphSearchNode>
typename DijkstrasAlgorithm<TGraphSearchNode>::
PixelType DijkstrasAlgorithm<TGraphSearchNode>::LocalCost()
{
return 1.0; // manhattan distance
};
template <typename TGraphSearchNode>
bool DijkstrasAlgorithm<TGraphSearchNode>::TerminationCondition()
{
if( !m_QS->m_SinkNodes.empty() )
{
if( m_NeighborNode == m_QS->m_SinkNodes[0] && !m_SearchFinished )
{
m_SearchFinished = true;
m_NeighborNode->SetPredecessor(m_CurrentNode);
}
}
else
{
m_SearchFinished = true;
}
return m_SearchFinished;
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::SearchEdgeSet()
{
// std::cout << " SES 0 " << std::endl;
GraphNeighborhoodIteratorType GHood(m_Radius, m_Graph, m_Graph->GetRequestedRegion() );
GraphNeighborhoodIndexType GNI;
// std::cout << " SES 1 " << std::endl;
for( unsigned int i = 0; i < GraphDimension; i++ )
{
// std::cout << " SES 2 " << std::endl;
GNI[i] = (long)(m_CurrentNode->GetLocation()[i] + 0.5);
}
// std::cout << " SES 3 " << std::endl;
GHood.SetLocation(GNI);
for( unsigned int dd = 0; dd < GraphDimension; dd++ )
{
if( GNI[dd] < 2 || GNI[dd] > (unsigned long)(m_GraphSize[dd] - 2) )
{
return;
}
}
for( unsigned int i = 0; i < m_EdgeTemplate.size(); i++ )
{
// std::cout << " SES 4 " << std::endl;
// std::cout << " ET " << m_EdgeTemplate[i] << " RAD " << m_Radius << " ind " <<
// GHood.GetIndex(m_EdgeTemplate[i])
// << std::endl;
if( !GHood.GetPixel(m_EdgeTemplate[i]) ) // std::cout << " OK " << std::endl;
// /else
{
// std::cout << " NOT OK " <<std::endl;
GraphNeighborhoodIndexType ind = GHood.GetIndex(m_EdgeTemplate[i]);
typename TGraphSearchNode::Pointer G = TGraphSearchNode::New();
G->SetUnVisited();
G->SetTotalCost(m_MaxCost);
NodeLocationType loc;
for( int j = 0; j < GraphDimension; j++ )
{
loc[j] = ind[j];
}
G->SetLocation(loc);
G->SetPredecessor(m_CurrentNode);
m_Graph->SetPixel(ind, G);
}
m_NeighborNode = GHood.GetPixel(m_EdgeTemplate[i]);
// std::cout << "DA i " << i << " position " << m_NeighborNode->GetLocation() << endl;
this->TerminationCondition();
if( !m_SearchFinished && m_CurrentNode != m_NeighborNode &&
!m_NeighborNode->GetDelivered() )
{
m_NewCost = m_CurrentCost + LocalCost();
CheckNodeStatus();
}
}
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::CheckNodeStatus()
// checks a graph neighbor's status
{
if( !m_NeighborNode->GetVisited() )
{
// set the cost and put into the queue
m_NeighborNode->SetTotalCost(m_NewCost);
m_NeighborNode->SetPredecessor(m_CurrentNode);
m_NeighborNode->SetVisited();
m_QS->m_Q.push(m_NeighborNode);
}
else if( m_NewCost < m_NeighborNode->GetTotalCost() )
{
m_NeighborNode->SetTotalCost(m_NewCost);
m_NeighborNode->SetPredecessor(m_CurrentNode);
m_QS->m_Q.push(m_NeighborNode);
}
}
template <typename TGraphSearchNode>
void DijkstrasAlgorithm<TGraphSearchNode>::FindPath()
{
if( m_QS->m_SourceNodes.empty() )
{
std::cout << "ERROR !! DID NOT SET SOURCE!!\n";
return;
}
while( !m_SearchFinished && !m_QS->m_Q.empty() )
{
m_CurrentNode = m_QS->m_Q.top();
m_CurrentCost = m_CurrentNode->GetTotalCost();
m_QS->m_Q.pop();
if( !m_CurrentNode->GetDelivered() )
{
m_QS->IncrementTimer();
this->SearchEdgeSet();
this->m_TotalCost += m_CurrentNode->GetTotalCost();
// if ( (m_CurrentNode->GetTimer() % 1.e5 ) == 0)
// std::cout << " searched " << m_CurrentNode->GetTimer() << " \n";
}
m_CurrentNode->SetDelivered();
} // end of while
m_NumberSearched = (unsigned long) m_QS->GetTimer();
std::cout << "Done with find path " << " Q size " << m_QS->m_Q.size() << " num searched "
<< m_NumberSearched
<< " \n";
return;
}
} // end namespace itk
#endif
| 29.510714
| 102
| 0.634394
|
KevinScholtes
|
b6b72c1630b812386588a73fbd70d8cc1da09715
| 368
|
cpp
|
C++
|
5 Star 30 Days Of Code/Day 2 Operators.cpp
|
TheCodeAlpha26/Hackerrank-Demystified
|
03713a8f3a05e5d6dfed6f6808b06340558e2310
|
[
"Apache-2.0"
] | 6
|
2021-04-26T17:09:54.000Z
|
2021-07-08T17:36:16.000Z
|
5 Star 30 Days Of Code/Day 2 Operators.cpp
|
TheCodeAlpha26/Hackerrank-Demystified
|
03713a8f3a05e5d6dfed6f6808b06340558e2310
|
[
"Apache-2.0"
] | null | null | null |
5 Star 30 Days Of Code/Day 2 Operators.cpp
|
TheCodeAlpha26/Hackerrank-Demystified
|
03713a8f3a05e5d6dfed6f6808b06340558e2310
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
void solve(double mc, int tp, int tx) {
double t=0.01*mc*(100+tx+tp);
printf("%.0f",t); //.0f to set precision (to nearest integer)
}
int main()
{
double meal_cost;
cin >> meal_cost;
int tip_percent,tp;
cin >> tip_percent>>tp;
solve(meal_cost, tip_percent, tp);
return 0;
}
| 23
| 78
| 0.597826
|
TheCodeAlpha26
|
b6b7a543f82a8096c663767628acda3aa22013b8
| 22,994
|
cpp
|
C++
|
code_reading/oceanbase-master/src/storage/ob_sstable_rowkey_helper.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | null | null | null |
code_reading/oceanbase-master/src/storage/ob_sstable_rowkey_helper.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | null | null | null |
code_reading/oceanbase-master/src/storage/ob_sstable_rowkey_helper.cpp
|
wangcy6/weekly_read
|
3a8837ee9cd957787ee1785e4066dd623e02e13a
|
[
"Apache-2.0"
] | 1
|
2020-10-18T12:59:31.000Z
|
2020-10-18T12:59:31.000Z
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX STORAGE
#include "ob_sstable_rowkey_helper.h"
#include "lib/container/ob_fixed_array_iterator.h"
#include "share/ob_get_compat_mode.h"
#include "storage/ob_sstable.h"
namespace oceanbase {
using namespace common;
using namespace blocksstable;
using namespace share;
using namespace share::schema;
namespace storage {
/*
*ObRowkeyObjComparer
*/
// temporarily keep if in compare func
// remove if to build more compare funcs array when perf critical
int ObRowkeyObjComparer::sstable_number_cmp_func(const ObObj& obj1, const ObObj& obj2, const ObCompareCtx& cmp_ctx)
{
int cmp = 0;
UNUSED(cmp_ctx);
if (OB_UNLIKELY(!obj1.is_number() || !obj2.is_number())) {
LOG_ERROR("unexpected error. mismatch function for comparison", K(obj1), K(obj2));
right_to_die_or_duty_to_live();
} else if (OB_LIKELY(((is_smallint_number(obj1) && is_smallint_number(obj2))))) {
cmp = obj1.v_.nmb_digits_[0] - obj2.v_.nmb_digits_[0];
cmp = cmp > 0 ? ObObjCmpFuncs::CR_GT : cmp < 0 ? ObObjCmpFuncs::CR_LT : ObObjCmpFuncs::CR_EQ;
} else {
cmp = number::ObNumber::compare(obj1.nmb_desc_, obj1.v_.nmb_digits_, obj2.nmb_desc_, obj2.v_.nmb_digits_);
}
return cmp;
}
int ObRowkeyObjComparer::sstable_collation_free_cmp_func(
const ObObj& obj1, const ObObj& obj2, const ObCompareCtx& cmp_ctx)
{
int cmp = 0;
UNUSED(cmp_ctx);
if (OB_UNLIKELY(
CS_TYPE_COLLATION_FREE != obj2.get_collation_type() || obj1.get_collation_type() != obj2.get_collation_type()
//|| obj1.get_type() != obj2.get_type()
//|| !obj1.is_varchar_or_char()
)) {
STORAGE_LOG(ERROR, "unexpected error, invalid argument", K(obj1), K(obj2));
right_to_die_or_duty_to_live();
} else {
const int32_t lhs_len = obj1.get_val_len();
const int32_t rhs_len = obj2.get_val_len();
const int32_t cmp_len = MIN(lhs_len, rhs_len);
cmp = MEMCMP(obj1.get_string_ptr(), obj2.get_string_ptr(), cmp_len);
if (0 == cmp) {
if (lhs_len != rhs_len) {
// in mysql mode, we should strip all trailing blanks before comparing two strings
const int32_t left_len = (lhs_len > cmp_len) ? lhs_len - cmp_len : rhs_len - cmp_len;
const char* ptr = (lhs_len > cmp_len) ? obj1.get_string_ptr() : obj2.get_string_ptr();
const unsigned char* uptr = reinterpret_cast<const unsigned char*>(ptr + cmp_len);
// int32_t is always capable of stroing the max lenth of varchar or char
for (int32_t i = 0; i < left_len; ++i) {
if (*(uptr + i) != ' ') {
// special behavior in mysql mode, 'a\1 < a' and 'ab > a'
if (*(uptr + i) < ' ') {
cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_LT : ObObjCmpFuncs::CR_GT;
} else {
cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT;
}
break;
}
}
}
} else {
cmp = cmp > 0 ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT;
}
}
return cmp;
}
int ObRowkeyObjComparer::sstable_oracle_collation_free_cmp_func(
const ObObj& obj1, const ObObj& obj2, const ObCompareCtx& cmp_ctx)
{
int cmp = 0;
UNUSED(cmp_ctx);
if (OB_UNLIKELY(
CS_TYPE_COLLATION_FREE != obj2.get_collation_type() || obj1.get_collation_type() != obj2.get_collation_type()
//|| obj1.get_type() != obj2.get_type()
//|| !obj1.is_varchar_or_char()
)) {
STORAGE_LOG(ERROR, "unexpected error, invalid argument", K(obj1), K(obj2));
right_to_die_or_duty_to_live();
} else {
const int32_t lhs_len = obj1.get_val_len();
const int32_t rhs_len = obj2.get_val_len();
const int32_t cmp_len = MIN(lhs_len, rhs_len);
cmp = MEMCMP(obj1.get_string_ptr(), obj2.get_string_ptr(), cmp_len);
if (0 == cmp) {
// in oracle mode, we should consider the trailing blanks during comparing two varchar
if (obj1.is_varying_len_char_type()) {
if (lhs_len != rhs_len) {
cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT;
}
} else {
// in oracle mode, we should strip all trailing blanks before comparing two char
const int32_t left_len = (lhs_len > cmp_len) ? lhs_len - cmp_len : rhs_len - cmp_len;
const char* ptr = (lhs_len > cmp_len) ? obj1.get_string_ptr() : obj2.get_string_ptr();
const unsigned char* uptr = reinterpret_cast<const unsigned char*>(ptr + cmp_len);
// int32_t is always capable of stroing the max lenth of varchar or char
for (int32_t i = 0; i < left_len; ++i) {
if (*(uptr + i) != ' ') {
cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT;
break;
}
}
}
} else {
cmp = cmp > 0 ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT;
}
}
return cmp;
}
ObRowkeyObjComparer::ObRowkeyObjComparer()
: cmp_func_(NULL),
cmp_ctx_(ObMaxType, CS_TYPE_INVALID, false, INVALID_TZ_OFF, NULL_FIRST),
is_collation_free_(false),
type_(COMPARER_MYSQL)
{}
void ObRowkeyObjComparer::reset()
{
cmp_func_ = NULL;
cmp_ctx_.cmp_cs_type_ = CS_TYPE_INVALID;
is_collation_free_ = false;
}
int ObRowkeyObjComparer::init_compare_func(const ObObjMeta& obj_meta)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!obj_meta.is_valid())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to init compare func", K(obj_meta), K(ret));
} else {
reset();
if (obj_meta.is_number()) {
cmp_func_ = sstable_number_cmp_func;
} else {
ObObjTypeClass obj_tc = obj_meta.get_type_class();
if (OB_FAIL(ObObjCmpFuncs::get_cmp_func(obj_tc, obj_tc, CO_CMP, cmp_func_))) {
STORAGE_LOG(WARN, "Failed to find rowkey obj cmp func", K(obj_meta), K(obj_tc), K(ret));
} else if (OB_ISNULL(cmp_func_)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "Failed to find rowkey cmp func", K(ret));
}
}
if (OB_SUCC(ret)) {
cmp_ctx_.cmp_cs_type_ = obj_meta.get_collation_type();
is_collation_free_ = false;
}
}
return ret;
}
int ObRowkeyObjComparer::init_compare_func_collation_free(const common::ObObjMeta& obj_meta)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!obj_meta.is_valid())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to init collation free compare func", K(obj_meta), K(ret));
} else if (obj_meta.is_collation_free_compatible()) {
reset();
cmp_func_ = sstable_collation_free_cmp_func;
cmp_ctx_.cmp_cs_type_ = obj_meta.get_collation_type();
is_collation_free_ = true;
} else if (OB_FAIL(init_compare_func(obj_meta))) {
STORAGE_LOG(WARN, "Failed to init compare func", K(obj_meta), K(ret));
}
return ret;
}
/*
*ObRowkeyObjComparerOracle
*/
int ObRowkeyObjComparerOracle::init_compare_func_collation_free(const common::ObObjMeta& obj_meta)
{
int ret = OB_SUCCESS;
// TODO oracle mode need add raw type future
if (OB_UNLIKELY(!obj_meta.is_valid() || !obj_meta.is_collation_free_compatible())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to init collation free compare func", K(obj_meta), K(ret));
} else {
reset();
cmp_func_ = sstable_oracle_collation_free_cmp_func;
cmp_ctx_.cmp_cs_type_ = obj_meta.get_collation_type();
is_collation_free_ = true;
}
return ret;
}
/*
*ObSSTableRowkeyHelper
*/
ObSSTableRowkeyHelper::ObSSTableRowkeyHelper()
: endkeys_(),
collation_free_endkeys_(),
cmp_funcs_(),
collation_free_cmp_funcs_(),
rowkey_column_cnt_(0),
column_type_array_(NULL),
sstable_(nullptr),
exist_collation_free_(false),
use_cmp_nullsafe_(false),
is_oracle_mode_(false),
is_inited_(false)
{}
void ObSSTableRowkeyHelper::reset()
{
endkeys_.reset();
collation_free_endkeys_.reset();
cmp_funcs_.reset();
collation_free_cmp_funcs_.reset();
rowkey_column_cnt_ = 0;
column_type_array_ = NULL;
sstable_ = nullptr;
exist_collation_free_ = false;
use_cmp_nullsafe_ = false;
is_oracle_mode_ = false;
is_inited_ = false;
}
int ObSSTableRowkeyHelper::get_macro_block_meta(
const MacroBlockId& macro_id, ObFullMacroBlockMeta& macro_meta, const int64_t schema_rowkey_column_cnt)
{
int ret = OB_SUCCESS;
if (!macro_id.is_valid() || schema_rowkey_column_cnt <= 0) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to get macro block meta", K(macro_id), K(schema_rowkey_column_cnt), K(ret));
} else if (OB_FAIL(sstable_->get_meta(macro_id, macro_meta))) {
STORAGE_LOG(WARN, "fail to get meta", K(ret), K(macro_id));
} else if (!macro_meta.is_valid()) {
ret = OB_ERR_SYS;
STORAGE_LOG(WARN, "Unexpected null macro meta", K(ret));
} else if (OB_ISNULL(macro_meta.meta_->endkey_) || OB_ISNULL(macro_meta.schema_->column_type_array_)) {
ret = OB_ERR_SYS;
STORAGE_LOG(WARN, "Unexpected null data macro endkey", K(macro_meta), K(ret));
} else if (OB_UNLIKELY(macro_meta.meta_->rowkey_column_number_ < schema_rowkey_column_cnt)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN,
"Unexpected mis matched rowkey column number",
K(macro_meta.meta_->rowkey_column_number_),
K(schema_rowkey_column_cnt),
K(ret));
}
return ret;
}
int ObSSTableRowkeyHelper::build_macro_endkeys(const ObIArray<MacroBlockId>& macro_ids, ObIAllocator& allocator,
const int64_t schema_rowkey_column_cnt, const bool need_build_collation_free)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(macro_ids.count() == 0 || schema_rowkey_column_cnt <= 0)) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to build macro endkeys", K(macro_ids), K(schema_rowkey_column_cnt), K(ret));
} else {
int64_t macro_block_count = macro_ids.count();
ObFullMacroBlockMeta full_meta;
ObStoreRowkey rowkey;
endkeys_.set_allocator(&allocator);
endkeys_.set_capacity(static_cast<uint32_t>(macro_block_count));
for (int64_t i = 0; OB_SUCC(ret) && i < macro_block_count; i++) {
if (OB_FAIL(get_macro_block_meta(macro_ids.at(i), full_meta, schema_rowkey_column_cnt))) {
STORAGE_LOG(WARN, "Failed to get macro block meta", K(i), K(ret));
} else {
const ObMacroBlockMetaV2* macro_meta = full_meta.meta_;
rowkey.assign(macro_meta->endkey_, macro_meta->rowkey_column_number_);
// TODO consider column order
if (rowkey.contains_min_or_max_obj() || (!use_cmp_nullsafe_ && rowkey.contains_null_obj())) {
ret = OB_ERR_SYS;
STORAGE_LOG(WARN, "Unexpected max or min macro endkey", K(rowkey), K(ret));
} else if (0 == i) {
rowkey_column_cnt_ = macro_meta->rowkey_column_number_;
column_type_array_ = full_meta.schema_->column_type_array_;
exist_collation_free_ = false;
if (need_build_collation_free) {
for (int64_t i = 0; !exist_collation_free_ && i < rowkey_column_cnt_; i++) {
if (column_type_array_[i].is_collation_free_compatible()) {
exist_collation_free_ = true;
}
}
if (exist_collation_free_) {
collation_free_endkeys_.set_allocator(&allocator);
collation_free_endkeys_.set_capacity(static_cast<uint32_t>(macro_block_count));
}
}
}
if (OB_FAIL(ret)) {
} else if (OB_FAIL(endkeys_.push_back(rowkey))) {
STORAGE_LOG(WARN, "Failed to push back macroblock endkey", K(rowkey), K(ret));
} else if (exist_collation_free_) {
if (OB_ISNULL(macro_meta->collation_free_endkey_)) {
// defend code to check null collation free endkey
for (int64_t i = 0; i < rowkey_column_cnt_; i++) {
// original varchar or char should be null now
if (rowkey.get_obj_ptr()[i].is_collation_free_compatible()) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "Unexpected null collation freekey with valid rowkey", K(i), K(*macro_meta), K(ret));
}
}
} else {
rowkey.assign(macro_meta->collation_free_endkey_, macro_meta->rowkey_column_number_);
}
if (OB_SUCC(ret)) {
if (OB_FAIL(collation_free_endkeys_.push_back(rowkey))) {
STORAGE_LOG(WARN, "Failed to push back macroblock endkey", K(rowkey), K(ret));
}
}
}
}
}
if (OB_SUCC(ret)) {
if (endkeys_.count() != macro_block_count ||
(exist_collation_free_ && collation_free_endkeys_.count() != macro_block_count)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN,
"Unexpected macro block endkeys count",
K(macro_block_count),
K_(exist_collation_free),
K(endkeys_.count()),
K(collation_free_endkeys_.count()),
K(ret));
}
}
}
return ret;
}
template <typename T>
int ObSSTableRowkeyHelper::make_rowkey_cmp_funcs(ObIAllocator& allocator)
{
int ret = OB_SUCCESS;
if (OB_ISNULL(column_type_array_) || rowkey_column_cnt_ <= 0) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN,
"Unexpected null column type array or rowkey column cnt",
KP_(column_type_array),
K_(rowkey_column_cnt),
K(ret));
} else {
void* buf = NULL;
T* cmp_funcs = NULL;
cmp_funcs_.set_allocator(&allocator);
cmp_funcs_.set_capacity(rowkey_column_cnt_);
if (OB_ISNULL(buf = allocator.alloc(sizeof(T) * rowkey_column_cnt_))) {
ret = OB_ALLOCATE_MEMORY_FAILED;
STORAGE_LOG(WARN, "Failed to allocate memory for cmopare func", K_(rowkey_column_cnt), K(ret));
} else {
cmp_funcs = reinterpret_cast<T*>(new (buf) T[rowkey_column_cnt_]);
for (int64_t i = 0; OB_SUCC(ret) && i < rowkey_column_cnt_; i++) {
if (OB_FAIL(cmp_funcs[i].init_compare_func(column_type_array_[i]))) {
STORAGE_LOG(WARN, "Failed to init compare func", K(i), K(ret));
} else if (OB_FAIL(cmp_funcs_.push_back(&cmp_funcs[i]))) {
STORAGE_LOG(WARN, "Failed to push back compare func", K(i), K(ret));
}
}
}
if (OB_SUCC(ret) && exist_collation_free_) {
collation_free_cmp_funcs_.set_allocator(&allocator);
collation_free_cmp_funcs_.set_capacity(rowkey_column_cnt_);
if (OB_ISNULL(buf = allocator.alloc(sizeof(T) * rowkey_column_cnt_))) {
ret = OB_ALLOCATE_MEMORY_FAILED;
STORAGE_LOG(WARN, "Failed to allocate memory for cmopare func", K_(rowkey_column_cnt), K(ret));
} else {
cmp_funcs = reinterpret_cast<T*>(new (buf) T[rowkey_column_cnt_]);
for (int64_t i = 0; OB_SUCC(ret) && i < rowkey_column_cnt_; i++) {
if (column_type_array_[i].is_collation_free_compatible()) {
if (OB_FAIL(cmp_funcs[i].init_compare_func_collation_free(column_type_array_[i]))) {
STORAGE_LOG(WARN, "Failed to init compare func", K(i), K(ret));
}
} else if (OB_FAIL(cmp_funcs[i].init_compare_func(column_type_array_[i]))) {
STORAGE_LOG(WARN, "Failed to init compare func", K(i), K(ret));
}
if (OB_SUCC(ret) && OB_FAIL(collation_free_cmp_funcs_.push_back(&cmp_funcs[i]))) {
STORAGE_LOG(WARN, "Failed to push back compare func", K(i), K(ret));
}
}
}
}
}
return ret;
}
int ObSSTableRowkeyHelper::init(const ObIArray<MacroBlockId>& macro_ids, const ObSSTableMeta& sstable_meta,
const bool need_build_collation_free, ObSSTable* sstable, ObIAllocator& allocator)
{
int ret = OB_SUCCESS;
reset();
if (OB_UNLIKELY(!sstable_meta.is_valid()) || OB_ISNULL(sstable)) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to init sstable rowkey helper", K(sstable_meta), KP(sstable), K(ret));
} else if (macro_ids.count() > 0) {
sstable_ = sstable;
ObWorker::CompatMode mode;
if (OB_FAIL(ObCompatModeGetter::get_tenant_mode(extract_tenant_id(sstable_meta.index_id_), mode))) {
STORAGE_LOG(WARN, "Failed to get compat mode", K(sstable_meta), K(ret));
// rewrite ret for caller deal with
ret = OB_TENANT_NOT_EXIST;
} else {
is_oracle_mode_ = (mode == ObWorker::CompatMode::ORACLE) && !is_sys_table(sstable_meta.index_id_);
use_cmp_nullsafe_ = ObTableSchema::is_index_table(static_cast<ObTableType>(sstable_meta.table_type_)) ||
TPKM_NEW_NO_PK == sstable_meta.table_mode_.pk_mode_;
if (OB_FAIL(build_macro_endkeys(
macro_ids, allocator, sstable_meta.rowkey_column_count_, need_build_collation_free))) {
STORAGE_LOG(WARN, "Failed to build macro endkeys", K(ret));
} else if (OB_FAIL(build_rowkey_cmp_funcs(allocator))) {
STORAGE_LOG(WARN, "Failed to build endkey cmp funcs", K(ret));
} else {
is_inited_ = true;
}
}
}
return ret;
}
int ObSSTableRowkeyHelper::build_rowkey_cmp_funcs(ObIAllocator& allocator)
{
int ret = OB_SUCCESS;
if (OB_ISNULL(column_type_array_) || rowkey_column_cnt_ <= 0) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN,
"Unexpected null column type array or rowkey column cnt",
KP_(column_type_array),
K_(rowkey_column_cnt),
K(ret));
} else if (is_oracle_mode_ && use_cmp_nullsafe_) {
ret = make_rowkey_cmp_funcs<ObRowkeyObjComparerNullsafeOracle>(allocator);
} else if (is_oracle_mode_) {
ret = make_rowkey_cmp_funcs<ObRowkeyObjComparerOracle>(allocator);
} else if (use_cmp_nullsafe_) {
ret = make_rowkey_cmp_funcs<ObRowkeyObjComparerNullsafeMysql>(allocator);
} else {
ret = make_rowkey_cmp_funcs<ObRowkeyObjComparer>(allocator);
}
return ret;
}
int ObSSTableRowkeyHelper::locate_block_idx_(const ObExtStoreRowkey& ext_rowkey, const int64_t cmp_rowkey_col_cnt,
const bool use_lower_bound, const int64_t last_block_idx, int64_t& block_idx)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(cmp_rowkey_col_cnt > ext_rowkey.get_store_rowkey().get_obj_cnt())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument to locate block index", K(ext_rowkey), K(cmp_rowkey_col_cnt), K(ret));
} else {
RowkeyArray* rowkey_array = NULL;
const ObStoreRowkey* cmp_rowkey = NULL;
RowkeyCmpFuncArray* cmp_funcs = NULL;
block_idx = -1;
if (!exist_collation_free_) {
cmp_rowkey = &(ext_rowkey.get_store_rowkey());
rowkey_array = &endkeys_;
cmp_funcs = &cmp_funcs_;
} else {
bool use_collation_free = false;
if (OB_FAIL(ext_rowkey.check_use_collation_free(!exist_collation_free_, use_collation_free))) {
STORAGE_LOG(WARN, "Fail to check use collation free, ", K(ret), K(ext_rowkey));
} else if (use_collation_free && collation_free_cmp_funcs_.count() > 0) {
cmp_rowkey = &(ext_rowkey.get_collation_free_store_rowkey());
rowkey_array = &collation_free_endkeys_;
cmp_funcs = &collation_free_cmp_funcs_;
} else {
cmp_rowkey = &(ext_rowkey.get_store_rowkey());
rowkey_array = &endkeys_;
cmp_funcs = &cmp_funcs_;
use_collation_free = false;
}
}
if (OB_SUCC(ret)) {
if (cmp_rowkey->get_obj_cnt() == rowkey_column_cnt_ && last_block_idx >= 0 &&
last_block_idx < rowkey_array->count()) {
// the rowkey may be in the same macro block, so check last macro block first
if (compare_nullsafe(rowkey_array->at(last_block_idx), *cmp_rowkey, *cmp_funcs) >= 0) {
if (0 == last_block_idx ||
compare_nullsafe(rowkey_array->at(last_block_idx - 1), *cmp_rowkey, *cmp_funcs) < 0) {
block_idx = last_block_idx;
}
}
}
if (-1 == block_idx) { // binary search
RowkeyComparor comparor(*cmp_funcs, cmp_rowkey_col_cnt < rowkey_column_cnt_);
ObStoreRowkey refine_cmp_rowkey((const_cast<ObStoreRowkey*>(cmp_rowkey))->get_obj_ptr(), cmp_rowkey_col_cnt);
RowkeyArray::iterator begin = rowkey_array->begin();
RowkeyArray::iterator end = rowkey_array->end();
RowkeyArray::iterator iter;
if (use_lower_bound) {
iter = std::lower_bound(begin, end, &refine_cmp_rowkey, comparor);
} else {
iter = std::upper_bound(begin, end, &refine_cmp_rowkey, comparor);
}
if (iter < end) {
block_idx = iter - begin;
}
}
}
}
return ret;
}
int ObSSTableRowkeyHelper::locate_block_idx_index(
const ObExtStoreRowkey& ext_rowkey, const int64_t last_block_idx, int64_t& block_idx)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!is_inited_)) {
ret = OB_NOT_INIT;
STORAGE_LOG(WARN, "ObSSTableRowkeyHelper is not inited", K(ret));
} else if (OB_UNLIKELY(!ext_rowkey.is_range_cutoffed())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "ExtRowkey is not range cutted", K(ext_rowkey), K(ret));
} else if (OB_UNLIKELY(ext_rowkey.get_range_cut_pos() == 0)) {
block_idx = ext_rowkey.is_range_check_min() ? 0 : -1;
} else {
ret = locate_block_idx_(
ext_rowkey, ext_rowkey.get_range_cut_pos(), ext_rowkey.is_range_check_min(), last_block_idx, block_idx);
}
return ret;
}
int ObSSTableRowkeyHelper::locate_block_idx_table(
const ObExtStoreRowkey& ext_rowkey, const int64_t last_block_idx, int64_t& block_idx)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!is_inited_)) {
ret = OB_NOT_INIT;
STORAGE_LOG(WARN, "ObSSTableRowkeyHelper is not inited", K(ret));
} else if (OB_UNLIKELY(!ext_rowkey.is_range_cutoffed())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "ExtRowkey is not range cutted", K(ext_rowkey), K(ret));
} else if (OB_UNLIKELY(ext_rowkey.get_range_cut_pos() == 0)) {
block_idx = ext_rowkey.is_range_check_min() ? 0 : -1;
} else if (OB_UNLIKELY(ext_rowkey.get_first_null_pos() == 0)) {
block_idx = is_oracle_mode_ ? -1 : 0;
} else {
int64_t cmp_rowkey_col_cnt = ext_rowkey.get_range_cut_pos();
bool use_lower_bound = ext_rowkey.is_range_check_min();
if (ext_rowkey.get_first_null_pos() > 0 && ext_rowkey.get_first_null_pos() < cmp_rowkey_col_cnt) {
cmp_rowkey_col_cnt = ext_rowkey.get_first_null_pos();
use_lower_bound = !is_oracle_mode_;
}
ret = locate_block_idx_(ext_rowkey, cmp_rowkey_col_cnt, use_lower_bound, last_block_idx, block_idx);
}
return ret;
}
} // end namespace storage
} // end namespace oceanbase
| 38.710438
| 119
| 0.670175
|
wangcy6
|
b6b9685cab98a2ba3d1d8883d8142265d8a14a78
| 1,601
|
hpp
|
C++
|
libbio/include/bio/crypto/crypto_Sha256.hpp
|
biosphere-switch/libbio
|
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
|
[
"MIT"
] | null | null | null |
libbio/include/bio/crypto/crypto_Sha256.hpp
|
biosphere-switch/libbio
|
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
|
[
"MIT"
] | null | null | null |
libbio/include/bio/crypto/crypto_Sha256.hpp
|
biosphere-switch/libbio
|
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
|
[
"MIT"
] | null | null | null |
#pragma once
#include <bio/mem/mem_Memory.hpp>
namespace bio::crypto {
// Grabbed from libnx, hardware-accelerated impl
class Sha256Context {
public:
static constexpr u64 HashSize = 0x20;
static constexpr u64 HashSize32 = HashSize / sizeof(u32);
static constexpr u64 BlockSize = 0x40;
static constexpr u32 InitialHash[HashSize32] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
};
private:
u32 intermediate_hash[HashSize32];
u8 block[BlockSize];
u64 bits_consumed;
u64 num_buffered;
bool finalized;
void EnsureFinalized();
void ProcessBlocks(const u8 *buf, u64 num_blocks);
public:
Sha256Context() : intermediate_hash(), block(), bits_consumed(0), num_buffered(0), finalized(false) {
mem::Copy(this->intermediate_hash, InitialHash, HashSize);
}
void Update(const void *buf, u64 size);
inline void GetHash(void *out_dest) {
this->EnsureFinalized();
auto dest32 = reinterpret_cast<u32*>(out_dest);
for(u32 i = 0; i < HashSize32; i++) {
dest32[i] = __builtin_bswap32(this->intermediate_hash[i]);
}
}
};
inline void CalculateSha256(const void *buf, u64 size, void *out) {
Sha256Context ctx;
ctx.Update(buf, size);
ctx.GetHash(out);
}
}
| 29.648148
| 113
| 0.564022
|
biosphere-switch
|
b6baf75f42c6a0f942ec07d8a30159d3dc2b9ad6
| 935
|
hpp
|
C++
|
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
|
yashbhavsar007/Delta-Blockchain
|
602dd5335d2cd51303e953e4c233c8f099da0b07
|
[
"MIT"
] | null | null | null |
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
|
yashbhavsar007/Delta-Blockchain
|
602dd5335d2cd51303e953e4c233c8f099da0b07
|
[
"MIT"
] | null | null | null |
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
|
yashbhavsar007/Delta-Blockchain
|
602dd5335d2cd51303e953e4c233c8f099da0b07
|
[
"MIT"
] | null | null | null |
#pragma once
#include <delta/plugins/json_rpc/utility.hpp>
#include <delta/protocol/types.hpp>
#include <fc/optional.hpp>
#include <fc/variant.hpp>
#include <fc/vector.hpp>
namespace delta { namespace plugins { namespace account_by_key {
namespace detail
{
class account_by_key_api_impl;
}
struct get_key_references_args
{
std::vector< delta::protocol::public_key_type > keys;
};
struct get_key_references_return
{
std::vector< std::vector< delta::protocol::account_name_type > > accounts;
};
class account_by_key_api
{
public:
account_by_key_api();
~account_by_key_api();
DECLARE_API( (get_key_references) )
private:
std::unique_ptr< detail::account_by_key_api_impl > my;
};
} } } // delta::plugins::account_by_key
FC_REFLECT( delta::plugins::account_by_key::get_key_references_args,
(keys) )
FC_REFLECT( delta::plugins::account_by_key::get_key_references_return,
(accounts) )
| 20.326087
| 77
| 0.735829
|
yashbhavsar007
|
b6bc263a733e9f6bbb8635aa9d1df83ca167e057
| 2,191
|
cpp
|
C++
|
libs/RFType/TypeDatabase.cpp
|
max-delta/retrofit-public
|
5447fd6399fd74ffbb75494c103940751000db12
|
[
"X11"
] | 3
|
2019-10-27T22:32:44.000Z
|
2020-05-21T04:00:46.000Z
|
libs/RFType/TypeDatabase.cpp
|
max-delta/retrofit-public
|
5447fd6399fd74ffbb75494c103940751000db12
|
[
"X11"
] | null | null | null |
libs/RFType/TypeDatabase.cpp
|
max-delta/retrofit-public
|
5447fd6399fd74ffbb75494c103940751000db12
|
[
"X11"
] | null | null | null |
#include "stdafx.h"
#include "TypeDatabase.h"
#include "core/macros.h"
#include "core/meta/LazyInitSingleton.h"
#include "core_rftype/Identifier.h"
#include "rftl/memory"
namespace RF::rftype {
///////////////////////////////////////////////////////////////////////////////
bool TypeDatabase::RegisterNewClassByName( char const* name, reflect::ClassInfo const& classInfo )
{
RF_ASSERT( name != nullptr );
if( IsValidClassName( name ) == false )
{
RF_DBGFAIL();
return false;
}
size_t nameLen = strnlen( name, 1024 );
math::HashVal64 const hash = math::StableHashBytes( name, nameLen );
bool const registerSuccess = RegisterNewClassByHash( hash, name, classInfo );
return registerSuccess;
}
reflect::ClassInfo const* TypeDatabase::GetClassInfoByName( char const* name ) const
{
size_t nameLen = strnlen( name, 1024 );
math::HashVal64 const hash = math::StableHashBytes( name, nameLen );
return GetClassInfoByHash( hash );
}
reflect::ClassInfo const* TypeDatabase::GetClassInfoByHash( math::HashVal64 const& hash ) const
{
ClassInfoByHash::const_iterator const iter = mClassInfoByHash.find( hash );
if( iter == mClassInfoByHash.end() )
{
return nullptr;
}
RF_ASSERT( iter->second.mClassInfo != nullptr );
return iter->second.mClassInfo;
}
TypeDatabase& TypeDatabase::GetGlobalMutableInstance()
{
return GetOrCreateGlobalInstance();
}
TypeDatabase const& TypeDatabase::GetGlobalInstance()
{
return GetOrCreateGlobalInstance();
}
///////////////////////////////////////////////////////////////////////////////
bool TypeDatabase::RegisterNewClassByHash( math::HashVal64 const& hash, char const* name, reflect::ClassInfo const& classInfo )
{
if( mClassInfoByHash.count( hash ) != 0 )
{
return false;
}
StoredClassInfo& newStorage = mClassInfoByHash[hash];
newStorage.mName = name;
newStorage.mClassInfo = &classInfo;
return true;
}
bool TypeDatabase::IsValidClassName( char const* name )
{
return IsValidIdentifier( name );
}
TypeDatabase& TypeDatabase::GetOrCreateGlobalInstance()
{
return GetOrInitFunctionStaticScopedSingleton<TypeDatabase>();
}
///////////////////////////////////////////////////////////////////////////////
}
| 22.357143
| 127
| 0.664537
|
max-delta
|
b6bd8fd53c78a5c0df38d175650861eff65c98dc
| 608
|
hpp
|
C++
|
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENCL_CONTEXT_ERROR_CALLBACK_TYPE_HPP_INCLUDED
#define SGE_OPENCL_CONTEXT_ERROR_CALLBACK_TYPE_HPP_INCLUDED
#include <sge/opencl/binary_error_data.hpp>
#include <sge/opencl/error_information_string.hpp>
namespace sge::opencl::context
{
using error_callback_type =
void(sge::opencl::error_information_string const &, sge::opencl::binary_error_data const &);
}
#endif
| 28.952381
| 96
| 0.771382
|
cpreh
|
b6bfb73351dc46f7693a02b53a3be53b5f550e1b
| 745
|
hpp
|
C++
|
app/src/main/cpp/common/src/common/Mesh.hpp
|
pehg/Break_it_all
|
dab56d82dd4541a710f16b1e6f61ee214059a1a9
|
[
"MIT"
] | null | null | null |
app/src/main/cpp/common/src/common/Mesh.hpp
|
pehg/Break_it_all
|
dab56d82dd4541a710f16b1e6f61ee214059a1a9
|
[
"MIT"
] | null | null | null |
app/src/main/cpp/common/src/common/Mesh.hpp
|
pehg/Break_it_all
|
dab56d82dd4541a710f16b1e6f61ee214059a1a9
|
[
"MIT"
] | null | null | null |
//
// Created by simonppg on 4/22/19.
//
#ifndef BREAK_IT_ALL_MESH_HPP
#define BREAK_IT_ALL_MESH_HPP
#include "Camera.hpp"
using glm::vec3;
#define NUM_ARRAY_ELEMENTS(a) (sizeof(a) / sizeof(*a))
#define INDEX_BUFFER_SIZE(numIndices) ((GLsizeiptr)((numIndices) * (sizeof(GLushort))))
#define VERTEX_BUFFER_SIZE(numIndices) ((GLsizeiptr)((numIndices) * (sizeof(float) * 6)))
#define ONE 1
#define TWO 2
class Mesh {
public:
Mesh(float *pDouble, int i);
Mesh(float *vertex, int v_size, short *indices, int i_size);
int type;
float *vertex;
short *indices;
int numVertices;
int numIndices;
unsigned int vbo; // vertex buffer object
unsigned int iab; // index array buffer
};
#endif //BREAK_IT_ALL_MESH_HPP
| 22.575758
| 89
| 0.702013
|
pehg
|
b6c58b4a719ddc165a4c06e1369168ee4029fd34
| 1,138
|
cpp
|
C++
|
src/db/db_impl.cpp
|
rickard1117/PidanDB
|
6955f6913cb404a0f09a5e44c07f36b0729c0a78
|
[
"MIT"
] | 7
|
2020-08-01T04:09:15.000Z
|
2021-08-08T17:26:19.000Z
|
src/db/db_impl.cpp
|
rickard1117/PidanDB
|
6955f6913cb404a0f09a5e44c07f36b0729c0a78
|
[
"MIT"
] | null | null | null |
src/db/db_impl.cpp
|
rickard1117/PidanDB
|
6955f6913cb404a0f09a5e44c07f36b0729c0a78
|
[
"MIT"
] | 2
|
2020-09-16T02:29:52.000Z
|
2020-09-28T10:51:38.000Z
|
#include "db/db_impl.h"
namespace pidan {
Status DBImpl::Put(const Slice &key, const Slice &value) {
Transaction *txn = txn_manager_.BeginWriteTransaction();
DataHeader *dh = new DataHeader(txn);
DataHeader *old_dh = nullptr;
auto result = index_.InsertUnique(key, dh, &old_dh);
if (!result) {
delete dh;
if (!old_dh->Put(txn, value)) {
txn_manager_.Abort(txn);
return Status::FAIL_BY_ACTIVE_TXN;
}
} else {
result = dh->Put(txn, value);
assert(result);
}
txn_manager_.Commit(txn);
return Status::SUCCESS;
}
Status DBImpl::Get(const Slice &key, std::string *val) {
Transaction txn = txn_manager_.BeginReadTransaction();
DataHeader *dh = nullptr;
if (!index_.Lookup(key, &dh)) {
txn_manager_.Abort(&txn);
return Status::KEY_NOT_EXIST;
}
bool not_found;
if (!dh->Select(&txn, val, ¬_found)) {
return Status::FAIL_BY_ACTIVE_TXN;
}
if (not_found) {
return Status::KEY_NOT_EXIST;
}
return Status::SUCCESS;
}
Status PidanDB::Open(const std::string &name, PidanDB **dbptr) {
*dbptr = new DBImpl();
return Status::SUCCESS;
}
} // namespace pidan
| 23.708333
| 64
| 0.665202
|
rickard1117
|
b6c7c92e3bfa79f0066631365f7853bef96538d9
| 670
|
cpp
|
C++
|
binary tree/flattenTreeToLinkedList.cpp
|
Gooner1886/DSA-101
|
44092e10ad39bebbf7da93e897927106d5a45ae7
|
[
"MIT"
] | 20
|
2022-01-04T19:36:14.000Z
|
2022-03-21T15:35:09.000Z
|
binary tree/flattenTreeToLinkedList.cpp
|
Gooner1886/DSA-101
|
44092e10ad39bebbf7da93e897927106d5a45ae7
|
[
"MIT"
] | null | null | null |
binary tree/flattenTreeToLinkedList.cpp
|
Gooner1886/DSA-101
|
44092e10ad39bebbf7da93e897927106d5a45ae7
|
[
"MIT"
] | null | null | null |
// Leetcode - 114 - Flatten Binary Tree to Linked List
void solve(TreeNode *root, vector<int> &preorder)
{
root->left = NULL;
root->right = NULL;
for (int i = 1; i < preorder.size(); i++)
{
root->right = new TreeNode(preorder[i]);
root = root->right;
}
}
void preorderTraversal(TreeNode *root, vector<int> &preorder)
{
if (!root)
return;
preorder.push_back(root->val);
preorderTraversal(root->left, preorder);
preorderTraversal(root->right, preorder);
}
void flatten(TreeNode *root)
{
if (!root)
return;
vector<int> preorder;
preorderTraversal(root, preorder);
solve(root, preorder);
}
| 23.928571
| 61
| 0.623881
|
Gooner1886
|
b6c9ac73c37b5204639c27d37f0655122c11a714
| 8,505
|
hpp
|
C++
|
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
|
FallenShard/Crisp
|
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
|
[
"MIT"
] | 6
|
2017-09-14T03:26:49.000Z
|
2021-09-18T05:40:59.000Z
|
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
|
FallenShard/Crisp
|
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
|
[
"MIT"
] | null | null | null |
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
|
FallenShard/Crisp
|
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
|
[
"MIT"
] | null | null | null |
#pragma once
#include <memory>
#include <array>
#include <vector>
#include <CrispCore/Math/BoundingBox.hpp>
#include "Spectrums/Spectrum.hpp"
namespace crisp
{
struct SurfacePoint
{
SurfacePoint() {}
SurfacePoint(const glm::vec3& p, const glm::vec3& n, float a)
: p(p)
, n(n)
, area(a)
, rayEpsilon(Ray3::Epsilon)
{
}
glm::vec3 p;
glm::vec3 n;
float area;
float rayEpsilon;
};
struct PoissonCheck
{
PoissonCheck(float maxDist, const glm::vec3& point)
: maxDist2(maxDist * maxDist)
, failed(false)
, p(point)
{
}
bool operator()(const SurfacePoint& point)
{
glm::vec3 diff = point.p - p;
if (glm::dot(diff, diff) < maxDist2)
{
failed = true;
return false;
}
return true;
}
float maxDist2;
bool failed;
glm::vec3 p;
};
struct IrradiancePoint
{
IrradiancePoint() {}
IrradiancePoint(const SurfacePoint& surfPt, const Spectrum& spectrum)
: p(surfPt.p)
, n(surfPt.n)
, e(spectrum)
, area(surfPt.area)
, rayEpsilon(surfPt.rayEpsilon)
{
}
glm::vec3 p;
glm::vec3 n;
Spectrum e;
float area;
float rayEpsilon;
};
struct IrradianceNode
{
glm::vec3 p;
bool isLeaf;
Spectrum e;
float sumArea;
std::array<std::unique_ptr<IrradianceNode>, 8> children;
std::array<IrradiancePoint*, 8> irrPts;
IrradianceNode()
: isLeaf(true)
, sumArea(0.0f)
{
for (int i = 0; i < 8; i++)
{
irrPts[i] = nullptr;
children[i] = nullptr;
}
}
inline BoundingBox3 getChildBound(int child, const BoundingBox3& bounds, const glm::vec3& mid)
{
BoundingBox3 bound;
bound.min.x = (child & 4) ? mid.x : bounds.min.x;
bound.min.y = (child & 2) ? mid.y : bounds.min.y;
bound.min.z = (child & 1) ? mid.z : bounds.min.z;
bound.max.x = (child & 4) ? bounds.max.x : mid.x;
bound.max.y = (child & 2) ? bounds.max.y : mid.y;
bound.max.z = (child & 1) ? bounds.max.z : mid.z;
return bound;
}
void insert(const BoundingBox3& nodeBounds, IrradiancePoint* point)
{
glm::vec3 mid = nodeBounds.getCenter();
if (isLeaf)
{
for (int i = 0; i < 8; i++)
{
if (!irrPts[i])
{
irrPts[i] = point;
return;
}
}
isLeaf = false;
IrradiancePoint* localPts[8];
for (int i = 0; i < 8; i++)
{
localPts[i] = irrPts[i];
children[i] = nullptr;
}
for (int i = 0; i < 8; i++)
{
IrradiancePoint* currPt = localPts[i];
int child =
(currPt->p.x > mid.x ? 4 : 0) +
(currPt->p.y > mid.y ? 2 : 0) +
(currPt->p.z > mid.z ? 1 : 0);
if (children[child] == nullptr)
children[child] = std::make_unique<IrradianceNode>();
BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid);
children[child]->insert(childBounds, currPt);
}
int child =
(point->p.x > mid.x ? 4 : 0) +
(point->p.y > mid.y ? 2 : 0) +
(point->p.z > mid.z ? 1 : 0);
if (children[child] == nullptr)
children[child] = std::make_unique<IrradianceNode>();
BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid);
children[child]->insert(childBounds, point);
}
}
Spectrum getLeafIrradiance()
{
Spectrum sum(0.0f);
if (isLeaf)
{
for (int i = 0; i < irrPts.size(); i++)
{
if (!irrPts[i])
break;
sum += irrPts[i]->e;
}
}
else
{
for (int i = 0; i < children.size(); i++)
{
if (!children[i])
continue;
sum += children[i]->getLeafIrradiance();
}
}
return sum;
}
Spectrum getTotalIrradiance()
{
Spectrum sum(0.0f);
if (isLeaf)
{
for (int i = 0; i < irrPts.size(); i++)
{
if (!irrPts[i])
break;
sum += irrPts[i]->e;
}
}
else
{
for (int i = 0; i < children.size(); i++)
{
if (!children[i])
continue;
sum += children[i]->getLeafIrradiance();
}
sum += e;
}
return sum;
}
void initHierarchy()
{
if (isLeaf)
{
float weightSum = 0.0f;
size_t i;
for (i = 0; i < 8; i++)
{
if (!irrPts[i])
break;
float weight = irrPts[i]->e.getLuminance();
e += irrPts[i]->e;
p += weight * irrPts[i]->p;
weightSum += weight;
sumArea += irrPts[i]->area;
}
if (weightSum > 0.0f)
p /= weightSum;
if (i > 0)
e /= static_cast<float>(i);
}
else
{
float weightSum = 0.0f;
size_t numChildren = 0;
for (uint32_t i = 0; i < 8; i++)
{
if (!children[i])
continue;
++numChildren;
children[i]->initHierarchy();
float weight = children[i]->e.getLuminance();
e += children[i]->e;
p += weight * children[i]->p;
weightSum += weight;
sumArea += children[i]->sumArea;
}
if (weightSum > 0.0f)
p /= weightSum;
if (numChildren > 0)
e /= static_cast<float>(numChildren);
}
}
template <typename Func>
Spectrum Mo(const BoundingBox3& nodeBounds, const glm::vec3& pt, Func& func, float maxError)
{
glm::vec3 diff = pt - p;
float sqrDist = glm::dot(diff, diff);
float distanceWeight = sumArea / sqrDist;
if (distanceWeight < maxError && !nodeBounds.contains(pt))
return func(sqrDist) * e * sumArea;
Spectrum mo = 0.0f;
if (isLeaf)
{
for (int i = 0; i < 8; i++)
{
if (!irrPts[i])
break;
glm::vec3 diffC = irrPts[i]->p - pt;
float cSqrDist = glm::dot(diffC, diffC);
mo += func(cSqrDist) * irrPts[i]->e * irrPts[i]->area;
}
}
else
{
glm::vec3 mid = nodeBounds.getCenter();
for (int child = 0; child < 8; child++)
{
if (!children[child])
continue;
BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid);
mo += children[child]->Mo(childBounds, pt, func, maxError);
}
}
return mo;
}
};
struct IrradianceTree
{
std::unique_ptr<IrradianceNode> root;
BoundingBox3 boundingBox;
};
}
| 28.444816
| 102
| 0.388595
|
FallenShard
|
b6d63ff87ed03714a1fa7cf95cc74d0f65869208
| 3,577
|
cpp
|
C++
|
android-30/android/widget/SimpleAdapter.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-30/android/widget/SimpleAdapter.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/android/widget/SimpleAdapter.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../JIntArray.hpp"
#include "../../JArray.hpp"
#include "../content/Context.hpp"
#include "../content/res/Resources_Theme.hpp"
#include "../view/View.hpp"
#include "../view/ViewGroup.hpp"
#include "./Filter.hpp"
#include "./ImageView.hpp"
#include "./TextView.hpp"
#include "../../JObject.hpp"
#include "../../JString.hpp"
#include "./SimpleAdapter.hpp"
namespace android::widget
{
// Fields
// QJniObject forward
SimpleAdapter::SimpleAdapter(QJniObject obj) : android::widget::BaseAdapter(obj) {}
// Constructors
SimpleAdapter::SimpleAdapter(android::content::Context arg0, JObject arg1, jint arg2, JArray arg3, JIntArray arg4)
: android::widget::BaseAdapter(
"android.widget.SimpleAdapter",
"(Landroid/content/Context;Ljava/util/List;I[Ljava/lang/String;[I)V",
arg0.object(),
arg1.object(),
arg2,
arg3.object<jarray>(),
arg4.object<jintArray>()
) {}
// Methods
jint SimpleAdapter::getCount() const
{
return callMethod<jint>(
"getCount",
"()I"
);
}
android::view::View SimpleAdapter::getDropDownView(jint arg0, android::view::View arg1, android::view::ViewGroup arg2) const
{
return callObjectMethod(
"getDropDownView",
"(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;",
arg0,
arg1.object(),
arg2.object()
);
}
android::content::res::Resources_Theme SimpleAdapter::getDropDownViewTheme() const
{
return callObjectMethod(
"getDropDownViewTheme",
"()Landroid/content/res/Resources$Theme;"
);
}
android::widget::Filter SimpleAdapter::getFilter() const
{
return callObjectMethod(
"getFilter",
"()Landroid/widget/Filter;"
);
}
JObject SimpleAdapter::getItem(jint arg0) const
{
return callObjectMethod(
"getItem",
"(I)Ljava/lang/Object;",
arg0
);
}
jlong SimpleAdapter::getItemId(jint arg0) const
{
return callMethod<jlong>(
"getItemId",
"(I)J",
arg0
);
}
android::view::View SimpleAdapter::getView(jint arg0, android::view::View arg1, android::view::ViewGroup arg2) const
{
return callObjectMethod(
"getView",
"(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;",
arg0,
arg1.object(),
arg2.object()
);
}
JObject SimpleAdapter::getViewBinder() const
{
return callObjectMethod(
"getViewBinder",
"()Landroid/widget/SimpleAdapter$ViewBinder;"
);
}
void SimpleAdapter::setDropDownViewResource(jint arg0) const
{
callMethod<void>(
"setDropDownViewResource",
"(I)V",
arg0
);
}
void SimpleAdapter::setDropDownViewTheme(android::content::res::Resources_Theme arg0) const
{
callMethod<void>(
"setDropDownViewTheme",
"(Landroid/content/res/Resources$Theme;)V",
arg0.object()
);
}
void SimpleAdapter::setViewBinder(JObject arg0) const
{
callMethod<void>(
"setViewBinder",
"(Landroid/widget/SimpleAdapter$ViewBinder;)V",
arg0.object()
);
}
void SimpleAdapter::setViewImage(android::widget::ImageView arg0, jint arg1) const
{
callMethod<void>(
"setViewImage",
"(Landroid/widget/ImageView;I)V",
arg0.object(),
arg1
);
}
void SimpleAdapter::setViewImage(android::widget::ImageView arg0, JString arg1) const
{
callMethod<void>(
"setViewImage",
"(Landroid/widget/ImageView;Ljava/lang/String;)V",
arg0.object(),
arg1.object<jstring>()
);
}
void SimpleAdapter::setViewText(android::widget::TextView arg0, JString arg1) const
{
callMethod<void>(
"setViewText",
"(Landroid/widget/TextView;Ljava/lang/String;)V",
arg0.object(),
arg1.object<jstring>()
);
}
} // namespace android::widget
| 23.688742
| 125
| 0.689405
|
YJBeetle
|
b6d713da27744740cbd2a04f40d244a6afd101c4
| 1,887
|
cpp
|
C++
|
src/examples/logisticregression.cpp
|
jaymwong/CppNumericalSolvers
|
2a0f98e7c54c35325641e05c035e43cafd570808
|
[
"MIT"
] | 2
|
2016-03-17T21:13:23.000Z
|
2021-01-10T00:53:08.000Z
|
src/examples/logisticregression.cpp
|
jaymwong/CppNumericalSolvers
|
2a0f98e7c54c35325641e05c035e43cafd570808
|
[
"MIT"
] | null | null | null |
src/examples/logisticregression.cpp
|
jaymwong/CppNumericalSolvers
|
2a0f98e7c54c35325641e05c035e43cafd570808
|
[
"MIT"
] | 1
|
2021-01-07T16:20:12.000Z
|
2021-01-07T16:20:12.000Z
|
#include <iostream>
#include "../../include/cppoptlib/meta.h"
#include "../../include/cppoptlib/problem.h"
#include "../../include/cppoptlib/solver/bfgssolver.h"
// to use this library just use the namespace "cppoptlib"
namespace cppoptlib {
// we define a new problem for optimizing the rosenbrock function
// we use a templated-class rather than "auto"-lambda function for a clean architecture
template<typename T>
class LogisticRegression : public Problem<T> {
public:
using typename Problem<T>::TVector;
using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
const MatrixType X;
const TVector y;
const MatrixType XX;
LogisticRegression(const MatrixType &X_, const TVector y_) : X(X_), y(y_), XX(X_.transpose()*X_) {}
T value(const TVector &beta) {
return (1.0/(1.0 + exp(-(X*beta).array())) - y.array()).matrix().squaredNorm();
}
void gradient(const TVector &beta, TVector &grad) {
const TVector p = 1.0/(1.0 + exp(-(X*beta).array()));
grad = X.transpose()*(p-y);
}
};
}
int main(int argc, char const *argv[]) {
typedef double T;
typedef cppoptlib::LogisticRegression<T> LogReg;
typedef typename LogReg::TVector TVector;
typedef typename LogReg::MatrixType MatrixType;
srand((unsigned int) time(0));
// create true model
TVector true_beta = TVector::Random(4);
// create data
MatrixType X = MatrixType::Random(50, 4);
TVector y = 1.0/(1.0 + exp(-(X*true_beta).array()));
// perform linear regression
LogReg f(X, y);
TVector beta = TVector::Random(4);
std::cout << "start in " << beta.transpose() << std::endl;
cppoptlib::BfgsSolver<LogReg> solver;
solver.minimize(f, beta);
std::cout << "result " << beta.transpose() << std::endl;
std::cout << "true model " << true_beta.transpose() << std::endl;
return 0;
}
| 31.45
| 103
| 0.647589
|
jaymwong
|
b6d962121987bcab856a0318aa250dcd1a68fb2d
| 1,552
|
cpp
|
C++
|
src/lib/classification/poset_classification/extension.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-10-27T15:18:28.000Z
|
2022-02-09T11:13:07.000Z
|
src/lib/classification/poset_classification/extension.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 4
|
2019-12-09T11:49:11.000Z
|
2020-07-30T17:34:45.000Z
|
src/lib/classification/poset_classification/extension.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-06-10T20:05:30.000Z
|
2020-12-18T04:59:19.000Z
|
// extension.cpp
//
// Anton Betten
// Dec 19, 2011
#include "foundations/foundations.h"
#include "group_actions/group_actions.h"
#include "classification/classification.h"
using namespace std;
namespace orbiter {
namespace classification {
extension::extension()
{
pt = -1;
orbit_len = 0;
type = EXTENSION_TYPE_UNPROCESSED;
data = 0;
data1 = 0;
data2 = 0;
}
extension::~extension()
{
}
int extension::get_pt()
{
return pt;
}
void extension::set_pt(int pt)
{
extension::pt = pt;
}
int extension::get_type()
{
return type;
}
void extension::set_type(int type)
{
extension::type = type;
}
int extension::get_orbit_len()
{
return orbit_len;
}
void extension::set_orbit_len(int orbit_len)
{
extension::orbit_len = orbit_len;
}
int extension::get_data()
{
return data;
}
void extension::set_data(int data)
{
extension::data = data;
}
int extension::get_data1()
{
return data1;
}
void extension::set_data1(int data1)
{
extension::data1 = data1;
}
int extension::get_data2()
{
return data2;
}
void extension::set_data2(int data2)
{
extension::data2 = data2;
}
void print_extension_type(ostream &ost, int t)
{
if (t == EXTENSION_TYPE_UNPROCESSED) {
ost << " unprocessed";
}
else if (t == EXTENSION_TYPE_EXTENSION) {
ost << " extension";
}
else if (t == EXTENSION_TYPE_FUSION) {
ost << " fusion";
}
else if (t == EXTENSION_TYPE_PROCESSING) {
ost << " processing";
}
else if (t == EXTENSION_TYPE_NOT_CANONICAL) {
ost << " not canonical";
}
else {
ost << "type=" << t;
}
}
}}
| 13.37931
| 46
| 0.664948
|
abetten
|
b6e141796369094324824c07eaba15be4e416bc3
| 2,060
|
cpp
|
C++
|
libbirch/libbirch/Memo.cpp
|
vishalbelsare/Birch
|
ead17b181a058250e9f5896d64954232d19e43f0
|
[
"Apache-2.0"
] | 86
|
2017-10-29T15:46:41.000Z
|
2022-01-17T07:18:16.000Z
|
libbirch/libbirch/Memo.cpp
|
vishalbelsare/Birch
|
ead17b181a058250e9f5896d64954232d19e43f0
|
[
"Apache-2.0"
] | 13
|
2020-09-27T03:31:57.000Z
|
2021-05-27T00:39:14.000Z
|
libbirch/libbirch/Memo.cpp
|
vishalbelsare/Birch
|
ead17b181a058250e9f5896d64954232d19e43f0
|
[
"Apache-2.0"
] | 12
|
2018-08-21T12:57:18.000Z
|
2021-05-26T18:41:50.000Z
|
/**
*@file
*/
#include "libbirch/Memo.hpp"
#include "libbirch/external.hpp"
#include "libbirch/memory.hpp"
#include "libbirch/thread.hpp"
libbirch::Memo::Memo() :
keys(nullptr),
values(nullptr),
nentries(0),
noccupied(0) {
//
}
libbirch::Memo::~Memo() {
std::free(keys);
std::free(values);
}
libbirch::Any*& libbirch::Memo::get(Any* key) {
assert(key);
/* reserve a slot */
if (++noccupied > crowd()) {
rehash();
}
auto i = hash(key);
auto k = keys[i];
while (k && k != key) {
i = (i + 1) & (nentries - 1);
k = keys[i];
}
if (k) {
--noccupied; // unreserve the slot, wasn't needed
} else {
keys[i] = key;
values[i] = nullptr;
}
return values[i];
}
int libbirch::Memo::hash(Any* key) const {
assert(nentries > 0);
return static_cast<int>(reinterpret_cast<size_t>(key) >> 6ull)
& (nentries - 1);
}
int libbirch::Memo::crowd() const {
/* the table is considered crowded if more than three-quarters of its
* entries are occupied */
return (nentries >> 1) + (nentries >> 2);
}
void libbirch::Memo::rehash() {
/* save previous table */
auto nentries1 = nentries;
auto keys1 = keys;
auto values1 = values;
/* size of new table */
nentries = std::max(INITIAL_SIZE, 2*nentries1);
/* allocate the new table */
keys = (Any**)std::malloc(nentries*sizeof(Any*));
values = (Any**)std::malloc(nentries*sizeof(Any*));
std::memset(keys, 0, nentries*sizeof(Any*));
//std::memset(values, 0, nentries*sizeof(Any*));
// ^ nullptr keys are used to indicate empty slots, while individual values
// are set to nullptr on first access in get(), so need not be here */
/* copy entries from previous table */
for (int i = 0; i < nentries1; ++i) {
auto key = keys1[i];
if (key) {
auto j = hash(key);
while (keys[j]) {
j = (j + 1) & (nentries - 1);
}
keys[j] = key;
values[j] = values1[i];
}
}
/* deallocate previous table */
if (nentries1 > 0) {
std::free(keys1);
std::free(values1);
}
}
| 21.914894
| 77
| 0.586408
|
vishalbelsare
|
b6e3bd44284375e49a0bec3135ac98997769a048
| 4,187
|
cpp
|
C++
|
src/scene.cpp
|
sndels/naiverend
|
8d2b76104fa9ea4cbff2dc95aeabebb9d506856c
|
[
"MIT"
] | null | null | null |
src/scene.cpp
|
sndels/naiverend
|
8d2b76104fa9ea4cbff2dc95aeabebb9d506856c
|
[
"MIT"
] | null | null | null |
src/scene.cpp
|
sndels/naiverend
|
8d2b76104fa9ea4cbff2dc95aeabebb9d506856c
|
[
"MIT"
] | null | null | null |
#include "scene.hpp"
#include "gl_core_4_1.h"
#include <glm/glm.hpp>
#include <iostream>
#include <vector>
#include "input_handler.hpp"
#include "math_types.hpp"
#include "model_parser.hpp"
#include "imgui/imgui.h"
#include "imgui/examples/opengl3_example/imgui_impl_glfw_gl3.h"
using glm::vec3;
using glm::mat3;
using glm::mat4;
using std::cerr;
using std::cin;
using std::endl;
Scene::Scene(const float& xres, const float& yres) :
res2f_(xres, yres),
modelPos3f_(0.f, 0.f, 0.f),
modelScale3f_(1.f),
modelRotY1f_(PI_F),
lightPos3f_(5.f, 7.f, -5.f)
{
;
}
bool Scene::init()
{
if (!pg_.loadProgram()) return false;
parseOBJ("res/head/head.obj", model_);
GLenum error = glGetError();
if(error != GL_NO_ERROR) {
cerr << "Error initializing scene!" << endl;
cerr << "Error code: " << error << endl;
cin.get();
return false;
}
cam_.setProj(res2f_.x, res2f_.y, 90.f, 0.1f, 10.f);
cam_.setView(vec3(0.f, 0.f, -4.f), vec3(0.f, 0.f, 0.f));
return true;
}
void Scene::update()
{
InputHandler& ih = InputHandler::getIH();
// Cam control
const MouseState ms = ih.getMouseState();
if (ms.state == LEFT_DOWN) cam_.rotateTrackball(ms.lastPos2f, ms.curPos2f);
cam_.movePos(vec3(0.f, 0.f, ms.scrollY / 4.f));
// Model control
const KeyboardState ks = ih.getKeyboardState();
vec3 modelOffset(0.f, 0.f, 0.f);
if (ks.shift) {
if (ks.up) modelOffset.z += 1.f;
if (ks.down) modelOffset.z -= 1.f;
} else {
if (ks.up) modelOffset.y += 1.f;
if (ks.down) modelOffset.y -= 1.f;
}
if (ks.left) modelOffset.x -= 1.f;
if (ks.right) modelOffset.x += 1.f;
if (length(modelOffset) > 0.f) modelPos3f_ += 0.05f * normalize(modelOffset);
ih.reset();
}
void Scene::render()
{
// Simple imgui-window
// mousepos could be passed to imgui before event-handling and check this
// to not pass mouse-events to program if hovering
ImGui::GetIO().MouseDrawCursor = ImGui::IsMouseHoveringAnyWindow();
{
ImGui::SliderFloat("x", &modelPos3f_.x, -2.f, 2.f);
ImGui::SliderFloat("y", &modelPos3f_.y, -2.f, 2.f);
ImGui::SliderFloat("z", &modelPos3f_.z, -2.f, 2.f);
ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
pg_.bind();
mat4 translate( 1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
modelPos3f_.x, modelPos3f_.y, modelPos3f_.z, 1.f );
mat4 scale(modelScale3f_.x, 0.f, 0.f, 0.f,
0.f, modelScale3f_.y, 0.f, 0.f,
0.f, 0.f, modelScale3f_.z, 0.f,
0.f, 0.f, 0.f, 1.f );
mat4 rotY(cos(modelRotY1f_), 0.f, -sin(modelRotY1f_), 0.f,
0.f, 1.f, 0.f, 0.f,
sin(modelRotY1f_), 0.f, cos(modelRotY1f_), 0.f,
0.f, 0.f, 0.f, 1.f );
mat4 modelToWorld = translate * rotY * scale;
mat4 viewMat = cam_.getViewMat();
mat4 projMat = cam_.getProjMat();
mat4 modelToCam = viewMat * modelToWorld;
mat4 modelToClip = projMat * modelToCam;
mat3 normalToCam = transpose(inverse(mat3(modelToCam[0][0], modelToCam[0][1], modelToCam[0][2],
modelToCam[1][0], modelToCam[1][1], modelToCam[1][2],
modelToCam[2][0], modelToCam[2][1], modelToCam[2][2] )));
mat3 worldToCam = transpose(inverse(mat3(viewMat[0][0], viewMat[0][1], viewMat[0][2],
viewMat[1][0], viewMat[1][1], viewMat[1][2],
viewMat[2][0], viewMat[2][1], viewMat[2][2] )));
pg_.updateModelToCam(modelToCam);
pg_.updateModelToClip(modelToClip);
pg_.updateNormalToCam(normalToCam);
pg_.updateToLight(normalize(worldToCam * lightPos3f_));
model_.render(pg_);
}
| 33.496
| 110
| 0.541438
|
sndels
|
b6e50918f04aefb0c3ddd2c5dde4d44ea56b5657
| 1,401
|
cpp
|
C++
|
6502/main.cpp
|
mavroskardia/6502
|
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
|
[
"MIT"
] | 1
|
2016-02-27T19:23:13.000Z
|
2016-02-27T19:23:13.000Z
|
6502/main.cpp
|
mavroskardia/6502
|
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
|
[
"MIT"
] | null | null | null |
6502/main.cpp
|
mavroskardia/6502
|
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
|
[
"MIT"
] | null | null | null |
#include "includes.h"
int do_assembly(const char*);
int do_run(const char*);
int do_tests();
int main(int argc, char** argv) {
int ret = 0;
switch (argc) {
case 2:
ret = string("test").compare(argv[1]) == 0 ? do_tests() : 1;
break;
case 3:
if (string("assemble").compare(argv[1]) == 0) ret = do_assembly(argv[2]);
else if (string("run").compare(argv[1]) == 0) ret = do_run(argv[2]);
break;
default:
cout << "usage: " << argv[0] << " <6502 assembly file>" << endl;
ret = 1;
}
return ret;
}
int do_assembly(const char* filename) {
int ret = 0;
auto assembler = Assembler(filename);
cout << "build assembler for file " << filename << endl;
try {
while (!assembler.eof()) {
stringstream lineout;
lineout << assembler.current_line_number() << ":\t";
vector<unsigned char> decoded = assembler.decodeline();
for (auto c : decoded)
lineout << "0x" << hex << (int)c;
cout << lineout.str() << endl;
}
}
catch (SyntaxException se) {
cerr << "Failed to assemble file: " << se.what();
ret = 1;
}
catch (UnknownInstruction ui) {
cerr << "Failed to assemble file: " << ui.what();
ret = 1;
}
catch (regex_error& re) {
cerr << "A regular expression failed: " << re.what() << " " << re.code() << endl;
ret = 1;
}
return ret;
}
int do_run(const char* filename) {
int ret = 0;
Executor e;
if (e.load(filename)) e.run();
return ret;
}
| 20.602941
| 83
| 0.598858
|
mavroskardia
|
b6e5b96b3b9a80bf364e304c2adacf3ba49033fd
| 554
|
hpp
|
C++
|
chratos/chratos_node/daemon.hpp
|
chratos-system/chratos
|
caf1b608a21ccc7b13726a64497036ab53f837b3
|
[
"BSD-2-Clause"
] | 2
|
2018-09-10T16:28:16.000Z
|
2020-02-13T17:44:43.000Z
|
chratos/chratos_node/daemon.hpp
|
chratos-system/chratos
|
caf1b608a21ccc7b13726a64497036ab53f837b3
|
[
"BSD-2-Clause"
] | null | null | null |
chratos/chratos_node/daemon.hpp
|
chratos-system/chratos
|
caf1b608a21ccc7b13726a64497036ab53f837b3
|
[
"BSD-2-Clause"
] | 2
|
2018-08-27T13:00:56.000Z
|
2018-10-16T21:54:13.000Z
|
#include <chratos/node/node.hpp>
#include <chratos/node/rpc.hpp>
namespace chratos_daemon
{
class daemon
{
public:
void run (boost::filesystem::path const &);
};
class daemon_config
{
public:
daemon_config (boost::filesystem::path const &);
bool deserialize_json (bool &, boost::property_tree::ptree &);
void serialize_json (boost::property_tree::ptree &);
bool upgrade_json (unsigned, boost::property_tree::ptree &);
bool rpc_enable;
chratos::rpc_config rpc;
chratos::node_config node;
bool opencl_enable;
chratos::opencl_config opencl;
};
}
| 22.16
| 63
| 0.749097
|
chratos-system
|
b6e6b03c6aec479a89fd0f21a6e2e0b311c44c75
| 20,841
|
cpp
|
C++
|
third_party/omr/compiler/optimizer/OMROptimization.cpp
|
xiacijie/omr-wala-linkage
|
a1aff7aef9ed131a45555451abde4615a04412c1
|
[
"Apache-2.0"
] | null | null | null |
third_party/omr/compiler/optimizer/OMROptimization.cpp
|
xiacijie/omr-wala-linkage
|
a1aff7aef9ed131a45555451abde4615a04412c1
|
[
"Apache-2.0"
] | null | null | null |
third_party/omr/compiler/optimizer/OMROptimization.cpp
|
xiacijie/omr-wala-linkage
|
a1aff7aef9ed131a45555451abde4615a04412c1
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "optimizer/OMROptimization.hpp"
#include <stddef.h>
#include <stdint.h>
#include "codegen/CodeGenerator.hpp"
#include "codegen/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "cs2/allocator.h"
#include "env/IO.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/Cfg.hpp"
#include "infra/CfgEdge.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Simplifier.hpp"
#include "optimizer/TransformUtil.hpp"
#define MAX_DEPTH_FOR_SMART_ANCHORING 3
// called once before perform is executed
void
OMR::Optimization::prePerform()
{
self()->prePerformOnBlocks();
}
// called once after perform is executed
void
OMR::Optimization::postPerform()
{
self()->postPerformOnBlocks();
}
TR::CodeGenerator *
OMR::Optimization::cg()
{
return self()->comp()->cg();
}
TR_FrontEnd *
OMR::Optimization::fe()
{
return self()->comp()->fe();
}
TR_Debug *
OMR::Optimization::getDebug()
{
return self()->comp()->getDebug();
}
TR::SymbolReferenceTable *
OMR::Optimization::getSymRefTab()
{
return self()->comp()->getSymRefTab();
}
TR_Memory *
OMR::Optimization::trMemory()
{
return self()->comp()->trMemory();
}
TR_StackMemory
OMR::Optimization::trStackMemory()
{
return self()->comp()->trStackMemory();
}
TR_HeapMemory
OMR::Optimization::trHeapMemory()
{
return self()->comp()->trHeapMemory();
}
TR_PersistentMemory *
OMR::Optimization::trPersistentMemory()
{
return self()->comp()->trPersistentMemory();
}
TR::Allocator
OMR::Optimization::allocator()
{
return self()->comp()->allocator();
}
OMR::Optimizations
OMR::Optimization::id()
{
return self()->manager()->id();
}
const char *
OMR::Optimization::name()
{
return self()->manager()->name();
}
void
OMR::Optimization::setTrace(bool trace)
{
self()->manager()->setTrace(trace);
}
bool
OMR::Optimization::getLastRun()
{
return self()->manager()->getLastRun();
}
void
OMR::Optimization::requestOpt(OMR::Optimizations optNum, bool value, TR::Block *block)
{
TR::OptimizationManager *manager = self()->optimizer()->getOptimization(optNum);
if (manager)
manager->setRequested(value, block);
}
// useful utility functions for opts
void
OMR::Optimization::requestDeadTreesCleanup(bool value, TR::Block *block)
{
self()->requestOpt(OMR::deadTreesElimination, value, block);
self()->requestOpt(OMR::trivialDeadTreeRemoval, value, block);
}
//---------------------------------------------------------------------
// Prepare to replace a node by changing its opcode.
// Use/def information and value number information must be given a
// chance to update themselves.
// The reference counts on all children must be decremented.
//
void
OMR::Optimization::prepareToReplaceNode(TR::Node * node)
{
// Value number information will be invalid after this optimization
//
self()->optimizer()->prepareForNodeRemoval(node);
node->removeAllChildren();
}
void
OMR::Optimization::prepareToReplaceNode(TR::Node * node, TR::ILOpCodes opcode)
{
TR::Node::recreate(node, opcode);
self()->prepareToReplaceNode(node);
}
/**
* Anchor all first level children of a given node, use this if you are to replace the node
* param node The node whose children is to be anchored
* param anchorTree The tree before which the anchor trees are to be inserted
*/
void
OMR::Optimization::anchorAllChildren(TR::Node * node, TR::TreeTop *anchorTree)
{
TR_ASSERT(anchorTree != NULL, "Can't anchor children to a NULL TR::TreeTop\n");
if (self()->trace())
traceMsg(self()->comp(), "%sanchoring children of node [" POINTER_PRINTF_FORMAT "]\n", self()->optDetailString(), node);
for (int i = 0; i <node->getNumChildren(); i++)
{
TR::TreeTop *tt = TR::TreeTop::create(self()->comp(), TR::Node::create(TR::treetop, 1, node->getChild(i)));
if (self()->trace())
traceMsg(self()->comp(), "TreeTop [" POINTER_PRINTF_FORMAT "] is created to anchor child [" POINTER_PRINTF_FORMAT "]\n", tt, node->getChild(i));
anchorTree->insertBefore(tt);
}
}
/** anchorChildren
* Only anchor order dependent children
* \param node Root node whose children is to be anchored
* \param anchorTree Tree before which anchor trees will be placed
*/
void
OMR::Optimization::anchorChildren(TR::Node *node, TR::TreeTop* anchorTree, uint32_t depth, bool hasCommonedAncestor, TR::Node* replacement)
{
TR::Node *prevChild = NULL;
// remaining path will be anchored to the original ancestor
if (node == replacement)
return;
if (!hasCommonedAncestor)
{
if (self()->trace())
traceMsg(self()->comp(),"set hasCommonedAncestor = true as %s %p has refCount %d > 1\n",
node->getOpCode().getName(),node,node->getReferenceCount());
hasCommonedAncestor = (node->getReferenceCount() > 1);
}
for (int j = node->getNumChildren()-1; j >= 0; --j)
{
TR::Node *child = node->getChild(j);
if (prevChild != child) // quite common for anchor to be called with two equal children
{
if (self()->nodeIsOrderDependent(child, depth, hasCommonedAncestor))
{
dumpOptDetails(self()->comp(), "%sanchor child %s [" POINTER_PRINTF_FORMAT "] at depth %d before %s [" POINTER_PRINTF_FORMAT "]\n",
self()->optDetailString(),child->getOpCode().getName(),child,depth,anchorTree->getNode()->getOpCode().getName(),anchorTree->getNode());
self()->generateAnchor(child, anchorTree);
}
else
{
self()->anchorChildren(child, anchorTree, depth + 1, hasCommonedAncestor, replacement); // skipped current child, so recurse its subtree
}
}
prevChild = child;
}
}
void
OMR::Optimization::generateAnchor(TR::Node *node, TR::TreeTop* anchorTree)
{
TR_ASSERT(anchorTree != NULL, "Can't anchor children to a NULL TR::TreeTop\n");
anchorTree->insertBefore(TR::TreeTop::create(self()->comp(),
TR::Node::create(TR::treetop, 1, node)));
}
void
OMR::Optimization::anchorNode(TR::Node *node, TR::TreeTop* anchorTree)
{
if (node->getOpCode().isLoadConst() && node->anchorConstChildren())
{
for (int32_t i=0; i < node->getNumChildren(); i++)
{
self()->generateAnchor(node->getChild(i), anchorTree);
}
}
else if (!node->getOpCode().isLoadConst())
{
self()->generateAnchor(node, anchorTree);
}
}
extern void createGuardSiteForRemovedGuard(TR::Compilation *comp, TR::Node* ifNode);
/**
* Folds a given if in IL. This method does NOT update CFG
* The callers should handle any updates to CFG or call
* conditionalToUnconditional
*/
bool
OMR::Optimization::removeOrconvertIfToGoto(TR::Node* &node, TR::Block* block, int takeBranch, TR::TreeTop* curTree, TR::TreeTop*& reachableTarget, TR::TreeTop*& unreachableTarget, const char* opt_details)
{
// Either change the conditional branch to an unconditional one or remove
// it altogether.
// In either case the CFG must be updated to reflect the change.
//
#ifdef J9_PROJECT_SPECIFIC
// doesn't matter taken or untaken, if it's a profiled guard we need to make sure the AOT relocation is created
createGuardSiteForRemovedGuard(self()->comp(), node);
#endif
if (takeBranch)
{
// Change the if into a goto
//
if (!performTransformation(self()->comp(), "%sChanging node [" POINTER_PRINTF_FORMAT "] %s into goto \n", opt_details, node, node->getOpCode().getName()))
return false;
self()->anchorChildren(node, curTree);
self()->prepareToReplaceNode(node);
TR::Node::recreate(node, TR::Goto);
reachableTarget = node->getBranchDestination();
unreachableTarget = block->getExit()->getNextTreeTop();
}
else
{
// Remove this node
//
if (!performTransformation(self()->comp(), "%sRemoving fall-through compare node [" POINTER_PRINTF_FORMAT "] %s\n", opt_details, node, node->getOpCode().getName()))
return false;
self()->anchorChildren(node, curTree);
reachableTarget = block->getExit()->getNextTreeTop();
unreachableTarget = node->getBranchDestination();
// Don't call remove node as we can't suppress the removal with performTransformation any more
self()->prepareToStopUsingNode(node, curTree);
node->removeAllChildren();
node = NULL;
}
return true;
}
/**
* Folds a given if by updating IL, CFG and Structures.
* If the removal of the edge caused the part of the CFG to become unreachable
* (orphaned), it will remove the subgraph.
*
* The callers should be aware that the block containing the if tree might be
* removed as well and handle such a scenario appropriately
*/
TR::CFGEdge*
OMR::Optimization::changeConditionalToUnconditional(TR::Node*& node, TR::Block* block, int takeBranch, TR::TreeTop* curTree, const char* opt_details)
{
TR::TreeTop *reachableTarget, *unreachableTarget;
if (!self()->removeOrconvertIfToGoto(node, block, takeBranch, curTree, reachableTarget, unreachableTarget, opt_details))
return NULL;
// Now "unreachableTarget" contains the branch destination that is NOT being
// taken.
//
TR::CFG * cfg = self()->comp()->getFlowGraph();
TR::CFGEdge* edge = NULL;
bool blocksWereRemoved = false;
if (cfg)
{
if (unreachableTarget != reachableTarget)
{
TR_ASSERT(unreachableTarget->getNode()->getOpCodeValue() == TR::BBStart, "Simplifier, expected BBStart");
TR_SuccessorIterator ei(block);
for (edge = ei.getFirst(); edge != NULL; edge = ei.getNext())
if (edge->getTo() == unreachableTarget->getNode()->getBlock())
{
blocksWereRemoved = cfg->removeEdge(edge);
break;
}
}
}
else if (takeBranch)
{
// There is no CFG so we may be dealing with extended basic blocks.
// Remove all non-fence treetops from here to the end of the block
//
for (TR::TreeTop * treeTop = block->getLastRealTreeTop(), * prevTreeTop;
treeTop->getNode() != node;
treeTop = prevTreeTop)
{
prevTreeTop = treeTop->getPrevRealTreeTop();
TR::TransformUtil::removeTree(self()->comp(), treeTop);
blocksWereRemoved = true;
}
}
return edge;
}
/**
* Prepare to stop using a node
*/
void
OMR::Optimization::prepareToStopUsingNode(TR::Node * node, TR::TreeTop* anchorTree, bool anchorChildrenNeeded)
{
if (anchorChildrenNeeded && node->getOpCodeValue() != TR::treetop)
{
self()->anchorChildren(node, anchorTree);
}
if (node->getReferenceCount() <= 1)
{
self()->optimizer()->prepareForNodeRemoval(node);
}
}
/**
* In the special case of replacing a node with its child then anchoring is not
* needed for the replacing child (as it and any children of its own will
* remain anchored)
*
* So if all of the node's other children are constants then no anchoring at
* all is required when replacing.
*/
TR::Node *
OMR::Optimization::replaceNodeWithChild(TR::Node *node, TR::Node *child, TR::TreeTop* anchorTree, TR::Block *block, bool correctBCDPrecision)
{
#ifdef J9_PROJECT_SPECIFIC
if (correctBCDPrecision &&
node->getType().isBCD() && child->getType().isBCD() &&
node->getDecimalPrecision() != child->getDecimalPrecision())
{
// The extra work for BCD (packed,zoned etc) nodes on a replace node is ensuring
// that the precision of the replacing node (child) matches the precision of the replaced
// node (node).
// If 'child' has a different precision than 'node' then the parent of 'node', if it is call
// for example, will pass too many or too few digits to its callee (even digits known to be zero
// are significant to calls to ensure the callee can demarshal the arguments correctly).
// If the 'child' truncates then there is the danger that this truncating side-effect will be lost unless
// a bcd modPrecOp is inserted.
// If correctBCDPrecision=false then the caller has guaranteed that there is no danger of a child truncation
// or widening causing any problems.
//
// This transformation is required for correctness so do not provide a performTransformation
int32_t childIndex = -1;
for (int32_t i=0; i < node->getNumChildren(); i++)
{
if (node->getChild(i) == child)
{
childIndex = i;
}
else if (node->getChild(i)->getOpCode().isLoadConst() && node->getChild(i)->anchorConstChildren())
{
for (int32_t j=0; j < node->getChild(i)->getNumChildren(); j++)
{
self()->anchorNode(node->getChild(i)->getChild(j), anchorTree);
}
}
else if (!node->getChild(i)->getOpCode().isLoadConst() &&
node->getChild(i)->getOpCodeValue() != TR::loadaddr)
{
self()->anchorNode(node->getChild(i), anchorTree);
}
}
if (childIndex == -1)
{
TR_ASSERT(false,"could not find child under node in replaceBCDNodeWithChild\n");
return node;
}
if (node->getReferenceCount() > 1)
{
TR::Node *newNode = TR::Node::create(TR::ILOpCode::modifyPrecisionOpCode(child->getDataType()), 1, child);
newNode->setDecimalPrecision(node->getDecimalPrecision());
dumpOptDetails(self()->comp(), "%sPrecision mismatch when replacing parent %s [" POINTER_PRINTF_FORMAT "] with child %s [" POINTER_PRINTF_FORMAT "] so create new parent %s [" POINTER_PRINTF_FORMAT "]\n",
self()->optDetailString(),node->getOpCode().getName(),node,child->getOpCode().getName(),child,newNode->getOpCode().getName(),newNode);
return self()->replaceNode(node, newNode, anchorTree, false); // needAnchor=false
}
else
{
dumpOptDetails(self()->comp(), "%sPrecision mismatch when replacing parent %s [" POINTER_PRINTF_FORMAT "] with child %s [" POINTER_PRINTF_FORMAT "] so change parent op to ",
self()->optDetailString(),node->getOpCode().getName(),node,child->getOpCode().getName(),child);
TR_ASSERT(node->getReferenceCount() == 1,"node %p refCount should be 1 and not %d\n",node,node->getReferenceCount());
child->incReferenceCount();
// zd2pd <- node - change to zdModifyPrecision (must use child type as modPrec is being applied to the child)
// zdX <- child
//
self()->prepareToReplaceNode(node, TR::ILOpCode::modifyPrecisionOpCode(child->getDataType()));
node->setNumChildren(1);
node->setChild(0, child);
dumpOptDetails(self()->comp(), "%s\n",node->getOpCode().getName());
if (self()->id() == OMR::treeSimplification)
return ((TR::Simplifier *) self())->simplify(node, block);
else
return node;
}
}
else
#endif
{
TR_ASSERT(node->hasChild(child),"node %p is not a child of node %p\n",child,node);
bool needAnchor = false;
for (int32_t i = 0; i < node->getNumChildren(); i++)
{
// skip anchoring for 1) the input 'child' 2) constants with no children 3) loadaddrs
if (node->getChild(i) != child &&
(!node->getChild(i)->getOpCode().isLoadConst() || node->getChild(i)->anchorConstChildren()) &&
node->getChild(i)->getOpCodeValue() != TR::loadaddr)
{
needAnchor = true;
break;
}
}
return self()->replaceNode(node, child, anchorTree, needAnchor);
}
}
/**
* Common routine to replace the node by another
*
* This routine replaces one use of this node by adjusting reference counts and
* returning the replacing node. It is assumed that the caller will replace the
* reference to the original node with the replacing node. The visit count on
* the original node is reset so that it is visited again on the next reference.
*/
TR::Node *
OMR::Optimization::replaceNode(TR::Node * node, TR::Node *other, TR::TreeTop *anchorTree, bool anchorChildren)
{
if (!performTransformation(self()->comp(), "%sReplace node [" POINTER_PRINTF_FORMAT "] %s by [" POINTER_PRINTF_FORMAT "] %s\n", self()->optDetailString(), node, node->getOpCode().getName(), other, other->getOpCode().getName()))
{
if(other->getReferenceCount() == 0)
{
// Because the replacement node will not be used and it does not currently exist in the compilation unit,
// it should be destroyed.
other->removeAllChildren();
}
return node;
}
// Increment the reference count on the replacing node, since it will be
// getting a new reference.
//
other->incReferenceCount();
// This must be done AFTER
// incrementing the count on the replacing node in case the replacing node is
// a child of the original node. Otherwise we can end up deleting
// use/def info from the child (in prepareForNodeRemoval)
// Adjust usedef and value number information if this node is not going to
// be used any more.
//
self()->prepareToStopUsingNode(node, anchorTree, anchorChildren);
// Decrement the reference count on the original node. This must be done AFTER
// incrementing the count on the replacing node in case the replacing node is
// a child of the original node. In this case we don't want the count on the
// replacing node to go to zero.
//
node->recursivelyDecReferenceCount();
// If the original node still has other uses make sure it is re-visited
// so the other references to it can be fixed up too.
//
if (node->getReferenceCount() > 0)
node->setVisitCount(0);
return other;
}
/**
* Common routine to remove the node from the tree
*/
void
OMR::Optimization::removeNode(TR::Node * node, TR::TreeTop *anchorTree)
{
// Reduce the reference counts of all children.
//
if (performTransformation(self()->comp(), "%sRemoving redundant node [" POINTER_PRINTF_FORMAT "] %s\n", self()->optDetailString(), node, node->getOpCode().getName()))
{
self()->prepareToStopUsingNode(node, anchorTree);
node->removeAllChildren();
}
}
bool
OMR::Optimization::nodeIsOrderDependent(TR::Node *node, uint32_t depth, bool hasCommonedAncestor)
{
// While it may be tempting to use futureUseCount here, futureUseCount isn't well maintained in simplifier
// and so shouldn't be used for functional items such as to anchor or not anchor a node. FutureUseCount
// should only be used as a heuristic for optimizations.
bool constNeedsAnchor = node->getOpCode().isLoadConst() && node->anchorConstChildren();
return ((node->getOpCode().isLoad() && node->getOpCode().hasSymbolReference() &&
((node->getReferenceCount() > 1) || hasCommonedAncestor)) ||
((!node->getOpCode().isLoadConst() || constNeedsAnchor) && depth >= MAX_DEPTH_FOR_SMART_ANCHORING));
}
| 36.057093
| 230
| 0.64685
|
xiacijie
|
b6eb39ef45bc5c2f56339e4c9849eee6c477b6e3
| 1,711
|
cxx
|
C++
|
src/converter/fix_helper.cxx
|
abdelkaderamar/fix2xml
|
fa781b747a8e40ed4c2d3dee8294fb51654f7428
|
[
"MIT"
] | 1
|
2019-09-26T12:08:19.000Z
|
2019-09-26T12:08:19.000Z
|
src/converter/fix_helper.cxx
|
abdelkaderamar/fix2xml
|
fa781b747a8e40ed4c2d3dee8294fb51654f7428
|
[
"MIT"
] | null | null | null |
src/converter/fix_helper.cxx
|
abdelkaderamar/fix2xml
|
fa781b747a8e40ed4c2d3dee8294fb51654f7428
|
[
"MIT"
] | 1
|
2020-12-11T04:11:44.000Z
|
2020-12-11T04:11:44.000Z
|
#include "fix_helper.hxx"
#include <quickfix/FixFieldNumbers.h>
#include <algorithm>
#include <functional>
#include <vector>
namespace fix2xml {
using namespace std;
//-----------------------------------------------------------------------------
void msg_to_list(const FIX::Message &fix_msg,
const FIX::DataDictionary &fix_dict,
multiset<string> &fields_set, list<multiset<string>> &ls) {
ls.push_back(fieldmap_to_list(fix_msg.getHeader(), fix_dict, ls));
fields_set = fieldmap_to_list(fix_msg, fix_dict, ls);
}
//-----------------------------------------------------------------------------
multiset<string> fieldmap_to_list(const FIX::FieldMap &fix_msg,
const FIX::DataDictionary &fix_dict,
list<multiset<string>> &ls) {
// Insert all the fields that are not NumInGroup in the multiset fields_set
multiset<string> fields_set;
for (auto it = fix_msg.begin(); it != fix_msg.end(); ++it) {
if (it->getField() == FIX::FIELD::MsgType)
continue;
FIX::TYPE::Type fix_type;
if (fix_dict.getFieldType(it->getField(), fix_type) &&
(fix_type == FIX::TYPE::NumInGroup))
continue;
fields_set.insert(it->getString());
}
// For each group insert its fields (as multiset) in the list ls
for (auto it = fix_msg.g_begin(); it != fix_msg.g_end(); ++it) {
const vector<FIX::FieldMap *> &groups = it->second;
for (size_t i = 0; i < groups.size(); ++i) {
ls.push_back(fieldmap_to_list(*groups[i], fix_dict, ls));
}
}
return fields_set;
}
//-----------------------------------------------------------------------------
} // end namespace fix2xml
| 34.22
| 79
| 0.548802
|
abdelkaderamar
|
b6f2464ac1f220f4d92948ee29510bccaf768fc8
| 2,030
|
cpp
|
C++
|
DS/DS/graph/bellman_ford.cpp
|
puneet222/Data-Structures
|
c5c460739c7423cce53685c5557c97c70ca1d171
|
[
"Apache-2.0"
] | null | null | null |
DS/DS/graph/bellman_ford.cpp
|
puneet222/Data-Structures
|
c5c460739c7423cce53685c5557c97c70ca1d171
|
[
"Apache-2.0"
] | null | null | null |
DS/DS/graph/bellman_ford.cpp
|
puneet222/Data-Structures
|
c5c460739c7423cce53685c5557c97c70ca1d171
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include<stdio.h>
#include<queue>
#include<malloc.h>
#include<limits.h>
using namespace std ;
struct graph{
int v ;
int e ;
int **wgh ;
} ;
struct graph *weightMatrix(int vertices , int edges)
{
struct graph *g = new graph ;
g -> v = vertices ;
g -> e = edges ;
g -> wgh = (int **)malloc(sizeof(int *)*(g -> v)) ;
for (int i = 0; i < g -> v; ++i)
{
g -> wgh[i] = (int *)malloc(sizeof(int)*(g -> v)) ;
}
int u , v ;
for(u = 0 ; u < g -> v ; u++)
{
for(v = 0 ; v < g -> v ; v++)
{
g -> wgh[u][v] = 0 ;
}
}
for (int i = 0; i < g -> e; ++i)
{
printf("Enter the vertices u and v such that there is an edge u -> v is there : ");
cin >> u >> v ;
int w ;
cout << "\nEnter the weight of the edge : " ;
cin >> w ;
g -> wgh[u][v] = w ;
}
return g ;
}
void printGraph(struct graph *g)
{
int u , v ;
for(u = 0 ; u < g -> v ; u++)
{
for(v = 0 ; v < g -> v ; v++)
{
printf(" %d ", g -> wgh[u][v]);
}
printf("\n");
}
}
void shortestpath(struct graph *g , int * distance , int *path , int s)
{
queue <int> Q ;
int qarr[g -> v] ;
for (int i = 0; i < g -> v; ++i)
{
distance[i] = INT_MAX ;
qarr[i] = 0 ;
}
distance[s] = 0 ;
Q.push(s) ;
qarr[s] = 1 ;
while(!Q.empty())
{
int v = Q.front() ;
Q.pop() ;
qarr[v] = 0 ;
for (int i = 0; i < g -> v; ++i)
{
if(g -> wgh[v][i])
{
int dnew = distance[v] + g -> wgh[v][i] ;
if(distance[i] > dnew)
{
distance[i] = dnew ;
path[i] = v ;
if(qarr[i] == 0)
{
Q.push(i) ;
qarr[i] == 1 ;
}
}
}
}
}
}
int main()
{
int v , e ;
printf("Enter number of vertices and edges in the graph : ");
scanf("%d%d" , &v , &e) ;
struct graph *g = weightMatrix(v , e) ;
printGraph(g);
int distance[g -> v] ;
int path[g -> v] ;
int s ;
printf("Enter the source from where you want to find the shortest path to all other nodes : ");
cin >> s ;
shortestpath(g , distance , path , s) ;
for (int i = 0; i < g -> v; ++i)
{
printf(" %d ", distance[i]);
}
}
| 17.964602
| 96
| 0.484236
|
puneet222
|
b6f669662fc07113ef4dc65531cf932b8353b1f9
| 2,127
|
cpp
|
C++
|
1. Деревья поиска/0.2. Удалить из дерева #3535/[OK]169443.cpp
|
godnoTA/acm.bsu.by
|
3e1cf1c545c691de82b5e1d2e0768b41ea581734
|
[
"Unlicense"
] | 19
|
2018-05-19T16:37:14.000Z
|
2022-03-23T20:13:43.000Z
|
1. Деревья поиска/0.2. Удалить из дерева #3535/[OK]169443.cpp
|
godnoTA/acm.bsu.by
|
3e1cf1c545c691de82b5e1d2e0768b41ea581734
|
[
"Unlicense"
] | 6
|
2020-05-07T21:06:48.000Z
|
2020-06-05T17:52:57.000Z
|
1. Деревья поиска/0.2. Удалить из дерева #3535/[OK]169443.cpp
|
godnoTA/acm.bsu.by
|
3e1cf1c545c691de82b5e1d2e0768b41ea581734
|
[
"Unlicense"
] | 31
|
2019-03-01T21:41:38.000Z
|
2022-03-27T17:56:39.000Z
|
#include<iostream>
#include<fstream>
using namespace std;
//Входной и выходной файлы
ifstream in("input.txt");
ofstream out("output.txt");
struct node{
int key;
node *left;
node *right;
};
void push(int a,node *&t)
{
if (t == NULL)
{
t = new node; //Выделяем память
t -> key = a; //Кладем в выделенное место аргумент a
t -> left = t -> right = NULL; //Очищаем память для следующего роста
}
if ((a > t->key)&&(t->right == NULL))
{
t->right = new node();
t->right->key = a;
t->right->left = NULL;
t->right->right = NULL;
}
else if ((a > t->key)&&(t->right != NULL))
{
push(a, t->right);
}
if ((a < t->key)&&(t->left == NULL))
{
t->left = new node();
t->left->key = a;
t->left->left = NULL;
t->left->right = NULL;
}
else if ((a < t->key)&&(t->left != NULL))
{
push(a, t->left);
}
}
node*& findmin(node *& min) {
if (min->left == NULL)
return min;
return findmin(min->left);
}
node*& del(int val,node *&Tree_) {
if (Tree_ == NULL) {
return Tree_;
}
if (val < Tree_->key)
Tree_->left = del(val,Tree_->left);
else {
if (val > Tree_->key) {
Tree_->right = del(val, Tree_->right);
}
else {
if (Tree_->left != NULL && Tree_->right != NULL) {
Tree_->key = findmin(Tree_->right)->key;
Tree_->right = del(Tree_->key, Tree_->right);
}
else {
if (Tree_->left != NULL)
Tree_ = Tree_->left;
else
Tree_ = Tree_->right;
}
}
}
return Tree_;
}
void output (node *&tree)
{
if (tree==NULL)
return; //Если дерево пустое, то отображать нечего, выходим
else //Иначе
{
out<<tree->key<<endl; //И записываем элемент
output(tree->left);//С помощью рекурсивного посещаем левое поддерево
//for (int i=0;i<a;++i)
//a--;
}
output(tree->right); //С помощью рекурсии посещаем правое поддерево
}
int main()
{
setlocale(LC_ALL, ".1251");
node* tree = NULL;
int val;
in>>val;
while (!in.eof()){
int l;
in >> l;
push(l, tree);
}
del(val,tree);
output(tree);
return 0;
}
| 19.694444
| 77
| 0.535966
|
godnoTA
|
b6f7f2f06130d095c5b2a916d993ecd6bd4f62f6
| 833
|
cpp
|
C++
|
机试/动态规划/leetcode123.cpp
|
codehuanglei/-
|
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
|
[
"MIT"
] | null | null | null |
机试/动态规划/leetcode123.cpp
|
codehuanglei/-
|
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
|
[
"MIT"
] | null | null | null |
机试/动态规划/leetcode123.cpp
|
codehuanglei/-
|
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0){
return 0;
}
int len = prices.size();
vector<vector<int>> dp(len, vector<int>(5));
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[0][2] = 0;
dp[0][3] = -prices[0];
dp[0][4] = 0;
for(int i = 1; i < prices.size(); i++){
dp[i][0] = dp[i-1][0]; //初始状态
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); //第一次买入
dp[i][2] = max(dp[i-1][2], dp[i-1][1] + prices[i]); //第一次卖出
dp[i][3] = max(dp[i-1][3], dp[i-1][2] - prices[i]);//第二次买入
dp[i][4] = max(dp[i-1][4], dp[i-1][3] + prices[i]);//第二次卖出
}
return max(max( max(dp[len-1][0], dp[len-1][1]), max(dp[len-1][2], dp[len-1][3]) ), dp[len-1][4]);
}
};
| 36.217391
| 105
| 0.421369
|
codehuanglei
|
b6f8e89b7854ae190ce4fb84d665ae55b410da1d
| 21,275
|
cc
|
C++
|
tests/unit/speech_recog_test.cc
|
CPqD/asr-sdk-cpp
|
ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1
|
[
"Apache-2.0"
] | 4
|
2017-10-12T20:09:31.000Z
|
2021-05-24T13:46:26.000Z
|
tests/unit/speech_recog_test.cc
|
CPqD/asr-sdk-cpp
|
ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1
|
[
"Apache-2.0"
] | null | null | null |
tests/unit/speech_recog_test.cc
|
CPqD/asr-sdk-cpp
|
ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1
|
[
"Apache-2.0"
] | 4
|
2017-10-04T14:30:11.000Z
|
2022-02-25T10:13:06.000Z
|
/*****************************************************************************
* Copyright 2017 CPqD. 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 <gtest/gtest.h>
#include "test_config.h"
#include <chrono>
#include <string>
#include <thread>
#include <cpqd/asr-client/file_audio_source.h>
#include <cpqd/asr-client/buffer_audio_source.h>
#include <cpqd/asr-client/recognition_config.h>
#include <cpqd/asr-client/recognition_exception.h>
#include <cpqd/asr-client/speech_recog.h>
#ifndef NO_INPUT_TIMEOUT_MS
#define NO_INPUT_TIMEOUT_MS 1000
#endif
/*
* ok: basicGrammar
* ok: basicGrammarClearVoice
* ok: recognizeNoSpeech (NO_MATCH)
* ok: recognizeNoInput
* ok: recognizeBufferAudioSource
* ok: recognizeBufferBlockRead
* ok: recognizeMaxWaitSeconds
* ok: closeWhileRecognize
* ok: closeWithoutRecognize
* ok: cancelWhileRecognize
* ok: cancelNoRecognize
* ok: waitRecognitionResult
* ok: waitRecognitionResultDuplicateTest
* ok: duplicateRecognize
* ok: multipleRecognize
* ok-ish: connectOnRecognize (doesn't test connection per se, only the object status)
* ok-ish: multipleAutoClose (doesn't test connection per se, only the object status)
* ok: sessionTimeout
*/
/* Most common recognizer configuration */
std::unique_ptr<SpeechRecognizer> defaultBuild(){
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
return SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username, test::password)
.maxWaitSeconds(30)
.build();
}
/*Class for simulating noInputTimeout*/
class DelayedFileAudioSource: public FileAudioSource {
public:
DelayedFileAudioSource(const std::string& file_name,
AudioFormat fmt = AudioFormat())
: FileAudioSource(file_name, fmt)
{}
int read(std::vector<char>& buffer) {
std::this_thread::sleep_for(
std::chrono::milliseconds(NO_INPUT_TIMEOUT_MS + 10)
);
return FileAudioSource::read(buffer);
}
};
TEST(RecognizerTest, basicGrammar) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::grammar_phone_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_LT(0, result.size());
bool at_least_one_high_confidence = false;
for (RecognitionResult& res : result) {
if(res.getCode() != RecognitionResult::Code::RECOGNIZED) continue;
at_least_one_high_confidence = true;
for (RecognitionResult::Alternative& alt : res.getAlternatives()) {
std::cout << "alt.getConfidence(): " << alt.getConfidence() << std::endl;
ASSERT_GE(alt.getConfidence(), 90);
}
}
ASSERT_EQ(true, at_least_one_high_confidence) << "No results with high confidence!";
}
TEST(NoGrammarTest, basicGrammarClearVoice) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_LT(0, result.size());
bool at_least_one_high_confidence = false;
for (RecognitionResult& res : result) {
if(res.getCode() != RecognitionResult::Code::RECOGNIZED) continue;
at_least_one_high_confidence = true;
for (RecognitionResult::Alternative& alt : res.getAlternatives()) {
std::cout << "alt.getConfidence(): " << alt.getConfidence() << std::endl;
ASSERT_GE(alt.getConfidence(), 90);
}
}
ASSERT_EQ(true, at_least_one_high_confidence) << "No results with high confidence!";
}
TEST(NoGrammarTest, recognizeNoSpeech) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_silence_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
EXPECT_EQ(RecognitionResult::Code::NO_SPEECH, result[0].getCode());
asr->close();
}
TEST(RecognizerTest, recognizeNoInput) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder()
.noInputTimeoutEnabled(true)
.noInputTimeoutMilliseconds(NO_INPUT_TIMEOUT_MS)
.startInputTimers(true)
.build();
// Making a buffer with delayed read to simulate no input timeout
std::shared_ptr<DelayedFileAudioSource> audio =
std::make_shared<DelayedFileAudioSource>(test::audio_silence_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::grammar_phone_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(30)
.build();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> res = asr->waitRecognitionResult();
EXPECT_EQ(RecognitionResult::Code::NO_INPUT_TIMEOUT, res[0].getCode());
asr->close();
}
TEST(RecognizerTest, recognizeBufferAudioSource) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder()
.noInputTimeoutEnabled(false)
.build();
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(30)
.build();
static long buffer_size = 200000; // Longer than audio_phone_8k
std::ifstream ifs;
ifs.open(test::audio_phone_8k_raw);
// Reading file content
std::vector<char> audio_content;
if (!ifs.eof() && !ifs.fail())
{
ifs.seekg(0, std::ios_base::end);
std::streampos fileSize = ifs.tellg();
audio_content.resize(fileSize);
ifs.seekg(0, std::ios_base::beg);
ifs.read(&audio_content[0], fileSize);
}
// Assert that file content is smaller than buffer size
ASSERT_LT(audio_content.size(), buffer_size);
// Writing content smaller than buffer_size
AudioFormat fmt;
fmt.fileFormat = AudioFileFormat::RAW;
fmt.bits_per_sample_ = 16;
std::shared_ptr<BufferAudioSource> audio =
std::make_shared<BufferAudioSource>(fmt, buffer_size);
asr->recognize(audio, std::move(lm));
audio->write(audio_content);
audio->finish();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
// Assert that there's at least one valid result
ASSERT_GT(result.size(), 0);
}
TEST(RecognizerTest, recognizeBufferBlockRead) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder()
.noInputTimeoutEnabled(false)
.build();
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(30)
.build();
char buffer[4000]; // Shorter than previsao-tempo-8k.raw
// Audio instance
AudioFormat fmt;
fmt.fileFormat = AudioFileFormat::RAW;
fmt.bits_per_sample_ = 16;
std::shared_ptr<BufferAudioSource> audio =
std::make_shared<BufferAudioSource>(fmt, 4000);
asr->recognize(audio, std::move(lm));
// Writing and blocking audio. For each 2000 samples (250ms), wait 300ms
std::ifstream ifs;
ifs.open(test::previsao_tempo_8k_raw);
ifs.read(buffer, 4000);
do {
audio->write(buffer, 4000);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
ifs.read(buffer, 4000);
} while (ifs.gcount() != 0);
audio->finish();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
// Assert that there's at least one valid result
ASSERT_GT(result.size(), 0);
}
TEST(RecognizerTest, recognizeMaxWaitSeconds) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
std::shared_ptr<AudioSource> audio =
std::make_shared<DelayedFileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials(test::username,
test::password)
.maxWaitSeconds(1)
.build();
asr->recognize(audio, std::move(lm));
try {
asr->waitRecognitionResult();
FAIL() << "Expected RecognitionException";
} catch (RecognitionException& err) {
EXPECT_EQ(err.getCode(), RecognitionError::Code::FAILURE);
} catch(...) {
FAIL() << "Expected RecognitionException";
}
}
TEST(RecognizerTest, closeWhileRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
asr->close();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, closeWithoutRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->close();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest,cancelNoRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->cancelRecognition();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest,cancelWhileRecognize) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::this_thread::sleep_for(std::chrono::milliseconds(300));
asr->cancelRecognition();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, waitRecognitionResultNoRecognizerTest) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, waitRecognitionResultDuplicateTest) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_GT(result.size(), 0);
result = asr->waitRecognitionResult();
ASSERT_EQ(result.size(), 0);
}
TEST(RecognizerTest, duplicateRecognize) {
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
auto lm = LanguageModelList::Builder().addFromURI(test::slm_uri).build();
asr->recognize(audio, std::move(lm));
std::shared_ptr<AudioSource> audio2 =
std::make_shared<FileAudioSource>(test::previsao_tempo_8k);
auto lm2 = LanguageModelList::Builder().addFromURI(test::slm_uri).build();
std::this_thread::sleep_for(std::chrono::milliseconds(120));
ASSERT_THROW(asr->recognize(audio2, std::move(lm2)), RecognitionException);
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_GT(result.size(), 0);
}
TEST(RecognizerTest, multipleRecognize) {
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
for (auto i = 0; i < 3; ++i) {
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addFromURI(test::grammar_phone_uri)
.build();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
}
}
TEST(RecognizerTest, multipleConnectOnRecognize) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials("asrdev", "inova")
.maxWaitSeconds(30)
.connectOnRecognize(true)
.build();
ASSERT_EQ(false, asr->isOpen()) <<
"Connection should stay closed until 1st recognition!";
int wait_secs[] = {2, 2, 6};
for (auto i = 0; i < 3; ++i) {
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addFromURI(test::grammar_phone_uri)
.build();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(true, asr->isOpen()) <<
"Connection should stay open after 1st recognition!";
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
std::this_thread::sleep_for(std::chrono::seconds(wait_secs[i]));
}
}
TEST(RecognizerTest, multipleAutoClose) {
std::unique_ptr<RecognitionConfig> config =
RecognitionConfig::Builder().build();
std::unique_ptr<SpeechRecognizer> asr = SpeechRecognizer::Builder()
.serverUrl(test::server_url)
.recogConfig(std::move(config))
.credentials("asrdev", "inova")
.maxWaitSeconds(30)
.connectOnRecognize(true)
.autoClose(true)
.build();
ASSERT_EQ(false, asr->isOpen()) <<
"Connection should stay closed until recognition!";
int wait_secs[] = {2, 2, 6};
for (auto i = 0; i < 3; ++i) {
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addFromURI(test::grammar_phone_uri)
.build();
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
ASSERT_EQ(false, asr->isOpen()) <<
"Connection should close after every recognition!";;
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
std::this_thread::sleep_for(std::chrono::seconds(wait_secs[i]));
}
}
TEST(RecognizerTest, sessionTimeout) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_phone_8k);
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder().addFromURI(test::grammar_phone_uri).build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::this_thread::sleep_for(std::chrono::seconds(65));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_LT(0, result.size());
bool at_least_one_recognized = false;
for (RecognitionResult& res : result) {
if(res.getCode() == RecognitionResult::Code::RECOGNIZED)
at_least_one_recognized = true;
}
ASSERT_EQ(true, at_least_one_recognized);
}
TEST(GrammarInline, Recog) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $root;\n"
"$root = sim | não;\n";
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.build();
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
ASSERT_GT(result.size(), 0);
}
TEST(GrammarInline, WrongGrammar) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $rodfot;\n"
"$root = sim | não;\n";
std::unique_ptr<LanguageModelList> lm =
LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.build();
try {
std::unique_ptr<SpeechRecognizer> asr = defaultBuild();
asr->recognize(audio, std::move(lm));
std::vector<RecognitionResult> result = asr->waitRecognitionResult();
asr->close();
} catch (RecognitionException& e) {
} catch (...) {
FAIL() << "Expected error on start recognition";
}
}
TEST(GrammarInline, TwoGrammars) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::unique_ptr<LanguageModelList> lm;
try {
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $root;\n"
"$root = sim | não;\n";
lm = LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.addInlineGrammar(str_gram)
.build();
} catch (RecognitionException& e) {
return;
} catch (...) {
FAIL() << "Expected error on LanguageModelList";
}
}
TEST(GrammarInline, InlineAndUri) {
std::shared_ptr<AudioSource> audio =
std::make_shared<FileAudioSource>(test::audio_yes_16k);
std::unique_ptr<LanguageModelList> lm;
try {
std::string str_gram = "#ABNF 1.0 UTF-8;\n"
"language pt-BR;\n"
"tag-format <semantics/1.0>;\n"
"mode voice;\n"
"root $root;\n"
"$root = sim | não;\n";
lm = LanguageModelList::Builder()
.addInlineGrammar(str_gram)
.addFromURI(test::grammar_phone_uri)
.build();
} catch (RecognitionException& e) {
return;
} catch (...) {
FAIL() << "Expected error on LanguageModelList";
}
}
| 33.769841
| 88
| 0.676193
|
CPqD
|
b6fb19c28ec6bab8291643f67434843fb09d55bf
| 3,231
|
cpp
|
C++
|
docs/tests/graph.cpp
|
nyorain/tokonoma
|
b3a4264ef4f9f40487c2f3280812bf7513b914bb
|
[
"MIT"
] | 23
|
2019-07-11T14:47:39.000Z
|
2021-12-24T09:56:24.000Z
|
docs/tests/graph.cpp
|
nyorain/tokonoma
|
b3a4264ef4f9f40487c2f3280812bf7513b914bb
|
[
"MIT"
] | null | null | null |
docs/tests/graph.cpp
|
nyorain/tokonoma
|
b3a4264ef4f9f40487c2f3280812bf7513b914bb
|
[
"MIT"
] | 4
|
2021-04-06T18:20:43.000Z
|
2022-01-15T09:20:45.000Z
|
#include "bugged.hpp"
#include <deferred/graph.hpp>
TEST(basic) {
FrameGraph graph;
auto& pass1 = graph.addPass();
vk::Image img1;
vk::Image img2;
auto& out1 = pass1.addOut(syncScopeFlex, img1);
auto& out2 = pass1.addOut(syncScopeFlex, img2);
auto scope2 = SyncScope {
vk::PipelineStageBits::computeShader,
vk::ImageLayout::shaderReadOnlyOptimal,
vk::AccessBits::shaderRead,
};
auto& pass2 = graph.addPass();
pass2.addIn(out1, scope2);
auto scope3 = SyncScope {
vk::PipelineStageBits::fragmentShader,
vk::ImageLayout::shaderReadOnlyOptimal,
vk::AccessBits::shaderRead,
};
auto& pass3 = graph.addPass();
pass3.addIn(out1, scope3);
pass3.addIn(out2, scope3);
graph.compute();
// test
auto& order = graph.order();
EXPECT(graph.check(), true);
EXPECT(order.size(), 3u);
EXPECT(order[0].pass, &pass1);
EXPECT(order[1].pass, &pass2);
EXPECT(order[2].pass, &pass3);
EXPECT(order[0].barriers.size(), 0u);
EXPECT(order[1].barriers.size(), 0u);
EXPECT(order[2].barriers.size(), 0u);
EXPECT(graph.check(), true);
}
TEST(outOfOrder) {
FrameGraph graph;
vk::Image img1;
vk::Image img2;
auto& pass1 = graph.addPass();
auto& pass3 = graph.addPass();
auto& pass2 = graph.addPass();
auto scope2 = SyncScope {
vk::PipelineStageBits::computeShader,
vk::ImageLayout::general,
vk::AccessBits::shaderRead | vk::AccessBits::shaderWrite
};
auto scope3 = SyncScope {
vk::PipelineStageBits::fragmentShader,
vk::ImageLayout::shaderReadOnlyOptimal,
vk::AccessBits::shaderRead,
};
auto& out1 = pass1.addOut(syncScopeFlex, img1);
auto& out2 = pass1.addOut(syncScopeFlex, img2);
pass3.addIn(out2, scope3);
auto& out3 = pass2.addInOut(out1, scope2);
pass3.addIn(out3, scope3);
graph.compute();
// test
EXPECT(graph.check(), true);
auto& order = graph.order();
EXPECT(order.size(), 3u);
EXPECT(order[0].pass, &pass1);
EXPECT(order[1].pass, &pass2);
EXPECT(order[2].pass, &pass3);
EXPECT(order[0].barriers.size(), 0u);
EXPECT(order[1].barriers.size(), 0u);
EXPECT(order[2].barriers.size(), 1u);
auto& b = order[2].barriers[0];
EXPECT(b.src, scope2);
EXPECT(b.dst, scope3);
EXPECT(b.target, &out3);
EXPECT(graph.check(), true);
}
TEST(cycle) {
FrameGraph graph;
vk::Image img1;
auto& pass = graph.addPass();
auto& out = pass.addOut(syncScopeFlex, img1);
pass.addIn(out, syncScopeFlex);
EXPECT(graph.check(), false);
}
TEST(cycle2) {
FrameGraph graph;
vk::Image img1;
vk::Image img2;
auto& pass1 = graph.addPass();
auto& pass2 = graph.addPass();
auto& out1 = pass1.addOut(syncScopeFlex, img1);
pass2.addIn(out1, syncScopeFlex);
auto& out2 = pass2.addOut(syncScopeFlex, img2);
pass1.addIn(out2, syncScopeFlex);
EXPECT(graph.check(), false);
}
TEST(badDep) {
FrameGraph graph;
vk::Image img1;
auto& pass1 = graph.addPass();
auto& out1 = pass1.addOut(syncScopeFlex, img1);
auto scope2 = SyncScope {
vk::PipelineStageBits::computeShader,
vk::ImageLayout::general,
vk::AccessBits::shaderRead | vk::AccessBits::shaderWrite
};
auto& pass2 = graph.addPass();
auto& out2 = pass2.addInOut(out1, scope2);
auto& pass3 = graph.addPass();
pass3.addIn(out1, syncScopeFlex);
pass3.addIn(out2, syncScopeFlex);
EXPECT(graph.check(), false);
}
| 23.078571
| 58
| 0.692974
|
nyorain
|
b6ffd38232e34a6c633d9472a60fc53d10602b17
| 1,380
|
cpp
|
C++
|
llvm/lib/Target/PTX/PTXRegisterInfo.cpp
|
clairechingching/ScaffCC
|
737ae90f85d9fe79819d66219747d27efa4fa5b9
|
[
"BSD-2-Clause"
] | 3
|
2019-02-12T04:14:39.000Z
|
2020-11-05T08:46:20.000Z
|
llvm/lib/Target/PTX/PTXRegisterInfo.cpp
|
clairechingching/ScaffCC
|
737ae90f85d9fe79819d66219747d27efa4fa5b9
|
[
"BSD-2-Clause"
] | 1
|
2020-02-22T09:59:21.000Z
|
2020-02-22T09:59:21.000Z
|
llvm/lib/Target/PTX/PTXRegisterInfo.cpp
|
clairechingching/ScaffCC
|
737ae90f85d9fe79819d66219747d27efa4fa5b9
|
[
"BSD-2-Clause"
] | 1
|
2020-05-15T12:53:42.000Z
|
2020-05-15T12:53:42.000Z
|
//===-- PTXRegisterInfo.cpp - PTX Register Information --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PTX implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "PTXRegisterInfo.h"
#include "PTX.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define GET_REGINFO_TARGET_DESC
#include "PTXGenRegisterInfo.inc"
using namespace llvm;
PTXRegisterInfo::PTXRegisterInfo(PTXTargetMachine &TM,
const TargetInstrInfo &tii)
// PTX does not have a return address register.
: PTXGenRegisterInfo(0), TII(tii) {
}
void PTXRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator /*II*/,
int /*SPAdj*/,
RegScavenger * /*RS*/) const {
llvm_unreachable("FrameIndex should have been previously eliminated!");
}
| 35.384615
| 80
| 0.588406
|
clairechingching
|
8e05cb6da00cf835ee44dbc77bfd1da9a6871ed1
| 1,217
|
cpp
|
C++
|
L9/17_JavaCpp_/03ObjectsInMemory/c_HeapInstance/1/FooBar.cpp
|
DeirdreHegarty/advanced_OOP
|
e62d8f2274422d3da9064e2576e2adc414eccee1
|
[
"MIT"
] | null | null | null |
L9/17_JavaCpp_/03ObjectsInMemory/c_HeapInstance/1/FooBar.cpp
|
DeirdreHegarty/advanced_OOP
|
e62d8f2274422d3da9064e2576e2adc414eccee1
|
[
"MIT"
] | null | null | null |
L9/17_JavaCpp_/03ObjectsInMemory/c_HeapInstance/1/FooBar.cpp
|
DeirdreHegarty/advanced_OOP
|
e62d8f2274422d3da9064e2576e2adc414eccee1
|
[
"MIT"
] | null | null | null |
/*
//Header file declarations reproduced here
// for quick access
//FooBar.h
class Bar{
public:
void doBarThing();
};
class Foo
{ //The default-access specifier is private in C++
Bar *aBar; //hence 'aBar' pointer is private
public:
virtual ~Foo();
void createBar();
void useBar();
void deleteBar();
};
*/
/*
* IMPORTANT: This is a lesson in how _NOT_ to write your C++
* Object creation/manipulation code.
*/
//[FooBar.cpp]
#include <iostream>
#include "FooBar.h"
using namespace std;
Foo::~Foo(){ // "Destructor"
cout<< "Foo() destructor" << endl;
}
//What happens if you call this twice: i.e. there's no
// garbage-collector in C++
void Foo::createBar(){
cout<<"createBar() running"<<endl;
aBar = new Bar();
}
//What if you call this before calling 'createBar()'?
// What would 'aBar' be pointing to?
void Foo::useBar(){
cout<<"useBar(): calling aBar->doBarThing()"<<endl;
aBar->doBarThing();
}
void Foo::deleteBar(){
cout<<"deleteBar(): delete aBar"<<endl;
delete aBar;
}
void Bar::doBarThing(){
cout<<"Bar::doBarThing()"<<endl;
}
| 23.403846
| 62
| 0.579293
|
DeirdreHegarty
|
8e07241468fe38fce70be538f51e493f0382cfe9
| 17,809
|
cpp
|
C++
|
gmsh/Geo/SOrientedBoundingBox.cpp
|
Poofee/fastFEM
|
14eb626df973e2123604041451912c867ab7188c
|
[
"MIT"
] | 4
|
2019-05-06T09:35:08.000Z
|
2021-05-14T16:26:45.000Z
|
gmsh/Geo/SOrientedBoundingBox.cpp
|
Poofee/fastFEM
|
14eb626df973e2123604041451912c867ab7188c
|
[
"MIT"
] | null | null | null |
gmsh/Geo/SOrientedBoundingBox.cpp
|
Poofee/fastFEM
|
14eb626df973e2123604041451912c867ab7188c
|
[
"MIT"
] | 1
|
2019-06-28T09:23:43.000Z
|
2019-06-28T09:23:43.000Z
|
// Gmsh - Copyright (C) 1997-2019 C. Geuzaine, J.-F. Remacle
//
// See the LICENSE.txt file for license information. Please report all
// issues on https://gitlab.onelab.info/gmsh/gmsh/issues.
//
// Contributor(s):
// Bastien Gorissen
//
#include <algorithm>
#include <cmath>
#include <time.h>
#include "GmshConfig.h"
#include "SOrientedBoundingBox.h"
#include "fullMatrix.h"
#include "SBoundingBox3d.h"
#if defined(HAVE_MESH)
#include "DivideAndConquer.h"
#endif
double SOrientedBoundingRectangle::area() { return size[0] * size[1]; }
SOrientedBoundingRectangle::SOrientedBoundingRectangle()
: center(2, 0.0), size(2, 0.0), axisX(2, 0.0), axisY(2, 0.0)
{
}
void SOrientedBoundingBox::fillp()
{
double dx = 0.5 * size[0];
double dy = 0.5 * size[1];
double dz = 0.5 * size[2];
p1x = center[0] - (axisX[0] * dx) - (axisY[0] * dy) - (axisZ[0] * dz);
p1y = center[1] - (axisX[1] * dx) - (axisY[1] * dy) - (axisZ[1] * dz);
p1z = center[2] - (axisX[2] * dx) - (axisY[2] * dy) - (axisZ[2] * dz);
p2x = center[0] + (axisX[0] * dx) - (axisY[0] * dy) - (axisZ[0] * dz);
p2y = center[1] + (axisX[1] * dx) - (axisY[1] * dy) - (axisZ[1] * dz);
p2z = center[2] + (axisX[2] * dx) - (axisY[2] * dy) - (axisZ[2] * dz);
p3x = center[0] - (axisX[0] * dx) + (axisY[0] * dy) - (axisZ[0] * dz);
p3y = center[1] - (axisX[1] * dx) + (axisY[1] * dy) - (axisZ[1] * dz);
p3z = center[2] - (axisX[2] * dx) + (axisY[2] * dy) - (axisZ[2] * dz);
p4x = center[0] + (axisX[0] * dx) + (axisY[0] * dy) - (axisZ[0] * dz);
p4y = center[1] + (axisX[1] * dx) + (axisY[1] * dy) - (axisZ[1] * dz);
p4z = center[2] + (axisX[2] * dx) + (axisY[2] * dy) - (axisZ[2] * dz);
p5x = center[0] - (axisX[0] * dx) - (axisY[0] * dy) + (axisZ[0] * dz);
p5y = center[1] - (axisX[1] * dx) - (axisY[1] * dy) + (axisZ[1] * dz);
p5z = center[2] - (axisX[2] * dx) - (axisY[2] * dy) + (axisZ[2] * dz);
p6x = center[0] + (axisX[0] * dx) - (axisY[0] * dy) + (axisZ[0] * dz);
p6y = center[1] + (axisX[1] * dx) - (axisY[1] * dy) + (axisZ[1] * dz);
p6z = center[2] + (axisX[2] * dx) - (axisY[2] * dy) + (axisZ[2] * dz);
p7x = center[0] - (axisX[0] * dx) + (axisY[0] * dy) + (axisZ[0] * dz);
p7y = center[1] - (axisX[1] * dx) + (axisY[1] * dy) + (axisZ[1] * dz);
p7z = center[2] - (axisX[2] * dx) + (axisY[2] * dy) + (axisZ[2] * dz);
p8x = center[0] + (axisX[0] * dx) + (axisY[0] * dy) + (axisZ[0] * dz);
p8y = center[1] + (axisX[1] * dx) + (axisY[1] * dy) + (axisZ[1] * dz);
p8z = center[2] + (axisX[2] * dx) + (axisY[2] * dy) + (axisZ[2] * dz);
}
SOrientedBoundingBox::SOrientedBoundingBox()
{
center = SVector3();
size = SVector3();
axisX = SVector3();
axisY = SVector3();
axisZ = SVector3();
fillp();
}
SOrientedBoundingBox::SOrientedBoundingBox(SVector3 ¢er_, double sizeX,
double sizeY, double sizeZ,
const SVector3 &axisX_,
const SVector3 &axisY_,
const SVector3 &axisZ_)
{
center = center_;
size = SVector3(sizeX, sizeY, sizeZ);
axisX = axisX_;
axisX.normalize();
axisY = axisY_;
axisY.normalize();
axisZ = axisZ_;
axisZ.normalize();
fillp();
}
SOrientedBoundingBox::SOrientedBoundingBox(SOrientedBoundingBox *other)
{
size = other->getSize();
axisX = other->getAxis(0);
axisY = other->getAxis(1);
axisZ = other->getAxis(2);
center = other->getCenter();
fillp();
}
SVector3 SOrientedBoundingBox::getAxis(int axis) const
{
SVector3 ret;
switch(axis) {
case 0: ret = axisX; break;
case 1: ret = axisY; break;
case 2: ret = axisZ; break;
}
return ret;
}
bool SOrientedBoundingBox::intersects(SOrientedBoundingBox &obb) const
{
SVector3 collide_axes[15];
for(int i = 0; i < 3; i++) {
collide_axes[i] = getAxis(i);
collide_axes[i + 3] = obb.getAxis(i);
}
SVector3 sizes[2];
sizes[0] = getSize();
sizes[1] = obb.getSize();
for(std::size_t i = 0; i < 3; i++) {
for(std::size_t j = 3; j < 6; j++) {
collide_axes[3 * i + j + 3] = crossprod(collide_axes[i], collide_axes[j]);
}
}
SVector3 T = obb.getCenter() - getCenter();
for(std::size_t i = 0; i < 15; i++) {
double val = 0.0;
for(std::size_t j = 0; j < 6; j++) {
val += 0.5 * (sizes[j < 3 ? 0 : 1])(j % 3) *
std::abs(dot(collide_axes[j], collide_axes[i]));
}
if(std::abs(dot(collide_axes[i], T)) > val) { return false; }
}
return true;
}
SOrientedBoundingBox *
SOrientedBoundingBox::buildOBB(std::vector<SPoint3> &vertices)
{
#if defined(HAVE_MESH)
int num_vertices = vertices.size();
// First organize the data
std::set<SPoint3> unique;
unique.insert(vertices.begin(), vertices.end());
num_vertices = unique.size();
fullMatrix<double> data(3, num_vertices);
fullVector<double> mean(3);
fullVector<double> vmins(3);
fullVector<double> vmaxs(3);
mean.setAll(0);
vmins.setAll(DBL_MAX);
vmaxs.setAll(-DBL_MAX);
size_t idx = 0;
for(std::set<SPoint3>::iterator uIter = unique.begin(); uIter != unique.end();
++uIter) {
const SPoint3 &pp = *uIter;
for(int d = 0; d < 3; d++) {
data(d, idx) = pp[d];
vmins(d) = std::min(vmins(d), pp[d]);
vmaxs(d) = std::max(vmaxs(d), pp[d]);
mean(d) += pp[d];
}
idx++;
}
for(int i = 0; i < 3; i++) { mean(i) /= num_vertices; }
// Get the deviation from the mean
fullMatrix<double> B(3, num_vertices);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < num_vertices; j++) { B(i, j) = data(i, j) - mean(i); }
}
// Compute the covariance matrix
fullMatrix<double> covariance(3, 3);
B.mult(B.transpose(), covariance);
covariance.scale(1. / (num_vertices - 1));
/*
Msg::Debug("Covariance matrix");
Msg::Debug("%f %f %f", covariance(0,0),covariance(0,1),covariance(0,2) );
Msg::Debug("%f %f %f", covariance(1,0),covariance(1,1),covariance(1,2) );
Msg::Debug("%f %f %f", covariance(2,0),covariance(2,1),covariance(2,2) );
*/
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(std::abs(covariance(i, j)) < 10e-16) covariance(i, j) = 0;
}
}
fullMatrix<double> left_eigv(3, 3);
fullMatrix<double> right_eigv(3, 3);
fullVector<double> real_eig(3);
fullVector<double> img_eig(3);
covariance.eig(real_eig, img_eig, left_eigv, right_eigv, true);
// Now, project the data in the new basis.
fullMatrix<double> projected(3, num_vertices);
left_eigv.transpose().mult(data, projected);
// Get the size of the box in the new direction
fullVector<double> mins(3);
fullVector<double> maxs(3);
for(int i = 0; i < 3; i++) {
mins(i) = DBL_MAX;
maxs(i) = -DBL_MAX;
for(int j = 0; j < num_vertices; j++) {
maxs(i) = std::max(maxs(i), projected(i, j));
mins(i) = std::min(mins(i), projected(i, j));
}
}
// double means[3];
double sizes[3];
// Note: the size is computed in the box's coordinates!
for(int i = 0; i < 3; i++) {
sizes[i] = maxs(i) - mins(i);
// means[i] = (maxs(i) - mins(i)) / 2.;
}
if(sizes[0] == 0 && sizes[1] == 0) {
// Entity is a straight line...
SVector3 center;
SVector3 Axis1;
SVector3 Axis2;
SVector3 Axis3;
Axis1[0] = left_eigv(0, 0);
Axis1[1] = left_eigv(1, 0);
Axis1[2] = left_eigv(2, 0);
Axis2[0] = left_eigv(0, 1);
Axis2[1] = left_eigv(1, 1);
Axis2[2] = left_eigv(2, 1);
Axis3[0] = left_eigv(0, 2);
Axis3[1] = left_eigv(1, 2);
Axis3[2] = left_eigv(2, 2);
center[0] = (vmaxs(0) + vmins(0)) / 2.0;
center[1] = (vmaxs(1) + vmins(1)) / 2.0;
center[2] = (vmaxs(2) + vmins(2)) / 2.0;
return new SOrientedBoundingBox(center, sizes[0], sizes[1], sizes[2], Axis1,
Axis2, Axis3);
}
// We take the smallest component, then project the data on the plane defined
// by the other twos
int smallest_comp = 0;
if(sizes[0] <= sizes[1] && sizes[0] <= sizes[2])
smallest_comp = 0;
else if(sizes[1] <= sizes[0] && sizes[1] <= sizes[2])
smallest_comp = 1;
else if(sizes[2] <= sizes[0] && sizes[2] <= sizes[1])
smallest_comp = 2;
// The projection has been done circa line 161.
// We just ignore the coordinate corresponding to smallest_comp.
std::vector<SPoint2 *> points;
for(int i = 0; i < num_vertices; i++) {
SPoint2 *p = new SPoint2(projected(smallest_comp == 0 ? 1 : 0, i),
projected(smallest_comp == 2 ? 1 : 2, i));
bool keep = true;
for(std::vector<SPoint2 *>::iterator point = points.begin();
point != points.end(); point++) {
if(std::abs((*p)[0] - (**point)[0]) < 10e-10 &&
std::abs((*p)[1] - (**point)[1]) < 10e-10) {
keep = false;
break;
}
}
if(keep) { points.push_back(p); }
else {
delete p;
}
}
// Find the convex hull from a delaunay triangulation of the points
DocRecord record(points.size());
record.numPoints = points.size();
srand((unsigned)time(0));
for(std::size_t i = 0; i < points.size(); i++) {
record.points[i].where.h =
points[i]->x() + (10e-6) * sizes[smallest_comp == 0 ? 1 : 0] *
(-0.5 + ((double)rand()) / RAND_MAX);
record.points[i].where.v =
points[i]->y() + (10e-6) * sizes[smallest_comp == 2 ? 1 : 0] *
(-0.5 + ((double)rand()) / RAND_MAX);
record.points[i].adjacent = nullptr;
}
try {
record.MakeMeshWithPoints();
} catch(const char *err) {
Msg::Error("%s", err);
}
std::vector<Segment> convex_hull;
for(int i = 0; i < record.numTriangles; i++) {
Segment segs[3];
segs[0].from = record.triangles[i].a;
segs[0].to = record.triangles[i].b;
segs[1].from = record.triangles[i].b;
segs[1].to = record.triangles[i].c;
segs[2].from = record.triangles[i].c;
segs[2].to = record.triangles[i].a;
for(int j = 0; j < 3; j++) {
bool okay = true;
for(std::vector<Segment>::iterator seg = convex_hull.begin();
seg != convex_hull.end(); seg++) {
if(((*seg).from == segs[j].from && (*seg).from == segs[j].to)
// FIXME:
// || ((*seg).from == segs[j].to && (*seg).from == segs[j].from)
) {
convex_hull.erase(seg);
okay = false;
break;
}
}
if(okay) { convex_hull.push_back(segs[j]); }
}
}
// Now, examinate all the directions given by the edges of the convex hull
// to find the one that lets us build the least-area bounding rectangle for
// then points.
fullVector<double> axis(2);
axis(0) = 1;
axis(1) = 0;
fullVector<double> axis2(2);
axis2(0) = 0;
axis2(1) = 1;
SOrientedBoundingRectangle least_rectangle;
least_rectangle.center[0] = 0.0;
least_rectangle.center[1] = 0.0;
least_rectangle.size[0] = -1.0;
least_rectangle.size[1] = 1.0;
fullVector<double> segment(2);
fullMatrix<double> rotation(2, 2);
for(std::vector<Segment>::iterator seg = convex_hull.begin();
seg != convex_hull.end(); seg++) {
// segment(0) = record.points[(*seg).from].where.h -
// record.points[(*seg).to].where.h; segment(1) =
// record.points[(*seg).from].where.v - record.points[(*seg).to].where.v;
segment(0) = points[(*seg).from]->x() - points[(*seg).to]->x();
segment(1) = points[(*seg).from]->y() - points[(*seg).to]->y();
segment.scale(1.0 / segment.norm());
double cosine = axis(0) * segment(0) + segment(1) * axis(1);
double sine = axis(1) * segment(0) - segment(1) * axis(0);
// double sine = axis(0)*segment(1) - segment(0)*axis(1);
rotation(0, 0) = cosine;
rotation(0, 1) = sine;
rotation(1, 0) = -sine;
rotation(1, 1) = cosine;
// TODO C++11 std::numeric_limits<double>
double max_x = -DBL_MAX;
double min_x = DBL_MAX;
double max_y = -DBL_MAX;
double min_y = DBL_MAX;
for(int i = 0; i < record.numPoints; i++) {
fullVector<double> pnt(2);
// pnt(0) = record.points[i].where.h;
// pnt(1) = record.points[i].where.v;
pnt(0) = points[i]->x();
pnt(1) = points[i]->y();
fullVector<double> rot_pnt(2);
rotation.mult(pnt, rot_pnt);
if(rot_pnt(0) < min_x) min_x = rot_pnt(0);
if(rot_pnt(0) > max_x) max_x = rot_pnt(0);
if(rot_pnt(1) < min_y) min_y = rot_pnt(1);
if(rot_pnt(1) > max_y) max_y = rot_pnt(1);
}
/**/
fullVector<double> center_rot(2);
fullVector<double> center_before_rot(2);
center_before_rot(0) = (max_x + min_x) / 2.0;
center_before_rot(1) = (max_y + min_y) / 2.0;
fullMatrix<double> rotation_inv(2, 2);
rotation_inv(0, 0) = cosine;
rotation_inv(0, 1) = -sine;
rotation_inv(1, 0) = sine;
rotation_inv(1, 1) = cosine;
rotation_inv.mult(center_before_rot, center_rot);
fullVector<double> axis_rot1(2);
fullVector<double> axis_rot2(2);
rotation_inv.mult(axis, axis_rot1);
rotation_inv.mult(axis2, axis_rot2);
if((least_rectangle.area() == -1) ||
(max_x - min_x) * (max_y - min_y) < least_rectangle.area()) {
least_rectangle.size[0] = max_x - min_x;
least_rectangle.size[1] = max_y - min_y;
least_rectangle.center[0] = (max_x + min_x) / 2.0;
least_rectangle.center[1] = (max_y + min_y) / 2.0;
least_rectangle.center[0] = center_rot(0);
least_rectangle.center[1] = center_rot(1);
least_rectangle.axisX[0] = axis_rot1(0);
least_rectangle.axisX[1] = axis_rot1(1);
// least_rectangle.axisX[0] = segment(0);
// least_rectangle.axisX[1] = segment(1);
least_rectangle.axisY[0] = axis_rot2(0);
least_rectangle.axisY[1] = axis_rot2(1);
}
}
// TODO C++11 std::numeric_limits<double>::min() / max()
double min_pca = DBL_MAX;
double max_pca = -DBL_MAX;
for(int i = 0; i < num_vertices; i++) {
min_pca = std::min(min_pca, projected(smallest_comp, i));
max_pca = std::max(max_pca, projected(smallest_comp, i));
}
double center_pca = (max_pca + min_pca) / 2.0;
double size_pca = (max_pca - min_pca);
double raw_data[3][5];
raw_data[0][0] = size_pca;
raw_data[1][0] = least_rectangle.size[0];
raw_data[2][0] = least_rectangle.size[1];
raw_data[0][1] = center_pca;
raw_data[1][1] = least_rectangle.center[0];
raw_data[2][1] = least_rectangle.center[1];
for(int i = 0; i < 3; i++) {
raw_data[0][2 + i] = left_eigv(i, smallest_comp);
raw_data[1][2 + i] =
least_rectangle.axisX[0] * left_eigv(i, smallest_comp == 0 ? 1 : 0) +
least_rectangle.axisX[1] * left_eigv(i, smallest_comp == 2 ? 1 : 2);
raw_data[2][2 + i] =
least_rectangle.axisY[0] * left_eigv(i, smallest_comp == 0 ? 1 : 0) +
least_rectangle.axisY[1] * left_eigv(i, smallest_comp == 2 ? 1 : 2);
}
// Msg::Info("Test 1 : %f
// %f",least_rectangle.center[0],least_rectangle.center[1]);
// Msg::Info("Test 2 : %f
// %f",least_rectangle.axisY[0],least_rectangle.axisY[1]);
int tri[3];
if(size_pca > least_rectangle.size[0]) {
// P > R0
if(size_pca > least_rectangle.size[1]) {
// P > R1
tri[0] = 0;
if(least_rectangle.size[0] > least_rectangle.size[1]) {
// R0 > R1
tri[1] = 1;
tri[2] = 2;
}
else {
// R1 > R0
tri[1] = 2;
tri[2] = 1;
}
}
else {
// P < R1
tri[0] = 2;
tri[1] = 0;
tri[2] = 1;
}
}
else { // P < R0
if(size_pca < least_rectangle.size[1]) {
// P < R1
tri[2] = 0;
if(least_rectangle.size[0] > least_rectangle.size[1]) {
tri[0] = 1;
tri[1] = 2;
}
else {
tri[0] = 2;
tri[1] = 1;
}
}
else {
tri[0] = 1;
tri[1] = 0;
tri[2] = 2;
}
}
SVector3 size;
SVector3 center;
SVector3 Axis1;
SVector3 Axis2;
SVector3 Axis3;
for(int i = 0; i < 3; i++) {
size[i] = raw_data[tri[i]][0];
center[i] = raw_data[tri[i]][1];
Axis1[i] = raw_data[tri[0]][2 + i];
Axis2[i] = raw_data[tri[1]][2 + i];
Axis3[i] = raw_data[tri[2]][2 + i];
}
SVector3 aux1;
SVector3 aux2;
SVector3 aux3;
for(int i = 0; i < 3; i++) {
aux1(i) = left_eigv(i, smallest_comp);
aux2(i) = left_eigv(i, smallest_comp == 0 ? 1 : 0);
aux3(i) = left_eigv(i, smallest_comp == 2 ? 1 : 2);
}
center = aux1 * center_pca + aux2 * least_rectangle.center[0] +
aux3 * least_rectangle.center[1];
// center[1] = -center[1];
/*
Msg::Info("Box center : %f %f %f",center[0],center[1],center[2]);
Msg::Info("Box size : %f %f %f",size[0],size[1],size[2]);
Msg::Info("Box axis 1 : %f %f %f",Axis1[0],Axis1[1],Axis1[2]);
Msg::Info("Box axis 2 : %f %f %f",Axis2[0],Axis2[1],Axis2[2]);
Msg::Info("Box axis 3 : %f %f %f",Axis3[0],Axis3[1],Axis3[2]);
Msg::Info("Volume : %f", size[0]*size[1]*size[2]);
*/
return new SOrientedBoundingBox(center, size[0], size[1], size[2], Axis1,
Axis2, Axis3);
#else
Msg::Error("SOrientedBoundingBox requires mesh module");
return 0;
#endif
}
double SOrientedBoundingBox::compare(SOrientedBoundingBox &obb1,
SOrientedBoundingBox &obb2)
{
// "center term"
double center_term = norm(obb1.getCenter() - obb2.getCenter());
// "size term"
double size_term = 0.0;
for(int i = 0; i < 3; i++) {
if(obb1.getSize()(i) + obb2.getSize()(i) != 0) {
size_term += std::abs(obb1.getSize()(i) - obb2.getSize()(i)) /
(obb1.getSize()(i) + obb2.getSize()(i));
}
}
// "orientation term"
double orientation_term = 0.0;
for(int i = 0; i < 3; i++) {
orientation_term += 1 - std::abs(dot(obb1.getAxis(i), obb2.getAxis(i)));
}
return center_term + size_term + orientation_term;
}
| 30.758204
| 80
| 0.563479
|
Poofee
|
8e07633464a0d666535aa331121e742093136dfd
| 21,396
|
cc
|
C++
|
PhysicsTools/Heppy/src/Davismt2.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 852
|
2015-01-11T21:03:51.000Z
|
2022-03-25T21:14:00.000Z
|
PhysicsTools/Heppy/src/Davismt2.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 30,371
|
2015-01-02T00:14:40.000Z
|
2022-03-31T23:26:05.000Z
|
PhysicsTools/Heppy/src/Davismt2.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 3,240
|
2015-01-02T05:53:18.000Z
|
2022-03-31T17:24:21.000Z
|
// #ifndef MT2_BISECT_C
// #define MT2_BISECT_C
/***********************************************************************/
/* */
/* Finding mt2 by Bisection */
/* */
/* Authors: Hsin-Chia Cheng, Zhenyu Han */
/* Dec 11, 2008, v1.01a */
/* */
/***********************************************************************/
/*******************************************************************************
Usage:
1. Define an object of type "mt2":
mt2_bisect::mt2 mt2_event;
2. Set momenta and the mass of the invisible particle, mn:
mt2_event.set_momenta( pa, pb, pmiss );
mt2_event.set_mass( mn );
where array pa[0..2], pb[0..2], pmiss[0..2] contains (mass,px,py)
for the visible particles and the missing momentum. pmiss[0] is not used.
All quantities are given in double.
3. Use Davismt2::get_mt2() to obtain the value of mt2:
double mt2_value = mt2_event.get_mt2();
*******************************************************************************/
#include "PhysicsTools/Heppy/interface/Davismt2.h"
// ClassImp(Davismt2);
using namespace std;
namespace heppy {
/*The user can change the desired precision below, the larger one of the following two definitions is used. Relative precision less than 0.00001 is not guaranteed to be
achievable--use with caution*/
const float Davismt2::RELATIVE_PRECISION = 0.00001;
const float Davismt2::ABSOLUTE_PRECISION = 0.0;
const float Davismt2::ZERO_MASS = 0.0;
const float Davismt2::MIN_MASS = 0.1;
const float Davismt2::SCANSTEP = 0.1;
Davismt2::Davismt2() {
solved = false;
momenta_set = false;
mt2_b = 0.;
scale = 1.;
verbose = 1;
}
Davismt2::~Davismt2() {}
double Davismt2::get_mt2() {
if (!momenta_set) {
cout << "Davismt2::get_mt2() ==> Please set momenta first!" << endl;
return 0;
}
if (!solved)
mt2_bisect();
return mt2_b * scale;
}
void Davismt2::set_momenta(double* pa0, double* pb0, double* pmiss0) {
solved = false; //reset solved tag when momenta are changed.
momenta_set = true;
ma = fabs(pa0[0]); // mass cannot be negative
if (ma < ZERO_MASS)
ma = ZERO_MASS;
pax = pa0[1];
pay = pa0[2];
masq = ma * ma;
Easq = masq + pax * pax + pay * pay;
Ea = sqrt(Easq);
mb = fabs(pb0[0]);
if (mb < ZERO_MASS)
mb = ZERO_MASS;
pbx = pb0[1];
pby = pb0[2];
mbsq = mb * mb;
Ebsq = mbsq + pbx * pbx + pby * pby;
Eb = sqrt(Ebsq);
pmissx = pmiss0[1];
pmissy = pmiss0[2];
pmissxsq = pmissx * pmissx;
pmissysq = pmissy * pmissy;
// set ma>= mb
if (masq < mbsq) {
double temp;
temp = pax;
pax = pbx;
pbx = temp;
temp = pay;
pay = pby;
pby = temp;
temp = Ea;
Ea = Eb;
Eb = temp;
temp = Easq;
Easq = Ebsq;
Ebsq = temp;
temp = masq;
masq = mbsq;
mbsq = temp;
temp = ma;
ma = mb;
mb = temp;
}
//normalize max{Ea, Eb} to 100
if (Ea > Eb)
scale = Ea / 100.;
else
scale = Eb / 100.;
if (sqrt(pmissxsq + pmissysq) / 100 > scale)
scale = sqrt(pmissxsq + pmissysq) / 100;
//scale = 1;
double scalesq = scale * scale;
ma = ma / scale;
mb = mb / scale;
masq = masq / scalesq;
mbsq = mbsq / scalesq;
pax = pax / scale;
pay = pay / scale;
pbx = pbx / scale;
pby = pby / scale;
Ea = Ea / scale;
Eb = Eb / scale;
Easq = Easq / scalesq;
Ebsq = Ebsq / scalesq;
pmissx = pmissx / scale;
pmissy = pmissy / scale;
pmissxsq = pmissxsq / scalesq;
pmissysq = pmissysq / scalesq;
mn = mn_unscale / scale;
mnsq = mn * mn;
if (ABSOLUTE_PRECISION > 100. * RELATIVE_PRECISION)
precision = ABSOLUTE_PRECISION;
else
precision = 100. * RELATIVE_PRECISION;
}
void Davismt2::set_mn(double mn0) {
solved = false; //reset solved tag when mn is changed.
mn_unscale = fabs(mn0); //mass cannot be negative
mn = mn_unscale / scale;
mnsq = mn * mn;
}
void Davismt2::print() {
cout << " Davismt2::print() ==> pax = " << pax * scale << "; pay = " << pay * scale << "; ma = " << ma * scale
<< ";" << endl;
cout << " Davismt2::print() ==> pbx = " << pbx * scale << "; pby = " << pby * scale << "; mb = " << mb * scale
<< ";" << endl;
cout << " Davismt2::print() ==> pmissx = " << pmissx * scale << "; pmissy = " << pmissy * scale << ";" << endl;
cout << " Davismt2::print() ==> mn = " << mn_unscale << ";" << endl;
}
//special case, the visible particle is massless
void Davismt2::mt2_massless() {
//rotate so that pay = 0
double theta, s, c;
theta = atan(pay / pax);
s = sin(theta);
c = cos(theta);
double pxtemp, pytemp;
Easq = pax * pax + pay * pay;
Ebsq = pbx * pbx + pby * pby;
Ea = sqrt(Easq);
Eb = sqrt(Ebsq);
pxtemp = pax * c + pay * s;
pax = pxtemp;
pay = 0;
pxtemp = pbx * c + pby * s;
pytemp = -s * pbx + c * pby;
pbx = pxtemp;
pby = pytemp;
pxtemp = pmissx * c + pmissy * s;
pytemp = -s * pmissx + c * pmissy;
pmissx = pxtemp;
pmissy = pytemp;
a2 = 1 - pbx * pbx / (Ebsq);
b2 = -pbx * pby / (Ebsq);
c2 = 1 - pby * pby / (Ebsq);
d21 = (Easq * pbx) / Ebsq;
d20 = -pmissx + (pbx * (pbx * pmissx + pby * pmissy)) / Ebsq;
e21 = (Easq * pby) / Ebsq;
e20 = -pmissy + (pby * (pbx * pmissx + pby * pmissy)) / Ebsq;
f22 = -(Easq * Easq / Ebsq);
f21 = -2 * Easq * (pbx * pmissx + pby * pmissy) / Ebsq;
f20 = mnsq + pmissxsq + pmissysq - (pbx * pmissx + pby * pmissy) * (pbx * pmissx + pby * pmissy) / Ebsq;
double Deltasq0 = 0;
double Deltasq_low, Deltasq_high;
int nsols_high, nsols_low;
Deltasq_low = Deltasq0 + precision;
nsols_low = nsols_massless(Deltasq_low);
if (nsols_low > 1) {
mt2_b = (double)sqrt(Deltasq0 + mnsq);
return;
}
/*
if( nsols_massless(Deltasq_high) > 0 )
{
mt2_b = (double) sqrt(mnsq+Deltasq0);
return;
}*/
//look for when both parablos contain origin
double Deltasq_high1, Deltasq_high2;
Deltasq_high1 = 2 * Eb * sqrt(pmissx * pmissx + pmissy * pmissy + mnsq) - 2 * pbx * pmissx - 2 * pby * pmissy;
Deltasq_high2 = 2 * Ea * mn;
if (Deltasq_high1 < Deltasq_high2)
Deltasq_high = Deltasq_high2;
else
Deltasq_high = Deltasq_high1;
nsols_high = nsols_massless(Deltasq_high);
int foundhigh;
if (nsols_high == nsols_low) {
foundhigh = 0;
double minmass, maxmass;
minmass = mn;
maxmass = sqrt(mnsq + Deltasq_high);
for (double mass = minmass + SCANSTEP; mass < maxmass; mass += SCANSTEP) {
Deltasq_high = mass * mass - mnsq;
nsols_high = nsols_massless(Deltasq_high);
if (nsols_high > 0) {
foundhigh = 1;
Deltasq_low = (mass - SCANSTEP) * (mass - SCANSTEP) - mnsq;
break;
}
}
if (foundhigh == 0) {
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> Deltasq_high not found at event " << nevt << endl;
mt2_b = (double)sqrt(Deltasq_low + mnsq);
return;
}
}
if (nsols_high == nsols_low) {
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> error: nsols_low=nsols_high=" << nsols_high << endl;
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> Deltasq_high=" << Deltasq_high << endl;
if (verbose > 0)
cout << "Davismt2::mt2_massless() ==> Deltasq_low= " << Deltasq_low << endl;
mt2_b = sqrt(mnsq + Deltasq_low);
return;
}
double minmass, maxmass;
minmass = sqrt(Deltasq_low + mnsq);
maxmass = sqrt(Deltasq_high + mnsq);
while (maxmass - minmass > precision) {
double Delta_mid, midmass, nsols_mid;
midmass = (minmass + maxmass) / 2.;
Delta_mid = midmass * midmass - mnsq;
nsols_mid = nsols_massless(Delta_mid);
if (nsols_mid != nsols_low)
maxmass = midmass;
if (nsols_mid == nsols_low)
minmass = midmass;
}
mt2_b = minmass;
return;
}
int Davismt2::nsols_massless(double Dsq) {
double delta;
delta = Dsq / (2 * Easq);
d1 = d11 * delta;
e1 = e11 * delta;
f1 = f12 * delta * delta + f10;
d2 = d21 * delta + d20;
e2 = e21 * delta + e20;
f2 = f22 * delta * delta + f21 * delta + f20;
double a, b;
if (pax > 0)
a = Ea / Dsq;
else
a = -Ea / Dsq;
if (pax > 0)
b = -Dsq / (4 * Ea) + mnsq * Ea / Dsq;
else
b = Dsq / (4 * Ea) - mnsq * Ea / Dsq;
double A4, A3, A2, A1, A0;
A4 = a * a * a2;
A3 = 2 * a * b2 / Ea;
A2 = (2 * a * a2 * b + c2 + 2 * a * d2) / (Easq);
A1 = (2 * b * b2 + 2 * e2) / (Easq * Ea);
A0 = (a2 * b * b + 2 * b * d2 + f2) / (Easq * Easq);
long double A3sq;
A3sq = A3 * A3;
/*
long double A0sq, A1sq, A2sq, A3sq, A4sq;
A0sq = A0*A0;
A1sq = A1*A1;
A2sq = A2*A2;
A3sq = A3*A3;
A4sq = A4*A4;
*/
long double B3, B2, B1, B0;
B3 = 4 * A4;
B2 = 3 * A3;
B1 = 2 * A2;
B0 = A1;
long double C2, C1, C0;
C2 = -(A2 / 2 - 3 * A3sq / (16 * A4));
C1 = -(3 * A1 / 4. - A2 * A3 / (8 * A4));
C0 = -A0 + A1 * A3 / (16 * A4);
long double D1, D0;
D1 = -B1 - (B3 * C1 * C1 / C2 - B3 * C0 - B2 * C1) / C2;
D0 = -B0 - B3 * C0 * C1 / (C2 * C2) + B2 * C0 / C2;
long double E0;
E0 = -C0 - C2 * D0 * D0 / (D1 * D1) + C1 * D0 / D1;
long double t1, t2, t3, t4, t5;
//find the coefficients for the leading term in the Sturm sequence
t1 = A4;
t2 = A4;
t3 = C2;
t4 = D1;
t5 = E0;
int nsol;
nsol = signchange_n(t1, t2, t3, t4, t5) - signchange_p(t1, t2, t3, t4, t5);
if (nsol < 0)
nsol = 0;
return nsol;
}
void Davismt2::mt2_bisect() {
solved = true;
cout.precision(11);
//if masses are very small, use code for massless case.
if (masq < MIN_MASS && mbsq < MIN_MASS) {
mt2_massless();
return;
}
double Deltasq0;
Deltasq0 = ma * (ma + 2 * mn); //The minimum mass square to have two ellipses
// find the coefficients for the two quadratic equations when Deltasq=Deltasq0.
a1 = 1 - pax * pax / (Easq);
b1 = -pax * pay / (Easq);
c1 = 1 - pay * pay / (Easq);
d1 = -pax * (Deltasq0 - masq) / (2 * Easq);
e1 = -pay * (Deltasq0 - masq) / (2 * Easq);
a2 = 1 - pbx * pbx / (Ebsq);
b2 = -pbx * pby / (Ebsq);
c2 = 1 - pby * pby / (Ebsq);
d2 = -pmissx + pbx * (Deltasq0 - mbsq) / (2 * Ebsq) + pbx * (pbx * pmissx + pby * pmissy) / (Ebsq);
e2 = -pmissy + pby * (Deltasq0 - mbsq) / (2 * Ebsq) + pby * (pbx * pmissx + pby * pmissy) / (Ebsq);
f2 = pmissx * pmissx + pmissy * pmissy -
((Deltasq0 - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) *
((Deltasq0 - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) +
mnsq;
// find the center of the smaller ellipse
double x0, y0;
x0 = (c1 * d1 - b1 * e1) / (b1 * b1 - a1 * c1);
y0 = (a1 * e1 - b1 * d1) / (b1 * b1 - a1 * c1);
// Does the larger ellipse contain the smaller one?
double dis = a2 * x0 * x0 + 2 * b2 * x0 * y0 + c2 * y0 * y0 + 2 * d2 * x0 + 2 * e2 * y0 + f2;
if (dis <= 0.01) {
mt2_b = (double)sqrt(mnsq + Deltasq0);
return;
}
/* find the coefficients for the two quadratic equations */
/* coefficients for quadratic terms do not change */
/* coefficients for linear and constant terms are polynomials of */
/* delta=(Deltasq-m7sq)/(2 E7sq) */
d11 = -pax;
e11 = -pay;
f10 = mnsq;
f12 = -Easq;
d21 = (Easq * pbx) / Ebsq;
d20 = ((masq - mbsq) * pbx) / (2. * Ebsq) - pmissx + (pbx * (pbx * pmissx + pby * pmissy)) / Ebsq;
e21 = (Easq * pby) / Ebsq;
e20 = ((masq - mbsq) * pby) / (2. * Ebsq) - pmissy + (pby * (pbx * pmissx + pby * pmissy)) / Ebsq;
f22 = -Easq * Easq / Ebsq;
f21 = (-2 * Easq * ((masq - mbsq) / (2. * Eb) + (pbx * pmissx + pby * pmissy) / Eb)) / Eb;
f20 = mnsq + pmissx * pmissx + pmissy * pmissy -
((masq - mbsq) / (2. * Eb) + (pbx * pmissx + pby * pmissy) / Eb) *
((masq - mbsq) / (2. * Eb) + (pbx * pmissx + pby * pmissy) / Eb);
//Estimate upper bound of mT2
//when Deltasq > Deltasq_high1, the larger encloses the center of the smaller
double p2x0, p2y0;
double Deltasq_high1;
p2x0 = pmissx - x0;
p2y0 = pmissy - y0;
Deltasq_high1 = 2 * Eb * sqrt(p2x0 * p2x0 + p2y0 * p2y0 + mnsq) - 2 * pbx * p2x0 - 2 * pby * p2y0 + mbsq;
//Another estimate, if both ellipses enclose the origin, Deltasq > mT2
double Deltasq_high2, Deltasq_high21, Deltasq_high22;
Deltasq_high21 =
2 * Eb * sqrt(pmissx * pmissx + pmissy * pmissy + mnsq) - 2 * pbx * pmissx - 2 * pby * pmissy + mbsq;
Deltasq_high22 = 2 * Ea * mn + masq;
if (Deltasq_high21 < Deltasq_high22)
Deltasq_high2 = Deltasq_high22;
else
Deltasq_high2 = Deltasq_high21;
//pick the smaller upper bound
double Deltasq_high;
if (Deltasq_high1 < Deltasq_high2)
Deltasq_high = Deltasq_high1;
else
Deltasq_high = Deltasq_high2;
double Deltasq_low; //lower bound
Deltasq_low = Deltasq0;
//number of solutions at Deltasq_low should not be larger than zero
if (nsols(Deltasq_low) > 0) {
//cout << "Davismt2::mt2_bisect() ==> nsolutions(Deltasq_low) > 0"<<endl;
mt2_b = (double)sqrt(mnsq + Deltasq0);
return;
}
int nsols_high, nsols_low;
nsols_low = nsols(Deltasq_low);
int foundhigh;
//if nsols_high=nsols_low, we missed the region where the two ellipse overlap
//if nsols_high=4, also need a scan because we may find the wrong tangent point.
nsols_high = nsols(Deltasq_high);
if (nsols_high == nsols_low || nsols_high == 4) {
//foundhigh = scan_high(Deltasq_high);
foundhigh = find_high(Deltasq_high);
if (foundhigh == 0) {
if (verbose > 0)
cout << "Davismt2::mt2_bisect() ==> Deltasq_high not found at event " << nevt << endl;
mt2_b = sqrt(Deltasq_low + mnsq);
return;
}
}
while (sqrt(Deltasq_high + mnsq) - sqrt(Deltasq_low + mnsq) > precision) {
double Deltasq_mid, nsols_mid;
//bisect
Deltasq_mid = (Deltasq_high + Deltasq_low) / 2.;
nsols_mid = nsols(Deltasq_mid);
// if nsols_mid = 4, rescan for Deltasq_high
if (nsols_mid == 4) {
Deltasq_high = Deltasq_mid;
//scan_high(Deltasq_high);
find_high(Deltasq_high);
continue;
}
if (nsols_mid != nsols_low)
Deltasq_high = Deltasq_mid;
if (nsols_mid == nsols_low)
Deltasq_low = Deltasq_mid;
}
mt2_b = (double)sqrt(mnsq + Deltasq_high);
return;
}
int Davismt2::find_high(double& Deltasq_high) {
double x0, y0;
x0 = (c1 * d1 - b1 * e1) / (b1 * b1 - a1 * c1);
y0 = (a1 * e1 - b1 * d1) / (b1 * b1 - a1 * c1);
double Deltasq_low = (mn + ma) * (mn + ma) - mnsq;
do {
double Deltasq_mid = (Deltasq_high + Deltasq_low) / 2.;
int nsols_mid = nsols(Deltasq_mid);
if (nsols_mid == 2) {
Deltasq_high = Deltasq_mid;
return 1;
} else if (nsols_mid == 4) {
Deltasq_high = Deltasq_mid;
continue;
} else if (nsols_mid == 0) {
d1 = -pax * (Deltasq_mid - masq) / (2 * Easq);
e1 = -pay * (Deltasq_mid - masq) / (2 * Easq);
d2 = -pmissx + pbx * (Deltasq_mid - mbsq) / (2 * Ebsq) + pbx * (pbx * pmissx + pby * pmissy) / (Ebsq);
e2 = -pmissy + pby * (Deltasq_mid - mbsq) / (2 * Ebsq) + pby * (pbx * pmissx + pby * pmissy) / (Ebsq);
f2 = pmissx * pmissx + pmissy * pmissy -
((Deltasq_mid - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) *
((Deltasq_mid - mbsq) / (2 * Eb) + (pbx * pmissx + pby * pmissy) / Eb) +
mnsq;
// Does the larger ellipse contain the smaller one?
double dis = a2 * x0 * x0 + 2 * b2 * x0 * y0 + c2 * y0 * y0 + 2 * d2 * x0 + 2 * e2 * y0 + f2;
if (dis < 0)
Deltasq_high = Deltasq_mid;
else
Deltasq_low = Deltasq_mid;
}
} while (Deltasq_high - Deltasq_low > 0.001);
return 0;
}
int Davismt2::scan_high(double& Deltasq_high) {
int foundhigh = 0;
int nsols_high;
// double Deltasq_low;
double tempmass, maxmass;
tempmass = mn + ma;
maxmass = sqrt(mnsq + Deltasq_high);
if (nevt == 32334)
cout << "Davismt2::scan_high() ==> Deltasq_high = " << Deltasq_high << endl; // ???
for (double mass = tempmass + SCANSTEP; mass < maxmass; mass += SCANSTEP) {
Deltasq_high = mass * mass - mnsq;
nsols_high = nsols(Deltasq_high);
if (nsols_high > 0) {
// Deltasq_low = (mass-SCANSTEP)*(mass-SCANSTEP) - mnsq;
foundhigh = 1;
break;
}
}
return foundhigh;
}
int Davismt2::nsols(double Dsq) {
double delta = (Dsq - masq) / (2 * Easq);
//calculate coefficients for the two quadratic equations
d1 = d11 * delta;
e1 = e11 * delta;
f1 = f12 * delta * delta + f10;
d2 = d21 * delta + d20;
e2 = e21 * delta + e20;
f2 = f22 * delta * delta + f21 * delta + f20;
//obtain the coefficients for the 4th order equation
//devided by Ea^n to make the variable dimensionless
long double A4, A3, A2, A1, A0;
A4 = -4 * a2 * b1 * b2 * c1 + 4 * a1 * b2 * b2 * c1 + a2 * a2 * c1 * c1 + 4 * a2 * b1 * b1 * c2 -
4 * a1 * b1 * b2 * c2 - 2 * a1 * a2 * c1 * c2 + a1 * a1 * c2 * c2;
A3 = (-4 * a2 * b2 * c1 * d1 + 8 * a2 * b1 * c2 * d1 - 4 * a1 * b2 * c2 * d1 - 4 * a2 * b1 * c1 * d2 +
8 * a1 * b2 * c1 * d2 - 4 * a1 * b1 * c2 * d2 - 8 * a2 * b1 * b2 * e1 + 8 * a1 * b2 * b2 * e1 +
4 * a2 * a2 * c1 * e1 - 4 * a1 * a2 * c2 * e1 + 8 * a2 * b1 * b1 * e2 - 8 * a1 * b1 * b2 * e2 -
4 * a1 * a2 * c1 * e2 + 4 * a1 * a1 * c2 * e2) /
Ea;
A2 = (4 * a2 * c2 * d1 * d1 - 4 * a2 * c1 * d1 * d2 - 4 * a1 * c2 * d1 * d2 + 4 * a1 * c1 * d2 * d2 -
8 * a2 * b2 * d1 * e1 - 8 * a2 * b1 * d2 * e1 + 16 * a1 * b2 * d2 * e1 + 4 * a2 * a2 * e1 * e1 +
16 * a2 * b1 * d1 * e2 - 8 * a1 * b2 * d1 * e2 - 8 * a1 * b1 * d2 * e2 - 8 * a1 * a2 * e1 * e2 +
4 * a1 * a1 * e2 * e2 - 4 * a2 * b1 * b2 * f1 + 4 * a1 * b2 * b2 * f1 + 2 * a2 * a2 * c1 * f1 -
2 * a1 * a2 * c2 * f1 + 4 * a2 * b1 * b1 * f2 - 4 * a1 * b1 * b2 * f2 - 2 * a1 * a2 * c1 * f2 +
2 * a1 * a1 * c2 * f2) /
Easq;
A1 = (-8 * a2 * d1 * d2 * e1 + 8 * a1 * d2 * d2 * e1 + 8 * a2 * d1 * d1 * e2 - 8 * a1 * d1 * d2 * e2 -
4 * a2 * b2 * d1 * f1 - 4 * a2 * b1 * d2 * f1 + 8 * a1 * b2 * d2 * f1 + 4 * a2 * a2 * e1 * f1 -
4 * a1 * a2 * e2 * f1 + 8 * a2 * b1 * d1 * f2 - 4 * a1 * b2 * d1 * f2 - 4 * a1 * b1 * d2 * f2 -
4 * a1 * a2 * e1 * f2 + 4 * a1 * a1 * e2 * f2) /
(Easq * Ea);
A0 = (-4 * a2 * d1 * d2 * f1 + 4 * a1 * d2 * d2 * f1 + a2 * a2 * f1 * f1 + 4 * a2 * d1 * d1 * f2 -
4 * a1 * d1 * d2 * f2 - 2 * a1 * a2 * f1 * f2 + a1 * a1 * f2 * f2) /
(Easq * Easq);
long double A3sq;
/*
long double A0sq, A1sq, A2sq, A3sq, A4sq;
A0sq = A0*A0;
A1sq = A1*A1;
A2sq = A2*A2;
A4sq = A4*A4;
*/
A3sq = A3 * A3;
long double B3, B2, B1, B0;
B3 = 4 * A4;
B2 = 3 * A3;
B1 = 2 * A2;
B0 = A1;
long double C2, C1, C0;
C2 = -(A2 / 2 - 3 * A3sq / (16 * A4));
C1 = -(3 * A1 / 4. - A2 * A3 / (8 * A4));
C0 = -A0 + A1 * A3 / (16 * A4);
long double D1, D0;
D1 = -B1 - (B3 * C1 * C1 / C2 - B3 * C0 - B2 * C1) / C2;
D0 = -B0 - B3 * C0 * C1 / (C2 * C2) + B2 * C0 / C2;
long double E0;
E0 = -C0 - C2 * D0 * D0 / (D1 * D1) + C1 * D0 / D1;
long double t1, t2, t3, t4, t5;
//find the coefficients for the leading term in the Sturm sequence
t1 = A4;
t2 = A4;
t3 = C2;
t4 = D1;
t5 = E0;
//The number of solutions depends on diffence of number of sign changes for x->Inf and x->-Inf
int nsol;
nsol = signchange_n(t1, t2, t3, t4, t5) - signchange_p(t1, t2, t3, t4, t5);
//Cannot have negative number of solutions, must be roundoff effect
if (nsol < 0)
nsol = 0;
return nsol;
}
//inline
int Davismt2::signchange_n(long double t1, long double t2, long double t3, long double t4, long double t5) {
int nsc;
nsc = 0;
if (t1 * t2 > 0)
nsc++;
if (t2 * t3 > 0)
nsc++;
if (t3 * t4 > 0)
nsc++;
if (t4 * t5 > 0)
nsc++;
return nsc;
}
//inline
int Davismt2::signchange_p(long double t1, long double t2, long double t3, long double t4, long double t5) {
int nsc;
nsc = 0;
if (t1 * t2 < 0)
nsc++;
if (t2 * t3 < 0)
nsc++;
if (t3 * t4 < 0)
nsc++;
if (t4 * t5 < 0)
nsc++;
return nsc;
}
} // namespace heppy
| 31.008696
| 171
| 0.509348
|
ckamtsikis
|
8e07bad7c48cced67ed1bb63bfa534f09f6a4132
| 1,964
|
hpp
|
C++
|
dev/Basic/long/database/entity/DevelopmentPlan.hpp
|
gusugusu1018/simmobility-prod
|
d30a5ba353673f8fd35f4868c26994a0206a40b6
|
[
"MIT"
] | 50
|
2018-12-21T08:21:38.000Z
|
2022-01-24T09:47:59.000Z
|
dev/Basic/long/database/entity/DevelopmentPlan.hpp
|
gusugusu1018/simmobility-prod
|
d30a5ba353673f8fd35f4868c26994a0206a40b6
|
[
"MIT"
] | 2
|
2018-12-19T13:42:47.000Z
|
2019-05-13T04:11:45.000Z
|
dev/Basic/long/database/entity/DevelopmentPlan.hpp
|
gusugusu1018/simmobility-prod
|
d30a5ba353673f8fd35f4868c26994a0206a40b6
|
[
"MIT"
] | 27
|
2018-11-28T07:30:34.000Z
|
2022-02-05T02:22:26.000Z
|
/*
* DevelopmentPlan.hpp
*
* Created on: Dec 22, 2015
* Author: gishara
*/
#pragma once
#include "Common.hpp"
#include "Types.hpp"
namespace sim_mob {
namespace long_term {
class DevelopmentPlan {
public:
DevelopmentPlan(BigSerial fmParcelId = INVALID_ID, BigSerial templateId = INVALID_ID,int unitTypeId = 0, int numUnits = 0, std::tm simulationDate = std::tm(), std::tm constructionStartDate = std::tm(), std::tm launchDate = std::tm());
virtual ~DevelopmentPlan();
DevelopmentPlan( const DevelopmentPlan &source);
/**
* Assign operator.
* @param source to assign.
* @return DevelopmentPlan instance reference.
*/
DevelopmentPlan& operator=(const DevelopmentPlan& source);
/**
* Getters and Setters
*/
BigSerial getFmParcelId() const;
int getNumUnits() const;
const std::tm& getSimulationDate() const;
int getUnitTypeId() const;
const std::tm& getLaunchDate() const;
const std::tm& getConstructionStartDate() const;
BigSerial getTemplateId() const;
void setFmParcelId(BigSerial fmParcelId);
void setNumUnits(int numUnits);
void setSimulationDate(const std::tm& simulationDate);
void setUnitTypeId(int unitTypeId);
void setLaunchDate(const std::tm& launchDate);
void setConstructionStartDate(const std::tm& constructionStartDate) ;
void setTemplateId(BigSerial templateId);
private:
friend class DevelopmentPlanDao;
private:
BigSerial fmParcelId;
BigSerial templateId;
int unitTypeId;
int numUnits;
std::tm simulationDate;
std::tm constructionStartDate;
std::tm launchDate;
};
}
}
| 31.677419
| 246
| 0.586049
|
gusugusu1018
|
8e088785a57c9cdd56c5d1336d4b561c74e6883d
| 5,064
|
cxx
|
C++
|
TOF/TOFbase/AliTOFRawMap.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
TOF/TOFbase/AliTOFRawMap.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
TOF/TOFbase/AliTOFRawMap.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////////////////
// //
// AliTOFRawMap class //
// //
// It enables fast check if the TDC channel was already engaged //
// for a measurement. //
// The index of a AliTOFrawData is saved in the each rawdatamap "cell" //
// (there is an offset +1, because the index can be zero and //
// zero means empty cell. //
// //
/////////////////////////////////////////////////////////////////////////
#include "TClonesArray.h"
#include "AliLog.h"
#include "AliTOFGeometry.h"
#include "AliTOFRawMap.h"
ClassImp(AliTOFRawMap)
AliTOFRawMap::AliTOFRawMap():
TObject(),
fNtrm(-1),
fNtrmChain(-1),
fNtdc(-1),
fNtdcChannel(-1),
fRawData(0x0),
fMaxIndex(-1),
fRawMap(0x0)
{
//
// Default ctor
//
}
////////////////////////////////////////////////////////////////////////
AliTOFRawMap::AliTOFRawMap(TClonesArray *dig)://, AliTOFGeometry *tofGeom:
TObject(),
fNtrm(AliTOFGeometry::NTRM()+2),
fNtrmChain(AliTOFGeometry::NChain()),
fNtdc(AliTOFGeometry::NTdc()),
fNtdcChannel(AliTOFGeometry::NCh()),
fRawData(dig),
fMaxIndex(-1),
fRawMap(0x0)
{
//
// ctor
//
// of course, these constants must not be hardwired
// change later
fMaxIndex = fNtrm*fNtrmChain*fNtdc*fNtdcChannel;
fRawMap = new Int_t[fMaxIndex];
Clear();
}
////////////////////////////////////////////////////////////////////////
AliTOFRawMap::~AliTOFRawMap()
{
//
// Destructor
//
if (fRawMap)
delete[] fRawMap;
}
////////////////////////////////////////////////////////////////////////
void AliTOFRawMap::Clear(const char *)
{
//
// Clear hitmap
//
memset(fRawMap,0,sizeof(int)*fMaxIndex);
}
////////////////////////////////////////////////////////////////////////
Int_t AliTOFRawMap::CheckedIndex(const Int_t * const slot) const
{
//
// Return checked indices for vol
//
Int_t index =
slot[0]*fNtrmChain*fNtdc*fNtdcChannel + // TRM
slot[1]*fNtdc*fNtdcChannel + // TRM chain
slot[2]*fNtdcChannel + // TDC
slot[3]; // TDC channel
if (index >= fMaxIndex) {
AliError("CheckedIndex - input outside bounds");
return -1;
} else {
return index;
}
}
////////////////////////////////////////////////////////////////////////
void AliTOFRawMap::SetHit(Int_t *slot, Int_t idigit)
{
//
// Assign digit to pad vol
//
// 0 means empty pad, we need to shift indeces by 1
fRawMap[CheckedIndex(slot)]=idigit+1;
}
////////////////////////////////////////////////////////////////////////
void AliTOFRawMap::SetHit(Int_t *slot)
{
//
// Assign last digit to channel slot
//
// 0 means empty pad, we need to shift indeces by 1
fRawMap[CheckedIndex(slot)]=fRawData->GetLast()+1;
}
////////////////////////////////////////////////////////////////////////
Int_t AliTOFRawMap::GetHitIndex(Int_t *slot) const
{
//
// Get contents of channel slot
//
// 0 means empty pad, we need to shift indeces by 1
return fRawMap[CheckedIndex(slot)]-1;
}
////////////////////////////////////////////////////////////////////////
TObject* AliTOFRawMap::GetHit(Int_t *slot) const
{
//
// Get pointer to object at alot
// return 0 if vol out of bounds
Int_t index = GetHitIndex(slot);
return (index <0) ? 0 : fRawData->UncheckedAt(index);
}
////////////////////////////////////////////////////////////////////////
FlagType AliTOFRawMap::TestHit(Int_t *slot) const
{
//
// Check if hit cell is empty, used or unused
//
Int_t inf = fRawMap[CheckedIndex(slot)];
if (inf > 0) {
return kUsed;
} else if (inf == 0) {
return kEmpty;
} else {
return kUnused;
}
}
| 28.772727
| 76
| 0.463073
|
AllaMaevskaya
|
8e08daffcf5d0d0d495089a41cb8900f3d15d331
| 650
|
cpp
|
C++
|
Chapter_13/Figures/Fig_13_8.cpp
|
mtrdazzo/Deitel
|
4efc02147a1768125d2e27d7d68f664c4628cdc5
|
[
"MIT"
] | 1
|
2021-09-07T19:23:24.000Z
|
2021-09-07T19:23:24.000Z
|
Chapter_13/Figures/Fig_13_8.cpp
|
mtrdazzo/Deitel
|
4efc02147a1768125d2e27d7d68f664c4628cdc5
|
[
"MIT"
] | null | null | null |
Chapter_13/Figures/Fig_13_8.cpp
|
mtrdazzo/Deitel
|
4efc02147a1768125d2e27d7d68f664c4628cdc5
|
[
"MIT"
] | null | null | null |
/**
* @file Fig_13_8.cpp
* @author Matthew J Randazzo (mtrdazzo@gmail.com)
* @brief width member function of classes istream and ostream
* @version 0.1
* @date 2020-07-19
*
* @copyright Copyright (c) 2020
*
*/
#include <iostream>
int main() {
int widthValue{4};
char sentence[10];
std::cout << "Enter a sequence:\n";
std::cin.width(5); // input only 5 characters from sentence
// set field width, then display characters based on that width
while (std::cin >> sentence) {
std::cout.width(widthValue++);
std::cout << sentence << "\n";
std::cin.width(5);
}
return EXIT_SUCCESS;
}
| 21.666667
| 67
| 0.615385
|
mtrdazzo
|
8e09c3050af11576e808b35c4254aa250b22992a
| 3,437
|
cpp
|
C++
|
Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp
|
UltraProton/Placement-Prepration
|
cc70f174c4410c254ce0469737a884fffdc81164
|
[
"MIT"
] | null | null | null |
Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp
|
UltraProton/Placement-Prepration
|
cc70f174c4410c254ce0469737a884fffdc81164
|
[
"MIT"
] | 3
|
2020-05-08T18:02:51.000Z
|
2020-05-09T08:37:35.000Z
|
Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp
|
UltraProton/PlacementPrep
|
cc70f174c4410c254ce0469737a884fffdc81164
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
node(int x){
data = x;
left = right = NULL;
}
};
/* converts a tree to its mrror image */
void mirror(struct node* node);
/* returns true if structure of two trees a and b is same
Only structure is considered for comparison, not data! */
bool isStructSame(struct node *a, struct node *b);
/* Returns true if the given tree is foldable */
bool isFoldable(struct node *root);
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
See http://www.geeksforgeeks.org/?p=662 for details */
void mirror(struct node* node)
{
if (node==NULL)
return;
else
{
struct node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
void insert(struct node *root,int n1,int n2,char lr)
{
if(root==NULL)
return;
if(root->data==n1)
{
switch(lr)
{
case 'L': root->left=new node(n2);
break;
case 'R': root->right=new node(n2);
break;
}
}
else
{
insert(root->left,n1,n2,lr);
insert(root->right,n1,n2,lr);
}
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
int t,k;
cin>>t;
while(t--)
{
int n;
cin>>n;
struct node *root=NULL;
while(n--)
{
char lr;
int n1,n2;
cin>>n1>>n2;
cin>>lr;
if(root==NULL)
{
root=new node(n1);
switch(lr){
case 'L': root->left=new node(n2);
break;
case 'R': root->right=new node(n2);
break;
}
}
else
{
insert(root,n1,n2,lr);
}
}
if(isFoldable(root) == 1)
{ cout<<"Yes"<<endl; }
else
{ cout<<"No"<<endl; }
getchar();
}
return 0;
}
/*This is a function problem.You only need to complete the function given below*/
/* Returns true if the given tree is foldable */
/* A binary tree node has data, pointer to left child
and a pointer to right child */
bool is_structurally_symmetric(struct node *a ,struct node *b){
if(!a && !b){
return true;
}
if(!a || !b){
return false;
}
bool l_ans= is_structurally_symmetric(a->left,b->right);
bool r_ans= is_structurally_symmetric(a->right, b->left);
if(l_ans && r_ans){
return true;
}
else{
return false;
}
}
bool isFoldable(struct node *root){
// if(root){
// bool x= is_structurally_symmetric(root->left, root->right);
// bool l_ans= isFoldable(root->left);
// bool r_ans= isFoldable(root->right);
// if(l_ans && r_ans){
// return true;
// }
// else{
// return false;
// }
// }
// return false;
bool ans= is_structurally_symmetric(root->left, root->right);
return ans;
}
| 21.347826
| 81
| 0.551644
|
UltraProton
|
8e0a7e06d8dc19dff9e3ddc30d095372b9ce0452
| 26
|
cpp
|
C++
|
tests/environment.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
tests/environment.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
tests/environment.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
#include "environment.h"
| 13
| 25
| 0.730769
|
TheQuantumPhysicist
|
8e0b642cd53e9e136944340e6f8368a9ae096647
| 3,381
|
cpp
|
C++
|
TAO/tests/Bug_3748_Regression/Test_Protocols_Hooks.cpp
|
cflowe/ACE
|
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
|
[
"DOC"
] | 36
|
2015-01-10T07:27:33.000Z
|
2022-03-07T03:32:08.000Z
|
TAO/tests/Bug_3748_Regression/Test_Protocols_Hooks.cpp
|
cflowe/ACE
|
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
|
[
"DOC"
] | 2
|
2018-08-13T07:30:51.000Z
|
2019-02-25T03:04:31.000Z
|
TAO/tests/Bug_3748_Regression/Test_Protocols_Hooks.cpp
|
cflowe/ACE
|
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
|
[
"DOC"
] | 38
|
2015-01-08T14:12:06.000Z
|
2022-01-19T08:33:00.000Z
|
// -*- C++ -*-
//
// $Id: Test_Protocols_Hooks.cpp 91648 2010-09-08 13:25:56Z johnnyw $
//
#include "Test_Protocols_Hooks.h"
#include "TestC.h"
Test_Protocols_Hooks::Test_Protocols_Hooks (void)
: failure_count_ (0)
{
}
Test_Protocols_Hooks::~Test_Protocols_Hooks (void)
{
}
void
Test_Protocols_Hooks::init_hooks (TAO_ORB_Core *)
{
// No-op.
}
CORBA::Boolean
Test_Protocols_Hooks::set_client_network_priority (IOP::ProfileId,
TAO_Stub *)
{
return false;
}
CORBA::Boolean
Test_Protocols_Hooks::set_server_network_priority (IOP::ProfileId,
CORBA::Policy *)
{
return false;
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_IIOP_Protocol_Properties &)
{
if (++this->failure_count_ < Test::expected_failure_number)
throw ::CORBA::INTERNAL ();
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_IIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_UIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_UIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_SHMIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_SHMIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_DIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_DIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::server_protocol_properties_at_orb_level (
TAO_SCIOP_Protocol_Properties &)
{
// No-op.
}
void
Test_Protocols_Hooks::client_protocol_properties_at_orb_level (
TAO_SCIOP_Protocol_Properties &)
{
// No-op.
}
CORBA::Long
Test_Protocols_Hooks::get_dscp_codepoint (void)
{
return -1;
}
void
Test_Protocols_Hooks::get_selector_hook (
CORBA::Policy *,
CORBA::Boolean &,
CORBA::Short &)
{
// No-op.
}
void
Test_Protocols_Hooks::get_selector_bands_policy_hook (
CORBA::Policy *,
CORBA::Short,
CORBA::Short &,
CORBA::Short &,
bool &
)
{
// No-op.
}
int
Test_Protocols_Hooks::get_thread_CORBA_priority (CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::get_thread_native_priority (
CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::get_thread_CORBA_and_native_priority (
CORBA::Short &,
CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::get_thread_implicit_CORBA_priority (CORBA::Short &)
{
return -1;
}
int
Test_Protocols_Hooks::restore_thread_CORBA_and_native_priority (
CORBA::Short,
CORBA::Short
)
{
return -1;
}
int
Test_Protocols_Hooks::set_thread_CORBA_priority (CORBA::Short)
{
return -1;
}
ACE_STATIC_SVC_DEFINE (Test_Protocols_Hooks,
ACE_TEXT ("Test_Protocols_Hooks"),
ACE_SVC_OBJ_T,
&ACE_SVC_NAME (Test_Protocols_Hooks),
ACE_Service_Type::DELETE_THIS
| ACE_Service_Type::DELETE_OBJ,
0)
ACE_FACTORY_DEFINE (ACE_Local_Service, Test_Protocols_Hooks)
| 18.080214
| 73
| 0.696539
|
cflowe
|
8e0b9590dd090921dfd51bf8831426402488f77c
| 1,115
|
hpp
|
C++
|
src/volt/gpu/d3d12/d3d12.hpp
|
voltengine/volt
|
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
|
[
"MIT"
] | null | null | null |
src/volt/gpu/d3d12/d3d12.hpp
|
voltengine/volt
|
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
|
[
"MIT"
] | null | null | null |
src/volt/gpu/d3d12/d3d12.hpp
|
voltengine/volt
|
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
|
[
"MIT"
] | null | null | null |
#pragma once
#include <volt/gpu/enums.hpp>
namespace volt::gpu::d3d12 {
extern std::unordered_map<HRESULT, std::string> result_messages;
extern std::unordered_map<command_types, D3D12_COMMAND_LIST_TYPE> command_list_types;
template<command_types T>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type;
template<>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::rasterization> = D3D12_COMMAND_LIST_TYPE_DIRECT;
template<>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::compute> = D3D12_COMMAND_LIST_TYPE_COMPUTE;
template<>
constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::copy> = D3D12_COMMAND_LIST_TYPE_COPY;
extern std::unordered_map<memory_type, D3D12_HEAP_TYPE> heap_types;
}
#define VOLT_D3D12_CHECK(expression, message)\
{\
::HRESULT result = expression;\
VOLT_ASSERT(result == S_OK, message + ('\n' + ::volt::gpu::d3d12::result_messages[result]))\
}
#ifdef VOLT_GPU_DEBUG
#define VOLT_D3D12_DEBUG_CHECK(expression, message) VOLT_D3D12_CHECK(expression, message)
#else
#define VOLT_D3D12_DEBUG_CHECK(expression, message) expression;
#endif
| 30.135135
| 114
| 0.821525
|
voltengine
|
8e0f910636ef878151394c403e6a3de3879d1de8
| 401
|
cpp
|
C++
|
exemplos/5_Repeticao/soma-ate-0.cpp
|
danielgs83/cpe-unb
|
f958d2a4899a8d4d5c1465637d1d1b10610661e4
|
[
"CC0-1.0"
] | 1
|
2022-02-04T17:16:50.000Z
|
2022-02-04T17:16:50.000Z
|
exemplos/5_Repeticao/soma-ate-0.cpp
|
danielgs83/cpe-unb
|
f958d2a4899a8d4d5c1465637d1d1b10610661e4
|
[
"CC0-1.0"
] | null | null | null |
exemplos/5_Repeticao/soma-ate-0.cpp
|
danielgs83/cpe-unb
|
f958d2a4899a8d4d5c1465637d1d1b10610661e4
|
[
"CC0-1.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int soma, parcela;
soma = 0;
cout << "numero a ser somado (0 para sair): ";
cin >> parcela; //leitura do primeiro numero
while (parcela != 0) {
soma += parcela; //acumula
cout << "numero a ser somado (0 para sair): ";
cin >> parcela; //leitura do proximo numero
}
cout << "Soma: " << soma << endl;
return 0;
}
| 17.434783
| 50
| 0.586035
|
danielgs83
|
8e0ffef18e846b6a08b69ae0c7a5c108185c7c95
| 2,027
|
cpp
|
C++
|
cpp/backtracking/The_knights_tour_problem.cpp
|
banerjeesoumya15/AlgoBook
|
79fcbd0631a6f1fbe24a8d3627550d1ec9ad605c
|
[
"MIT"
] | 191
|
2020-09-28T10:00:20.000Z
|
2022-03-06T14:36:55.000Z
|
cpp/backtracking/The_knights_tour_problem.cpp
|
banerjeesoumya15/AlgoBook
|
79fcbd0631a6f1fbe24a8d3627550d1ec9ad605c
|
[
"MIT"
] | 210
|
2020-09-28T10:06:36.000Z
|
2022-03-05T03:44:24.000Z
|
cpp/backtracking/The_knights_tour_problem.cpp
|
banerjeesoumya15/AlgoBook
|
79fcbd0631a6f1fbe24a8d3627550d1ec9ad605c
|
[
"MIT"
] | 320
|
2020-09-28T09:56:14.000Z
|
2022-02-12T16:45:57.000Z
|
#include <bits/stdc++.h>
using namespace std;
//a function to check whether a grid is valid or not
bool isvalid(int x, int y, int **tour, int n){
return(x>=0 && y>=0 && x<n && y<n && tour[x][y]==-1);
}
//function to solve the tour
bool solve_knighttour(int x, int y, int moves,int n, int **tour, int nxt_x[8], int nxt_y[8]){
//if moves are equal to no of grids then solved (base case)
if(moves==n*n){
return true;
}
//variables for the next grid
int new_x, new_y;
for(int k=0; k<n; k++){
//updating next grid
new_x = x + nxt_x[k];
new_y = y + nxt_y[k];
//checking for validity
if(isvalid(new_x, new_y, tour, n)){
tour[new_x][new_y] = moves;
if(solve_knighttour(new_x, new_y, moves+1, n, tour, nxt_x, nxt_y))
return true;
else
//back tracking
tour[new_x][new_y] = -1;
}
}
//if not found return false
return false;
}
//function to print the solution
void print(int **tour,int n){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << tour[i][j] <<" ";
}
cout << endl;
}
}
int main(){
int n = 8;
int **tour = new int *[n]; //matrix for the knights tour
for(int i=0; i<n; i++){
tour[i] = new int [n];
for(int j=0; j<n; j++){
tour[i][j] = -1; //mark all the points as -1
}
}
//knight is initially here(0,0)
tour[0][0] = 0;
//next coordinates of x and y for the knight
int nxt_x_move[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int nxt_y_move[8] = {1, 2, 2, 1, -1, -2, -2, -1};
//start exploring the matrix by function call starting from (0,0)
if(solve_knighttour(0, 0, 1, n, tour, nxt_x_move, nxt_y_move)){
//if the tour exists then a function call for printing.
print(tour, n);
return 0;
}
else{
cout << "No tour found!!" <<endl;
}
return 0;
}
| 27.767123
| 93
| 0.510607
|
banerjeesoumya15
|
8e11f514fbf9d3a021bc436e68abee51dd29ae11
| 3,955
|
cpp
|
C++
|
tests/TestWord.cpp
|
SergioRosello/OSO
|
bbd3c6a95b1c2388732babc6a540c07034cce026
|
[
"MIT"
] | 1
|
2019-10-14T07:25:32.000Z
|
2019-10-14T07:25:32.000Z
|
tests/TestWord.cpp
|
SergioRosello/OSO
|
bbd3c6a95b1c2388732babc6a540c07034cce026
|
[
"MIT"
] | null | null | null |
tests/TestWord.cpp
|
SergioRosello/OSO
|
bbd3c6a95b1c2388732babc6a540c07034cce026
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "../include/Selection.h"
namespace OSO {
// The fixture for testing class Foo.
class WordTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
WordTest() {
// You can do set-up work for each test here.
}
~WordTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test suite for Foo.
};
TEST_F(WordTest, CheckWordSizeIsCorrect) {
Cell firstLetter = Cell(Coordinates(0, 3), 'H');
Cell secondLetter = Cell(Coordinates(0, 2), 'O');
Cell thirdLetter = Cell(Coordinates(0, 1), 'L');
Cell lastLetter = Cell(Coordinates(0, 0), 'A');
Selection word = Selection(firstLetter, lastLetter);
EXPECT_EQ(word.GetSize(), 4);
}
TEST_F(WordTest, CheckWordOrientationSizeIsCorrect) {
// North
Cell firstNorthLetter = Cell(Coordinates(0, 2), 'O');
Cell secondNorthLetter = Cell(Coordinates(0, 1), 'S');
Cell thirdNorthLetter = Cell(Coordinates(0, 0), 'O');
Selection northWord = Selection(firstNorthLetter, thirdNorthLetter);
EXPECT_EQ(northWord.GetSize(), 3);
// North-East
Cell firstNorthEastLetter = Cell(Coordinates(0, 2), 'O');
Cell secondNorthEastLetter = Cell(Coordinates(1, 2), 'S');
Cell thirdNorthEastLetter = Cell(Coordinates(2, 0), 'O');
Selection northEastWord = Selection(firstNorthEastLetter, thirdNorthEastLetter);
EXPECT_EQ(northEastWord.GetSize(), 3);
// East
Cell firstEastLetter = Cell(Coordinates(0, 0), 'O');
Cell secondEastLetter = Cell(Coordinates(1, 0), 'S');
Cell thirdEastLetter = Cell(Coordinates(2, 0), 'O');
Selection eastWord = Selection(firstEastLetter, thirdEastLetter);
EXPECT_EQ(eastWord.GetSize(), 3);
// South-East
Cell firstSouthEastLetter = Cell(Coordinates(0, 0), 'O');
Cell secondSouthEastLetter = Cell(Coordinates(1, 1), 'S');
Cell thirdSouthEastLetter = Cell(Coordinates(2, 2), 'O');
Selection southEastWord = Selection(firstSouthEastLetter, thirdSouthEastLetter);
EXPECT_EQ(southEastWord.GetSize(), 3);
// South
Cell firstSouthLetter = Cell(Coordinates(0, 0), 'O');
Cell secondSouthLetter = Cell(Coordinates(0, 1), 'S');
Cell thirdSouthLetter = Cell(Coordinates(0, 2), 'O');
Selection southWord = Selection(firstSouthLetter, thirdSouthLetter);
EXPECT_EQ(southWord.GetSize(), 3);
// Sout-West
Cell firstSouthWestLetter = Cell(Coordinates(2, 0), 'O');
Cell secondSouthWestLetter = Cell(Coordinates(1, 1), 'S');
Cell thirdSouthWestLetter = Cell(Coordinates(0, 2), 'O');
Selection southWestWord = Selection(firstSouthWestLetter, thirdSouthWestLetter);
EXPECT_EQ(southWestWord.GetSize(), 3);
// West
Cell firstWestLetter = Cell(Coordinates(2, 0), 'O');
Cell secondWestLetter = Cell(Coordinates(1, 0), 'S');
Cell thirdWestLetter = Cell(Coordinates(0, 0), 'O');
Selection westWord = Selection(firstWestLetter, thirdWestLetter);
EXPECT_EQ(westWord.GetSize(), 3);
// North-West
Cell firstNorthWestLetter = Cell(Coordinates(2, 2), 'O');
Cell secondNorthWestLetter = Cell(Coordinates(1, 1), 'S');
Cell thirdNorthWestLetter = Cell(Coordinates(0, 0), 'O');
Selection northWestWord = Selection(firstNorthWestLetter, thirdNorthWestLetter);
EXPECT_EQ(northWestWord.GetSize(), 3);
}
} // namespace
| 34.692982
| 84
| 0.672566
|
SergioRosello
|
8e1250f35886ace8a9135303cfb8532ee7dde5fb
| 4,415
|
cpp
|
C++
|
src/test/git/TestGitClientImpl.cpp
|
TNG/mustard-cli
|
aa8db4e923271546b46a1f9a71778b3bed1efe3a
|
[
"Apache-2.0"
] | 7
|
2019-04-12T07:13:32.000Z
|
2021-09-22T20:53:44.000Z
|
src/test/git/TestGitClientImpl.cpp
|
TNG/mustard-cli
|
aa8db4e923271546b46a1f9a71778b3bed1efe3a
|
[
"Apache-2.0"
] | 2
|
2020-07-21T05:01:13.000Z
|
2020-08-14T15:38:17.000Z
|
src/test/git/TestGitClientImpl.cpp
|
TNG/mustard-cli
|
aa8db4e923271546b46a1f9a71778b3bed1efe3a
|
[
"Apache-2.0"
] | 1
|
2020-07-21T05:03:09.000Z
|
2020-07-21T05:03:09.000Z
|
#include <gtest/gtest.h>
#include <Depend.h>
#include "../../main/git/GitClientImpl.h"
#include "GitTestEnvironment.h"
using namespace testing;
class TestGitClientImpl: public Test
{
public:
GitClientImpl gitClient;
};
TEST_F ( TestGitClientImpl, Unit_GetHeadCommit )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "test" );
EXPECT_TRUE ( gitClient.workingDirectoryIsClean() );
}
TEST_F ( TestGitClientImpl, Unit_WorkingDirIsClean_No )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "test" );
testEnv.run ( "touch anotherone" );
EXPECT_FALSE ( gitClient.workingDirectoryIsClean() );
}
TEST_F ( TestGitClientImpl, Unit_FindMergeBase )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "test" );
const Commitish expectedMergeBase = gitClient.getHeadCommit();
testEnv.run ( "git checkout -q -b feature" );
testEnv.createFileAndCommit ( "featureFile" );
testEnv.run ( "git checkout -q master" );
testEnv.createFileAndCommit ( "masterDevelopment" );
EXPECT_STRNE ( expectedMergeBase.c_str(), gitClient.getHeadCommit().c_str() );
const Commitish mergeBase = gitClient.getMergeBase ( "feature", "master" );
EXPECT_STREQ ( expectedMergeBase.c_str(), mergeBase.c_str() );
}
TEST_F ( TestGitClientImpl, Unit_GitReset )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "someFile" );
testEnv.createFileAndCommit ( "someOtherFile" );
EXPECT_TRUE ( gitClient.workingDirectoryIsClean() );
testEnv.run ( "git branch future" );
gitClient.reset ( "HEAD^" );
testEnv.run ( "touch someOtherFile" );
EXPECT_FALSE ( gitClient.workingDirectoryIsClean() );
gitClient.reset ( "future" );
EXPECT_TRUE ( gitClient.workingDirectoryIsClean() );
}
TEST_F ( TestGitClientImpl, Unit_GetConfigValue )
{
GitTestEnvironment testEnv;
const string expectedValue = "someValue";
const string keyPath = "category.key";
testEnv.run ( "git config --add " + keyPath + " " + expectedValue );
const string valueFromConfig = gitClient.getConfigValue ( keyPath );
EXPECT_STREQ ( expectedValue.c_str(), valueFromConfig.c_str() );
}
TEST_F ( TestGitClientImpl, Unit_GetDiff )
{
GitTestEnvironment testEnv;
testEnv.createFileAndCommit ( "myFile" );
testEnv.run ( "echo someMoreContent >> myFile" );
testEnv.run ( "git commit -m 'some more stuff'" );
testEnv.run ( "echo lessContent >> myFile" );
const string diff = gitClient.getDiff();
const string expectedDiff = "diff --git a/myFile b/myFile\n"
"index e69de29..6924897 100644\n"
"--- a/myFile\n"
"+++ b/myFile\n"
"@@ -0,0 +1,2 @@\n"
"+someMoreContent\n"
"+lessContent\n"
"";
EXPECT_STREQ ( expectedDiff.c_str(), diff.c_str() );
}
TEST_F ( TestGitClientImpl, Unit_getFeatureBranchOnOrigin )
{
GitTestEnvironment testEnv;
GitTestEnvironment remoteEnv ( "/tmp/remoteTestEnv" );
testEnv.run ( "git remote add origin /tmp/remoteTestEnv" );
testEnv.createFileAndCommit ( "testFile" );
testEnv.run ( "git checkout -b feature 2>/dev/null" );
testEnv.createFileAndCommit ( "anotherTestFile" );
testEnv.run ( "git push -u origin HEAD 2>/dev/null" );
const Commitish featureCommit ( gitClient.getHeadCommit() );
testEnv.createFileAndCommit ( "yetAnotherTestFile" );
ASSERT_EQ ( featureCommit, gitClient.getFeatureBranchOnOrigin() );
ASSERT_NE ( featureCommit, gitClient.getHeadCommit() );
}
TEST_F ( TestGitClientImpl, Unit_getFeatureBranchOnOrigin_CommitMessageWithBrackets )
{
GitTestEnvironment testEnv;
GitTestEnvironment remoteEnv ( "/tmp/remoteTestEnv" );
testEnv.run ( "git remote add origin /tmp/remoteTestEnv" );
testEnv.createFileAndCommit ( "testFile" );
testEnv.run ( "git checkout -b feature 2>/dev/null" );
testEnv.run ( "touch anotherTestFile" );
testEnv.run ( "git add anotherTestFile" );
testEnv.run ( "git commit -m '[log] Another test file has been created [blah]'" );
testEnv.run ( "git push -u origin HEAD 2>/dev/null" );
const Commitish featureCommit ( gitClient.getHeadCommit() );
ASSERT_EQ ( featureCommit, gitClient.getFeatureBranchOnOrigin() );
}
| 34.76378
| 86
| 0.671574
|
TNG
|
8e162cb1124cae1e7130e2f70a1789d04925c119
| 448
|
cc
|
C++
|
example/linux/flutter/generated_plugin_registrant.cc
|
jainris/flutter_audio_desktop
|
63d5823facbab34358875c6722874f950eb10393
|
[
"MIT"
] | 50
|
2020-09-13T12:13:40.000Z
|
2022-02-26T03:36:45.000Z
|
example/linux/flutter/generated_plugin_registrant.cc
|
jainris/flutter_audio_desktop
|
63d5823facbab34358875c6722874f950eb10393
|
[
"MIT"
] | 28
|
2020-09-23T05:29:26.000Z
|
2021-03-17T11:21:11.000Z
|
example/linux/flutter/generated_plugin_registrant.cc
|
jainris/flutter_audio_desktop
|
63d5823facbab34358875c6722874f950eb10393
|
[
"MIT"
] | 16
|
2020-09-14T07:12:29.000Z
|
2021-10-13T23:52:12.000Z
|
//
// Generated file. Do not edit.
//
#include "generated_plugin_registrant.h"
#include <flutter_audio_desktop/flutter_audio_desktop_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) flutter_audio_desktop_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAudioDesktopPlugin");
flutter_audio_desktop_plugin_register_with_registrar(flutter_audio_desktop_registrar);
}
| 32
| 89
| 0.841518
|
jainris
|
8e1788ea9d52b0333d00766225789530cdb08ec7
| 19,774
|
hpp
|
C++
|
library/grammar/string.hpp
|
grandquista/chimera
|
2a5326afc866d878517f2b0f5df2bf6cba20f4eb
|
[
"MIT"
] | 2
|
2017-12-14T07:05:06.000Z
|
2021-02-07T03:31:27.000Z
|
library/grammar/string.hpp
|
grandquista/chimera
|
2a5326afc866d878517f2b0f5df2bf6cba20f4eb
|
[
"MIT"
] | 149
|
2018-08-06T13:14:46.000Z
|
2019-11-19T02:00:56.000Z
|
library/grammar/string.hpp
|
grandquista/chimera
|
2a5326afc866d878517f2b0f5df2bf6cba20f4eb
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017 Adam Grandquist <grandquista@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// 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.
//! parse definitions for string tokens.
#pragma once
#include <algorithm>
#include <cstdint>
#include <numeric>
#include <string>
#include <string_view>
#include <gsl/gsl>
#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/unescape.hpp>
#include "asdl/asdl.hpp"
#include "grammar/exprfwd.hpp"
#include "grammar/flags.hpp"
#include "grammar/oper.hpp"
#include "grammar/rules.hpp"
#include "grammar/whitespace.hpp"
#include "object/object.hpp"
namespace chimera {
namespace library {
namespace grammar {
namespace token {
using namespace std::literals;
struct StringHolder : rules::VariantCapture<object::Object> {
std::string string;
template <typename String>
void apply(String &&in) {
string.append(std::forward<String>(in));
}
};
struct LiteralChar : plus<not_one<'\0', '{', '}'>> {};
template <>
struct Action<LiteralChar> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(in.string());
}
};
template <flags::Flag Option>
using FExpression =
sor<list_tail<sor<ConditionalExpression<Option>, StarExpr<Option>>,
Comma<Option>>,
YieldExpr<Option>>;
struct Conversion : one<'a', 'r', 's'> {};
template <>
struct Action<Conversion> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
asdl::FormattedValue formattedValue{
top.template pop<asdl::ExprImpl>(),
asdl::FormattedValue::STR,
{}};
switch (in.peek_char()) {
case 'a':
formattedValue.conversion = asdl::FormattedValue::ASCII;
break;
case 'r':
formattedValue.conversion = asdl::FormattedValue::REPR;
break;
case 's':
formattedValue.conversion = asdl::FormattedValue::STR;
break;
default:
break;
}
top.push(std::move(formattedValue));
}
};
template <flags::Flag Option>
struct FormatSpec;
template <flags::Flag Option>
using ReplacementField =
if_must<LBrt<Option>, FExpression<Option>,
opt<one<'!'>, Conversion>,
opt<one<':'>, FormatSpec<Option>>, RBrt<Option>>;
template <flags::Flag Option>
struct FormatSpec
: star<sor<LiteralChar, one<0>, ReplacementField<Option>>> {};
template <flags::Flag Option>
struct Action<FormatSpec<Option>> {
template <typename Top>
static void apply0(Top &&top) {
auto formatSpec = top.template pop<asdl::ExprImpl>();
auto expr = top.template pop<asdl::ExprImpl>();
if (std::holds_alternative<asdl::FormattedValue>(*expr.value)) {
std::get<asdl::FormattedValue>(*expr.value).format_spec =
std::move(formatSpec);
top.push(std::move(expr));
} else {
top.push(asdl::FormattedValue{std::move(expr),
asdl::FormattedValue::STR,
std::move(formatSpec)});
}
}
};
struct LeftFLiteral : String<'{', '{'> {};
template <>
struct Action<LeftFLiteral> {
template <typename Top>
static void apply0(Top &&top) {
top.apply("{"sv);
}
};
struct RightFLiteral : String<'}', '}'> {};
template <>
struct Action<RightFLiteral> {
template <typename Top>
static void apply0(Top &&top) {
top.apply("}"sv);
}
};
struct FLiteral : plus<sor<LiteralChar, LeftFLiteral, RightFLiteral>> {
using Transform = StringHolder;
};
template <>
struct Action<FLiteral> {
template <typename Top>
static void apply0(Top &&top) {
top.push(object::Object(object::String(top.string), {}));
}
};
template <flags::Flag Option>
using FString =
must<star<sor<FLiteral, ReplacementField<Option>>>, eof>;
template <typename Chars>
struct SingleChars : plus<Chars> {};
template <typename Chars>
struct Action<SingleChars<Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(in.string());
}
};
template <unsigned Len>
struct Hexseq : rep<Len, ranges<'0', '9', 'a', 'f', 'A', 'F'>> {};
template <unsigned Len>
struct Action<Hexseq<Len>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string string;
if (tao::pegtl::unescape::utf8_append_utf32(
string, tao::pegtl::unescape::unhex_string<std::uint32_t>(
in.begin(), in.end()))) {
top.apply(std::move(string));
}
}
};
template <char Open, unsigned Len>
using UTF = seq<one<Open>, Hexseq<Len>>;
struct Octseq : seq<range<'0', '7'>, rep_opt<2, range<'0', '7'>>> {};
template <>
struct Action<Octseq> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string string;
if (tao::pegtl::unescape::utf8_append_utf32(
string, std::accumulate(
in.begin(), in.end(), std::uint32_t(0),
[](const auto init, const auto c) {
return (init << 2) |
static_cast<std::uint32_t>(c - '0');
}))) {
top.apply(std::move(string));
}
}
};
struct EscapeControl : one<'a', 'b', 'f', 'n', 'r', 't', 'v'> {};
template <>
struct Action<EscapeControl> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
switch (in.peek_char()) {
case 'a':
top.apply("\a"sv);
break;
case 'b':
top.apply("\b"sv);
break;
case 'f':
top.apply("\f"sv);
break;
case 'n':
top.apply("\n"sv);
break;
case 'r':
top.apply("\r"sv);
break;
case 't':
top.apply("\t"sv);
break;
case 'v':
top.apply("\v"sv);
break;
default:
Expects(false);
}
}
};
template <typename Chars>
struct EscapeIgnore : seq<Chars> {};
template <typename Chars>
struct Action<EscapeIgnore<Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(R"(\)"sv);
top.apply(in.string());
}
};
using Escape = one<'\\'>;
using XEscapeseq = UTF<'x', 2>;
template <typename Chars, typename... Escapes>
using Escapeseq = sor<Escapes..., XEscapeseq, Octseq, Eol,
EscapeControl, EscapeIgnore<Chars>>;
template <typename Chars, typename... Escapes>
using Item = seq<if_then_else<Escape, Escapeseq<Chars, Escapes...>,
SingleChars<minus<Chars, Escape>>>,
discard>;
template <typename Chars>
using RawItem = if_then_else<Escape, Chars, Chars>;
template <typename Triple, typename Chars, typename... Escapes>
using Long = if_must<
Triple,
until<Triple, Item<seq<not_at<Triple>, Chars>, Escapes...>>>;
template <typename Triple, typename Chars>
struct LongRaw
: if_must<Triple,
until<Triple, RawItem<seq<not_at<Triple>, Chars>>>> {};
template <typename Triple, typename Chars>
struct Action<LongRaw<Triple, Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string_view view(in.begin(), in.size());
view.remove_prefix(3);
view.remove_suffix(3);
top.apply(view);
}
};
template <typename Quote, typename Chars, typename... Escapes>
using Short =
if_must<Quote,
until<Quote, Item<minus<seq<not_at<Quote>, Chars>, Eol>,
Escapes...>>>;
template <typename Quote, typename Chars>
struct ShortRaw
: if_must<Quote,
until<Quote,
RawItem<minus<seq<not_at<Quote>, Chars>, Eol>>>> {};
template <typename Quote, typename Chars>
struct Action<ShortRaw<Quote, Chars>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
std::string_view view(in.begin(), in.size());
view.remove_prefix(1);
view.remove_suffix(1);
top.apply(view);
}
};
using TripleSingle = rep<3, one<'\''>>;
using TripleDouble = rep<3, one<'"'>>;
using Single = one<'\''>;
using Double = one<'"'>;
template <typename Chars>
using Raw =
sor<LongRaw<TripleDouble, Chars>, LongRaw<TripleSingle, Chars>,
ShortRaw<Double, Chars>, ShortRaw<Single, Chars>>;
template <typename Chars, typename... Escapes>
using Escaped = sor<Long<TripleDouble, Chars, Escapes...>,
Long<TripleSingle, Chars, Escapes...>,
Short<Double, Chars, Escapes...>,
Short<Single, Chars, Escapes...>>;
using UTF16Escape = UTF<'u', 4>;
using UTF32Escape = UTF<'U', 8>;
struct UName : star<not_one<'}'>> {};
template <>
struct Action<UName> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
top.apply(in.string());
}
};
using UNameEscape = if_must<String<'N', '{'>, UName, one<'}'>>;
template <typename Prefix, typename RawPrefix, typename Chars,
typename... Escapes>
using StringImpl = sor<seq<RawPrefix, Raw<Chars>>,
seq<Prefix, Escaped<Chars, Escapes...>>>;
using BytesPrefix = one<'b', 'B'>;
using BytesRawPrefix = sor<seq<one<'r', 'R'>, one<'b', 'B'>>,
seq<one<'b', 'B'>, one<'r', 'R'>>>;
template <flags::Flag Option>
struct Bytes
: plus<Token<Option, StringImpl<BytesPrefix, BytesRawPrefix,
range<0, 0b1111111>>>> {
struct Transform : rules::VariantCapture<object::Object> {
object::Bytes bytes;
template <typename String>
void apply(String &&in) {
for (const auto &byte : in) {
bytes.emplace_back(static_cast<std::uint8_t>(byte));
}
}
};
};
template <flags::Flag Option>
struct Action<Bytes<Option>> {
template <typename Top>
static void apply0(Top &&top) {
top.push(object::Object(std::move(top.bytes), {}));
}
};
using StrPrefix = opt<one<'u', 'U'>>;
using StrRawPrefix = one<'r', 'R'>;
template <flags::Flag Option>
struct DocString
: plus<Token<Option,
StringImpl<StrPrefix, StrRawPrefix, any, UTF16Escape,
UTF32Escape, UNameEscape>>> {
using Transform = StringHolder;
};
template <flags::Flag Option>
struct Action<DocString<Option>> {
template <typename Top>
static void apply0(Top &&top) {
top.push(object::Object(object::String(top.string), {}));
}
};
using JoinedStrPrefix = one<'f', 'F'>;
using JoinedStrRawPrefix = sor<seq<one<'r', 'R'>, one<'f', 'F'>>,
seq<one<'f', 'F'>, one<'r', 'R'>>>;
struct PartialString
: plus<StringImpl<StrPrefix, StrRawPrefix, any, UTF16Escape,
UTF32Escape, UNameEscape>> {
struct Transform {
std::string string;
template <typename Outer>
void success(Outer &&outer) {
outer.push(std::move(string));
}
template <typename String>
void apply(String &&in) {
string.append(std::forward<String>(in));
}
};
};
template <flags::Flag Option>
struct FormattedString
: seq<StringImpl<JoinedStrPrefix, JoinedStrRawPrefix, any,
UTF16Escape, UTF32Escape, UNameEscape>> {
struct Transform : rules::Stack<asdl::ExprImpl> {
std::string string;
template <typename Outer>
void success(Outer &&outer) {
if (auto s = size(); s > 0) {
asdl::JoinedStr joinedStr;
joinedStr.values.reserve(s);
transform<asdl::ExprImpl>(std::back_inserter(joinedStr.values));
outer.push(std::move(joinedStr));
}
}
template <typename String>
void apply(String &&in) {
string.append(std::forward<String>(in));
}
};
};
template <flags::Flag Option>
struct Action<FormattedString<Option>> {
template <typename Input, typename Top>
static void apply(const Input &in, Top &&top) {
auto result = tao::pegtl::parse_nested<
FString<flags::list<flags::DISCARD, flags::IMPLICIT>>, Action,
Normal>(in,
tao::pegtl::memory_input<>(top.string.c_str(),
top.string.size(),
"<f_string>"),
std::forward<Top>(top));
Ensures(result);
}
};
template <flags::Flag Option>
struct JoinedStrOne
: plus<Token<Option, sor<PartialString, FormattedString<Option>>>> {
using Transform = rules::VariantCapture<std::string, asdl::JoinedStr>;
};
template <flags::Flag Option>
struct Action<JoinedStrOne<Option>> {
using State = std::variant<std::string, asdl::JoinedStr>;
struct Visitor {
auto operator()(std::string &&value, std::string &&element) {
value.append(element);
return State{std::move(value)};
}
auto operator()(std::string &&value, asdl::JoinedStr &&joinedStr) {
joinedStr.values.emplace(
joinedStr.values.begin(),
object::Object(object::String(value), {}));
return State{std::move(joinedStr)};
}
auto operator()(asdl::JoinedStr &&value, std::string &&element) {
value.values.emplace_back(
object::Object(object::String(element), {}));
return State{std::move(value)};
}
auto operator()(asdl::JoinedStr &&value,
asdl::JoinedStr &&joinedStr) {
std::move(joinedStr.values.begin(), joinedStr.values.end(),
std::back_inserter(value.values));
return State{std::move(value)};
}
};
template <typename Top>
static void apply0(Top &&top) {
State value;
for (auto &&element : top.vector()) {
value =
std::visit(Visitor{}, std::move(value), std::move(element));
}
std::visit(top, std::move(value));
}
};
template <flags::Flag Option>
struct JoinedStr : seq<JoinedStrOne<Option>> {
struct Transform
: rules::Stack<std::string, asdl::JoinedStr, object::Object> {
struct Push {
using State = std::variant<asdl::JoinedStr, object::Object>;
State operator()(std::string && /*value*/) { Expects(false); }
auto operator()(asdl::JoinedStr &&value) {
return State{std::move(value)};
}
auto operator()(object::Object &&value) {
return State{std::move(value)};
}
};
template <typename Outer>
void success(Outer &&outer) {
std::visit(outer, std::visit(Push{}, pop()));
}
};
};
template <flags::Flag Option>
struct Action<JoinedStr<Option>> {
struct Push {
using State = std::variant<asdl::JoinedStr, object::Object>;
auto operator()(std::string &&value) {
return State{object::Object(object::String(value), {})};
}
auto operator()(asdl::JoinedStr &&value) {
return State{std::move(value)};
}
auto operator()(object::Object &&value) {
return State{std::move(value)};
}
};
template <typename Top>
static void apply0(Top &&top) {
std::visit(top, std::visit(Push{}, top.pop()));
}
};
} // namespace token
template <flags::Flag Option>
struct DocString : seq<token::DocString<Option>, sor<NEWLINE, at<Eolf>>> {
using Transform =
rules::ReshapeCapture<asdl::DocString, object::Object>;
};
template <flags::Flag Option>
struct STRING : sor<token::Bytes<Option>, token::JoinedStr<Option>> {};
} // namespace grammar
} // namespace library
} // namespace chimera
| 40.02834
| 80
| 0.51148
|
grandquista
|
8e19451dbab2934f8cf55793fc1999021ad77ba2
| 23,113
|
cxx
|
C++
|
TUHKMgen/AliGenUHKM.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
TUHKMgen/AliGenUHKM.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
TUHKMgen/AliGenUHKM.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/////////////////////////////////////////////////////////////////////////////
// Generator using UHKM 3.0 as an external generator. //
// ( only the HYDJET++ part is implemented for a moment) //
// temporary link: //
// http://lav01.sinp.msu.ru/~igor/hydjet++/hydjet++.txt //
// The main UHKM options are accessable through this interface. //
// Uses the TUHKMgen implementation of TGenerator. //
// Author of the first implementation: Sergey Zaporozhets //
// (zaporozh@sunhe.jinr.ru) //
// Futhers modifications were made by //
// Ionut Cristian Arsene (i.c.arsene@fys.uio.no) //
// & Malinina Liudmila(malinina@lav01.sinp.msu.ru) using as an example //
// AliGenTherminator.cxx created by Adam Kisiel //
// //
////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include "TUHKMgen.h"
#ifndef DATABASE_PDG
#include "DatabasePDG.h"
#endif
#ifndef PARTICLE_PDG
#include "ParticlePDG.h"
#endif
#include <TLorentzVector.h>
#include <TPDGCode.h>
#include <TParticle.h>
#include <TClonesArray.h>
#include <TMCProcess.h>
#include <TDatabasePDG.h>
#include <TSystem.h>
#include "AliGenUHKM.h"
#include "AliRun.h"
#include "AliConst.h"
#include "AliDecayer.h"
#include "AliGenEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliLog.h"
using namespace std;
ClassImp(AliGenUHKM)
//_______________________________________
AliGenUHKM::AliGenUHKM()
:AliGenMC(),
fTrials(0),
fUHKMgen(0),
fHydjetParams(),
fStableFlagged(0)
{
// Default constructor setting up default reasonable parameter values
// for central Pb+Pb collisions at 5.5TeV
// LHC
fHydjetParams.fSqrtS=5500; //LHC
fHydjetParams.fAw=207;//Pb-Pb
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.170;
fHydjetParams.fMuB = 0.0;
fHydjetParams.fMuS = 0.0;
fHydjetParams.fMuI3 = 0.0;
fHydjetParams.fThFO = 0.130;
fHydjetParams.fMu_th_pip = 0.0;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=10.;
fHydjetParams.fSigmaTau=3.;
fHydjetParams.fR=11.;
fHydjetParams.fYlmax=4.0;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=1;
fHydjetParams.fPtmin=7.0;
fHydjetParams.fT0=0.8;
fHydjetParams.fTau0=0.1;
fHydjetParams.fNf=0;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
/* RHIC
fHydjetParams.fSqrtS=200; //RHIC
fHydjetParams.fAw=197;//Au-Au
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.165;
fHydjetParams.fMuB = 0.0285;
fHydjetParams.fMuS = 0.007;
fHydjetParams.fMuI3 = -0.001;
fHydjetParams.fThFO = 0.100;
fHydjetParams.fMu_th_pip = 0.053;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=8.;
fHydjetParams.fSigmaTau=2.;
fHydjetParams.fR=10.;
fHydjetParams.fYlmax=3.3;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=0;
fHydjetParams.fPtmin=3.4;
fHydjetParams.fT0=0.3;
fHydjetParams.fTau0=0.4;
fHydjetParams.fNf=2;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
*/
strncpy(fParticleFilename, Form("%s/TUHKMgen/UHKM/particles.data", gSystem->Getenv("ALICE_ROOT")), 255);
strncpy(fDecayFilename, Form("%s/TUHKMgen/UHKM/tabledecay.txt", gSystem->Getenv("ALICE_ROOT")), 255);
for(Int_t i=0; i<500; i++) {
fStableFlagPDG[i] = 0;
fStableFlagStatus[i] = kFALSE;
}
fStableFlagged = 0;
}
//_______________________________________
AliGenUHKM::AliGenUHKM(Int_t npart)
:AliGenMC(npart),
fTrials(0),
fUHKMgen(0),
fHydjetParams(),
fStableFlagged(0)
{
// Constructor specifying the size of the particle table
// and setting up default reasonable parameter values
// for central Pb+Pb collisions at 5.5TeV
fName = "UHKM";
fTitle= "Particle Generator using UHKM 3.0";
fNprimaries = 0;
//LHC
fHydjetParams.fSqrtS=5500; //LHC
fHydjetParams.fAw=207;//Pb-Pb
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.170;
fHydjetParams.fMuB = 0.0;
fHydjetParams.fMuS = 0.0;
fHydjetParams.fMuI3 = 0.0;
fHydjetParams.fThFO = 0.130;
fHydjetParams.fMu_th_pip = 0.0;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=10.;
fHydjetParams.fSigmaTau=3.;
fHydjetParams.fR=11.;
fHydjetParams.fYlmax=4.0;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=1;
fHydjetParams.fPtmin=7.0;
fHydjetParams.fT0=0.8;
fHydjetParams.fTau0=0.1;
fHydjetParams.fNf=0;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
/*RHIC
fHydjetParams.fSqrtS=200; //RHIC
fHydjetParams.fAw=197;//Au-Au
fHydjetParams.fBmin=0.;
fHydjetParams.fBmax=0.5; //0-5% centrality
fHydjetParams.fT = 0.165;
fHydjetParams.fMuB = 0.0285;
fHydjetParams.fMuS = 0.007;
fHydjetParams.fMuI3 = -0.001;
fHydjetParams.fThFO = 0.100;
fHydjetParams.fMu_th_pip = 0.053;
fHydjetParams.fSeed=0;
fHydjetParams.fTau=8.;
fHydjetParams.fSigmaTau=2.;
fHydjetParams.fR=10.;
fHydjetParams.fYlmax=3.3;
fHydjetParams.fUmax=1.1;
fHydjetParams.fDelta=0.;
fHydjetParams.fEpsilon=0.;
fHydjetParams.fWeakDecay=0;//>=0 on ,-1 off
fHydjetParams.fEtaType=1;//gaus
fHydjetParams.fCorrS=1.;
fHydjetParams.fNhsel=2;
fHydjetParams.fIshad=1;
fHydjetParams.fPtmin=3.4;
fHydjetParams.fT0=0.3;
fHydjetParams.fTau0=0.4;
fHydjetParams.fNf=2;
fHydjetParams.fIenglu=0;
fHydjetParams.fIanglu=0;
*/
strncpy(fParticleFilename, Form("%s/TUHKMgen/UHKM/particles.data", gSystem->Getenv("ALICE_ROOT")), 255);
strncpy(fDecayFilename, Form("%s/TUHKMgen/UHKM/tabledecay.txt", gSystem->Getenv("ALICE_ROOT")), 255);
for(Int_t i=0; i<500; i++) {
fStableFlagPDG[i] = 0;
fStableFlagStatus[i] = kFALSE;
}
fStableFlagged = 0;
}
//__________________________________________
AliGenUHKM::~AliGenUHKM()
{
// Destructor, do nothing
// delete fParticles;
}
void AliGenUHKM::SetAllParametersRHIC()
{
// Set reasonable default parameters for 0-5% central Au+Au collisions
// at 200 GeV at RHIC
SetEcms(200.0); // RHIC top energy
SetAw(197); // Au+Au
SetBmin(0.0); // 0%
SetBmax(0.5); // 5%
SetChFrzTemperature(0.165); // T_ch = 165 MeV
SetMuB(0.0285); // mu_B = 28.5 MeV
SetMuS(0.007); // mu_S = 7 MeV
SetMuQ(-0.001); // mu_Q = -1 MeV
SetThFrzTemperature(0.100); // T_th = 100 MeV
SetMuPionThermal(0.053); // mu_th_pion = 53 MeV
SetSeed(0); // use UNIX time
SetTauB(8.0); // tau = 8 fm/c
SetSigmaTau(2.0); // sigma_tau = 2 fm/c
SetRmaxB(10.0); // fR = 10 fm
SetYlMax(3.3); // fYmax = 3.3
SetEtaRMax(1.1); // Umax = 1.1
SetMomAsymmPar(0.0); // delta = 0.0
SetCoordAsymmPar(0.0); // epsilon = 0.0
// SetFlagWeakDecay(0); // weak decay on (<0 off !!!)
SetEtaType(1); // gaus distributed with fYmax dispersion (0 means boost invariant)
SetGammaS(1.0); // gammaS = 1.0 (no strangeness canonical suppresion)
SetPyquenNhsel(2); // hydro on, jets on, jet quenching on
SetPyquenShad(1); // shadowing on (0 off)
SetPyquenPtmin(3.4); // ptmin = 3.4 GeV/c
SetPyquenT0(0.3); // T0 = 300 MeV
SetPyquenTau0(0.4); // tau0 = 0.4 fm/c
SetPyquenNf(2); // 2 flavours
SetPyquenIenglu(0); // radiative and collisional energy loss
SetPyquenIanglu(0); // small gluon angular distribution
}
void AliGenUHKM::SetAllParametersLHC()
{
// Set reasonable default parameters for 0-5% central Pb+Pb collisions
// at 5.5 TeV at LHC
SetEcms(5500.0); // LHC
SetAw(207); // Pb+Pb
SetBmin(0.0); // 0%
SetBmax(0.5); // 5%
SetChFrzTemperature(0.170); // T_ch = 170 MeV
SetMuB(0.0); // mu_B = 0 MeV
SetMuS(0.0); // mu_S = 0 MeV
SetMuQ(0.0); // mu_Q = 0 MeV
SetThFrzTemperature(0.130); // T_th = 130 MeV
SetMuPionThermal(0.0); // mu_th_pion = 0 MeV
SetSeed(0); // use UNIX time
SetTauB(10.0); // tau = 10 fm/c
SetSigmaTau(3.0); // sigma_tau = 3 fm/c
SetRmaxB(11.0); // fR = 11 fm
SetYlMax(4.0); // fYmax = 4.0
SetEtaRMax(1.1); // Umax = 1.1
SetMomAsymmPar(0.0); // delta = 0.0
SetCoordAsymmPar(0.0); // epsilon = 0.0
// SetFlagWeakDecay(0); // weak decay on (<0 off !!!)
SetEtaType(1); // gaus distributed with fYmax dispersion (0 means boost invariant)
SetGammaS(1.0); // gammaS = 1.0 (no strangeness canonical suppresion)
SetPyquenNhsel(2); // hydro on, jets on, jet quenching on
SetPyquenShad(1); // shadowing on (0 off)
SetPyquenPtmin(7.0); // ptmin = 7.0 GeV/c
SetPyquenT0(0.8); // T0 = 800 MeV
SetPyquenTau0(0.1); // tau0 = 0.4 fm/c
SetPyquenNf(0); // 0 flavours
SetPyquenIenglu(0); // radiative and collisional energy loss
SetPyquenIanglu(0); // small gluon angular distribution
}
//_________________________________________
void AliGenUHKM::Init()
{
// Initialization of the TGenerator::TUHKMgen interface object.
// Model input parameters are transmited to the TUHKMgen object which forwards them
// further to the model.
// HYDJET++ is initialized (average multiplicities are calculated, particle species definitions and decay
// channels are loaded, etc.)
SetMC(new TUHKMgen());
fUHKMgen = (TUHKMgen*) fMCEvGen;
SetAllParameters();
AliGenMC::Init();
fUHKMgen->Initialize();
CheckPDGTable();
fUHKMgen->Print();
}
//________________________________________
void AliGenUHKM::Generate()
{
// Generate one HYDJET++ event, get the output and push particles further
// to AliRoot's stack
Float_t polar[3] = {0,0,0};
Float_t origin[3] = {0,0,0};
Float_t origin0[3] = {0,0,0};
Float_t time0 = 0.;
Float_t p[3];
Float_t v[3];
Float_t mass=0.0, energy=0.0;
Vertex();
for(Int_t j=0; j<3; j++) origin0[j] = fVertex[j];
time0 = fTime;
// Generate the event and import particles
fUHKMgen->GenerateEvent();
fUHKMgen->ImportParticles(&fParticles,"All");
Int_t np = fParticles.GetEntriesFast();
Int_t nt = 0;
// Handle the IDs of particles on the stack
Int_t* idsOnStack = new Int_t[np];
Int_t* newPos = new Int_t[np];
for(Int_t i=0; i<np; i++) {
newPos[i] = i;
idsOnStack[i] = -1;
}
// Generate a random phi used to rotate the whole event
Double_t eventRotation = gRandom->Rndm()*TMath::Pi();
TParticle *iparticle;
Double_t partMomPhi=0.0, partPt=0.0;
Double_t partVtxPhi=0.0, partVtxR=0.0;
//_________ Loop for particles in the stack
for(Int_t i=0; i<np; i++) {
iparticle = (TParticle*)fParticles.At(i);
Int_t kf = iparticle->GetPdgCode();
Bool_t hasMother = (iparticle->GetFirstMother() >= 0);
Bool_t hasDaughter = (iparticle->GetNDaughters() > 0);
if(hasDaughter) {
// This particle has decayed
// It will not be tracked
// Add it only once with coordinates not
// smeared with primary vertex position
// rotate the direction of the particle
partMomPhi = TMath::ATan2(iparticle->Py(), iparticle->Px());
partPt = TMath::Hypot(iparticle->Px(), iparticle->Py());
p[0] = partPt*TMath::Cos(partMomPhi+eventRotation);
p[1] = partPt*TMath::Sin(partMomPhi+eventRotation);
p[2] = iparticle->Pz();
mass = TDatabasePDG::Instance()->GetParticle(kf)->Mass();
energy = sqrt(mass*mass + p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);
// rotate the freezeout point
partVtxPhi = TMath::ATan2(iparticle->Vy(), iparticle->Vx());
partVtxR = TMath::Hypot(iparticle->Vx(), iparticle->Vy());
v[0] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[1] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[2] = iparticle->Vz();
Float_t time = iparticle->T();
Int_t imo = -1;
if(hasMother) {
imo = iparticle->GetFirstMother(); //index of mother particle in fParticles
} // if has mother
Bool_t trackFlag = kFALSE; // tFlag is kFALSE --> do not track the particle
PushTrack(trackFlag, (imo>=0 ? idsOnStack[imo] : imo), kf,
p[0], p[1], p[2], energy,
v[0], v[1], v[2], time,
polar[0], polar[1], polar[2],
(hasMother ? kPDecay : kPNoProcess), nt);
idsOnStack[i] = nt;
fNprimaries++;
KeepTrack(nt);
}
else {
// This is a final state particle
// It will be tracked
// Add it TWICE to the stack !!!
// First time with event-wide coordinates (for femtoscopy) -
// this one will not be tracked
// Second time with event-wide c0ordinates and vertex smearing
// this one will be tracked
// rotate the direction of the particle
partMomPhi = TMath::ATan2(iparticle->Py(), iparticle->Px());
partPt = TMath::Hypot(iparticle->Px(), iparticle->Py());
p[0] = partPt*TMath::Cos(partMomPhi+eventRotation);
p[1] = partPt*TMath::Sin(partMomPhi+eventRotation);
p[2] = iparticle->Pz();
energy = sqrt(mass*mass + p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);
// rotate the freezeout point
partVtxPhi = TMath::ATan2(iparticle->Vy(), iparticle->Vx());
partVtxR = TMath::Hypot(iparticle->Vx(), iparticle->Vy());
v[0] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[1] = partVtxR*TMath::Cos(partVtxPhi + eventRotation);
v[2] = iparticle->Vz();
Int_t type = iparticle->GetStatusCode(); // 1-from jet / 0-from hydro
Int_t coeffT=1;
if(type==1) coeffT=-1; //to separate particles from jets
Int_t imo = -1;
if(hasMother) {
imo = iparticle->GetFirstMother();
} // if has mother
Bool_t trackFlag = kFALSE; // tFlag = kFALSE --> do not track this one, its for femtoscopy
PushTrack(trackFlag, (imo>=0 ? idsOnStack[imo] : imo), kf,
p[0], p[1], p[2], energy,
v[0], v[1], v[2], (iparticle->T())*coeffT, // freeze-out time is negative if the particle comes from jet
polar[0], polar[1], polar[2],
hasMother ? kPDecay:kPNoProcess, nt);
idsOnStack[i] = nt;
fNprimaries++;
KeepTrack(nt);
origin[0] = origin0[0]+v[0];
origin[1] = origin0[1]+v[1];
origin[2] = origin0[2]+v[2];
Float_t time = time0+iparticle->T();
imo = nt;
trackFlag = fTrackIt; // Track this particle, unless otherwise specified by fTrackIt
PushTrack(trackFlag, imo, kf,
p[0], p[1], p[2], energy,
origin[0], origin[1], origin[2], time,
polar[0], polar[1], polar[2],
hasMother ? kPDecay:kPNoProcess, nt);
fNprimaries++;
KeepTrack(nt);
}
}
SetHighWaterMark(fNprimaries);
TArrayF eventVertex;
eventVertex.Set(3);
eventVertex[0] = origin0[0];
eventVertex[1] = origin0[1];
eventVertex[2] = origin0[2];
Float_t eventTime = time0;
// Builds the event header, to be called after each event
AliGenEventHeader* header = new AliGenHijingEventHeader("UHKM");
Double_t b = 0.;
Double_t npart = 0;
Double_t nbin = 0;
fUHKMgen->GetCentrality(b, npart, nbin);
printf("********** %13.3f %13.3f %13.3f \n", b, npart, nbin);
((AliGenHijingEventHeader*) header)->SetNProduced(fNprimaries);
((AliGenHijingEventHeader*) header)->SetPrimaryVertex(eventVertex);
((AliGenHijingEventHeader*) header)->SetInteractionTime(eventTime);
((AliGenHijingEventHeader*) header)->SetImpactParameter(b);
((AliGenHijingEventHeader*) header)->SetTotalEnergy(0.0);
((AliGenHijingEventHeader*) header)->SetHardScatters(0);
((AliGenHijingEventHeader*) header)->SetParticipants(Int_t(npart), 0);
((AliGenHijingEventHeader*) header)->SetCollisions(Int_t(nbin), 0, 0, 0);
((AliGenHijingEventHeader*) header)->SetSpectators(0, 0, 0, 0);
((AliGenHijingEventHeader*) header)->SetReactionPlaneAngle(0);//evrot);
header->SetPrimaryVertex(fVertex);
header->SetInteractionTime(fTime);
AddHeader(header);
fCollisionGeometry = (AliGenHijingEventHeader*) header;
delete [] idsOnStack;
delete [] newPos;
}
void AliGenUHKM::Copy(TObject &) const
{
Fatal("Copy","Not implemented!\n");
}
void AliGenUHKM::SetAllParameters() {
// Forward all input parameters to the TGenerator::TUHKMgen object
fUHKMgen->SetEcms(fHydjetParams.fSqrtS);
fUHKMgen->SetBmin(fHydjetParams.fBmin);
fUHKMgen->SetBmax(fHydjetParams.fBmax);
fUHKMgen->SetAw(fHydjetParams.fAw);
fUHKMgen->SetSeed(fHydjetParams.fSeed);
fUHKMgen->SetChFrzTemperature(fHydjetParams.fT);
fUHKMgen->SetMuB(fHydjetParams.fMuB);
fUHKMgen->SetMuS(fHydjetParams.fMuS);
fUHKMgen->SetMuQ(fHydjetParams.fMuI3);
fUHKMgen->SetTauB(fHydjetParams.fTau);
fUHKMgen->SetThFrzTemperature(fHydjetParams.fThFO);
fUHKMgen->SetMuPionThermal(fHydjetParams.fMu_th_pip);
fUHKMgen->SetSigmaTau(fHydjetParams.fSigmaTau);
fUHKMgen->SetRmaxB(fHydjetParams.fR);
fUHKMgen->SetYlMax(fHydjetParams.fYlmax);
fUHKMgen->SetEtaRMax(fHydjetParams.fUmax);
fUHKMgen->SetMomAsymmPar(fHydjetParams.fDelta);
fUHKMgen->SetCoordAsymmPar(fHydjetParams.fEpsilon);
fUHKMgen->SetGammaS(fHydjetParams.fCorrS);
fUHKMgen->SetEtaType(fHydjetParams.fEtaType);
fUHKMgen->SetFlagWeakDecay(fHydjetParams.fWeakDecay);
//PYQUEN parameters
fUHKMgen->SetPyquenNhsel(fHydjetParams.fNhsel);
fUHKMgen->SetPyquenShad(fHydjetParams.fIshad);
fUHKMgen->SetPyquenPtmin(fHydjetParams.fPtmin);
fUHKMgen->SetPyquenT0(fHydjetParams.fT0);
fUHKMgen->SetPyquenTau0(fHydjetParams.fTau0);
fUHKMgen->SetPyquenNf(fHydjetParams.fNf);
fUHKMgen->SetPyquenIenglu(fHydjetParams.fIenglu);
fUHKMgen->SetPyquenIanglu(fHydjetParams.fIanglu);
fUHKMgen->SetPDGParticleFile(fParticleFilename);
fUHKMgen->SetPDGDecayFile(fDecayFilename);
// fUHKMgen->SetUseCharmParticles(fUseCharmParticles);
// fUHKMgen->SetMinimumWidth(fMinWidth);
// fUHKMgen->SetMaximumWidth(fMaxWidth);
// fUHKMgen->SetMinimumMass(fMinMass);
// fUHKMgen->SetMaximumMass(fMaxMass);
// cout << "AliGenUHKM::Init() no. stable flagged particles = " << fStableFlagged << endl;
for(Int_t i=0; i<fStableFlagged; i++) {
// cout << "AliGenUHKM::Init() flag no. " << i
// << " PDG = " << fStableFlagPDG[i]
// << " flag = " << fStableFlagStatus[i] << endl;
fUHKMgen->SetPDGParticleStable(fStableFlagPDG[i], fStableFlagStatus[i]);
}
cout<<" Print all parameters "<<endl;
cout<<" SqrtS = "<<fHydjetParams.fSqrtS<<endl;
cout<<" Bmin = "<< fHydjetParams.fBmin<<endl;
cout<<" Bmax= "<<fHydjetParams.fBmax<<endl;
cout<<" Aw= "<<fHydjetParams.fAw<<endl;
cout<<" Seed= "<<fHydjetParams.fSeed<<endl;
cout<<" ---Stat-model parameters----------- "<<endl;
cout<<" ChFrzTemperature= "<<fHydjetParams.fT<<endl;
cout<<" MuB= "<<fHydjetParams.fMuB<<endl;
cout<<" MuS= "<<fHydjetParams.fMuS<<endl;
cout<<" MuQ= "<<fHydjetParams.fMuI3<<endl;
cout<<" TauB= "<<fHydjetParams.fTau<<endl;
cout<<" ThFrzTemperature= "<<fHydjetParams.fThFO<<endl;
cout<<" MuPionThermal= "<<fHydjetParams.fMu_th_pip<<endl;
cout<<"-----Volume parameters -------------- "<<endl;
cout<<" SigmaTau= "<<fHydjetParams.fSigmaTau<<endl;
cout<<" RmaxB= "<<fHydjetParams.fR<<endl;
cout<<" YlMax= "<<fHydjetParams.fYlmax<<endl;
cout<<" EtaRMax= "<<fHydjetParams.fUmax<<endl;
cout<<" MomAsymmPar= "<<fHydjetParams.fDelta<<endl;
cout<<" CoordAsymmPar= "<<fHydjetParams.fEpsilon<<endl;
cout<<" --------Flags------ "<<endl;
cout<<" GammaS= "<<fHydjetParams.fCorrS<<endl;
cout<<" EtaType= "<<fHydjetParams.fEtaType<<endl;
cout<<" FlagWeakDecay= "<<fHydjetParams.fWeakDecay<<endl;
cout<<"----PYQUEN parameters---"<<endl;
cout<<" Nhsel= "<<fHydjetParams.fNhsel<<endl;
cout<<" Shad= "<<fHydjetParams.fIshad<<endl;
cout<<" Ptmin= "<<fHydjetParams.fPtmin<<endl;
cout<<" T0= "<<fHydjetParams.fT0<<endl;
cout<<" Tau0= "<<fHydjetParams.fTau0<<endl;
cout<<" Nf= "<<fHydjetParams.fNf<<endl;
cout<<" Ienglu= "<<fHydjetParams.fIenglu<<endl;
cout<<" Ianglu= "<<fHydjetParams.fIanglu<<endl;
// cout<<"----PDG table parameters---"<<endl;
// cout<<" UseCharmParticles= "<<fUseCharmParticles<<endl;
// cout<<" MinimumWidth= "<<fMinWidth<<endl;
// cout<<" MaximumWidth= "<<fMaxWidth<<endl;
// cout<<" MinimumMass= "<<fMinMass<<endl;
// cout<<" MaximumMass= "<<fMaxMass<<endl;
// cout << "AliGenUHKM::SetAllParameters() OUT" << endl;
}
// add the additional PDG codes from UHKM(SHARE table) to ROOT's table
void AliGenUHKM::CheckPDGTable() {
// Add temporarely all particle definitions from HYDJET++ which miss in the ROOT's PDG tables
// to the TDatabasePDG table.
DatabasePDG *uhkmPDG = fUHKMgen->PDGInfo(); // UHKM's PDG table
TParticlePDG *rootTestParticle;
ParticlePDG *uhkmTestParticle;
// loop over all particles in the SHARE table
for(Int_t i=0; i<uhkmPDG->GetNParticles(); i++) {
// get a particle specie
uhkmTestParticle = uhkmPDG->GetPDGParticleByIndex(i);
// check if this code exists in ROOT's table
rootTestParticle = TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG());
if(!rootTestParticle) { // if not then add it to the ROOT's PDG database
TDatabasePDG::Instance()->AddParticle(uhkmTestParticle->GetName(), uhkmTestParticle->GetName(),
uhkmTestParticle->GetMass(), uhkmTestParticle->GetElectricCharge(),
(uhkmTestParticle->GetWidth()<1e-10 ? kTRUE : kFALSE),
uhkmTestParticle->GetWidth(),
(Int_t(uhkmTestParticle->GetBaryonNumber())==0 ? "meson" : "baryon"),
uhkmTestParticle->GetPDG());
if(uhkmTestParticle->GetWidth()<1e-10)
cout << uhkmTestParticle->GetPDG() << " with mass "
<< TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG())->Mass()
<< TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG())->Width() << endl;
}
} // end for
}
| 35.287023
| 109
| 0.637304
|
AllaMaevskaya
|
8e19f72fb5aa9c9e2c6dcc6fd006fdb906053580
| 321
|
cpp
|
C++
|
CodeChef/Begginer-Problems/FACTRL2.cpp
|
annukamat/My-Competitive-Journey
|
adb13a5723483cde13e5f3859b3a7ad840b86c97
|
[
"MIT"
] | 7
|
2018-11-08T11:39:27.000Z
|
2020-09-10T17:50:57.000Z
|
CodeChef/Begginer-Problems/FACTRL2.cpp
|
annukamat/My-Competitive-Journey
|
adb13a5723483cde13e5f3859b3a7ad840b86c97
|
[
"MIT"
] | null | null | null |
CodeChef/Begginer-Problems/FACTRL2.cpp
|
annukamat/My-Competitive-Journey
|
adb13a5723483cde13e5f3859b3a7ad840b86c97
|
[
"MIT"
] | 2
|
2019-09-16T14:34:03.000Z
|
2019-10-12T19:24:00.000Z
|
#include <iostream>
#include <vector>
using namespace std;
long long int fact(int n){
if(n==1 || n==0){
return 1;
}else{
return n*fact(n-1);
}
}
int main(){
int t,n;
cin>>t;
vector<int>a;
while(t--){
cin>>n;
cout<<fact(n)<<"\n";
}
return 0;
}
| 13.956522
| 28
| 0.457944
|
annukamat
|
8e1b77a1b41375bf2e83aaaa75576ef7a55dea34
| 16,114
|
cc
|
C++
|
LuaKitProject/src/Projects/common/common/business_client_thread_impl.cc
|
andrewvmail/luakit
|
edbadd7824bd17b6a430d8323f255d404498c27a
|
[
"MIT"
] | 321
|
2018-06-17T03:52:46.000Z
|
2022-03-18T02:34:52.000Z
|
LuaKitProject/src/Projects/common/common/business_client_thread_impl.cc
|
andrewvmail/luakit
|
edbadd7824bd17b6a430d8323f255d404498c27a
|
[
"MIT"
] | 19
|
2018-06-26T10:37:45.000Z
|
2020-12-09T03:16:45.000Z
|
LuaKitProject/src/Projects/common/common/business_client_thread_impl.cc
|
andrewvmail/luakit
|
edbadd7824bd17b6a430d8323f255d404498c27a
|
[
"MIT"
] | 58
|
2018-06-21T10:43:03.000Z
|
2022-03-29T12:42:11.000Z
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "common/business_client_thread_impl.h"
#include <string>
#include "base/atomicops.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h"
#include "common/business_client_thread_delegate.h"
#include "tools/lua_helpers.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lstate.h"
}
namespace {
struct BusinessThreadGlobals {
BusinessThreadGlobals()
: blocking_pool(new base::SequencedWorkerPool(3, "BusinessBlocking")) {
}
// This lock protects |threads|. Do not read or modify that array
// without holding this lock. Do not block while holding this lock.
base::Lock lock;
// This array is protected by |lock|. The threads are not owned by this
// array. Typically, the threads are owned on the UI thread by
// content::BusinessMainLoop. BusinessThreadImpl objects remove themselves from
// this array upon destruction.
std::vector<BusinessThreadImpl*> threads;
std::vector<lua_State*> luaStates;
// Only atomic operations are used on this array. The delegates are not owned
// by this array, rather by whoever calls BusinessThread::SetDelegate.
std::vector<content::BusinessThreadDelegate*> thread_delegates;
const scoped_refptr<base::SequencedWorkerPool> blocking_pool;
};
base::LazyInstance<BusinessThreadGlobals>::Leaky
g_globals = LAZY_INSTANCE_INITIALIZER;
} // namespace
BusinessThreadImpl::BusinessThreadImpl(BusinessThreadID identifier,const char * thread_name)
: Thread(thread_name),
identifier_(identifier) {
BusinessThreadGlobals& globals = g_globals.Get();
globals.threads.push_back(NULL);
globals.luaStates.push_back(NULL);
globals.thread_delegates.push_back(NULL);
Initialize();
}
BusinessThreadImpl::BusinessThreadImpl(BusinessThreadID identifier,
base::MessageLoop* message_loop)
: Thread(message_loop->thread_name().c_str()),
identifier_(identifier) {
BusinessThreadGlobals& globals = g_globals.Get();
globals.threads.push_back(NULL);
globals.luaStates.push_back(NULL);
globals.thread_delegates.push_back(NULL);
set_message_loop(message_loop);
Initialize();
}
// static
void BusinessThreadImpl::ShutdownThreadPool() {
BusinessThreadGlobals& globals = g_globals.Get();
globals.blocking_pool->Shutdown();
}
void BusinessThreadImpl::Init() {
BusinessThreadGlobals& globals = g_globals.Get();
using base::subtle::AtomicWord;
AtomicWord* storage =
reinterpret_cast<AtomicWord*>(&globals.thread_delegates[identifier_]);
AtomicWord stored_pointer = base::subtle::NoBarrier_Load(storage);
content::BusinessThreadDelegate* delegate =
reinterpret_cast<content::BusinessThreadDelegate*>(stored_pointer);
if (delegate)
delegate->Init();
}
void BusinessThreadImpl::CleanUp() {
BusinessThreadGlobals& globals = g_globals.Get();
using base::subtle::AtomicWord;
AtomicWord* storage =
reinterpret_cast<AtomicWord*>(&globals.thread_delegates[identifier_]);
AtomicWord stored_pointer = base::subtle::NoBarrier_Load(storage);
content::BusinessThreadDelegate* delegate =
reinterpret_cast<content::BusinessThreadDelegate*>(stored_pointer);
if (delegate)
delegate->CleanUp();
}
void BusinessThreadImpl::Initialize() {
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
DCHECK(identifier_ >= 0 && identifier_ < BusinessThread::getThreadCount());
DCHECK(globals.threads[identifier_] == NULL);
globals.threads[identifier_] = this;
if(identifier_ == UI){
lua_State* luaState = luaL_newstate();
luaInit(luaState);
DLOG(INFO) << "UI luaL_newstate" << identifier_;
globals.luaStates[identifier_] = luaState;
}
}
BusinessThreadImpl::~BusinessThreadImpl() {
// All Thread subclasses must call Stop() in the destructor. This is
// doubly important here as various bits of code check they are on
// the right BusinessThread.
Stop();
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
globals.threads[identifier_] = NULL;
#ifndef NDEBUG
// Double check that the threads are ordered correctly in the enumeration.
for (int i = identifier_ + 1; i < BusinessThread::getThreadCount(); ++i) {
DCHECK(!globals.threads[i]) <<
"Threads must be listed in the reverse order that they die";
}
#endif
}
void BusinessThreadImpl::ThreadMain(){
BusinessThreadGlobals& globals = g_globals.Get();
lua_State* luaState = luaL_newstate();
luaInit(luaState);
LOG(INFO) << "BusinessThreadImpl::ThreadMain luaL_newstate" << identifier_;
globals.luaStates[identifier_] = luaState;
Thread::ThreadMain();
}
// static
bool BusinessThreadImpl::PostTaskHelper(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay,
bool nestable) {
DCHECK(identifier >= 0 && identifier < BusinessThread::getThreadCount());
// Optimization: to avoid unnecessary locks, we listed the ID enumeration in
// order of lifetime. So no need to lock if we know that the other thread
// outlives this one.
// Note: since the array is so small, ok to loop instead of creating a map,
// which would require a lock because std::map isn't thread safe, defeating
// the whole purpose of this optimization.
BusinessThreadID current_thread;
bool guaranteed_to_outlive_target_thread =
GetCurrentThreadIdentifier(¤t_thread) &&
current_thread <= identifier;
BusinessThreadGlobals& globals = g_globals.Get();
if (!guaranteed_to_outlive_target_thread)
globals.lock.Acquire();
base::MessageLoop* message_loop = globals.threads[identifier] ?
globals.threads[identifier]->message_loop() : NULL;
if (message_loop) {
if (nestable) {
message_loop->PostDelayedTask(from_here, task, delay);
} else {
message_loop->PostNonNestableDelayedTask(from_here, task, delay);
}
}
if (!guaranteed_to_outlive_target_thread)
globals.lock.Release();
return !!message_loop;
}
// An implementation of MessageLoopProxy to be used in conjunction
// with BusinessThread.
class BusinessThreadMessageLoopProxy : public base::MessageLoopProxy {
public:
explicit BusinessThreadMessageLoopProxy(BusinessThreadID identifier)
: id_(identifier) {
}
// MessageLoopProxy implementation.
// virtual bool PostDelayedTask(
// const tracked_objects::Location& from_here,
// const base::Closure& task, int64 delay_ms) OVERRIDE {
// return BusinessThread::PostDelayedTask(id_, from_here, task, delay_ms);
// }
virtual bool PostDelayedTask(
const tracked_objects::Location& from_here,
const base::Closure& task, base::TimeDelta delay) OVERRIDE {
return BusinessThread::PostDelayedTask(id_, from_here, task, delay);
}
// virtual bool PostNonNestableDelayedTask(
// const tracked_objects::Location& from_here,
// const base::Closure& task,
// int64 delay_ms) OVERRIDE {
// return BusinessThread::PostNonNestableDelayedTask(id_, from_here, task,
// delay_ms);
// }
virtual bool PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay) OVERRIDE {
return BusinessThread::PostNonNestableDelayedTask(id_, from_here, task,
delay);
}
virtual bool RunsTasksOnCurrentThread() const OVERRIDE {
return BusinessThread::CurrentlyOn(id_);
}
protected:
virtual ~BusinessThreadMessageLoopProxy() {}
private:
BusinessThreadID id_;
DISALLOW_COPY_AND_ASSIGN(BusinessThreadMessageLoopProxy);
};
// static
bool BusinessThread::PostBlockingPoolTask(
const tracked_objects::Location& from_here,
const base::Closure& task) {
return g_globals.Get().blocking_pool->PostWorkerTask(from_here, task);
}
bool BusinessThread::PostBlockingPoolTaskAndReply(
const tracked_objects::Location& from_here,
const base::Closure& task,
const base::Closure& reply) {
return g_globals.Get().blocking_pool->PostTaskAndReply(
from_here, task, reply);
}
// static
bool BusinessThread::PostBlockingPoolSequencedTask(
const std::string& sequence_token_name,
const tracked_objects::Location& from_here,
const base::Closure& task) {
return g_globals.Get().blocking_pool->PostNamedSequencedWorkerTask(
sequence_token_name, from_here, task);
}
// static
base::SequencedWorkerPool* BusinessThread::GetBlockingPool() {
return g_globals.Get().blocking_pool;
}
// static
bool BusinessThread::IsWellKnownThread(BusinessThreadID identifier) {
if (g_globals == NULL)
return false;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
return (identifier >= 0 && identifier < BusinessThread::getThreadCount() &&
globals.threads[identifier]);
}
// static
bool BusinessThread::CurrentlyOn(BusinessThreadID identifier) {
// We shouldn't use MessageLoop::current() since it uses LazyInstance which
// may be deleted by ~AtExitManager when a WorkerPool thread calls this
// function.
// http://crbug.com/63678
base::ThreadRestrictions::ScopedAllowSingleton allow_singleton;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
DCHECK(identifier >= 0 && identifier < BusinessThread::getThreadCount());
return globals.threads[identifier] &&
globals.threads[identifier]->message_loop() ==
base::MessageLoop::current();
}
// static
bool BusinessThread::IsMessageLoopValid(BusinessThreadID identifier) {
if (g_globals == NULL)
return false;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
DCHECK(identifier >= 0 && identifier < BusinessThread::getThreadCount());
return globals.threads[identifier] &&
globals.threads[identifier]->message_loop();
}
// static
bool BusinessThread::PostTask(BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, base::TimeDelta(), true);
}
// static
bool BusinessThread::PostDelayedTask(BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
int64 delay_ms) {
return BusinessThreadImpl::PostTaskHelper(
identifier,
from_here,
task,
base::TimeDelta::FromMilliseconds(delay_ms),
true);
}
// static
bool BusinessThread::PostDelayedTask(BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, delay, true);
}
// static
bool BusinessThread::PostNonNestableTask(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, base::TimeDelta(), false);
}
// static
bool BusinessThread::PostNonNestableDelayedTask(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
int64 delay_ms) {
return BusinessThreadImpl::PostTaskHelper(
identifier,
from_here,
task,
base::TimeDelta::FromMilliseconds(delay_ms),
false);
}
// static
bool BusinessThread::PostNonNestableDelayedTask(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
base::TimeDelta delay) {
return BusinessThreadImpl::PostTaskHelper(
identifier, from_here, task, delay, false);
}
// static
bool BusinessThread::PostTaskAndReply(
BusinessThreadID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task,
const base::Closure& reply) {
return GetMessageLoopProxyForThread(identifier)->PostTaskAndReply(from_here,
task,
reply);
}
// static
bool BusinessThread::GetCurrentThreadIdentifier(BusinessThreadID* identifier) {
if (g_globals == NULL)
return false;
// We shouldn't use MessageLoop::current() since it uses LazyInstance which
// may be deleted by ~AtExitManager when a WorkerPool thread calls this
// function.
// http://crbug.com/63678
base::ThreadRestrictions::ScopedAllowSingleton allow_singleton;
base::MessageLoop* cur_message_loop = base::MessageLoop::current();
BusinessThreadGlobals& globals = g_globals.Get();
for (int i = 0; i < BusinessThread::getThreadCount(); ++i) {
if (globals.threads[i] &&
globals.threads[i]->message_loop() == cur_message_loop) {
*identifier = globals.threads[i]->identifier_;
return true;
}
}
return false;
}
bool BusinessThread::GetThreadIdentifierByName(BusinessThreadID* identifier, std::string name) {
if (g_globals == NULL)
return false;
// We shouldn't use MessageLoop::current() since it uses LazyInstance which
// may be deleted by ~AtExitManager when a WorkerPool thread calls this
// function.
// http://crbug.com/63678
base::ThreadRestrictions::ScopedAllowSingleton allow_singleton;
BusinessThreadGlobals& globals = g_globals.Get();
for (int i = 0; i < BusinessThread::getThreadCount(); ++i) {
if (globals.threads[i] &&
globals.threads[i]->thread_name() == name) {
*identifier = globals.threads[i]->identifier_;
return true;
}
}
return false;
}
lua_State* BusinessThread::GetCurrentThreadLuaState(){
base::MessageLoop* cur_message_loop = base::MessageLoop::current();
BusinessThreadGlobals& globals = g_globals.Get();
for (int i = 0; i < BusinessThread::getThreadCount(); ++i) {
if (globals.threads[i] &&
globals.threads[i]->message_loop() == cur_message_loop) {
return globals.luaStates[i];
}
}
return NULL;
}
int BusinessThread::getThreadCount(){
BusinessThreadGlobals& globals = g_globals.Get();
return (int)globals.threads.size();
}
// static
scoped_refptr<base::MessageLoopProxy>
BusinessThread::GetMessageLoopProxyForThread(BusinessThreadID identifier) {
scoped_refptr<base::MessageLoopProxy> proxy(
new BusinessThreadMessageLoopProxy(identifier));
return proxy;
}
// static
base::MessageLoop* BusinessThread::UnsafeGetMessageLoopForThread(BusinessThreadID identifier) {
if (g_globals == NULL)
return NULL;
BusinessThreadGlobals& globals = g_globals.Get();
base::AutoLock lock(globals.lock);
base::Thread* thread = globals.threads[identifier];
DCHECK(thread);
base::MessageLoop* loop = thread->message_loop();
return loop;
}
// static
void BusinessThread::SetDelegate(BusinessThreadID identifier,
content::BusinessThreadDelegate* delegate) {
using base::subtle::AtomicWord;
BusinessThreadGlobals& globals = g_globals.Get();
AtomicWord* storage = reinterpret_cast<AtomicWord*>(
&globals.thread_delegates[identifier]);
AtomicWord old_pointer = base::subtle::NoBarrier_AtomicExchange(
storage, reinterpret_cast<AtomicWord>(delegate));
// This catches registration when previously registered.
DCHECK(!delegate || !old_pointer);
}
| 34.139831
| 96
| 0.707459
|
andrewvmail
|
8e1f39860ad53ee845c9229cd700b5083a830a9c
| 651
|
cpp
|
C++
|
Online Judges/Huxley/93GatoNoChapeu.cpp
|
NelsonGomesNeto/ProgramC
|
e743b1b869f58f7f3022d18bac00c5e0b078562e
|
[
"MIT"
] | 3
|
2018-12-18T13:39:42.000Z
|
2021-06-23T18:05:18.000Z
|
Online Judges/Huxley/93GatoNoChapeu.cpp
|
NelsonGomesNeto/ProgramC
|
e743b1b869f58f7f3022d18bac00c5e0b078562e
|
[
"MIT"
] | 1
|
2018-11-02T21:32:40.000Z
|
2018-11-02T22:47:12.000Z
|
Online Judges/Huxley/93GatoNoChapeu.cpp
|
NelsonGomesNeto/ProgramC
|
e743b1b869f58f7f3022d18bac00c5e0b078562e
|
[
"MIT"
] | 6
|
2018-10-27T14:07:52.000Z
|
2019-11-14T13:49:29.000Z
|
#include <bits/stdc++.h>
#define lli long long int
int main()
{
lli height, working;
while (scanf("%lld %lld", &height, &working) && !(!height && !working))
{
for (lli n = 1, c = 1, cc = 1, h = height, pile = height; n < height;)
{
// printf("%lld %lld %lld\n", n, c, h);
if (h == 1) { printf("0 1\n"); break; }
c *= n;
h /= (n + 1);
pile += c * h;
if (h <= 1 && c != working)
n ++, c = 1, cc = 1, h = height, pile = height;
else if (h != 1) cc += c;
else if (h == 1 && c == working)
{
printf("%lld %lld\n", cc, pile);
break;
}
}
}
return(0);
}
| 24.111111
| 74
| 0.428571
|
NelsonGomesNeto
|
8e20ae742e2e67402b240670ebd6aeed26f4edb8
| 3,840
|
hpp
|
C++
|
Demos/Tests/TestBase/Camera.hpp
|
DhirajWishal/Flint
|
0750bd515de0b5cc3d23f7c2282c50ca483dff24
|
[
"Apache-2.0"
] | null | null | null |
Demos/Tests/TestBase/Camera.hpp
|
DhirajWishal/Flint
|
0750bd515de0b5cc3d23f7c2282c50ca483dff24
|
[
"Apache-2.0"
] | 1
|
2021-10-30T11:19:53.000Z
|
2021-10-30T11:19:54.000Z
|
Demos/Tests/TestBase/Camera.hpp
|
DhirajWishal/Flint
|
0750bd515de0b5cc3d23f7c2282c50ca483dff24
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021 Dhiraj Wishal
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "GraphicsCore/Device.hpp"
#include <glm/glm.hpp>
namespace Flint
{
/**
* Flint editor camera matrix.
*/
struct CameraMatrix
{
CameraMatrix(const glm::mat4& view, const glm::mat4& projection) : mViewMatrix(view), mProjectionMatrix(projection) {}
glm::mat4 mViewMatrix = glm::mat4(1);
glm::mat4 mProjectionMatrix = glm::mat4(1);
};
/**
* Flint editor camera.
*/
class Camera
{
public:
Camera();
/**
* Move the camera to the front.
*/
void MoveFront(uint64 delta);
/**
* Move the camera to the back.
*/
void MoveBack(uint64 delta);
/**
* Move the camera to the left.
*/
void MoveLeft(uint64 delta);
/**
* Move the camera to the right.
*/
void MoveRight(uint64 delta);
/**
* Handle mouse position.
*
* @param position The mouse position.
*/
void MousePosition(FExtent2D<float> position);
/**
* Update the camera.
* This updates all the vectors and matrices.
*/
void Update();
/**
* Get the default view projection matrices.
*
* @return The camera matrix.
*/
CameraMatrix GetMatrix() const { return CameraMatrix(viewMatrix, projectionMatrix); }
/**
* Reset the first mouse boolean value to its default (true).
*/
void ResetFirstMouse();
/**
* Set the camera aspect ratio.
*
* @param extent The display extent.
*/
void SetAspectRatio(FBox2D extent);
public:
/**
* Get the camera position.
*
* @return The position vector.
*/
const glm::vec3 GetPosition() const { return mPosition; }
/**
* Set the camera position.
*
* @param position The camera position.
*/
void SetPosition(glm::vec3 position) { mPosition = position; }
/**
* Get the camera up vector.
*
* @return The camera up vector.
*/
const glm::vec3 GetCameraUp() const { return mUp; }
/**
* Get the camera front vector.
*
* @return The camera front vector.
*/
const glm::vec3 GetCameraFront() const { return mFront; }
/**
* Set the camera's range (far and near plane).
*
* @param near The near plane.
* @param far The far plane.
*/
void SetCameraRange(float near, float far) { mCameraNear = near, mCameraFar = far; }
/**
* Get the camera range.
*
* @return The near and far plane.
*/
const std::pair<float, float> GetCameraRange() const { return { mCameraNear, mCameraFar }; }
/**
* Get the camera pitch and yaw values.
*
* @return The rotation values.
*/
const std::pair<float, float> GetPitchYaw() const { return { mPitch, mYaw }; }
/**
* Set the camera view matrix.
*
* @param mat The matrix to set.
*/
void SetViewMatrix(glm::mat4 mat) { viewMatrix = mat; }
/**
* Set the movement bias.
*
* @param bias The bias to set.
*/
void SetMovementBias(const float bias) { mMovementBias = bias; }
/**
* Get the movement bias.
*
* @return The movement bias.
*/
float& GetMovementBias() { return mMovementBias; }
private:
glm::mat4 viewMatrix = glm::mat4(1);
glm::mat4 projectionMatrix = glm::mat4(1);
glm::vec3 mPosition = glm::vec3{ 0.0f, 1.0f, 0.0f };
glm::vec3 mUp = glm::vec3{ 0.0f, 1.0f, 0.0f };
glm::vec3 mFront = glm::vec3{ 0.0f, 0.0f, -1.0f };
glm::vec3 mRight = glm::vec3{ 1.0f, 0.0f, 0.0f };
glm::vec3 mWorldUp = glm::vec3{ 0.0f, 1.0f, 0.0f };
float mMovementBias = 0.05f;
float mFieldOfView = 60.0f;
float mAspectRatio = 0.5f;
float mCameraFar = 256.0f;
float mCameraNear = 0.001f;
float mAngelX = 0.0f;
float mAngelY = 0.0f;
float mAngelZ = 0.0f;
float mLastX = 0.0f;
float mLastY = 0.0f;
float mYaw = 90.0f;
float mPitch = 0.0f;
uint32 mWindowWidth = 0;
uint32 mWindowHeight = 0;
bool bFirstMouse = true;
};
}
| 20.645161
| 120
| 0.622396
|
DhirajWishal
|
8e22e8d5c0651e4c65a88720de2083de7edd2054
| 7,199
|
cc
|
C++
|
systems/controllers/pid_controlled_system.cc
|
RobotLocomotion/drake-python3.7
|
ae397a4c6985262d23e9675b9bf3927c08d027f5
|
[
"BSD-3-Clause"
] | 2
|
2021-02-25T02:01:02.000Z
|
2021-03-17T04:52:04.000Z
|
systems/controllers/pid_controlled_system.cc
|
RobotLocomotion/drake-python3.7
|
ae397a4c6985262d23e9675b9bf3927c08d027f5
|
[
"BSD-3-Clause"
] | null | null | null |
systems/controllers/pid_controlled_system.cc
|
RobotLocomotion/drake-python3.7
|
ae397a4c6985262d23e9675b9bf3927c08d027f5
|
[
"BSD-3-Clause"
] | 1
|
2021-06-13T12:05:39.000Z
|
2021-06-13T12:05:39.000Z
|
#include "drake/systems/controllers/pid_controlled_system.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/systems/primitives/saturation.h"
namespace drake {
namespace systems {
namespace controllers {
template <typename T>
PidControlledSystem<T>::PidControlledSystem(std::unique_ptr<System<T>> plant,
double Kp, double Ki, double Kd,
int state_output_port_index,
int plant_input_port_index)
: state_output_port_index_(state_output_port_index),
plant_input_port_index_{plant_input_port_index} {
const int input_size = plant->get_input_port(plant_input_port_index_).size();
const Eigen::VectorXd Kp_v = Eigen::VectorXd::Ones(input_size) * Kp;
const Eigen::VectorXd Ki_v = Eigen::VectorXd::Ones(input_size) * Ki;
const Eigen::VectorXd Kd_v = Eigen::VectorXd::Ones(input_size) * Kd;
const MatrixX<double> selector = MatrixX<double>::Identity(
plant->get_input_port(plant_input_port_index_).size() * 2,
plant->get_input_port(plant_input_port_index_).size() * 2);
Initialize(std::move(plant), selector, Kp_v, Ki_v, Kd_v);
}
template <typename T>
PidControlledSystem<T>::PidControlledSystem(std::unique_ptr<System<T>> plant,
const Eigen::VectorXd& Kp,
const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd,
int state_output_port_index,
int plant_input_port_index)
: PidControlledSystem(
std::move(plant),
MatrixX<double>::Identity(2 * Kp.size(), 2 * Kp.size()), Kp, Ki, Kd,
state_output_port_index, plant_input_port_index) {}
template <typename T>
PidControlledSystem<T>::PidControlledSystem(
std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector,
double Kp, double Ki, double Kd, int state_output_port_index,
int plant_input_port_index)
: state_output_port_index_(state_output_port_index),
plant_input_port_index_{plant_input_port_index} {
const int input_size = plant->get_input_port(plant_input_port_index_).size();
const Eigen::VectorXd Kp_v = Eigen::VectorXd::Ones(input_size) * Kp;
const Eigen::VectorXd Ki_v = Eigen::VectorXd::Ones(input_size) * Ki;
const Eigen::VectorXd Kd_v = Eigen::VectorXd::Ones(input_size) * Kd;
Initialize(std::move(plant), feedback_selector, Kp_v, Ki_v, Kd_v);
}
template <typename T>
PidControlledSystem<T>::PidControlledSystem(
std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd, int state_output_port_index,
int plant_input_port_index)
: state_output_port_index_(state_output_port_index),
plant_input_port_index_{plant_input_port_index} {
Initialize(std::move(plant), feedback_selector, Kp, Ki, Kd);
}
template <typename T>
void PidControlledSystem<T>::Initialize(
std::unique_ptr<System<T>> plant, const MatrixX<double>& feedback_selector,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd) {
DRAKE_DEMAND(plant != nullptr);
DiagramBuilder<T> builder;
plant_ = builder.template AddSystem(std::move(plant));
DRAKE_ASSERT(plant_->num_input_ports() >= 1);
DRAKE_ASSERT(plant_->num_output_ports() >= 1);
// state_output_port_index_ will be checked by the get_output_port call below.
auto input_ports =
ConnectController(plant_->get_input_port(plant_input_port_index_),
plant_->get_output_port(state_output_port_index_),
feedback_selector, Kp, Ki, Kd, &builder);
builder.ExportInput(input_ports.control_input_port);
builder.ExportInput(input_ports.state_input_port);
for (int i=0; i < plant_->num_output_ports(); i++) {
builder.ExportOutput(plant_->get_output_port(i));
}
builder.BuildInto(this);
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectController(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp,
const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd,
DiagramBuilder<T>* builder) {
auto controller = builder->template AddSystem<PidController<T>>(
feedback_selector,
Kp, Ki, Kd);
auto plant_input_adder =
builder->template AddSystem<Adder<T>>(2, plant_input.size());
builder->Connect(plant_output, controller->get_input_port_estimated_state());
builder->Connect(controller->get_output_port_control(),
plant_input_adder->get_input_port(0));
builder->Connect(plant_input_adder->get_output_port(), plant_input);
return ConnectResult{
plant_input_adder->get_input_port(1),
controller->get_input_port_desired_state()};
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectController(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd,
DiagramBuilder<T>* builder) {
return ConnectController(plant_input, plant_output,
MatrixX<double>::Identity(plant_output.size(), plant_output.size()),
Kp, Ki, Kd, builder);
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectControllerWithInputSaturation(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const MatrixX<double>& feedback_selector, const Eigen::VectorXd& Kp,
const Eigen::VectorXd& Ki, const Eigen::VectorXd& Kd,
const VectorX<T>& min_plant_input, const VectorX<T>& max_plant_input,
DiagramBuilder<T>* builder) {
auto saturation = builder->template AddSystem<Saturation<T>>(
min_plant_input, max_plant_input);
builder->Connect(saturation->get_output_port(), plant_input);
return
PidControlledSystem<T>::ConnectController(saturation->get_input_port(),
plant_output, feedback_selector, Kp, Ki, Kd, builder);
}
template <typename T>
typename PidControlledSystem<T>::ConnectResult
PidControlledSystem<T>::ConnectControllerWithInputSaturation(
const InputPort<T>& plant_input,
const OutputPort<T>& plant_output,
const Eigen::VectorXd& Kp, const Eigen::VectorXd& Ki,
const Eigen::VectorXd& Kd, const VectorX<T>& min_plant_input,
const VectorX<T>& max_plant_input, DiagramBuilder<T>* builder) {
return ConnectControllerWithInputSaturation(plant_input, plant_output,
MatrixX<double>::Identity(plant_output.size(), plant_output.size()),
Kp, Ki, Kd, min_plant_input, max_plant_input, builder);
}
template <typename T>
PidControlledSystem<T>::~PidControlledSystem() {}
} // namespace controllers
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS(
class ::drake::systems::controllers::PidControlledSystem)
| 42.347059
| 80
| 0.711488
|
RobotLocomotion
|
8e27b8f69bd4c6ef07d4ebdc6d55e6ba669c8e09
| 2,382
|
cpp
|
C++
|
Day12/12.cpp
|
Legolaszstudio/aoc2021
|
dc2e341738e11a55232ae0f37aa0cc5625d8d831
|
[
"BSD-3-Clause"
] | null | null | null |
Day12/12.cpp
|
Legolaszstudio/aoc2021
|
dc2e341738e11a55232ae0f37aa0cc5625d8d831
|
[
"BSD-3-Clause"
] | null | null | null |
Day12/12.cpp
|
Legolaszstudio/aoc2021
|
dc2e341738e11a55232ae0f37aa0cc5625d8d831
|
[
"BSD-3-Clause"
] | null | null | null |
#include <string>
#include <fstream>
#include <sstream>
#include <deque>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <set>
struct Graph {
std::unordered_map<std::string, std::vector<std::string>> tree;
//WARNING It is not the best option to store the entire solutions but I wanted to see all the combinations
std::vector<std::vector<std::string>> solutions;
};
void walkGraph(Graph& graph, std::string currentNode, std::vector<std::string> path, std::multiset<std::string> visited, bool partTwo);
void startSolving(Graph& graph, bool partTwo);
int main() {
Graph graph;
std::string line;
std::ifstream file("12.txt");
while (std::getline(file, line)) {
std::stringstream X(line);
std::string nodeName;
std::vector<std::string> temp = {};
while (std::getline(X, nodeName, '-')) {
temp.push_back(nodeName);
}
graph.tree[temp[0]].push_back(temp[1]);
graph.tree[temp[1]].push_back(temp[0]);
}
startSolving(graph, false);
int solution = graph.solutions.size();
std::cout << "There were " << solution << " possible solutions for part1" << std::endl;
std::cout << "To run second part press enter:" << std::endl << std::endl;
getchar();
graph.solutions = {};
startSolving(graph, true);
solution = graph.solutions.size();
std::cout << "There were " << solution << " possible solutions for part2" << std::endl;
return 0;
}
void startSolving(Graph& graph, bool partTwo) {
// Store solution
std::vector<std::string> path = {};
// Store visited nodes
std::multiset<std::string> visited = {};
// We visited twice
walkGraph(graph, "start", path, visited, partTwo);
}
void walkGraph(Graph& graph, std::string currentNode, std::vector<std::string> path, std::multiset<std::string> visited, bool partTwo) {
if (std::islower(currentNode[0])) {
if (visited.count(currentNode) == 1) { partTwo = false; }
visited.insert(currentNode);
}
path.push_back(currentNode);
if (currentNode == "end") {
graph.solutions.push_back(path);
//Uncomment to print solutions
//for (const auto& item : path) {
// std::cout << item << ",";
//}
//std::cout << std::endl;
} else {
for (const auto& item : graph.tree[currentNode]) {
if (item == "start") continue;
if (!visited.count(item) > 0 || (partTwo && visited.count(item) < 2)) {
walkGraph(graph, item, path, visited, partTwo);
}
}
}
}
| 30.538462
| 136
| 0.669186
|
Legolaszstudio
|
8e2ce4cd297c21145788a920086b875e6bc37617
| 12,262
|
cpp
|
C++
|
groups/bal/balb/balb_leakybucket.cpp
|
AlisdairM/bde
|
bc65db208c32513aa545080f57090cc39c608be0
|
[
"Apache-2.0"
] | 1
|
2022-01-23T11:31:12.000Z
|
2022-01-23T11:31:12.000Z
|
groups/bal/balb/balb_leakybucket.cpp
|
AlisdairM/bde
|
bc65db208c32513aa545080f57090cc39c608be0
|
[
"Apache-2.0"
] | null | null | null |
groups/bal/balb/balb_leakybucket.cpp
|
AlisdairM/bde
|
bc65db208c32513aa545080f57090cc39c608be0
|
[
"Apache-2.0"
] | null | null | null |
// balb_leakybucket.cpp -*-C++-*-
#include <balb_leakybucket.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(balb_leakybucket.cpp,"$Id$ $CSID$")
#include <bsl_c_math.h>
namespace BloombergLP {
namespace {
bsls::Types::Uint64 calculateNumberOfUnitsToDrain(
bsls::Types::Uint64* fractionalUnitDrainedInNanoUnits,
bsls::Types::Uint64 drainRate,
const bsls::TimeInterval& timeInterval)
// Return the number of units that would be drained from a leaky bucket
// over the specified 'timeInterval' at the specified 'drainRate', plus the
// specified 'fractionalUnitDrainedInNanoUnits', representing a fractional
// remainder from a previous call to 'calculateNumberOfUnitsToDrain'. Load
// into 'fractionalUnitDrainedInNanoUnits' the fractional remainder
// (between 0.0 and 1.0, represented in nano-units) from this calculation.
// The behavior is undefined unless
// '0 <= *fractionalUnitDrainedInNanoUnits < 1000000000' (i.e., it
// represents a value between 0 and 1 unit) and
// 'timeInterval.seconds() * drainRate <= ULLONG_MAX'. Note that
// 'fractionalUnitDrainedInNanoUnits' is represented in nano-units to avoid
// using a floating point representation.
{
const bsls::Types::Uint64 k_NANOUNITS_PER_UNIT = 1000000000;
BSLS_ASSERT(static_cast<bsls::Types::Uint64>(timeInterval.seconds()) <=
ULLONG_MAX / drainRate);
BSLS_ASSERT(0 != fractionalUnitDrainedInNanoUnits);
BSLS_ASSERT(*fractionalUnitDrainedInNanoUnits < k_NANOUNITS_PER_UNIT);
bsls::Types::Uint64 units = drainRate * timeInterval.seconds();
units += (drainRate / k_NANOUNITS_PER_UNIT) * timeInterval.nanoseconds();
bsls::Types::Uint64 nanounits = 0;
// As long as rate is represented by a whole number, the fractional part
// of number of units to drain comes from fractional part of seconds of
// the time interval
nanounits = *fractionalUnitDrainedInNanoUnits +
(drainRate % k_NANOUNITS_PER_UNIT) * timeInterval.nanoseconds();
*fractionalUnitDrainedInNanoUnits = nanounits % k_NANOUNITS_PER_UNIT;
units += nanounits / k_NANOUNITS_PER_UNIT;
return units;
}
} // close unnamed namespace
namespace balb {
//------------------
// class LeakyBucket
//------------------
// CLASS METHODS
bsls::Types::Uint64 LeakyBucket::calculateCapacity(
bsls::Types::Uint64 drainRate,
const bsls::TimeInterval& timeWindow)
{
BSLS_ASSERT(1 == drainRate ||
timeWindow <= LeakyBucket::calculateDrainTime(ULLONG_MAX,
drainRate,
false));
bsls::Types::Uint64 fractionalUnitsInNanoUnits = 0;
bsls::Types::Uint64 capacity = calculateNumberOfUnitsToDrain(
&fractionalUnitsInNanoUnits,
drainRate,
timeWindow);
// Round the returned capacity to 1, which is okay, because it does not
// affect the drain rate.
return (0 != capacity) ? capacity : 1;
}
bsls::TimeInterval LeakyBucket::calculateDrainTime(
bsls::Types::Uint64 numUnits,
bsls::Types::Uint64 drainRate,
bool ceilFlag)
{
BSLS_ASSERT(drainRate > 1 || numUnits <= LLONG_MAX);
bsls::TimeInterval interval(0,0);
interval.addSeconds(numUnits / drainRate);
bsls::Types::Uint64 remUnits = numUnits % drainRate;
const double nanoSecs = static_cast<double>(remUnits) * 1e9 /
static_cast<double>(drainRate);
interval.addNanoseconds(static_cast<bsls::Types::Int64>(
ceilFlag ? ceil(nanoSecs) : floor(nanoSecs)));
return interval;
}
bsls::TimeInterval LeakyBucket::calculateTimeWindow(
bsls::Types::Uint64 drainRate,
bsls::Types::Uint64 capacity)
{
BSLS_ASSERT(drainRate > 0);
BSLS_ASSERT(drainRate > 1 || capacity <= LLONG_MAX);
bsls::TimeInterval window = LeakyBucket::calculateDrainTime(capacity,
drainRate,
true);
if (0 == window) {
window.addNanoseconds(1);
}
return window;
}
// CREATORS
LeakyBucket::LeakyBucket(bsls::Types::Uint64 drainRate,
bsls::Types::Uint64 capacity,
const bsls::TimeInterval& currentTime)
: d_drainRate(drainRate)
, d_capacity(capacity)
, d_unitsReserved(0)
, d_unitsInBucket(0)
, d_fractionalUnitDrainedInNanoUnits(0)
, d_lastUpdateTime(currentTime)
, d_statSubmittedUnits(0)
, d_statSubmittedUnitsAtLastUpdate(0)
, d_statisticsCollectionStartTime(currentTime)
{
BSLS_ASSERT_OPT(0 < d_drainRate);
BSLS_ASSERT_OPT(0 < d_capacity);
BSLS_ASSERT(LLONG_MIN != currentTime.seconds());
// Calculate the maximum interval between updates that would not cause the
// number of units drained to overflow an unsigned 64-bit integral type.
if (drainRate == 1) {
// 'd_maxUpdateInterval' is a signed 64-bit integral type that can't
// represent 'ULLONG_MAX' number of seconds, so we set
// 'd_maxUpdateInterval' to the maximum representable value when
// 'drainRate' is 1.
d_maxUpdateInterval = bsls::TimeInterval(LLONG_MAX, 999999999);
}
else {
d_maxUpdateInterval = LeakyBucket::calculateDrainTime(ULLONG_MAX,
drainRate,
false);
}
}
// MANIPULATORS
bsls::TimeInterval LeakyBucket::calculateTimeToSubmit(
const bsls::TimeInterval& currentTime)
{
bsls::Types::Uint64 usedUnits = d_unitsInBucket + d_unitsReserved;
// Return 0-length time interval if units can be submitted right now.
if (usedUnits < d_capacity) {
return bsls::TimeInterval(0, 0); // RETURN
}
updateState(currentTime);
// Return 0-length time interval if units can be submitted after the state
// has been updated.
if (d_unitsInBucket + d_unitsReserved < d_capacity) {
return bsls::TimeInterval(0, 0); // RETURN
}
bsls::TimeInterval timeToSubmit(0,0);
bsls::Types::Uint64 backlogUnits;
// From here, 'd_unitsInBucket + d_unitsReserved' is always greater than
// 'd_capacity'
backlogUnits = d_unitsInBucket + d_unitsReserved - d_capacity + 1;
timeToSubmit = LeakyBucket::calculateDrainTime(backlogUnits,
d_drainRate,
true);
// Return 1 nanosecond if the time interval was rounded to zero (in cases
// of high drain rates).
if (timeToSubmit == 0) {
timeToSubmit.addNanoseconds(1);
}
return timeToSubmit;
}
void LeakyBucket::setRateAndCapacity(bsls::Types::Uint64 newRate,
bsls::Types::Uint64 newCapacity)
{
BSLS_ASSERT_SAFE(0 < newRate);
BSLS_ASSERT_SAFE(0 < newCapacity);
d_drainRate = newRate;
d_capacity = newCapacity;
// Calculate the maximum interval between updates that would not cause the
// number of units drained to overflow an unsigned 64-bit integral type.
if (newRate == 1) {
d_maxUpdateInterval = bsls::TimeInterval(LLONG_MAX, 999999999);
}
else {
d_maxUpdateInterval = LeakyBucket::calculateDrainTime(ULLONG_MAX,
newRate,
false);
}
}
void LeakyBucket::updateState(const bsls::TimeInterval& currentTime)
{
BSLS_ASSERT(LLONG_MIN != currentTime.seconds());
bsls::TimeInterval delta = currentTime - d_lastUpdateTime;
d_statSubmittedUnitsAtLastUpdate = d_statSubmittedUnits;
// If delta is greater than the time it takes to drain the maximum number
// of units representable by 64 bit integral type, then reset
// 'unitsInBucket'.
if (delta > d_maxUpdateInterval) {
d_lastUpdateTime = currentTime;
d_unitsInBucket = 0;
d_fractionalUnitDrainedInNanoUnits = 0;
return; // RETURN
}
if (delta >= bsls::TimeInterval(0, 0)) {
bsls::Types::Uint64 units;
units = calculateNumberOfUnitsToDrain(
&d_fractionalUnitDrainedInNanoUnits,
d_drainRate,
delta);
if (units < d_unitsInBucket) {
d_unitsInBucket -= units;
}
else {
d_unitsInBucket = 0;
}
}
else {
// The delta maybe negative when the system clocks are updated. If the
// specified 'currentTime' precedes 'statisticsCollectionStartTime',
// adjust it to prevent the statistics collection interval from going
// negative.
if (currentTime < d_statisticsCollectionStartTime) {
d_statisticsCollectionStartTime = currentTime;
}
}
d_lastUpdateTime = currentTime;
}
bool LeakyBucket::wouldOverflow(const bsls::TimeInterval& currentTime)
{
updateState(currentTime);
if (1 > ULLONG_MAX - d_unitsInBucket - d_unitsReserved ||
d_unitsInBucket + d_unitsReserved + 1 > d_capacity) {
return true; // RETURN
}
return false;
}
// ACCESSORS
void LeakyBucket::getStatistics(bsls::Types::Uint64* submittedUnits,
bsls::Types::Uint64* unusedUnits) const
{
BSLS_ASSERT(0 != submittedUnits);
BSLS_ASSERT(0 != unusedUnits);
*submittedUnits = d_statSubmittedUnitsAtLastUpdate;
bsls::Types::Uint64 fractionalUnits = 0;
// 'monitoredInterval' can not be negative, as the 'updateState' method
// ensures that 'd_lastUpdateTime' always precedes
// 'statisticsCollectionStartTime'.
bsls::TimeInterval monitoredInterval = d_lastUpdateTime -
d_statisticsCollectionStartTime;
bsls::Types::Uint64 drainedUnits = calculateNumberOfUnitsToDrain(
&fractionalUnits,
d_drainRate,
monitoredInterval);
if (drainedUnits < d_statSubmittedUnitsAtLastUpdate) {
*unusedUnits = 0;
}
else {
*unusedUnits = drainedUnits - d_statSubmittedUnitsAtLastUpdate;
}
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2021 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 36.494048
| 79
| 0.576333
|
AlisdairM
|
8e2efa1781bfb88bc7793216fa25a00987bde79b
| 681
|
cpp
|
C++
|
framework/source/metadata_backward_compatibility.cpp
|
xrEngine512/interop
|
c80711fbbe08f350ad5d8058163770f57ed20b0c
|
[
"MIT"
] | null | null | null |
framework/source/metadata_backward_compatibility.cpp
|
xrEngine512/interop
|
c80711fbbe08f350ad5d8058163770f57ed20b0c
|
[
"MIT"
] | 4
|
2017-05-31T12:34:10.000Z
|
2018-10-13T18:53:03.000Z
|
framework/source/metadata_backward_compatibility.cpp
|
xrEngine512/MosaicFramework
|
c80711fbbe08f350ad5d8058163770f57ed20b0c
|
[
"MIT"
] | 1
|
2020-04-23T14:09:11.000Z
|
2020-04-23T14:09:11.000Z
|
//
// Created by islam on 14.01.18.
//
#include "metadata_backward_compatibility.h"
#include "exceptions.h"
namespace interop {
module_metadata_t convert_metadata_to_current(const version_t & version, const void * metadata)
{
/** version of module's interop ABI matches version of node **/
if (version == interop_framework_abi_version_m) {
return *reinterpret_cast<const module_metadata_t *>(metadata);
} else {
throw error_t("unable to convert metadata of version " + version.to_string() +
" to current format version (" + interop_framework_abi_version_m.to_string() +
")");
}
}
} // namespace interop
| 32.428571
| 100
| 0.671072
|
xrEngine512
|
8e3ed45500eab3fc875fa1d2d2cfc349273f1962
| 14,036
|
hpp
|
C++
|
Svc/UdpReceiver/test/ut/Handcode/GTestBase.hpp
|
SSteve/fprime
|
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
|
[
"Apache-2.0"
] | 5
|
2019-10-22T03:41:02.000Z
|
2022-01-16T12:48:31.000Z
|
Svc/UdpReceiver/test/ut/Handcode/GTestBase.hpp
|
SSteve/fprime
|
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
|
[
"Apache-2.0"
] | 42
|
2021-06-10T23:31:10.000Z
|
2021-06-25T00:35:31.000Z
|
Svc/UdpReceiver/test/ut/Handcode/GTestBase.hpp
|
SSteve/fprime
|
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
|
[
"Apache-2.0"
] | 3
|
2020-09-05T18:17:21.000Z
|
2020-11-15T04:06:24.000Z
|
// ======================================================================
// \title UdpReceiver/test/ut/GTestBase.hpp
// \author Auto-generated
// \brief hpp file for UdpReceiver component Google Test harness base class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef UdpReceiver_GTEST_BASE_HPP
#define UdpReceiver_GTEST_BASE_HPP
#include "TesterBase.hpp"
#include "gtest/gtest.h"
// ----------------------------------------------------------------------
// Macros for telemetry history assertions
// ----------------------------------------------------------------------
#define ASSERT_TLM_SIZE(size) \
this->assertTlm_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_PacketsReceived_SIZE(size) \
this->assertTlm_UR_PacketsReceived_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_PacketsReceived(index, value) \
this->assertTlm_UR_PacketsReceived(__FILE__, __LINE__, index, value)
#define ASSERT_TLM_UR_BytesReceived_SIZE(size) \
this->assertTlm_UR_BytesReceived_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_BytesReceived(index, value) \
this->assertTlm_UR_BytesReceived(__FILE__, __LINE__, index, value)
#define ASSERT_TLM_UR_PacketsDropped_SIZE(size) \
this->assertTlm_UR_PacketsDropped_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_PacketsDropped(index, value) \
this->assertTlm_UR_PacketsDropped(__FILE__, __LINE__, index, value)
#define ASSERT_TLM_UR_DecodeErrors_SIZE(size) \
this->assertTlm_UR_DecodeErrors_size(__FILE__, __LINE__, size)
#define ASSERT_TLM_UR_DecodeErrors(index, value) \
this->assertTlm_UR_DecodeErrors(__FILE__, __LINE__, index, value)
// ----------------------------------------------------------------------
// Macros for event history assertions
// ----------------------------------------------------------------------
#define ASSERT_EVENTS_SIZE(size) \
this->assertEvents_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_PortOpened_SIZE(size) \
this->assertEvents_UR_PortOpened_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_PortOpened(index, _port) \
this->assertEvents_UR_PortOpened(__FILE__, __LINE__, index, _port)
#define ASSERT_EVENTS_UR_SocketError_SIZE(size) \
this->assertEvents_UR_SocketError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_SocketError(index, _error) \
this->assertEvents_UR_SocketError(__FILE__, __LINE__, index, _error)
#define ASSERT_EVENTS_UR_BindError_SIZE(size) \
this->assertEvents_UR_BindError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_BindError(index, _error) \
this->assertEvents_UR_BindError(__FILE__, __LINE__, index, _error)
#define ASSERT_EVENTS_UR_RecvError_SIZE(size) \
this->assertEvents_UR_RecvError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_RecvError(index, _error) \
this->assertEvents_UR_RecvError(__FILE__, __LINE__, index, _error)
#define ASSERT_EVENTS_UR_DecodeError_SIZE(size) \
this->assertEvents_UR_DecodeError_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_DecodeError(index, _stage, _error) \
this->assertEvents_UR_DecodeError(__FILE__, __LINE__, index, _stage, _error)
#define ASSERT_EVENTS_UR_DroppedPacket_SIZE(size) \
this->assertEvents_UR_DroppedPacket_size(__FILE__, __LINE__, size)
#define ASSERT_EVENTS_UR_DroppedPacket(index, _diff) \
this->assertEvents_UR_DroppedPacket(__FILE__, __LINE__, index, _diff)
namespace Svc {
//! \class UdpReceiverGTestBase
//! \brief Auto-generated base class for UdpReceiver component Google Test harness
//!
class UdpReceiverGTestBase :
public UdpReceiverTesterBase
{
protected:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
//! Construct object UdpReceiverGTestBase
//!
UdpReceiverGTestBase(
#if FW_OBJECT_NAMES == 1
const char *const compName, /*!< The component name*/
const U32 maxHistorySize /*!< The maximum size of each history*/
#else
const U32 maxHistorySize /*!< The maximum size of each history*/
#endif
);
//! Destroy object UdpReceiverGTestBase
//!
virtual ~UdpReceiverGTestBase(void);
protected:
// ----------------------------------------------------------------------
// Telemetry
// ----------------------------------------------------------------------
//! Assert size of telemetry history
//!
void assertTlm_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_PacketsReceived
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_PacketsReceived_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_PacketsReceived(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_BytesReceived
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_BytesReceived_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_BytesReceived(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_PacketsDropped
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_PacketsDropped_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_PacketsDropped(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Channel: UR_DecodeErrors
// ----------------------------------------------------------------------
//! Assert telemetry value in history at index
//!
void assertTlm_UR_DecodeErrors_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertTlm_UR_DecodeErrors(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32& val /*!< The channel value*/
) const;
protected:
// ----------------------------------------------------------------------
// Events
// ----------------------------------------------------------------------
void assertEvents_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_PortOpened
// ----------------------------------------------------------------------
void assertEvents_UR_PortOpened_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_PortOpened(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32 port
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_SocketError
// ----------------------------------------------------------------------
void assertEvents_UR_SocketError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_SocketError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const char *const error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_BindError
// ----------------------------------------------------------------------
void assertEvents_UR_BindError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_BindError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const char *const error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_RecvError
// ----------------------------------------------------------------------
void assertEvents_UR_RecvError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_RecvError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const char *const error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_DecodeError
// ----------------------------------------------------------------------
void assertEvents_UR_DecodeError_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_DecodeError(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
UdpReceiverComponentBase::DecodeStage stage,
const I32 error
) const;
protected:
// ----------------------------------------------------------------------
// Event: UR_DroppedPacket
// ----------------------------------------------------------------------
void assertEvents_UR_DroppedPacket_size(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 size /*!< The asserted size*/
) const;
void assertEvents_UR_DroppedPacket(
const char *const __callSiteFileName, /*!< The name of the file containing the call site*/
const U32 __callSiteLineNumber, /*!< The line number of the call site*/
const U32 __index, /*!< The index*/
const U32 diff
) const;
};
} // end namespace Svc
#endif
| 39.76204
| 100
| 0.558421
|
SSteve
|
8e3f6cf476c45f2b7a7bef65b062dc198e4b0edc
| 13,656
|
hpp
|
C++
|
server/http_context.hpp
|
photonmaster/scymnus
|
bcbf580091a730c63e15b67b6331705a281ba20b
|
[
"MIT"
] | 7
|
2021-08-19T01:11:21.000Z
|
2021-08-31T15:25:51.000Z
|
server/http_context.hpp
|
photonmaster/scymnus
|
bcbf580091a730c63e15b67b6331705a281ba20b
|
[
"MIT"
] | null | null | null |
server/http_context.hpp
|
photonmaster/scymnus
|
bcbf580091a730c63e15b67b6331705a281ba20b
|
[
"MIT"
] | null | null | null |
#pragma once
#include <filesystem>
#include <fstream>
#include <charconv>
#include "core/named_tuple.hpp"
#include "core/traits.hpp"
#include "date_manager.hpp"
#include "external/json.hpp"
#include "http/http_common.hpp"
#include "http/query_parser.hpp"
#include "http_request.hpp"
#include "http_response.hpp"
#include "mime/mime.hpp"
#include "server/memory_resource_manager.hpp"
//#include "url/url.hpp"
#include "external/decimal_from.hpp"
namespace scymnus {
template <int Status> using status_t = std::integral_constant<int, Status>;
template <int Status> constexpr status_t<Status> status;
template <http_content_type ContentType>
using content_t = std::integral_constant<http_content_type, ContentType>;
template <http_content_type ContentType>
constexpr content_t<ContentType> content_type;
struct no_content {};
template <int Status, class T,
http_content_type ContentType = http_content_type::NONE>
struct meta_info {
static constexpr int status = Status;
static constexpr http_content_type content_type = ContentType;
};
struct context {
using allocator_type = std::pmr::polymorphic_allocator<char>;
std::pmr::string *output_buffer_;
explicit context(std::pmr::string *output_buffer,
allocator_type allocator = {})
: output_buffer_{output_buffer}, raw_url_{allocator}, req_{allocator},
res_{allocator} {}
const std::pmr::string &raw_url() const { return raw_url_; }
http_method method() const { return method_; }
// request related methods
const http_request &request() const { return req_; }
const std::pmr::string &request_body() const { return req_.body_; }
void add_request_header(const std::pmr::string &field,
const std::pmr::string &value) {
req_.headers_.emplace(field, value);
}
void add_request_header(std::pmr::string &&field, std::pmr::string &&value) {
req_.headers_.emplace(std::move(field), std::move(value));
}
// response related methods
const http_response &response() const { return res_; }
std::string_view response_body() const { return res_.body_; }
void add_response_header(const std::pmr::string &field,
const std::pmr::string &value) {
res_.headers_.emplace(field, value);
}
void add_response_header(std::pmr::string &&field, std::pmr::string &&value) {
res_.headers_.emplace(std::move(field), std::move(value));
}
template <http_content_type ContentType, int Status, int N, class... H>
auto write_as(status_t<Status> st, const char (&body)[N], H &&...headers) {
start_buffer_position_ = output_buffer_->size();
using json = nlohmann::json;
static_assert(ContentType != http_content_type::NONE,
"a content type, different from NONE, must be selected");
content_type = ContentType;
res_.status_code_ = st;
output_buffer_->append(status_codes.at(Status));
output_buffer_->append(to_string_view(ContentType));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:");
char buff[24];
if constexpr (ContentType == http_content_type::JSON) {
json v = body;
auto payload = v.dump();
auto size = payload.size();
output_buffer_->append(decimal_from(size, buff));
//output_buffer_->append(fmt::format_int(size).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - size, output_buffer_->end()};
} else {
output_buffer_->append(decimal_from(N-1, buff));
//output_buffer_->append(fmt::format_int(N - 1).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - N - 1, output_buffer_->end()};
}
return meta_info<Status, const char *, ContentType>{};
}
template <http_content_type ContentType, int Status, class T, class... H>
auto write_as(status_t<Status> st, T &&body, H &&...headers) {
static_assert(ContentType != http_content_type::NONE,
"a content type, different from NONE, must be selected");
start_buffer_position_ = output_buffer_->size();
using json = nlohmann::json;
content_type = ContentType;
if constexpr (is_string_like_v<T>) {
res_.status_code_ = st;
if constexpr (ContentType == http_content_type::JSON) {
if (json::accept(body)) {
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(),
output_buffer_->end()};
} else {
auto payload = json(std::forward<T>(body)).dump();
write_response_headers(payload.size());
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - payload.size(),
output_buffer_->end()};
}
return meta_info<sizeof(T)?Status:0, T, http_content_type::JSON>{};
} else { // plain text
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(),
output_buffer_->end()};
return meta_info<sizeof(T)?Status:0, T, http_content_type::PLAIN_TEXT>{};
}
}
else if constexpr (std::is_constructible_v<json, std::remove_cv_t<T>>) {
static_assert(sizeof(T) && ContentType == http_content_type::JSON,
"content type must be JSON");
auto payload = json(std::forward<T>(body)).dump();
res_.status_code_ = st;
write_response_headers(payload.size());
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - payload.size(),
output_buffer_->end()};
return meta_info<sizeof(T)?Status:0, T, ContentType>{};
}
else {
static_assert(!sizeof(T), "Type not supported");
}
};
template <int Status, int N, class... H>
auto write(status_t<Status> st, const char (&body)[N], H &&...headers) {
start_buffer_position_ = output_buffer_->size();
content_type = http_content_type::PLAIN_TEXT;
res_.status_code_ = st;
output_buffer_->append(status_codes.at(Status));
output_buffer_->append(to_string_view(http_content_type::PLAIN_TEXT));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:");
char buff[24];
output_buffer_->append(decimal_from(N-1, buff));
//output_buffer_->append(fmt::format_int(N - 1).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - N - 1, output_buffer_->end()};
return meta_info<Status, const char *, http_content_type::PLAIN_TEXT>{};
}
template <int Status, class T, class... H>
auto write(status_t<Status> st, T &&body, H &&...headers) {
using json = nlohmann::json;
start_buffer_position_ = output_buffer_->size();
if constexpr (std::is_same_v<std::remove_cv_t<T>, std::string>) {
content_type = http_content_type::PLAIN_TEXT;
res_.status_code_ = st;
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(), output_buffer_->end()};
return meta_info<Status, T, http_content_type::PLAIN_TEXT>{};
} else if constexpr (std::is_constructible_v<json, std::remove_cv_t<T>>) {
json v = std::forward<T>(body);
auto payload = v.dump();
content_type = http_content_type::JSON;
res_.status_code_ = st;
write_response_headers(payload.size());
output_buffer_->append(payload);
res_.body_ = {output_buffer_->end() - payload.size(),
output_buffer_->end()};
return meta_info<Status, T, http_content_type::JSON>{};
}
else {
static_assert(!sizeof(T), "Type is not supported");
}
};
// for No Content
template <int Status, class... H>
[[deprecated("HTTP status code should be 204 when there is no content")]] auto
write(status_t<Status> st, H &&...headers) requires(Status == 200) {
write_no_content<Status>();
return meta_info<Status, no_content, http_content_type::NONE>{};
}
template <int Status, class... H>
auto write(status_t<Status> st, H &&...headers) requires(Status != 200) {
write_no_content<Status>();
return meta_info<Status, no_content, http_content_type::NONE>{};
}
void write_file(const std::filesystem::path &p) {
namespace fs = std::filesystem;
if (!p.has_filename() || !fs::exists(p)) {
write(status<404>);
return;
}
std::ifstream stream(p.c_str(), std::ios::binary);
std::string body(std::istreambuf_iterator<char>{stream}, {});
auto ct = mime_map::content_type(p.extension().string());
if (ct) {
std::pmr::string value{memory_resource_manager::instance().pool()};
value.append(*ct);
add_response_header("Content-Type", std::move(value));
}
res_.status_code_ = 200;
write_response_headers(body.size());
output_buffer_->append(body);
res_.body_ = {output_buffer_->end() - body.size(), output_buffer_->end()};
}
void write_response_headers(std::size_t size) {
if (res_.status_code_.value() == 200)
output_buffer_->append("HTTP/1.1 200 OK\r\n");
else {
auto status = status_codes.at(res_.status_code_.value_or(500), 500);
output_buffer_->append(status);
}
if (content_type != http_content_type::NONE)
output_buffer_->append(to_string_view(content_type));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:");
char buff[24];
output_buffer_->append(decimal_from(size, buff));
//output_buffer_->append(fmt::format_int(size).c_str());
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
}
// in case of an exception clear is called to clean up
// the output_buffer
// erase might throw an out of range exception if start_buffer_position is
// beyond end of string
void clear() noexcept {
if (is_response_written()){
res_.reset();
output_buffer_->erase(start_buffer_position_, std::string::npos);
}
}
void reset() {
query_.reset();
raw_url_.clear();
req_.reset();
res_.reset();
start_buffer_position_ = std::numeric_limits<size_t>::max();
}
bool is_response_written() {
return start_buffer_position_ != std::numeric_limits<size_t>::max();
}
// write support
query_string get_query_string() {
if (query_)
return query_.value();
query_ = query_string();
auto query_start = raw_url_.find('?');
if (query_start != std::string::npos && query_start != raw_url_.size()) {
query_.value().parse(
{raw_url_.data() + query_start + 1, raw_url_.size()});
}
return query_.value();
}
http_content_type content_type{http_content_type::NONE};
private:
friend class connection;
template <int Status> void write_no_content() {
start_buffer_position_ = output_buffer_->size();
res_.status_code_ = Status;
output_buffer_->append(status_codes.at(Status));
for (auto &v : res_.headers_) {
output_buffer_->append(v.first);
output_buffer_->append(":");
output_buffer_->append(v.second);
output_buffer_->append("\r\n");
}
output_buffer_->append("Content-Length:0");
output_buffer_->append("\r\nServer:scymnus\r\n");
date_manager::instance().append_http_time(*output_buffer_);
}
http_request req_;
http_response res_;
std::optional<query_string> query_;
http_method method_;
std::pmr::string raw_url_;
std::size_t start_buffer_position_{std::numeric_limits<size_t>::max()};
};
} // namespace scymnus
| 36.126984
| 89
| 0.603691
|
photonmaster
|
8e3fc245d1db558c8a00cf72a0a4d0f26e5e772f
| 669
|
cc
|
C++
|
test/collections/btree_map.cc
|
Alexhuszagh/funxx
|
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2017-07-21T22:58:38.000Z
|
2017-07-21T22:58:38.000Z
|
test/collections/btree_map.cc
|
Alexhuszagh/funxx
|
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
test/collections/btree_map.cc
|
Alexhuszagh/funxx
|
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
// :copyright: (c) 2017 Alex Huszagh.
// :license: MIT, see LICENSE.md for more details.
/*
* \addtogroup Tests
* \brief B-tree map unittests.
*/
#include <pycpp/collections/btree_map.h>
#include <gtest/gtest.h>
PYCPP_USING_NAMESPACE
// TESTS
// -----
TEST(btree_map, constructor_null)
{
using map = btree_map<int, int>;
map m1, m2;
EXPECT_EQ(m1.size(), 0);
EXPECT_EQ(m2.size(), 0);
EXPECT_TRUE(m1.find(1) == m1.end());
EXPECT_TRUE(m2.find(1) == m2.end());
m1.insert(make_pair(1, 1));
EXPECT_EQ(m1.size(), 1);
EXPECT_EQ(m2.size(), 0);
EXPECT_TRUE(m1.find(1) != m1.end());
EXPECT_TRUE(m2.find(1) == m2.end());
}
| 20.272727
| 51
| 0.61136
|
Alexhuszagh
|
8e44e5ce8037c084d185b31b2dfa3424701da62a
| 2,905
|
cpp
|
C++
|
2020/04.cpp
|
mdelorme/advent_of_code
|
47142d501055fc0d36989db9b189be7e6756d779
|
[
"Unlicense"
] | null | null | null |
2020/04.cpp
|
mdelorme/advent_of_code
|
47142d501055fc0d36989db9b189be7e6756d779
|
[
"Unlicense"
] | null | null | null |
2020/04.cpp
|
mdelorme/advent_of_code
|
47142d501055fc0d36989db9b189be7e6756d779
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
std::vector<std::string> passports;
bool is_valid(std::string str) {
str = str.substr(1);
std::istringstream iff(str);
bool valid=true;
try {
for (std::string s; iff >> s;) {
size_t pos = s.find(":");
std::string key = s.substr(0, pos);
std::string value = s.substr(pos+1);
if (key == "byr") {
int byr = std::stoi(value);
if (byr < 1920 || byr > 2002)
valid = false;
}
else if (key == "iyr") {
int iyr = std::stoi(value);
if (iyr < 2010 || iyr > 2020)
valid = false;
}
else if (key == "eyr") {
int eyr = std::stoi(value);
if (eyr < 2020 || eyr > 2030)
valid = false;
}
else if (key == "hgt") {
int height = std::stoi(value.substr(0, value.size()-2));
std::string unit = value.substr(value.size()-2);
if (unit == "in") {
valid = (height >= 59 && height <= 76);
}
else if (unit == "cm") {
valid = (height >= 150 && height <= 193);
}
else
valid = false;
}
else if (key == "hcl") {
std::regex regexp("#[[:xdigit:]]{6}");
valid = std::regex_match(value, regexp);
}
else if (key == "ecl"){
std::array<std::string, 7> valid_eyes {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"};
valid = (std::find(valid_eyes.begin(), valid_eyes.end(), value) != valid_eyes.end());
}
else if (key == "pid") {
std::regex regexp("[[:digit:]]{9}");
valid = std::regex_match(value, regexp);
}
if (!valid)
return false;
}
}
catch(...) {
return false;
}
return valid;
}
void part1() {
uint nvalid=0;
std::string needed_keys[] {"byr", "iyr", "eyr", "hgt", "ecl", "hcl", "pid"};
for (auto p: passports) {
bool valid = true;
for (auto k: needed_keys) {
if (p.find(k) == std::string::npos) {
valid = false;
break;
}
}
if (valid)
nvalid++;
}
std::cout << "Part 1 : " << nvalid << std::endl;
}
void part2() {
uint nvalid=0;
std::string needed_keys[] {"byr", "iyr", "eyr", "hgt", "ecl", "hcl", "pid"};
for (auto p: passports) {
bool valid = true;
for (auto k: needed_keys) {
if (p.find(k) == std::string::npos) {
valid = false;
break;
}
}
if (valid && is_valid(p))
nvalid++;
}
std::cout << "Part 2 : " << nvalid << std::endl;
}
int main(int argc, char **argv) {
std::ifstream f_in;
f_in.open("04.in");
while (!f_in.eof()) {
std::string line;
std::getline(f_in, line);
std::string passport_line = "";
while (line != "") {
passport_line += " " + line;
std::getline(f_in, line);
}
passports.push_back(passport_line);
}
f_in.close();
part1();
part2();
return 0;
}
| 22.346154
| 96
| 0.483305
|
mdelorme
|
8e47d105a11187712c0cb262db1c1cccb0d83f5f
| 7,731
|
cpp
|
C++
|
modules/build_seqset/correct_reads_test.cpp
|
spiralgenetics/biograph
|
33c78278ce673e885f38435384f9578bfbf9cdb8
|
[
"BSD-2-Clause"
] | 16
|
2021-07-14T23:32:31.000Z
|
2022-03-24T16:25:15.000Z
|
modules/build_seqset/correct_reads_test.cpp
|
spiralgenetics/biograph
|
33c78278ce673e885f38435384f9578bfbf9cdb8
|
[
"BSD-2-Clause"
] | 9
|
2021-07-20T20:39:47.000Z
|
2021-09-16T20:57:59.000Z
|
modules/build_seqset/correct_reads_test.cpp
|
spiralgenetics/biograph
|
33c78278ce673e885f38435384f9578bfbf9cdb8
|
[
"BSD-2-Clause"
] | 9
|
2021-07-15T19:38:35.000Z
|
2022-01-31T19:24:56.000Z
|
#include "modules/build_seqset/correct_reads.h"
#include "modules/bio_base/dna_testutil.h"
#include "modules/build_seqset/part_repo.h"
#include "modules/io/config.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace {
using namespace testing;
using namespace build_seqset;
using namespace dna_testutil;
} // namespace
class correct_reads_test : public Test {
public:
void SetUp() override {
static size_t n = 0;
boost::filesystem::create_directories(CONF_S(temp_root));
m_ref_path_prefix = CONF_S(temp_root) + "/ref";
m_ref_path_prefix += std::to_string(n);
m_repo_path = CONF_S(temp_root) + "/repo";
m_repo_path += std::to_string(n);
m_entries.emplace(m_depth, m_ref_path_prefix, m_repo_path);
m_entries->open_write_pass("initial");
++n;
}
void set_initial_repo(dna_slice seq) { m_entries->add_initial_repo(seq); }
void add_kmers(dna_slice seq) {
CHECK_GE(seq.size(), m_kmer_size);
for (auto it = seq.begin(); (it + m_kmer_size - 1) != seq.end(); ++it) {
m_kmers.insert(canonicalize(make_kmer(it, m_kmer_size), m_kmer_size));
}
m_first_kmers.insert(make_kmer(seq.begin(), m_kmer_size));
m_first_kmers.insert(make_kmer(seq.rcbegin(), m_kmer_size));
m_kmer_bases += seq.size();
}
void start_correction() {
m_ks.emplace(m_kmer_bases, m_kmer_size, get_maximum_mem_bytes(),
[&](const kmer_set::kmer_output_f& out_f, progress_handler_t) {
for (kmer_t k : m_kmers) {
unsigned flags = 0;
if (m_first_kmers.count(k)) {
flags |= kmer_set::k_fwd_starts_read;
}
if (m_first_kmers.count(rev_comp(k, m_kmer_size))) {
flags |= kmer_set::k_rev_starts_read;
}
out_f(k, flags);
}
});
m_entries->flush();
m_entries->open_write_pass("initial");
m_cr.emplace(*m_entries, *m_ks, m_params);
m_cr->add_initial_repo();
}
void add_read(dna_slice seq) {
unaligned_read r;
r.sequence = seq.as_string();
corrected_read c;
m_cr->correct(r, c);
}
void load_repo() {
m_cr.reset();
m_entries->flush();
}
std::set<dna_sequence> stored_sequences() {
CHECK(m_entries);
std::set<dna_sequence> seqs;
std::mutex mu;
m_entries->for_each_partition("initial",
[&](const part_repo::partition_ref& part) {
std::lock_guard<std::mutex> l(mu);
for (const auto& e : *part.main) {
seqs.insert(e.sequence());
}
});
return seqs;
}
Matcher<const std::set<dna_sequence>&> ContainsAllOf(const std::set<dna_sequence>& seqs) {
CHECK_GT(seqs.size(), 0);
Matcher<const std::set<dna_sequence>&> result = _;
for (const auto& seq : seqs) {
result = AllOf(result, Contains(seq));
}
return result;
}
protected:
std::string m_ref_path_prefix;
std::string m_repo_path;
size_t m_kmer_bases = 0;
std::set<kmer_t> m_kmers;
std::set<kmer_t> m_first_kmers;
boost::optional<kmer_set> m_ks;
boost::optional<part_repo> m_entries;
boost::optional<correct_reads> m_cr;
read_correction_params m_params;
unsigned m_depth = 1;
unsigned m_kmer_size = 2 * k_dna_test_sequence_length;
};
TEST_F(correct_reads_test, simple_fwd) {
add_kmers(tseq("bcde"));
add_kmers(dna_sequence("GA") + tseq("bcde") + dna_sequence("A"));
start_correction();
add_read(dna_sequence("GA") + tseq("bcde") + dna_sequence("A"));
load_repo();
std::set<dna_sequence> expected = {
dna_sequence("GA") + tseq("bcde") + dna_sequence("A"),
dna_sequence("A") + tseq("bcde") + dna_sequence("A"),
(dna_sequence("GA") + tseq("bcde") + dna_sequence("A")).rev_comp()};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4,
((dna_sequence("GA") + tseq("bcde") + dna_sequence("A")).size() + 3) / 4);
}
TEST_F(correct_reads_test, simple_rc) {
add_kmers(tseq("bcde"));
add_kmers(dna_sequence("A") + tseq("bcde") + dna_sequence("GA"));
start_correction();
add_read(dna_sequence("A") + tseq("bcde") + dna_sequence("GA"));
load_repo();
std::set<dna_sequence> expected = {
(dna_sequence("A") + tseq("bcde") + dna_sequence("GA")).rev_comp(),
(dna_sequence("A") + tseq("bcde") + dna_sequence("G")).rev_comp(),
(dna_sequence("A") + tseq("bcde") + dna_sequence("GA"))};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4,
((dna_sequence("A") + tseq("bcde") + dna_sequence("GA")).size() + 3) / 4);
}
TEST_F(correct_reads_test, fwd_in_repo) {
set_initial_repo(tseq("abcdefghij"));
add_kmers(tseq("abcd"));
add_kmers(tseq("ghij"));
start_correction();
add_read(tseq("abcd"));
add_read(tseq("ghij"));
load_repo();
std::set<dna_sequence> expected = {dna_sequence(tseq("abcd")), dna_sequence(tseq_rc("abcd")),
dna_sequence(tseq("ghij")), dna_sequence(tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainsAllOf(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4, (tseq("abcdefghij").size() + 3) / 4);
}
TEST_F(correct_reads_test, rc_in_repo) {
set_initial_repo(tseq_rc("abcdefghij"));
add_kmers(tseq("abcd"));
add_kmers(tseq("ghij"));
start_correction();
add_read(tseq("abcd"));
add_read(tseq("ghij"));
load_repo();
std::set<dna_sequence> expected = {
dna_sequence(tseq("abcd")), dna_sequence(tseq_rc("abcd")),
dna_sequence(tseq("ghij")), dna_sequence(tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainsAllOf(expected));
EXPECT_EQ(m_entries->repo_slice().size() / 4,
(tseq_rc("abcdefghij").size() + 3) / 4);
}
TEST_F(correct_reads_test, fwd_almost_in_repo) {
set_initial_repo(tseq("abcdefghij"));
add_kmers(dna_G + tseq("abcd"));
add_kmers((dna_G + tseq("abcd")).subseq(1, tseq("abcd").size() - 1));
add_kmers(tseq("ghij") + dna_G);
add_kmers((tseq("ghij") + dna_G).subseq(1, tseq("ghij").size() - 1));
start_correction();
add_read(dna_G + tseq("abcd"));
add_read(tseq("ghij") + dna_G);
load_repo();
std::set<dna_sequence> expected = {dna_sequence(dna_G + tseq("abcd")),
dna_sequence(tseq_rc("abcd") + dna_C),
dna_sequence(tseq("ghij") + dna_G),
dna_sequence(dna_C + tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_GT(m_entries->repo_slice().size() / 4,
(tseq("abcdefghij").size() + 3) / 4);
}
TEST_F(correct_reads_test, rev_almost_in_repo) {
set_initial_repo(tseq_rc("abcdefghij"));
add_kmers(dna_G + tseq("abcd"));
add_kmers((dna_G + tseq("abcd")).subseq(1, tseq("abcd").size() - 1));
add_kmers(tseq("ghij") + dna_G);
add_kmers((tseq("ghij") + dna_G).subseq(1, tseq("ghij").size() - 1));
start_correction();
add_read(dna_G + tseq("abcd"));
add_read(tseq("ghij") + dna_G);
load_repo();
std::set<dna_sequence> expected = {dna_sequence(dna_G + tseq("abcd")),
dna_sequence(tseq_rc("abcd") + dna_C),
dna_sequence(tseq("ghij") + dna_G),
dna_sequence(dna_C + tseq_rc("ghij"))};
EXPECT_THAT(stored_sequences(), ContainerEq(expected));
EXPECT_GT(m_entries->repo_slice().size() / 4,
(tseq("abcdefghij").size() + 3) / 4);
}
| 34.513393
| 96
| 0.608071
|
spiralgenetics
|
8e4db243cb4788f9aafac665ea049faaf53059e3
| 1,105
|
cpp
|
C++
|
Actividad2_recibe/ventanaarchivoexistente.cpp
|
adricatena/I2-puertoSerie
|
cb9efbde2bf30e517649e80a9ebb585449194287
|
[
"MIT"
] | null | null | null |
Actividad2_recibe/ventanaarchivoexistente.cpp
|
adricatena/I2-puertoSerie
|
cb9efbde2bf30e517649e80a9ebb585449194287
|
[
"MIT"
] | null | null | null |
Actividad2_recibe/ventanaarchivoexistente.cpp
|
adricatena/I2-puertoSerie
|
cb9efbde2bf30e517649e80a9ebb585449194287
|
[
"MIT"
] | null | null | null |
#include "ventanaarchivoexistente.h"
#include "ui_ventanaarchivoexistente.h"
VentanaArchivoExistente::VentanaArchivoExistente(QWidget *parent) :
QDialog(parent),
ui(new Ui::VentanaArchivoExistente)
{
ui->setupUi(this);
configuracion = new QSettings("Informatica II", "Actividad 2", this);
}
VentanaArchivoExistente::~VentanaArchivoExistente()
{
delete configuracion;
delete ui;
}
void VentanaArchivoExistente::on_btnAceptar_clicked()
{
if(ui->checkBoxSi->isChecked() && ui->checkBoxNo->isChecked())
{
msj.setText("Error! Ambas opciones estan seleccionadas.");
msj.exec();
}
else
{
if(ui->checkBoxNo->isChecked())
{
QString nombreViejo = configuracion->value("Nombre", "").toString();
QString nombreNuevo = nombreViejo.left(nombreViejo.lastIndexOf('/')) + ui->leNombreArchivo->text();
configuracion->setValue("Nombre", nombreNuevo);
}
QDialog::accept();
}
}
void VentanaArchivoExistente::on_btnCancelar_clicked()
{
close();
}
| 26.95122
| 112
| 0.640724
|
adricatena
|
8e4f9a1fc9b1d1a49e96f9ef39fff5f0ef06b3c1
| 1,791
|
cpp
|
C++
|
dev/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | 1,738
|
2017-09-21T10:59:12.000Z
|
2022-03-31T21:05:46.000Z
|
dev/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | 427
|
2017-09-29T22:54:36.000Z
|
2022-02-15T19:26:50.000Z
|
dev/Gems/EMotionFX/Code/Tests/UI/LY-93621.cpp
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | 671
|
2017-09-21T08:04:01.000Z
|
2022-03-29T14:30:07.000Z
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <Tests/UI/CommandRunnerFixture.h>
namespace EMotionFX
{
INSTANTIATE_TEST_CASE_P(LY93621, CommandRunnerFixture,
::testing::Values(std::vector<std::string> {
R"str(CreateAnimGraph)str",
R"str(AnimGraphAddGroupParameter -animGraphID 0 -name Group0)str",
R"str(AnimGraphAdjustParameter -animGraphID 0 -name Group0 -newName Group01 -type {6B42666E-82D7-431E-807E-DA789C53AF05} -contents <ObjectStream version="3">
<Class name="GroupParameter" version="1" type="{6B42666E-82D7-431E-807E-DA789C53AF05}">
<Class name="Parameter" field="BaseClass1" version="1" type="{4AF0BAFC-98F8-4EA3-8946-4AD87D7F2A6C}">
<Class name="AZStd::string" field="name" value="Group01" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
<Class name="AZStd::string" field="description" value="" type="{03AAAB3F-5C47-5A66-9EBC-D5FA4DB353C9}"/>
</Class>
<Class name="AZStd::vector" field="childParameters" type="{496E6454-2F91-5CDC-9771-3B589F3F8FEB}"/>
</Class>
</ObjectStream>)str",
}
));
} // end namespace EMotionFX
| 54.272727
| 169
| 0.646008
|
jeikabu
|
8e53f4f2c6c82933b403124f1fac80b47f2c14b7
| 5,556
|
hpp
|
C++
|
include/multi_trie_index.hpp
|
kampersanda/frechet_simsearch
|
c91e0b12f0acf5f8a563ec16d71bf76bc0dc169c
|
[
"MIT"
] | 7
|
2019-10-07T08:48:44.000Z
|
2022-03-23T02:39:45.000Z
|
include/multi_trie_index.hpp
|
kampersanda/frechet_simsearch
|
c91e0b12f0acf5f8a563ec16d71bf76bc0dc169c
|
[
"MIT"
] | null | null | null |
include/multi_trie_index.hpp
|
kampersanda/frechet_simsearch
|
c91e0b12f0acf5f8a563ec16d71bf76bc0dc169c
|
[
"MIT"
] | 1
|
2019-12-23T16:33:01.000Z
|
2019-12-23T16:33:01.000Z
|
#pragma once
#include "trit_array_trie.hpp"
#include "vcode_array.hpp"
namespace frechet_simsearch {
template <class Point, uint32_t Length>
class MultiTrieIndex {
public:
using point_type = Point;
using vcode_trait_type = VCodeTraits<Length>;
using vint_type = typename vcode_trait_type::vint_type;
using hasher_type = FrechetHasher<Point, Length>;
using database_type = VCodeArray<Point, Length>;
using trie_type = TritArrayTrie;
public:
MultiTrieIndex() = default;
MultiTrieIndex(const std::vector<Curve<Point>>& curves, const Configure& cfg)
: m_indexes(cfg.buckets), m_bucket_begs(cfg.buckets + 1) {
const size_t n_curves = curves.size();
std::vector<uint8_t> codes_buf(n_curves * Length);
std::vector<const uint8_t*> codes(n_curves);
{
size_t i = 0;
m_database = std::make_unique<database_type>(curves, cfg, [&](const uint8_t* code) {
const size_t beg = i * Length;
std::copy(code, code + Length, &codes_buf[beg]);
codes[i++] = &codes_buf[beg];
});
}
uint32_t bkt_beg = 0;
for (uint32_t b = 0; b < cfg.buckets; ++b) {
m_bucket_begs[b] = bkt_beg;
bkt_beg += (b + Length) / cfg.buckets;
}
m_bucket_begs[cfg.buckets] = bkt_beg;
tfm::printfln("[MultiTrieIndex construction]");
for (uint32_t b = 0; b < cfg.buckets; ++b) {
uint32_t sub_length = m_bucket_begs[b + 1] - m_bucket_begs[b];
tfm::printfln("# bucket %d (L=%d)", b, sub_length);
m_indexes[b] = std::make_unique<trie_type>(codes, sub_length, cfg.reduction_threshold);
for (size_t i = 0; i < n_curves; ++i) {
codes[i] += sub_length;
}
tfm::printfln("# - %d nodes; %f values per leaf", //
m_indexes[b]->get_num_nodes(), m_indexes[b]->get_num_values_per_leaf());
}
m_candidates.reserve(1U << 16); // for range_search
}
~MultiTrieIndex() = default;
size_t range_search(const Curve<Point>& query_curve, uint32_t hamming_range, std::function<void(size_t)> fn) {
m_candidates.clear();
size_t num_candidates = 0;
const uint8_t* qcode = m_database->get_hasher().hash_code8(query_curve.points);
const vint_type* qvcode = vcode_trait_type::to_vints(qcode, DOMAIN_BITS);
const int32_t buckets = static_cast<int32_t>(m_indexes.size());
const int32_t gph_range = int32_t(hamming_range) - buckets + 1;
for (int32_t b = 0; b < buckets; ++b) {
if (gph_range + b < 0) {
continue;
}
const int32_t sub_range = (gph_range + b) / buckets;
const uint8_t* sub_qcode = qcode + m_bucket_begs[b];
m_indexes[b]->range_search(sub_qcode, sub_range, [&](uint32_t id) { m_candidates.push_back(id); });
}
std::sort(m_candidates.begin(), m_candidates.end());
uint32_t prev_id = uint32_t(-1);
for (size_t i = 0; i < m_candidates.size(); ++i) {
const uint32_t cand_id = m_candidates[i];
if (prev_id == cand_id) {
continue;
}
uint32_t hamming_dist =
vcode_trait_type::get_hamming_distance(qvcode, m_database->get(cand_id), DOMAIN_BITS);
if (hamming_dist <= hamming_range) {
fn(cand_id);
}
prev_id = cand_id;
++num_candidates;
}
return num_candidates;
}
// in bytes
size_t get_memory_usage() const {
return get_index_memory_usage() + get_database_memory_usage();
}
size_t get_index_memory_usage() const {
size_t memory = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
memory += m_indexes[b]->get_memory_usage();
}
memory += m_bucket_begs.size() * sizeof(uint32_t);
return memory;
}
size_t get_database_memory_usage() const {
return m_database->get_memory_usage();
}
size_t get_ITLB() const {
return get_index_ITLB() + get_database_memory_usage();
}
size_t get_index_ITLB() const {
size_t memory = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
memory += m_indexes[b]->get_ITLB();
}
memory += m_bucket_begs.size() * sizeof(uint32_t);
return memory;
}
size_t size() const {
return m_database->size();
}
const VCodeArray<Point, Length>& get_database() const {
return *m_database.get();
}
size_t get_num_nodes() const {
size_t num = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
num += m_indexes[b]->get_num_nodes();
}
return num;
}
size_t get_num_inner_nodes() const {
size_t num = 0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
num += m_indexes[b]->get_num_inner_nodes();
}
return num;
}
float get_num_values_per_leaf() const {
float sum = 0.0;
for (size_t b = 0; b < m_indexes.size(); ++b) {
sum += m_indexes[b]->get_num_values_per_leaf();
}
return sum / m_indexes.size();
}
private:
std::unique_ptr<database_type> m_database;
std::vector<std::unique_ptr<trie_type>> m_indexes;
std::vector<uint32_t> m_bucket_begs;
// for seach
std::vector<uint32_t> m_candidates;
};
} // namespace frechet_simsearch
| 33.46988
| 114
| 0.578294
|
kampersanda
|
8e56d9e614f40f44f8657bdba23674583775c8bd
| 2,620
|
cpp
|
C++
|
src/frame_transformation.cpp
|
sakshikakde/human-detector-and-tracker
|
04e1fd08b858ababfa4fa91da8306890ef1d7d00
|
[
"MIT"
] | null | null | null |
src/frame_transformation.cpp
|
sakshikakde/human-detector-and-tracker
|
04e1fd08b858ababfa4fa91da8306890ef1d7d00
|
[
"MIT"
] | 3
|
2021-10-16T05:46:37.000Z
|
2021-10-18T22:16:20.000Z
|
src/frame_transformation.cpp
|
sakshikakde/human-detector-and-tracker
|
04e1fd08b858ababfa4fa91da8306890ef1d7d00
|
[
"MIT"
] | 2
|
2021-10-06T02:52:31.000Z
|
2021-10-06T05:16:28.000Z
|
/**
* MIT License
*
* Copyright (c) 2021 Anubhav Paras, Sakshi Kakde, Siddharth Telang
*
* 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.
*
* @file frame_transformation.cpp
* @author Anubhav Paras (anubhav@umd.edu)
* @author Sakshi Kakde (sakshi@umd.edu)
* @author Siddharth Telang (stelang@umd.edu)
* @brief Performs frame transformation
* @version 0.1
* @date 2021-10-25
*
* @copyright Copyright (c) 2021
*
*/
#include <frame_transformation.hpp>
FrameTransformation::FrameTransformation() {
// camera intrinsic matrix
this->K = Eigen::MatrixXf(3, 3);
this->K << 964.828979, 0, 643.788025, 0, 964.828979, 484.407990, 0, 0, 1;
this->T_c = Eigen::MatrixXf(3, 4);
this->T_c << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0;
this->T_r = Eigen::MatrixXf(4, 4);;
this->T_r<< 0, 0, 1, 10, -1, 0, 0, 10, 0, -1, 0, 10, 0, 0, 0, 1;
// Projection matrix
this->P = this->K * this->T_c * this->T_r;
}
FrameTransformation::~FrameTransformation() {}
Coord3D FrameTransformation::getRobotFrame(Coord2D imageCoordinates) {
// logic goes here
// Calculate P inverse
Eigen::MatrixXf P_T = this->P.transpose();
Eigen::MatrixXf P_inv = P_T * (this->P * P_T).inverse();
// Image coordinates to homogenous coordinates
Eigen::MatrixXf x(3, 1);
x << imageCoordinates.x, imageCoordinates.y, 1;
Eigen::MatrixXf X = P_inv * x;
// populate Coord3D
Coord3D X_robot;
if (X(3, 0) != 0) {
X_robot.x = X(0, 0) / X(3, 0);
X_robot.y = X(1, 0) / X(3, 0);
X_robot.z = X(2, 0) / X(3, 0);
} else {
return Coord3D(0, 0, 0);
}
return X_robot;
}
| 35.890411
| 81
| 0.681679
|
sakshikakde
|
8e5ae16a99a4d082dbe5b8f34c5a4c69add57ac0
| 2,282
|
cc
|
C++
|
conf_crawler/url_dedup/dedup_config.cc
|
WinterW/crawler_cpp
|
e0c8dba77233005b1ab13731d1cbcce274b70778
|
[
"Apache-2.0"
] | null | null | null |
conf_crawler/url_dedup/dedup_config.cc
|
WinterW/crawler_cpp
|
e0c8dba77233005b1ab13731d1cbcce274b70778
|
[
"Apache-2.0"
] | null | null | null |
conf_crawler/url_dedup/dedup_config.cc
|
WinterW/crawler_cpp
|
e0c8dba77233005b1ab13731d1cbcce274b70778
|
[
"Apache-2.0"
] | 2
|
2020-09-12T13:50:38.000Z
|
2020-09-16T15:55:14.000Z
|
/**
* @Copyright 2011 GanJi Inc.
* @file ganji/crawler/conf_crawler/url_dedup/dedup_config.cc
* @namespace ganji::crawler::conf_crawler::dedup
* @version 1.0
* @author lisizhong
* @date 2011-08-01
*
* 改动程序后, 请使用tools/cpplint/cpplint.py 检查代码是否符合编码规范!
* 遵循的编码规范请参考: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
* Change Log:
*/
#include "conf_crawler/url_dedup/dedup_config.h"
#include <stdlib.h>
#include "util/config/config.h"
using std::string;
namespace ganji { namespace crawler { namespace conf_crawler { namespace dedup {
using ganji::util::config::Config;
int DedupConfig::CheckVal(int val, const string &name) {
if (val <= 0) {
fprintf(stderr, "%s:%d <= 0\n", name.c_str(), val);
exit(1);
}
return 0;
}
int DedupConfig::LoadConfig(const string &conf_file) {
Config conf;
conf.loadConfFile(conf_file);
conf.getItemValue(kDedupHost, dedup_host_);
conf.getItemValue(kDedupPort, dedup_port_);
conf.getItemValue(kNbThreadCount, nb_thread_count_);
conf.getItemValue(kBloomFilterMaxElem, bf_max_elem_);
string bf_fpf;
conf.getItemValue(kBloomFilterFPF, bf_fpf);
bf_fpf_ = atof(bf_fpf.c_str());
conf.getItemValue(kBucketCount, bucket_count_);
conf.getItemValue(kDayCount, day_count_);
conf.getItemValue(kMd5Path, md5_path_);
CheckVal(dedup_port_, "dedup_port_");
CheckVal(nb_thread_count_, "nb_thread_count_");
CheckVal(bf_max_elem_, "bf_max_elem_");
CheckVal(bucket_count_, "bucket_count_");
CheckVal(day_count_, "day_count_");
return 0;
}
void DedupConfig::PrintConfig() const {
fprintf(stdout, "--------------------------DedupConfig config--------------------------\n");
fprintf(stdout, "dedup host:%s\n", dedup_host_.c_str());
fprintf(stdout, "dedup port:%d\n", dedup_port_);
fprintf(stdout, "nb thread count:%d\n", nb_thread_count_);
fprintf(stdout, "bloom filter max elem:%d\n", bf_max_elem_);
fprintf(stdout, "bloom filter fpf:%f\n", bf_fpf_);
fprintf(stdout, "bucket count:%d\n", bucket_count_);
fprintf(stdout, "day count:%d\n", day_count_);
fprintf(stdout, "md5 path:%s\n", md5_path_.c_str());
fprintf(stdout, "--------------------------DedupConfig config--------------------------\n");
}
}}}}; ///< end of namespace ganji::crawler::conf_crawler::dedup
| 31.694444
| 94
| 0.689308
|
WinterW
|
8e5b90c24846d9cb3ce2bc6863a6f6474e160be2
| 3,230
|
cpp
|
C++
|
GTraining/SortedArrayIterator.cpp
|
tzaffi/cpp
|
43d99e70d8fa712f90ea0f6147774e4e0f2b11da
|
[
"MIT"
] | null | null | null |
GTraining/SortedArrayIterator.cpp
|
tzaffi/cpp
|
43d99e70d8fa712f90ea0f6147774e4e0f2b11da
|
[
"MIT"
] | null | null | null |
GTraining/SortedArrayIterator.cpp
|
tzaffi/cpp
|
43d99e70d8fa712f90ea0f6147774e4e0f2b11da
|
[
"MIT"
] | null | null | null |
//
// Created by zeph on 12/4/16.
//
#include <vector>
/**
* Given two sorted Vectors, use the merge sort iteration method to iterate through the arrays
* and reduce from the union by applying the choice() function. For example, if:
* o choice = insertLeft() - always pick the left param (useful for union)
* o choice = insertLeftIfEqual() - pick the left param if both are equal (useful for intersection)
* o choice = insertLeftUnique() - always pick the left param if it is different from the previous insertion
* @tparam T - a comparable type
* @param a - an array of T's sorted in ascending order
* @param b - an array of T's sorted in ascending order
* @param insertChoice - a function that given T-values left and right and an aggregator vector to insert the
* choice into, provides logic for picking a choice and then inserts that choice into the aggreagator.
* Returns true iff a choice was inserted (false in the case when nothing was inserted)
* @param finishEarly - optional parameter defaulting to false. Set true if you want to finish early such
* as in the case of intersection.
* @return the aggregator vector from the reduction operator that was applied to a and b
*/
template <typename T>
inline std::vector<T> iterateAndReduce(const std::vector<T>& a,
const std::vector<T>& b,
bool insertChoice(const T& left, const T& right, std::vector<T>& aggregator),
bool finishEarly = false){
std::vector<T> aggregator;
auto i = a.cbegin(), j = b.cbegin();
while(i != a.cend() && j != b.cend()){
while(i != a.cend() && j != b.cend() && *i == *j){
insertChoice(*i, *j, aggregator);
++i, ++j;
}
while(i != a.cend() && j != b.cend() && *i < *j){
insertChoice(*i, *j, aggregator);
++i;
}
while(i != a.cend() && j != b.cend() && *j < *i){
insertChoice(*j, *i, aggregator);
++j;
}
}
if(!finishEarly){
while(i != a.cend()){
insertChoice(*i, *a.cbegin(), aggregator);
++i;
}
while(j != b.cend()){
insertChoice(*j, *b.cbegin(), aggregator);
++j;
}
}
return aggregator;
}
namespace Choosers{
template <typename T>
bool insertLeftIfEqual(const T& left, const T& right, std::vector<T>& aggregator){
if(left == right){
aggregator.push_back(left);
return true;
}
return false;
}
template <typename T>
bool insertLeftOrBothIfEqual (const T &left , const T &right , std::vector<T> &aggregator){
aggregator.push_back(left);
if(left == right){ aggregator.push_back(right); }
return true;
}
template <typename T>
bool insertLeftIfNewElement (const T &left , const T &right , std::vector<T> &aggregator){
auto lastInsertItr = aggregator.cend();
bool alreadyInserted = ( (lastInsertItr != aggregator.cbegin()) && (*(lastInsertItr-1) == left));
if(alreadyInserted){ return false; }
aggregator.push_back(left);
return true;
}
}
| 39.390244
| 116
| 0.588854
|
tzaffi
|
8e5c5cf73edd2031dd4c597f8ce890c017208f5d
| 3,459
|
hh
|
C++
|
include/tchecker/system/intvar.hh
|
arnabSur/tchecker
|
24ba7703068a41c6e9c613b4ef80ad6c788e65bc
|
[
"MIT"
] | 7
|
2019-08-12T12:22:07.000Z
|
2021-11-18T01:48:27.000Z
|
include/tchecker/system/intvar.hh
|
arnabSur/tchecker
|
24ba7703068a41c6e9c613b4ef80ad6c788e65bc
|
[
"MIT"
] | 40
|
2019-07-03T04:31:19.000Z
|
2022-03-31T03:40:43.000Z
|
include/tchecker/system/intvar.hh
|
arnabSur/tchecker
|
24ba7703068a41c6e9c613b4ef80ad6c788e65bc
|
[
"MIT"
] | 8
|
2019-07-04T06:40:49.000Z
|
2021-12-03T15:51:50.000Z
|
/*
* This file is a part of the TChecker project.
*
* See files AUTHORS and LICENSE for copyright details.
*
*/
#ifndef TCHECKER_SYSTEM_INTVAR_HH
#define TCHECKER_SYSTEM_INTVAR_HH
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
#include "tchecker/basictypes.hh"
#include "tchecker/system/attribute.hh"
#include "tchecker/variables/intvars.hh"
/*!
\file intvar.hh
\brief Bounded integer variables in systems
*/
namespace tchecker {
namespace system {
/*!
\class intvars_t
\brief Collection of bounded integer variables
*/
class intvars_t {
public:
/*!
\brief Add an integer variable
\param name : variable name
\param size : variable size (array of integer variables)
\param min : minimal value
\param max : maximal value
\param initial : initial calue
\param attr : attributes
\pre name is not a declared integer variable
\post variable name with minimal value min, maximal value max, initial value init and attributes attr has been added
\throw std::invalid_argument : if name is a declared integer variable
*/
void add_intvar(std::string const & name, tchecker::intvar_id_t size = 1,
tchecker::integer_t min = std::numeric_limits<tchecker::integer_t>::min(),
tchecker::integer_t max = std::numeric_limits<tchecker::integer_t>::max(),
tchecker::integer_t initial = std::numeric_limits<tchecker::integer_t>::min(),
tchecker::system::attributes_t const & attr = tchecker::system::attributes_t());
/*!
\brief Accessor
\param kind : kind of declared variable
\return number of declared bounded integer variables if kind = tchecker::VK_DECLARED,
number of flattened bounded integer variables if kind = tchecker::VK_FLATTENED
*/
inline tchecker::intvar_id_t intvars_count(enum tchecker::variable_kind_t kind) const
{
return _integer_variables.size(kind);
}
/*!
\brief Accessor
\param name : variable name
\return identifier of variable name
\throw std::invalid_argument : if name is not am integer variable
*/
inline tchecker::intvar_id_t intvar_id(std::string const & name) const { return _integer_variables.id(name); }
/*!
\brief Accessor
\param id : variable identifier
\return name of integer variable id
\throw std::invalid_argument : if id is not an integer variable
*/
inline std::string const & intvar_name(tchecker::intvar_id_t id) const { return _integer_variables.name(id); }
/*!
\brief Accessor
\param id : integer variable identifier
\return attributes of integer variable id
\throw std::invalid_argument : if id is not an integer variable
*/
tchecker::system::attributes_t const & intvar_attributes(tchecker::intvar_id_t id) const;
/*!
\brief Accessor
\param name : integer variable name
\return true if name is a declared integer variable, false otherwise
*/
bool is_intvar(std::string const & name) const;
/*!
\brief Accessor
\return integer variables
*/
inline tchecker::integer_variables_t const & integer_variables() const { return _integer_variables; }
private:
tchecker::integer_variables_t _integer_variables; /*!< Integer variables */
std::vector<tchecker::system::attributes_t> _integer_variables_attr; /*!< Integer variables attributes */
};
} // end of namespace system
} // end of namespace tchecker
#endif // TCHECKER_SYSTEM_INTVAR_HH
| 31.162162
| 119
| 0.713501
|
arnabSur
|
8e5eff5c63cdb00e353c2626a812851af7f7b89e
| 5,673
|
hpp
|
C++
|
modules/gate_ops/bit_group/bit_group.hpp
|
ICHEC/QNLP
|
2966c7f71e6979c7ddef62520c3749cf6473fabe
|
[
"Apache-2.0"
] | 29
|
2020-04-13T04:40:35.000Z
|
2021-12-17T11:21:35.000Z
|
modules/gate_ops/bit_group/bit_group.hpp
|
ICHEC/QNLP
|
2966c7f71e6979c7ddef62520c3749cf6473fabe
|
[
"Apache-2.0"
] | 6
|
2020-03-12T17:40:00.000Z
|
2021-01-20T12:15:08.000Z
|
modules/gate_ops/bit_group/bit_group.hpp
|
ICHEC/QNLP
|
2966c7f71e6979c7ddef62520c3749cf6473fabe
|
[
"Apache-2.0"
] | 9
|
2020-09-28T05:00:30.000Z
|
2022-03-04T02:11:49.000Z
|
/**
* @file bit_group.hpp
* @author Lee J. O'Riordan (lee.oriordan@ichec.ie)
* @brief Implements grouping of bits to LSB side of register
* @version 0.1
* @date 2019-04-02
* @detailed This header file introduces routines for bit-wise shifting of set bits to the side of a register (ie |01010> -> |00011>).
* Note: yes, we are cheating to reset the qubits by Hadamrding and measuring in Z-basis. Uncompute steps to follow.
*
* @copyright Copyright (c) 2020
*/
#ifndef QNLP_BIT_GROUP
#define QNLP_BIT_GROUP
#include<algorithm>
namespace QNLP{
/**
* @brief Class definition for bit-wise grouping in register.
*
* @tparam SimulatorType
*/
template <class SimulatorType>
class BitGroup{
private:
/**
* @brief Swap the qubits if `qreg_idx0` is set and `qreg_idx1` is not.
* Uses Auxiliary qubits `qaux_idx` which are set to |10> at start and end of operations.
*
* @param qSim Quantum simulator object derived from SimulatorGeneral
* @param qreg_idx0 Index of qubit 0 in qSim qubit register
* @param qreg_idx1 Index of qubit 1 in qSim qubit register
* @param qaux_idx Indices of auxiliary qubits in qSim qubit register that are set to |10>
*/
static void q_ops(SimulatorType& qSim, std::size_t qreg_idx0, std::size_t qreg_idx1, const std::vector<std::size_t>& qaux_idx){
//Swap if C0 is set and C1 is not
qSim.applyGateCCX(qreg_idx0, qaux_idx[0], qaux_idx[1]);
qSim.applyGateCCX(qreg_idx1, qreg_idx0, qaux_idx[1]);
qSim.applyGateCSwap(qaux_idx[1], qreg_idx0, qreg_idx1);
//Reset Aux gate to |0>
qSim.applyGateH(qaux_idx[1]);
qSim.collapseToBasisZ(qaux_idx[1], 0);
}
/*
//@brief WIP:Swaps all qubits in register indices given by qreg_idx to their right-most positions.
// Method works from opposing ends of register and subregisters iteratively until all qubits are in the correct positions.
//
//@param qSim Quantum simulator object derived from SimulatorGeneral
//@param qreg_idx Indices of the qSim register to group to the LSB position.
//@param qaux_idx Indices of auxiliary qubits in qSim register
static void bit_swap_s2e(SimulatorType& qSim, const std::vector<std::size_t>& qreg_idx, const std::vector<std::size_t>& qaux_idx){
assert(qaux_idx.size() >= 2);
std::size_t num_qubits = qreg_idx.size();
//Apply the op from opposite ends of register working towards centre, reduce size from left, then repeat until 2 qubits remain.
qSim.applyGateX(qaux_idx[0]);
for(int num_offset=0; num_offset < qreg_idx.size()/2 + 1 + qreg_idx.size()%2; num_offset++){
for(std::size_t i=0; i < num_qubits/2 + num_qubits%2; i++){
if (i + num_offset == num_qubits - (i+1) + num_offset)
continue;
q_ops(qSim, qreg_idx[i + num_offset], qreg_idx[num_qubits - (i+1) + num_offset], qaux_idx);
}
num_qubits--;
}
qSim.applyGateX(qaux_idx[0]);
}*/
/**
* @brief Swaps all qubits in register indices given by qreg_idx to their right-most positions.
* Method works by pairing qubits using even-odd indexed cycles iteratively until all qubits are in the correct positions.
*
*
* @param qSim Quantum simulator object derived from SimulatorGeneral
* @param qreg_idx Indices of the qSim register to group to the LSB position.
* @param qaux_idx Indices of auxiliary qubits in qSim register in |00> state
*/
static void bit_swap_pair(SimulatorType& qSim, const std::vector<std::size_t>& qreg_idx, const std::vector<std::size_t>& qaux_idx, bool lsb){
bool isOdd = qreg_idx.size() % 2;
qSim.applyGateX(qaux_idx[0]);
for(std::size_t num_steps = 0; num_steps < qreg_idx.size(); num_steps++){
for(int i = 0; i < qreg_idx.size()-1; i+=2){
if(i + 1 + isOdd < qreg_idx.size()){
if(lsb)
q_ops(qSim, qreg_idx[i + isOdd], qreg_idx[i + 1 + isOdd], qaux_idx);
else
q_ops(qSim, qreg_idx[i + 1 + isOdd], qreg_idx[i + isOdd], qaux_idx);
}
}
isOdd = !isOdd;
}
qSim.applyGateX(qaux_idx[0]);
}
public:
/**
* @brief Swaps all qubits in register indices given by qreg_idx to their right-most positions.
* Method works by pairing qubits using even-odd indexed cycles iteratively until all qubits are in the correct positions.
* Intermediate qubit reset operation may not be realisable on all platforms (Hadarmard followed by SigmaZ projection to |0>)
*
* @param qSim Quantum simulator object derived from SimulatorGeneral
* @param qreg_idx Indices of the qSim register to group to the LSB position.
* @param qaux_idx Indices of auxiliary qubits in qSim register in |00> state
* @param lsb Indicates if to shift the values to the MSB or LSB equivalent positions.
*/
static void bit_group(SimulatorType& qSim, const std::vector<std::size_t>& qreg_idx, const std::vector<std::size_t>& qaux_idx, bool lsb=true){
bit_swap_pair(qSim, qreg_idx, qaux_idx, lsb);
}
};
}
#endif
| 47.275
| 150
| 0.609907
|
ICHEC
|
8e60171a198c91c1f18eba310410edbff7d07090
| 4,895
|
cpp
|
C++
|
ngraph/frontend/onnx_import/src/utils/onnx_internal.cpp
|
kenkoyanagi/openvino
|
864b3ba62fb86e685c847ca84016043cdea870c5
|
[
"Apache-2.0"
] | 1
|
2021-04-22T07:28:03.000Z
|
2021-04-22T07:28:03.000Z
|
ngraph/frontend/onnx_import/src/utils/onnx_internal.cpp
|
kenkoyanagi/openvino
|
864b3ba62fb86e685c847ca84016043cdea870c5
|
[
"Apache-2.0"
] | 105
|
2020-06-04T00:23:29.000Z
|
2022-02-21T13:04:33.000Z
|
ngraph/frontend/onnx/onnx_import/src/utils/onnx_internal.cpp
|
mpapaj/openvino
|
37b46de1643a2ba6c3b6a076f81d0a47115ede7e
|
[
"Apache-2.0"
] | 3
|
2021-04-25T06:52:41.000Z
|
2021-05-07T02:01:44.000Z
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <onnx/onnx_pb.h>
#include "core/graph.hpp"
#include "core/model.hpp"
#include "core/null_node.hpp"
#include "core/transform.hpp"
#include "onnx_import/onnx_framework_node.hpp"
#include "onnx_import/utils/onnx_internal.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace detail
{
void remove_dangling_parameters(std::shared_ptr<Function>& function)
{
const auto parameters = function->get_parameters();
for (auto parameter : parameters)
{
const auto parameter_users = parameter->get_users();
// if a Parameter is connected to a ONNXFrameworkNode that was not converted
// during convert_function it means, this Parameter is dangling and we can
// remove it from function
const bool is_dangling_parameter = std::all_of(
parameter_users.begin(),
parameter_users.end(),
[](const std::shared_ptr<ngraph::Node>& node) -> bool {
return std::dynamic_pointer_cast<frontend::ONNXFrameworkNode>(node) !=
nullptr;
});
if (is_dangling_parameter)
{
function->remove_parameter(parameter);
}
}
}
void remove_dangling_results(std::shared_ptr<Function>& function)
{
const auto results = function->get_results();
for (auto result : results)
{
// we can remove Result from function if after function conversion,
// Result is connected to NullNode only
const auto result_inputs = result->input_values();
const bool is_dangling_result =
std::all_of(result_inputs.begin(),
result_inputs.end(),
[](const Output<ngraph::Node>& node) -> bool {
return ngraph::op::is_null(node);
});
if (is_dangling_result)
{
function->remove_result(result);
}
}
}
void convert_decoded_function(std::shared_ptr<Function> function)
{
for (const auto& node : function->get_ordered_ops())
{
if (auto raw_node =
std::dynamic_pointer_cast<frontend::ONNXFrameworkNode>(node))
{
if (auto subgraph_node =
std::dynamic_pointer_cast<frontend::ONNXSubgraphFrameworkNode>(
node))
{
subgraph_node->infer_inputs_from_parent();
convert_decoded_function(subgraph_node->get_subgraph_body());
}
const auto& onnx_node = raw_node->get_onnx_node();
OutputVector ng_nodes{onnx_node.get_ng_nodes()};
if (ng_nodes.size() > raw_node->get_output_size())
{
ng_nodes.resize(raw_node->get_output_size());
}
replace_node(raw_node, ng_nodes);
}
else
{
// Have to revalidate node because new intpus can affect shape/type
// propagation for already translated nodes
node->revalidate_and_infer_types();
}
}
remove_dangling_parameters(function);
remove_dangling_results(function);
}
std::shared_ptr<Function> import_onnx_model(ONNX_NAMESPACE::ModelProto& model_proto,
const std::string& model_path)
{
transform::expand_onnx_functions(model_proto);
transform::fixup_legacy_operators(model_proto);
transform::update_external_data_paths(model_proto, model_path);
auto p_model_proto = common::make_unique<ONNX_NAMESPACE::ModelProto>(model_proto);
auto model = common::make_unique<Model>(std::move(p_model_proto));
Graph graph{std::move(model)};
return graph.convert();
}
} // namespace detail
} // namespace onnx_import
} // namespace ngraph
| 43.705357
| 98
| 0.489275
|
kenkoyanagi
|
769fc25c2db959e7739f02dfbd9b42abdccf62af
| 1,315
|
hh
|
C++
|
src/motor/introspect/api/motor/introspect/node/reference.hh
|
motor-dev/Motor
|
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
|
[
"BSD-3-Clause"
] | null | null | null |
src/motor/introspect/api/motor/introspect/node/reference.hh
|
motor-dev/Motor
|
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
|
[
"BSD-3-Clause"
] | null | null | null |
src/motor/introspect/api/motor/introspect/node/reference.hh
|
motor-dev/Motor
|
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
|
[
"BSD-3-Clause"
] | null | null | null |
/* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#ifndef MOTOR_INTROSPECT_NODE_REFERENCE_HH_
#define MOTOR_INTROSPECT_NODE_REFERENCE_HH_
/**************************************************************************************************/
#include <motor/introspect/stdafx.h>
#include <motor/introspect/node/node.hh>
namespace Motor { namespace Meta { namespace AST {
class Namespace;
class motor_api(INTROSPECT) Reference : public Node
{
friend class Object;
private:
const inamespace m_referenceName;
ref< const Node > m_node;
Meta::Value m_value;
protected:
virtual minitl::tuple< raw< const Meta::Method >, bool > getCall(DbContext & context)
const override;
virtual ConversionCost distance(const Type& type) const override;
virtual bool doResolve(DbContext & context) override;
virtual void doEval(const Type& expectedType, Value& result) const override;
virtual void doVisit(Node::Visitor & visitor) const override;
public:
Reference(const inamespace& name);
~Reference();
const inamespace& name() const
{
return m_referenceName;
}
};
}}} // namespace Motor::Meta::AST
/**************************************************************************************************/
#endif
| 29.222222
| 100
| 0.591635
|
motor-dev
|
76a412372c85c9f49be328ce89adba110ab8bef5
| 56,487
|
cpp
|
C++
|
src/test/analysis.cpp
|
akazachk/vpc
|
2339159e963b30287f780b6c03202fcbf0e9c131
|
[
"MIT"
] | 6
|
2019-03-18T00:22:43.000Z
|
2022-03-16T19:21:21.000Z
|
src/test/analysis.cpp
|
akazachk/vpc
|
2339159e963b30287f780b6c03202fcbf0e9c131
|
[
"MIT"
] | 14
|
2019-03-18T03:30:53.000Z
|
2020-10-08T15:32:45.000Z
|
src/test/analysis.cpp
|
akazachk/vpc
|
2339159e963b30287f780b6c03202fcbf0e9c131
|
[
"MIT"
] | 2
|
2021-10-05T17:44:29.000Z
|
2021-11-04T20:45:01.000Z
|
/**
* @file analysis.cpp
* @author A. M. Kazachkov
* @date 2019-03-04
*/
#include "analysis.hpp"
// COIN-OR
#include <OsiSolverInterface.hpp>
#include <OsiCuts.hpp>
#include <CglGMI.hpp>
// Project files
#include "BBHelper.hpp"
#include "CglVPC.hpp"
#include "CutHelper.hpp"
#include "Disjunction.hpp"
#include "PartialBBDisjunction.hpp"
#include "PRLP.hpp"
#include "SolverHelper.hpp"
#include "VPCParameters.hpp"
using namespace VPCParametersNamespace;
#include "utility.hpp" // isInfinity, stringValue
const int countBoundInfoEntries = 11;
const int countGapInfoEntries = 4;
const int countSummaryBBInfoEntries = 4 * 2;
const int countFullBBInfoEntries = static_cast<int>(BB_INFO_CONTENTS.size()) * 4 * 2;
const int countOrigProbEntries = 13;
const int countPostCutProbEntries = 10;
const int countDisjInfoEntries = 12;
const int countCutInfoEntries = 10;
const int countObjInfoEntries = 1 + 4 * static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES);
const int countFailInfoEntries = 1 + static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES);
const int countParamInfoEntries = intParam::NUM_INT_PARAMS + doubleParam::NUM_DOUBLE_PARAMS + stringParam::NUM_STRING_PARAMS;
int countTimeInfoEntries = 0; // set in printHeader
const int countVersionInfoEntries = 5;
const int countExtraInfoEntries = 4;
void printHeader(const VPCParameters& params,
const std::vector<std::string>& time_name,
const char SEP) {
FILE* logfile = params.logfile;
if (logfile == NULL)
return;
countTimeInfoEntries = time_name.size();
// First line of the header details the categories of information displayed
std::string tmpstring = "";
fprintf(logfile, "%c", SEP);
fprintf(logfile, "%s", "PARAM INFO");
tmpstring.assign(countParamInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "BOUND INFO");
tmpstring.assign(countBoundInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "GAP INFO");
tmpstring.assign(countGapInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "BB INFO");
tmpstring.assign(countSummaryBBInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "ORIG PROB");
tmpstring.assign(countOrigProbEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "POST-CUT PROB");
tmpstring.assign(countPostCutProbEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "DISJ INFO");
tmpstring.assign(countDisjInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "CUT INFO");
tmpstring.assign(countCutInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "OBJ INFO");
tmpstring.assign(countObjInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "FAIL INFO");
tmpstring.assign(countFailInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "FULL BB INFO");
tmpstring.assign(countFullBBInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "TIME INFO");
tmpstring.assign(countTimeInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "VERSION INFO");
tmpstring.assign(countVersionInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "WRAP UP INFO");
tmpstring.assign(countExtraInfoEntries, SEP);
fprintf(logfile, "%s", tmpstring.c_str());
fprintf(logfile, "%s", "END");
fprintf(logfile, "\n");
fprintf(logfile, "%s%c", "INSTANCE", SEP);
{ // PARAM INFO
//printParams(params, logfile, 1); // names for int/double params
printParams(params, logfile, 7); // names for int/double/string params
} // PARAM INFO
{ // BOUND INFO
int count = 0;
fprintf(logfile, "%s%c", "LP OBJ", SEP); count++; // 1
fprintf(logfile, "%s%c", "BEST DISJ OBJ", SEP); count++; // 2
fprintf(logfile, "%s%c", "WORST DISJ OBJ", SEP); count++; // 3
fprintf(logfile, "%s%c", "IP OBJ", SEP); count++; // 4
fprintf(logfile, "%s%c", "NUM GMIC", SEP); count++; // 5
fprintf(logfile, "%s%c", "GMIC OBJ", SEP); count++; // 6
fprintf(logfile, "%s%c", "NUM L&PC", SEP); count++; // 7
fprintf(logfile, "%s%c", "L&PC OBJ", SEP); count++; // 8
fprintf(logfile, "%s%c", "NUM VPC", SEP); count++; // 9
fprintf(logfile, "%s%c", "VPC OBJ", SEP); count++; // 10
fprintf(logfile, "%s%c", "VPC+GMIC OBJ", SEP); count++; // 11
assert(count == countBoundInfoEntries);
} // BOUND INFO
{ // GAP INFO
int count = 0;
fprintf(logfile, "%s%c", "GMIC % GAP CLOSED", SEP); count++; // 1
fprintf(logfile, "%s%c", "L&PC % GAP CLOSED", SEP); count++; // 2
fprintf(logfile, "%s%c", "VPC % GAP CLOSED", SEP); count++; // 3
fprintf(logfile, "%s%c", "GMIC+VPC % GAP CLOSED", SEP); count++; // 4
assert(count == countGapInfoEntries);
} // GAP INFO
{ // BB INFO
int count = 0;
std::vector<std::string> nameVec = {"NODES", "TIME"};
for (auto name : nameVec) {
fprintf(logfile, "%s%c", ("FIRST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("FIRST REF+V " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF+V " + name).c_str(), SEP); count++;
}
assert(count == countSummaryBBInfoEntries);
} // BB INFO
{ // ORIG PROB
int count = 0;
fprintf(logfile, "%s%c", "ROWS", SEP); count++;
fprintf(logfile, "%s%c", "COLS", SEP); count++;
fprintf(logfile, "%s%c", "NUM FRAC", SEP); count++;
fprintf(logfile, "%s%c", "MIN FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "MAX FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "EQ ROWS", SEP); count++;
fprintf(logfile, "%s%c", "BOUND ROWS", SEP); count++;
fprintf(logfile, "%s%c", "ASSIGN ROWS", SEP); count++;
fprintf(logfile, "%s%c", "FIXED COLS", SEP); count++;
fprintf(logfile, "%s%c", "GEN INT", SEP); count++;
fprintf(logfile, "%s%c", "BINARY", SEP); count++;
fprintf(logfile, "%s%c", "CONTINUOUS", SEP); count++;
fprintf(logfile, "%s%c", "A-DENSITY", SEP); count++;
assert(count == countOrigProbEntries);
} // ORIG PROB
{ // POST-CUT PROB
int count = 0;
fprintf(logfile, "%s%c", "NEW NUM FRAC", SEP); count++;
fprintf(logfile, "%s%c", "NEW MIN FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "NEW MAX FRACTIONALITY", SEP); count++;
fprintf(logfile, "%s%c", "NEW A-DENSITY", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE GMIC (gmics)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE VPC (gmics)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE GMIC (vpcs)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE VPC (vpcs)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE GMIC (all cuts)", SEP); count++;
fprintf(logfile, "%s%c", "ACTIVE VPC (all cuts)", SEP); count++;
assert(count == countPostCutProbEntries);
} // POST-CUT PROB
{ // DISJ INFO
int count = 0;
fprintf(logfile, "%s%c", "NUM DISJ TERMS", SEP); count++;
fprintf(logfile, "%s%c", "NUM INTEGER SOL", SEP); count++;
fprintf(logfile, "%s%c", "NUM DISJ", SEP); count++;
// fprintf(logfile, "%s%c", "MIN DENSITY PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX DENSITY PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG DENSITY PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN ROWS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX ROWS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG ROWS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN COLS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX COLS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG COLS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN POINTS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX POINTS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG POINTS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MIN RAYS PRLP", SEP); count++;
// fprintf(logfile, "%s%c", "MAX RAYS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG RAYS PRLP", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB EXPLORED NODES", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB PRUNED NODES", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB MIN DEPTH", SEP); count++;
fprintf(logfile, "%s%c", "AVG PARTIAL BB MAX DEPTH", SEP); count++;
assert(count == countDisjInfoEntries);
} // DISJ INFO
{ // CUT INFO
int count = 0;
fprintf(logfile, "%s%c", "NUM ROUNDS", SEP); count++;
fprintf(logfile, "%s%c", "NUM CUTS", SEP); count++; // repeat, but it's ok
fprintf(logfile, "%s%c", "NUM ONE SIDED CUTS", SEP); count++;
fprintf(logfile, "%s%c", "NUM OPTIMALITY CUTS", SEP); count++;
fprintf(logfile, "%s%c", "MIN SUPPORT VPC", SEP); count++;
fprintf(logfile, "%s%c", "MAX SUPPORT VPC", SEP); count++;
fprintf(logfile, "%s%c", "AVG SUPPORT VPC", SEP); count++;
fprintf(logfile, "%s%c", "MIN SUPPORT GOMORY", SEP); count++;
fprintf(logfile, "%s%c", "MAX SUPPORT GOMORY", SEP); count++;
fprintf(logfile, "%s%c", "AVG SUPPORT GOMORY", SEP); count++;
assert(count == countCutInfoEntries);
} // CUT INFO
{ // OBJ INFO
// For each objective: num obj, num fails, num active
int count = 0;
fprintf(logfile, "%s%c", "NUM OBJ", SEP); count++;
for (int obj_ind = 0; obj_ind < static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES); obj_ind++) {
fprintf(logfile, "NUM OBJ %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
fprintf(logfile, "NUM CUTS %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
fprintf(logfile, "NUM FAILS %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
fprintf(logfile, "NUM ACTIVE %s%c", CglVPC::ObjectiveTypeName[obj_ind].c_str(), SEP); count++;
}
assert(count == countObjInfoEntries);
} // OBJ INFO
{ // FAIL INFO
int count = 0;
fprintf(logfile, "%s%c", "NUM FAILS", SEP); count++;
for (int fail_ind = 0; fail_ind < static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES); fail_ind++) {
fprintf(logfile, "%s%c", CglVPC::FailureTypeName[fail_ind].c_str(), SEP); count++;
}
assert(count == countFailInfoEntries);
} // FAIL INFO
{ // FULL BB INFO
int count = 0;
for (std::string name : BB_INFO_CONTENTS) {
fprintf(logfile, "%s%c", ("FIRST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("FIRST REF+V " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("BEST REF+V " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("AVG REF " + name).c_str(), SEP); count++;
fprintf(logfile, "%s%c", ("AVG REF+V " + name).c_str(), SEP); count++;
}
for (std::string name : BB_INFO_CONTENTS) {
fprintf(logfile, "%s%c", ("ALL REF " + name).c_str(), SEP); count++;
}
for (std::string name : BB_INFO_CONTENTS) {
fprintf(logfile, "%s%c", ("ALL REF+V " + name).c_str(), SEP); count++;
}
assert(count == countFullBBInfoEntries);
} // FULL BB INFO
{ // TIME INFO
int count = 0;
for (int t = 0; t < (int) time_name.size(); t++) {
fprintf(logfile, "%s%c", time_name[t].c_str(), SEP); count++;
}
assert(count == countTimeInfoEntries);
} // TIME INFO
{ // VERSION INFO
fprintf(logfile, "%s%c", "vpc_version", SEP);
fprintf(logfile, "%s%c", "cbc_version", SEP);
fprintf(logfile, "%s%c", "clp_version", SEP);
fprintf(logfile, "%s%c", "gurobi_version", SEP);
fprintf(logfile, "%s%c", "cplex_version", SEP);
} // VERSION INFO
{ // WRAP UP INFO
fprintf(logfile, "%s%c", "ExitReason", SEP);
fprintf(logfile, "%s%c", "end_time_string", SEP);
fprintf(logfile, "%s%c", "time elapsed", SEP);
fprintf(logfile, "%s%c", "instname", SEP);
} // WRAP UP INFO
fprintf(logfile, "\n");
fflush(logfile);
} /* printHeader */
void printBoundAndGapInfo(const SummaryBoundInfo& boundInfo, FILE* logfile, const char SEP) {
if (!logfile)
return;
{ // BOUND INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(boundInfo.lp_obj, "%2.20f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(boundInfo.best_disj_obj, "%2.20f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(boundInfo.worst_disj_obj, "%2.20f").c_str(), SEP); count++;
if (!isInfinity(std::abs(boundInfo.ip_obj))) {
fprintf(logfile, "%s%c", stringValue(boundInfo.ip_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
fprintf(logfile, "%s%c", stringValue(boundInfo.num_gmic).c_str(), SEP); count++;
if (boundInfo.num_gmic > 0) {
fprintf(logfile, "%s%c", stringValue(boundInfo.gmic_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
fprintf(logfile, "%s%c", stringValue(boundInfo.num_lpc).c_str(), SEP); count++;
if (boundInfo.num_lpc > 0) {
fprintf(logfile, "%s%c", stringValue(boundInfo.lpc_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
fprintf(logfile, "%s%c", stringValue(boundInfo.num_vpc).c_str(), SEP); count++;
if (boundInfo.num_vpc > 0) {
fprintf(logfile, "%s%c", stringValue(boundInfo.vpc_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
if (!isInfinity(std::abs(boundInfo.gmic_vpc_obj))) {
fprintf(logfile, "%s%c", stringValue(boundInfo.gmic_vpc_obj, "%2.20f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++;
}
assert(count == countBoundInfoEntries);
} // BOUND INFO
{ // GAP INFO
int count = 0;
if (!isInfinity(std::abs(boundInfo.ip_obj))) {
if (!isInfinity(std::abs(boundInfo.gmic_obj))) {
double val = 100. * (boundInfo.gmic_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // gmic
}
if (!isInfinity(std::abs(boundInfo.lpc_obj))) {
double val = 100. * (boundInfo.lpc_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // lpc
}
if (!isInfinity(std::abs(boundInfo.vpc_obj))) {
double val = 100. * (boundInfo.vpc_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // vpc
}
if (!isInfinity(std::abs(boundInfo.gmic_vpc_obj))) {
double val = 100. * (boundInfo.gmic_vpc_obj - boundInfo.lp_obj)
/ (boundInfo.ip_obj - boundInfo.lp_obj);
fprintf(logfile, "%s%c", stringValue(val, "%2.6f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%c", SEP); count++; // gmic_vpc
}
} else {
fprintf(logfile, "%c", SEP); count++; // gmic
fprintf(logfile, "%c", SEP); count++; // lpc
fprintf(logfile, "%c", SEP); count++; // vpc
fprintf(logfile, "%c", SEP); count++; // gmic+vpc
}
assert(count == countGapInfoEntries);
}
fflush(logfile);
} /* printBoundAndGapInfo */
void printSummaryBBInfo(const std::vector<SummaryBBInfo>& info_vec, FILE* logfile,
const bool print_blanks, const char SEP) {
if (!logfile)
return;
int count = 0;
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%ld%c", info.first_bb_info.nodes, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%ld%c", info.best_bb_info.nodes, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%2.3f%c", info.first_bb_info.time, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
for (auto info : info_vec) {
if (!print_blanks)
fprintf(logfile, "%2.3f%c", info.best_bb_info.time, SEP);
else
fprintf(logfile, "%c", SEP);
count++;
}
fflush(logfile);
assert(count == countSummaryBBInfoEntries);
} /* printSummaryBBInfo */
void printFullBBInfo(const std::vector<SummaryBBInfo>& info_vec, FILE* logfile,
const bool print_blanks, const char SEP) {
if (!logfile)
return;
// const std::vector<bool> did_branch(info_vec.size());
// for (unsigned i = 0; i < info_vec.size(); i++) {
// did_branch[i] = info_vec[i].vec_bb_info.size() > 0;
// }
int count = 0;
if (!print_blanks) {
for (auto& info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.first_bb_info.obj, "%2.20f").c_str(), SEP);
count++;
}
for (auto& info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.best_bb_info.obj, "%2.20f").c_str(), SEP);
count++;
}
for (auto& info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.avg_bb_info.obj, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.first_bb_info.bound, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.best_bb_info.bound, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%s%c", stringValue(info.avg_bb_info.bound, "%2.20f").c_str(), SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.nodes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.nodes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.nodes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.root_passes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.root_passes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.root_passes, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.first_bb_info.first_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.best_bb_info.first_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.avg_bb_info.first_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.first_bb_info.last_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.best_bb_info.last_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.20f%c", info.avg_bb_info.last_cut_pass, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.first_bb_info.root_iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.best_bb_info.root_iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%ld%c", info.avg_bb_info.root_iters, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.first_bb_info.root_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.best_bb_info.root_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.avg_bb_info.root_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.first_bb_info.last_sol_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.best_bb_info.last_sol_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.avg_bb_info.last_sol_time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.first_bb_info.time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.best_bb_info.time, SEP);
count++;
}
for (auto info : info_vec) {
fprintf(logfile, "%2.3f%c", info.avg_bb_info.time, SEP);
count++;
}
// Finally, all
for (auto info : info_vec) {
std::vector<std::string> vec_str;
createStringFromBBInfoVec(info.vec_bb_info, vec_str);
for (unsigned i = 0; i < vec_str.size(); i++) {
fprintf(logfile, "%s%c", vec_str[i].c_str(), SEP);
count++;
}
}
} else {
for (unsigned i = 0; i < BB_INFO_CONTENTS.size() * info_vec.size() * 4; i++) {
fprintf(logfile, "%c", SEP); count++;
}
}
fflush(logfile);
assert(count == countFullBBInfoEntries);
} /* printFullBBInfo */
void printOrigProbInfo(const OsiSolverInterface* const solver, FILE* logfile,
const char SEP) {
if (!logfile)
return;
const int num_rows = solver->getNumRows();
const int num_cols = solver->getNumCols();
// Get row stats
int num_eq_rows = 0, num_bound_rows = 0, num_assign_rows = 0;
const CoinPackedMatrix* mat = solver->getMatrixByRow();
for (int row = 0; row < num_rows; row++) {
const double row_lb = solver->getRowLower()[row];
const double row_ub = solver->getRowUpper()[row];
if (isVal(row_lb, row_ub))
num_eq_rows++;
if (mat->getVectorSize(row) == 1) {
if (isVal(row_lb, row_ub))
num_assign_rows++;
else
num_bound_rows++;
}
}
// Calculate fractionality
int num_frac = 0;
int num_fixed = 0, num_gen_int = 0, num_bin = 0, num_cont = 0;
double min_frac = 1., max_frac = 0.;
for (int col = 0; col < num_cols; col++) {
const double col_lb = solver->getColLower()[col];
const double col_ub = solver->getColUpper()[col];
if (isVal(col_lb, col_ub))
num_fixed++;
if (!solver->isInteger(col)) {
num_cont++;
continue;
}
if (solver->isBinary(col))
num_bin++;
else
num_gen_int++;
const double val = solver->getColSolution()[col];
const double floorxk = std::floor(val);
const double ceilxk = std::ceil(val);
const double frac = CoinMin(val - floorxk, ceilxk - val);
if (!isVal(frac, 0., 1e-5)) {
num_frac++;
if (frac < min_frac)
min_frac = frac;
if (frac > max_frac)
max_frac = frac;
}
}
int count = 0;
fprintf(logfile, "%s%c", stringValue(num_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_cols).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_frac).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(min_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(max_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_eq_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_bound_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_assign_rows).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_fixed).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_gen_int).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_bin).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(num_cont).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue((double) mat->getNumElements() / (num_rows * num_cols)).c_str(), SEP); count++;
fflush(logfile);
assert(count == countOrigProbEntries);
} /* printOrigProbInfo */
/**
* @details Assumed that solver is already with cuts added
*/
void printPostCutProbInfo(const OsiSolverInterface* const solver,
const SummaryCutInfo& cutInfoGMICs, const SummaryCutInfo& cutInfoVPCs,
FILE* logfile, const char SEP) {
if (!logfile)
return;
const int num_rows = solver->getNumRows();
const int num_cols = solver->getNumCols();
// Calculate fractionality
int num_frac = 0;
double min_frac = 1., max_frac = 0.;
for (int col = 0; col < num_cols; col++) {
if (!solver->isInteger(col)) {
continue;
}
const double val = solver->getColSolution()[col];
const double floorxk = std::floor(val);
const double ceilxk = std::ceil(val);
const double frac = CoinMin(val - floorxk, ceilxk - val);
if (!isVal(frac, 0., 1e-5)) {
num_frac++;
if (frac < min_frac)
min_frac = frac;
if (frac > max_frac)
max_frac = frac;
}
}
int count = 0;
fprintf(logfile, "%s%c", stringValue(num_frac).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(min_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(max_frac, "%.5f").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue((double) solver->getMatrixByCol()->getNumElements() / (num_rows * num_cols)).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.num_active_gmic).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoVPCs.num_active_gmic).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.num_active_vpc).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoVPCs.num_active_vpc).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.num_active_all).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoVPCs.num_active_all).c_str(), SEP); count++;
fflush(logfile);
assert(count == countPostCutProbEntries);
} /* printPostCutProbInfo */
void printDisjInfo(const SummaryDisjunctionInfo& disjInfo, FILE* logfile,
const char SEP) {
if (!logfile)
return;
int count = 0;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_terms, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.num_integer_sol, "%d").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.num_disj, "%d").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_density_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_rows_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_cols_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_points_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_num_rays_prlp, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_explored_nodes, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_pruned_nodes, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_min_depth, "%g").c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(disjInfo.avg_max_depth, "%g").c_str(), SEP); count++;
fflush(logfile);
assert(count == countDisjInfoEntries);
} /* printDisjInfo */
void printCutInfo(const SummaryCutInfo& cutInfoGMICs,
const SummaryCutInfo& cutInfo, FILE* logfile, const char SEP) {
if (!logfile)
return;
{ // CUT INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_rounds).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_cuts).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numCutsOfType[static_cast<int>(CglVPC::CutType::ONE_SIDED_CUT)]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numCutsOfType[static_cast<int>(CglVPC::CutType::OPTIMALITY_CUT)]).c_str(), SEP); count++;
if (cutInfo.num_cuts > 0) {
fprintf(logfile, "%s%c", stringValue(cutInfo.min_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.max_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.avg_support, "%.3f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
}
if (cutInfoGMICs.num_cuts > 0) {
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.min_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.max_support).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfoGMICs.avg_support, "%.3f").c_str(), SEP); count++;
} else {
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(0).c_str(), SEP); count++;
}
assert(count == countCutInfoEntries);
} // CUT INFO
{ // OBJ INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_obj_tried).c_str(), SEP); count++;
for (int obj_ind = 0; obj_ind < static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES); obj_ind++) {
fprintf(logfile, "%s%c", stringValue(cutInfo.numObjFromHeur[obj_ind]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numCutsFromHeur[obj_ind]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numFailsFromHeur[obj_ind]).c_str(), SEP); count++;
fprintf(logfile, "%s%c", stringValue(cutInfo.numActiveFromHeur[obj_ind]).c_str(), SEP); count++;
}
assert(count == countObjInfoEntries);
} // OBJ INFO
{ // FAIL INFO
int count = 0;
fprintf(logfile, "%s%c", stringValue(cutInfo.num_failures).c_str(), SEP); count++;
for (int fail_ind = 0; fail_ind < static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES); fail_ind++) {
fprintf(logfile, "%s%c", stringValue(cutInfo.numFails[fail_ind]).c_str(), SEP); count++;
}
assert(count == countFailInfoEntries);
} // FAIL INFO
fflush(logfile);
} /* printCutInfo */
/// @details Gets cut support size and updates min/max component of \p cutInfo
int checkCutDensity(
/// [in,out] Where to save min and max support
SummaryCutInfo& cutInfo,
/// [in] Row that we want to check
const OsiRowCut* const cut,
/// [in] What counts as a zero coefficient
const double EPS) {
int num_elem = cut->row().getNumElements();
const double* el = cut->row().getElements();
for (int i = 0; i < cut->row().getNumElements(); i++) {
if (isZero(el[i], EPS)) {
num_elem--;
}
}
if (num_elem < cutInfo.min_support)
cutInfo.min_support = num_elem;
if (num_elem > cutInfo.max_support)
cutInfo.max_support = num_elem;
return num_elem;
} // checkCutDensity
/// @brief Find active cuts, and also report density of cuts
bool checkCutActivity(
const OsiSolverInterface* const solver,
const OsiRowCut* const cut) {
if (solver && solver->isProvenOptimal()) {
const double activity = dotProduct(cut->row(), solver->getColSolution());
return isVal(activity, cut->rhs());
} else {
return false;
}
} /* checkCutActivity */
/**
* @details The cut properties we want to look at are:
* 1. Gap closed
* 2. Activity (after adding cuts)
* 3. Density
*/
void analyzeStrength(
const VPCParameters& params,
const OsiSolverInterface* const solver_gmic,
const OsiSolverInterface* const solver_vpc,
const OsiSolverInterface* const solver_all,
SummaryCutInfo& cutInfoGMICs, SummaryCutInfo& cutInfoVPCs,
const OsiCuts* const gmics, const OsiCuts* const vpcs,
const SummaryBoundInfo& boundInfo, std::string& output) {
cutInfoGMICs.num_active_gmic = 0;
cutInfoGMICs.num_active_vpc = 0;
cutInfoGMICs.num_active_all = 0;
cutInfoVPCs.num_active_gmic = 0;
cutInfoVPCs.num_active_vpc = 0;
cutInfoVPCs.num_active_all = 0;
cutInfoVPCs.numActiveFromHeur.resize(static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES), 0);
if (vpcs) {
const int num_vpcs = vpcs->sizeCuts();
int total_support = 0;
for (int cut_ind = 0; cut_ind < num_vpcs; cut_ind++) {
const OsiRowCut* const cut = vpcs->rowCutPtr(cut_ind);
if (checkCutActivity(solver_gmic, cut)) {
cutInfoVPCs.num_active_gmic++;
}
if (checkCutActivity(solver_vpc, cut)) {
cutInfoVPCs.num_active_vpc++;
cutInfoVPCs.numActiveFromHeur[static_cast<int>(cutInfoVPCs.objType[cut_ind])]++;
}
if (checkCutActivity(solver_all, cut)) {
cutInfoVPCs.num_active_all++;
}
total_support += checkCutDensity(cutInfoVPCs, cut, params.get(EPS) / 2.);
}
cutInfoVPCs.avg_support = (double) total_support / num_vpcs;
}
if (gmics) {
const int num_gmics = gmics->sizeCuts();
cutInfoGMICs.num_cuts = num_gmics;
int total_support = 0;
for (int cut_ind = 0; cut_ind < num_gmics; cut_ind++) {
const OsiRowCut* const cut = gmics->rowCutPtr(cut_ind);
if (checkCutActivity(solver_gmic, cut)) {
cutInfoGMICs.num_active_gmic++;
}
if (checkCutActivity(solver_vpc, cut)) {
cutInfoGMICs.num_active_vpc++;
}
if (checkCutActivity(solver_all, cut)) {
cutInfoGMICs.num_active_all++;
}
total_support += checkCutDensity(cutInfoGMICs, cut, params.get(EPS) / 2.);
}
cutInfoGMICs.avg_support = (double) total_support / num_gmics;
}
// Print results from adding cuts
int NAME_WIDTH = 25;
int NUM_DIGITS_BEFORE_DEC = 7;
int NUM_DIGITS_AFTER_DEC = 7;
const double INF = std::numeric_limits<double>::max();
char tmpstring[300];
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"\n## Results from adding cuts ##\n");
output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "LP: ",
stringValue(boundInfo.lp_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
if (!isInfinity(std::abs(boundInfo.gmic_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"%-*.*s%s (%d cuts", NAME_WIDTH, NAME_WIDTH, "GMICs: ",
stringValue(boundInfo.gmic_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str(),
boundInfo.num_gmic);
output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active GMICs", cutInfoGMICs.num_active_gmic);
output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active VPCs", cutInfoVPCs.num_active_gmic);
output += tmpstring;
output += ")\n";
}
if (!isInfinity(std::abs(boundInfo.vpc_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"%-*.*s%s (%d cuts", NAME_WIDTH, NAME_WIDTH, "VPCs: ",
stringValue(boundInfo.vpc_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str(),
boundInfo.num_vpc);
output += tmpstring;
if (gmics && gmics->sizeCuts() > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active GMICs", cutInfoGMICs.num_active_vpc);
output += tmpstring;
}
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active VPCs", cutInfoVPCs.num_active_vpc);
output += tmpstring;
output += ")\n";
}
if (boundInfo.num_gmic + boundInfo.num_lpc > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
"%-*.*s%s (%d cuts", NAME_WIDTH, NAME_WIDTH, "All: ",
stringValue(boundInfo.all_cuts_obj, "% -*.*g", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str(),
boundInfo.num_gmic + boundInfo.num_lpc + boundInfo.num_vpc);
output += tmpstring;
if (gmics && gmics->sizeCuts() > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active GMICs", cutInfoGMICs.num_active_all);
output += tmpstring;
}
if (vpcs && vpcs->sizeCuts() > 0) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char),
", %d active VPCs", cutInfoVPCs.num_active_all);
output += tmpstring;
}
output += ")\n";
}
if (!isInfinity(std::abs(boundInfo.best_disj_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "Disjunctive lb: ",
stringValue(boundInfo.best_disj_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
}
if (!isInfinity(std::abs(boundInfo.worst_disj_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "Disjunctive ub: ",
stringValue(boundInfo.worst_disj_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
}
if (!isInfinity(std::abs(boundInfo.ip_obj))) {
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*.*s%s\n",
NAME_WIDTH, NAME_WIDTH, "IP: ",
stringValue(boundInfo.ip_obj, "% -*.*g",
INF,
NUM_DIGITS_BEFORE_DEC,
NUM_DIGITS_AFTER_DEC).c_str());
output += tmpstring;
}
} /* analyzeStrength */
/** @details Branch-and-bound itself has already been performed */
void analyzeBB(const VPCParameters& params, SummaryBBInfo& info_nocuts,
SummaryBBInfo& info_mycuts, SummaryBBInfo& info_allcuts, std::string& output) {
if (params.get(BB_RUNS) == 0) {
return;
}
// B&B mode: ones bit = no_cuts, tens bit = w/vpcs, hundreds bit = w/gmics
const int mode_param = params.get(intParam::BB_MODE);
const int mode_ones = mode_param % 10;
const int mode_tens = (mode_param % 100 - (mode_param % 10)) / 10;
const int mode_hundreds = (mode_param % 1000 - (mode_param % 100)) / 100;
const bool branch_with_no_cuts = (mode_ones > 0);
const bool branch_with_vpcs = (mode_tens > 0) && (info_mycuts.num_cuts > 0);
const bool branch_with_gmics = (mode_hundreds > 0) && (info_allcuts.num_cuts > 0);
if (branch_with_no_cuts + branch_with_vpcs + branch_with_gmics == 0) {
return;
}
// Save results to string and also print to the logfile
const int NAME_WIDTH = 10; //25
const int NUM_DIGITS_BEFORE_DEC = 15; //10
const int NUM_DIGITS_AFTER_DEC = 2; //2
const double INF = 1e50; //params.get(doubleParam::INF);
const bool use_gurobi = use_bb_option(params.get(intParam::BB_STRATEGY), BB_Strategy_Options::gurobi);
const bool use_cplex = use_bb_option(params.get(intParam::BB_STRATEGY), BB_Strategy_Options::cplex);
const bool use_cbc = use_bb_option(params.get(intParam::BB_STRATEGY), BB_Strategy_Options::cbc);
const std::string SOLVER =
use_gurobi ? "Gur" :
(use_cplex ? "Cpx" :
(use_cbc ? "Cbc" : "")
);
char tmpstring[300];
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n## Branch-and-bound results ##\n"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, ""); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Obj"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Bound"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Iters"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Nodes"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Root passes"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "First cut pass"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Last cut pass"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Root time"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Last sol time"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NUM_DIGITS_BEFORE_DEC, "Time"); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
if (branch_with_no_cuts) {
const std::string CURR_NAME = SOLVER;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, CURR_NAME.c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.obj, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.bound, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.iters, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.nodes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.root_passes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.first_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.last_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.root_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.last_sol_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_nocuts.avg_bb_info.time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
} // no cuts
if (branch_with_vpcs) {
const std::string CURR_NAME = SOLVER + "V";
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, CURR_NAME.c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.obj, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.bound, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.iters, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.nodes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.root_passes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.first_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.last_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.root_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.last_sol_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_mycuts.avg_bb_info.time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
} // vpcs
if (branch_with_gmics) {
const std::string CURR_NAME = SOLVER + "V+G";
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%-*s", NAME_WIDTH, CURR_NAME.c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.obj, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.bound, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.iters, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.nodes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.root_passes, "%-*ld", std::numeric_limits<long double>::max(), NUM_DIGITS_BEFORE_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.first_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.last_cut_pass, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.root_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.last_sol_time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "%s", stringValue(info_allcuts.avg_bb_info.time, "%-*.*f", INF, NUM_DIGITS_BEFORE_DEC, NUM_DIGITS_AFTER_DEC).c_str()); output += tmpstring;
snprintf(tmpstring, sizeof(tmpstring) / sizeof(char), "\n"); output += tmpstring;
} // gmics
} /* analyzeBB */
double getNumGomoryRounds(const VPCParameters& params,
const OsiSolverInterface* const origSolver,
const OsiSolverInterface* const postCutSolver) {
#ifdef TRACE
printf("\nGetting number rounds of Gomory cuts req'd to get bound.\n");
#endif
const int num_cuts = postCutSolver->getNumRows() - origSolver->getNumRows();
const double post_cut_opt = postCutSolver->getObjValue();
const int min_sic_rounds = (params.get(STRENGTHEN) == 2) ? 2 : 0;
int max_rounds = 1000;
int total_num_sics = 0;
int num_sic_rounds = 0;
double curr_sic_opt = 0.;
std::vector<int> numCutsByRoundSIC;
std::vector<double> boundByRoundSIC;
OsiSolverInterface* copySolver = origSolver->clone();
if (!copySolver->isProvenOptimal()) {
copySolver->initialSolve();
checkSolverOptimality(copySolver, false);
}
while (num_sic_rounds < min_sic_rounds
|| (lessThanVal(curr_sic_opt, post_cut_opt) && total_num_sics < num_cuts)) {
OsiCuts GMICs;
CglGMI gen;
gen.generateCuts(*copySolver, GMICs);
const int curr_num_cuts = GMICs.sizeCuts();
if (curr_num_cuts == 0)
break;
num_sic_rounds++;
total_num_sics += curr_num_cuts;
numCutsByRoundSIC.push_back(curr_num_cuts);
curr_sic_opt = applyCutsCustom(copySolver, GMICs, params.logfile);
boundByRoundSIC.push_back(curr_sic_opt);
// Other stopping conditions:
// Bound does not improve at all after one round
if (num_sic_rounds >= 2
&& !greaterThanVal(curr_sic_opt, boundByRoundSIC[num_sic_rounds - 2])) {
break;
}
// Bound does not significantly improve after five rounds
if (num_sic_rounds > 4) {
const double delta = curr_sic_opt - boundByRoundSIC[num_sic_rounds - 4];
if (!greaterThanVal(delta, 1e-3)) {
break;
}
}
} // do rounds of Gomory cuts
if (max_rounds < num_sic_rounds) {
max_rounds = boundByRoundSIC.size();
}
const double final_sic_bound = copySolver->getObjValue();
return final_sic_bound;
} /* getNumGomoryRounds */
void updateDisjInfo(SummaryDisjunctionInfo& disjInfo, const int num_disj, const CglVPC& gen) {
if (num_disj <= 0)
return;
const Disjunction* const disj = gen.getDisjunction();
const PRLP* const prlp = gen.getPRLP();
if (!prlp)
return;
disjInfo.num_disj = num_disj;
disjInfo.num_integer_sol += !(disj->integer_sol.empty());
disjInfo.avg_num_terms = (disjInfo.avg_num_terms * (num_disj - 1) + disj->num_terms) / num_disj;
disjInfo.avg_density_prlp = (disjInfo.avg_density_prlp * (num_disj - 1) + prlp->density) / num_disj;
disjInfo.avg_num_rows_prlp += (disjInfo.avg_num_rows_prlp * (num_disj - 1) + prlp->getNumRows()) / num_disj;
disjInfo.avg_num_cols_prlp += (disjInfo.avg_num_cols_prlp * (num_disj - 1) + prlp->getNumCols()) / num_disj;
disjInfo.avg_num_points_prlp += (disjInfo.avg_num_points_prlp * (num_disj - 1) + prlp->numPoints) / num_disj;
disjInfo.avg_num_rays_prlp += (disjInfo.avg_num_rays_prlp * (num_disj - 1) + prlp->numRays) / num_disj;
try {
const PartialBBDisjunction* const partialDisj =
dynamic_cast<const PartialBBDisjunction* const >(disj);
disjInfo.avg_explored_nodes += (disjInfo.avg_explored_nodes * (num_disj - 1) + partialDisj->data.num_nodes_on_tree) / num_disj;
disjInfo.avg_pruned_nodes += (disjInfo.avg_pruned_nodes * (num_disj - 1) + partialDisj->data.num_pruned_nodes) / num_disj;
disjInfo.avg_min_depth += (disjInfo.avg_min_depth * (num_disj - 1) + partialDisj->data.min_node_depth) / num_disj;
disjInfo.avg_max_depth += (disjInfo.avg_max_depth * (num_disj - 1) + partialDisj->data.max_node_depth) / num_disj;
} catch (std::exception& e) {
}
} /* updateDisjInfo */
/**
* @details Use this to add to cutInfo (but within one round,
* because the cutType and objType vectors are cleared in gen in each round
* (so tracking that based on isSetupForRepeatedUse does not work,
* and the old cutType and objType stored in cutInfo would be overwritten)
*/
void updateCutInfo(SummaryCutInfo& cutInfo, const CglVPC& gen) {
cutInfo.num_cuts += gen.num_cuts;
cutInfo.num_obj_tried += gen.num_obj_tried;
cutInfo.num_failures += gen.num_failures;
// For cutType and objType, what we do depends on whether the generator is setup for repeated use or not
if (gen.isSetupForRepeatedUse) {
cutInfo.cutType = gen.cutType;
cutInfo.objType = gen.objType;
} else {
cutInfo.cutType.insert(cutInfo.cutType.end(), gen.cutType.begin(), gen.cutType.end());
cutInfo.objType.insert(cutInfo.objType.end(), gen.objType.begin(), gen.objType.end());
}
if (cutInfo.numCutsOfType.size() > 0) {
for (int i = 0; i < static_cast<int>(CglVPC::CutType::NUM_CUT_TYPES); i++) {
cutInfo.numCutsOfType[i] += gen.numCutsOfType[i];
}
} else {
cutInfo.numCutsOfType = gen.numCutsOfType;
}
if (cutInfo.numCutsFromHeur.size() > 0) {
for (int i = 0; i < static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES); i++) {
cutInfo.numCutsFromHeur[i] += gen.numCutsFromHeur[i];
cutInfo.numObjFromHeur[i] += gen.numObjFromHeur[i];
cutInfo.numFailsFromHeur[i] += gen.numFailsFromHeur[i];
}
} else {
cutInfo.numCutsFromHeur = gen.numCutsFromHeur;
cutInfo.numObjFromHeur = gen.numObjFromHeur;
cutInfo.numFailsFromHeur = gen.numFailsFromHeur;
}
if (cutInfo.numFails.size() > 0) {
for (int i = 0; i < static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES); i++) {
cutInfo.numFails[i] += gen.numFails[i];
}
} else {
cutInfo.numFails = gen.numFails;
}
} /* updateCutInfo (within one round) */
/**
* @details Compute total number of cuts / objectives / failures of various types, as well as total activity
*/
void setCutInfo(SummaryCutInfo& cutInfo, const int num_rounds,
const SummaryCutInfo* const oldCutInfos) {
const int numCutTypes = static_cast<int>(CglVPC::CutType::NUM_CUT_TYPES);
const int numObjTypes = static_cast<int>(CglVPC::ObjectiveType::NUM_OBJECTIVE_TYPES);
const int numFailTypes = static_cast<int>(CglVPC::FailureType::NUM_FAILURE_TYPES);
cutInfo.num_cuts = 0;
cutInfo.num_active_gmic = 0;
cutInfo.num_active_vpc = 0;
cutInfo.num_active_all = 0;
cutInfo.num_obj_tried = 0;
cutInfo.num_failures = 0;
cutInfo.num_rounds = num_rounds;
cutInfo.cutType.resize(0);
cutInfo.objType.resize(0);
cutInfo.numCutsOfType.clear();
cutInfo.numCutsOfType.resize(numCutTypes, 0);
cutInfo.numCutsFromHeur.clear();
cutInfo.numCutsFromHeur.resize(numObjTypes, 0);
cutInfo.numObjFromHeur.clear();
cutInfo.numObjFromHeur.resize(numObjTypes, 0);
cutInfo.numFailsFromHeur.clear();
cutInfo.numFailsFromHeur.resize(numObjTypes, 0);
cutInfo.numActiveFromHeur.clear();
cutInfo.numActiveFromHeur.resize(numObjTypes, 0);
cutInfo.numFails.clear();
cutInfo.numFails.resize(numFailTypes, 0);
for (int round = 0; round < num_rounds; round++) {
cutInfo.num_cuts += oldCutInfos[round].num_cuts;
cutInfo.num_active_gmic += oldCutInfos[round].num_active_gmic;
cutInfo.num_active_vpc += oldCutInfos[round].num_active_vpc;
cutInfo.num_active_all += oldCutInfos[round].num_active_all;
cutInfo.num_obj_tried += oldCutInfos[round].num_obj_tried;
cutInfo.num_failures += oldCutInfos[round].num_failures;
for (int i = 0; i < numCutTypes; i++) {
cutInfo.numCutsOfType[i] += oldCutInfos[round].numCutsOfType[i];
}
for (int i = 0; i < numObjTypes; i++) {
cutInfo.numCutsFromHeur[i] += oldCutInfos[round].numCutsFromHeur[i];
cutInfo.numObjFromHeur[i] += oldCutInfos[round].numObjFromHeur[i];
cutInfo.numFailsFromHeur[i] += oldCutInfos[round].numFailsFromHeur[i];
}
if (oldCutInfos[round].numActiveFromHeur.size() > 0) {
for (int i = 0; i < numObjTypes; i++) {
cutInfo.numActiveFromHeur[i] += oldCutInfos[round].numActiveFromHeur[i];
}
}
for (int i = 0; i < numFailTypes; i++) {
cutInfo.numFails[i] += oldCutInfos[round].numFails[i];
}
}
cutInfo.cutType.resize(cutInfo.num_cuts);
cutInfo.objType.resize(cutInfo.num_cuts);
int cut_ind = 0;
for (int round = 0; round < num_rounds; round++) {
for (int i = 0; i < oldCutInfos[round].num_cuts; i++) {
cutInfo.cutType[cut_ind] = oldCutInfos[round].cutType[i];
cutInfo.objType[cut_ind] = oldCutInfos[round].objType[i];
cut_ind++;
}
}
} /* setCutInfo (merge from multiple rounds) */
| 45.849838
| 217
| 0.652876
|
akazachk
|
76a4ece61a7d68d10de049ef4a74ce6bd9f37d37
| 1,494
|
cpp
|
C++
|
multiview/contrib/mosya_conics/src/IsCrossingWindow.cpp
|
prcvlabs/multiview
|
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
|
[
"Apache-2.0"
] | 5
|
2021-09-03T23:12:08.000Z
|
2022-03-04T21:43:32.000Z
|
multiview/contrib/mosya_conics/src/IsCrossingWindow.cpp
|
prcvlabs/multiview
|
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
|
[
"Apache-2.0"
] | 3
|
2021-09-08T02:57:46.000Z
|
2022-02-26T05:33:02.000Z
|
multiview/contrib/mosya_conics/src/IsCrossingWindow.cpp
|
prcvlabs/multiview
|
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
|
[
"Apache-2.0"
] | 2
|
2021-09-26T03:14:40.000Z
|
2022-01-26T06:42:52.000Z
|
namespace mosya {
int IsCrossingWindow(M6x1 A, reals R)
/*
*/
{
reals RR,F0,x,y,det,Two=2.;
RR = R*R;
F0 = (A(0) + A(1) + A(1) + A(2))*RR + Two*(A(3) + A(4))*R + A(5);
if (((A(0) - A(1) - A(1) + A(2))*RR + Two*(A(3) - A(4))*R + A(5))*F0 <= 0) return(1);
if (((A(0) - A(1) - A(1) + A(2))*RR - Two*(A(3) - A(4))*R + A(5))*F0 <= 0) return(1);
if (((A(0) + A(1) + A(1) + A(2))*RR - Two*(A(3) + A(4))*R + A(5))*F0 <= 0) return(1);
y = -(A(1)*R+A(4))/A(2);
if (abs(y) < R) { if ((A(0)*RR + Two*A(1)*R*y + A(2)*y*y + Two*(A(3)*R + A(4)*y) + A(5))*F0 <= 0) return(1); }
y = (A(1)*R-A(4))/A(2);
if (abs(y) < R) { if ((A(0)*RR - Two*A(1)*R*y + A(2)*y*y - Two*(A(3)*R - A(4)*y) + A(5))*F0 <= 0) return(1); }
x = -(A(1)*R+A(3))/A(0);
if (abs(x) < R) { if ((A(0)*x*x + Two*A(1)*R*x + A(2)*RR + Two*(A(3)*x + A(4)*R) + A(5))*F0 <= 0) return(1); }
x = (A(1)*R-A(3))/A(0);
if (abs(x) < R) { if ((A(0)*x*x - Two*A(1)*R*x + A(2)*RR + Two*(A(3)*x - A(4)*R) + A(5))*F0 <= 0) return(1); }
det = A(0)*A(2) - A(1)*A(1); // determinant
if (abs(det)<1.e-100) return(0); // if singular, skip this step
x = (A(3)*A(2) - A(4)*A(1))/det;
y = (A(0)*A(4) - A(1)*A(3))/det;
if ((abs(x)<R) && (abs(y)<R)) { if ((A(0)*x*x + Two*A(1)*x*y + A(2)*y*y + Two*(A(3)*x + A(4)*y) + A(5))*F0 <= 0) return(1); }
return(0);
} // end of function IsCrossingWindow
} // namespace mosya
| 35.571429
| 132
| 0.390897
|
prcvlabs
|
76a6fbb86df683ddd90b26466743ee20b8bee87b
| 1,247
|
cpp
|
C++
|
C-Plus-Plus/Pancake_sort.cpp
|
MjCode01/DS-Algo-Point
|
79d826fa63090014dfaab281e5170c25b86c6bbf
|
[
"MIT"
] | 1,148
|
2020-09-28T15:06:16.000Z
|
2022-03-17T16:30:08.000Z
|
C-Plus-Plus/Pancake_sort.cpp
|
MjCode01/DS-Algo-Point
|
79d826fa63090014dfaab281e5170c25b86c6bbf
|
[
"MIT"
] | 520
|
2020-09-28T18:34:26.000Z
|
2021-10-30T17:06:43.000Z
|
C-Plus-Plus/Pancake_sort.cpp
|
MjCode01/DS-Algo-Point
|
79d826fa63090014dfaab281e5170c25b86c6bbf
|
[
"MIT"
] | 491
|
2020-09-28T18:40:14.000Z
|
2022-03-20T13:41:44.000Z
|
//This code is solely written by Arnav without any external sources.
// Pancake sort
#include<bits/stdc++.h>
using namespace std;
void flip(int arr[] , int i){
for(int j = 0 ; j <= (i / 2) ; j++)
{
int temp = arr[i-j] ;
arr[i-j] = arr[j] ;
arr[j] = temp ;
}
}
// time complexity = O(n) ; Space complexity = O(1)
void sort(int arr[] , int n){
int curr_size = n ;
while(curr_size > 0)
{
int max_index = max_element(arr , arr + curr_size) - arr; // time complexity = O(n) ; space complexity = O(1);
if(max_index !=curr_size -1)
{
flip(arr, max_index);
flip(arr, curr_size -1) ;}
curr_size-- ;
}
}
//time complexity = O(n * max(p, q)) where p is the time complexity of flip() and q is the complexity of max_element(); space complexity = O(1)
int main()
{
int n ; cin >> n ;
int a[n] ;
for(int i = 0 ; i < n ; i ++)
{
cin >> a[i] ;
}
sort(a , n);
for(int i = 0 ; i < n ; i ++)
{
cout << a[i] << " " ;
}
}
/* here n is the number of elements in the array to be sorted and a[0...n-1] is the array.
input example:
5
5 4 3 2 1
Output:
1 2 3 4 5
Overall time complexity = O(n*n) ; Overall Space complexity = O(1) */
| 18.338235
| 144
| 0.540497
|
MjCode01
|
76a97b05240b232ce4c2d9953ced0cdb79098a1e
| 21,068
|
cc
|
C++
|
src/moorerror.cc
|
CHEN-Lin/OpenMoor
|
f463f586487b9023e7f3678c9d851000558b14d7
|
[
"Apache-2.0"
] | 7
|
2019-02-10T07:03:45.000Z
|
2022-03-04T16:09:38.000Z
|
src/moorerror.cc
|
CHEN-Lin/OpenMoor
|
f463f586487b9023e7f3678c9d851000558b14d7
|
[
"Apache-2.0"
] | null | null | null |
src/moorerror.cc
|
CHEN-Lin/OpenMoor
|
f463f586487b9023e7f3678c9d851000558b14d7
|
[
"Apache-2.0"
] | 4
|
2018-03-01T14:34:52.000Z
|
2018-06-14T12:13:55.000Z
|
// This file is part of OpenMOOR, an Open-source simulation program for MOORing
// systems in offshore renewable energy applications.
//
// Copyright 2018 Lin Chen <l.chen.tj@gmail.com> & Biswajit Basu <basub@tcd.ie>
//
// 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 "moorerror.h"
namespace moor {
std::string ErrorCategory::message(ErrorCode err)
{
switch (err)
{
case ErrorCode::SUCCESS:
return "Successful.";
case ErrorCode::MOORING_FILE_NONEXISTENT:
return "Failed to find main mooring file. It should be a xml file.";
case ErrorCode::MOORING_FILE_ERROR_PARSE:
return "Parse error found in main input xml file. Check xml format.";
case ErrorCode::MOORING_FILE_NO_CASE:
return "Root node of main input file must be 'case'.";
case ErrorCode::MOORING_FILE_INCOMPLETE:
return ("Incomplete components found in mooring input file. "
"Required are: 'constants', 'platform', 'connections', "
"'cables', 'structuralproperties', 'hydroproperties', "
"'seabedproperties', 'currents' and 'solvers'.");
case ErrorCode::MOORING_FILE_INCOMPLETE_CONSTANTS:
return ("Incomplete constants definition. Required are "
"'gravitationalacceleration', 'waterdensity' and "
"'waterdepth'.");
case ErrorCode::MOORING_FILE_NAN_CONSTANT:
return "NaN found in constant definitions.";
case ErrorCode::MOORING_FILE_INCOMPLETE_PLATFORM:
return ("Failed to find platform position definition or incomplete "
"position components provided. Position of the reference "
"point is required to have six component: 'x', 'y', 'z' "
"'roll', 'pitch' and 'yaw'.");
case ErrorCode::MOORING_FILE_NAN_PLATFORM_POSITION:
return "NaN found in platform position definition.";
case ErrorCode::MOORING_FILE_BAD_CONNECTIONS_NUM:
return ("Unacceptable 'number' of 'connections': "
"NaN or nonpositive.");
case ErrorCode::MOORING_FILE_NO_CONNECTION:
return "Failed to find at least one connection definition.";
case ErrorCode::MOORING_FILE_INCOMPLETE_CONNECTION_DEF:
return ("Incomplete connection definition. Required are 'id', "
"'type', 'x', 'y' and 'z'.");
case ErrorCode::MOORING_FILE_NAN_CONNECTION_DEF:
return "NaN found in connection 'id' or position components.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_CONNECTION_ID:
return ("Found connection 'id' out of range of the 'number' of "
"'connections'. ");
case ErrorCode::MOORING_FILE_UNKNOWN_CONNECTION_TYPE:
return ("Found unknown connection 'type'. Currently supported "
"types are 'anchor' and 'fairlead'.");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_CONNECTION_ID:
return ("Found connection missed or repeatedly defined. Check "
"connection 'id' and the 'number' of 'connections'.");
// Cable error.
case ErrorCode::MOORING_FILE_BAD_CABLES_NUM:
return "Unacceptable 'number' of 'cables': NaN or nonpositive.";
case ErrorCode::MOORING_FILE_NO_CABLE_DEF:
return "Failed to find at least one cable.";
case ErrorCode::MOORING_FILE_INCOMPLETE_CABLE_DEF:
return ("Incomplete cable definition. Required are: 'id', "
"'initialstatefile (can be empty)', 'icurrent', 'isolver', "
"'segmentlength', 'istructproperty', "
"'ihydroproperty', 'iseabedproperty', 'iconnection' and "
"'saveflag'.");
case ErrorCode::MOORING_FILE_NAN_CABLE_DEF:
return ("NaN found in cable 'id', 'icurrent', 'isolver', "
"'nodenumber', or 'saveflag'.");
case ErrorCode::MOORING_FILE_OUTOFRANGE_CABLE_ID:
return "Found cable 'id' out of range of the 'number' of 'cables'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_LENGTH:
return "NaN found in cable 'segmentlength'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_STRUCTPROP_INDEX:
return "NaN found in cable 'istructproperty'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_HYDROPROP_INDEX:
return "NaN found in cable 'ihydroproperty'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_SEABEDPROP_INDEX:
return "NaN found in cable 'iseabedproperty'.";
case ErrorCode::MOORING_FILE_NAN_CABLE_CONNECTION_INDEX:
return "NaN found in cable 'iconnection'.";
case ErrorCode::MOORING_FILE_BAD_CABLE_CONNECTION_INDEX:
return "Failed to find two connection indexes for a cable.";
case ErrorCode::MOORING_FILE_MISSED_REPEATED_CABLE_ID:
return ("Found cable missed or repeatedly defined. Check cable 'id'"
" and the 'number' of cables.");
// Structural property error.
case ErrorCode::MOORING_FILE_BAD_STRUCTPROPS_NUM:
return "Unacceptable number of 'structuralproperties'.";
case ErrorCode::MOORING_FILE_NO_STRUCTPROP:
return "Failed to find at least one 'structuralproperty'.";
case ErrorCode::MOORING_FILE_INCOMPLETE_STRUCTPROP_DEF:
return ("Incomplete 'structuralproperty' data. Required are: 'id', "
"'diameter', 'unitlengthmass', 'unitlengthweight', "
"'bendingstiffness', 'torsionalstiffness', and "
"'dampingcoefficient'");
case ErrorCode::MOORING_FILE_NAN_STRUCTPROP:
return "NaN found in 'structuralproperty'.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_STRUCTPROP_ID:
return ("Found 'structuralproperty' out of range of the number of "
"'structuralproperties'.");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_STRUCTPROP_ID:
return ("Found 'structuralproperty' missed or repeatedly defined. "
"Check 'structuralproperty' 'id' and the 'number' of "
"'structuralproperties'.");
// Hydro-property error.
case ErrorCode::MOORING_FILE_BAD_HYDROPROPS_NUM:
return ("Unacceptable number of 'hydroperoperties': "
"NaN or nonpositive.");
case ErrorCode::MOORING_FILE_NO_HYDROPROP:
return "Unable to find at least one 'hydroproperty'.";
case ErrorCode::MOORING_FILE_INCOMPLETE_HYDROPROP_DEF:
return ("Incomplete hydroproperty data. Required are 'id', "
"'addedmasscoefficient' and 'dragcoefficient'");
case ErrorCode::MOORING_FILE_NAN_HYDROPROP:
return "NaN found in 'hydroproperty' 'id'.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_HYDROPROP_ID:
return "Found 'hydroproperty' 'id' out of range.";
case ErrorCode::MOORING_FIEL_INCOMPLETE_HYDRO_COEFFICIENTS:
return ("Incomplete addedmasscoefficient or dragcoefficient data."
"Required are 'tangential', 'normal' and 'binormal' "
"components");
case ErrorCode::MOORING_FIEL_NAN_HYDRO_COEFFICIENTS:
return ("NaN found in 'addedmasscoefficient' or 'dragcoefficient' "
"data");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_HYDROPROP_ID:
return ("Found 'hydroproperty' missed or repeatedly defined. "
"Check 'hydroproperty' 'id' and the 'number' of "
"'hydroproperties'.");
// Seabed property error.
case ErrorCode::MOORING_FILE_BAD_SEABEDPROPS_NUM:
return "Unacceptable number of 'seabedproperties'.";
case ErrorCode::MOORING_FILE_NO_SEABEDPROP:
return "Unable to find at least one 'seabedproperty' definition.";
case ErrorCode::MOORING_FILE_INCOMPLETE_SEABEDPROP_DEF:
return ("Incomplete seabedproperty data. Required are 'id', "
"'dampingcoefficient' and 'stiffnesscoefficient'.");
case ErrorCode::MOORING_FILE_NAN_SEABEDPROP:
return ("NaN found in 'seabedproperty' data.");
case ErrorCode::MOORING_FILE_OUTOFRANGE_SEABEDPROP_ID:
return ("Seabedproperty 'id' is out of range!\n");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_SEABEDPROP_ID:
return ("Found 'seabedproperty' missed or repeatedly defined. "
"Check 'seabedproperty' 'id' and the number of "
"'seabedproperties'.");
// Current error.
case ErrorCode::MOORING_FILE_BAD_CURRENTS_NUM:
return "Unacceptable of number of 'currents'.";
case ErrorCode::MOORING_FILE_NO_CURRENT:
return "Unable find at least one current definition";
case ErrorCode::MOORING_FILE_INCOMPLETE_CURRENT_DEF:
return ("Incomplete current data. Required are 'id', "
"'polyorder' and 'profilefile'.");
case ErrorCode::MOORING_FILE_NAN_CURRENT:
return "NaN found in current 'id' or 'polyorder'.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_CURRENT_ID:
return "Found out of range current 'id'.";
case ErrorCode::MOORING_FILE_MISSED_REPEATED_CURRENT_ID:
return ("Found 'current' missed or repeatedly defined. "
"Check 'current' 'id' and the number of 'currents'.");
case ErrorCode::MOORING_FILE_BAD_CURRENT_DATA:
return ("Unacceptable current profile data or NaN found. Check "
"current data file. Current data file should have one line "
"of header and data matrix with 6 columns containing "
"three coordinates in global reference system and three "
"current velocities.");
// Solver error.
case ErrorCode::MOORING_FILE_BAD_SOLVERS_NUM:
return "Unacceptable number of 'solvers'.";
case ErrorCode::MOORING_FILE_NO_SOLVER:
return "Unable to find at least one 'solver' definition.";
case ErrorCode::MOORING_FILE_INCOMPLETE_SOLVER_DEF:
return ("Incomplete solver definition. Required are 'id', "
"'iterationnumberlimit', 'convergencetolerance', "
"'initialrelaxationfactor', 'relaxationincreasefactor', "
"'relaxationdecreasefactor' and 'lambdainfinity'");
case ErrorCode::MOORING_FILE_NAN_SOLVER:
return "NaN found in 'solver' definition.";
case ErrorCode::MOORING_FILE_OUTOFRANGE_SOLVER_ID:
return ("Found solver 'id' out of range of the 'number' of "
"'solvers'.");
case ErrorCode::MOORING_FILE_MISSED_REPEATED_SOLVER_ID:
return ("Found 'solver' missed or repeatedly defined. "
"Check 'solver' 'id' and the number of 'solvers'.");
// Setting error.
case ErrorCode::SETTING_FILE_NONEXISTENT:
return "Failed to find Setting.xml file.";
case ErrorCode::SETTING_FILE_ERROR_PARSE:
return "Found xml parse error in Setting.xml.";
case ErrorCode::SETTING_FILE_NO_SETTING_NODE:
return "Root node of Setting.xml must be setting.";
case ErrorCode::SETTING_FILE_NO_SIMULATION_TYPE:
return "Failed to find 'simulationtype' definition in Setting.xml.";
case ErrorCode::SETTING_FILE_UNKNOWN_SIMULATION_TYPE:
return ("Found unknown 'simulationtype'. Currently supported are "
"'shooting', 'relaxation', and 'forcedmotion'.");
case ErrorCode::SETTING_FILE_NO_MOORING_FILE_DEF:
return "Failed to find 'mooringinputfile' definition in Setting.xml.";
case ErrorCode::SETTING_FILE_NO_SHOOTING_PARA:
return "Unable to find 'shooting' parameter definition.";
case ErrorCode::SETTING_FILE_INCOMPLETE_SHOOTING_PARA:
return ("Incomplete parameters for shooting. Required are "
"'fairleadpositiontolerance', "
"'fairleadforcerelaxationfactor', "
"'fairleadpositioniterationlimit', "
"'platformpositioniterationlimit', "
"'platformdisplacementtolerance', "
"'platformdisplacementrelaxationfactor', "
"'cableoutofplanestiffness', "
"'platformhydrostaticstiffness' and "
"'platformotherload'.");
case ErrorCode::SETTING_FILE_NAN_SHOOTING_PARA:
return ("NaN found in shooting parameters: "
"'fairleadpositiontolerance', "
"'fairleadforcerelaxationfactor', "
"'fairleadpositioniterationlimit', "
"'platformpositioniterationlimit', "
"'platformdisplacementtolerance' or "
"'platformdisplacementrelaxationfactor'.");
case ErrorCode::SETTING_FILE_INCOMPLETE_SHOOTING_FAIRLEAD_TOLERANCE:
return ("Incomplete definition of 'shooting' parameter "
"fairleadpositiontolerance.");
case ErrorCode::SETTING_FILE_NAN_SHOOTING_FAIRLEAD_TOLERANCE:
return ("NaN found in 'shooting' parameter "
"'fairleadpositiontolerance'.");
case ErrorCode::SETTING_FILE_BAD_SHOOTING_STIFFNESS:
return ("NaN or not 36 elements found in "
"'platformhydrostaticstiffness' for "
"'shooting'.");
case ErrorCode::SETTING_FILE_BAD_SHOOTING_LOAD:
return ("NaN or not 6 elements found in 'platformotherload' for "
"'shooting'.");
case ErrorCode::SETTING_FILE_NO_RELAXATION_PARA:
return "Unable to find 'relaxation' parameter definition.";
case ErrorCode::SETTING_FILE_INCOMPLETE_RELAXATION:
return ("Incomplete parameters for 'relaxation'. Required are "
"'platformvelocitytolerance', 'cablevelocitytolerance', "
"'stoptime', 'timestep', 'platformmass', "
"'platformdamping', 'platformhydrostaticstiffness' and "
"'platformotherload'.");
case ErrorCode::SETTING_FILE_NAN_RELAXATION_PARA:
return ("NaN found in 'relaxation' parameters: "
"'platformvelocitytolerance', 'cablevelocitytolerance'"
"'stoptime', or 'timestep'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_MASS:
return ("NaN or not 36 elements found in "
"'platformmass' for 'relaxtion'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_DAMPING:
return ("NaN or not 36 elements found in "
"'platformdamping' for 'relaxtion'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_STIFFNESS:
return ("NaN or not 36 elements found in "
"'platformhydrostaticstiffness' for 'relaxtion'.");
case ErrorCode::SETTING_FILE_BAD_RELAXATION_LOAD:
return ("NaN or not 6 elements found in 'platformotherload' for "
"'relaxtion'.");
case ErrorCode::SETTING_FILE_NO_MOTION:
return "Unable to find 'forcedmotion' node in Setting.xml.";
case ErrorCode::SETTING_FILE_NO_TIME_HISTORY:
return "Unable to find 'timehistory' file definition.";
// Validation of mooring input data.
case ErrorCode::MOORING_INVALID_CONSTANT:
return "Found nonpositive constants.";
case ErrorCode::MOORING_INVALID_CABLE_CURRENT_INDEX:
return "Cable 'icurrent' is out of range.";
case ErrorCode::MOORING_INVALID_CABLE_SOLVER_INDEX:
return "Cable 'isolver' is out of range.";
case ErrorCode::MOORING_INVALID_CABLE_NODE_NUM:
return "Cable 'nodenumber' is negative.";
case ErrorCode::MOORING_INVALID_CABLE_PROP_ASSOCIATION:
return ("Failed to find at least one group of cable length and "
"associated property or found inconsistent cable segments "
"and properties definitions.");
case ErrorCode::MOORING_INVALID_CABLE_CONNECTION_INDEX:
return ("Two same ends found for a cable or cable connection index "
"out of range. In addtion, currently, the first connection "
"must be an 'anchor' and the second must be a 'fairlead'.");
case ErrorCode::MOORING_INVALID_CABLE_SEGMENT_LENGTH:
return "Cable segmentlength should be positive.";
case ErrorCode::MOORING_INVALID_STRUCT_PROP:
return ("Positive values required for diameter, unitlengthmass, "
" unitlengthweight, and axialstiffness.");
case ErrorCode::MOORING_INVALID_HYDRO_COEFFICIENT:
return ("Nonnegative values required for bending stiffness, "
"torsional stiffness and damping coefficient.");
case ErrorCode::MOORING_INVALID_SEABED:
return ("Nonnegative values required hydrodynamic coefficients.");
case ErrorCode::MOORING_INVALID_CURRENT:
return ("Invalid current data. Required are that polyorder is "
"nonnegative and less then the number of profile data "
"points and at least one data point provided. In addition, "
"the Z coordinate should be negative and decreasing "
"monotonically");
case ErrorCode::MOORING_INVALID_SOLVER:
return ("Invalid solver found: iterationnumberlimit, "
"convergencetolerance, "
"initialrelaxationfactor, relaxationincreasefactor, "
"and relaxationdecreasefactor should be positive numbers; "
"relaxationincreasefactor and relaxationincreasefactor "
"should be no less than 1; lambdainfinity should not be equal "
"to 1 and often between -1 and 0.");
case ErrorCode::MOORING_INVALID_CABLE_STATE:
return ("Initial cable state matrix read successfully, however, "
"the cable coordinate is not valid. The cable coordinate "
"should be positive, begining with zero, increasing "
"monotonically and terminating with full cable length "
"consistent with the sum of segmentlength and at "
"least two nodes are required. Check the first column of "
"initial state file and the 'segmentlength'.");
case ErrorCode::SHOOTING_BAD_PARA:
return ("Found nonpositive tolerance or relaxation factor or "
"negative iteration limit in shooting control.");
case ErrorCode::RELAXATION_BAD_PARA:
return ("Found nonpositive tolerance, steptime, or timestep.");
case ErrorCode::CURRENT_FILE_NONEXISTENT:
return "Unable to find current profile data file.";
case ErrorCode::CURRENT_FILE_BAD_DATA:
return ("Found NaN or wrong column number (expect 6) of current "
"profile data.");
case ErrorCode::MOTION_FILE_NONEXISTENT:
return "Unable to find forcedmotion time history data.";
case ErrorCode::MOTION_FILE_BAD_DATA:
return ("Found NaN or wrong column number (expect 7) of forced "
"motion time history.");
case ErrorCode::FORCED_MOTION_BAD_TIME:
return "Found negative or decreasing time in the forced velocity.";
case ErrorCode::TIME_STEP_TOO_SMALL:
return "Time step too small, no need to update.";
case ErrorCode::SINGULAR_MATRIX_SOLVER:
return ("Singularity found in solving the cable equation. "
"Check input.");
case ErrorCode::NAN_CABLE_SOLUTION:
return ("NaN found in cable state solution.");
}
}
} // End of namespace moor.
| 45.8
| 83
| 0.623078
|
CHEN-Lin
|