hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5dce0207b6d99ec0a88c88a57160b5a0ecc20997
4,507
cpp
C++
source/predictdepth.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
4
2020-03-04T10:41:26.000Z
2021-04-15T06:29:41.000Z
source/predictdepth.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
2
2019-01-14T15:58:47.000Z
2021-04-18T09:09:51.000Z
source/predictdepth.cpp
astolap/WaSP
2daa1963d1f3d3fb50d3b576d470f9af0f6ce463
[ "BSD-2-Clause" ]
4
2018-07-20T14:36:42.000Z
2021-06-28T13:03:57.000Z
/*BSD 2-Clause License * Copyright(c) 2019, Pekka Astola * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met : * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "predictdepth.hh" #include "warping.hh" #include "medianfilter.hh" #include "ppm.hh" #include "inpainting.hh" #include "merging.hh" #include <ctime> #include <vector> #include <cstdint> using std::int32_t; using std::uint32_t; using std::int16_t; using std::uint16_t; using std::int8_t; using std::uint8_t; void WaSP_predict_depth(view* SAI, view *LF) { /* forward warp depth */ if (SAI->n_depth_references > 0) { printf("Predicting normalized disparity for view %03d_%03d\n", SAI->c, SAI->r); uint16_t **warped_texture_views_0_N = new uint16_t*[SAI->n_depth_references](); uint16_t **warped_depth_views_0_N = new uint16_t*[SAI->n_depth_references](); float **DispTargs_0_N = new float*[SAI->n_depth_references](); init_warping_arrays( SAI->n_depth_references, warped_texture_views_0_N, warped_depth_views_0_N, DispTargs_0_N, SAI->nr, SAI->nc, SAI->ncomp); for (int32_t ij = 0; ij < SAI->n_depth_references; ij++) { view *ref_view = LF + SAI->depth_references[ij]; int32_t tmp_w, tmp_r, tmp_ncomp; aux_read16PGMPPM( ref_view->path_out_pgm, tmp_w, tmp_r, tmp_ncomp, ref_view->depth); ref_view->color = new uint16_t[ref_view->nr*ref_view->nc * 3](); //aux_read16PGMPPM(ref_view->path_out_ppm, tmp_w, tmp_r, tmp_ncomp, // ref_view->color); warpView0_to_View1( ref_view, SAI, warped_texture_views_0_N[ij], warped_depth_views_0_N[ij], DispTargs_0_N[ij]); delete[](ref_view->depth); delete[](ref_view->color); ref_view->depth = nullptr; ref_view->color = nullptr; } /* merge depth using median*/ //int32_t startt = clock(); double *hole_mask = new double[SAI->nr*SAI->nc](); for (int32_t ij = 0; ij < SAI->nr * SAI->nc; ij++) { hole_mask[ij] = INIT_DISPARITY_VALUE; std::vector<uint16_t> depth_values; for (int32_t uu = 0; uu < SAI->n_depth_references; uu++) { uint16_t *pp = warped_depth_views_0_N[uu]; float *pf = DispTargs_0_N[uu]; if (*(pf + ij) > INIT_DISPARITY_VALUE) { depth_values.push_back(*(pp + ij)); } } if (depth_values.size() > 0) { SAI->depth[ij] = getMedian(depth_values); hole_mask[ij] = 1.0f; } } uint32_t nholes = holefilling( SAI->depth, SAI->nr, SAI->nc, INIT_DISPARITY_VALUE, hole_mask); delete[](hole_mask); clean_warping_arrays( SAI->n_depth_references, warped_texture_views_0_N, warped_depth_views_0_N, DispTargs_0_N); } }
31.739437
87
0.607278
astolap
5dce530424b87c168b126ff86d52f7deab82eb32
375
hpp
C++
src/texture.hpp
Honeybunch/raycaster
7fc70e1cae2a4959fec6e99a94ccf57f36420c88
[ "MIT" ]
null
null
null
src/texture.hpp
Honeybunch/raycaster
7fc70e1cae2a4959fec6e99a94ccf57f36420c88
[ "MIT" ]
null
null
null
src/texture.hpp
Honeybunch/raycaster
7fc70e1cae2a4959fec6e99a94ccf57f36420c88
[ "MIT" ]
null
null
null
#pragma once #include "texture_types.hpp" namespace raycaster { texture load_texture(const char *filepath); const uint8_t *texture_get_image(texture t); uint32_t texture_get_width(texture t); uint32_t texture_get_height(texture t); uint32_t texture_get_channels(texture t); uint32_t texture_get_size(texture t); void destroy_texture(texture t); } // namespace raycaster
22.058824
44
0.810667
Honeybunch
5dd761884638a68e07ba43e0773063c7e933c7ec
1,969
cc
C++
gui/load_relief_frame.cc
soukouki/simutrans
758283664349afb5527db470780767abb4db8114
[ "Artistic-1.0" ]
23
2017-03-11T16:44:14.000Z
2022-02-10T13:31:03.000Z
gui/load_relief_frame.cc
soukouki/simutrans
758283664349afb5527db470780767abb4db8114
[ "Artistic-1.0" ]
32
2018-01-31T11:11:16.000Z
2022-03-03T14:37:58.000Z
gui/load_relief_frame.cc
soukouki/simutrans
758283664349afb5527db470780767abb4db8114
[ "Artistic-1.0" ]
17
2017-08-02T15:59:25.000Z
2022-02-10T13:31:06.000Z
/* * This file is part of the Simutrans project under the Artistic License. * (see LICENSE.txt) */ #include <string> #include <stdio.h> #include "../simworld.h" #include "load_relief_frame.h" #include "welt.h" #include "simwin.h" #include "../dataobj/translator.h" #include "../dataobj/settings.h" #include "../dataobj/environment.h" #include "../dataobj/height_map_loader.h" /** * Action, started on button pressing */ bool load_relief_frame_t::item_action(const char *fullpath) { sets->heightfield = fullpath; if (gui_frame_t *new_world_gui = win_get_magic( magic_welt_gui_t )) { static_cast<welt_gui_t*>(new_world_gui)->update_preview(true); } return false; } load_relief_frame_t::load_relief_frame_t(settings_t* const sets) : savegame_frame_t( NULL, false, "maps/", env_t::show_delete_buttons ) { new_format.init( button_t::square_automatic, "Maximize height levels"); new_format.pressed = env_t::new_height_map_conversion; bottom_left_frame.add_component( &new_format ); const std::string extra_path = env_t::program_dir + env_t::objfilename + "maps/"; this->add_path(extra_path.c_str()); set_name(translator::translate("Lade Relief")); this->sets = sets; sets->heightfield = ""; } const char *load_relief_frame_t::get_info(const char *fullpath) { static char size[64]; sint16 w, h; sint8 *h_field ; height_map_loader_t hml(new_format.pressed); if(hml.get_height_data_from_file(fullpath, (sint8)sets->get_groundwater(), h_field, w, h, true )) { sprintf( size, "%i x %i", w, h ); env_t::new_height_map_conversion = new_format.pressed; return size; } return ""; } bool load_relief_frame_t::check_file( const char *fullpath, const char * ) { sint16 w, h; sint8 *h_field; height_map_loader_t hml(new_format.pressed); if(hml.get_height_data_from_file(fullpath, (sint8)sets->get_groundwater(), h_field, w, h, true )) { return w>0 && h>0; env_t::new_height_map_conversion = new_format.pressed; } return false; }
25.907895
135
0.731336
soukouki
5de0866d172736958bd7f785d6d2b2f265c6201b
495
hpp
C++
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
vapaee/vapaee.io-source
b2b0c07850a817629055a848b9239a59dc10b545
[ "MIT" ]
7
2019-06-09T03:52:14.000Z
2020-03-01T13:27:24.000Z
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
vapaee/vapaee.io-source
b2b0c07850a817629055a848b9239a59dc10b545
[ "MIT" ]
27
2019-12-28T12:29:12.000Z
2022-03-02T04:08:55.000Z
contracts/vapaeetokens/vapaeetokens.dispatcher.hpp
vapaee/vapaee.io-source
b2b0c07850a817629055a848b9239a59dc10b545
[ "MIT" ]
2
2019-11-29T22:32:47.000Z
2021-02-18T23:47:47.000Z
#define HANDLER void #define EOSIO_DISPATCH_VAPAEE( TYPE, MEMBERS, HANDLERS ) \ extern "C" { \ void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \ if( code == receiver ) { \ switch( action ) { \ EOSIO_DISPATCH_HELPER( TYPE, MEMBERS ) \ } \ } \ name handler = eosio::name(string("h") + eosio::name(action).to_string()); \ switch( handler.value ) { \ EOSIO_DISPATCH_HELPER( TYPE, HANDLERS ) \ } \ } \ } \
30.9375
82
0.567677
vapaee
5de18f2b8e19e5f3e560b6afae3f6c584c0624e2
1,697
cpp
C++
ext/include/osgEarth/TextureCompositor.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
6
2015-09-26T15:33:41.000Z
2021-06-13T13:21:50.000Z
ext/include/osgEarth/TextureCompositor.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
null
null
null
ext/include/osgEarth/TextureCompositor.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
5
2015-05-04T09:02:23.000Z
2019-06-17T11:34:12.000Z
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 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/> */ #include <osgEarth/TextureCompositor> #include <osgEarth/Registry> #include <osgEarth/Capabilities> using namespace osgEarth; #define LC "[TextureCompositor] " TextureCompositor::TextureCompositor() { //nop } bool TextureCompositor::reserveTextureImageUnit(int& out_unit) { out_unit = -1; unsigned maxUnits = osgEarth::Registry::instance()->getCapabilities().getMaxGPUTextureUnits(); Threading::ScopedMutexLock exclusiveLock( _reservedUnitsMutex ); for( unsigned i=0; i<maxUnits; ++i ) { if (_reservedUnits.find(i) == _reservedUnits.end()) { _reservedUnits.insert( i ); out_unit = i; return true; } } return false; } void TextureCompositor::releaseTextureImageUnit(int unit) { Threading::ScopedMutexLock exclusiveLock( _reservedUnitsMutex ); _reservedUnits.erase( unit ); }
28.762712
98
0.709487
energonQuest
5de81bd593ea23d921b914f76e6e658d904aa090
475
cpp
C++
alerts/zlipWrapper/private/CCRC.cpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
alerts/zlipWrapper/private/CCRC.cpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
alerts/zlipWrapper/private/CCRC.cpp
ymuv/CameraAlerts
7b2d794e38aff98bc2c5e7fafb9dec1a1bef3fe4
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <QByteArray> #include <zlib.h> #include "alerts/zlipWrapper/CCRC.hpp" template <class T> unsigned long CCRC::calc(const T& data, int offset, int endOffset) { unsigned long crc = crc32(0L, Z_NULL, 0); crc = crc32(crc, reinterpret_cast<const unsigned char *>( data.data() + offset), data.size()- offset - endOffset); return crc; } template unsigned long CCRC::calc( const QByteArray&, int, int);
23.75
79
0.644211
ymuv
5de87638ebd72dc517076c2a159d070c8504250a
2,972
cpp
C++
fboss/agent/packet/test/ICMPHdrTest.cpp
vitaliy-senchyshyn/fboss
6cb64342bfba08a668848e2b105689ff11887aa1
[ "BSD-3-Clause" ]
2
2018-02-28T06:57:08.000Z
2018-02-28T06:57:37.000Z
fboss/agent/packet/test/ICMPHdrTest.cpp
vitaliy-senchyshyn/fboss
6cb64342bfba08a668848e2b105689ff11887aa1
[ "BSD-3-Clause" ]
2
2018-10-06T18:29:44.000Z
2018-10-07T16:46:04.000Z
fboss/agent/packet/test/ICMPHdrTest.cpp
vitaliy-senchyshyn/fboss
6cb64342bfba08a668848e2b105689ff11887aa1
[ "BSD-3-Clause" ]
1
2019-10-14T05:28:17.000Z
2019-10-14T05:28:17.000Z
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/packet/ICMPHdr.h" /* * References: * https://code.google.com/p/googletest/wiki/Primer * https://code.google.com/p/googletest/wiki/AdvancedGuide */ #include <gtest/gtest.h> #include <folly/IPAddress.h> #include <folly/IPAddressV6.h> #include <folly/io/Cursor.h> #include "fboss/agent/hw/mock/MockRxPacket.h" using namespace facebook::fboss; using folly::IPAddress; using folly::IPAddressV6; using folly::io::Cursor; using std::string; TEST(ICMPHdrTest, default_constructor) { ICMPHdr icmpv6Hdr; EXPECT_EQ(0, icmpv6Hdr.type); EXPECT_EQ(0, icmpv6Hdr.code); EXPECT_EQ(0, icmpv6Hdr.csum); } TEST(ICMPHdrTest, copy_constructor) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); ICMPHdr rhs(lhs); EXPECT_EQ(lhs, rhs); } TEST(ICMPHdrTest, parameterized_data_constructor) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); EXPECT_EQ(type, lhs.type); EXPECT_EQ(code, lhs.code); EXPECT_EQ(csum, lhs.csum); } TEST(ICMPHdrTest, cursor_data_constructor) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong auto pkt = MockRxPacket::fromHex( // ICMPv6 Header "80" // Type: Echo Request "00" // Code: 0 "00 00" // Checksum ); Cursor cursor(pkt->buf()); ICMPHdr icmpv6Hdr(cursor); EXPECT_EQ(type, icmpv6Hdr.type); EXPECT_EQ(code, icmpv6Hdr.code); EXPECT_EQ(csum, icmpv6Hdr.csum); } TEST(ICMPHdrTest, cursor_data_constructor_too_small) { auto pkt = MockRxPacket::fromHex( // ICMPv6 Header "80" // Type: Echo Request "00" // Code: 0 "00 " // OOPS! One octet too small! ); Cursor cursor(pkt->buf()); EXPECT_THROW({ICMPHdr icmpv6Hdr(cursor);}, HdrParseError); } TEST(ICMPHdrTest, assignment_operator) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); ICMPHdr rhs = lhs; EXPECT_EQ(lhs, rhs); } TEST(ICMPHdrTest, equality_operator) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 02; uint16_t csum = 0; // Obviously wrong ICMPHdr lhs(type, code, csum); ICMPHdr rhs(type, code, csum); EXPECT_EQ(lhs, rhs); } TEST(ICMPHdrTest, inequality_operator) { ICMPv6Type type = ICMPV6_TYPE_ECHO_REQUEST; uint8_t code = 0; uint16_t csum1 = 0; // Obviously wrong uint16_t csum2 = 1; // Obviously wrong ICMPHdr lhs(type, code, csum1); ICMPHdr rhs(type, code, csum2); EXPECT_NE(lhs, rhs); }
26.535714
79
0.702557
vitaliy-senchyshyn
5de996fa4d288cf20fa94093dc1352dea15f8d33
7,167
cpp
C++
tests/vu/test_runner.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
25
2015-04-07T23:13:49.000Z
2021-09-27T08:03:53.000Z
tests/vu/test_runner.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
42
2015-04-27T03:12:48.000Z
2018-05-08T13:53:39.000Z
tests/vu/test_runner.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
8
2015-04-26T06:29:01.000Z
2021-05-27T09:50:03.000Z
#include <assert.h> #include <common-ee.h> #include <string.h> #include <timer.h> #include "test_runner.h" static const bool DEBUG_TEST_RUNNER = false; static u32 vu_reg_pos = 0x100; // 16 integer regs, 32 float regs, 3 status regs. static u32 vu_reg_size = 16 * (16 + 32 + 3); static u8 *const vu0_reg_mem = vu0_mem + vu_reg_pos; static u8 *const vu1_reg_mem = vu1_mem + vu_reg_pos; // Helper to "sleep" the ee for a few ticks (less than a second.) // This is used to wait for the vu test to finish. // We don't use interlock in case it stalls. static void delay_ticks(int t) { u32 goal = cpu_ticks() + t; while (cpu_ticks() < goal) { continue; } } // Determine whether the specified vu is running or not. static bool vu_running(int vu) { // Must be 0 or 1. Change to 0 or (1 << 8). u32 mask = vu == 0 ? 1 : (1 << 8); u32 stat; asm volatile ( "cfc2 %0, $29" : "=r"(stat) ); return (stat & mask) != 0; } void TestRunner::Execute() { // Just to be sure. RunnerExit(); InitRegisters(); InitFlags(); if (vu_ == 1) { if (DEBUG_TEST_RUNNER) { printf("Calling vu0 code.\n"); } asm volatile ( // This writes to cmsar1 ($31). The program is simply at 0. "ctc2 $0, $31\n" ); } else { if (DEBUG_TEST_RUNNER) { printf("Calling vu0 code.\n"); } asm volatile ( // Actually call the microcode. "vcallms 0\n" ); } if (DEBUG_TEST_RUNNER) { printf("Waiting for vu to finish.\n"); } // Spin while waiting for the vu unit to finish. u32 max_ticks = cpu_ticks() + 100000; while (vu_running(vu_)) { if (cpu_ticks() > max_ticks) { printf("ERROR: Timed out waiting for vu code to finish.\n"); // TODO: Force stop? break; } delay_ticks(200); } if (DEBUG_TEST_RUNNER && !vu_running(vu_)) { printf("Finished with vu code.\n"); } } void TestRunner::RunnerExit() { using namespace VU; // The goal here is to store all the registers from the VU side. // This way we're not testing register transfer, we're testing VU interaction. // Issues with spilling may be more obvious this way. // First, integers. u32 pos = vu_reg_pos / 16; for (int i = 0; i < 16; ++i) { Wr(ISW(DEST_XYZW, Reg(VI00 + i), VI00, pos++)); } // Then floats. Wr(IADDIU(VI02, VI00, pos)); for (int i = 0; i < 32; ++i) { Wr(SQ(DEST_XYZW, Reg(VF00 + i), VI00, pos++)); } // Lastly, flags (now that we've saved integers.) Wr(FCGET(VI01)); Wr(ISW(DEST_XYZW, VI01, VI00, pos++)); Wr(FMOR(VI01, VI00)); Wr(ISW(DEST_XYZW, VI01, VI00, pos++)); Wr(FSOR(VI01, 0)); Wr(ISW(DEST_XYZW, VI01, VI00, pos++)); // And actually write an exit (just two NOPs, the first with an E bit.) SafeExit(); if (DEBUG_TEST_RUNNER) { printf("Emitted exit code.\n"); } } void TestRunner::InitRegisters() { // Clear the register state (which will be set by the code run in RunnerExit.) if (vu_ == 1) { memset(vu1_reg_mem, 0xCC, vu_reg_size); } else { memset(vu0_reg_mem, 0xCC, vu_reg_size); } } void TestRunner::InitFlags() { // Grab the previous values. asm volatile ( // Try to clear them first, if possible. "vnop\n" "ctc2 $0, $16\n" "ctc2 $0, $17\n" "ctc2 $0, $18\n" // Then read. "vnop\n" "cfc2 %0, $16\n" "cfc2 %1, $17\n" "cfc2 %2, $18\n" : "=&r"(status_), "=&r"(mac_), "=&r"(clipping_) ); if (clipping_ != 0) { printf("WARNING: Clipping flag was not cleared.\n"); } } u16 TestRunner::GetValueAddress(const u32 *val) { u16 ptr = 0; if (vu_ == 0) { assert(val >= (u32 *)vu0_mem && val < (u32 *)(vu0_mem + vu0_mem_size)); ptr = ((u8 *)val - vu0_mem) / 16; } else { assert(val >= (u32 *)vu1_mem && val < (u32 *)(vu1_mem + vu1_mem_size)); ptr = ((u8 *)val - vu1_mem) / 16; } return ptr; } void TestRunner::WrLoadFloatRegister(VU::Dest dest, VU::Reg r, const u32 *val) { using namespace VU; assert(r >= VF00 && r <= VF31); u16 ptr = GetValueAddress(val); if ((ptr & 0x3FF) == ptr) { Wr(LQ(dest, r, VI00, ptr)); } else { // This shouldn't happen? Even with 16kb, all reads should be < 0x400. printf("Unhandled pointer load."); assert(false); } } void TestRunner::WrSetIntegerRegister(VU::Reg r, u32 v) { using namespace VU; assert(r >= VI00 && r <= VI15); assert((v & 0xFFFF) == v); // Except for 0x8000, we can get to everything with one op. if (v == 0x8000) { Wr(IADDI(r, VI00, -1)); Wr(ISUBIU(r, r, 0x7FFF)); } else if (v & 0x8000) { Wr(ISUBIU(r, VI00, v & ~0x8000)); } else { Wr(IADDIU(r, VI00, v)); } } void TestRunner::WrLoadIntegerRegister(VU::Dest dest, VU::Reg r, const u32 *val) { using namespace VU; assert(r >= VI00 && r <= VI15); u16 ptr = GetValueAddress(val); if ((ptr & 0x3FF) == ptr) { Wr(ILW(dest, r, VI00, ptr)); } else { // This shouldn't happen? Even with 16kb, all reads should be < 0x400. printf("Unhandled pointer load."); assert(false); } } void TestRunner::PrintRegister(VU::Reg r, bool newline) { using namespace VU; if (r >= VI00 && r <= VI15) { PrintIntegerRegister(r - VI00); } else { PrintVectorRegister(r); } if (newline) { printf("\n"); } } void TestRunner::PrintIntegerRegister(int i) { const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; // The integer registers are first, so it's just at the specified position. const u32 *p = (const u32 *)(regs + 16 * i); printf("%04x", *p); } union FloatBits { float f; u32 u; }; static inline void printFloatString(const FloatBits &bits) { // We want -0.0 and -NAN to show as negative. // So, let's just print the sign manually with an absolute value. FloatBits positive = bits; positive.u &= ~0x80000000; char sign = '+'; if (bits.u & 0x80000000) { sign = '-'; } printf("%c%0.2f", sign, positive.f); } static inline void printFloatBits(const FloatBits &bits) { printf("%08x/", bits.u); printFloatString(bits); } void TestRunner::PrintRegisterField(VU::Reg r, VU::Field field, bool newline) { using namespace VU; assert(r >= VF00 && r <= VF31); const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; const FloatBits *p = (const FloatBits *)(regs + 16 * (16 + r)); printFloatBits(p[field]); if (newline) { printf("\n"); } } void TestRunner::PrintVectorRegister(int i) { const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; // Skip the 16 integer registers, and jump to the vector. const FloatBits *p = (const FloatBits *)(regs + 16 * (16 + i)); // Let's just print each lane separated by a space. printFloatBits(p[0]); printf(" "); printFloatBits(p[1]); printf(" "); printFloatBits(p[2]); printf(" "); printFloatBits(p[3]); } void TestRunner::PrintStatus(bool newline) { const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem; // Skip 16 integer regs and 32 vector regs, to get a base for the status regs. const u32 *flags = (const u32 *)(regs + 16 * (16 + 32)); // Note that they are spaced out by 16 bytes (4 words.) u32 clipping = flags[0]; u32 mac = flags[4]; u32 status = flags[8]; if (status == status_ && mac == mac_ && clipping == clipping_) { printf(" (no flag changes)"); } else { printf(" st=+%04x,-%04x, mac=+%04x,-%04x, clip=%08x", status & ~status_, ~status & status_, mac & ~mac_, ~mac & mac_, clipping); } if (newline) { printf("\n"); } }
23.89
130
0.629273
unknownbrackets
5decf23567abe79738db2ccd0ab8f389a42e1458
1,600
hpp
C++
algorithms/kruskal.hpp
EMACC99/graph_visualizer
79291c2365c139d846b67698c2b983d22b670f6c
[ "MIT" ]
null
null
null
algorithms/kruskal.hpp
EMACC99/graph_visualizer
79291c2365c139d846b67698c2b983d22b670f6c
[ "MIT" ]
1
2021-03-16T20:13:58.000Z
2021-03-17T01:04:08.000Z
algorithms/kruskal.hpp
EMACC99/graph_visualizer
79291c2365c139d846b67698c2b983d22b670f6c
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <algorithm> #include "../includes/node.hpp" #include "../includes/edge.hpp" #include "../includes/globals.hpp" // int raiz(const int &u, const std::vector<int> &padres){ // if (padres[u] != -1) // return raiz(padres[u], padres); // return u; // } /** * @brief check the root of two nodes and meke them the sema as they are in the same conex component (disjoint sets) * * @param u * @param padres * @return int */ int raiz(const int &u, std::vector<int> & padres){ int p = padres[u]; if (p == -1) return u; else{ int r = raiz(p,padres); padres[u] = r; return r; } } /** * @brief join the roots of two given nodes * * @param u * @param v * @param padres */ void juntar(const int &u, const int &v, std::vector<int> &padres){ padres[raiz(u, padres)] = raiz(v, padres); } /** * @brief executes de mst kruskal * * @return std::vector<edge> */ std::vector<edge> kusrkal(){ std::vector<edge> arbol; std::vector<edge> kruskal_aristas = aristas; std::sort(kruskal_aristas.begin(), kruskal_aristas.end(), compare()); //las ordenamos por peso std::vector<int> padres (vertices.size()); for (auto &elem : padres) elem = -1; int u,v; for (int i = 0; i < kruskal_aristas.size(); ++i){ u = kruskal_aristas[i].nodes[0]; v = kruskal_aristas[i].nodes[1]; if (raiz(u,padres) != raiz(v, padres)){ arbol.push_back(kruskal_aristas[i]); juntar(u,v,padres); } } return arbol; }
24.242424
116
0.575
EMACC99
5df28db94f03945126a46fe651a3622346012c95
2,145
hpp
C++
engine/lib/math-funcs/include/noob/math/mat4.hpp
ColinGilbert/noobwerkz-engine
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
23
2015-03-02T10:56:40.000Z
2021-01-27T03:32:49.000Z
engine/lib/math-funcs/include/noob/math/mat4.hpp
ColinGilbert/noobwerkz-engine-borked
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
73
2015-04-14T09:39:05.000Z
2020-11-11T21:49:10.000Z
engine/lib/math-funcs/include/noob/math/mat4.hpp
ColinGilbert/noobwerkz-engine-borked
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
3
2016-02-22T01:29:32.000Z
2018-01-02T06:07:12.000Z
#pragma once #include <array> #include "vec4.hpp" namespace noob { /* stored like this: 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15 */ template <typename T> struct mat4_type { mat4_type() noexcept(true) = default; mat4_type(T a, T b, T c, T d, T e, T f, T g, T h, T i, T j, T k, T l, T mm, T n, T o, T p) noexcept(true) { m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f; m[6] = g; m[7] = h; m[8] = i; m[9] = j; m[10] = k; m[11] = l; m[12] = mm; m[13] = n; m[14] = o; m[15] = p; } mat4_type(const std::array<T,16>& mm) noexcept(true) { for (uint32_t i = 0; i < 16; i++) { m[i] = mm[i]; } } T& operator[](uint32_t x) noexcept(true) { return m[x]; } const T& operator[](uint32_t x) const noexcept(true) { return m[x]; } vec4_type<T> operator*(const vec4_type<T>& rhs) const noexcept(true) { // 0x + 4y + 8z + 12w T x = m[0] * rhs.v[0] + m[4] * rhs.v[1] + m[8] * rhs.v[2] + m[12] * rhs.v[3]; // 1x + 5y + 9z + 13w T y = m[1] * rhs.v[0] + m[5] * rhs.v[1] + m[9] * rhs.v[2] + m[13] * rhs.v[3]; // 2x + 6y + 10z + 14w T z = m[2] * rhs.v[0] + m[6] * rhs.v[1] + m[10] * rhs.v[2] + m[14] * rhs.v[3]; // 3x + 7y + 11z + 15w T w = m[3] * rhs.v[0] + m[7] * rhs.v[1] + m[11] * rhs.v[2] + m[15] * rhs.v[3]; return vec4_type<T>(x, y, z, w); } mat4_type operator*(const mat4_type& rhs) const noexcept(true) { mat4_type r; std::fill_n(&r.m[0], 16, 0.0); uint32_t r_index = 0; for (uint32_t col = 0; col < 4; col++) { for (uint32_t row = 0; row < 4; row++) { T sum = 0.0f; for (uint32_t i = 0; i < 4; i++) { sum += rhs.m[i + col * 4] * m[row + i * 4]; } r.m[r_index] = sum; r_index++; } } return r; } mat4_type& operator=(const mat4_type& rhs) noexcept(true) { for (uint32_t i = 0; i < 16; i++) { m[i] = rhs.m[i]; } return *this; } std::array<T, 16> m; }; }
18.491379
108
0.435431
ColinGilbert
5df3bde3711d7e111f675f2b04d73527f8b74c8a
2,012
cpp
C++
Prim/PrimComToken_Enum.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
Prim/PrimComToken_Enum.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
2
2021-07-07T17:31:49.000Z
2021-07-16T11:40:38.000Z
Prim/PrimComToken_Enum.cpp
OuluLinux/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
#include <Prim/PrimIncludeAll.h> #ifndef NO_DATA TYPEINFO_SINGLE(PrimComToken_Enum, PrimComToken_String); #endif #ifndef NO_CODE // // Construct an aName token for a string value in theValue as part of aParser, using // someOptions for parsing, and aUsage as a description of the token. // PrimComToken_Enum::PrimComToken_Enum(PrimComParse& aParser, const PrimEnum& anEnum, int& theValue, const char* aName, const char* aUsage, const TokenOptions& someOptions) : Super(aParser, _buffer, aName, aUsage, someOptions), _enum(anEnum), _value(theValue), _default_value(0) {} // // Construct an aName token for a string value defaulting to defaultValue in theValue // as part of aParser, using someOptions for parsing, and aUsage as a description of the token. // PrimComToken_Enum::PrimComToken_Enum(PrimComParse& aParser, const PrimEnum& anEnum, int& theValue, const char* aName, const char* aUsage, int defaultValue, const TokenOptions& someOptions) : Super(aParser, _buffer, aName, aUsage, *PrimStringHandle(anEnum[defaultValue]), someOptions), _enum(anEnum), _value(theValue), _default_value(defaultValue) {} // // The default destructor does nothing. // PrimComToken_Enum::~PrimComToken_Enum() {} // // Initialise for a new parsing pass. // void PrimComToken_Enum::initialise_parse(PrimComParse& aParser) { _value = _default_value; Super::initialise_parse(aParser); } // // Attempt to parse someText, returning true if accepted. // const char* PrimComToken_Enum::parse_text(PrimComParse& aParser, const char* someText) { const char* p = Super::parse_text(aParser, someText); if (p == 0) // If bad text return 0; // parsing fails std::istrstream s((char*)_buffer.str()); size_t aValue = _enum[s]; if (!s && aParser.diagnose_warnings()) { PRIMWRN(BAD_PARSE, *this << " failed to resolve \"" << _buffer << "\""); return 0; } _value = aValue; return p; } #endif
28.338028
126
0.698807
UltimateScript
5df5298d3186ec5d2e696adea58960b14325d6cb
19,504
cpp
C++
src/mirrage/graphic/src/device_memory.cpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
14
2017-10-26T08:45:54.000Z
2021-04-06T11:44:17.000Z
src/mirrage/graphic/src/device_memory.cpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
17
2017-10-09T20:11:58.000Z
2018-11-08T22:05:14.000Z
src/mirrage/graphic/src/device_memory.cpp
lowkey42/mirrage
2527537989a548062d0bbca8370d063fc6b81a18
[ "MIT" ]
1
2018-09-26T23:10:06.000Z
2018-09-26T23:10:06.000Z
#include <mirrage/graphic/device_memory.hpp> #include <mirrage/utils/container_utils.hpp> #include <mirrage/utils/ranges.hpp> #include <gsl/gsl> #include <bitset> #include <cmath> #include <mutex> namespace mirrage::graphic { namespace { template <typename T> constexpr T log2(T n) { return (n < 2) ? 0 : 1 + log2(n / 2); } template <std::uint32_t MinSize, std::uint32_t MaxSize> class Buddy_block_alloc { public: Buddy_block_alloc(const vk::Device&, std::uint32_t type, bool mapable, std::mutex& free_mutex); Buddy_block_alloc(const Buddy_block_alloc&) = delete; Buddy_block_alloc(Buddy_block_alloc&&) = delete; Buddy_block_alloc& operator=(const Buddy_block_alloc&) = delete; Buddy_block_alloc& operator=(Buddy_block_alloc&&) = delete; ~Buddy_block_alloc() { if(_allocation_count > 0) { LOG(plog::error) << "Still " << _allocation_count << " unfreed GPU memory allocations left."; } } auto alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory>; void free(std::uint32_t index, std::uint32_t layer); auto free_memory() const -> std::uint32_t { auto free_memory = std::size_t(0); for(auto i = std::size_t(0); i < layers; i++) { auto free = _free_blocks[i].size(); free_memory = total_size / (1L << (i + 1)) * free; } return gsl::narrow<std::uint32_t>(free_memory); } auto empty() const noexcept { return !_free_blocks[0].empty(); } private: using Free_list = std::vector<std::uint32_t>; static constexpr auto layers = log2(MaxSize) - log2(MinSize) + 1; static constexpr auto total_size = (1 << layers) * MinSize; static constexpr auto blocks = (1 << layers) - 1; vk::UniqueDeviceMemory _memory; char* _mapped_addr; std::array<Free_list, layers> _free_blocks; std::bitset<blocks / 2> _free_buddies; std::int64_t _allocation_count = 0; std::mutex& _free_mutex; auto _index_to_offset(std::uint32_t layer, std::uint32_t idx) -> vk::DeviceSize; /// split given block, return index of one of the new blocks auto _split(std::uint32_t layer, std::uint32_t idx) -> std::uint32_t; /// tries to merge the given block with its buddy auto _merge(std::uint32_t layer, std::uint32_t idx) -> bool; auto _buddies_different(std::uint32_t layer, std::uint32_t idx) { auto abs_idx = (1L << layer) - 1 + idx; MIRRAGE_INVARIANT(abs_idx > 0, "_buddies_different() called for layer 0!"); return _free_buddies[gsl::narrow<std::size_t>((abs_idx - 1) / 2)]; } }; } // namespace template <std::uint32_t MinSize, std::uint32_t MaxSize> class Device_memory_pool { public: Device_memory_pool(const vk::Device&, std::uint32_t type, bool mapable); ~Device_memory_pool() = default; auto alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory>; auto shrink_to_fit() -> std::size_t { auto lock = std::scoped_lock{_mutex}; auto new_end = std::remove_if( _blocks.begin(), _blocks.end(), [](auto& block) { return block->empty(); }); auto deleted = std::distance(new_end, _blocks.end()); if(deleted > 0) { LOG(plog::debug) << "Freed " << deleted << "/" << _blocks.size() << " blocks in allocator for type " << _type; } _blocks.erase(new_end, _blocks.end()); return gsl::narrow<std::size_t>(deleted); } auto usage_statistic() const -> Device_memory_pool_usage { auto lock = std::scoped_lock{_mutex}; auto usage = Device_memory_pool_usage{0, 0, _blocks.size()}; for(auto& block : _blocks) { usage.reserved += MaxSize; usage.used += MaxSize - block->free_memory(); } return usage; } private: const vk::Device& _device; std::uint32_t _type; bool _mapable; mutable std::mutex _mutex; std::vector<std::unique_ptr<Buddy_block_alloc<MinSize, MaxSize>>> _blocks; }; class Device_heap { public: Device_heap(const vk::Device& device, std::uint32_t type, bool mapable) : _device(device) , _type(type) , _mapable(mapable) , _temporary_pool(device, type, mapable) , _normal_pool(device, type, mapable) , _persistent_pool(device, type, mapable) { } Device_heap(const Device_heap&) = delete; Device_heap(Device_heap&&) = delete; Device_heap& operator=(const Device_heap&) = delete; Device_heap& operator=(Device_heap&&) = delete; auto alloc(std::uint32_t size, std::uint32_t alignment, Memory_lifetime lifetime) -> util::maybe<Device_memory> { auto memory = [&] { switch(lifetime) { case Memory_lifetime::temporary: return _temporary_pool.alloc(size, alignment); case Memory_lifetime::normal: return _normal_pool.alloc(size, alignment); case Memory_lifetime::persistent: return _persistent_pool.alloc(size, alignment); } MIRRAGE_FAIL("Unreachable"); }(); if(memory.is_some()) return memory; // single allocation auto alloc_info = vk::MemoryAllocateInfo{size, _type}; auto m = _device.allocateMemoryUnique(alloc_info); auto mem_addr = _mapable ? static_cast<char*>(_device.mapMemory(*m, 0, VK_WHOLE_SIZE)) : nullptr; return Device_memory{this, +[](void* self, std::uint32_t, std::uint32_t, vk::DeviceMemory memory) { static_cast<Device_heap*>(self)->_device.freeMemory(memory); }, 0, size, m.release(), 0, mem_addr}; } auto shrink_to_fit() -> std::size_t { return _temporary_pool.shrink_to_fit() + _normal_pool.shrink_to_fit() + _persistent_pool.shrink_to_fit(); } auto usage_statistic() const -> Device_memory_type_usage { auto temporary_usage = _temporary_pool.usage_statistic(); auto normal_usage = _normal_pool.usage_statistic(); auto persistent_usage = _persistent_pool.usage_statistic(); return {temporary_usage.reserved + normal_usage.reserved + persistent_usage.reserved, temporary_usage.used + normal_usage.used + persistent_usage.used, temporary_usage, normal_usage, persistent_usage}; } private: friend class Device_memory_allocator; friend class Device_memory; const vk::Device& _device; std::uint32_t _type; bool _mapable; Device_memory_pool<1024L * 1024 * 4, 256L * 1024 * 1024> _temporary_pool; Device_memory_pool<1024L * 1024 * 1, 256L * 1024 * 1024> _normal_pool; Device_memory_pool<1024L * 1024 * 1, 256L * 1024 * 1024> _persistent_pool; }; Device_memory::Device_memory(Device_memory&& rhs) noexcept : _owner(rhs._owner) , _deleter(rhs._deleter) , _index(rhs._index) , _layer(rhs._layer) , _memory(std::move(rhs._memory)) , _offset(rhs._offset) , _mapped_addr(rhs._mapped_addr) { rhs._owner = nullptr; } Device_memory& Device_memory::operator=(Device_memory&& rhs) noexcept { if(&rhs == this) return *this; if(_owner) { _deleter(_owner, _index, _layer, _memory); } _owner = rhs._owner; _deleter = rhs._deleter; _index = rhs._index; _layer = rhs._layer; _memory = rhs._memory; _offset = rhs._offset; _mapped_addr = rhs._mapped_addr; rhs._owner = nullptr; return *this; } Device_memory::~Device_memory() { if(_owner) { _deleter(_owner, _index, _layer, _memory); } } Device_memory::Device_memory(void* owner, Deleter* deleter, std::uint32_t index, std::uint32_t layer, vk::DeviceMemory m, vk::DeviceSize o, char* mapped_addr) : _owner(owner) , _deleter(deleter) , _index(index) , _layer(layer) , _memory(m) , _offset(o) , _mapped_addr(mapped_addr) { } Device_memory_allocator::Device_memory_allocator(const vk::Device& device, vk::PhysicalDevice gpu, bool dedicated_alloc_supported) : _device(device) , _is_unified_memory_architecture(true) , _is_dedicated_allocations_supported(dedicated_alloc_supported) { auto memory_properties = gpu.getMemoryProperties(); const auto host_visible_flags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent; const auto device_local_flags = vk::MemoryPropertyFlagBits::eDeviceLocal; _pools.reserve(memory_properties.memoryTypeCount); for(auto id : util::range(memory_properties.memoryTypeCount)) { auto host_visible = (memory_properties.memoryTypes[id].propertyFlags & host_visible_flags) == host_visible_flags; _pools.emplace_back(std::make_unique<Device_heap>(_device, id, host_visible)); } for(auto i : util::range(memory_properties.memoryTypeCount)) { auto host_visible = (memory_properties.memoryTypes[i].propertyFlags & host_visible_flags) == host_visible_flags; auto device_local = (memory_properties.memoryTypes[i].propertyFlags & device_local_flags) == device_local_flags; if(host_visible) { _host_visible_pools.emplace_back(i); } if(device_local) { _device_local_pools.emplace_back(i); } if(host_visible || device_local) { _is_unified_memory_architecture &= host_visible && device_local; } } if(_is_unified_memory_architecture) { LOG(plog::info) << "Detected a unified memory architecture."; } if(_is_dedicated_allocations_supported) { LOG(plog::info) << "VK_NV_dedicated_allocation enabled"; } } Device_memory_allocator::~Device_memory_allocator() = default; auto Device_memory_allocator::alloc(std::uint32_t size, std::uint32_t alignment, std::uint32_t type_mask, bool host_visible, Memory_lifetime lifetime) -> util::maybe<Device_memory> { const auto& pool_ids = host_visible ? _host_visible_pools : _device_local_pools; for(auto id : pool_ids) { if(type_mask & (1u << id)) { auto& pool = _pools[id]; try { return pool->alloc(size, alignment, lifetime); } catch(std::system_error& e) { auto usage = usage_statistic(); LOG(plog::error) << "Couldn't allocate block of size " << size << "\n Usage: " << usage.used << "/" << usage.reserved; // free memory and retry if(e.code() == vk::Result::eErrorOutOfDeviceMemory && shrink_to_fit() > 0) { return pool->alloc(size, alignment, lifetime); } } } } MIRRAGE_FAIL("No pool on the device matches the requirements. Type mask=" << type_mask << ", host visible=" << host_visible); } auto Device_memory_allocator::alloc_dedicated(vk::Image image, bool host_visible) -> util::maybe<Device_memory> { return alloc_dedicated({}, image, host_visible); } auto Device_memory_allocator::alloc_dedicated(vk::Buffer buffer, bool host_visible) -> util::maybe<Device_memory> { return alloc_dedicated(buffer, {}, host_visible); } auto Device_memory_allocator::alloc_dedicated(vk::Buffer buffer, vk::Image image, bool host_visible) -> util::maybe<Device_memory> { const auto& pool_ids = host_visible ? _host_visible_pools : _device_local_pools; auto requirements = buffer ? _device.getBufferMemoryRequirements(buffer) : _device.getImageMemoryRequirements(image); for(auto id : pool_ids) { if(requirements.memoryTypeBits & (1u << id)) { auto alloc_info = vk::MemoryAllocateInfo{requirements.size, id}; #ifdef VK_NV_dedicated_allocation auto dedicated_info = vk::DedicatedAllocationMemoryAllocateInfoNV{}; if(_is_dedicated_allocations_supported) { dedicated_info.buffer = buffer; dedicated_info.image = image; alloc_info.pNext = &dedicated_info; } #endif LOG(plog::debug) << "Alloc: " << (float(requirements.size) / 1024.f / 1024.f) << " MB"; auto mem = _device.allocateMemoryUnique(alloc_info); auto mem_addr = host_visible ? static_cast<char*>(_device.mapMemory(*mem, 0, VK_WHOLE_SIZE)) : nullptr; return Device_memory{ this, +[](void* self, std::uint32_t, std::uint32_t, vk::DeviceMemory memory) { static_cast<Device_memory_allocator*>(self)->_device.freeMemory(memory); }, 0, 0, mem.release(), 0, mem_addr}; } } MIRRAGE_FAIL("No pool on the device matches the requirements. Type mask=" << requirements.memoryTypeBits << ", host visible=" << host_visible); } auto Device_memory_allocator::shrink_to_fit() -> std::size_t { auto sum = std::size_t(0); for(auto& heap : _pools) { if(heap) { sum += heap->shrink_to_fit(); } } return sum; } auto Device_memory_allocator::usage_statistic() const -> Device_memory_usage { auto types = std::unordered_map<std::uint32_t, Device_memory_type_usage>(); auto reserved = std::size_t(0); auto used = std::size_t(0); auto type = std::uint32_t(0); for(auto& heap : _pools) { if(heap) { auto& t_usage = types[0]; t_usage = heap->usage_statistic(); reserved += t_usage.reserved; used += t_usage.used; } type++; } return {reserved, used, types}; } // POOL template <std::uint32_t MinSize, std::uint32_t MaxSize> Device_memory_pool<MinSize, MaxSize>::Device_memory_pool(const vk::Device& device, std::uint32_t type, bool mapable) : _device(device), _type(type), _mapable(mapable) { } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Device_memory_pool<MinSize, MaxSize>::alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory> { if(size > MaxSize) return util::nothing; auto lock = std::scoped_lock{_mutex}; for(auto& block : _blocks) { auto m = block->alloc(size, alignment); if(m.is_some()) return m; } _blocks.emplace_back( std::make_unique<Buddy_block_alloc<MinSize, MaxSize>>(_device, _type, _mapable, _mutex)); auto m = _blocks.back()->alloc(size, alignment); MIRRAGE_INVARIANT(m.is_some(), "Couldn't allocate " << size << " byte with allignment" << alignment << " from newly created block of size " << MaxSize); return m; } namespace { template <std::uint32_t MinSize, std::uint32_t MaxSize> Buddy_block_alloc<MinSize, MaxSize>::Buddy_block_alloc(const vk::Device& device, std::uint32_t type, bool mapable, std::mutex& free_mutex) : _memory(device.allocateMemoryUnique({MaxSize, type})) , _mapped_addr(mapable ? static_cast<char*>(device.mapMemory(*_memory, 0, VK_WHOLE_SIZE)) : nullptr) , _free_mutex(free_mutex) { LOG(plog::debug) << "Alloc: " << (MaxSize / 1024.f / 1024.f) << " MB"; _free_blocks[0].emplace_back(0); } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::alloc(std::uint32_t size, std::uint32_t alignment) -> util::maybe<Device_memory> { // protected by the mutex locked in Device_memory_pool::alloc, that is the same as _free_mutex if(size < alignment) { size = alignment; } else if(size % alignment != 0) { size += alignment - size % alignment; } if(size < MinSize) { size = MinSize; } auto layer = gsl::narrow<std::uint32_t>(std::ceil(std::log2(static_cast<float>(size))) - log2(MinSize)); layer = layer < layers ? layers - layer - 1 : 0; // find first layer with free block >= size auto current_layer = layer; while(_free_blocks[current_layer].empty()) { if(current_layer == 0) { return util::nothing; //< not enough free space } current_layer--; } // reserve found block auto index = _free_blocks[current_layer].back(); _free_blocks[current_layer].pop_back(); if(current_layer > 0) { _buddies_different(current_layer, index).flip(); } // unwinde and split all blocks an the way down for(; current_layer <= layer; current_layer++) { if(current_layer != layer) index = _split(current_layer, index); } auto offset = _index_to_offset(layer, index); MIRRAGE_INVARIANT(offset % alignment == 0, "Resulting offset is not aligned correctly. Expected:" << alignment << " Offset: " << offset); _allocation_count++; return Device_memory{this, +[](void* self, std::uint32_t i, std::uint32_t l, vk::DeviceMemory) { static_cast<Buddy_block_alloc*>(self)->free(l, i); }, index, layer, *_memory, offset, _mapped_addr ? _mapped_addr + offset : nullptr}; } template <std::uint32_t MinSize, std::uint32_t MaxSize> void Buddy_block_alloc<MinSize, MaxSize>::free(std::uint32_t layer, std::uint32_t index) { auto lock = std::scoped_lock{_free_mutex}; _allocation_count--; _free_blocks[layer].emplace_back(index); if(layer == 0) { MIRRAGE_INVARIANT(index == 0, "index overflow in layer 0, index=" << index); } else { _buddies_different(layer, index).flip(); _merge(layer, index); } } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::_index_to_offset(std::uint32_t layer, std::uint32_t idx) -> vk::DeviceSize { return total_size / (1L << (layer + 1)) * idx; } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::_split(std::uint32_t layer, std::uint32_t idx) -> std::uint32_t { _buddies_different(layer + 1, idx * 2 + 1) = true; _free_blocks[layer + 1].emplace_back(idx * 2 + 1); return idx * 2; } template <std::uint32_t MinSize, std::uint32_t MaxSize> auto Buddy_block_alloc<MinSize, MaxSize>::_merge(std::uint32_t layer, std::uint32_t index) -> bool { if(layer == 0) return false; auto diff = _buddies_different(layer, index); if(diff == false) { // both free // remove nodes from freelist and add parent auto parent_index = index / 2; util::erase_fast(_free_blocks[layer], parent_index * 2); util::erase_fast(_free_blocks[layer], parent_index * 2 + 1); _free_blocks[layer - 1].emplace_back(parent_index); if(layer > 1) { _buddies_different(layer - 1, parent_index).flip(); _merge(layer - 1, parent_index); } return true; } return false; } } // namespace } // namespace mirrage::graphic
31.559871
104
0.622488
lowkey42
5df53d6d97c8bc4307d93f202acfe67b94973e08
238
cpp
C++
src/PL_CSC.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
src/PL_CSC.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
src/PL_CSC.cpp
ddsmarques/pairtree
b04e590acf769269ebc38b76ba1f19d6344fef80
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2018 Daniel dos Santos Marques <[email protected]> // License: BSD 3 clause #include <iostream> #include "Trainer.h" int main(int argc, char** argv) { Trainer trainer; trainer.train(argv[1]); return 0; }
18.307692
75
0.697479
ddsmarques
5df6477f2ff543a723c0d79fdccef83c74875181
6,176
cc
C++
cores/Nibbler/RISC-V-ILA/app/main.cc
yuzeng2333/IMDb
84a3ae9ec4d0c9251e3dee572e9bc0240bddb660
[ "MIT" ]
null
null
null
cores/Nibbler/RISC-V-ILA/app/main.cc
yuzeng2333/IMDb
84a3ae9ec4d0c9251e3dee572e9bc0240bddb660
[ "MIT" ]
null
null
null
cores/Nibbler/RISC-V-ILA/app/main.cc
yuzeng2333/IMDb
84a3ae9ec4d0c9251e3dee572e9bc0240bddb660
[ "MIT" ]
null
null
null
#include "riscvIla.hpp" #include <ilang/vtarget-out/vtarget_gen.h> using namespace ilang; /// the function to parse commandline arguments VerilogVerificationTargetGenerator::vtg_config_t SetConfiguration(); VerilogVerificationTargetGenerator::vtg_config_t HandleArguments(int argc, char **argv); void verifyNibblerInstCosa( Ila& model, VerilogVerificationTargetGenerator::vtg_config_t vtg_cfg, const std::vector<std::string> & design_files, const std::string & varmap, const std::string & instcont ) { VerilogGeneratorBase::VlgGenConfig vlg_cfg; vlg_cfg.pass_node_name = true; vtg_cfg.CosaAddKeep = false; vtg_cfg.MemAbsReadAbstraction = true; vtg_cfg.target_select = vtg_cfg.INST; //vtg_cfg.ForceInstCheckReset = true; std::string RootPath = ".."; std::string VerilogPath = RootPath + "/verilog/"; std::string IncludePath = VerilogPath + "include/"; std::string RefrelPath = RootPath + "/refinement/"; std::string OutputPath = RootPath + "/verification/"; std::vector<std::string> path_to_design_files; // update path for(auto && f : design_files) path_to_design_files.push_back( VerilogPath + f ); VerilogVerificationTargetGenerator vg( {IncludePath}, // no include path_to_design_files, // designs "param_riscv_Core", // top_module_name RefrelPath + varmap, // variable mapping RefrelPath + instcont, // conditions of start/ready OutputPath, // output path model.get(), // model VerilogVerificationTargetGenerator::backend_selector::COSA, // backend: COSA vtg_cfg, // target generator configuration vlg_cfg); // verilog generator configuration vg.GenerateTargets(); } void verifyNibblerInvPdr( Ila& model, VerilogVerificationTargetGenerator::vtg_config_t vtg_cfg, const std::vector<std::string> & design_files, const std::string & varmap, const std::string & instcont ) { VerilogGeneratorBase::VlgGenConfig vlg_cfg; vlg_cfg.pass_node_name = true; vtg_cfg.CosaAddKeep = false; vtg_cfg.MemAbsReadAbstraction = true; vtg_cfg.target_select = vtg_cfg.INV; vtg_cfg.InvariantSynthesisKeepMemory = false; vtg_cfg.InvariantCheckKeepMemory = false; vtg_cfg.YosysSmtFlattenHierarchy = true; vtg_cfg.AbcPath = "~/abc/"; vtg_cfg.YosysPropertyCheckShowProof = true; // vtg_cfg.YosysSmtStateSort = vtg_cfg.BitVec; // vtg_cfg.ForceInstCheckReset = true; std::string RootPath = ".."; std::string VerilogPath = RootPath + "/verilog/"; std::string IncludePath = VerilogPath + "include/"; std::string RefrelPath = RootPath + "/refinement/"; std::string OutputPath = RootPath + "/verification/"; std::vector<std::string> path_to_design_files; // update path for(auto && f : design_files) path_to_design_files.push_back( VerilogPath + f ); VerilogVerificationTargetGenerator vg( {IncludePath}, // no include path_to_design_files, // designs "param_riscv_Core", // top_module_name RefrelPath + varmap, // variable mapping RefrelPath + instcont, // conditions of start/ready OutputPath, // output path model.get(), // model VerilogVerificationTargetGenerator::backend_selector::ABCPDR, // backend: Z3PDR, COSA vtg_cfg, // target generator configuration vlg_cfg); // verilog generator configuration vg.GenerateTargets(); } int main(int argc, char **argv) { // TODO std::vector<std::string> design_files = { "param-Ctrl.v", "param-ShiftDemux.v", "param-CoreDpathRegfile.v", "param-CoreDpathAlu.v", "param-SIMDLaneDpath.v", "param-ClkEnBuf.v", "param-DeserializedReg.v", "param-PCComputation.v", "param-Dpath.v", "param-Core.v" }; auto vtg_cfg = SetConfiguration(); //auto vtg_cfg = HandleArguments(argc, argv); // build the model riscvILA_user nibbler; nibbler.addInstructions(); // 37 base integer instructions verifyNibblerInstCosa(nibbler.model, vtg_cfg, design_files, "varmap-nibbler.json", "instcond-nibbler.json"); verifyNibblerInvPdr(nibbler.model, vtg_cfg, design_files, "varmap-nibbler.json", "instcond-nibbler.json"); // riscvILA_user riscvILA(0); return 0; } VerilogVerificationTargetGenerator::vtg_config_t HandleArguments(int argc, char **argv) { // the solver, the cosa environment // you can use a commandline parser if desired, but since it is not the main focus of // this demo, we skip it // set ilang option, operators like '<' will refer to unsigned arithmetics SetUnsignedComparison(true); VerilogVerificationTargetGenerator::vtg_config_t ret; for(unsigned p = 1; p<argc; p++) { std::string arg = argv[p]; auto split = arg.find("="); auto argName = arg.substr(0,split); auto param = arg.substr(split+1); if(argName == "Solver") ret.CosaSolver = param; else if(argName == "Env") ret.CosaPyEnvironment = param; else if(argName == "Cosa") ret.CosaPath = param; // else unknown else { std::cerr<<"Unknown argument:" << argName << std::endl; std::cerr<<"Expecting Solver/Env/Cosa=???" << std::endl; } } ret.CosaGenTraceVcd = true; /// other configurations ret.PortDeclStyle = VlgVerifTgtGenBase::vtg_config_t::NEW; ret.CosaGenJgTesterScript = true; //ret.CosaOtherSolverOptions = "--blackbox-array"; //ret.ForceInstCheckReset = true; return ret; } VerilogVerificationTargetGenerator::vtg_config_t SetConfiguration() { // set ilang option, operators like '<' will refer to unsigned arithmetics SetUnsignedComparison(true); VerilogVerificationTargetGenerator::vtg_config_t ret; ret.CosaSolver = "btor"; ret.CosaPyEnvironment = "/ibuild/ilang-env/bin/activate"; ret.CosaGenTraceVcd = true; /// other configurations ret.PortDeclStyle = VlgVerifTgtGenBase::vtg_config_t::NEW; ret.CosaGenJgTesterScript = true; //ret.CosaOtherSolverOptions = "--blackbox-array"; //ret.ForceInstCheckReset = true; return ret; }
32.505263
110
0.686528
yuzeng2333
5df8c24ffd67744dd690811b123ba5f5648fd10a
3,148
cpp
C++
src/Buffers/test_CPUBuffer.cpp
abcucberkeley/cudaDecon
d21ae81f47701bdd68ba155ccf2be97cf6bc3feb
[ "BSL-1.0" ]
13
2020-03-11T18:41:04.000Z
2022-03-10T09:46:47.000Z
src/Buffers/test_CPUBuffer.cpp
tlambert03/CUDA_SIMrecon
84f6828d2db850660088ec4d625735f98ab722d5
[ "MIT" ]
8
2019-12-16T15:38:14.000Z
2021-11-25T20:38:44.000Z
src/Buffers/test_CPUBuffer.cpp
tlambert03/CUDA_SIMrecon
84f6828d2db850660088ec4d625735f98ab722d5
[ "MIT" ]
11
2019-02-28T22:37:16.000Z
2021-07-12T15:05:54.000Z
#include "Buffer.h" #include "CPUBuffer.h" #include "GPUBuffer.h" #include "gtest/gtest.h" #include <cstdlib> int compareArrays(char* arr1, char* arr2, int size); TEST(CPUBuffer, IncludeTest) { ASSERT_EQ(0, 0); } TEST(CPUBuffer, ConstructorTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); CPUBuffer b(4 * sizeof(float)); ASSERT_EQ(4 * sizeof(float), b.getSize()); EXPECT_TRUE(0 != b.getPtr()); } TEST(CPUBuffer, ResizeTest) { CPUBuffer a; a.resize(10); ASSERT_EQ(10, a.getSize()); EXPECT_TRUE(0 != a.getPtr()); } TEST(CPUBuffer, SetFromPlainArrayTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); a.resize(4 * sizeof(float)); float src[4] = {11.0, 22.0, 33.0, 44.0}; float result[4] = {11.0, 22.0, 33.0, 44.0}; float out[4]; a.setFrom(src, 0, sizeof(src), 0); a.setPlainArray(out, 0, a.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); } TEST(CPUBuffer, SetTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); a.resize(4 * sizeof(float)); float src[4] = {11.0, 22.0, 33.0, 44.0}; float result[4] = {11.0, 22.0, 33.0, 44.0}; float out[4]; a.setFrom(src, 0, sizeof(src), 0); a.setPlainArray(out, 0, a.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); CPUBuffer b; b.resize(a.getSize()); a.set(&b, 0, 4 * sizeof(float), 0); b.setPlainArray(out, 0, b.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); } TEST(CPUBuffer, TakeOwnershipTest) { CPUBuffer a; float* src = new float[4]; src[0] = 11.0; src[1] = 22.0; src[2] = 33.0; src[3] = 44.0; float result[4] = {11.0, 22.0, 33.0, 44.0}; a.takeOwnership(src, 4 * sizeof(float)); ASSERT_EQ(0, compareArrays((char*)a.getPtr(), (char*)result, sizeof(result))); } TEST(CPUBuffer, Dump) { CPUBuffer a; float* src = new float[4]; src[0] = 11.0; src[1] = 22.0; src[2] = 33.0; src[3] = 44.0; a.takeOwnership(src, 4 * sizeof(float)); a.dump(std::cout, 2); ASSERT_EQ(0, 0); } TEST(CPUBuffer, GPUSetTest) { CPUBuffer a; ASSERT_EQ(0, a.getSize()); ASSERT_EQ(0, a.getPtr()); a.resize(4 * sizeof(float)); float src[4] = {11.0, 22.0, 33.0, 44.0}; float result[4] = {11.0, 22.0, 33.0, 44.0}; float out[4]; a.setFrom(src, 0, sizeof(src), 0); a.setPlainArray(out, 0, a.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); GPUBuffer b; b.resize(a.getSize()); a.set(&b, 0, 4 * sizeof(float), 0); CPUBuffer c; c.resize(b.getSize()); ASSERT_EQ(4 * sizeof(float), c.getSize()); b.set(&c, 0, 4 * sizeof(float), 0); c.setPlainArray(out, 0, c.getSize(), 0); ASSERT_EQ(0, compareArrays((char*)out, (char*)result, sizeof(result))); } int compareArrays(char* arr1, char* arr2, int size) { int difference = 0; for (int i = 0; i < size; ++i) { difference += abs(arr1[i] - arr2[i]); } return difference; }
27.137931
72
0.589263
abcucberkeley
5dfce1c18a3a44da16a8b3fb291b51abb45bce46
21,261
cpp
C++
source/file/brfile.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/file/brfile.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/file/brfile.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** File Class Copyright (c) 1995-2017 by Rebecca Ann Heineman <[email protected]> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brfile.h" #include "brfilemanager.h" #include "brendian.h" #include "brmemoryfunctions.h" #include <stdio.h> /*! ************************************ \class Burger::File \brief System file reference class A functional equivalent to FILE *, except files are all considered binary and pathnames are only Burgerlib format ***************************************/ /*! ************************************ \brief Create a Burger::File class Initialize variables, however no file is opened so all file access functions will fail until Open() is called and it succeeds \sa Open(const char *,eFileAccess), Open(Filename *,eFileAccess), Close(), ~File() ***************************************/ Burger::File::File() : m_pFile(NULL), m_uPosition(0), m_Filename(), m_Semaphore() { #if defined(BURGER_MAC) MemoryClear(m_FSRef,sizeof(m_FSRef)); #endif } /*! ************************************ \brief Create a Burger::File class with a file Open a file and initialize the variables. If the file open operation fails, all file access functions will fail until a new file is opened. \param pFileName Pointer to a "C" string containing a Burgerlib pathname \param eAccess Enumeration on permissions requested on the opened file \sa Open(const char *,eFileAccess), File(Filename *,eFileAccess), Close() ***************************************/ Burger::File::File(const char *pFileName,eFileAccess eAccess) : m_pFile(NULL), m_uPosition(0), m_Filename(pFileName), m_Semaphore() { #if defined(BURGER_MAC) MemoryClear(m_FSRef,sizeof(m_FSRef)); #endif Open(pFileName,eAccess); } /*! ************************************ \brief Create a Burger::File class with a Burger::Filename Open a file and initialize the variables. If the file open operation fails, all file access functions will fail until a new file is opened. \param pFileName Pointer to a Burger::Filename object \param eAccess Enumeration on permissions requested on the opened file \sa File(const char *,eFileAccess), Open(Filename *,eFileAccess), Close() ***************************************/ Burger::File::File(Filename *pFileName,eFileAccess eAccess) : m_pFile(NULL), m_uPosition(0), m_Filename(pFileName[0]), m_Semaphore() { #if defined(BURGER_MAC) MemoryClear(m_FSRef,sizeof(m_FSRef)); #endif Open(pFileName,eAccess); } /*! ************************************ \brief Close any open file Shut down the \ref File and close any open file. \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ Burger::File::~File() { Close(); } /*! ************************************ \brief Create a new File instance Allocate memory using Burger::Alloc() and initialize a File with it. \param pFileName Pointer to a "C" string containing a Burgerlib pathname \param eAccess Enumeration on permissions requested on the opened file \return \ref NULL if out of memory or the file didn't successfully open \sa Burger::Delete(const File *) ***************************************/ Burger::File * BURGER_API Burger::File::New(const char *pFileName,eFileAccess eAccess) { // Manually allocate the memory File *pThis = new (Alloc(sizeof(File))) File(); if (pThis) { // Load up the data if (pThis->Open(pFileName,eAccess)==kErrorNone) { // We're good! return pThis; } // Kill the malformed class Delete(pThis); } // Sorry Charlie! return nullptr; } /*! ************************************ \brief Create a new File instance Allocate memory using Burger::Alloc() and initialize a File with it. \param pFileName Pointer to a Burger::Filename object \param eAccess Enumeration on permissions requested on the opened file \return \ref NULL if out of memory or the file didn't successfully open \sa Burger::Delete(const File *) ***************************************/ Burger::File * BURGER_API Burger::File::New(Filename *pFileName,eFileAccess eAccess) { // Manually allocate the memory File *pThis = new (Alloc(sizeof(File))) File(); if (pThis) { // Load up the data if (pThis->Open(pFileName,eAccess)==kErrorNone) { // We're good! return pThis; } // Kill the malformed class Delete(pThis); } // Sorry Charlie! return nullptr; } /*! ************************************ \fn uint_t Burger::File::IsOpened(void) const \brief Return \ref TRUE if a file is open Test if a file is currently open. If there's an active file, return \ref TRUE, otherwise return \ref FALSE \return \ref TRUE if there's an open file \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ /*! ************************************ \brief Open a file using a Burgerlib pathname Close any previously opened file and open a new file. \param pFileName Pointer to a "C" string containing a Burgerlib pathname \param eAccess Enumeration on permissions requested on the opened file \return kErrorNone if no error, error code if not. \sa Open(Filename *, eFileAccess) and File(const char *,eFileAccess) ***************************************/ Burger::eError BURGER_API Burger::File::Open(const char *pFileName,eFileAccess eAccess) BURGER_NOEXCEPT { Filename MyFilename(pFileName); return Open(&MyFilename,eAccess); } /*! ************************************ \brief Open a file using a Burger::Filename Close any previously opened file and open a new file. \param pFileName Pointer to a Burger::Filename object \param eAccess Enumeration on permissions requested on the opened file \return kErrorNone if no error, error code if not. \sa Open(const char *, eFileAccess) and File(const char *,eFileAccess) ***************************************/ #if !(defined(BURGER_WINDOWS) || defined(BURGER_MSDOS) || defined(BURGER_MACOS) || defined(BURGER_IOS) || defined(BURGER_XBOX360) || defined(BURGER_VITA)) || defined(DOXYGEN) Burger::eError BURGER_API Burger::File::Open(Filename *pFileName,eFileAccess eAccess) BURGER_NOEXCEPT { static const char *g_OpenFlags[4] = { "rb","wb","ab","r+b" }; Close(); FILE *fp = fopen(pFileName->GetNative(),g_OpenFlags[eAccess&3]); uint_t uResult = kErrorFileNotFound; if (fp) { m_pFile = fp; uResult = kErrorNone; } return static_cast<Burger::eError>(uResult); } /*! ************************************ \brief Close any open file Close any previously opened file \return kErrorNone if no error, error code if not. \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ Burger::eError BURGER_API Burger::File::Close(void) BURGER_NOEXCEPT { eError uResult = kErrorNone; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { if (fclose(static_cast<FILE *>(fp))) { uResult = kErrorIO; } m_pFile = NULL; } return uResult; } /*! ************************************ \brief Return the size of a file in bytes If a file is open, query the operating system for the size of the file in bytes. \note The return value is 32 bits wide on a 32 bit operating system, 64 bits wide on 64 bit operating systems \return 0 if error or an empty file. Non-zero is the size of the file in bytes. \sa Open(const char *, eFileAccess) and Open(Filename *,eFileAccess) ***************************************/ uintptr_t BURGER_API Burger::File::GetSize(void) { uintptr_t uSize = 0; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { // Save the current file mark long Temp = ftell(fp); // Seek to the end of file if (!fseek(fp,0,SEEK_END)) { // Get the file size uSize = static_cast<uintptr_t>(ftell(fp)); } // If no error, restore the old file mark if (Temp!=-1) { fseek(fp,Temp,SEEK_SET); } } return uSize; } /*! ************************************ \brief Read data from an open file If a file is open, perform a read operation. This function will fail if the file was not opened for read access. \param pOutput Pointer to a buffer of data to read from a file \param uSize Number of bytes to read \return Number of bytes read (Can be less than what was requested due to EOF or read errors) \sa Write(const void *,uintptr_t) ***************************************/ uintptr_t BURGER_API Burger::File::Read(void *pOutput,uintptr_t uSize) { uintptr_t uResult = 0; if (uSize && pOutput) { FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { uResult = fread(pOutput,1,uSize,fp); } } return uResult; } /*! ************************************ \brief Write data into an open file If a file is open, perform a write operation. This function will fail if the file was not opened for write access. \param pInput Pointer to a buffer of data to write to a file \param uSize Number of bytes to write \return Number of bytes written (Can be less than what was requested due to EOF or write errors) \sa Read(void *,uintptr_t) ***************************************/ uintptr_t BURGER_API Burger::File::Write(const void *pInput,uintptr_t uSize) BURGER_NOEXCEPT { uintptr_t uResult = 0; if (uSize && pInput) { FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { uResult = fwrite(pInput,1,uSize,fp); } } return uResult; } /*! ************************************ \brief Get the current file mark If a file is open, query the operating system for the location of the file mark for future reads or writes. \return Current file mark or zero if an error occurred \sa Write(const void *,uintptr_t) ***************************************/ uintptr_t BURGER_API Burger::File::GetMark(void) { uintptr_t uMark = 0; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { // Save the current file mark long Temp = ftell(fp); // If no error, restore the old file mark if (Temp!=-1) { uMark = static_cast<uintptr_t>(Temp); } } return uMark; } /*! ************************************ \brief Set the current file mark If a file is open, set the read/write mark at the location passed. \param uMark Value to set the new file mark to. \return kErrorNone if successful, kErrorOutOfBounds if not. \sa GetMark() or SetMarkAtEOF() ***************************************/ Burger::eError BURGER_API Burger::File::SetMark(uintptr_t uMark) { eError uResult = kErrorNotInitialized; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { // Seek to the end of file if (!fseek(fp,static_cast<long>(uMark),SEEK_SET)) { uResult = kErrorNone; } else { uResult = kErrorOutOfBounds; } } return uResult; } /*! ************************************ \brief Set the current file mark at the end of the file If a file is open, set the read/write mark to the end of the file. \return kErrorNone if successful, kErrorOutOfBounds if not. \sa GetMark() or SetMark() ***************************************/ uint_t BURGER_API Burger::File::SetMarkAtEOF(void) { uint_t uResult = kErrorOutOfBounds; FILE *fp = static_cast<FILE *>(m_pFile); if (fp) { if (!fseek(fp,0,SEEK_END)) { uResult = kErrorNone; } } return uResult; } /*! ************************************ \brief Get the time the file was last modified If a file is open, query the operating system for the last time the file was modified. \param pOutput Pointer to a Burger::TimeDate_t to receive the file modification time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa GetCreationTime() or SetModificationTime() ***************************************/ Burger::eError BURGER_API Burger::File::GetModificationTime(TimeDate_t *pOutput) { pOutput->Clear(); return kErrorNotSupportedOnThisPlatform; } /*! ************************************ \brief Get the time the file was created If a file is open, query the operating system for the time the file was created. \param pOutput Pointer to a Burger::TimeDate_t to receive the file creation time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa GetModificationTime() or SetCreationTime() ***************************************/ Burger::eError BURGER_API Burger::File::GetCreationTime(TimeDate_t *pOutput) { pOutput->Clear(); return kErrorNotSupportedOnThisPlatform; } /*! ************************************ \brief Set the time the file was last modified If a file is open, call the operating system to set the file modification time to the passed value. \param pInput Pointer to a Burger::TimeDate_t to use for the new file modification time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetCreationTime() or GetModificationTime() ***************************************/ uint_t BURGER_API Burger::File::SetModificationTime(const TimeDate_t * /* pInput */) { return kErrorNotSupportedOnThisPlatform; } /*! ************************************ \brief Set the time the file was created If a file is open, call the operating system to set the file creation time to the passed value. \param pInput Pointer to a Burger::TimeDate_t to use for the new file creation time \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetModificationTime() or GetCreationTime() ***************************************/ uint_t BURGER_API Burger::File::SetCreationTime(const TimeDate_t * /* pInput */) { return kErrorNotSupportedOnThisPlatform; } #endif uint_t BURGER_API Burger::File::OpenAsync(const char *pFileName,eFileAccess eAccess) { m_Filename.Set(pFileName); FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandOpen,nullptr,eAccess); return 0; } uint_t BURGER_API Burger::File::OpenAsync(Filename *pFileName,eFileAccess eAccess) { m_Filename = pFileName[0]; FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandOpen,nullptr,eAccess); return 0; } uint_t BURGER_API Burger::File::CloseAsync(void) { FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandClose,nullptr,0); return 0; } uint_t BURGER_API Burger::File::ReadAsync(void *pOutput,uintptr_t uSize) { FileManager::g_pFileManager->AddQueue(this,FileManager::kIOCommandRead,pOutput,uSize); return 0; } /*! ************************************ \fn Burger::File::SetAuxType(uint32_t uAuxType) \brief Set the file's auxiliary type If a file is open, call the MacOS operating system to set the file's auxiliary type to the passed value. The file's auxiliary type is usually set to the application ID code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail with a code of kErrorNotSupportedOnThisPlatform. \param uAuxType Value to set the file's auxiliary type \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetAuxAndFileType(), SetFileType() or GetAuxType() ***************************************/ /*! ************************************ \fn Burger::File::SetFileType(uint32_t uFileType) \brief Set the file's type code If a file is open, call the MacOS operating system to set the file's type to the passed value. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail with a code of kErrorNotSupportedOnThisPlatform. \param uFileType Value to set the file's type \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetAuxAndFileType(), SetAuxType() or GetFileType() ***************************************/ /*! ************************************ \fn Burger::File::GetAuxType(void) \brief Get the file's auxiliary type If a file is open, call the MacOS operating system to get the file's auxiliary type. The file's auxiliary type is usually set to the application ID code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail by returning zero. \return The four byte code or zero on failure \sa SetAuxType() or GetFileType() ***************************************/ /*! ************************************ \fn Burger::File::GetFileType(void) \brief Get the file's type code If a file is open, call the MacOS operating system to get the file's type code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail by returning zero. \return The four byte code or zero on failure \sa SetFileType() or GetAuxType() ***************************************/ /*! ************************************ \fn Burger::File::SetAuxAndFileType(uint32_t uAuxType,uint32_t uFileType) \brief Set the file's auxiliary and file type If a file is open, call the MacOS operating system to set the file's auxiliary and file types to the passed values. The file's auxiliary type is usually set to the application ID code. \note This is a MacOS exclusive feature. If the application is not running on MacOS, it will fail with a code of kErrorNotSupportedOnThisPlatform. \param uAuxType Value to set the file's auxiliary type \param uFileType Value to set the file's type \return kErrorNone if successful, kErrorNotSupportedOnThisPlatform if not available or other codes for errors \sa SetFileType() or SetAuxType() ***************************************/ /*! ************************************ \brief Read a "C" string with the terminating zero to a file stream Read a "C" string with a terminating zero from the file stream. If the string read is larger than the buffer, it is truncated. The buffer will have an ending zero on valid read or a trucated read. If uLength was zero, then pInput can be \ref NULL \param pOutput Pointer to a "C" string to write. \param uLength Size of the buffer (To prevent overruns) \return \ref TRUE if the string was read, \ref FALSE, hit EOF \sa Burger::WriteCString(FILE *,const char *) ***************************************/ uint_t BURGER_API Burger::File::ReadCString(char *pOutput,uintptr_t uLength) { // Set the maximum buffer size // and remove 1 to make space or the ending zero char *pEnd = (pOutput+uLength)-1; uint_t uTemp; for (;;) { // Stay until either zero or EOF uint8_t Buffer; if (Read(&Buffer,1)!=1) { uTemp = 666; // EOF reached break; } uTemp = Buffer; if (!uTemp) { // Exit due to end of string? break; } // Can I store it? if (pOutput<pEnd) { pOutput[0] = static_cast<char>(uTemp); ++pOutput; // Inc the input pointer } } if (uLength) { // Any space in buffer? pOutput[0] = 0; // Add ending zero } if (uTemp) { // EOF? return FALSE; // Hit the EOF. } return TRUE; // Hit the end of string (More data may be present) } /*! ************************************ \brief Read a big endian 32-bit value from a file. Given a file opened for reading, read a 32-bit value in big endian format from the file stream. \sa Burger::File::ReadBigWord16() and Burger::File::ReadLittleWord32() \return A 32 bit big endian int converted to native endian ***************************************/ uint32_t BURGER_API Burger::File::ReadBigWord32(void) { uint32_t mValue; Read(&mValue,4); // Save the long word return BigEndian::Load(&mValue); } /*! ************************************ \brief Read a big endian 16-bit value from a file. Given a file opened for reading, read a 16-bit value in big endian format from the file stream. \sa Burger::File::ReadBigWord32() and Burger::File::ReadLittleWord16() \return A 16 bit big endian short converted to native endian ***************************************/ uint16_t BURGER_API Burger::File::ReadBigWord16(void) { uint16_t mValue; Read(&mValue,2); // Save the short word return BigEndian::Load(&mValue); } /*! ************************************ \brief Read a little endian 32-bit value from a file. Given a file opened for reading, read a 32-bit value in little endian format from the file stream. \sa Burger::File::ReadLittleWord16() and Burger::File::ReadBigWord32() \return A 32 bit little endian int converted to native endian ***************************************/ uint32_t BURGER_API Burger::File::ReadLittleWord32(void) { uint32_t mValue; Read(&mValue,4); // Save the long word return LittleEndian::Load(&mValue); } /*! ************************************ \brief Read a little endian 16-bit value from a file. Given a file opened for reading, read a 16-bit value in little endian format from the file stream. \sa Burger::File::ReadLittleWord32() and Burger::File::ReadBigWord16() \return A 16 bit little endian short converted to native endian ***************************************/ uint16_t BURGER_API Burger::File::ReadLittleWord16(void) { uint16_t mValue; Read(&mValue,2); // Save the long word return LittleEndian::Load(&mValue); }
28.423797
174
0.648041
Olde-Skuul
b909222bddaf0414336790ed23872ec1ea1532c0
168
cc
C++
c_src/allocators.cc
silviucpp/ezlib
f7b74e29d26a9359062894c2e05649be2fca1868
[ "MIT" ]
16
2016-01-12T21:36:32.000Z
2022-01-13T13:28:43.000Z
c_src/allocators.cc
silviucpp/ezlib
f7b74e29d26a9359062894c2e05649be2fca1868
[ "MIT" ]
2
2016-01-11T22:20:01.000Z
2018-10-09T20:11:07.000Z
c_src/allocators.cc
silviucpp/ezlib
f7b74e29d26a9359062894c2e05649be2fca1868
[ "MIT" ]
3
2016-01-11T16:12:50.000Z
2020-12-02T21:44:31.000Z
#include "allocators.h" #include "erl_nif.h" void* mem_allocate(size_t size) { return enif_alloc(size); } void mem_deallocate(void* ptr) { enif_free(ptr); }
12
31
0.690476
silviucpp
b90b91620a969c95e23a40f6f2a7381727c4d1c6
6,942
cpp
C++
build_bwt.cpp
jltsiren/relative-fm
68c11f172fd2a546792aad3ad81ee1e185b5ee7f
[ "MIT" ]
16
2015-04-29T11:18:01.000Z
2020-09-21T20:32:08.000Z
build_bwt.cpp
jltsiren/relative-fm
68c11f172fd2a546792aad3ad81ee1e185b5ee7f
[ "MIT" ]
null
null
null
build_bwt.cpp
jltsiren/relative-fm
68c11f172fd2a546792aad3ad81ee1e185b5ee7f
[ "MIT" ]
2
2015-12-06T20:49:38.000Z
2021-08-14T10:33:01.000Z
/* Copyright (c) 2015, 2016, 2017 Genome Research Ltd. Copyright (c) 2014 Jouni Siren and Simon Gog Author: Jouni Siren <[email protected]> Author: Simon Gog Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <unistd.h> #include <sdsl/construct.hpp> #include <sdsl/lcp.hpp> #include "support.h" using namespace relative; const size_type DEFAULT_SA_SAMPLE_RATE = 17; const size_type DEFAULT_ISA_SAMPLE_RATE = 64; int main(int argc, char** argv) { if(argc < 2) { std::cerr << "Usage: build_bwt [options] input1 [input2 ...]" << std::endl; std::cerr << " -i N Sample one out of N ISA values (default " << DEFAULT_ISA_SAMPLE_RATE << ")." << std::endl; std::cerr << " -l Also build the LCP array." << std::endl; std::cerr << " -s N Sample one out of N SA values (default " << DEFAULT_SA_SAMPLE_RATE << ")." << std::endl; std::cerr << std::endl; return 1; } bool build_lcp = false; size_type sa_sample_rate = DEFAULT_SA_SAMPLE_RATE, isa_sample_rate = DEFAULT_ISA_SAMPLE_RATE; int c = 0; while((c = getopt(argc, argv, "i:ls:")) != -1) { switch(c) { case 'i': isa_sample_rate = atol(optarg); break; case 'l': build_lcp = true; break; case 's': sa_sample_rate = atol(optarg); break; case '?': return 2; default: return 3; } } std::cout << "BWT construction" << std::endl; std::cout << "Options:"; if(isa_sample_rate > 0) { std::cout << " isa_sample_rate=" << isa_sample_rate; } if(build_lcp) { std::cout << " lcp"; } if(sa_sample_rate > 0) { std::cout << " sa_sample_rate=" << sa_sample_rate; } std::cout << std::endl; std::cout << std::endl; for(int i = optind; i < argc; i++) { std::string base_name = argv[i]; std::cout << "File: " << base_name << std::endl; sdsl::int_vector<8> text; sdsl::cache_config config; size_type size = 0; // Read text. { std::ifstream in(base_name.c_str(), std::ios_base::binary); if(!in) { std::cerr << "build_bwt: Cannot open input file " << base_name << std::endl; std::cout << std::endl; continue; } size = sdsl::util::file_size(base_name); text.resize(size + 1); std::cout << "Text size: " << size << std::endl; in.read((char*)(text.data()), size); text[size] = 0; in.close(); } // Build BWT and sample SA. sdsl::int_vector<0> sa_samples, isa_samples; { double start = readTimer(); sdsl::int_vector<64> sa(size + 1); divsufsort64((const unsigned char*)(text.data()), (int64_t*)(sa.data()), size + 1); if(sa_sample_rate > 0) { sa_samples = sdsl::int_vector<0>(size / sa_sample_rate + 1, 0, bit_length(size)); for(size_type i = 0; i <= size; i += sa_sample_rate) { sa_samples[i / sa_sample_rate] = sa[i]; } } if(isa_sample_rate > 0) { isa_samples = sdsl::int_vector<0>(size / isa_sample_rate + 1, 0, bit_length(size)); for(size_type i = 0; i <= size; i++) { if(sa[i] % isa_sample_rate == 0) { isa_samples[sa[i] / isa_sample_rate] = i; } } } char_type* bwt = (char_type*)(sa.data()); // Overwrite SA with BWT. size_type to_add[2] = { (size_type)-1, size }; for(size_type i = 0; i <= size; i++) { bwt[i] = text[sa[i] + to_add[sa[i] == 0]]; } for(size_type i = 0; i <= size; i++) { text[i] = bwt[i]; } sdsl::util::clear(sa); double seconds = readTimer() - start; std::cout << "BWT built in " << seconds << " seconds (" << (inMegabytes(size) / seconds) << " MB/s)" << std::endl; } // Compact the alphabet and write it. { Alphabet alpha(text); for(size_type i = 0; i <= size; i++) { text[i] = alpha.char2comp[text[i]]; } std::string filename = base_name + ALPHA_EXTENSION; if(!(sdsl::store_to_file(alpha, filename))) { std::cerr << "build_bwt: Cannot write to alphabet file " << filename << std::endl; } else { std::cout << "Alphabet written to " << filename << std::endl; } } // Write BWT. { std::string filename = base_name + BWT_EXTENSION; if(!(sdsl::store_to_file(text, filename))) { std::cerr << "build_bwt: Cannot open BWT file " << filename << std::endl; } else { std::cout << "BWT written to " << filename << std::endl; if(build_lcp) { config.file_map[sdsl::conf::KEY_BWT] = filename; } } sdsl::util::clear(text); } // Write SA/ISA samples. if(sa_sample_rate > 0 || isa_sample_rate > 0) { std::string filename = base_name + SAMPLE_EXTENSION; std::ofstream out(filename.c_str(), std::ios_base::binary); if(!out) { std::cerr << "build_bwt: Cannot open sample file " << filename << std::endl; } else { sdsl::write_member(sa_sample_rate, out); sa_samples.serialize(out); sdsl::write_member(isa_sample_rate, out); isa_samples.serialize(out); out.close(); std::cout << "Samples written to " << filename << std::endl; } sdsl::util::clear(sa_samples); sdsl::util::clear(isa_samples); } // Build and write LCP. if(build_lcp) { double start = readTimer(); construct_lcp_bwt_based(config); sdsl::int_vector_buffer<0> lcp_buffer(sdsl::cache_file_name(sdsl::conf::KEY_LCP, config)); SLArray lcp(lcp_buffer); double seconds = readTimer() - start; std::cout << "LCP array built in " << seconds << " seconds (" << (inMegabytes(size) / seconds) << " MB/s)" << std::endl; std::string filename = base_name + LCP_EXTENSION; sdsl::store_to_file(lcp, filename); lcp_buffer.close(); std::remove(sdsl::cache_file_name(sdsl::conf::KEY_LCP, config).c_str()); } std::cout << std::endl; } return 0; }
34.029412
126
0.60703
jltsiren
2c6cc68367f41d0284cd7f981f6da2ea7a251162
942
cpp
C++
Matrix/Median in a row-wise Sortedd Matrix.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
9
2020-10-01T09:29:10.000Z
2022-02-12T04:58:41.000Z
Matrix/Median in a row-wise Sortedd Matrix.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
6
2020-10-03T16:08:58.000Z
2020-10-14T12:06:25.000Z
Matrix/Median in a row-wise Sortedd Matrix.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
17
2020-10-01T09:17:27.000Z
2021-06-18T09:36:31.000Z
class Solution{ public: int median(vector<vector<int>> &matrix, int r, int c){ // code here int min = INT_MAX, max = INT_MIN; // Maximum and minimum element from the array for(int i = 0;i<r;++i) { if(matrix[i][0] < min) { min = matrix[i][0]; } if(matrix[i][c-1] > max) { max = matrix[i][c-1]; } } int desired = (r*c +1)/2; while(min<max) { int mid = min + (max - min) /2; int place = 0; for(int i = 0 ;i<r;i++) { place += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin(); } if(place<desired) { min = mid +1; } else{ max = mid; } } return min; } };
25.459459
98
0.359873
vermagaurav8
2c6d492cbe59ce88947591fe7dbfe67dfb0cf0b7
4,038
hpp
C++
em_unet/src/PyGreentea/evaluation/src_cython/zi/heap/binary_heap.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
10
2018-09-13T17:37:22.000Z
2020-05-08T16:20:42.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/heap/binary_heap.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
1
2018-12-02T14:17:39.000Z
2018-12-02T20:59:26.000Z
em_unet/src/PyGreentea/evaluation/src_cython/zi/heap/binary_heap.hpp
VCG/psc
4826c495b89ff77b68a3c0d5c6e3af805db25386
[ "MIT" ]
2
2019-03-03T12:06:10.000Z
2020-04-12T13:23:02.000Z
// // Copyright (C) 2010 Aleksandar Zlateski <[email protected]> // ---------------------------------------------------------- // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #ifndef ZI_HEAP_BINARY_HEAP_HPP #define ZI_HEAP_BINARY_HEAP_HPP #include <zi/bits/cstdint.hpp> #include <zi/bits/hash.hpp> #include <zi/bits/unordered_map.hpp> #include <zi/utility/exception.hpp> #include <functional> #include <cstring> #include <cstdlib> #include <cstddef> #include <map> #include <zi/detail/identity.hpp> #include <zi/detail/member_function.hpp> #include <zi/detail/member_variable.hpp> #include <zi/detail/global_function.hpp> #include <zi/heap/detail/binary_heap_impl.hpp> namespace zi { namespace heap { using ::zi::detail::identity; using ::zi::detail::member_function; using ::zi::detail::const_member_function; using ::zi::detail::member_variable; using ::zi::detail::global_function; template< class KeyExtractor, class Hash = ::zi::hash< typename KeyExtractor::result_type >, class Pred = std::equal_to< typename KeyExtractor::result_type > > struct hashed_index { typedef typename KeyExtractor::result_type key_type; typedef KeyExtractor key_extractor; typedef unordered_map< const key_type, uint32_t, Hash, Pred > container_type; }; template< class KeyExtractor, class Compare = std::less< typename KeyExtractor::result_type > > struct ordered_index { typedef typename KeyExtractor::result_type key_type; typedef KeyExtractor key_extractor; typedef std::map< const key_type, uint32_t, Compare > container_type; }; template< class ValueExtractor, class ValueCompare = std::less< typename ValueExtractor::result_type > > struct value { typedef typename ValueExtractor::result_type value_type; typedef ValueExtractor value_extractor; typedef ValueCompare compare_type; }; } // namespace heap template< class Type, class IndexTraits = heap::hashed_index< heap::identity< Type > >, class ValueTraits = heap::value< heap::identity< Type > >, class Allocator = std::allocator< Type > > struct binary_heap: ::zi::heap::detail::binary_heap_impl< Type, typename IndexTraits::key_type, typename ValueTraits::value_type, typename IndexTraits::key_extractor, typename ValueTraits::value_extractor, typename ValueTraits::compare_type, typename IndexTraits::container_type, Allocator > { private: typedef typename ValueTraits::compare_type compare_type; typedef Allocator alloc_type ; typedef ::zi::heap::detail::binary_heap_impl< Type, typename IndexTraits::key_type, typename ValueTraits::value_type, typename IndexTraits::key_extractor, typename ValueTraits::value_extractor, typename ValueTraits::compare_type, typename IndexTraits::container_type, Allocator > base_type; public: binary_heap( const alloc_type& alloc ) : base_type( compare_type(), alloc ) { } binary_heap( const compare_type& compare = compare_type(), const alloc_type& alloc = alloc_type()) : base_type( compare, alloc ) { } }; } // namespace zi #endif
30.590909
82
0.668895
VCG
2c7155ffd3fe940dc76676ef5cc2c14c387fae9b
140
hxx
C++
src/Providers/UNIXProviders/BGPAttributesForRoute/UNIX_BGPAttributesForRoute_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/BGPAttributesForRoute/UNIX_BGPAttributesForRoute_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/BGPAttributesForRoute/UNIX_BGPAttributesForRoute_FREEBSD.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_FREEBSD #ifndef __UNIX_BGPATTRIBUTESFORROUTE_PRIVATE_H #define __UNIX_BGPATTRIBUTESFORROUTE_PRIVATE_H #endif #endif
11.666667
46
0.864286
brunolauze
2c726e26dbc634fe32ce8ee51e3229c60d158366
1,630
cpp
C++
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
shaopengyuan/FMT-Firmware
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
[ "Apache-2.0" ]
72
2021-09-13T20:29:29.000Z
2022-03-30T01:42:09.000Z
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
shaopengyuan/FMT-Firmware
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
[ "Apache-2.0" ]
33
2019-01-09T11:02:15.000Z
2022-03-31T11:47:54.000Z
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
shaopengyuan/FMT-Firmware
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
[ "Apache-2.0" ]
35
2019-03-06T01:54:00.000Z
2022-02-03T07:06:37.000Z
// Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 "FullBuffer.hpp" TEST_F(FullBuffer, Block_8) { fill_buffer_except(7); try_block_8(); } TEST_F(FullBuffer, Block_4) { fill_buffer_except(3); try_block_4(); } TEST_F(FullBuffer, Block_2) { fill_buffer_except(1); try_block_2(); } TEST_F(FullBuffer, Block_1) { fill_buffer_except(0); try_block_1(); } # define SUCCESSFUL_SERIALIZATION 3 # define ARRAY_SERIALIZATION (SUCCESSFUL_SERIALIZATION + 1) TEST_F(FullBuffer, ArrayBlock_8) { fill_buffer_except(8 * SUCCESSFUL_SERIALIZATION + 7); try_array_block_8(ARRAY_SERIALIZATION); } TEST_F(FullBuffer, ArrayBlock_4) { fill_buffer_except(4 * SUCCESSFUL_SERIALIZATION + 3); try_array_block_4(ARRAY_SERIALIZATION); } TEST_F(FullBuffer, ArrayBlock_2) { fill_buffer_except(2 * SUCCESSFUL_SERIALIZATION + 1); try_array_block_2(ARRAY_SERIALIZATION); } TEST_F(FullBuffer, ArrayBlock_1) { fill_buffer_except(SUCCESSFUL_SERIALIZATION); try_array_block_1(ARRAY_SERIALIZATION); }
24.328358
75
0.745399
shaopengyuan
2c76092f73c7aa8f3ba9540812917f283984af57
106
cpp
C++
src/add_test/library/src/echo.cpp
mariokonrad/cmake-cheatsheet
268d68327e0d6af997684ec9e0fc96b5e7276a22
[ "CC-BY-4.0" ]
36
2019-03-28T09:05:10.000Z
2022-01-13T14:33:17.000Z
src/add_test/library/src/echo.cpp
bernedom/cmake-cheatsheet
280378bafe187a525b8376ba17b73781bba08861
[ "CC-BY-4.0" ]
null
null
null
src/add_test/library/src/echo.cpp
bernedom/cmake-cheatsheet
280378bafe187a525b8376ba17b73781bba08861
[ "CC-BY-4.0" ]
5
2019-04-05T20:55:37.000Z
2021-11-01T08:40:42.000Z
#include <library/echo.hpp> namespace library { std::string echo(const std::string & s) { return s; } }
11.777778
39
0.679245
mariokonrad
2c7a7c042aec611c7029b8ec65a0be05c512621c
9,713
cc
C++
benchmarks/ycsb-cs.cc
sfu-dis/corobase
3a213e72d5561687bbedb925b977c86a9ce36e04
[ "MIT" ]
166
2020-11-02T05:30:35.000Z
2022-03-26T07:39:16.000Z
benchmarks/ycsb-cs.cc
sfu-dis/corobase
3a213e72d5561687bbedb925b977c86a9ce36e04
[ "MIT" ]
2
2020-06-02T00:12:58.000Z
2020-06-13T23:22:25.000Z
benchmarks/ycsb-cs.cc
sfu-dis/corobase
3a213e72d5561687bbedb925b977c86a9ce36e04
[ "MIT" ]
19
2020-11-08T02:44:09.000Z
2022-02-26T19:49:33.000Z
/* * A YCSB implementation based off of Silo's and equivalent to FOEDUS's. */ #include "bench.h" #include "ycsb.h" #ifndef ADV_COROUTINE extern uint g_reps_per_tx; extern uint g_rmw_additional_reads; extern ReadTransactionType g_read_txn_type; extern YcsbWorkload ycsb_workload; class ycsb_cs_worker : public ycsb_base_worker { public: ycsb_cs_worker( unsigned int worker_id, unsigned long seed, ermia::Engine *db, const std::map<std::string, ermia::OrderedIndex *> &open_tables, spin_barrier *barrier_a, spin_barrier *barrier_b) : ycsb_base_worker(worker_id, seed, db, open_tables, barrier_a, barrier_b) { } // Essentially a coroutine scheduler that switches between active transactions virtual void MyWork(char *) override { // No replication support ALWAYS_ASSERT(is_worker); workload = get_workload(); txn_counts.resize(workload.size()); if (ermia::config::coro_batch_schedule) { //PipelineScheduler(); BatchScheduler(); } else { Scheduler(); } } virtual workload_desc_vec get_workload() const override { workload_desc_vec w; if (ycsb_workload.insert_percent() || ycsb_workload.update_percent()) { LOG(FATAL) << "Not implemented"; } LOG_IF(FATAL, g_read_txn_type != ReadTransactionType::SimpleCoro) << "Read txn type must be simple-coro"; if (ycsb_workload.read_percent()) { w.push_back(workload_desc("Read", double(ycsb_workload.read_percent()) / 100.0, nullptr, TxnRead)); } if (ycsb_workload.rmw_percent()) { LOG_IF(FATAL, ermia::config::index_probe_only) << "Not supported"; w.push_back(workload_desc("RMW", double(ycsb_workload.rmw_percent()) / 100.0, nullptr, TxnRMW)); } if (ycsb_workload.scan_percent()) { if (ermia::config::scan_with_it) { w.push_back(workload_desc("ScanWithIterator", double(ycsb_workload.scan_percent()) / 100.0, nullptr, TxnScanWithIterator)); } else { LOG_IF(FATAL, ermia::config::index_probe_only) << "Not supported"; w.push_back(workload_desc("Scan", double(ycsb_workload.scan_percent()) / 100.0, nullptr, TxnScan)); } } return w; } static ermia::coro::generator<rc_t> TxnRead(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_read(idx, begin_epoch); } static ermia::coro::generator<rc_t> TxnRMW(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_rmw(idx, begin_epoch); } static ermia::coro::generator<rc_t> TxnScan(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_scan(idx, begin_epoch); } static ermia::coro::generator<rc_t> TxnScanWithIterator(bench_worker *w, uint32_t idx, ermia::epoch_num begin_epoch) { return static_cast<ycsb_cs_worker *>(w)->txn_scan_with_iterator(idx, begin_epoch); } // Read transaction with context-switch using simple coroutine ermia::coro::generator<rc_t> txn_read(uint32_t idx, ermia::epoch_num begin_epoch) { ermia::transaction *txn = nullptr; if (ermia::config::index_probe_only) { arenas[idx].reset(); } else { txn = db->NewTransaction( ermia::transaction::TXN_FLAG_CSWITCH | ermia::transaction::TXN_FLAG_READ_ONLY, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; } for (int i = 0; i < g_reps_per_tx; ++i) { ermia::varstr &v = str(arenas[idx], sizeof(ycsb_kv::value)); rc_t rc = rc_t{RC_INVALID}; if (ermia::config::index_probe_only) { ermia::varstr &k = str(arenas[idx], sizeof(ycsb_kv::key)); new (&k) ermia::varstr((char *)&k + sizeof(ermia::varstr), sizeof(ycsb_kv::key)); BuildKey(rng_gen_key(), k); ermia::ConcurrentMasstree::threadinfo ti(begin_epoch); ermia::ConcurrentMasstree::versioned_node_t sinfo; ermia::OID oid = ermia::INVALID_OID; rc._val = (co_await table_index->GetMasstree().search_coro(k, oid, ti, &sinfo)) ? RC_TRUE : RC_FALSE; } else { ermia::varstr &k = GenerateKey(txn); rc = co_await table_index->coro_GetRecord(txn, k, v); } #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else // Under SI this must succeed ALWAYS_ASSERT(rc._val == RC_TRUE); ASSERT(ermia::config::index_probe_only || *(char*)v.data() == 'a'); #endif if (!ermia::config::index_probe_only) memcpy((char*)(&v) + sizeof(ermia::varstr), (char *)v.data(), sizeof(ycsb_kv::value)); } #ifndef CORO_BATCH_COMMIT if (!ermia::config::index_probe_only) { TryCatchCoro(db->Commit(txn)); } #endif co_return {RC_TRUE}; } // Read-modify-write transaction with context-switch using simple coroutine ermia::coro::generator<rc_t> txn_rmw(uint32_t idx, ermia::epoch_num begin_epoch) { auto *txn = db->NewTransaction(ermia::transaction::TXN_FLAG_CSWITCH, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; for (int i = 0; i < g_reps_per_tx; ++i) { ermia::varstr &k = GenerateKey(txn); ermia::varstr &v = str(arenas[idx], sizeof(ycsb_kv::value)); rc_t rc = rc_t{RC_INVALID}; rc = co_await table_index->coro_GetRecord(txn, k, v); #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else // Under SI this must succeed LOG_IF(FATAL, rc._val != RC_TRUE); ALWAYS_ASSERT(rc._val == RC_TRUE); ASSERT(*(char*)v.data() == 'a'); #endif ASSERT(v.size() == sizeof(ycsb_kv::value)); memcpy((char*)(&v) + sizeof(ermia::varstr), (char *)v.data(), v.size()); // Re-initialize the value structure to use my own allocated memory - // DoTupleRead will change v.p to the object's data area to avoid memory // copy (in the read op we just did). new (&v) ermia::varstr((char *)&v + sizeof(ermia::varstr), sizeof(ycsb_kv::value)); new (v.data()) ycsb_kv::value("a"); rc = co_await table_index->coro_UpdateRecord(txn, k, v); // Modify-write TryCatchCoro(rc); } for (int i = 0; i < g_rmw_additional_reads; ++i) { ermia::varstr &k = GenerateKey(txn); ermia::varstr &v = str(arenas[idx], sizeof(ycsb_kv::value)); rc_t rc = rc_t{RC_INVALID}; rc = co_await table_index->coro_GetRecord(txn, k, v); #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else // Under SI this must succeed ALWAYS_ASSERT(rc._val == RC_TRUE); ASSERT(*(char*)v.data() == 'a'); #endif ASSERT(v.size() == sizeof(ycsb_kv::value)); memcpy((char*)(&v) + sizeof(ermia::varstr), (char *)v.data(), v.size()); } #ifndef CORO_BATCH_COMMIT TryCatchCoro(db->Commit(txn)); #endif co_return {RC_TRUE}; } ermia::coro::generator<rc_t> txn_scan(uint32_t idx, ermia::epoch_num begin_epoch) { auto *txn = db->NewTransaction(ermia::transaction::TXN_FLAG_CSWITCH | ermia::transaction::TXN_FLAG_READ_ONLY, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; for (int i = 0; i < g_reps_per_tx; ++i) { rc_t rc = rc_t{RC_INVALID}; ScanRange range = GenerateScanRange(txn); ycsb_scan_callback callback; rc = co_await table_index->coro_Scan(txn, range.start_key, &range.end_key, callback); ALWAYS_ASSERT(callback.size() <= g_scan_max_length); #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else ALWAYS_ASSERT(rc._val == RC_TRUE); #endif } #ifndef CORO_BATCH_COMMIT TryCatchCoro(db->Commit(txn)); #endif co_return {RC_TRUE}; } ermia::coro::generator<rc_t> txn_scan_with_iterator(uint32_t idx, ermia::epoch_num begin_epoch) { auto *txn = db->NewTransaction(ermia::transaction::TXN_FLAG_CSWITCH | ermia::transaction::TXN_FLAG_READ_ONLY, arenas[idx], &transactions[idx], idx); ermia::TXN::xid_context *xc = txn->GetXIDContext(); xc->begin_epoch = begin_epoch; for (int i = 0; i < g_reps_per_tx; ++i) { rc_t rc = rc_t{RC_INVALID}; ScanRange range = GenerateScanRange(txn); ycsb_scan_callback callback; ermia::ConcurrentMasstree::coro_ScanIterator</*IsRerverse=*/false> iter(txn->GetXIDContext(), &table_index->GetMasstree(), range.start_key, &range.end_key); bool more = co_await iter.init(); ermia::varstr valptr; ermia::dbtuple* tuple = nullptr; while (more) { if (!ermia::config::index_probe_only) { tuple = ermia::oidmgr->oid_get_version( iter.tuple_array(), iter.value(), txn->GetXIDContext()); if (tuple) { rc = txn->DoTupleRead(tuple, &valptr); if (rc._val == RC_TRUE) { callback.Invoke(iter.key().data(), iter.key().length(), valptr); } } #if defined(SSI) || defined(SSN) || defined(MVOCC) TryCatchCoro(rc); #else ALWAYS_ASSERT(rc._val == RC_TRUE); #endif } more = iter.next(); } ALWAYS_ASSERT(ermia::config::index_probe_only || callback.size() <= g_scan_max_length); } #ifndef CORO_BATCH_COMMIT TryCatchCoro(db->Commit(txn)); #endif co_return {RC_TRUE}; } }; void ycsb_cs_do_test(ermia::Engine *db, int argc, char **argv) { ycsb_parse_options(argc, argv); ycsb_bench_runner<ycsb_cs_worker> r(db); r.run(); } #endif // ADV_COROUTINE
36.107807
120
0.650777
sfu-dis
2c7fdde362e53ae77e884f8df0b864268c483ff4
5,130
cpp
C++
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
plugins/api/src/data_object_modify_info.cpp
mcv21/irods
3c793a5acbbbe25b5f20aaeeca2609417855eee6
[ "BSD-3-Clause" ]
null
null
null
#include "api_plugin_number.h" #include "rodsDef.h" #include "rcConnect.h" #include "rodsPackInstruct.h" #include "rcMisc.h" #include "client_api_whitelist.hpp" #include "apiHandler.hpp" #include <functional> #ifdef RODS_SERVER // // Server-side Implementation // #include "objDesc.hpp" #include "irods_stacktrace.hpp" #include "irods_server_api_call.hpp" #include "irods_re_serialization.hpp" #include "rsModDataObjMeta.hpp" #include "scoped_privileged_client.hpp" #include "key_value_proxy.hpp" #include <string> #include <tuple> namespace { // // Function Prototypes // auto call_data_object_modify_info(irods::api_entry*, rsComm_t*, modDataObjMeta_t*) -> int; auto is_input_valid(const bytesBuf_t*) -> std::tuple<bool, std::string>; auto rs_data_object_modify_info(rsComm_t*, modDataObjMeta_t*) -> int; // // Function Implementations // auto call_data_object_modify_info(irods::api_entry* api, rsComm_t* comm, modDataObjMeta_t* input) -> int { return api->call_handler<modDataObjMeta_t*>(comm, input); } auto is_input_valid(const modDataObjMeta_t* input) -> std::tuple<bool, std::string> { if (!input) { return {false, "Input is null"}; } irods::experimental::key_value_proxy proxy{*input->regParam}; const auto is_invalid_keyword = [](const auto& handle) { // To allow modification of a column, comment out the condition // referencing that column. return handle.key() == CHKSUM_KW || handle.key() == COLL_ID_KW || //handle.key() == DATA_COMMENTS_KW || handle.key() == DATA_CREATE_KW || //handle.key() == DATA_EXPIRY_KW || handle.key() == DATA_ID_KW || handle.key() == DATA_MAP_ID_KW || handle.key() == DATA_MODE_KW || //handle.key() == DATA_MODIFY_KW || handle.key() == DATA_NAME_KW || handle.key() == DATA_OWNER_KW || handle.key() == DATA_OWNER_ZONE_KW || //handle.key() == DATA_RESC_GROUP_NAME_KW || // Not defined. handle.key() == DATA_SIZE_KW || //handle.key() == DATA_TYPE_KW || handle.key() == FILE_PATH_KW || handle.key() == REPL_NUM_KW || handle.key() == REPL_STATUS_KW || handle.key() == RESC_HIER_STR_KW || handle.key() == RESC_ID_KW || handle.key() == RESC_NAME_KW || handle.key() == STATUS_STRING_KW || handle.key() == VERSION_KW; }; if (std::any_of(std::begin(proxy), std::end(proxy), is_invalid_keyword)) { return {false, "Invalid keyword found"}; } return {true, ""}; } auto rs_data_object_modify_info(rsComm_t* comm, modDataObjMeta_t* input) -> int { if (auto [valid, msg] = is_input_valid(input); !valid) { rodsLog(LOG_ERROR, msg.data()); return USER_BAD_KEYWORD_ERR; } irods::experimental::scoped_privileged_client spc{*comm}; return rsModDataObjMeta(comm, input); } using operation = std::function<int(rsComm_t*, modDataObjMeta_t*)>; const operation op = rs_data_object_modify_info; #define CALL_DATA_OBJECT_MODIFY_INFO call_data_object_modify_info } // anonymous namespace #else // RODS_SERVER // // Client-side Implementation // #include "modDataObjMeta.h" namespace { using operation = std::function<int(rsComm_t*, modDataObjMeta_t*)>; const operation op{}; #define CALL_DATA_OBJECT_MODIFY_INFO nullptr } // anonymous namespace #endif // RODS_SERVER // The plugin factory function must always be defined. extern "C" auto plugin_factory(const std::string& _instance_name, const std::string& _context) -> irods::api_entry* { #ifdef RODS_SERVER irods::client_api_whitelist::instance().add(DATA_OBJECT_MODIFY_INFO_APN); #endif // RODS_SERVER // clang-format off irods::apidef_t def{DATA_OBJECT_MODIFY_INFO_APN, // API number RODS_API_VERSION, // API version NO_USER_AUTH, // Client auth NO_USER_AUTH, // Proxy auth "ModDataObjMeta_PI", 0, // In PI / bs flag nullptr, 0, // Out PI / bs flag op, // Operation "data_object_modify_info", // Operation name clearModDataObjMetaInp, // Null clear function (funcPtr) CALL_DATA_OBJECT_MODIFY_INFO}; // clang-format on auto* api = new irods::api_entry{def}; api->in_pack_key = "ModDataObjMeta_PI"; api->in_pack_value = ModDataObjMeta_PI; return api; }
32.675159
94
0.569591
mcv21
2c8c834831719e425d519b2c0b9966f3d5ef31b0
1,035
cpp
C++
Problem Set Volumes/Volume 2/291 - The House Of Santa Claus.cpp
ztrixack/uva-online-judge
ef87e745390a6a1965fe06621e50c6dc48db7257
[ "MIT" ]
null
null
null
Problem Set Volumes/Volume 2/291 - The House Of Santa Claus.cpp
ztrixack/uva-online-judge
ef87e745390a6a1965fe06621e50c6dc48db7257
[ "MIT" ]
null
null
null
Problem Set Volumes/Volume 2/291 - The House Of Santa Claus.cpp
ztrixack/uva-online-judge
ef87e745390a6a1965fe06621e50c6dc48db7257
[ "MIT" ]
null
null
null
//============================================================================ // Name : 291 - The House Of Santa Claus.cpp // Author : ztrixack // Copyright : MIT License // Description : 278 The House Of Santa Claus in C++, Ansi-style // Run Time : 0.008 seconds //============================================================================ #include <iostream> #include <string> #include <algorithm> using namespace std; #define FRI(i, a, b) for (i = a; i < b; ++i) int mem[] = { 1, 2, 3, 1, 5, 3, 4, 5, 2 }; int main() { int i, x, y; bool ma; do { bool direct[5][5] = { {0, 1, 1, 0, 1}, {0, 0, 1, 0, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 0} }; ma = true; FRI (i, 0, 8) { x = min(mem[i] - 1, mem[i + 1] - 1); y = max(mem[i] - 1, mem[i + 1] - 1); if (!(direct[x][y]) || direct[y][x]) { ma = false; break; } direct[y][x] = true; } if (ma) { FRI(i, 0, 9) cout << mem[i]; cout << endl; } next_permutation(mem, mem + 9); } while (mem[0] == 1); return 0; }
25.875
110
0.416425
ztrixack
2c9ba5f1643b1cd82cb93145c7fca4d5cf0795fc
2,673
cpp
C++
src/main.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
src/main.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
src/main.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <iomanip> #include "Connect4State.h" #include "humanplayer.h" #include "autoc4player.h" #include "l181139AIplayer.h" using namespace std; void BlankLines(int n) { for (int i = 0; i < n; i++) cout << "\n"; } void ShowConnect4(GameState *C) { Connect4State *C4 = static_cast<Connect4State *>(C); string P1 = C4->GetPlayerName(0); string P2 = C4->GetPlayerName(1); cout << "\t\t" << P1 << "\t\t vs \t\t" << P2; BlankLines(3); for (int i = 1; i < 8; i++) { if (i == 1) cout << setw(8) << i; else cout << setw(11) << i; } BlankLines(3); for (int r = 0; r < 6; r++) { for (int c = 0; c < 7; c++) { if (c == 0) cout << setw(2) << "|"; char PlayerCode = C4->getState(r, c); cout << setw(6) << PlayerCode << setw(5) << "|"; } cout << endl; for (int b = 0; r < 5 && b < 2; b++) { for (int c = 0; r < 5 && c < 7; c++) { if (c == 0) cout << setw(2) << "|"; cout << setw(6) << ' ' << setw(5) << "|"; } cout << endl; } } for (int i = 0; i < 80; i++) cout << char(220); if (C4->GetTurningPlayer() == 1) cout << endl << "Turn of " << P2; else cout << endl << "Turn of " << P1; cout << endl << endl; } int main() { Player *Players[3]; int InvalidMoveCount[3]; Players[1] = new l181139AIplayer("Malik", 'L'); //Players[1] = new l181139AIplayer("Malik", 'P'); Players[0] = new HumanPlayer("Human1", 'H'); //Players[1] = new HumanPlayer("Human2", 'K'); //Players[1] = new AutoC4Player('L'); Players[2] = new AutoC4Player('B'); int TotalPlayers = 2; for (int i = 0; i < TotalPlayers - 1; i++) { for (int j = i + 1; j < TotalPlayers; j++) { GameState *C4 = new Connect4State(); C4->AddPlayer(Players[i]); C4->AddPlayer(Players[j]); int TurningPlayer; int Toggle = 1; while (!C4->GameOver()) { if (Toggle) { ShowConnect4(C4); } Toggle = (Toggle + 1) % 2; TurningPlayer = C4->GetTurningPlayer(); cout << "Player Turning: " << C4->GetPlayerName(TurningPlayer) << "-" << C4->GetPlayerColor(TurningPlayer) << endl; if (!C4->MakeMove()) { TurningPlayer = C4->GetTurningPlayer(); InvalidMoveCount[TurningPlayer]++; cout << "made invalid Move\n"; ShowConnect4(C4); system("pause"); } } ShowConnect4(C4); cout << "\nWho Won?\n" << C4->WhoWon() << " Color:" << C4->GetPlayerColor(C4->WhoWon()); } } return 0; }
22.090909
123
0.495698
ghostdart
2c9c77633a0c1777af09aa7d61a0ee6dbf81c06d
2,058
cpp
C++
test/src/hcExam/hcExam01.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
2
2019-07-15T05:01:57.000Z
2019-09-25T20:23:04.000Z
test/src/hcExam/hcExam01.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
null
null
null
test/src/hcExam/hcExam01.cpp
josokw/ExamGenerator
22a566799c4bb31275ef942ae5ae529285eb741a
[ "MIT" ]
null
null
null
#include "hcExam01.h" #include "GenHeader.h" #include "GenItem.h" #include "GenOption.h" #include "GenText.h" #include "Log.h" #include <vector> void hcExam01(std::ofstream &LaTeXfile) { LOGD("Generating LaTeX started", 3); const bool IS_CORRECT{true}; // std::vector<message_t> messages; // std::shared_ptr<GenExams> pMCtst(new GenExams(messages)); // pMCtst->setID("Hard coded test1"); // std::shared_ptr<GenItem> pI; // std::shared_ptr<GenText> pT1; // std::shared_ptr<GenText> pT2; // std::shared_ptr<GenText> pT3; // std::shared_ptr<GenJava> pJ1; // std::shared_ptr<GenJava> pJ2; // std::shared_ptr<GenOption> pO1; // std::shared_ptr<GenOption> pO2; // std::shared_ptr<GenOption> pO3; // std::shared_ptr<GenOption> pO4; // std::shared_ptr<GenImage> pImg; auto pHeader = std::make_shared<GenHeader>(); pHeader->setID("h1"); pHeader->School = "HAN Engineering"; pHeader->Course = "Introduction C programming"; pHeader->Lecturer = "Jos Onokiewicz"; pHeader->Other = "22th September 2018"; pHeader->BoxedText = "Success!"; // pMCtst->add(pHeader); // Item #1 ------------------------------------------------------------------ auto pItem = std::make_unique<GenItem>(); pItem->setID("I1"); auto pText1 = std::make_unique<GenText>(pItem->getID() + ".txt", "Welk van de volgende typen gebruik je om aan te geven dat het een " "variabele tekst bevat?"); auto pO1 = std::make_unique<GenOption>("O1", "Character"); auto pO2 = std::make_unique<GenOption>("O2", "char"); auto pO3 = std::make_unique<GenOption>("O3", "String"); auto pO4 = std::make_unique<GenOption>("O4", "String[ ]"); // pItem->addToStem(pText1); // pItem->addToOptions(pO1); // pItem->addToOptions(pO2); // pItem->addToOptions(pO3, IS_CORRECT); // pItem->addToOptions(pO4); // pItem->shuffleON(); // pMCtst->add(pI); // pMCtst->generate(TexFile); LOGD("Generating LaTeX ready", 3); }
31.181818
80
0.6069
josokw
2ca4465ca23c9ca59239947c9babf8dd0212fafd
1,486
hpp
C++
3rdparty/stout/include/stout/os/socket.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
4
2019-03-06T03:04:40.000Z
2019-07-20T15:35:00.000Z
3rdparty/stout/include/stout/os/socket.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
6
2018-11-30T08:04:45.000Z
2019-05-15T03:04:28.000Z
3rdparty/stout/include/stout/os/socket.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
4
2019-03-11T11:51:22.000Z
2020-05-11T07:27:31.000Z
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_SOCKET_HPP__ #define __STOUT_OS_SOCKET_HPP__ #include <stout/error.hpp> #include <stout/try.hpp> #include <stout/os/int_fd.hpp> #ifdef __WINDOWS__ #include <stout/os/windows/socket.hpp> #else #include <stout/os/posix/socket.hpp> #endif // __WINDOWS__ namespace net { // Returns a socket file descriptor for the specified options. // NOTE: on OS X, the returned socket will have the SO_NOSIGPIPE option set. inline Try<int_fd> socket(int family, int type, int protocol) { int_fd s; if ((s = ::socket(family, type, protocol)) < 0) { return ErrnoError(); } #ifdef __APPLE__ // Disable SIGPIPE via setsockopt because OS X does not support // the MSG_NOSIGNAL flag on send(2). const int enable = 1; if (setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &enable, sizeof(int)) == -1) { return ErrnoError(); } #endif // __APPLE__ return s; } } // namespace net { #endif // __STOUT_OS_SOCKET_HPP__
28.037736
76
0.728129
sagar8192
2ca7d5a766386b8acd33397e6800e2896350a71f
1,900
cpp
C++
C++/ServerProject/main.cpp
AlexanderArgyriou/TCP-Sever-Client
ad621f94afda08b3d03cb760faf148b4348ed401
[ "MIT" ]
null
null
null
C++/ServerProject/main.cpp
AlexanderArgyriou/TCP-Sever-Client
ad621f94afda08b3d03cb760faf148b4348ed401
[ "MIT" ]
null
null
null
C++/ServerProject/main.cpp
AlexanderArgyriou/TCP-Sever-Client
ad621f94afda08b3d03cb760faf148b4348ed401
[ "MIT" ]
null
null
null
#include "pch.h" #define _WIN32_WINNT 0x0501 #include "Server.h" int main() { cout << "Server is Running..." << endl << endl; for (;;) { Server newServer; boost::asio::io_service NewService; tcp::acceptor NewAcceptor(NewService, tcp::endpoint(tcp::v4(), 4523)); //listen to new Connection tcp::socket ServerSocket(NewService); //ServerSide Socket creation NewAcceptor.accept(ServerSocket); //waiting for connection //After Connection enstablished string ClientGetName = newServer.Read(ServerSocket); //Catch client MsgName string ClientGetSurname = newServer.Read(ServerSocket); //Catch client MsgSurname string ClientGetAM = newServer.Read(ServerSocket); //Catch client MsgAm int ResponseResult = 0; cout << "Client Name: " << ClientGetName.c_str(); cout << "Client Surname: " << ClientGetSurname.c_str(); cout << "Client Am: " << ClientGetAM.c_str(); if (stoi(ClientGetAM) < 0) { cout << "Negative AM Error" << endl; newServer.Send(ServerSocket, "Negative AM Error"); //Response }//if else { if (((ClientGetName.length() + ClientGetSurname.length()) % 2) == 0) //name + surname letters are even { for (int i = 0; i <= stoi(ClientGetAM); ++i) { if (i % 2 == 0) ++ResponseResult; //number of even numbers from 0-ClientAm } //for } //if else { for (int i = 1; i <= stoi(ClientGetAM); ++i) //name + surname letters are odd { if (i % 2 != 0) ++ResponseResult; //number of odd numbers from 1-ClientAm } //for } //else cout << "Result sent Back:" << to_string(ResponseResult).c_str() << endl; string Return = "The Result is:" + to_string(ResponseResult) + "\n"; newServer.Send(ServerSocket, Return); //Response } //else cout << endl; ResponseResult = 0; //reset } //for infinite loop return 0; } //main
30.15873
106
0.625263
AlexanderArgyriou
2ca87bae7f11b13142de7d3ee4935ff338a1a172
10,072
cpp
C++
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
6
2019-11-18T16:05:12.000Z
2021-06-16T16:11:41.000Z
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
26
2019-10-17T14:59:31.000Z
2022-02-07T17:06:30.000Z
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
7
2020-03-13T07:17:07.000Z
2022-03-29T07:58:37.000Z
#include <iostream> #include <random> #include <lsAdvect.hpp> #include <lsBooleanOperation.hpp> #include <lsConvexHull.hpp> #include <lsDomain.hpp> #include <lsExpand.hpp> #include <lsMakeGeometry.hpp> #include <lsPrune.hpp> #include <lsSmartPointer.hpp> #include <lsToDiskMesh.hpp> #include <lsToMesh.hpp> #include <lsToSurfaceMesh.hpp> #include <lsToVoxelMesh.hpp> #include <lsVTKWriter.hpp> /** 3D Example showing how to use the library for topography simulation. A hexagonal pattern of rounded cones is formed. These cones are then used as masks for etching. A uniform layer is then deposited on top creating voids in the structure. \example PatternedSubstrate.cpp */ // implement velocity field describing a directional etch class directionalEtch : public lsVelocityField<double> { public: double getScalarVelocity(const std::array<double, 3> & /*coordinate*/, int material, const std::array<double, 3> &normalVector, unsigned long /*pointId*/) { // etch directionally if (material > 0) { return (normalVector[2] > 0.) ? -normalVector[2] : 0; } else { return 0; } } std::array<double, 3> getVectorVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { return std::array<double, 3>({}); } }; // implement velocity field describing an isotropic deposition class isotropicDepo : public lsVelocityField<double> { public: double getScalarVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { // deposit isotropically everywhere return 1; } std::array<double, 3> getVectorVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { return std::array<double, 3>({}); } }; // create a rounded cone as the primitive pattern. // Define a pointcloud and create a hull mesh using lsConvexHull. void makeRoundCone(lsSmartPointer<lsMesh<>> mesh, hrleVectorType<double, 3> center, double radius, double height) { // cone is just a circle with a point above the center auto cloud = lsSmartPointer<lsPointCloud<double, 3>>::New(); // frist inside top point { hrleVectorType<double, 3> topPoint = center; topPoint[2] += height; cloud->insertNextPoint(topPoint); } // now create all points of the base unsigned numberOfBasePoints = 40; unsigned numberOfEdgePoints = 7; for (unsigned i = 0; i < numberOfBasePoints; ++i) { double angle = double(i) / double(numberOfBasePoints) * 2. * 3.141592; for (unsigned j = 1; j <= numberOfEdgePoints; ++j) { double distance = double(j) / double(numberOfEdgePoints) * radius; double pointHeight = std::sqrt(double(numberOfEdgePoints - j) / double(numberOfEdgePoints)) * height; double x = center[0] + distance * cos(angle); double y = center[1] + distance * sin(angle); cloud->insertNextPoint( hrleVectorType<double, 3>(x, y, center[2] + pointHeight)); } } lsConvexHull<double, 3>(mesh, cloud).apply(); } int main() { constexpr int D = 3; omp_set_num_threads(6); // scale in micrometers double coneDistance = 3.5; double xExtent = 21; double yConeDelta = std::sqrt(3) * coneDistance / 2; double yExtent = 6 * yConeDelta; double gridDelta = 0.15; double bounds[2 * D] = {-xExtent / 2., xExtent / 2., -yExtent / 2., yExtent / 2., -5, 5}; lsDomain<double, D>::BoundaryType boundaryCons[D]; boundaryCons[0] = lsDomain<double, D>::BoundaryType::PERIODIC_BOUNDARY; boundaryCons[1] = lsDomain<double, D>::BoundaryType::PERIODIC_BOUNDARY; boundaryCons[2] = lsDomain<double, D>::BoundaryType::INFINITE_BOUNDARY; auto substrate = lsSmartPointer<lsDomain<double, D>>::New(bounds, boundaryCons, gridDelta); { double origin[3] = {0., 0., 0.001}; double planeNormal[3] = {0., 0., 1.}; auto plane = lsSmartPointer<lsPlane<double, D>>::New(origin, planeNormal); lsMakeGeometry<double, D>(substrate, plane).apply(); } // copy the structure to add the pattern on top auto pattern = lsSmartPointer<lsDomain<double, D>>::New(bounds, boundaryCons, gridDelta); pattern->setLevelSetWidth(2); // Create varying cones and put them in hexagonal pattern --------- { std::cout << "Creating pattern..." << std::endl; // need to place cone one grid delta below surface to avoid rounding hrleVectorType<double, D> coneCenter(-xExtent / 2.0 + coneDistance / 2.0, -3 * yConeDelta, -gridDelta); double coneRadius = 1.4; double coneHeight = 1.5; // adjust since cone is slightly below the surface { double gradient = coneHeight / coneRadius; coneRadius += gridDelta / gradient; coneHeight += gridDelta * gradient; } // random radius cones double variation = 0.1; std::mt19937 gen(532132432); std::uniform_real_distribution<> dis(1 - variation, 1 + variation); // for each row for (unsigned j = 0; j < 6; ++j) { // for each cone in a row for (unsigned i = 0; i < 6; ++i) { // make ls from cone mesh and add to substrate auto cone = lsSmartPointer<lsDomain<double, D>>::New( bounds, boundaryCons, gridDelta); // create cone auto coneMesh = lsSmartPointer<lsMesh<>>::New(); makeRoundCone(coneMesh, coneCenter, coneRadius * dis(gen), coneHeight * dis(gen)); lsFromSurfaceMesh<double, D>(cone, coneMesh, false).apply(); lsBooleanOperation<double, D> boolOp(pattern, cone, lsBooleanOperationEnum::UNION); boolOp.apply(); // now shift mesh for next bool coneCenter[0] += coneDistance; } coneCenter[0] = -xExtent / 2. + ((j % 2) ? coneDistance / 2.0 : 0); coneCenter[1] += yConeDelta; } } lsBooleanOperation<double, D>(substrate, pattern, lsBooleanOperationEnum::UNION) .apply(); // Etch the substrate under the pattern --------------------------- unsigned numberOfEtchSteps = 30; std::cout << "Advecting" << std::endl; lsAdvect<double, D> advectionKernel; advectionKernel.insertNextLevelSet(pattern); advectionKernel.insertNextLevelSet(substrate); { auto velocities = lsSmartPointer<directionalEtch>::New(); advectionKernel.setVelocityField(velocities); // Now advect the level set, outputting every // advection step. Save the physical time that // passed during the advection. double passedTime = 0.; for (unsigned i = 0; i < numberOfEtchSteps; ++i) { std::cout << "\rEtch step " + std::to_string(i) + " / " << numberOfEtchSteps << std::flush; auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "substrate-" + std::to_string(i) + ".vtp") .apply(); advectionKernel.apply(); passedTime += advectionKernel.getAdvectedTime(); } std::cout << std::endl; { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "substrate-" + std::to_string(numberOfEtchSteps) + ".vtp") .apply(); } std::cout << "Time passed during directional etch: " << passedTime << std::endl; } // make disk mesh and output { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToDiskMesh<double, 3>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, lsFileFormatEnum::VTP, "diskMesh.vtp").apply(); } // Deposit new layer ---------------------------------------------- // new level set for new layer auto fillLayer = lsSmartPointer<lsDomain<double, D>>::New(substrate); { auto velocities = lsSmartPointer<isotropicDepo>::New(); advectionKernel.setVelocityField(velocities); advectionKernel.insertNextLevelSet(fillLayer); // stop advection in voids, which will form advectionKernel.setIgnoreVoids(true); double passedTime = 0.; unsigned numberOfDepoSteps = 30; for (unsigned i = 0; i < numberOfDepoSteps; ++i) { std::cout << "\rDepo step " + std::to_string(i) + " / " << numberOfDepoSteps << std::flush; auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>(mesh, "fillLayer-" + std::to_string(numberOfEtchSteps + 1 + i) + ".vtp") .apply(); advectionKernel.apply(); passedTime += advectionKernel.getAdvectedTime(); } std::cout << std::endl; { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>( mesh, "fillLayer-" + std::to_string(numberOfEtchSteps + numberOfDepoSteps) + ".vtp") .apply(); } std::cout << "Time passed during isotropic deposition: " << passedTime << std::endl; } // now output the final level sets { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "final-substrate.vtp").apply(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>(mesh, "final-fillLayer.vtp").apply(); } return 0; }
34.611684
80
0.606732
YourKarma42
2ca90626c2839ad729800f30daddb71e9c9d17de
699
cpp
C++
Math/PillaiFunction.cpp
igortakeo/Algorithms
6608132e442df7b0fb295aa63f287fa65a941939
[ "MIT" ]
null
null
null
Math/PillaiFunction.cpp
igortakeo/Algorithms
6608132e442df7b0fb295aa63f287fa65a941939
[ "MIT" ]
null
null
null
Math/PillaiFunction.cpp
igortakeo/Algorithms
6608132e442df7b0fb295aa63f287fa65a941939
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define pb push_back using namespace std; // Pillai's Arithmetical Function search result to for(i = 1 until n) sum += gcd(i, n) vector<int> Divisors(int n){ vector<int>v; for(int i=1; i*i <= n; i++){ if(n%i == 0){ v.pb(i); if(i != (n/i))v.pb(n/i); } } return v; } double phi(int n){ double totient = n; for(int i=2; i*i<=n; i++){ if(n%i == 0){ while(n%i == 0) n/=i; totient *= (1.0 -(1.0/(double)i)); } } if(n>1) totient *= (1.0 -(1.0/(double)n)); return totient; } int main(){ int n, ans = 0; cin >> n; vector<int> d = Divisors(n); for(auto a : d){ ans += a*phi(n/a); } cout << ans << endl; return 0; }
14.265306
87
0.515021
igortakeo
2caf4f07438e65cc804bea91704c942233c37e81
4,344
cpp
C++
Client/Client.cpp
laboox/Computer-Networks-CA3-S2015
1c6d6cd03be06c1978dda355bdeb2401d6d154d5
[ "MIT" ]
null
null
null
Client/Client.cpp
laboox/Computer-Networks-CA3-S2015
1c6d6cd03be06c1978dda355bdeb2401d6d154d5
[ "MIT" ]
null
null
null
Client/Client.cpp
laboox/Computer-Networks-CA3-S2015
1c6d6cd03be06c1978dda355bdeb2401d6d154d5
[ "MIT" ]
null
null
null
/** * File "Client.cpp" * Created by Sina on Sun May 31 13:39:03 2015. */ #include "Client.h" Client::Client(string name, address IP, address serverIp, int routerPort) : SuperClient(IP, serverIp, routerPort) { this->name = name; } void Client::run(){ fd_set router_fds, read_fds; FD_ZERO(&router_fds); FD_ZERO(&read_fds); FD_SET(0, &router_fds); FD_SET(routerFd, &router_fds); sh(routerFd); int max_fd = routerFd; while(true){ read_fds = router_fds; if(select(max_fd+1, &read_fds, NULL, NULL, NULL) < 0) throw Exeption("problem in sockets select!"); for(int client_fd=0; client_fd<=max_fd ; client_fd++) { try { if(FD_ISSET(client_fd , &read_fds)) { if(client_fd==0) { //cerr<<"in recive\n"; string cmd; getline(cin, cmd); parseCmd(cmd); } else if(client_fd==routerFd) { //cerr<<"sock recive\n"; Packet p; p.recive(routerFd); parsePacket(p); } } } catch(Exeption ex) { cout<<ex.get_error()<<endl; } } } } void Client::updateGroups(string data){ istringstream iss(data); string name, addr; while(iss>>name>>addr){ groups[name] = stringToAddr(addr); } } void Client::parsePacket(Packet p){ if(p.getType() == GET_GROUPS_LIST){ cout<<"Groups are:\n"; cout<<p.getDataStr(); updateGroups(p.getDataStr()); } else if(p.getType() == DATA){ //SuperClient::reciveUnicast(p); cout<<"Data: "<<p.getDataStr()<<endl; } else if(p.getType() == SHOW_MY_GROUPS){ cout<<"i'm in groups:\n"<<p.getDataStr()<<endl; } } void Client::parseCmd(string line){ string cmd0, cmd1, cmd2; istringstream iss(line); iss>>cmd0; if(cmd0=="Get"){ if(iss>>cmd1>>cmd2 && cmd1=="group" && cmd2=="list"){ getGroupList(); cout<<"group list request sent.\n"; } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Select"){ if(iss>>cmd1){ selectGroup(cmd1); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Join"){ if(iss>>cmd1){ joinGroup(cmd1); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Send"){ if(iss>>cmd1 && cmd1=="message"){ string message; getline(iss, message); sendMessage(message); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="Show"){ if(iss>>cmd1 && cmd1=="group"){ showGroup(); } else { throw Exeption("invalid cmd"); } } else if(cmd0=="SendUniCast"){ if(iss>>cmd1>>cmd2){ SuperClient::sendUnicast(stringToAddr(cmd1), cmd2); } else { throw Exeption("invalid cmd"); } } } void Client::sendMessage(string message){ if(selGroup == "") throw Exeption("no Group selected!\n"); Packet p; p.setType(SEND_MESSAGE); p.setSource(IP); p.setDest(groups[selGroup]); p.setData(message); p.send(routerFd); } void Client::getGroupList(){ Packet p; p.setType(GET_GROUPS_LIST); p.setSource(IP); p.setDest(serverIP); p.send(routerFd); } void Client::showGroup(){ Packet p; p.setType(SHOW_MY_GROUPS); p.setSource(IP); p.setDest(serverIP); p.send(routerFd); } void Client::selectGroup(string g){ if(groups.count(g)<=0) throw Exeption("Group does not exist"); selGroup = g; cout<<"group "<< g << " with ip " << addrToString( groups[g] ) <<" selected!\n"; } void Client::joinGroup(string g){ if(groups.count(g)<=0) throw Exeption("Group does not exist"); Packet p; p.setType(REQ_JOIN); p.setSource(IP); p.setDest(serverIP); p.setData(g); p.send(routerFd); cout<<"group "<< g << " with ip " << addrToString( groups[g] ) <<" joined!\n"; }
24.542373
84
0.508748
laboox
2cafb68262c344939433dd3300226cc9f8519380
7,369
cpp
C++
src/GoIO_cpp/GPortRef.cpp
lionel-rigoux/GoIO_SDK
ea7311d03dac554eceb830f70e2dcd273ae47459
[ "BSD-3-Clause" ]
3
2018-11-14T07:20:39.000Z
2021-12-20T20:32:48.000Z
src/GoIO_cpp/GPortRef.cpp
lionel-rigoux/GoIO_SDK
ea7311d03dac554eceb830f70e2dcd273ae47459
[ "BSD-3-Clause" ]
null
null
null
src/GoIO_cpp/GPortRef.cpp
lionel-rigoux/GoIO_SDK
ea7311d03dac554eceb830f70e2dcd273ae47459
[ "BSD-3-Clause" ]
3
2020-04-28T13:10:05.000Z
2021-12-20T13:32:12.000Z
/********************************************************************************* Copyright (c) 2010, Vernier Software & Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Vernier Software & Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VERNIER SOFTWARE & TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ // GPortRef.cpp #include "stdafx.h" #include "GPortRef.h" #include "GUtils.h" #include "GTextUtils.h" #ifdef _DEBUG #include "GPlatformDebug.h" // for DEBUG_NEW definition #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef LIB_NAMESPACE namespace LIB_NAMESPACE { #endif namespace { const cppstring k_sPortRefCode = "PortRef"; const cppstring k_sPortTypeCode = "PortType"; const cppstring k_sLocationCode = "Location"; const cppstring k_sDisplayNameCode = "DisplayName"; } // local namespace GPortRef &GPortRef::operator=(const GPortRef &source) { m_ePortType = source.GetPortType(); m_sLocation = source.GetLocation(); m_sDisplayName = source.GetDisplayName(); m_USBVendorID = source.GetUSBVendorID(); m_USBProductID = source.GetUSBProductID(); return *this; } GPortRef::GPortRef(const GPortRef & source) { m_ePortType = source.GetPortType(); m_sLocation = source.GetLocation(); m_sDisplayName = source.GetDisplayName(); m_USBVendorID = source.GetUSBVendorID(); m_USBProductID = source.GetUSBProductID(); } GPortRef & GPortRef::Assign(const GPortRef & src) { SetPortType(src.GetPortType()); SetLocation(src.GetLocation()); SetDisplayName(src.GetDisplayName()); SetUSBVendorID(src.GetUSBVendorID()); SetUSBProductID(src.GetUSBProductID()); return (*this); } void GPortRef::EncodeToString(cppstring * pOutString) { if (pOutString != NULL) { cppsstream ss; EncodeToStream(&ss); *pOutString = ss.str(); } } void GPortRef::EncodeToStream(cppostream * pOutStream) { // We use a single XML tag to encode the port ref to the stream. // The tag is self-terminating; all fields are attributes. // Note that the DECODE method does not require all fields to be // present and does not care about their order. // REVISIT - use GXMLUtils to just build an element an write it. if (pOutStream != NULL) { *pOutStream << GSTD_S("<") << k_sPortRefCode << GSTD_S(" "); *pOutStream << k_sPortTypeCode << GSTD_S("=\"") << GetPortType() << GSTD_S("\" "); *pOutStream << k_sLocationCode << GSTD_S("=\"") << GetLocation() << GSTD_S("\" "); *pOutStream << k_sDisplayNameCode << GSTD_S("=\"") << GetDisplayName() << GSTD_S("\" "); *pOutStream << "/>"; } } int GPortRef::DecodeFromString(const cppstring & sInString) { int nResult = kResponse_Error; cppstring::size_type nSearchStartPos = 0; cppstring::size_type nCurrentPos = 0; cppstring::size_type nNextPos = 0; cppstring::size_type nTestPos = 0; // ensure that we have a GPortRef tag... nSearchStartPos = sInString.find(k_sPortRefCode, 0); if (nSearchStartPos != cppstring::npos) nSearchStartPos += k_sPortRefCode.length(); if (nSearchStartPos >= sInString.length()) nSearchStartPos = cppstring::npos; if (nSearchStartPos != cppstring::npos) nTestPos = sInString.find_last_of('>'); if (nTestPos != cppstring::npos) { cppstring sSubStr; // decode port-type nCurrentPos = sInString.find(k_sPortTypeCode, nSearchStartPos); nCurrentPos += k_sPortTypeCode.length(); if (nCurrentPos < sInString.length()) nCurrentPos = sInString.find('\"', nCurrentPos); else nCurrentPos = cppstring::npos; if (nCurrentPos != cppstring::npos) nNextPos = nCurrentPos + 1; if (nNextPos != cppstring::npos) nNextPos = sInString.find('\"', nNextPos); if ( nCurrentPos != cppstring::npos && nNextPos != cppstring::npos && nCurrentPos < nNextPos) sSubStr = sInString.substr(nCurrentPos + 1, (nNextPos - nCurrentPos - 1)); if (sSubStr.length() > 0) m_ePortType = (EPortType) GTextUtils::CPPStringToLong(sSubStr.c_str()); sSubStr = GSTD_S(""); // decode location nCurrentPos = sInString.find(k_sLocationCode, nSearchStartPos); nCurrentPos += k_sLocationCode.length(); if (nCurrentPos < sInString.length()) nCurrentPos = sInString.find('\"', nCurrentPos); else nCurrentPos = cppstring::npos; if (nCurrentPos != cppstring::npos) nNextPos = nCurrentPos + 1; if (nNextPos != cppstring::npos) nNextPos = sInString.find('\"', nNextPos); if ( nCurrentPos != cppstring::npos && nNextPos != cppstring::npos && nCurrentPos < nNextPos) sSubStr = sInString.substr(nCurrentPos + 1, (nNextPos - nCurrentPos - 1)); if (sSubStr.length() > 0) m_sLocation = sSubStr; sSubStr = GSTD_S(""); // decode display-name nCurrentPos = sInString.find(k_sDisplayNameCode, nSearchStartPos); nCurrentPos += k_sDisplayNameCode.length(); if (nCurrentPos < sInString.length()) nCurrentPos = sInString.find('\"', nCurrentPos); else nCurrentPos = cppstring::npos; if (nCurrentPos != cppstring::npos) nNextPos = nCurrentPos + 1; if (nNextPos != cppstring::npos) nNextPos = sInString.find('\"', nNextPos); if (nCurrentPos != cppstring::npos && nNextPos != cppstring::npos && nCurrentPos < nNextPos) sSubStr = sInString.substr(nCurrentPos + 1, (nNextPos - nCurrentPos - 1)); if (sSubStr.length() > 0) m_sDisplayName = sSubStr; sSubStr = GSTD_S(""); } return nResult; } int GPortRef::DecodeFromStream(cppistream * pInStream) { // REVISIT - use GXMLUtils to extract the element int nResult = kResponse_Error; if (pInStream != NULL) { // Get the text from the in-stream up until the next ">"... cppstring sText; std::getline(*pInStream, sText, GSTD_S('>')); if (sText.length() > 0) { sText += GSTD_S('>'); nResult = DecodeFromString(sText); } } return nResult; } #ifdef LIB_NAMESPACE } #endif
33.495455
91
0.680825
lionel-rigoux
2cb6c94b694687676e30311e354d1d830ba7d363
421
hpp
C++
src/pattern-aggregator.hpp
Rutvik28/dfc
86ce00057c358f91d38826d3c36c95ad0d7b4b74
[ "MIT" ]
null
null
null
src/pattern-aggregator.hpp
Rutvik28/dfc
86ce00057c358f91d38826d3c36c95ad0d7b4b74
[ "MIT" ]
1
2019-09-19T21:31:36.000Z
2019-09-23T04:43:25.000Z
src/pattern-aggregator.hpp
skindstrom/dfc
4d7b9c29bc791c0a18a325478eafbeb459b48758
[ "MIT" ]
null
null
null
#ifndef DFC_PATTERN_AGGREGATOR_HPP #define DFC_PATTERN_AGGREGATOR_HPP #include <vector> #include "immutable-pattern.hpp" namespace dfc { class PatternAggregator { private: std::vector<RawPattern> patterns_; public: void add(RawPattern pat); std::vector<ImmutablePattern> aggregate(); private: void removeDuplicates(); std::vector<ImmutablePattern> createPatterns() const; }; } // namespace dfc #endif
17.541667
55
0.760095
Rutvik28
2cb925922e5aab8253a8ee29367255f1a2b29f6b
8,461
cpp
C++
CocosWidget/Slider.cpp
LingJiJian/Tui-x
e00e79109db466143ed2b399a8991be4e5fea28f
[ "MIT" ]
67
2015-02-09T03:20:59.000Z
2022-01-17T05:53:07.000Z
CocosWidget/Slider.cpp
fuhongxue/Tui-x
9b288540a36942dd7f3518dc3e12eb2112bd93b0
[ "MIT" ]
3
2015-04-14T01:47:27.000Z
2016-03-15T06:56:04.000Z
CocosWidget/Slider.cpp
fuhongxue/Tui-x
9b288540a36942dd7f3518dc3e12eb2112bd93b0
[ "MIT" ]
34
2015-02-18T04:42:07.000Z
2019-08-15T05:34:46.000Z
/**************************************************************************** Copyright (c) 2014 Lijunlin - Jason lee Created by Lijunlin - Jason lee on 2014 [email protected] http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "Slider.h" NS_CC_WIDGET_BEGIN CSlider::CSlider() : m_pSlider(NULL) , m_bDrag(false) { setThisObject(this); } CSlider::~CSlider() { } CSlider* CSlider::create() { CSlider* pRet = new CSlider(); if( pRet && pRet->init() ) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } CSlider* CSlider::create(const char* pSlider, const char* pProgress) { CSlider* pRet = new CSlider(); if( pRet && pRet->initWithSlider(pSlider, pProgress) ) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } bool CSlider::initWithSlider(const char* pSlider, const char* pProgress) { setSliderImage(pSlider); if( initWithFile(pProgress) ) { return true; } return false; } CSlider* CSlider::createSpriteFrame(const char* pSlider, const char* pProgress) { CSlider* pRet = new CSlider(); if (pRet && pRet->initWithSliderSpriteFrame(pSlider, pProgress)) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } bool CSlider::initWithSliderSpriteFrame(const char* pSlider, const char* pProgress) { setSliderSpriteFrameName(pSlider); if (initWithFileSpriteFrame(pProgress)) { return true; } return false; } void CSlider::setContentSize(const Size& tSize) { if( m_pSlider && m_pProgressSprite ) { const Size& tSliderSize = m_pSlider->getContentSize(); Size tTargetSize; tTargetSize.width = m_tProgressSize.width + tSliderSize.width; tTargetSize.height = m_tProgressSize.height + tSliderSize.height; CProgressBar::setContentSize(tTargetSize); return; } CProgressBar::setContentSize(tSize); } int CSlider::valueFromPercent(float fPercentage) { return (int)(fPercentage * m_nMaxValue); } int CSlider::valueFromPoint(const Vec2& tPoint) { int nRet = 0; switch( m_eDirection ) { case eProgressBarDirectionLeftToRight: { float fHalfWidth = m_tProgressSize.width / 2; if( tPoint.x < m_tCenterPoint.x - fHalfWidth ) { nRet = m_nMinValue; break; } if( tPoint.x > m_tCenterPoint.x + fHalfWidth ) { nRet = m_nMaxValue; break; } float fStartPoint = tPoint.x - (m_tCenterPoint.x - fHalfWidth); float fPercentage = fStartPoint / m_tProgressSize.width; nRet = valueFromPercent(fPercentage); } break; case eProgressBarDirectionRightToLeft: { float fHalfWidth = m_tProgressSize.width / 2; if( tPoint.x < m_tCenterPoint.x - fHalfWidth ) { nRet = m_nMaxValue; break; } if( tPoint.x > m_tCenterPoint.x + fHalfWidth ) { nRet = m_nMinValue; break; } float fStartPoint = tPoint.x - (m_tCenterPoint.x - fHalfWidth); float fPercentage = (m_tProgressSize.width - fStartPoint) / m_tProgressSize.width; nRet = valueFromPercent(fPercentage); } break; case eProgressBarDirectionBottomToTop: { float fHalfHeight = m_tProgressSize.height / 2; if( tPoint.y < m_tCenterPoint.y - fHalfHeight ) { nRet = m_nMinValue; break; } if( tPoint.y > m_tCenterPoint.y + fHalfHeight ) { nRet = m_nMaxValue; break; } float fStartPoint = tPoint.y - (m_tCenterPoint.y - fHalfHeight); float fPercentage = fStartPoint / m_tProgressSize.height; nRet = valueFromPercent(fPercentage); } break; case eProgressBarDirectionTopToBottom: { float fHalfHeight = m_tProgressSize.height / 2; if( tPoint.y < m_tCenterPoint.y - fHalfHeight ) { nRet = m_nMaxValue; break; } if( tPoint.y > m_tCenterPoint.y + fHalfHeight ) { nRet = m_nMinValue; break; } float fStartPoint = tPoint.y - (m_tCenterPoint.y - fHalfHeight); float fPercentage = (m_tProgressSize.height - fStartPoint) / m_tProgressSize.height; nRet = valueFromPercent(fPercentage); } break; default: break; } return nRet; } CWidgetTouchModel CSlider::onTouchBegan(Touch *pTouch) { m_bDrag = m_pSlider->getBoundingBox().containsPoint( convertToNodeSpace(pTouch->getLocation()) ); if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); return eWidgetTouchSustained; } return eWidgetTouchNone; } void CSlider::onTouchMoved(Touch *pTouch, float fDuration) { if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); } } void CSlider::onTouchEnded(Touch *pTouch, float fDuration) { if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); } } void CSlider::onTouchCancelled(Touch *pTouch, float fDuration) { if( m_bDrag ) { changeValueAndExecuteEvent(valueFromPoint(convertToNodeSpace(pTouch->getLocation())), true); } } void CSlider::pointFromValue(int nValue, Vec2& tOutPoint) { float fPercentage = getPercentage(); switch( m_eDirection ) { case eProgressBarDirectionLeftToRight: { tOutPoint.x = m_tProgressSize.width * fPercentage + (m_tCenterPoint.x - m_tProgressSize.width / 2); tOutPoint.y = m_tCenterPoint.y; } break; case eProgressBarDirectionRightToLeft: { tOutPoint.x = m_tProgressSize.width - (m_tProgressSize.width * fPercentage) + (m_tCenterPoint.x - m_tProgressSize.width / 2); tOutPoint.y = m_tCenterPoint.y; } break; case eProgressBarDirectionBottomToTop: { tOutPoint.x = m_tCenterPoint.x; tOutPoint.y = m_tProgressSize.height * fPercentage + (m_tCenterPoint.y - m_tProgressSize.height / 2); } break; case eProgressBarDirectionTopToBottom: { tOutPoint.x = m_tCenterPoint.x; tOutPoint.y = m_tProgressSize.height - (m_tProgressSize.height * fPercentage) + (m_tCenterPoint.y - m_tProgressSize.height / 2); } break; default: break; } } void CSlider::changeValueAndExecuteEvent(int nValue, bool bExeEvent) { CProgressBar::changeValueAndExecuteEvent(nValue, bExeEvent); if( m_pSlider ) { Vec2 tOutPoint; pointFromValue(m_nValue, tOutPoint); m_pSlider->setPosition(tOutPoint); } } void CSlider::setSliderImage(const char* pFile) { if( pFile && strlen(pFile) ) { Texture2D* pTexture = Director::getInstance()->getTextureCache()->addImage(pFile); setSliderTexture(pTexture); } } void CSlider::setSliderTexture(Texture2D* pTexture) { if( m_pSlider ) { m_pSlider->setTexture(pTexture); Rect tRect = Rect::ZERO; tRect.size = pTexture->getContentSize(); m_pSlider->setTextureRect(tRect); } else { m_pSlider = Sprite::createWithTexture(pTexture); addChild(m_pSlider, 2); } setContentSize(_contentSize); } void CSlider::setSliderSpriteFrame(SpriteFrame* pFrame) { if( pFrame ) { if( m_pSlider ) { m_pSlider->setSpriteFrame(pFrame); } else { m_pSlider = Sprite::createWithSpriteFrame(pFrame); addChild(m_pSlider,2); } } setContentSize(_contentSize); } void CSlider::setValue( int nValue ) { changeValueAndExecuteEvent(nValue, true); } void CSlider::setSliderSpriteFrameName(const char* pSpriteName) { SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(pSpriteName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; sprintf(msg, "Invalid spriteFrameName: %s", pSpriteName); CCAssert(pFrame != NULL, msg); #endif return setSliderSpriteFrame(pFrame); } NS_CC_WIDGET_END
23.372928
131
0.714336
LingJiJian
2cbcbf06bc2d170744d660890740960491444f2d
871
c++
C++
9.1.two.arrays.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
9.1.two.arrays.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
9.1.two.arrays.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r",stdin); freopen("output.txt","w", stdout); #endif int n,m; cin>>n>>m; int arr[n][m]; for( int i=0; i<n;i++){ for(int j=0;j<m;j++){ cin>>arr[i][j]; } } cout<<"Matrix is:\n"; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cout<<arr[i][j]<<" "; } cout<<"\n"; } int x; cin>>x; bool flag=false; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(arr[i][j]==x){ cout<<i<<" "<<j<<"\n"; flag=true; } } } if(flag){ cout<<"Element is found\n"; }else{ cout<<"Element is not found\n"; } return 0; }
15.836364
38
0.375431
Sambitcr-7
2cbcc094d6d3489ff9636dc69edb9fcf8f692dd4
9,380
cpp
C++
test/src/generators.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
1
2020-02-19T13:13:10.000Z
2020-02-19T13:13:10.000Z
test/src/generators.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
null
null
null
test/src/generators.cpp
BeatWolf/etl
32e8153b38e0029176ca4fe2395b7fa6babe3189
[ "MIT" ]
null
null
null
//======================================================================= // Copyright (c) 2014-2018 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" /// sequence_generator TEMPLATE_TEST_CASE_2("sequence/fast_vector_1", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b[0], 0.0); REQUIRE_EQUALS(b[1], 1.0); REQUIRE_EQUALS(b[2], 2.0); } TEMPLATE_TEST_CASE_2("sequence/fast_vector_2", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::sequence_generator<Z>(99); REQUIRE_EQUALS(b[0], 99.0); REQUIRE_EQUALS(b[1], 100.0); REQUIRE_EQUALS(b[2], 101.0); } TEMPLATE_TEST_CASE_2("sequence/fast_vector_3", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::sequence_generator<Z>(99); REQUIRE_EQUALS(b[0], 99.0); REQUIRE_EQUALS(b[1], 100.0); REQUIRE_EQUALS(b[2], 101.0); } TEMPLATE_TEST_CASE_2("sequence/fast_vector_4", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = 0.5 * etl::sequence_generator<Z>(99.0); REQUIRE_EQUALS(b[0], 49.5); REQUIRE_EQUALS(b[1], 50.0); REQUIRE_EQUALS(b[2], 50.5); } TEMPLATE_TEST_CASE_2("sequence/fast_matrix_1", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b(0, 0), 0.0); REQUIRE_EQUALS(b(0, 1), 1.0); REQUIRE_EQUALS(b(1, 0), 2.0); REQUIRE_EQUALS(b(1, 1), 3.0); REQUIRE_EQUALS(b(2, 0), 4.0); REQUIRE_EQUALS(b(2, 1), 5.0); } TEMPLATE_TEST_CASE_2("sequence/fast_matrix_2", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = 0.1 * etl::sequence_generator<Z>(); REQUIRE_DIRECT(etl::decay_traits<decltype(0.1 * etl::sequence_generator())>::is_generator); REQUIRE_EQUALS_APPROX(b(0, 0), 0.0); REQUIRE_EQUALS_APPROX(b(0, 1), 0.1); REQUIRE_EQUALS_APPROX(b(1, 0), 0.2); REQUIRE_EQUALS_APPROX(b(1, 1), 0.3); REQUIRE_EQUALS_APPROX(b(2, 0), 0.4); REQUIRE_EQUALS_APPROX(b(2, 1), 0.5); } TEMPLATE_TEST_CASE_2("sequence/fast_matrix_3", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b(1.0); b = 0.1 * etl::sequence_generator<Z>() + b; REQUIRE_EQUALS_APPROX(b(0, 0), 1.0); REQUIRE_EQUALS_APPROX(b(0, 1), 1.1); REQUIRE_EQUALS_APPROX(b(1, 0), 1.2); REQUIRE_EQUALS_APPROX(b(1, 1), 1.3); REQUIRE_EQUALS_APPROX(b(2, 0), 1.4); REQUIRE_EQUALS_APPROX(b(2, 1), 1.5); } TEMPLATE_TEST_CASE_2("sequence/dyn_vector_1", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b[0], 0.0); REQUIRE_EQUALS(b[1], 1.0); REQUIRE_EQUALS(b[2], 2.0); } TEMPLATE_TEST_CASE_2("sequence/dyn_vector_2", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::sequence_generator<Z>(); REQUIRE_EQUALS(b[0], 0.0); REQUIRE_EQUALS(b[1], 1.0); REQUIRE_EQUALS(b[2], 2.0); } TEMPLATE_TEST_CASE_2("sequence/dyn_matrix_1", "generator", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::sequence_generator<Z>() >> 2.0; REQUIRE_EQUALS(b(0, 0), 0.0); REQUIRE_EQUALS(b(0, 1), 2.0); REQUIRE_EQUALS(b(1, 0), 4.0); REQUIRE_EQUALS(b(1, 1), 6.0); REQUIRE_EQUALS(b(2, 0), 8.0); REQUIRE_EQUALS(b(2, 1), 10.0); } /// normal_generator //Simply ensures that it compiles TEMPLATE_TEST_CASE_2("normal/fast_vector_1", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("normal/fast_matrix_1", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = etl::normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("normal/dyn_vector_1", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::normal_generator<Z>() >> etl::normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("normal/dyn_matrix_1", "generator", Z, float, double) { etl::dyn_matrix<Z> b(3, 5); b = etl::normal_generator<Z>(); } /// truncated_normal_generator //Simply ensures that it compiles TEMPLATE_TEST_CASE_2("truncated_normal/fast_vector_1", "generator", Z, float, double) { etl::fast_vector<Z, 3> b; b = etl::truncated_normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("truncated_normal/fast_matrix_1", "generator", Z, float, double) { etl::fast_matrix<Z, 3, 2> b; b = etl::truncated_normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("truncated_normal/dyn_vector_1", "generator", Z, float, double) { etl::dyn_vector<Z> b(3); b = etl::truncated_normal_generator<Z>(); } TEMPLATE_TEST_CASE_2("truncated_normal/dyn_matrix_1", "generator", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::truncated_normal_generator<Z>(); } /// uniform_generator TEMPLATE_TEST_CASE_2("generators/uniform/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::uniform_generator<Z>(-2.0, +2.0); for (auto value : b) { REQUIRE_DIRECT(value >= -2.0); REQUIRE_DIRECT(value <= +2.0); } } TEMPLATE_TEST_CASE_2("generators/uniform/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::uniform_generator<Z>(5.5, 8.0); for (auto value : b) { REQUIRE_DIRECT(value >= 5.5); REQUIRE_DIRECT(value <= 8.0); } } TEMPLATE_TEST_CASE_2("generators/uniform/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::uniform_generator<Z>(1.0, 2.0) >> 4.0; for (auto value : b) { REQUIRE_DIRECT(value >= 4.0); REQUIRE_DIRECT(value <= 8.0); } } /// dropout_mask TEMPLATE_TEST_CASE_2("generators/dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } /// state_dropout_mask TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); auto dropout = etl::state_dropout_mask<Z>(0.5); b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0)); } } TEMPLATE_TEST_CASE_2("generators/state_dropout_mask/4", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); auto dropout = etl::state_dropout_mask<Z>(0.5); b = (dropout * 0.5f) + 1.0f; for (auto value : b) { REQUIRE_DIRECT(value == Z(1.0) || value == Z(1.5)); } } /// inverted_dropout_mask TEMPLATE_TEST_CASE_2("generators/inverted_dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::inverted_dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0 / 0.8)); } } TEMPLATE_TEST_CASE_2("generators/inverted_dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::inverted_dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.0 / 0.5)); } } TEMPLATE_TEST_CASE_2("generators/inverted_dropout_mask/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::inverted_dropout_mask<Z>(0.5) >> 2.0; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0 / 0.5)); } } /// state_inverted_dropout_mask TEMPLATE_TEST_CASE_2("generators/state_inverted_dropout_mask/1", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_inverted_dropout_mask<Z>(0.2); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(1.25)); } } TEMPLATE_TEST_CASE_2("generators/state_inverted_dropout_mask/2", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); b = etl::state_inverted_dropout_mask<Z>(0.5); for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0)); } } TEMPLATE_TEST_CASE_2("generators/state_inverted_dropout_mask/3", "uniform", Z, float, double) { etl::dyn_matrix<Z> b(3, 2); auto dropout = etl::state_inverted_dropout_mask<Z>(0.5); b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0)); } b = dropout; for (auto value : b) { REQUIRE_DIRECT(value == Z(0.0) || value == Z(2.0)); } }
25.911602
95
0.6129
BeatWolf
2cc1a61317e22d15fc9f4f103cf81cd7de2522bf
1,063
cpp
C++
src/render/OGL2_0/CIndexBufferOGL2_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
4
2015-08-13T08:25:36.000Z
2017-04-07T21:33:10.000Z
src/render/OGL2_0/CIndexBufferOGL2_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
src/render/OGL2_0/CIndexBufferOGL2_0.cpp
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
// // CIndexBufferOGL2_0.h // OpenJam // // Created by Yevgeniy Logachev // Copyright (c) 2014 yev. All rights reserved. // #if defined(RENDER_OGL2_0) #include "CIndexBufferOGL2_0.h" using namespace jam; // ***************************************************************************** // Constants // ***************************************************************************** // ***************************************************************************** // Public Methods // ***************************************************************************** CIndexBufferOGL2_0::CIndexBufferOGL2_0() { } CIndexBufferOGL2_0::~CIndexBufferOGL2_0() { } // ***************************************************************************** // Protected Methods // ***************************************************************************** // ***************************************************************************** // Private Methods // ***************************************************************************** #endif /* defined(RENDER_OGL2_0) */
27.25641
80
0.281279
opengamejam
2cc2880daa8fb8d10a2c84b8b5d42d91dba386af
9,740
cpp
C++
test/test_unscented_transform.cpp
MartinEekGerhardsen/bayes-filter-cpp
fb734811a2eed1339616e95f70c42b988ef7719f
[ "MIT" ]
8
2018-06-27T13:10:45.000Z
2022-01-25T02:57:54.000Z
test/test_unscented_transform.cpp
MartinEekGerhardsen/bayes-filter-cpp
fb734811a2eed1339616e95f70c42b988ef7719f
[ "MIT" ]
null
null
null
test/test_unscented_transform.cpp
MartinEekGerhardsen/bayes-filter-cpp
fb734811a2eed1339616e95f70c42b988ef7719f
[ "MIT" ]
3
2020-08-20T03:00:13.000Z
2022-01-04T10:11:16.000Z
/* * test_unscented_transform.cpp * * Created on: 12 Jun 2018 * Author: Fabian Meyer */ #include "bayes_filter/unscented_transform.h" #include "eigen_assert.h" #include <catch.hpp> using namespace bf; using namespace std::placeholders; static Eigen::VectorXd linearTransform( const Eigen::VectorXd &state, const Eigen::VectorXd &facs) { assert(state.rows() == facs.rows()); Eigen::VectorXd result(state.size()); for(unsigned int i = 0; i < state.rows(); ++i) result(i) = state(i) * facs(i); return result; } static Eigen::MatrixXd linearTransformCov( const Eigen::MatrixXd &cov, const Eigen::VectorXd &facs) { assert(cov.rows() == facs.rows()); Eigen::MatrixXd result; result.setZero(cov.rows(), cov.cols()); for(unsigned int i = 0; i < cov.rows(); ++i) result(i, i) = cov(i, i) * facs(i) * facs(i); return result; } static SigmaPoints linearTransformSig( SigmaPoints &sigma, const Eigen::VectorXd &facs) { assert(facs.rows() == sigma.points.rows()); SigmaPoints result; result = sigma; for(unsigned int i = 0; i < sigma.points.cols(); ++i) { result.points.col(i) = linearTransform(result.points.col(i), facs); } return result; } TEST_CASE("Unscented Transform") { /* ===================================================================== * Sigma Points * ===================================================================== */ SECTION("calculate sigma points") { const double eps = 1e-6; UnscentedTransform trans; SECTION("with simple params") { trans.setAlpha(1.0); trans.setBeta(1.0); trans.setKappa(1.0); Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; Eigen::MatrixXd wexp(2, 7); wexp << 0.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 1.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125; Eigen::MatrixXd sexp(3, 7); sexp << 1, 3, 1, 1, -1, 1, 1, 1, 1, 3, 1, 1, -1, 1, 1, 1, 1, 3, 1, 1, -1; SigmaPoints sigma; trans.calcSigmaPoints(state, cov, sigma); REQUIRE(trans.calcLambda(state.size()) == Approx(1.0).margin(eps)); REQUIRE_MAT(wexp, sigma.weights, eps); REQUIRE_MAT(sexp, sigma.points, eps); } SECTION("with different params") { trans.setAlpha(1.0); trans.setBeta(2.0); trans.setKappa(2.0); Eigen::VectorXd state(2); state << 1, 1; Eigen::MatrixXd cov(2, 2); cov << 1, 0, 0, 1; Eigen::MatrixXd wexp(2, 5); wexp << 0.5, 0.125, 0.125, 0.125, 0.125, 2.5, 0.125, 0.125, 0.125, 0.125; Eigen::MatrixXd sexp(2, 5); sexp << 1, 3, 1, -1, 1, 1, 1, 3, 1, -1; SigmaPoints sigma; trans.calcSigmaPoints(state, cov, sigma); REQUIRE(trans.calcLambda(state.size()) == Approx(2.0).margin(eps)); REQUIRE_MAT(wexp, sigma.weights, eps); REQUIRE_MAT(sexp, sigma.points, eps); } SECTION("with zero uncertainty") { trans.setAlpha(1.0); trans.setBeta(1.0); trans.setKappa(1.0); Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 0, 0, 0, 0, 0; Eigen::MatrixXd wexp(2, 7); wexp << 0.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 1.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125; Eigen::MatrixXd sexp(3, 7); sexp << 1, 3, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1; SigmaPoints sigma; trans.calcSigmaPoints(state, cov, sigma); REQUIRE(trans.calcLambda(state.size()) == Approx(1.0).margin(eps)); REQUIRE_MAT(wexp, sigma.weights, eps); REQUIRE_MAT(sexp, sigma.points, eps); } } /* ===================================================================== * Recover Distribution * ===================================================================== */ SECTION("recover distribution") { const double eps = 1e-6; UnscentedTransform trans; SECTION("with identity transform") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } SECTION("with identity transform and near zero uncertainty") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1e-16, 0, 0, 0, 1, 0, 0, 0, 1e-16; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } SECTION("with linear transform") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; Eigen::VectorXd facs(3); facs << 1, 2, 3; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); sigma = linearTransformSig(sigma, facs); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); state = linearTransform(state, facs); cov = linearTransformCov(cov, facs); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } SECTION("with linear transform and near zero uncertainty") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1e-16, 0, 0, 0, 1, 0, 0, 0, 1e-16; Eigen::VectorXd facs(3); facs << 1, 2, 3; SigmaPoints sigma; Eigen::VectorXd actMu; Eigen::MatrixXd actCov; trans.calcSigmaPoints(state, cov, sigma); sigma = linearTransformSig(sigma, facs); trans.recoverMean(sigma, actMu); trans.recoverCovariance(sigma, actMu, actCov); state = linearTransform(state, facs); cov = linearTransformCov(cov, facs); REQUIRE_MAT(state, actMu, eps); REQUIRE_MAT(cov, actCov, eps); } } /* ===================================================================== * Cross Covariance * ===================================================================== */ SECTION("caclulate cross covariance") { const double eps = 1e-6; UnscentedTransform trans; SECTION("with identity transform") { Eigen::VectorXd state(3); state << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; SigmaPoints sigma; Eigen::MatrixXd actCrossCov; trans.calcSigmaPoints(state, cov, sigma); trans.recoverCrossCorrelation(sigma, state, sigma, state, actCrossCov); REQUIRE_MAT(cov, actCrossCov, eps); } SECTION("with linear transform") { Eigen::VectorXd state1(3); state1 << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1, 0, 0, 0, 1, 0, 0, 0, 1; Eigen::VectorXd facs(3); facs << 1, 2, 3; Eigen::VectorXd state2 = linearTransform(state1, facs); Eigen::MatrixXd crossCov(3, 3); crossCov << 1, 0, 0, 0, 2, 0, 0, 0, 3; SigmaPoints sigma1; SigmaPoints sigma2; Eigen::MatrixXd actCrossCov; trans.calcSigmaPoints(state1, cov, sigma1); sigma2 = linearTransformSig(sigma1, facs); trans.recoverCrossCorrelation(sigma1, state1, sigma2, state2, actCrossCov); REQUIRE_MAT(crossCov, actCrossCov, eps); } SECTION("with linear transform and near zero uncertainty") { Eigen::VectorXd state1(3); state1 << 1, 1, 1; Eigen::MatrixXd cov(3, 3); cov << 1e-16, 0, 0, 0, 1, 0, 0, 0, 1e-16; Eigen::VectorXd facs(3); facs << 1, 2, 3; Eigen::VectorXd state2 = linearTransform(state1, facs); Eigen::MatrixXd crossCov(3, 3); crossCov << 0, 0, 0, 0, 2, 0, 0, 0, 0; SigmaPoints sigma1; SigmaPoints sigma2; Eigen::MatrixXd actCrossCov; trans.calcSigmaPoints(state1, cov, sigma1); sigma2 = linearTransformSig(sigma1, facs); trans.recoverCrossCorrelation(sigma1, state1, sigma2, state2, actCrossCov); REQUIRE_MAT(crossCov, actCrossCov, eps); } } }
30.342679
80
0.489322
MartinEekGerhardsen
2cc4c8b4378b4d8b9f4621e2b5599b8ee8d786d2
447
cpp
C++
headers/10-throw1.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
1
2022-03-07T09:14:07.000Z
2022-03-07T09:14:07.000Z
headers/10-throw1.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
null
null
null
headers/10-throw1.cpp
cpp-tutor/learnmoderncpp-tutorial
96ca86a2508c80093f51f8ac017f41a994d04d52
[ "MIT" ]
null
null
null
// 10-throw1.cpp : simple exception demonstration, throw and catch #include <iostream> #include <exception> using namespace std; template <typename T> void getInteger(T& value) { cout << "Please enter an integer (0 to throw): "; cin >> value; if (!value) { throw exception{}; } } int main() { long long v{}; try { getInteger(v); } catch (...) { cerr << "Caught exception!\n"; return 1; } cout << "Got value: " << v << '\n'; }
16.555556
66
0.612975
cpp-tutor
2cc77442f3f1ac290fd662ee4c3e018d2c6df545
4,664
cpp
C++
libraries/vulkan_utils/private/VulkanMemory.cpp
jcelerier/scop_vulkan
9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0
[ "MIT" ]
132
2021-04-04T21:19:46.000Z
2022-03-13T13:47:00.000Z
libraries/vulkan_utils/private/VulkanMemory.cpp
jcelerier/scop_vulkan
9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0
[ "MIT" ]
null
null
null
libraries/vulkan_utils/private/VulkanMemory.cpp
jcelerier/scop_vulkan
9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0
[ "MIT" ]
7
2021-04-04T21:19:48.000Z
2021-04-09T09:16:34.000Z
#include "VulkanMemory.hpp" #include <stdexcept> #include <cstring> #include "VulkanCommandBuffer.hpp" uint32_t findMemoryType(VkPhysicalDevice physical_device, uint32_t type_filter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties mem_prop; vkGetPhysicalDeviceMemoryProperties(physical_device, &mem_prop); for (uint32_t i = 0; i < mem_prop.memoryTypeCount; i++) { if (type_filter & (1 << i) && ((mem_prop.memoryTypes[i].propertyFlags & properties) == properties)) { return i; } } throw std::runtime_error("VkMemory: Failed to get memory type"); } void createBuffer(VkDevice device, VkBuffer &buffer, VkDeviceSize size, VkBufferUsageFlags usage) { VkBufferCreateInfo buffer_info{}; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.size = size; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &buffer_info, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("VkMemory: Failed to create buffer"); } } void allocateBuffer(VkPhysicalDevice physical_device, VkDevice device, VkBuffer &buffer, VkDeviceMemory &buffer_memory, VkMemoryPropertyFlags properties) { VkMemoryRequirements mem_requirement; vkGetBufferMemoryRequirements(device, buffer, &mem_requirement); VkMemoryAllocateInfo alloc_info{}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = mem_requirement.size; alloc_info.memoryTypeIndex = findMemoryType( physical_device, mem_requirement.memoryTypeBits, properties); if (vkAllocateMemory(device, &alloc_info, nullptr, &buffer_memory) != VK_SUCCESS) { throw std::runtime_error("VkMemory: Failed to allocate memory"); } vkBindBufferMemory(device, buffer, buffer_memory, 0); } void copyBufferOnGpu(VkDevice device, VkCommandPool command_pool, VkQueue gfx_queue, VkBuffer dst_buffer, VkBuffer src_buffer, VkDeviceSize size) { VkCommandBuffer cmd_buffer = beginSingleTimeCommands(device, command_pool); VkBufferCopy copy_region{}; copy_region.size = size; copy_region.dstOffset = 0; copy_region.srcOffset = 0; vkCmdCopyBuffer(cmd_buffer, src_buffer, dst_buffer, 1, &copy_region); endSingleTimeCommands(device, command_pool, cmd_buffer, gfx_queue); } void copyBufferOnGpu(VkDevice device, VkCommandPool command_pool, VkQueue gfx_queue, VkBuffer dst_buffer, VkBuffer src_buffer, VkBufferCopy copy_region) { VkCommandBuffer cmd_buffer = beginSingleTimeCommands(device, command_pool); vkCmdCopyBuffer(cmd_buffer, src_buffer, dst_buffer, 1, &copy_region); endSingleTimeCommands(device, command_pool, cmd_buffer, gfx_queue); } void copyOnCpuCoherentMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, void const *dataToCopy) { void *mapped_data{}; vkMapMemory(device, memory, offset, size, 0, &mapped_data); memcpy(mapped_data, dataToCopy, size); vkUnmapMemory(device, memory); } void copyCpuBufferToGpu(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue queue, VkBuffer dstBuffer, void *srcData, VkBufferCopy copyRegion) { // Staging buffer on CPU VkBuffer staging_buffer{}; VkDeviceMemory staging_buffer_memory{}; createBuffer(device, staging_buffer, copyRegion.size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); allocateBuffer(physicalDevice, device, staging_buffer, staging_buffer_memory, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); // Copy on staging buffer copyOnCpuCoherentMemory( device, staging_buffer_memory, 0, copyRegion.size, srcData); // Copy on GPU copyBufferOnGpu( device, commandPool, queue, dstBuffer, staging_buffer, copyRegion); // Cleaning vkDestroyBuffer(device, staging_buffer, nullptr); vkFreeMemory(device, staging_buffer_memory, nullptr); }
31.727891
79
0.65416
jcelerier
2cc81dc413167b8d02de7c92c789bfdbe81d834d
816
hpp
C++
src/monitors/probes/list.hpp
owenmylotte/ablate
92b190a2d422eb89748338c04fd7b29976be54b1
[ "BSD-3-Clause" ]
null
null
null
src/monitors/probes/list.hpp
owenmylotte/ablate
92b190a2d422eb89748338c04fd7b29976be54b1
[ "BSD-3-Clause" ]
null
null
null
src/monitors/probes/list.hpp
owenmylotte/ablate
92b190a2d422eb89748338c04fd7b29976be54b1
[ "BSD-3-Clause" ]
null
null
null
#ifndef ABLATELIBRARY_PROBEINITIALIZER_LIST_HPP #define ABLATELIBRARY_PROBEINITIALIZER_LIST_HPP #include <memory> #include <vector> #include "probeInitializer.hpp" namespace ablate::monitors::probes { class List : public ProbeInitializer { private: const std::vector<Probe> list; public: /** * default list of probe monitors, useful for the parser init * @param probes */ explicit List(const std::vector<std::shared_ptr<Probe>>& probes); /** * list of probe monitors * @param probes */ explicit List(std::vector<Probe> probes); /** * list of probe locations with names * @return */ const std::vector<Probe>& GetProbes() const override { return list; } }; } // namespace ablate::monitors::probes #endif // ABLATELIBRARY_LIST_HPP
22.666667
73
0.675245
owenmylotte
2cc82bfa7ec04687ec56f78e45d1b268fc14af9c
8,688
cpp
C++
tests/tria/math/quat_test.cpp
BastianBlokland/tria
a90c1a1b0cc9479b1e3a1c41aa5286571a8aab78
[ "MIT" ]
null
null
null
tests/tria/math/quat_test.cpp
BastianBlokland/tria
a90c1a1b0cc9479b1e3a1c41aa5286571a8aab78
[ "MIT" ]
null
null
null
tests/tria/math/quat_test.cpp
BastianBlokland/tria
a90c1a1b0cc9479b1e3a1c41aa5286571a8aab78
[ "MIT" ]
null
null
null
#include "catch2/catch.hpp" #include "tria/math/mat.hpp" #include "tria/math/quat.hpp" #include "tria/math/quat_io.hpp" #include "tria/math/utils.hpp" #include "tria/math/vec.hpp" namespace tria::math::tests { TEST_CASE("[math] - Quat", "[math]") { SECTION("Quaternions are fixed size") { auto q1 = Quatf{}; CHECK(sizeof(q1) == sizeof(float) * 4); auto q2 = Quat<double>{}; CHECK(sizeof(q2) == sizeof(double) * 4); } SECTION("Quaternions can be reassigned") { auto q = Quatf{}; q = identityQuatf(); CHECK(q[0] == 0); CHECK(q[1] == 0); CHECK(q[2] == 0); CHECK(q[3] == 1); } SECTION("Quaternions can be checked for equality") { CHECK(identityQuatf() == identityQuatf()); CHECK(!(Quatf{} == identityQuatf())); } SECTION("Quaternions can be checked for inequality") { CHECK(Quatf{} != identityQuatf()); CHECK(!(identityQuatf() != identityQuatf())); } SECTION("Dividing a quaternion by a scalar divides each component") { CHECK(approx(Quatf{2, 4, 6, 2} / 2, Quatf{1, 2, 3, 1})); } SECTION("Multiplying a quaternion by a scalar multiplies each component") { CHECK(approx(Quatf{2, 4, 6, 2} * 2, Quatf{4, 8, 12, 4})); } SECTION("Square magnitude is sum of squared components") { const auto q = Quatf{1.f, 2.f, 3.f, 1.f}; CHECK(approx(q.getSqrMag(), 15.f)); } SECTION("Magnitude is the square root of the sum of squared components") { const auto q = Quatf{0.f, 42.f, 0.f, 0.f}; CHECK(approx(q.getMag(), 42.0f)); } SECTION("Identity quat multiplied by a identity quat returns another identity quat") { CHECK(approx(identityQuatf() * identityQuatf(), identityQuatf())); } SECTION("Inverse an of identity quaternion is also a identity quaternion") { CHECK(approx(identityQuatf().getInv(), identityQuatf())); } SECTION("Square magnitude of an identity quaternion is 1") { CHECK(approx(identityQuatf().getSqrMag(), 1.f)); } SECTION("Multiplying an identity quaternion by a vector yields the same vector") { auto q = identityQuatf(); CHECK(approx(q * dir3d::forward(), dir3d::forward())); CHECK(approx(q * Vec3f{.42, 13.37, -42}, Vec3f{.42, 13.37, -42})); } SECTION("Quaternions can be composed") { auto rot1 = angleAxisQuatf(dir3d::up(), 42.f); auto rot2 = angleAxisQuatf(dir3d::right(), 13.37f); auto comb1 = rot1 * rot2; auto comb2 = rot2 * rot1; CHECK(approx(comb1 * Vec3f{.42, 13.37, -42}, rot1 * (rot2 * Vec3f{.42, 13.37, -42}), .000001f)); CHECK(approx(comb2 * Vec3f{.42, 13.37, -42}, rot2 * (rot1 * Vec3f{.42, 13.37, -42}), .000001f)); } SECTION( "Multiplying a quaternion by a normalized quaternion returns in a normalized quaternion") { auto rot1 = angleAxisQuatf(dir3d::up(), 42.f); auto rot2 = angleAxisQuatf(dir3d::right(), 13.37f); CHECK(approx(rot1.getSqrMag(), 1.f, .000001f)); CHECK(approx(rot2.getSqrMag(), 1.f, .000001f)); CHECK(approx((rot1 * rot2).getSqrMag(), 1.f, .000001f)); } SECTION("Inverse of a normalized quaternion is also normalized") { auto rot = angleAxisQuatf(Vec3f{.42, 13.37, -42}.getNorm(), 13.37f); CHECK(approx(rot.getSqrMag(), 1.f, .000001f)); CHECK(approx(rot.getInv().getSqrMag(), 1.f, .000001f)); } SECTION("Rotating 'left' 180 degrees over y axis results in 'right'") { auto rot = angleAxisQuatf(dir3d::up(), 180.f * math::degToRad<float>); CHECK(approx(rot * dir3d::left(), dir3d::right(), .000001f)); } SECTION("Rotating 'left' 90 degrees over y axis results in 'forward'") { auto rot = angleAxisQuatf(dir3d::up(), 90.f * math::degToRad<float>); CHECK(approx(rot * dir3d::left(), dir3d::forward(), .000001f)); } SECTION("Rotating 'left' by inverse of 90 degrees over y axis results in 'backward'") { auto rot = angleAxisQuatf(dir3d::up(), 90.f * math::degToRad<float>); CHECK(approx(rot.getInv() * dir3d::left(), dir3d::backward(), .000001f)); } SECTION("Rotating a vector by 42 degrees results in a vector that is 42 degrees away") { auto rot = angleAxisQuatf(dir3d::up(), 42.f * math::degToRad<float>); CHECK(approx( angle(dir3d::forward(), rot * dir3d::forward()) * math::radToDeg<float>, 42.f, .000001f)); CHECK(approx( angle(dir3d::forward(), rot.getInv() * dir3d::forward()) * math::radToDeg<float>, 42.f, .000001f)); } SECTION("Quaternion angle axis over right axis provides the same results as x-rotation matrix") { auto rotMat = rotXMat4f(42.f); auto rotQuat = angleAxisQuatf(dir3d::right(), 42.f); auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f}; auto vec2 = rotQuat * Vec3f{.42, 13.37, -42}; CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f)); } SECTION("Quaternion angle axis over up axis provides the same results as y-rotation matrix") { auto rotMat = rotYMat4f(42.f); auto rotQuat = angleAxisQuatf(dir3d::up(), 42.f); auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f}; auto vec2 = rotQuat * Vec3f{.42, 13.37, -42}; CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f)); } SECTION( "Quaternion angle axis over forward axis provides the same results as z-rotation matrix") { auto rotMat = rotZMat4f(42.f); auto rotQuat = angleAxisQuatf(dir3d::forward(), 42.f); auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f}; auto vec2 = rotQuat * Vec3f{.42, 13.37, -42}; CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f)); } SECTION( "Creating rotation matrix from angle-axis over right is the same as a x-rotation matrix") { auto rotMat = rotXMat4f(42.f); auto rotQuat = angleAxisQuatf(dir3d::right(), 42.f); CHECK(approx(rotMat, rotMat4f(rotQuat), .000001f)); } SECTION("Creating rotation matrix from angle-axis over up is the same as a y-rotation matrix") { auto rotMat = rotYMat4f(42.f); auto rotQuat = angleAxisQuatf(dir3d::up(), 42.f); CHECK(approx(rotMat, rotMat4f(rotQuat), .000001f)); } SECTION( "Creating rotation matrix from angle-axis over forward is the same as a z-rotation matrix") { auto rotMat = rotZMat4f(42.f); auto rotQuat = angleAxisQuatf(dir3d::forward(), 42.f); CHECK(approx(rotMat, rotMat4f(rotQuat), .000001f)); } SECTION("Rotation matrix from axes is the same as from a quaternion") { auto rot = angleAxisQuatf(dir3d::up(), 42.f) * angleAxisQuatf(dir3d::right(), 13.f); auto newRight = rot * dir3d::right(); auto newUp = rot * dir3d::up(); auto newForward = rot * dir3d::forward(); auto matFromAxes = rotMat4f(newRight, newUp, newForward); CHECK(approx(matFromAxes, rotMat4f(rot), .000001f)); } SECTION("Rotate 180 degrees over y axis rotation can be retrieved from rotation matrix") { auto mat = Mat3f{}; mat[0][0] = -1.f; mat[1][1] = 1.f; mat[2][2] = -1.f; CHECK(approx(quatFromMat(mat), angleAxisQuatf(dir3d::up(), math::pi<float>), .000001f)); } SECTION("Quaternion -> Matrix -> Quaternion produces the same value") { auto rotQuat1 = angleAxisQuatf(dir3d::up(), 42.f) * angleAxisQuatf(dir3d::right(), 13.f); auto rotQuat2 = quatFromMat(rotMat3f(rotQuat1)); auto vec = Vec3f{.42, 13.37, -42}; CHECK(approx(rotQuat1 * vec, rotQuat2 * vec, .00001f)); } SECTION("Quaternion created from orthogonal rotation matrix is normalized") { auto mat = rotXMat3f(42.f) * rotYMat3f(-13.37f) * rotZMat3f(1.1f); auto quat = quatFromMat(mat); CHECK(approx(quat.getSqrMag(), 1.f, .000001f)); } SECTION("Look rotation rotates from identity to the given axis system") { auto newFwd = Vec3f{.42, 13.37, -42}.getNorm(); auto rot = lookRotQuatf(newFwd, dir3d::up()); CHECK(approx(rot * dir3d::forward(), newFwd, .000001f)); } SECTION("Look rotation returns a normalized quaternion") { auto rot = lookRotQuatf(Vec3f{.42, 13.37, -42}, dir3d::down()); CHECK(approx(rot.getSqrMag(), 1.f, .000001f)); } SECTION("Look rotation is the same as building a rotation matrix from axes") { auto rotQuat = lookRotQuatf(dir3d::right(), dir3d::down()); auto rotMat = rotMat4f(dir3d::forward(), dir3d::down(), dir3d::right()); auto vec1 = rotMat * Vec4f{.42, 13.37, -42, 0.f}; auto vec2 = rotQuat * Vec3f{.42, 13.37, -42}; CHECK(approx(Vec3f{vec1.x(), vec1.y(), vec1.z()}, vec2, .00001f)); } SECTION("Normalizing a quaterion results in a quaternion with length 1") { auto q = Quatf{1337.f, 42.f, -42.f, 5.f}; CHECK(approx(q.getNorm().getMag(), 1.f)); q.norm(); CHECK(approx(q.getMag(), 1.f)); } } } // namespace tria::math::tests
37.61039
100
0.635474
BastianBlokland
2cca7b2d7c7dc21b45de21c60391fab7a08e3f31
7,798
cpp
C++
src/services/openid_connect.cpp
umr-dbs/mapping-gfbio
820f0ccde16cab9f5780864d2402149230f01acf
[ "MIT" ]
null
null
null
src/services/openid_connect.cpp
umr-dbs/mapping-gfbio
820f0ccde16cab9f5780864d2402149230f01acf
[ "MIT" ]
2
2018-04-04T10:38:47.000Z
2020-12-07T13:26:04.000Z
src/services/openid_connect.cpp
umr-dbs/mapping-gfbio
820f0ccde16cab9f5780864d2402149230f01acf
[ "MIT" ]
2
2018-03-07T07:50:24.000Z
2018-06-05T13:51:58.000Z
#include "openid_connect.h" void OpenIdConnectService::OpenIdConnectService::run() { try { const std::string &request = params.get("request"); if (request == "login") { this->login(params.get("access_token")); } else { // FALLBACK response.sendFailureJSON("OpenIdConnectService: Invalid request"); } } catch (const std::exception &e) { response.sendFailureJSON(e.what()); } } auto OpenIdConnectService::login(const std::string &access_token) const -> void { static const std::unordered_set<std::string> allowed_jwt_algorithms{"RS256"}; static const auto jwks_endpoint_url = Configuration::get<std::string>("oidc.jwks_endpoint"); static const auto user_endpoint_url = Configuration::get<std::string>("oidc.user_endpoint"); static const auto allowed_clock_skew_seconds = Configuration::get<uint32_t>("oidc.allowed_clock_skew_seconds"); const auto jwks = download_jwks(jwks_endpoint_url); const auto jwt_algorithm = jwks.get("alg", "").asString(); if (allowed_jwt_algorithms.count(jwt_algorithm) <= 0) { throw OpenIdConnectService::OpenIdConnectServiceException( concat("OpenIdConnectService: Algorithm ", jwt_algorithm, " is not supported")); } const std::string pem = jwks_to_pem(jwks.get("n", "").asString(), jwks.get("e", "").asString()); const auto decoded_token = jwt::decode(access_token, jwt::params::algorithms({jwt_algorithm}), jwt::params::secret(pem), jwt::params::leeway(allowed_clock_skew_seconds), jwt::params::verify(true)); const auto &payload = decoded_token.payload(); const uint32_t expiration_time = payload.get_claim_value<uint32_t>(jwt::registered_claims::expiration); const auto user_json = download_user_data(user_endpoint_url, access_token); OpenIdConnectService::User user{ .goe_id = user_json.get("goe_id", "").asString(), .email = user_json.get("email", "").asString(), .given_name = user_json.get("given_name", "").asString(), .family_name = user_json.get("family_name", "").asString(), .preferred_username = user_json.get("preferred_username", "").asString(), .expiration_time = expiration_time, }; response.sendSuccessJSON("session", createSessionAndAccountIfNotExist(user)); } auto OpenIdConnectService::jwks_to_pem(const std::string &n, const std::string &e) -> std::string { auto n_decoded = cppcodec::base64_url_unpadded::decode(n); auto e_decoded = cppcodec::base64_url_unpadded::decode(e); BIGNUM *modul = BN_bin2bn(n_decoded.data(), n_decoded.size(), nullptr); BIGNUM *expon = BN_bin2bn(e_decoded.data(), e_decoded.size(), nullptr); std::unique_ptr<RSA, std::function<void(RSA *)>> rsa( RSA_new(), [](RSA *rsa) { RSA_free(rsa); } ); RSA_set0_key(rsa.get(), modul, expon, nullptr); std::unique_ptr<BIO, std::function<void(BIO *)>> memory_file( BIO_new(BIO_s_mem()), [](BIO *bio) { BIO_set_close(bio, BIO_CLOSE); BIO_free_all(bio); } ); PEM_write_bio_RSA_PUBKEY(memory_file.get(), rsa.get()); BUF_MEM *memory_pointer; BIO_get_mem_ptr(memory_file.get(), &memory_pointer); return std::string(memory_pointer->data, memory_pointer->length); } auto OpenIdConnectService::download_jwks(const std::string &url) -> Json::Value { std::stringstream data; cURL curl; curl.setOpt(CURLOPT_PROXY, Configuration::get<std::string>("proxy", "").c_str()); curl.setOpt(CURLOPT_URL, url.c_str()); curl.setOpt(CURLOPT_WRITEFUNCTION, cURL::defaultWriteFunction); curl.setOpt(CURLOPT_WRITEDATA, &data); curl.perform(); try { curl.perform(); } catch (const cURLException &e) { throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: JSON Web Key Set service unavailable"); } Json::Reader reader(Json::Features::strictMode()); Json::Value response; if (!reader.parse(data.str(), response) || response.empty() || !response.isMember("keys") || !response["keys"][0].isMember("n") || !response["keys"][0].isMember("e") || !response["keys"][0].isMember("alg")) { Log::error(concat( "OpenIdConnectService: JSON Web Key Set is invalid (malformed JSON)", '\n', data.str() )); throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: JSON Web Key Set is invalid (malformed JSON)"); } // return first key return response["keys"][0]; } auto OpenIdConnectService::download_user_data(const std::string &url, const std::string &access_token) -> Json::Value { std::stringstream data; cURL curl; curl.setOpt(CURLOPT_PROXY, Configuration::get<std::string>("proxy", "").c_str()); curl.setOpt(CURLOPT_URL, url.c_str()); curl.setOpt(CURLOPT_HTTPAUTH, CURLAUTH_BEARER); // NOLINT(hicpp-signed-bitwise) curl.setOpt(CURLOPT_XOAUTH2_BEARER, access_token.c_str()); curl.setOpt(CURLOPT_WRITEFUNCTION, cURL::defaultWriteFunction); curl.setOpt(CURLOPT_WRITEDATA, &data); curl.perform(); try { curl.perform(); } catch (const cURLException &e) { throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: User endpoint unavailable"); } Json::Reader reader(Json::Features::strictMode()); Json::Value response; if (!reader.parse(data.str(), response) || response.empty() || !response.isMember("goe_id") || !response.isMember("email")) { Log::error(concat( "OpenIdConnectService: User data is invalid (malformed JSON)", '\n', data.str() )); throw OpenIdConnectService::OpenIdConnectServiceException("OpenIdConnectService: User data is invalid (malformed JSON)"); } return response; } auto OpenIdConnectService::createSessionAndAccountIfNotExist(const User &user) -> std::string { std::shared_ptr<UserDB::Session> session; const auto user_id = OpenIdConnectService::EXTERNAL_ID_PREFIX + user.goe_id; const std::time_t current_time = std::time(nullptr); const auto expiration_time_in_seconds = user.expiration_time - current_time; try { // create session for user if he already exists session = UserDB::createSessionForExternalUser(user_id, expiration_time_in_seconds); // TODO: think about updating user data like email, etc. } catch (const UserDB::authentication_error &e) { // user does not exist locally => CREATE try { auto mapping_user = UserDB::createExternalUser( user.preferred_username, concat(user.given_name, ' ', user.family_name), user.email, user_id ); try { auto gfbio_group = UserDB::loadGroup("gfbio"); mapping_user->joinGroup(*gfbio_group); } catch (const UserDB::database_error &) { auto gfbio_group = UserDB::createGroup("gfbio"); mapping_user->joinGroup(*gfbio_group); } session = UserDB::createSessionForExternalUser(user_id, expiration_time_in_seconds); } catch (const std::exception &e) { throw OpenIdConnectService::OpenIdConnectServiceException( "OpenIdConnectService: Could not create new user from GFBio Single Sign On."); } } return session->getSessiontoken(); }
39.989744
136
0.63901
umr-dbs
2cd067070b2e7be96aa262c8a9c3d38d039051b4
607
hpp
C++
nucleo/Inc/globals.hpp
cerberuspower/monochromator
0324831743652bccea7c760b3994d06c7a766c16
[ "Apache-2.0" ]
null
null
null
nucleo/Inc/globals.hpp
cerberuspower/monochromator
0324831743652bccea7c760b3994d06c7a766c16
[ "Apache-2.0" ]
null
null
null
nucleo/Inc/globals.hpp
cerberuspower/monochromator
0324831743652bccea7c760b3994d06c7a766c16
[ "Apache-2.0" ]
null
null
null
#ifndef __GLOBALS_INCLUDED__ #define __GLOBALS_INCLUDED__ #include "motor.hpp" #include "uart.hpp" #include <string.h> #include <stdlib.h> #include "stm32f3xx_hal.h" typedef struct monochromator_t { Motor *motor; Uart *uart; uint16_t end_stop_forward; uint16_t end_stop_reverse; uint8_t aBuffer[RX_BUFFER_SIZE]; uint32_t current_position; uint8_t step_divider_settings; uint32_t Max_Wavelength; uint32_t Min_Wavelength; } monochromator_t; void buffer_analyze(char buffer[12]); extern monochromator_t monochromator; #endif // ifndef __GLOBALS_INCLUDED__
21.678571
38
0.75453
cerberuspower
2cd2b742faf6023ff160a7276bbbf12f21043749
554
cc
C++
BetaScatt/src/PadEventAction.cc
eric-presbitero/BetaScatt
3dc27e088483d6c34f714825a76439382ea08204
[ "MIT" ]
5
2020-10-14T09:45:57.000Z
2022-02-08T10:45:59.000Z
BetaScatt/src/PadEventAction.cc
eric-presbitero/BetaScatt
3dc27e088483d6c34f714825a76439382ea08204
[ "MIT" ]
null
null
null
BetaScatt/src/PadEventAction.cc
eric-presbitero/BetaScatt
3dc27e088483d6c34f714825a76439382ea08204
[ "MIT" ]
null
null
null
#ifdef G4ANALYSIS_USE #include "PadAnalysisManager.hh" #endif #include "PadEventAction.hh" PadEventAction::PadEventAction( PadAnalysisManager* aAnalysisManager ):fAnalysisManager(aAnalysisManager){} PadEventAction::~PadEventAction(){} void PadEventAction::BeginOfEventAction(const G4Event* aEvent){ #ifdef G4ANALYSIS_USE if(fAnalysisManager) fAnalysisManager->BeginOfEvent(aEvent); #endif } void PadEventAction::EndOfEventAction(const G4Event* aEvent) { #ifdef G4ANALYSIS_USE if(fAnalysisManager) fAnalysisManager->EndOfEvent(aEvent); #endif }
23.083333
63
0.815884
eric-presbitero
2cd524148cb8c4d18e66358a72d90effe06160dc
2,062
cpp
C++
examples/dfa/src/dfa_layer.cpp
ktnyt/LAPlus
d750862c758a2d6fa3acc5b2b567efc05008b5ae
[ "MIT" ]
null
null
null
examples/dfa/src/dfa_layer.cpp
ktnyt/LAPlus
d750862c758a2d6fa3acc5b2b567efc05008b5ae
[ "MIT" ]
null
null
null
examples/dfa/src/dfa_layer.cpp
ktnyt/LAPlus
d750862c758a2d6fa3acc5b2b567efc05008b5ae
[ "MIT" ]
null
null
null
/****************************************************************************** * * dfa_layer.cpp * * MIT License * * Copyright (c) 2016 Kotone Itaya * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * *****************************************************************************/ #include "dfa_layer.hpp" #include <cmath> namespace lp = laplus; DFALayer::DFALayer(const std::size_t n_input, const std::size_t n_output, const std::size_t n_final) : W(lp::Matrixf::Normal(n_input, n_output, 0.0, std::sqrt((float)n_input))) , B(lp::Matrixf::Normal(n_final, n_output, 0.0, std::sqrt((float)n_final))) { W /= std::sqrt(static_cast<float>(n_input)); B /= std::sqrt(static_cast<float>(n_final)); } lp::Matrixf DFALayer::operator()(lp::Matrixf x) { return x.dot(W).apply(lp::sigmoid); } void DFALayer::update(lp::Matrixf e, lp::Matrixf x, lp::Matrixf y, float lr) { lp::Matrixf d_x = e.dot(B) * y.apply(lp::dsigmoid); lp::Matrixf d_W = -x.transpose().dot(d_x); W += d_W * lr; }
38.90566
79
0.654219
ktnyt
2cd7cf85017d8c97a5a3a16b7d89b7552d83b960
1,359
cpp
C++
src/617.merge-two-binary-trees.cpp
Hilbert-Yaa/heil-my-lc
075567698e3b826a542f63389e9a8f3136df799a
[ "MIT" ]
null
null
null
src/617.merge-two-binary-trees.cpp
Hilbert-Yaa/heil-my-lc
075567698e3b826a542f63389e9a8f3136df799a
[ "MIT" ]
null
null
null
src/617.merge-two-binary-trees.cpp
Hilbert-Yaa/heil-my-lc
075567698e3b826a542f63389e9a8f3136df799a
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=617 lang=cpp * * [617] Merge Two Binary Trees */ #include <bits/stdc++.h> #using namespace std; // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { if(root1==nullptr && root2==nullptr) return nullptr; else if(root1==nullptr) return root2; else if(root2==nullptr) return root1; else { return new TreeNode(root1->val + root2->val, mergeTrees(root1->left, root2->left), mergeTrees(root1->right,root2->right)); } // * there might be memory problems, since I don't have the implementation of constructors... /* could be faster if replacing the else block with expanded code: * else { * TreeNode* root = new TreeNode(root1->val + root2->val); * root->left = mergeTrees(root1->left, root2->left); * root->right = mergeTrees(root1->right,root2->right); * return root; * } */ } }; // @lc code=end
33.146341
134
0.597498
Hilbert-Yaa
2cda2623e923f4dc411d197b1b6e215b64a3f9aa
35,118
cpp
C++
hip/hip/kernels/share/qDataUpdateS.cpp
artv3/Laghos
64449d427349b0ca35086a63ae4e7d1ed5894f08
[ "BSD-2-Clause" ]
1
2019-11-20T21:45:18.000Z
2019-11-20T21:45:18.000Z
hip/hip/kernels/share/qDataUpdateS.cpp
jeffhammond/Laghos
12e62aa7eb6175f27380106b40c9286d710a0f52
[ "BSD-2-Clause" ]
null
null
null
hip/hip/kernels/share/qDataUpdateS.cpp
jeffhammond/Laghos
12e62aa7eb6175f27380106b40c9286d710a0f52
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights // reserved. See files LICENSE and NOTICE for details. // // This file is part of CEED, a collection of benchmarks, miniapps, software // libraries and APIs for efficient high-order finite element and spectral // element discretizations for exascale applications. For more information and // source code availability see http://github.com/ceed. // // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, // a collaborative effort of two U.S. Department of Energy organizations (Office // of Science and the National Nuclear Security Administration) responsible for // the planning and preparation of a capable exascale ecosystem, including // software, applications, hardware, advanced system engineering and early // testbed platforms, in support of the nation's exascale computing imperative. #include "../hip.hpp" // ***************************************************************************** template<const int NUM_DIM, const int NUM_QUAD, const int NUM_QUAD_1D, const int NUM_DOFS_1D> kernel void rUpdateQuadratureData2S(const double GAMMA, const double H0, const double CFL, const bool USE_VISCOSITY, const int numElements, const double* restrict dofToQuad, const double* restrict dofToQuadD, const double* restrict quadWeights, const double* restrict v, const double* restrict e, const double* restrict rho0DetJ0w, const double* restrict invJ0, const double* restrict J, const double* restrict invJ, const double* restrict detJ, double* restrict stressJinvT, double* restrict dtEst) { const int NUM_QUAD_2D = NUM_QUAD_1D*NUM_QUAD_1D; const int NUM_QUAD_DOFS_1D = (NUM_QUAD_1D * NUM_DOFS_1D); const int NUM_MAX_1D = (NUM_QUAD_1D<NUM_DOFS_1D)?NUM_DOFS_1D:NUM_QUAD_1D; const int idx = blockIdx.x; const int el = idx; if (el < numElements) { share double s_dofToQuad[NUM_QUAD_DOFS_1D];//@dim(NUM_QUAD_1D, NUM_DOFS_1D); share double s_dofToQuadD[NUM_QUAD_DOFS_1D];//@dim(NUM_QUAD_1D, NUM_DOFS_1D); share double s_xy[NUM_DIM * NUM_QUAD_DOFS_1D];//@dim(NUM_DIM, NUM_DOFS_1D, NUM_QUAD_1D); share double s_xDy[NUM_DIM * NUM_QUAD_DOFS_1D];//@dim(NUM_DIM, NUM_DOFS_1D, NUM_QUAD_1D); share double s_gradv[NUM_DIM * NUM_DIM * NUM_QUAD_2D];//@dim(NUM_DIM, NUM_DIM, NUM_QUAD_2D); double r_v[NUM_DIM * NUM_DOFS_1D];//@dim(NUM_DIM, NUM_DOFS_1D); { const int x = threadIdx.x; for (int id = x; id < NUM_QUAD_DOFS_1D; id += NUM_MAX_1D) { s_dofToQuad[id] = dofToQuad[id]; s_dofToQuadD[id] = dofToQuadD[id]; } } sync; { const int dx = threadIdx.x; if (dx < NUM_DOFS_1D) { for (int qy = 0; qy < NUM_QUAD_1D; ++qy) { for (int vi = 0; vi < NUM_DIM; ++vi) { s_xy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = 0; s_xDy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = 0; } } for (int dy = 0; dy < NUM_DOFS_1D; ++dy) { for (int vi = 0; vi < NUM_DIM; ++vi) { r_v[ijN(vi, dy,NUM_DIM)] = v[_ijklNM(vi,dx,dy,el,NUM_DOFS_1D,numElements)]; } } for (int qy = 0; qy < NUM_QUAD_1D; ++qy) { double xy[NUM_DIM]; double xDy[NUM_DIM]; for (int vi = 0; vi < NUM_DIM; ++vi) { xy[vi] = 0; xDy[vi] = 0; } for (int dy = 0; dy < NUM_DOFS_1D; ++dy) { for (int vi = 0; vi < NUM_DIM; ++vi) { xy[vi] += r_v[ijN(vi, dy,NUM_DIM)] * s_dofToQuad[ijN(qy,dy,NUM_QUAD_1D)]; xDy[vi] += r_v[ijN(vi, dy,NUM_DIM)] * s_dofToQuadD[ijN(qy,dy,NUM_QUAD_1D)]; } } for (int vi = 0; vi < NUM_DIM; ++vi) { s_xy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = xy[vi]; s_xDy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] = xDy[vi]; } } } } sync; { const int qy = threadIdx.x; if (qy < NUM_QUAD_1D) { for (int qx = 0; qx < NUM_MAX_1D; ++qx) { double gradX[NUM_DIM]; double gradY[NUM_DIM]; for (int vi = 0; vi < NUM_DIM; ++vi) { gradX[vi] = 0; gradY[vi] = 0; } for (int dx = 0; dx < NUM_DOFS_1D; ++dx) { for (int vi = 0; vi < NUM_DIM; ++vi) { gradX[vi] += s_xy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] * s_dofToQuadD[ijN(qx, dx,NUM_QUAD_1D)]; gradY[vi] += s_xDy[ijkNM(vi, dx, qy,NUM_DIM,NUM_DOFS_1D)] * s_dofToQuad[ijN(qx, dx,NUM_QUAD_1D)]; } } for (int vi = 0; vi < NUM_DIM; ++vi) { s_gradv[ijkN(vi, 0, qx + qy*NUM_QUAD_1D,NUM_DIM)] = gradX[vi]; s_gradv[ijkN(vi, 1, qx + qy*NUM_QUAD_1D,NUM_DIM)] = gradY[vi]; } } } } sync; { const int qBlock = threadIdx.x; for (int q = qBlock; q < NUM_QUAD; q += NUM_MAX_1D) { double q_gradv[NUM_DIM * NUM_DIM];//@dim(NUM_DIM, NUM_DIM); double q_stress[NUM_DIM * NUM_DIM];//@dim(NUM_DIM, NUM_DIM); const double invJ_00 = invJ[ijklNM(0,0,q,el,NUM_DIM,NUM_QUAD)]; const double invJ_10 = invJ[ijklNM(1,0,q,el,NUM_DIM,NUM_QUAD)]; const double invJ_01 = invJ[ijklNM(0,1,q,el,NUM_DIM,NUM_QUAD)]; const double invJ_11 = invJ[ijklNM(1,1,q,el,NUM_DIM,NUM_QUAD)]; q_gradv[ijN(0,0,2)] = ((s_gradv[ijkN(0,0,q,2)]*invJ_00) + (s_gradv[ijkN(1,0,q, 2)]*invJ_01)); q_gradv[ijN(1,0,2)] = ((s_gradv[ijkN(0,0,q,2)]*invJ_10) + (s_gradv[ijkN(1,0,q, 2)]*invJ_11)); q_gradv[ijN(0,1,2)] = ((s_gradv[ijkN(0,1,q,2)]*invJ_00) + (s_gradv[ijkN(1,1,q, 2)]*invJ_01)); q_gradv[ijN(1,1,2)] = ((s_gradv[ijkN(0,1,q,2)]*invJ_10) + (s_gradv[ijkN(1,1,q, 2)]*invJ_11)); const double q_Jw = detJ[ijN(q,el,NUM_QUAD)]*quadWeights[q]; const double q_rho = rho0DetJ0w[ijN(q,el,NUM_QUAD)]/q_Jw; const double q_e = fmax(0.0,e[ijN(q,el,NUM_QUAD)]); // TODO: Input OccaVector eos(q,e) -> (stress, soundSpeed) const double s = -(GAMMA - 1.0) * q_rho * q_e; q_stress[ijN(0,0,2)] = s; q_stress[ijN(1,0,2)] = 0; q_stress[ijN(0,1,2)] = 0; q_stress[ijN(1,1,2)] = s; const double gradv00 = q_gradv[ijN(0,0,2)]; const double gradv11 = q_gradv[ijN(1,1,2)]; const double gradv10 = 0.5 * (q_gradv[ijN(1,0,2)] + q_gradv[ijN(0,1,2)]); q_gradv[ijN(1,0,2)] = gradv10; q_gradv[ijN(0,1,2)] = gradv10; double comprDirX = 1; double comprDirY = 0; double minEig = 0; // linalg/densemat.cpp: Eigensystem2S() if (gradv10 == 0) { minEig = (gradv00 < gradv11) ? gradv00 : gradv11; } else { const double zeta = (gradv11 - gradv00) / (2.0 * gradv10); const double azeta = fabs(zeta); double t = 1.0 / (azeta + sqrt(1.0 + zeta*zeta)); if ((t < 0) != (zeta < 0)) { t = -t; } const double c = sqrt(1.0 / (1.0 + t*t)); const double s = c * t; t *= gradv10; if ((gradv00 - t) <= (gradv11 + t)) { minEig = gradv00 - t; comprDirX = c; comprDirY = -s; } else { minEig = gradv11 + t; comprDirX = s; comprDirY = c; } } // Computes the initial->physical transformation Jacobian. const double J_00 = J[ijklNM(0,0,q,el,NUM_DIM,NUM_QUAD)]; const double J_10 = J[ijklNM(1,0,q,el,NUM_DIM,NUM_QUAD)]; const double J_01 = J[ijklNM(0,1,q,el,NUM_DIM,NUM_QUAD)]; const double J_11 = J[ijklNM(1,1,q,el,NUM_DIM,NUM_QUAD)]; const double invJ0_00 = invJ0[ijklNM(0,0,q,el,NUM_DIM,NUM_QUAD)]; const double invJ0_10 = invJ0[ijklNM(1,0,q,el,NUM_DIM,NUM_QUAD)]; const double invJ0_01 = invJ0[ijklNM(0,1,q,el,NUM_DIM,NUM_QUAD)]; const double invJ0_11 = invJ0[ijklNM(1,1,q,el,NUM_DIM,NUM_QUAD)]; const double Jpi_00 = ((J_00 * invJ0_00) + (J_10 * invJ0_01)); const double Jpi_10 = ((J_00 * invJ0_10) + (J_10 * invJ0_11)); const double Jpi_01 = ((J_01 * invJ0_00) + (J_11 * invJ0_01)); const double Jpi_11 = ((J_01 * invJ0_10) + (J_11 * invJ0_11)); const double physDirX = (Jpi_00 * comprDirX) + (Jpi_10 * comprDirY); const double physDirY = (Jpi_01 * comprDirX) + (Jpi_11 * comprDirY); const double q_h = H0 * sqrt((physDirX * physDirX) + (physDirY * physDirY)); // TODO: soundSpeed will be an input as well (function call or values per q) const double soundSpeed = sqrt(GAMMA * (GAMMA - 1.0) * q_e); dtEst[ijN(q, el,NUM_QUAD)] = CFL * q_h / soundSpeed; if (USE_VISCOSITY) { // TODO: Check how we can extract outside of kernel const double mu = minEig; double coeff = 2.0 * q_rho * q_h * q_h * fabs(mu); if (mu < 0) { coeff += 0.5 * q_rho * q_h * soundSpeed; } for (int y = 0; y < NUM_DIM; ++y) { for (int x = 0; x < NUM_DIM; ++x) { q_stress[ijN(x,y,2)] += coeff * q_gradv[ijN(x,y,2)]; } } } const double S00 = q_stress[ijN(0,0,2)]; const double S10 = q_stress[ijN(1,0,2)]; const double S01 = q_stress[ijN(0,1,2)]; const double S11 = q_stress[ijN(1,1,2)]; stressJinvT[ijklNM(0,0,q,el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S00 * invJ_00) + (S10 * invJ_01)); stressJinvT[ijklNM(1,0,q,el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S00 * invJ_10) + (S10 * invJ_11)); stressJinvT[ijklNM(0,1,q,el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S01 * invJ_00) + (S11 * invJ_01)); stressJinvT[ijklNM(1,1,q,el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S01 * invJ_10) + (S11 * invJ_11)); } } } } // ***************************************************************************** template<const int NUM_DIM, const int NUM_QUAD, const int NUM_QUAD_1D, const int NUM_DOFS_1D> kernel void rUpdateQuadratureData3S(const double GAMMA, const double H0, const double CFL, const bool USE_VISCOSITY, const int numElements, const double* restrict dofToQuad, const double* restrict dofToQuadD, const double* restrict quadWeights, const double* restrict v, const double* restrict e, const double* restrict rho0DetJ0w, const double* restrict invJ0, const double* restrict J, const double* restrict invJ, const double* restrict detJ, double* restrict stressJinvT, double* restrict dtEst) { const int NUM_QUAD_2D = NUM_QUAD_1D*NUM_QUAD_1D; const int NUM_QUAD_DOFS_1D = (NUM_QUAD_1D * NUM_DOFS_1D); const int el = blockIdx.x; if (el < numElements) { share double s_dofToQuad[NUM_QUAD_DOFS_1D]; share double s_dofToQuadD[NUM_QUAD_DOFS_1D]; { const int y = threadIdx.y; { const int x = threadIdx.x; const int id = (y * NUM_QUAD_1D) + x; for (int i = id; i < (NUM_DOFS_1D * NUM_QUAD_1D); i += NUM_QUAD_2D) { s_dofToQuad[id] = dofToQuad[id]; s_dofToQuadD[id] = dofToQuadD[id]; } } } sync; for (int qz = 0; qz < NUM_QUAD_1D; ++qz) { { const int qy = threadIdx.y; { const int qx = 0 + threadIdx.x; const int q = qx + qy*NUM_QUAD_1D + qz*NUM_QUAD_2D; double gradv[9]; double q_gradv[9]; double q_stress[9]; // Brute-force convertion of dof -> quad for now for (int i = 0; i < 9; ++i) { gradv[i] = 0; } for (int dz = 0; dz < NUM_DOFS_1D; ++dz) { double xy[3]; double Dxy[3]; double xDy[3]; for (int vi = 0; vi < 3; ++vi) { xy[vi] = Dxy[vi] = xDy[vi] = 0; } for (int dy = 0; dy < NUM_DOFS_1D; ++dy) { double x[3]; double Dx[3]; for (int vi = 0; vi < 3; ++vi) { x[vi] = Dx[vi] = 0; } for (int dx = 0; dx < NUM_DOFS_1D; ++dx) { const double wx = s_dofToQuad[ijN(qx,dx,NUM_QUAD_1D)]; const double wDx = s_dofToQuadD[ijN(qx,dx,NUM_QUAD_1D)]; for (int vi = 0; vi < 3; ++vi) { const double r_v = v[_ijklmNM(vi,dx,dy,dz,el,NUM_DOFS_1D,numElements)]; x[vi] += wx * r_v; Dx[vi] += wDx * r_v; } } const double wy = s_dofToQuad[ijN(qy,dy,NUM_QUAD_1D)]; const double wDy = s_dofToQuadD[ijN(qy,dy,NUM_QUAD_1D)]; for (int vi = 0; vi < 3; ++vi) { xy[vi] += wy * x[vi]; Dxy[vi] += wy * Dx[vi]; xDy[vi] += wDy * x[vi]; } } const double wz = s_dofToQuad[ijN(qz,dz,NUM_QUAD_1D)]; const double wDz = s_dofToQuadD[ijN(qz,dz,NUM_QUAD_1D)]; for (int vi = 0; vi < 3; ++vi) { gradv[ijN(vi,0,3)] += wz * Dxy[vi]; gradv[ijN(vi,1,3)] += wz * xDy[vi]; gradv[ijN(vi,2,3)] += wDz * xy[vi]; } } const double invJ_00 = invJ[ijklNM(0, 0, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_10 = invJ[ijklNM(1, 0, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_20 = invJ[ijklNM(2, 0, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_01 = invJ[ijklNM(0, 1, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_11 = invJ[ijklNM(1, 1, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_21 = invJ[ijklNM(2, 1, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_02 = invJ[ijklNM(0, 2, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_12 = invJ[ijklNM(1, 2, q, el,NUM_DIM,NUM_QUAD)]; const double invJ_22 = invJ[ijklNM(2, 2, q, el,NUM_DIM,NUM_QUAD)]; q_gradv[ijN(0,0,3)] = ((gradv[ijN(0,0,3)] * invJ_00) + (gradv[ijN(1,0, 3)] * invJ_01) + (gradv[ijN(2,0,3)] * invJ_02)); q_gradv[ijN(1,0,3)] = ((gradv[ijN(0,0,3)] * invJ_10) + (gradv[ijN(1,0, 3)] * invJ_11) + (gradv[ijN(2,0,3)] * invJ_12)); q_gradv[ijN(2,0,3)] = ((gradv[ijN(0,0,3)] * invJ_20) + (gradv[ijN(1,0, 3)] * invJ_21) + (gradv[ijN(2,0,3)] * invJ_22)); q_gradv[ijN(0,1,3)] = ((gradv[ijN(0,1,3)] * invJ_00) + (gradv[ijN(1,1, 3)] * invJ_01) + (gradv[ijN(2,1,3)] * invJ_02)); q_gradv[ijN(1,1,3)] = ((gradv[ijN(0,1,3)] * invJ_10) + (gradv[ijN(1,1, 3)] * invJ_11) + (gradv[ijN(2,1,3)] * invJ_12)); q_gradv[ijN(2,1,3)] = ((gradv[ijN(0,1,3)] * invJ_20) + (gradv[ijN(1,1, 3)] * invJ_21) + (gradv[ijN(2,1,3)] * invJ_22)); q_gradv[ijN(0,2,3)] = ((gradv[ijN(0,2,3)] * invJ_00) + (gradv[ijN(1,2, 3)] * invJ_01) + (gradv[ijN(2,2,3)] * invJ_02)); q_gradv[ijN(1,2,3)] = ((gradv[ijN(0,2,3)] * invJ_10) + (gradv[ijN(1,2, 3)] * invJ_11) + (gradv[ijN(2,2,3)] * invJ_12)); q_gradv[ijN(2,2,3)] = ((gradv[ijN(0,2,3)] * invJ_20) + (gradv[ijN(1,2, 3)] * invJ_21) + (gradv[ijN(2,2,3)] * invJ_22)); const double q_Jw = detJ[ijN(q,el,NUM_QUAD)] * quadWeights[q]; const double q_rho = rho0DetJ0w[ijN(q,el,NUM_QUAD)] / q_Jw; const double q_e = fmax(0.0, e[ijN(q,el,NUM_QUAD)]); const double s = -(GAMMA - 1.0) * q_rho * q_e; q_stress[ijN(0, 0,3)] = s; q_stress[ijN(1, 0,3)] = 0; q_stress[ijN(2, 0,3)] = 0; q_stress[ijN(0, 1,3)] = 0; q_stress[ijN(1, 1,3)] = s; q_stress[ijN(2, 1,3)] = 0; q_stress[ijN(0, 2,3)] = 0; q_stress[ijN(1, 2,3)] = 0; q_stress[ijN(2, 2,3)] = s; const double gradv00 = q_gradv[ijN(0, 0,3)]; const double gradv11 = q_gradv[ijN(1, 1,3)]; const double gradv22 = q_gradv[ijN(2, 2,3)]; const double gradv10 = 0.5 * (q_gradv[ijN(1, 0,3)] + q_gradv[ijN(0, 1,3)]); const double gradv20 = 0.5 * (q_gradv[ijN(2, 0,3)] + q_gradv[ijN(0, 2,3)]); const double gradv21 = 0.5 * (q_gradv[ijN(2, 1,3)] + q_gradv[ijN(1, 2,3)]); q_gradv[ijN(1, 0,3)] = gradv10; q_gradv[ijN(2, 0,3)] = gradv20; q_gradv[ijN(0, 1,3)] = gradv10; q_gradv[ijN(2, 1,3)] = gradv21; q_gradv[ijN(0, 2,3)] = gradv20; q_gradv[ijN(1, 2,3)] = gradv21; double minEig = 0; double comprDirX = 1; double comprDirY = 0; double comprDirZ = 0; { // Compute eigenvalues using quadrature formula const double q_ = (gradv00 + gradv11 + gradv22) / 3.0; const double gradv_q00 = (gradv00 - q_); const double gradv_q11 = (gradv11 - q_); const double gradv_q22 = (gradv22 - q_); const double p1 = ((gradv10 * gradv10) + (gradv20 * gradv20) + (gradv21 * gradv21)); const double p2 = ((gradv_q00 * gradv_q00) + (gradv_q11 * gradv_q11) + (gradv_q22 * gradv_q22) + (2.0 * p1)); const double p = sqrt(p2 / 6.0); const double pinv = 1.0 / p; // det(pinv * (gradv - q*I)) const double r = (0.5 * pinv * pinv * pinv * ((gradv_q00 * gradv_q11 * gradv_q22) + (2.0 * gradv10 * gradv21 * gradv20) - (gradv_q11 * gradv20 * gradv20) - (gradv_q22 * gradv10 * gradv10) - (gradv_q00 * gradv21 * gradv21))); double phi = 0; if (r <= -1.0) { phi = M_PI / 3.0; } else if (r < 1.0) { phi = acos(r) / 3.0; } minEig = q_ + (2.0 * p * cos(phi + (2.0 * M_PI / 3.0))); const double eig3 = q_ + (2.0 * p * cos(phi)); const double eig2 = 3.0 * q_ - minEig - eig3; double maxNorm = 0; for (int i = 0; i < 3; ++i) { const double x = q_gradv[i + 3*0] - (i == 0)*eig3; const double y = q_gradv[i + 3*1] - (i == 1)*eig3; const double z = q_gradv[i + 3*2] - (i == 2)*eig3; const double cx = ((x * (gradv00 - eig2)) + (y * gradv10) + (z * gradv20)); const double cy = ((x * gradv10) + (y * (gradv11 - eig2)) + (z * gradv21)); const double cz = ((x * gradv20) + (y * gradv21) + (z * (gradv22 - eig2))); const double cNorm = (cx*cx + cy*cy + cz*cz); if ((cNorm > 1e-16) && (maxNorm < cNorm)) { comprDirX = cx; comprDirY = cy; comprDirZ = cz; maxNorm = cNorm; } } if (maxNorm > 1e-16) { const double maxNormInv = 1.0 / sqrt(maxNorm); comprDirX *= maxNormInv; comprDirY *= maxNormInv; comprDirZ *= maxNormInv; } } // Computes the initial->physical transformation Jacobian. const double J_00 = J[ijklNM(0, 0, q, el,NUM_DIM,NUM_QUAD)]; const double J_10 = J[ijklNM(1, 0, q, el,NUM_DIM,NUM_QUAD)]; const double J_20 = J[ijklNM(2, 0, q, el,NUM_DIM,NUM_QUAD)]; const double J_01 = J[ijklNM(0, 1, q, el,NUM_DIM,NUM_QUAD)]; const double J_11 = J[ijklNM(1, 1, q, el,NUM_DIM,NUM_QUAD)]; const double J_21 = J[ijklNM(2, 1, q, el,NUM_DIM,NUM_QUAD)]; const double J_02 = J[ijklNM(0, 2, q, el,NUM_DIM,NUM_QUAD)]; const double J_12 = J[ijklNM(1, 2, q, el,NUM_DIM,NUM_QUAD)]; const double J_22 = J[ijklNM(2, 2, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_00 = invJ0[ijklNM(0, 0, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_10 = invJ0[ijklNM(1, 0, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_20 = invJ0[ijklNM(2, 0, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_01 = invJ0[ijklNM(0, 1, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_11 = invJ0[ijklNM(1, 1, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_21 = invJ0[ijklNM(2, 1, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_02 = invJ0[ijklNM(0, 2, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_12 = invJ0[ijklNM(1, 2, q, el,NUM_DIM,NUM_QUAD)]; const double invJ0_22 = invJ0[ijklNM(2, 2, q, el,NUM_DIM,NUM_QUAD)]; const double Jpi_00 = ((J_00 * invJ0_00) + (J_10 * invJ0_01) + (J_20 * invJ0_02)); const double Jpi_10 = ((J_00 * invJ0_10) + (J_10 * invJ0_11) + (J_20 * invJ0_12)); const double Jpi_20 = ((J_00 * invJ0_20) + (J_10 * invJ0_21) + (J_20 * invJ0_22)); const double Jpi_01 = ((J_01 * invJ0_00) + (J_11 * invJ0_01) + (J_21 * invJ0_02)); const double Jpi_11 = ((J_01 * invJ0_10) + (J_11 * invJ0_11) + (J_21 * invJ0_12)); const double Jpi_21 = ((J_01 * invJ0_20) + (J_11 * invJ0_21) + (J_21 * invJ0_22)); const double Jpi_02 = ((J_02 * invJ0_00) + (J_12 * invJ0_01) + (J_22 * invJ0_02)); const double Jpi_12 = ((J_02 * invJ0_10) + (J_12 * invJ0_11) + (J_22 * invJ0_12)); const double Jpi_22 = ((J_02 * invJ0_20) + (J_12 * invJ0_21) + (J_22 * invJ0_22)); const double physDirX = ((Jpi_00 * comprDirX) + (Jpi_10 * comprDirY) + (Jpi_20 * comprDirZ)); const double physDirY = ((Jpi_01 * comprDirX) + (Jpi_11 * comprDirY) + (Jpi_21 * comprDirZ)); const double physDirZ = ((Jpi_02 * comprDirX) + (Jpi_12 * comprDirY) + (Jpi_22 * comprDirZ)); const double q_h = H0 * sqrt((physDirX * physDirX) + (physDirY * physDirY) + (physDirZ * physDirZ)); const double soundSpeed = sqrt(GAMMA * (GAMMA - 1.0) * q_e); dtEst[ijN(q, el,NUM_QUAD)] = CFL * q_h / soundSpeed; if (USE_VISCOSITY) { // TODO: Check how we can extract outside of kernel const double mu = minEig; double coeff = 2.0 * q_rho * q_h * q_h * fabs(mu); if (mu < 0) { coeff += 0.5 * q_rho * q_h * soundSpeed; } for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { q_stress[ijN(x, y,3)] += coeff * q_gradv[ijN(x, y,3)]; } } } const double S00 = q_stress[ijN(0, 0,3)]; const double S10 = q_stress[ijN(1, 0,3)]; const double S20 = q_stress[ijN(2, 0,3)]; const double S01 = q_stress[ijN(0, 1,3)]; const double S11 = q_stress[ijN(1, 1,3)]; const double S21 = q_stress[ijN(2, 1,3)]; const double S02 = q_stress[ijN(0, 2,3)]; const double S12 = q_stress[ijN(1, 2,3)]; const double S22 = q_stress[ijN(2, 2,3)]; stressJinvT[ijklNM(0, 0, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S00 * invJ_00) + (S10 * invJ_01) + (S20 * invJ_02)); stressJinvT[ijklNM(1, 0, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S00 * invJ_10) + (S10 * invJ_11) + (S20 * invJ_12)); stressJinvT[ijklNM(2, 0, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S00 * invJ_20) + (S10 * invJ_21) + (S20 * invJ_22)); stressJinvT[ijklNM(0, 1, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S01 * invJ_00) + (S11 * invJ_01) + (S21 * invJ_02)); stressJinvT[ijklNM(1, 1, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S01 * invJ_10) + (S11 * invJ_11) + (S21 * invJ_12)); stressJinvT[ijklNM(2, 1, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S01 * invJ_20) + (S11 * invJ_21) + (S21 * invJ_22)); stressJinvT[ijklNM(0, 2, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S02 * invJ_00) + (S12 * invJ_01) + (S22 * invJ_02)); stressJinvT[ijklNM(1, 2, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S02 * invJ_10) + (S12 * invJ_11) + (S22 * invJ_12)); stressJinvT[ijklNM(2, 2, q, el,NUM_DIM, NUM_QUAD)] = q_Jw * ((S02 * invJ_20) + (S12 * invJ_21) + (S22 * invJ_22)); } } } } } // ***************************************************************************** typedef void (*fUpdateQuadratureDataS)(const double GAMMA, const double H0, const double CFL, const bool USE_VISCOSITY, const int numElements, const double* restrict dofToQuad, const double* restrict dofToQuadD, const double* restrict quadWeights, const double* restrict v, const double* restrict e, const double* restrict rho0DetJ0w, const double* restrict invJ0, const double* restrict J, const double* restrict invJ, const double* restrict detJ, double* restrict stressJinvT, double* restrict dtEst); // ***************************************************************************** void rUpdateQuadratureDataS(const double GAMMA, const double H0, const double CFL, const bool USE_VISCOSITY, const int NUM_DIM, const int NUM_QUAD, const int NUM_QUAD_1D, const int NUM_DOFS_1D, const int nzones, const double* restrict dofToQuad, const double* restrict dofToQuadD, const double* restrict quadWeights, const double* restrict v, const double* restrict e, const double* restrict rho0DetJ0w, const double* restrict invJ0, const double* restrict J, const double* restrict invJ, const double* restrict detJ, double* restrict stressJinvT, double* restrict dtEst) { const int grid = nzones; const int b1d = (NUM_QUAD_1D<NUM_DOFS_1D)?NUM_DOFS_1D:NUM_QUAD_1D; const dim3 blck(b1d,b1d,1); assert(LOG2(NUM_DIM)<=4); assert(LOG2(NUM_DOFS_1D-2)<=4); assert(NUM_QUAD_1D==2*(NUM_DOFS_1D-1)); assert(IROOT(NUM_DIM,NUM_QUAD)==NUM_QUAD_1D); const unsigned int id = (NUM_DIM<<4)|(NUM_DOFS_1D-2); static std::unordered_map<unsigned int,fUpdateQuadratureDataS> call = { // 2D {0x20,&rUpdateQuadratureData2S<2,2*2,2,2>}, {0x21,&rUpdateQuadratureData2S<2,4*4,4,3>}, {0x22,&rUpdateQuadratureData2S<2,6*6,6,4>}, {0x23,&rUpdateQuadratureData2S<2,8*8,8,5>}, {0x24,&rUpdateQuadratureData2S<2,10*10,10,6>}, {0x25,&rUpdateQuadratureData2S<2,12*12,12,7>}, {0x26,&rUpdateQuadratureData2S<2,14*14,14,8>}, {0x27,&rUpdateQuadratureData2S<2,16*16,16,9>}, {0x28,&rUpdateQuadratureData2S<2,18*18,18,10>}, {0x29,&rUpdateQuadratureData2S<2,20*20,20,11>}, {0x2A,&rUpdateQuadratureData2S<2,22*22,22,12>}, {0x2B,&rUpdateQuadratureData2S<2,24*24,24,13>}, {0x2C,&rUpdateQuadratureData2S<2,26*26,26,14>}, {0x2D,&rUpdateQuadratureData2S<2,28*28,28,15>}, //{0x2E,&rUpdateQuadratureData2S<2,30*30,30,16>}, uses too much shared data //{0x2F,&rUpdateQuadratureData2S<2,32*32,32,17>}, uses too much shared data // 3D {0x30,&rUpdateQuadratureData3S<3,2*2*2,2,2>}, {0x31,&rUpdateQuadratureData3S<3,4*4*4,4,3>}, {0x32,&rUpdateQuadratureData3S<3,6*6*6,6,4>}, {0x33,&rUpdateQuadratureData3S<3,8*8*8,8,5>}, {0x34,&rUpdateQuadratureData3S<3,10*10*10,10,6>}, {0x35,&rUpdateQuadratureData3S<3,12*12*12,12,7>}, {0x36,&rUpdateQuadratureData3S<3,14*14*14,14,8>}, {0x37,&rUpdateQuadratureData3S<3,16*16*16,16,9>}, {0x38,&rUpdateQuadratureData3S<3,18*18*18,18,10>}, {0x39,&rUpdateQuadratureData3S<3,20*20*20,20,11>}, {0x3A,&rUpdateQuadratureData3S<3,22*22*22,22,12>}, {0x3B,&rUpdateQuadratureData3S<3,24*24*24,24,13>}, {0x3C,&rUpdateQuadratureData3S<3,26*26*26,26,14>}, {0x3D,&rUpdateQuadratureData3S<3,28*28*28,28,15>}, {0x3E,&rUpdateQuadratureData3S<3,30*30*30,30,16>}, {0x3F,&rUpdateQuadratureData3S<3,32*32*32,32,17>}, }; if (!call[id]) { printf("\n[rUpdateQuadratureDataS] id \033[33m0x%X\033[m ",id); fflush(stdout); } assert(call[id]); call0(id,grid,blck, GAMMA,H0,CFL,USE_VISCOSITY, nzones,dofToQuad,dofToQuadD,quadWeights, v,e,rho0DetJ0w,invJ0,J,invJ,detJ, stressJinvT,dtEst); }
48.371901
129
0.440287
artv3
2cddcd8889216dde8e8197eab76a84f25b0bdbe1
410
hpp
C++
library/ATF/stdext__hash_compare.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/stdext__hash_compare.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/stdext__hash_compare.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <std__less.hpp> START_ATF_NAMESPACE namespace stdext { template<typename _Ty, typename _Less = std::less<_Ty>> struct hash_compare { _Less comp; }; }; // end namespace stdext END_ATF_NAMESPACE
22.777778
108
0.663415
lemkova
2ce5982951e8331ea1d02d7b12f25da0b03c43b5
742
cpp
C++
main.cpp
fore-head/210810_Make-to-1_LIS
2595e1fd34042248cc22d825df966dcfb08311a3
[ "MIT" ]
null
null
null
main.cpp
fore-head/210810_Make-to-1_LIS
2595e1fd34042248cc22d825df966dcfb08311a3
[ "MIT" ]
null
null
null
main.cpp
fore-head/210810_Make-to-1_LIS
2595e1fd34042248cc22d825df966dcfb08311a3
[ "MIT" ]
1
2021-08-03T13:51:37.000Z
2021-08-03T13:51:37.000Z
// // Created by 이인성 on 2021/08/03. // #include <iostream> int min_op[1000001]; int min(int n, int m) { if(n <= m) return n; else return m; } int main() { int N; scanf("%d", &N); min_op[0] = 0; min_op[1] = 0; for(int i = 2; i <= N; i++) { if((i%2 != 0) && (i%3 != 0)) { min_op[i] = min_op[i-1] + 1; } else if((i%2 == 0) && (i%3 != 0)) { min_op[i] = 1 + min(min_op[i-1], min_op[i/2]); } else if((i%2 != 0) && (i%3 == 0)) { min_op[i] = 1 + min(min_op[i-1], min_op[i/3]); } else min_op[i] = 1 + min(min_op[i-1], min(min_op[i/2], min_op[i/3])); } // for(int i=0; i<=N; i++) { // printf("%d -> %d\n", i, min_op[i]); // } printf("%d\n", min_op[N]); return 0; }
19.526316
70
0.442049
fore-head
f8ebd0e4432c71e9c8f689f4a14ea4e5ed4a7eb3
1,891
cpp
C++
src/lib/Colour.cpp
gtirloni/procdraw
34ddb1b96f0f47af7304914e938f53d10ca5478d
[ "Apache-2.0" ]
null
null
null
src/lib/Colour.cpp
gtirloni/procdraw
34ddb1b96f0f47af7304914e938f53d10ca5478d
[ "Apache-2.0" ]
null
null
null
src/lib/Colour.cpp
gtirloni/procdraw
34ddb1b96f0f47af7304914e938f53d10ca5478d
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Simon Bates // // 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 "Colour.h" namespace Procdraw { // Foley and van Dam Fig. 13.34 // h [0, 360) // s [0, 1] // v [0, 1] std::tuple<float, float, float> Hsv2rgb(float h, float s, float v) { float r = 0.0f; float g = 0.0f; float b = 0.0f; if (s == 0) { r = v; g = v; b = v; } else { if (h == 360) { h = 0; } h = h / 60; int i = static_cast<int>(h); float f = h - i; float p = v * (1 - s); float q = v * (1 - (s * f)); float t = v * (1 - (s * (1 - f))); switch (i) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; break; } } return std::make_tuple(r, g, b); } } // namespace Procdraw
23.345679
76
0.424114
gtirloni
f8f320e68bdc82147a13add265cd46a71fee8340
1,575
cpp
C++
BAC_2nd/ch7/UVa1354.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch7/UVa1354.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch7/UVa1354.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa1354 Mobile Computing // Rujia Liu #include<cstdio> #include<cstring> #include<vector> using namespace std; struct Tree { double L, R; // distance from the root to the leftmost/rightmost point Tree():L(0),R(0) {} }; const int maxn = 6; int n, vis[1<<maxn]; double r, w[maxn], sum[1<<maxn]; vector<Tree> tree[1<<maxn]; void dfs(int subset) { if(vis[subset]) return; vis[subset] = true; bool have_children = false; for(int left = (subset-1)&subset; left; left = (left-1)&subset) { have_children = true; int right = subset^left; double d1 = sum[right] / sum[subset]; double d2 = sum[left] / sum[subset]; dfs(left); dfs(right); for(int i = 0; i < tree[left].size(); i++) for(int j = 0; j < tree[right].size(); j++) { Tree t; t.L = max(tree[left][i].L + d1, tree[right][j].L - d2); t.R = max(tree[right][j].R + d2, tree[left][i].R - d1); if(t.L + t.R < r) tree[subset].push_back(t); } } if(!have_children) tree[subset].push_back(Tree()); } int main() { int T; scanf("%d", &T); while(T--) { scanf("%lf%d", &r, &n); for(int i = 0; i < n; i++) scanf("%lf", &w[i]); for(int i = 0; i < (1<<n); i++) { sum[i] = 0; tree[i].clear(); for(int j = 0; j < n; j++) if(i & (1<<j)) sum[i] += w[j]; } int root = (1<<n)-1; memset(vis, 0, sizeof(vis)); dfs(root); double ans = -1; for(int i = 0; i < tree[root].size(); i++) ans = max(ans, tree[root][i].L + tree[root][i].R); printf("%.10lf\n", ans); } return 0; }
22.826087
72
0.525714
Anyrainel
f8f38bd682ef50835a6d1e7a0c972d62133fe7d3
1,213
cpp
C++
Syl3D/misc/skyboxmanager.cpp
Jedi18/Syl3D
8f62a3cd5349eaff83c36e9366003da61888ec73
[ "MIT" ]
2
2020-12-06T06:43:32.000Z
2021-01-13T14:16:01.000Z
Syl3D/misc/skyboxmanager.cpp
Jedi18/Syl3D
8f62a3cd5349eaff83c36e9366003da61888ec73
[ "MIT" ]
4
2020-11-30T03:18:03.000Z
2021-05-22T16:46:25.000Z
Syl3D/misc/skyboxmanager.cpp
Jedi18/Syl3D
8f62a3cd5349eaff83c36e9366003da61888ec73
[ "MIT" ]
2
2020-12-05T07:46:14.000Z
2020-12-05T12:09:54.000Z
#include "skyboxmanager.h" #include "../entity/entityfactory.h" #include "../utility/fileio.h" SkyboxManager* SkyboxManager::_instance = nullptr; SkyboxManager::SkyboxManager() { _skyboxNames = utility::FileIO::filesInPath("resources/skyboxes"); } SkyboxManager* SkyboxManager::skyboxManager() { if (_instance == nullptr) { _instance = new SkyboxManager(); } return _instance; } void SkyboxManager::releaseInstance() { if (_instance != nullptr) { delete _instance; } } void SkyboxManager::addSkybox(const std::string& skyboxName) { if (_skyboxes.find(skyboxName) != _skyboxes.end()) { setSkybox(skyboxName); return; } std::shared_ptr<CubeMap> skycubebox1 = std::make_shared<CubeMap>("resources/skyboxes/" + skyboxName); std::shared_ptr<Skybox> skybox = std::make_shared<Skybox>(); skybox->setCubemap(skycubebox1); _skyboxes[skyboxName] = skybox; setSkybox(skyboxName); } void SkyboxManager::setSkybox(const std::string& skyboxName) { if (_skyboxes.find(skyboxName) == _skyboxes.end()) { return; } EntityFactory::entityFactory()->entityContainer()->setSkybox(_skyboxes[skyboxName]); } const std::vector<std::string>& SkyboxManager::skyboxNames() const { return _skyboxNames; }
24.755102
102
0.734542
Jedi18
f8f9a636edda72964354efc7bec76edea8cf6d55
651
cpp
C++
sample/k_distance_main.cpp
iwiwi/top-k-pruned-landmark-labeling
e334aab5faa10b0aa098f6895d8df393644fa532
[ "BSD-3-Clause" ]
1
2021-06-06T01:31:34.000Z
2021-06-06T01:31:34.000Z
sample/k_distance_main.cpp
iwiwi/top-k-pruned-landmark-labeling
e334aab5faa10b0aa098f6895d8df393644fa532
[ "BSD-3-Clause" ]
null
null
null
sample/k_distance_main.cpp
iwiwi/top-k-pruned-landmark-labeling
e334aab5faa10b0aa098f6895d8df393644fa532
[ "BSD-3-Clause" ]
1
2018-01-10T00:18:42.000Z
2018-01-10T00:18:42.000Z
#include <cstdlib> #include <iostream> #include "top_k_pruned_landmark_labeling.hpp" using namespace std; int main(int argc, char **argv) { if (argc != 2) { cerr << "Usage: " << argv[0] << " (index_file)" << endl; exit(EXIT_FAILURE); } TopKPrunedLandmarkLabeling kpll; if (!kpll.LoadIndex(argv[1])) { cerr << "error: Load failed" << endl; exit(EXIT_FAILURE); } for (int u, v; cin >> u >> v; ) { vector<int> dist; kpll.KDistanceQuery(u, v, dist); cout << dist.size(); for (size_t i = 0; i < dist.size(); i++){ cout << " " << dist[i]; } cout << endl; } exit(EXIT_SUCCESS); }
20.34375
60
0.55914
iwiwi
5d0944bbcca152ebd69e6ea349b58a1d45764087
5,428
cpp
C++
PlatformTest/main.cpp
SamirAroudj/BaseProject
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
[ "BSD-3-Clause" ]
null
null
null
PlatformTest/main.cpp
SamirAroudj/BaseProject
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
[ "BSD-3-Clause" ]
1
2019-06-19T15:55:25.000Z
2019-06-27T07:47:27.000Z
PlatformTest/main.cpp
SamirAroudj/BaseProject
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
[ "BSD-3-Clause" ]
1
2019-07-07T04:37:56.000Z
2019-07-07T04:37:56.000Z
/* * Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #ifdef _WINDOWS #include <Windows.h> #elif _LINUX #include <cstdio> #endif // _WINDOWS #include <sstream> #include "Platform/Application.h" #include "Platform/Input/InputManager.h" #include "Platform/Multithreading/Manager.h" #include "Platform/ResourceManagement/MemoryManager.h" #include "Platform/Timing/TimePeriod.h" using namespace Input; using namespace Platform; using namespace std; using namespace Timing; #ifdef MEMORY_MANAGEMENT const uint32 ResourceManagement::DEFAULT_POOL_BUCKET_NUMBER = 5; const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_CAPACITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 1024, 1024, 1024, 1024, 1024 }; const uint16 ResourceManagement::DEFAULT_POOL_BUCKET_GRANULARITIES[DEFAULT_POOL_BUCKET_NUMBER] = { 16, 32, 64, 128, 256 }; #endif // MEMORY_MANAGEMENT std::mutex osMutex; class OutputTask : public Multithreading::Task { public: OutputTask(wostringstream &os, char c, uint32 count) : Task(), mOS(os), mChar(c), mCount(count) { }; virtual void function() { for (uint32 i = 0; i < mCount; ++i) { osMutex.lock(); mOS << mChar; osMutex.unlock(); //Sleep(10); } osMutex.lock(); mOS << "\n"; osMutex.unlock(); } private: wostringstream &mOS; char mChar; uint32 mCount; }; class MyApp : public Application { public: #ifdef _WINDOWS MyApp(HINSTANCE instanceHandle) : Application(instanceHandle), mPeriod(5.0f) { } #elif _LINUX MyApp() : mPeriod(5.0f) {} #endif // _WINDOWS virtual ~MyApp() { } virtual void onActivation() { Application::onActivation(); } virtual void onDeactivation() { Application::onDeactivation(); } void testMultithreading(wostringstream &os) { os << "Test multithreading: \n"; for (uint32 i = 0; i < 100; ++i) { OutputTask task1(os, 'a', 4); OutputTask task2(os, 'b', 10); OutputTask task3(os, 'c', 12); Multithreading::Manager &manager = Multithreading::Manager::getSingleton(); manager.enqueue(&task1); manager.enqueue(&task2); manager.enqueue(&task3); task1.waitUntilFinished(); osMutex.lock(); os << "Task 1 has finished!\n"; osMutex.unlock(); task2.waitUntilFinished(); osMutex.lock(); os << "Task 2 has finished!\n"; osMutex.unlock(); task3.waitUntilFinished(); osMutex.lock(); os << "Task 3 has finished!\n"; osMutex.unlock(); } } protected: virtual void postRender() { } virtual void render() { } virtual void update() { const Keyboard &keyboard = InputManager::getSingleton().getKeyboard(); const Mouse &mouse = InputManager::getSingleton().getMouse(); wostringstream os(wostringstream::out); os.clear(); if (keyboard.isKeyDown(Input::KEY_ESCAPE)) mRunning = false; bool change = false; if (mInterpretingTextInput && keyboard.isKeyPressed(Input::KEY_RETURN)) { wstring text = endTextInput(); os << L"Finished text:\n"; os << text << L"\n"; change = true; } else { if (!mInterpretingTextInput && keyboard.isKeyPressed(Input::KEY_RETURN)) { mLastTextLength = 0; os << L"Start text input.\n"; startTextInput(); change = true; } if (keyboard.isKeyDown(Input::KEY_M)) { change = true; testMultithreading(os); } } if (isInterpretingTextInput()) { if (keyboard.isKeyPressed(Input::KEY_LEFT)) { change = true; mTextInput.moveCursorToTheLeft(); } if (keyboard.isKeyPressed(Input::KEY_RIGHT)) { change = true; mTextInput.moveCursorToTheRight(); } if (keyboard.isKeyPressed(Input::KEY_DELETE)) { change = true; mTextInput.removeCharacterAtCursorPosition(); } if (keyboard.isKeyPressed(Input::KEY_BACKSPACE)) { change = true; mTextInput.removeCharacterBeforeCursorPosition(); } } if (mLastTextLength != mTextInput.getTextLength()) change = true; if (change && mInterpretingTextInput) { wstring text = mTextInput.getText(); text.insert(mTextInput.getCursorPosition(), L"|"); os << text << L"\n"; } Real mouseXMotion = mouse.getRelativeXMotion(); Real mouseYMotion = mouse.getRelativeYMotion(); if (mouseXMotion != 0.0f && mouseYMotion != 0.0f) { change = true; os << L"\nmouse x: " << mouseXMotion; os << L"\nmouse y: " << mouseYMotion; } #ifdef _LINUX if (mPeriod.hasExpired()) { printf("%f seconds have elapsed.\n", mPeriod.getElapsedTime()); mPeriod.reset(); } #endif // _LINUX if (change) { #ifdef _WINDOWS OutputDebugString(os.str().c_str()); #elif _LINUX wprintf(os.str().c_str()); #endif // _WINDOWS etc } mLastTextLength = mTextInput.getTextLength(); } TimePeriod mPeriod; uint32 mLastTextLength; }; #ifdef _WINDOWS int32 WINAPI WinMain(HINSTANCE applicationHandle, HINSTANCE unused, LPSTR commandLineString, int32 windowShowState) { #else int main(int argc, char *argv[]) { #endif // _WINDOWS { #ifdef _WINDOWS MyApp application(applicationHandle); #else MyApp application; #endif // _WINDOWS application.run(); } #ifdef MEMORY_MANAGEMENT ResourceManagement::MemoryManager::shutDown(); #endif // MEMORY_MANAGEMENT return 0; }
23
128
0.670965
SamirAroudj
5d0c3b90f20d4d8285413757a86b5a10ca171c7a
16,731
cpp
C++
latte-dock/declarativeimports/core/iconitem.cpp
VaughnValle/lush-pop
cdfe9d7b6a7ebb89ba036ab9a4f07d8db6817355
[ "MIT" ]
64
2020-07-08T18:49:29.000Z
2022-03-23T22:58:49.000Z
latte-dock/declarativeimports/core/iconitem.cpp
VaughnValle/kanji-pop
0153059f0c62a8aeb809545c040225da5d249bb8
[ "MIT" ]
1
2021-04-02T04:39:45.000Z
2021-09-25T11:53:18.000Z
latte-dock/declarativeimports/core/iconitem.cpp
VaughnValle/kanji-pop
0153059f0c62a8aeb809545c040225da5d249bb8
[ "MIT" ]
11
2020-12-04T18:19:11.000Z
2022-01-10T08:50:08.000Z
/* * Copyright 2012 Marco Martin <[email protected]> * Copyright 2014 David Edmundson <[email protected]> * Copyright 2016 Smith AR <[email protected]> * Michail Vourlakos <[email protected]> * * This file is part of Latte-Dock and is a Fork of PlasmaCore::IconItem * * Latte-Dock is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * Latte-Dock is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "iconitem.h" // local #include "extras.h" // Qt #include <QDebug> #include <QPainter> #include <QPaintEngine> #include <QQuickWindow> #include <QPixmap> #include <QSGSimpleTextureNode> #include <QuickAddons/ManagedTextureNode> // KDE #include <KIconTheme> #include <KIconThemes/KIconLoader> #include <KIconThemes/KIconEffect> namespace Latte { IconItem::IconItem(QQuickItem *parent) : QQuickItem(parent), m_lastValidSourceName(QString()), m_smooth(false), m_active(false), m_textureChanged(false), m_sizeChanged(false), m_usesPlasmaTheme(false), m_colorGroup(Plasma::Theme::NormalColorGroup) { setFlag(ItemHasContents, true); connect(KIconLoader::global(), SIGNAL(iconLoaderSettingsChanged()), this, SIGNAL(implicitWidthChanged())); connect(KIconLoader::global(), SIGNAL(iconLoaderSettingsChanged()), this, SIGNAL(implicitHeightChanged())); connect(this, &QQuickItem::enabledChanged, this, &IconItem::enabledChanged); connect(this, &QQuickItem::windowChanged, this, &IconItem::schedulePixmapUpdate); connect(this, SIGNAL(overlaysChanged()), this, SLOT(schedulePixmapUpdate())); connect(this, SIGNAL(providesColorsChanged()), this, SLOT(schedulePixmapUpdate())); //initialize implicit size to the Dialog size setImplicitWidth(KIconLoader::global()->currentSize(KIconLoader::Dialog)); setImplicitHeight(KIconLoader::global()->currentSize(KIconLoader::Dialog)); setSmooth(true); } IconItem::~IconItem() { } void IconItem::setSource(const QVariant &source) { if (source == m_source) { return; } m_source = source; QString sourceString = source.toString(); // If the QIcon was created with QIcon::fromTheme(), try to load it as svg if (source.canConvert<QIcon>() && !source.value<QIcon>().name().isEmpty()) { sourceString = source.value<QIcon>().name(); } if (!sourceString.isEmpty()) { setLastValidSourceName(sourceString); setLastLoadedSourceId(sourceString); //If a url in the form file:// is passed, take the image pointed by that from disk QUrl url(sourceString); if (url.isLocalFile()) { m_icon = QIcon(); m_imageIcon = QImage(url.path()); m_svgIconName.clear(); m_svgIcon.reset(); } else { if (!m_svgIcon) { m_svgIcon = std::make_unique<Plasma::Svg>(this); m_svgIcon->setColorGroup(m_colorGroup); m_svgIcon->setStatus(Plasma::Svg::Normal); m_svgIcon->setUsingRenderingCache(false); m_svgIcon->setDevicePixelRatio((window() ? window()->devicePixelRatio() : qApp->devicePixelRatio())); connect(m_svgIcon.get(), &Plasma::Svg::repaintNeeded, this, &IconItem::schedulePixmapUpdate); } if (m_usesPlasmaTheme) { //try as a svg icon from plasma theme m_svgIcon->setImagePath(QLatin1String("icons/") + sourceString.split('-').first()); m_svgIcon->setContainsMultipleImages(true); //invalidate the image path to recalculate it later } else { m_svgIcon->setImagePath(QString()); } //success? if (m_svgIcon->isValid() && m_svgIcon->hasElement(sourceString)) { m_icon = QIcon(); m_svgIconName = sourceString; //ok, svg not available from the plasma theme } else { //try to load from iconloader an svg with Plasma::Svg const auto *iconTheme = KIconLoader::global()->theme(); QString iconPath; if (iconTheme) { iconPath = iconTheme->iconPath(sourceString + QLatin1String(".svg") , static_cast<int>(qMin(width(), height())) , KIconLoader::MatchBest); if (iconPath.isEmpty()) { iconPath = iconTheme->iconPath(sourceString + QLatin1String(".svgz") , static_cast<int>(qMin(width(), height())) , KIconLoader::MatchBest); } } else { qWarning() << "KIconLoader has no theme set"; } if (!iconPath.isEmpty()) { m_svgIcon->setImagePath(iconPath); m_svgIconName = sourceString; //fail, use QIcon } else { //if we started with a QIcon use that. m_icon = source.value<QIcon>(); if (m_icon.isNull()) { m_icon = QIcon::fromTheme(sourceString); } m_svgIconName.clear(); m_svgIcon.reset(); m_imageIcon = QImage(); } } } } else if (source.canConvert<QIcon>()) { m_icon = source.value<QIcon>(); m_iconCounter++; setLastLoadedSourceId("_icon_"+QString::number(m_iconCounter)); m_imageIcon = QImage(); m_svgIconName.clear(); m_svgIcon.reset(); } else if (source.canConvert<QImage>()) { m_imageIcon = source.value<QImage>(); m_iconCounter++; setLastLoadedSourceId("_image_"+QString::number(m_iconCounter)); m_icon = QIcon(); m_svgIconName.clear(); m_svgIcon.reset(); } else { m_icon = QIcon(); m_imageIcon = QImage(); m_svgIconName.clear(); m_svgIcon.reset(); } if (width() > 0 && height() > 0) { schedulePixmapUpdate(); } emit sourceChanged(); emit validChanged(); } QVariant IconItem::source() const { return m_source; } void IconItem::setLastLoadedSourceId(QString id) { if (m_lastLoadedSourceId == id) { return; } m_lastLoadedSourceId = id; } QString IconItem::lastValidSourceName() { return m_lastValidSourceName; } void IconItem::setLastValidSourceName(QString name) { if (m_lastValidSourceName == name || name == "" || name == "application-x-executable") { return; } m_lastValidSourceName = name; emit lastValidSourceNameChanged(); } void IconItem::setColorGroup(Plasma::Theme::ColorGroup group) { if (m_colorGroup == group) { return; } m_colorGroup = group; if (m_svgIcon) { m_svgIcon->setColorGroup(group); } emit colorGroupChanged(); } Plasma::Theme::ColorGroup IconItem::colorGroup() const { return m_colorGroup; } void IconItem::setOverlays(const QStringList &overlays) { if (overlays == m_overlays) { return; } m_overlays = overlays; emit overlaysChanged(); } QStringList IconItem::overlays() const { return m_overlays; } bool IconItem::isActive() const { return m_active; } void IconItem::setActive(bool active) { if (m_active == active) { return; } m_active = active; if (isComponentComplete()) { schedulePixmapUpdate(); } emit activeChanged(); } bool IconItem::providesColors() const { return m_providesColors; } void IconItem::setProvidesColors(const bool provides) { if (m_providesColors == provides) { return; } m_providesColors = provides; emit providesColorsChanged(); } void IconItem::setSmooth(const bool smooth) { if (smooth == m_smooth) { return; } m_smooth = smooth; update(); } bool IconItem::smooth() const { return m_smooth; } bool IconItem::isValid() const { return !m_icon.isNull() || m_svgIcon || !m_imageIcon.isNull(); } int IconItem::paintedWidth() const { return boundingRect().size().toSize().width(); } int IconItem::paintedHeight() const { return boundingRect().size().toSize().height(); } bool IconItem::usesPlasmaTheme() const { return m_usesPlasmaTheme; } void IconItem::setUsesPlasmaTheme(bool usesPlasmaTheme) { if (m_usesPlasmaTheme == usesPlasmaTheme) { return; } m_usesPlasmaTheme = usesPlasmaTheme; // Reload icon with new settings const QVariant src = m_source; m_source.clear(); setSource(src); update(); emit usesPlasmaThemeChanged(); } void IconItem::updatePolish() { QQuickItem::updatePolish(); loadPixmap(); } QSGNode *IconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData) { Q_UNUSED(updatePaintNodeData) if (m_iconPixmap.isNull() || width() < 1.0 || height() < 1.0) { delete oldNode; return nullptr; } ManagedTextureNode *textureNode = dynamic_cast<ManagedTextureNode *>(oldNode); if (!textureNode || m_textureChanged) { if (oldNode) delete oldNode; textureNode = new ManagedTextureNode; textureNode->setTexture(QSharedPointer<QSGTexture>(window()->createTextureFromImage(m_iconPixmap.toImage(), QQuickWindow::TextureCanUseAtlas))); textureNode->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest); m_sizeChanged = true; m_textureChanged = false; } if (m_sizeChanged) { const auto iconSize = qMin(boundingRect().size().width(), boundingRect().size().height()); const QRectF destRect(QPointF(boundingRect().center() - QPointF(iconSize / 2, iconSize / 2)), QSizeF(iconSize, iconSize)); textureNode->setRect(destRect); m_sizeChanged = false; } return textureNode; } void IconItem::schedulePixmapUpdate() { polish(); } void IconItem::enabledChanged() { schedulePixmapUpdate(); } QColor IconItem::backgroundColor() const { return m_backgroundColor; } void IconItem::setBackgroundColor(QColor background) { if (m_backgroundColor == background) { return; } m_backgroundColor = background; emit backgroundColorChanged(); } QColor IconItem::glowColor() const { return m_glowColor; } void IconItem::setGlowColor(QColor glow) { if (m_glowColor == glow) { return; } m_glowColor = glow; emit glowColorChanged(); } void IconItem::updateColors() { QImage icon = m_iconPixmap.toImage(); if (icon.format() != QImage::Format_Invalid) { float rtotal = 0, gtotal = 0, btotal = 0; float total = 0.0f; for(int row=0; row<icon.height(); ++row) { QRgb *line = (QRgb *)icon.scanLine(row); for(int col=0; col<icon.width(); ++col) { QRgb pix = line[col]; int r = qRed(pix); int g = qGreen(pix); int b = qBlue(pix); int a = qAlpha(pix); float saturation = (qMax(r, qMax(g, b)) - qMin(r, qMin(g, b))) / 255.0f; float relevance = .1 + .9 * (a / 255.0f) * saturation; rtotal += (float)(r * relevance); gtotal += (float)(g * relevance); btotal += (float)(b * relevance); total += relevance * 255; } } int nr = (rtotal / total) * 255; int ng = (gtotal / total) * 255; int nb = (btotal / total) * 255; QColor tempColor(nr, ng, nb); if (tempColor.hsvSaturationF() > 0.15f) { tempColor.setHsvF(tempColor.hueF(), 0.65f, tempColor.valueF()); } tempColor.setHsvF(tempColor.hueF(), tempColor.saturationF(), 0.55f); //original 0.90f ??? setBackgroundColor(tempColor); tempColor.setHsvF(tempColor.hueF(), tempColor.saturationF(), 1.0f); setGlowColor(tempColor); } } void IconItem::loadPixmap() { if (!isComponentComplete()) { return; } const auto size = qMin(width(), height()); //final pixmap to paint QPixmap result; if (size <= 0) { m_iconPixmap = QPixmap(); update(); return; } else if (m_svgIcon) { m_svgIcon->resize(size, size); if (m_svgIcon->hasElement(m_svgIconName)) { result = m_svgIcon->pixmap(m_svgIconName); } else if (!m_svgIconName.isEmpty()) { const auto *iconTheme = KIconLoader::global()->theme(); QString iconPath; if (iconTheme) { iconPath = iconTheme->iconPath(m_svgIconName + QLatin1String(".svg") , static_cast<int>(qMin(width(), height())) , KIconLoader::MatchBest); if (iconPath.isEmpty()) { iconPath = iconTheme->iconPath(m_svgIconName + QLatin1String(".svgz"), static_cast<int>(qMin(width(), height())) , KIconLoader::MatchBest); } } else { qWarning() << "KIconLoader has no theme set"; } if (!iconPath.isEmpty()) { m_svgIcon->setImagePath(iconPath); } result = m_svgIcon->pixmap(); } } else if (!m_icon.isNull()) { result = m_icon.pixmap(QSize(static_cast<int>(size), static_cast<int>(size)) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio())); } else if (!m_imageIcon.isNull()) { result = QPixmap::fromImage(m_imageIcon); } else { m_iconPixmap = QPixmap(); update(); return; } // Strangely KFileItem::overlays() returns empty string-values, so // we need to check first whether an overlay must be drawn at all. // It is more efficient to do it here, as KIconLoader::drawOverlays() // assumes that an overlay will be drawn and has some additional // setup time. for (const QString &overlay : m_overlays) { if (!overlay.isEmpty()) { // There is at least one overlay, draw all overlays above m_pixmap // and cancel the check KIconLoader::global()->drawOverlays(m_overlays, result, KIconLoader::Desktop); break; } } if (!isEnabled()) { result = KIconLoader::global()->iconEffect()->apply(result, KIconLoader::Desktop, KIconLoader::DisabledState); } else if (m_active) { result = KIconLoader::global()->iconEffect()->apply(result, KIconLoader::Desktop, KIconLoader::ActiveState); } m_iconPixmap = result; if (m_providesColors && m_lastLoadedSourceId != m_lastColorsSourceId) { m_lastColorsSourceId = m_lastLoadedSourceId; updateColors(); } m_textureChanged = true; //don't animate initial setting update(); } void IconItem::itemChange(ItemChange change, const ItemChangeData &value) { QQuickItem::itemChange(change, value); } void IconItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { if (newGeometry.size() != oldGeometry.size()) { m_sizeChanged = true; if (newGeometry.width() > 1 && newGeometry.height() > 1) { schedulePixmapUpdate(); } else { update(); } const auto oldSize = qMin(oldGeometry.size().width(), oldGeometry.size().height()); const auto newSize = qMin(newGeometry.size().width(), newGeometry.size().height()); if (!almost_equal(oldSize, newSize, 2)) { emit paintedSizeChanged(); } } QQuickItem::geometryChanged(newGeometry, oldGeometry); } void IconItem::componentComplete() { QQuickItem::componentComplete(); schedulePixmapUpdate(); } }
27.931553
152
0.591298
VaughnValle
5d184b089a0766b1185c34f8932657fda107ae31
12,451
cpp
C++
dali/internal/event/actors/layer-impl.cpp
vcebollada/dali-core
1f880695d4f6cb871db7f946538721e882ba1633
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/event/actors/layer-impl.cpp
vcebollada/dali-core
1f880695d4f6cb871db7f946538721e882ba1633
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-03-22T10:19:17.000Z
2020-03-22T10:19:17.000Z
dali/internal/event/actors/layer-impl.cpp
fayhot/dali-core
a69ea317f30961164520664a645ac36c387055ef
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2019 Samsung Electronics 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. * */ // CLASS HEADER #include <dali/internal/event/actors/layer-impl.h> // EXTERNAL INCLUDES // INTERNAL INCLUDES #include <dali/public-api/actors/layer.h> #include <dali/public-api/common/dali-common.h> #include <dali/public-api/object/type-registry.h> #include <dali/internal/event/actors/layer-list.h> #include <dali/internal/event/common/property-helper.h> #include <dali/internal/event/common/scene-impl.h> #include <dali/internal/event/common/event-thread-services.h> using Dali::Internal::SceneGraph::UpdateManager; namespace Dali { namespace { typedef Layer::Behavior Behavior; DALI_ENUM_TO_STRING_TABLE_BEGIN( BEHAVIOR ) DALI_ENUM_TO_STRING_WITH_SCOPE( Layer, LAYER_UI ) DALI_ENUM_TO_STRING_WITH_SCOPE( Layer, LAYER_3D ) DALI_ENUM_TO_STRING_TABLE_END( BEHAVIOR ) } // namespace namespace Internal { namespace { // Properties // Name Type writable animatable constraint-input enum for index-checking DALI_PROPERTY_TABLE_BEGIN DALI_PROPERTY( "clippingEnable", BOOLEAN, true, false, true, Dali::Layer::Property::CLIPPING_ENABLE ) DALI_PROPERTY( "clippingBox", RECTANGLE, true, false, true, Dali::Layer::Property::CLIPPING_BOX ) DALI_PROPERTY( "behavior", STRING, true, false, false, Dali::Layer::Property::BEHAVIOR ) DALI_PROPERTY_TABLE_END( DEFAULT_DERIVED_ACTOR_PROPERTY_START_INDEX, LayerDefaultProperties ) // Actions const char* const ACTION_RAISE = "raise"; const char* const ACTION_LOWER = "lower"; const char* const ACTION_RAISE_TO_TOP = "raiseToTop"; const char* const ACTION_LOWER_TO_BOTTOM = "lowerToBottom"; BaseHandle Create() { return Dali::Layer::New(); } TypeRegistration mType( typeid( Dali::Layer ), typeid( Dali::Actor ), Create, LayerDefaultProperties ); TypeAction a1( mType, ACTION_RAISE, &Layer::DoAction ); TypeAction a2( mType, ACTION_LOWER, &Layer::DoAction ); TypeAction a3( mType, ACTION_RAISE_TO_TOP, &Layer::DoAction ); TypeAction a4( mType, ACTION_LOWER_TO_BOTTOM, &Layer::DoAction ); } // unnamed namespace LayerPtr Layer::New() { // create node, nodes are owned by UpdateManager SceneGraph::Layer* layerNode = SceneGraph::Layer::New(); OwnerPointer< SceneGraph::Node > transferOwnership( layerNode ); AddNodeMessage( EventThreadServices::Get().GetUpdateManager(), transferOwnership ); LayerPtr layer( new Layer( Actor::LAYER, *layerNode ) ); // Second-phase construction layer->Initialize(); return layer; } LayerPtr Layer::NewRoot( LayerList& layerList ) { // create node, nodes are owned by UpdateManager SceneGraph::Layer* rootLayer = SceneGraph::Layer::New(); OwnerPointer< SceneGraph::Layer > transferOwnership( rootLayer ); InstallRootMessage( EventThreadServices::Get().GetUpdateManager(), transferOwnership ); LayerPtr root( new Layer( Actor::ROOT_LAYER, *rootLayer ) ); // root actor is immediately considered to be on-stage root->mIsOnStage = true; // The root actor will not emit a stage connection signal so set the signalled flag here as well root->mOnStageSignalled = true; // layer-list must be set for the root layer root->mLayerList = &layerList; layerList.SetRootLayer( &(*root) ); layerList.RegisterLayer( *root ); return root; } Layer::Layer( Actor::DerivedType type, const SceneGraph::Layer& layer ) : Actor( type, layer ), mLayerList( NULL ), mClippingBox( 0, 0, 0, 0 ), mSortFunction( Layer::ZValue ), mBehavior( Dali::Layer::LAYER_UI ), mIsClipping( false ), mDepthTestDisabled( true ), mTouchConsumed( false ), mHoverConsumed( false ) { } void Layer::OnInitialize() { } Layer::~Layer() { if ( mIsRoot ) { // Guard to allow handle destruction after Core has been destroyed if( EventThreadServices::IsCoreRunning() ) { UninstallRootMessage( GetEventThreadServices().GetUpdateManager(), &GetSceneLayerOnStage() ); GetEventThreadServices().UnregisterObject( this ); } } } unsigned int Layer::GetDepth() const { return mLayerList ? mLayerList->GetDepth( this ) : 0u; } void Layer::Raise() { if ( mLayerList ) { mLayerList->RaiseLayer(*this); } } void Layer::Lower() { if ( mLayerList ) { mLayerList->LowerLayer(*this); } } void Layer::RaiseAbove( const Internal::Layer& target ) { // cannot raise above ourself, both have to be on stage if( ( this != &target ) && OnStage() && target.OnStage() ) { // get parameters depth const uint32_t targetDepth = target.GetDepth(); if( GetDepth() < targetDepth ) { MoveAbove( target ); } } } void Layer::LowerBelow( const Internal::Layer& target ) { // cannot lower below ourself, both have to be on stage if( ( this != &target ) && OnStage() && target.OnStage() ) { // get parameters depth const uint32_t targetDepth = target.GetDepth(); if( GetDepth() > targetDepth ) { MoveBelow( target ); } } } void Layer::RaiseToTop() { if ( mLayerList ) { mLayerList->RaiseLayerToTop(*this); } } void Layer::LowerToBottom() { if ( mLayerList ) { mLayerList->LowerLayerToBottom(*this); } } void Layer::MoveAbove( const Internal::Layer& target ) { // cannot raise above ourself, both have to be on stage if( ( this != &target ) && mLayerList && target.OnStage() ) { mLayerList->MoveLayerAbove(*this, target ); } } void Layer::MoveBelow( const Internal::Layer& target ) { // cannot lower below ourself, both have to be on stage if( ( this != &target ) && mLayerList && target.OnStage() ) { mLayerList->MoveLayerBelow(*this, target ); } } void Layer::SetBehavior( Dali::Layer::Behavior behavior ) { mBehavior = behavior; // Notify update side object. SetBehaviorMessage( GetEventThreadServices(), GetSceneLayerOnStage(), behavior ); // By default, disable depth test for LAYER_UI, and enable for LAYER_3D. SetDepthTestDisabled( mBehavior == Dali::Layer::LAYER_UI ); } void Layer::SetClipping(bool enabled) { if (enabled != mIsClipping) { mIsClipping = enabled; // layerNode is being used in a separate thread; queue a message to set the value SetClippingMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mIsClipping ); } } void Layer::SetClippingBox(int x, int y, int width, int height) { if( ( x != mClippingBox.x ) || ( y != mClippingBox.y ) || ( width != mClippingBox.width ) || ( height != mClippingBox.height ) ) { // Clipping box is not animatable; this is the most up-to-date value mClippingBox.Set(x, y, width, height); // Convert mClippingBox to GL based coordinates (from bottom-left) ClippingBox clippingBox( mClippingBox ); if( mScene ) { clippingBox.y = static_cast<int32_t>( mScene->GetSize().height ) - clippingBox.y - clippingBox.height; // layerNode is being used in a separate thread; queue a message to set the value SetClippingBoxMessage( GetEventThreadServices(), GetSceneLayerOnStage(), clippingBox ); } } } void Layer::SetDepthTestDisabled( bool disable ) { if( disable != mDepthTestDisabled ) { mDepthTestDisabled = disable; // Send message. // layerNode is being used in a separate thread; queue a message to set the value SetDepthTestDisabledMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mDepthTestDisabled ); } } bool Layer::IsDepthTestDisabled() const { return mDepthTestDisabled; } void Layer::SetSortFunction(Dali::Layer::SortFunctionType function) { if( function != mSortFunction ) { mSortFunction = function; // layerNode is being used in a separate thread; queue a message to set the value SetSortFunctionMessage( GetEventThreadServices(), GetSceneLayerOnStage(), mSortFunction ); } } void Layer::SetTouchConsumed( bool consume ) { mTouchConsumed = consume; } bool Layer::IsTouchConsumed() const { return mTouchConsumed; } void Layer::SetHoverConsumed( bool consume ) { mHoverConsumed = consume; } bool Layer::IsHoverConsumed() const { return mHoverConsumed; } void Layer::OnStageConnectionInternal() { if ( !mIsRoot ) { DALI_ASSERT_DEBUG( NULL == mLayerList ); // Find the ordered layer-list for ( Actor* parent = mParent; parent != NULL; parent = parent->GetParent() ) { if( parent->IsLayer() ) { Layer* parentLayer = static_cast< Layer* >( parent ); // cheaper than dynamic_cast mLayerList = parentLayer->mLayerList; } } } DALI_ASSERT_DEBUG( NULL != mLayerList ); mLayerList->RegisterLayer( *this ); } void Layer::OnStageDisconnectionInternal() { mLayerList->UnregisterLayer(*this); // mLayerList is only valid when on-stage mLayerList = NULL; } const SceneGraph::Layer& Layer::GetSceneLayerOnStage() const { return static_cast< const SceneGraph::Layer& >( GetNode() ); // we know our node is a layer node } void Layer::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue ) { if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT ) { Actor::SetDefaultProperty( index, propertyValue ); } else { switch( index ) { case Dali::Layer::Property::CLIPPING_ENABLE: { SetClipping( propertyValue.Get<bool>() ); break; } case Dali::Layer::Property::CLIPPING_BOX: { Rect<int32_t> clippingBox( propertyValue.Get<Rect<int32_t> >() ); SetClippingBox( clippingBox.x, clippingBox.y, clippingBox.width, clippingBox.height ); break; } case Dali::Layer::Property::BEHAVIOR: { Behavior behavior(Dali::Layer::LAYER_UI); if( Scripting::GetEnumeration< Behavior >( propertyValue.Get< std::string >().c_str(), BEHAVIOR_TABLE, BEHAVIOR_TABLE_COUNT, behavior ) ) { SetBehavior( behavior ); } break; } default: { DALI_LOG_WARNING( "Unknown property (%d)\n", index ); break; } } // switch(index) } // else } Property::Value Layer::GetDefaultProperty( Property::Index index ) const { Property::Value ret; if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT ) { ret = Actor::GetDefaultProperty( index ); } else { switch( index ) { case Dali::Layer::Property::CLIPPING_ENABLE: { ret = mIsClipping; break; } case Dali::Layer::Property::CLIPPING_BOX: { ret = mClippingBox; break; } case Dali::Layer::Property::BEHAVIOR: { ret = Scripting::GetLinearEnumerationName< Behavior >( GetBehavior(), BEHAVIOR_TABLE, BEHAVIOR_TABLE_COUNT ); break; } default: { DALI_LOG_WARNING( "Unknown property (%d)\n", index ); break; } } // switch(index) } return ret; } Property::Value Layer::GetDefaultPropertyCurrentValue( Property::Index index ) const { Property::Value ret; if( index < DEFAULT_ACTOR_PROPERTY_MAX_COUNT ) { ret = Actor::GetDefaultPropertyCurrentValue( index ); } else { ret = GetDefaultProperty( index ); // Layer only has event-side properties } return ret; } bool Layer::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& /*attributes*/ ) { bool done = false; Layer* layer = dynamic_cast<Layer*>( object ); if( layer ) { if( 0 == actionName.compare( ACTION_RAISE ) ) { layer->Raise(); done = true; } else if( 0 == actionName.compare( ACTION_LOWER ) ) { layer->Lower(); done = true; } else if( 0 == actionName.compare( ACTION_RAISE_TO_TOP ) ) { layer->RaiseToTop(); done = true; } else if( 0 == actionName.compare( ACTION_LOWER_TO_BOTTOM ) ) { layer->LowerToBottom(); done = true; } } return done; } } // namespace Internal } // namespace Dali
25.410204
145
0.674886
vcebollada
5d1b2a4f682f4dd4ba7a71698dff5a1e231f6ddb
1,943
cpp
C++
firmware/src/main.cpp
brianpepin/lpm
969105a6374fa65c2de4e74a119d614b32e6ea2c
[ "MIT" ]
3
2020-06-02T01:23:18.000Z
2022-02-25T22:20:24.000Z
firmware/src/main.cpp
brianpepin/lpm
969105a6374fa65c2de4e74a119d614b32e6ea2c
[ "MIT" ]
null
null
null
firmware/src/main.cpp
brianpepin/lpm
969105a6374fa65c2de4e74a119d614b32e6ea2c
[ "MIT" ]
null
null
null
#include <globals.h> #include <adc.h> #include <battery.h> #include <button.h> #include <power.h> #include <flash.h> #include <logger.h> #include <views/default.h> Button buttons[] = { {PIN_UP, BUTTON_ACTIVE_LOW}, {PIN_DOWN, BUTTON_ACTIVE_LOW}, {PIN_LEFT, BUTTON_ACTIVE_LOW}, {PIN_RIGHT, BUTTON_ACTIVE_LOW}, {PIN_SELECT, BUTTON_ACTIVE_LOW} }; DPad dpad(buttons); DefaultView defaultView; View *currentView; void setup() { Serial.begin(9600); Power::init(); display.begin(); Flash::init(); Adc::init(); Battery::init(); Logger::init(); pinMode(PIN_UP, INPUT_PULLUP); pinMode(PIN_DOWN, INPUT_PULLUP); pinMode(PIN_LEFT, INPUT_PULLUP); pinMode(PIN_RIGHT, INPUT_PULLUP); pinMode(PIN_SELECT, INPUT_PULLUP); // Start reading all button state // so buttons held down during // power up are ignored. for (unsigned int i = 0; i < COUNT_OF(buttons); i++) { buttons[i].zero(); } defaultView.init(nullptr); currentView = &defaultView; } void loop() { DPad::Action action = dpad.read(); if (action.button == Button_Select) { Power::processPowerButton(action.state); } Power::tick(); if (action.state.changed || Battery::isCharging() || Logger::isLogging()) { Power::resetSleep(); } bool newReading = Adc::update(); bool updated = currentView->processDpad(action, &currentView); updated |= currentView->update(newReading); updated |= Battery::update(); if (newReading && Logger::isLogging()) { int32_t reading; Adc::read(&reading); if (reading < 0) { reading = 0; } updated |= Logger::update(reading); } if (updated) { display.firstPage(); display.setFontDirection(0); do { currentView->render(); Battery::render(); Logger::render(); } while (display.nextPage()); } if (Battery::isDepleted()) { Power::turnOff(); } }
18.158879
75
0.626866
brianpepin
5d1d823c10e30cee858f14367fe30222b494d526
1,256
hpp
C++
gapvector_impl/gapvector_reverse_iterator_implement.hpp
Catminusminus/gapvector
cdc235fbf26022a12234057877e6189a9312c0b7
[ "Unlicense" ]
null
null
null
gapvector_impl/gapvector_reverse_iterator_implement.hpp
Catminusminus/gapvector
cdc235fbf26022a12234057877e6189a9312c0b7
[ "Unlicense" ]
2
2018-03-26T14:06:23.000Z
2018-03-29T17:08:45.000Z
gapvector_impl/gapvector_reverse_iterator_implement.hpp
Catminusminus/gapvector
cdc235fbf26022a12234057877e6189a9312c0b7
[ "Unlicense" ]
null
null
null
#ifndef GAPVECTOR_REVERSE_ITERATOR_IMPLEMENT_HPP #define GAPVECTOR_REVERSE_ITERATOR_IMPLEMENT_HPP template <typename T> void gapvectorReverseIterator<T>::increment() { --index; } template <typename T> void gapvectorReverseIterator<T>::decrement() { ++index; } template <typename T> T &gapvectorReverseIterator<T>::dereference() const { return (gap_vector->at(index - 1)); } template <typename T> bool gapvectorReverseIterator<T>::equal(const gapvectorReverseIterator<T> &anotherIterator) const { return (this->gap_vector == anotherIterator.gap_vector && this->index == anotherIterator.index); } template <typename T> size_t gapvectorReverseIterator<T>::distance_to(const gapvectorReverseIterator<T> &anotherIterator) const { if (this->index >= anotherIterator.index) { return this->index - anotherIterator.index; } return anotherIterator.index - this->index; } template <typename T> void gapvectorReverseIterator<T>::advance(size_t difference) { index -= difference; } template <typename T> gapvectorReverseIterator<T>::gapvectorReverseIterator() { } template <typename T> gapvectorReverseIterator<T>::gapvectorReverseIterator(gapvector<T> *gap_v, size_t ind) : gap_vector(gap_v), index(ind) { } #endif
22.836364
118
0.754777
Catminusminus
5d29761d3684c04b79fec3c3688e9df1d29eaf01
4,449
cpp
C++
Source/Editor/Private/Customizations/ClassFilter/ClassFilterNode.cpp
foobit/SaveExtension
390033bc757f2b694c497e22c324dcac539bcd15
[ "Apache-2.0" ]
110
2018-10-20T21:47:54.000Z
2022-03-14T03:47:58.000Z
Source/Editor/Private/Customizations/ClassFilter/ClassFilterNode.cpp
foobit/SaveExtension
390033bc757f2b694c497e22c324dcac539bcd15
[ "Apache-2.0" ]
68
2018-12-19T09:08:56.000Z
2022-03-09T06:43:38.000Z
Source/Editor/Private/Customizations/ClassFilter/ClassFilterNode.cpp
foobit/SaveExtension
390033bc757f2b694c497e22c324dcac539bcd15
[ "Apache-2.0" ]
45
2018-12-03T14:35:47.000Z
2022-03-05T01:35:24.000Z
// Copyright 2015-2020 Piperift. All Rights Reserved. #include "ClassFilterNode.h" #include <Engine/Blueprint.h> #include <PropertyHandle.h> #include "Misc/ClassFilter.h" FSEClassFilterNode::FSEClassFilterNode(const FString& InClassName, const FString& InClassDisplayName) { ClassName = InClassName; ClassDisplayName = InClassDisplayName; bPassesFilter = false; bIsBPNormalType = false; Class = nullptr; Blueprint = nullptr; } FSEClassFilterNode::FSEClassFilterNode( const FSEClassFilterNode& InCopyObject) { ClassName = InCopyObject.ClassName; ClassDisplayName = InCopyObject.ClassDisplayName; bPassesFilter = InCopyObject.bPassesFilter; FilterState = InCopyObject.FilterState; Class = InCopyObject.Class; Blueprint = InCopyObject.Blueprint; UnloadedBlueprintData = InCopyObject.UnloadedBlueprintData; ClassPath = InCopyObject.ClassPath; ParentClassPath = InCopyObject.ParentClassPath; ClassName = InCopyObject.ClassName; BlueprintAssetPath = InCopyObject.BlueprintAssetPath; bIsBPNormalType = InCopyObject.bIsBPNormalType; // We do not want to copy the child list, do not add it. It should be the only item missing. } /** * Adds the specified child to the node. * * @param Child The child to be added to this node for the tree. */ void FSEClassFilterNode::AddChild(FSEClassFilterNodePtr& Child) { ChildrenList.Add(Child); Child->ParentNode = TSharedRef<FSEClassFilterNode>{ AsShared() }; } void FSEClassFilterNode::AddUniqueChild(FSEClassFilterNodePtr& Child) { check(Child.IsValid()); if (const UClass* NewChildClass = Child->Class.Get()) { for (auto& CurrentChild : ChildrenList) { if (CurrentChild.IsValid() && CurrentChild->Class == NewChildClass) { const bool bNewChildHasMoreInfo = Child->UnloadedBlueprintData.IsValid(); const bool bOldChildHasMoreInfo = CurrentChild->UnloadedBlueprintData.IsValid(); if (bNewChildHasMoreInfo && !bOldChildHasMoreInfo) { // make sure, that new child has all needed children for (int OldChildIndex = 0; OldChildIndex < CurrentChild->ChildrenList.Num(); ++OldChildIndex) { Child->AddUniqueChild(CurrentChild->ChildrenList[OldChildIndex]); } // replace child CurrentChild = Child; } return; } } } AddChild(Child); } FString FSEClassFilterNode::GetClassName(EClassViewerNameTypeToDisplay NameType) const { switch (NameType) { case EClassViewerNameTypeToDisplay::ClassName: return ClassName; case EClassViewerNameTypeToDisplay::DisplayName: return ClassDisplayName; case EClassViewerNameTypeToDisplay::Dynamic: FString CombinedName; FString SanitizedName = FName::NameToDisplayString(ClassName, false); if (ClassDisplayName.IsEmpty() && !ClassDisplayName.Equals(SanitizedName) && !ClassDisplayName.Equals(ClassName)) { TArray<FStringFormatArg> Args; Args.Add(ClassName); Args.Add(ClassDisplayName); CombinedName = FString::Format(TEXT("{0} ({1})"), Args); } else { CombinedName = ClassName; } return MoveTemp(CombinedName); } ensureMsgf(false, TEXT("FSEClassFilterNode::GetClassName called with invalid name type.")); return ClassName; } FText FSEClassFilterNode::GetClassTooltip(bool bShortTooltip) const { if (Class.IsValid()) { return Class->GetToolTipText(bShortTooltip); } else if (Blueprint.IsValid() && Blueprint->GeneratedClass) { // #NOTE: Unloaded blueprint classes won't show tooltip for now return Blueprint->GeneratedClass->GetToolTipText(bShortTooltip); } return FText::GetEmpty(); } bool FSEClassFilterNode::IsBlueprintClass() const { return BlueprintAssetPath != NAME_None; } void FSEClassFilterNode::SetOwnFilterState(EClassFilterState State) { FilterState = State; } void FSEClassFilterNode::SetStateFromFilter(const FSEClassFilter& Filter) { const TSoftClassPtr<> ClassAsset{ ClassPath.ToString() }; if (Filter.AllowedClasses.Contains(ClassAsset)) { FilterState = EClassFilterState::Allowed; } else if (Filter.IgnoredClasses.Contains(ClassAsset)) { FilterState = EClassFilterState::Denied; } else { FilterState = EClassFilterState::None; } } EClassFilterState FSEClassFilterNode::GetParentFilterState() const { FSEClassFilterNodePtr Parent = ParentNode.Pin(); while (Parent) { // return first parent found filter if (Parent->FilterState != EClassFilterState::None) return Parent->FilterState; Parent = Parent->ParentNode.Pin(); } return EClassFilterState::None; }
26.017544
115
0.757249
foobit
5d2a22a3ee1d87aaad98253af00bf68a0238fa0e
2,820
cpp
C++
libs/network/src/p2pservice/identity_cache.cpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/network/src/p2pservice/identity_cache.cpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/network/src/p2pservice/identity_cache.cpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
2
2019-11-13T10:55:24.000Z
2019-11-13T11:37:09.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "network/p2pservice/identity_cache.hpp" #include <algorithm> #include <iterator> namespace fetch { namespace p2p { void IdentityCache::Update(ConnectionMap const &connections) { FETCH_LOCK(lock_); for (auto const &element : connections) { auto const &address = element.first; auto const &uri = element.second; UpdateInternal(address, uri); } } void IdentityCache::Update(Address const &address, Uri const &uri) { FETCH_LOCK(lock_); UpdateInternal(address, uri); } bool IdentityCache::Lookup(Address const &address, Uri &uri) const { bool success = false; FETCH_LOCK(lock_); auto it = cache_.find(address); if (it != cache_.end()) { uri = it->second.uri; success = true; } return success; } IdentityCache::AddressSet IdentityCache::FilterOutUnresolved(AddressSet const &addresses) { AddressSet resolvedAddresses; { FETCH_LOCK(lock_); std::copy_if(addresses.begin(), addresses.end(), std::inserter(resolvedAddresses, resolvedAddresses.begin()), [this](Address const &address) { bool resolved = false; auto it = cache_.find(address); if ((it != cache_.end()) && (it->second.uri.scheme() != Uri::Scheme::Muddle)) { resolved = true; } return resolved; }); } return resolvedAddresses; } void IdentityCache::UpdateInternal(Address const &address, Uri const &uri) { auto cache_it = cache_.find(address); if (cache_it != cache_.end()) { auto &cache_entry = cache_it->second; // if the cache entry exists them only update it if the if (uri.scheme() != Uri::Scheme::Muddle) { cache_entry.uri = uri; cache_entry.last_update = Clock::now(); cache_entry.resolve = false; // This entry is considered resolved } } else { cache_.emplace(address, uri); } } } // namespace p2p } // namespace fetch
25.87156
96
0.599645
jinmannwong
5d2a6ba7920af77702281f15fe3eef4a488cbdd0
21,032
cpp
C++
planning/obstacle_cruise_planner/src/pid_based_planner/pid_based_planner.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
null
null
null
planning/obstacle_cruise_planner/src/pid_based_planner/pid_based_planner.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
null
null
null
planning/obstacle_cruise_planner/src/pid_based_planner/pid_based_planner.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 TIER IV, Inc. // // 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 "obstacle_cruise_planner/pid_based_planner/pid_based_planner.hpp" #include "obstacle_cruise_planner/utils.hpp" #include "tier4_autoware_utils/tier4_autoware_utils.hpp" #include "tier4_planning_msgs/msg/velocity_limit.hpp" namespace { StopSpeedExceeded createStopSpeedExceededMsg( const rclcpp::Time & current_time, const bool stop_flag) { StopSpeedExceeded msg{}; msg.stamp = current_time; msg.stop_speed_exceeded = stop_flag; return msg; } VelocityLimit createVelocityLimitMsg( const rclcpp::Time & current_time, const double vel, const double acc, const double max_jerk, const double min_jerk) { VelocityLimit msg; msg.stamp = current_time; msg.sender = "obstacle_cruise_planner"; msg.use_constraints = true; msg.max_velocity = vel; if (acc < 0) { msg.constraints.min_acceleration = acc; } msg.constraints.max_jerk = max_jerk; msg.constraints.min_jerk = min_jerk; return msg; } Float32MultiArrayStamped convertDebugValuesToMsg( const rclcpp::Time & current_time, const DebugValues & debug_values) { Float32MultiArrayStamped debug_msg{}; debug_msg.stamp = current_time; for (const auto & v : debug_values.getValues()) { debug_msg.data.push_back(v); } return debug_msg; } template <class T> size_t getIndexWithLongitudinalOffset( const T & points, const double longitudinal_offset, boost::optional<size_t> start_idx) { if (points.empty()) { throw std::logic_error("points is empty."); } if (start_idx) { if (/*start_idx.get() < 0 || */ points.size() <= start_idx.get()) { throw std::out_of_range("start_idx is out of range."); } } else { if (longitudinal_offset > 0) { start_idx = 0; } else { start_idx = points.size() - 1; } } double sum_length = 0.0; if (longitudinal_offset > 0) { for (size_t i = start_idx.get(); i < points.size() - 1; ++i) { const double segment_length = tier4_autoware_utils::calcDistance2d(points.at(i), points.at(i + 1)); sum_length += segment_length; if (sum_length >= longitudinal_offset) { const double front_length = segment_length; const double back_length = sum_length - longitudinal_offset; if (front_length < back_length) { return i; } else { return i + 1; } } } return points.size() - 1; } for (size_t i = start_idx.get(); i > 0; --i) { const double segment_length = tier4_autoware_utils::calcDistance2d(points.at(i), points.at(i + 1)); sum_length += segment_length; if (sum_length >= -longitudinal_offset) { const double front_length = segment_length; const double back_length = sum_length + longitudinal_offset; if (front_length < back_length) { return i; } else { return i + 1; } } } return 0; } double calcMinimumDistanceToStop(const double initial_vel, const double min_acc) { return -std::pow(initial_vel, 2) / 2.0 / min_acc; } tier4_planning_msgs::msg::StopReasonArray makeStopReasonArray( const rclcpp::Time & current_time, const geometry_msgs::msg::Pose & stop_pose, const boost::optional<PIDBasedPlanner::StopObstacleInfo> & stop_obstacle_info) { // create header std_msgs::msg::Header header; header.frame_id = "map"; header.stamp = current_time; // create stop factor tier4_planning_msgs::msg::StopFactor stop_factor; stop_factor.stop_pose = stop_pose; if (stop_obstacle_info) { stop_factor.stop_factor_points.emplace_back(stop_obstacle_info->obstacle.collision_point); } // create stop reason stamped tier4_planning_msgs::msg::StopReason stop_reason_msg; stop_reason_msg.reason = tier4_planning_msgs::msg::StopReason::OBSTACLE_STOP; stop_reason_msg.stop_factors.emplace_back(stop_factor); // create stop reason array tier4_planning_msgs::msg::StopReasonArray stop_reason_array; stop_reason_array.header = header; stop_reason_array.stop_reasons.emplace_back(stop_reason_msg); return stop_reason_array; } } // namespace PIDBasedPlanner::PIDBasedPlanner( rclcpp::Node & node, const LongitudinalInfo & longitudinal_info, const vehicle_info_util::VehicleInfo & vehicle_info) : PlannerInterface(node, longitudinal_info, vehicle_info) { min_accel_during_cruise_ = node.declare_parameter<double>("pid_based_planner.min_accel_during_cruise"); // pid controller const double kp = node.declare_parameter<double>("pid_based_planner.kp"); const double ki = node.declare_parameter<double>("pid_based_planner.ki"); const double kd = node.declare_parameter<double>("pid_based_planner.kd"); pid_controller_ = std::make_unique<PIDController>(kp, ki, kd); output_ratio_during_accel_ = node.declare_parameter<double>("pid_based_planner.output_ratio_during_accel"); // some parameters // use_predicted_obstacle_pose_ = // node.declare_parameter<bool>("pid_based_planner.use_predicted_obstacle_pose"); vel_to_acc_weight_ = node.declare_parameter<double>("pid_based_planner.vel_to_acc_weight"); min_cruise_target_vel_ = node.declare_parameter<double>("pid_based_planner.min_cruise_target_vel"); obstacle_velocity_threshold_from_cruise_to_stop_ = node.declare_parameter<double>( "pid_based_planner.obstacle_velocity_threshold_from_cruise_to_stop"); // publisher stop_reasons_pub_ = node.create_publisher<tier4_planning_msgs::msg::StopReasonArray>("~/output/stop_reasons", 1); stop_speed_exceeded_pub_ = node.create_publisher<StopSpeedExceeded>("~/output/stop_speed_exceeded", 1); debug_values_pub_ = node.create_publisher<Float32MultiArrayStamped>("~/debug/values", 1); } Trajectory PIDBasedPlanner::generateTrajectory( const ObstacleCruisePlannerData & planner_data, boost::optional<VelocityLimit> & vel_limit, DebugData & debug_data) { stop_watch_.tic(__func__); debug_values_.resetValues(); // calc obstacles to cruise and stop boost::optional<StopObstacleInfo> stop_obstacle_info; boost::optional<CruiseObstacleInfo> cruise_obstacle_info; calcObstaclesToCruiseAndStop(planner_data, stop_obstacle_info, cruise_obstacle_info); // plan cruise planCruise(planner_data, vel_limit, cruise_obstacle_info, debug_data); // plan stop const auto output_traj = planStop(planner_data, stop_obstacle_info, debug_data); // publish debug values publishDebugValues(planner_data); const double calculation_time = stop_watch_.toc(__func__); RCLCPP_INFO_EXPRESSION( rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_, " %s := %f [ms]", __func__, calculation_time); return output_traj; } void PIDBasedPlanner::calcObstaclesToCruiseAndStop( const ObstacleCruisePlannerData & planner_data, boost::optional<StopObstacleInfo> & stop_obstacle_info, boost::optional<CruiseObstacleInfo> & cruise_obstacle_info) { debug_values_.setValues(DebugValues::TYPE::CURRENT_VELOCITY, planner_data.current_vel); debug_values_.setValues(DebugValues::TYPE::CURRENT_ACCELERATION, planner_data.current_acc); // search highest probability obstacle for stop and cruise for (const auto & obstacle : planner_data.target_obstacles) { // NOTE: from ego's front to obstacle's back const double dist_to_obstacle = calcDistanceToObstacle(planner_data, obstacle); const bool is_stop_required = isStopRequired(obstacle); if (is_stop_required) { // stop // calculate error distance (= distance to stop) const double error_dist = dist_to_obstacle - longitudinal_info_.safe_distance_margin; if (stop_obstacle_info) { if (error_dist > stop_obstacle_info->dist_to_stop) { return; } } stop_obstacle_info = StopObstacleInfo(obstacle, error_dist); // update debug values debug_values_.setValues(DebugValues::TYPE::STOP_CURRENT_OBJECT_DISTANCE, dist_to_obstacle); debug_values_.setValues(DebugValues::TYPE::STOP_CURRENT_OBJECT_VELOCITY, obstacle.velocity); debug_values_.setValues( DebugValues::TYPE::STOP_TARGET_OBJECT_DISTANCE, longitudinal_info_.safe_distance_margin); debug_values_.setValues( DebugValues::TYPE::STOP_TARGET_ACCELERATION, longitudinal_info_.min_strong_accel); debug_values_.setValues(DebugValues::TYPE::STOP_ERROR_OBJECT_DISTANCE, error_dist); } else { // cruise // calculate distance between ego and obstacle based on RSS const double rss_dist = calcRSSDistance( planner_data.current_vel, obstacle.velocity, longitudinal_info_.safe_distance_margin); // calculate error distance and normalized one const double error_dist = dist_to_obstacle - rss_dist; if (cruise_obstacle_info) { if (error_dist > cruise_obstacle_info->dist_to_cruise) { return; } } const double normalized_dist_to_cruise = error_dist / dist_to_obstacle; cruise_obstacle_info = CruiseObstacleInfo(obstacle, error_dist, normalized_dist_to_cruise); // update debug values debug_values_.setValues(DebugValues::TYPE::CRUISE_CURRENT_OBJECT_VELOCITY, obstacle.velocity); debug_values_.setValues(DebugValues::TYPE::CRUISE_CURRENT_OBJECT_DISTANCE, dist_to_obstacle); debug_values_.setValues(DebugValues::TYPE::CRUISE_TARGET_OBJECT_DISTANCE, rss_dist); debug_values_.setValues(DebugValues::TYPE::CRUISE_ERROR_OBJECT_DISTANCE, error_dist); } } } double PIDBasedPlanner::calcDistanceToObstacle( const ObstacleCruisePlannerData & planner_data, const TargetObstacle & obstacle) { const double offset = vehicle_info_.max_longitudinal_offset_m; // TODO(murooka) enable this option considering collision_point (precise obstacle point to measure // distance) if (use_predicted_obstacle_pose_) { // // interpolate current obstacle pose from predicted path // const auto current_interpolated_obstacle_pose = // obstacle_cruise_utils::getCurrentObjectPoseFromPredictedPath( // obstacle.predicted_paths.at(0), obstacle.time_stamp, planner_data.current_time); // if (current_interpolated_obstacle_pose) { // return tier4_autoware_utils::calcSignedArcLength( // planner_data.traj.points, planner_data.current_pose.position, // current_interpolated_obstacle_pose->position) - offset; // } // // RCLCPP_INFO_EXPRESSION( // rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), true, // "Failed to interpolated obstacle pose from predicted path. Use non-interpolated obstacle // pose."); // } const size_t ego_idx = findExtendedNearestIndex(planner_data.traj, planner_data.current_pose); return tier4_autoware_utils::calcSignedArcLength( planner_data.traj.points, ego_idx, obstacle.collision_point) - offset; } // Note: If stop planning is not required, cruise planning will be done instead. bool PIDBasedPlanner::isStopRequired(const TargetObstacle & obstacle) { const bool is_cruise_obstacle = isCruiseObstacle(obstacle.classification.label); const bool is_stop_obstacle = isStopObstacle(obstacle.classification.label); if (is_cruise_obstacle) { return std::abs(obstacle.velocity) < obstacle_velocity_threshold_from_cruise_to_stop_; } else if (is_stop_obstacle && !is_cruise_obstacle) { return true; } return false; } Trajectory PIDBasedPlanner::planStop( const ObstacleCruisePlannerData & planner_data, const boost::optional<StopObstacleInfo> & stop_obstacle_info, DebugData & debug_data) { bool will_collide_with_obstacle = false; size_t zero_vel_idx = 0; bool zero_vel_found = false; if (stop_obstacle_info) { RCLCPP_INFO_EXPRESSION( rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_, "stop planning"); auto local_stop_obstacle_info = stop_obstacle_info.get(); // check if the ego will collide with the obstacle with a limit acceleration const double feasible_dist_to_stop = calcMinimumDistanceToStop(planner_data.current_vel, longitudinal_info_.min_strong_accel); if (local_stop_obstacle_info.dist_to_stop < feasible_dist_to_stop) { will_collide_with_obstacle = true; local_stop_obstacle_info.dist_to_stop = feasible_dist_to_stop; } // set zero velocity index const auto opt_zero_vel_idx = doStop( planner_data, local_stop_obstacle_info, debug_data.obstacles_to_stop, debug_data.stop_wall_marker); if (opt_zero_vel_idx) { zero_vel_idx = opt_zero_vel_idx.get(); zero_vel_found = true; } } // generate output trajectory auto output_traj = planner_data.traj; if (zero_vel_found) { // publish stop reason const auto stop_pose = planner_data.traj.points.at(zero_vel_idx).pose; const auto stop_reasons_msg = makeStopReasonArray(planner_data.current_time, stop_pose, stop_obstacle_info); stop_reasons_pub_->publish(stop_reasons_msg); // insert zero_velocity for (size_t traj_idx = zero_vel_idx; traj_idx < output_traj.points.size(); ++traj_idx) { output_traj.points.at(traj_idx).longitudinal_velocity_mps = 0.0; } } // publish stop_speed_exceeded if the ego will collide with the obstacle const auto stop_speed_exceeded_msg = createStopSpeedExceededMsg(planner_data.current_time, will_collide_with_obstacle); stop_speed_exceeded_pub_->publish(stop_speed_exceeded_msg); return output_traj; } boost::optional<size_t> PIDBasedPlanner::doStop( const ObstacleCruisePlannerData & planner_data, const StopObstacleInfo & stop_obstacle_info, std::vector<TargetObstacle> & debug_obstacles_to_stop, visualization_msgs::msg::MarkerArray & debug_wall_marker) const { const size_t ego_idx = findExtendedNearestIndex(planner_data.traj, planner_data.current_pose); // TODO(murooka) Should I use interpolation? const auto modified_stop_info = [&]() -> boost::optional<std::pair<size_t, double>> { const double dist_to_stop = stop_obstacle_info.dist_to_stop; const size_t obstacle_zero_vel_idx = getIndexWithLongitudinalOffset(planner_data.traj.points, dist_to_stop, ego_idx); // check if there is already stop line between obstacle and zero_vel_idx const auto behavior_zero_vel_idx = tier4_autoware_utils::searchZeroVelocityIndex(planner_data.traj.points); if (behavior_zero_vel_idx) { const double zero_vel_diff_length = tier4_autoware_utils::calcSignedArcLength( planner_data.traj.points, obstacle_zero_vel_idx, behavior_zero_vel_idx.get()); if ( 0 < zero_vel_diff_length && zero_vel_diff_length < longitudinal_info_.safe_distance_margin) { const double modified_dist_to_stop = dist_to_stop + longitudinal_info_.safe_distance_margin - min_behavior_stop_margin_; const size_t modified_obstacle_zero_vel_idx = getIndexWithLongitudinalOffset(planner_data.traj.points, modified_dist_to_stop, ego_idx); return std::make_pair(modified_obstacle_zero_vel_idx, modified_dist_to_stop); } } return std::make_pair(obstacle_zero_vel_idx, dist_to_stop); }(); if (!modified_stop_info) { return {}; } const size_t modified_zero_vel_idx = modified_stop_info->first; const double modified_dist_to_stop = modified_stop_info->second; // virtual wall marker for stop const auto marker_pose = obstacle_cruise_utils::calcForwardPose( planner_data.traj, ego_idx, modified_dist_to_stop + vehicle_info_.max_longitudinal_offset_m); if (marker_pose) { visualization_msgs::msg::MarkerArray wall_msg; const auto markers = tier4_autoware_utils::createStopVirtualWallMarker( marker_pose.get(), "obstacle stop", planner_data.current_time, 0); tier4_autoware_utils::appendMarkerArray(markers, &debug_wall_marker); } debug_obstacles_to_stop.push_back(stop_obstacle_info.obstacle); return modified_zero_vel_idx; } void PIDBasedPlanner::planCruise( const ObstacleCruisePlannerData & planner_data, boost::optional<VelocityLimit> & vel_limit, const boost::optional<CruiseObstacleInfo> & cruise_obstacle_info, DebugData & debug_data) { // do cruise if (cruise_obstacle_info) { RCLCPP_INFO_EXPRESSION( rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_, "cruise planning"); vel_limit = doCruise( planner_data, cruise_obstacle_info.get(), debug_data.obstacles_to_cruise, debug_data.cruise_wall_marker); // update debug values debug_values_.setValues(DebugValues::TYPE::CRUISE_TARGET_VELOCITY, vel_limit->max_velocity); debug_values_.setValues( DebugValues::TYPE::CRUISE_TARGET_ACCELERATION, vel_limit->constraints.min_acceleration); } else { // reset previous target velocity if adaptive cruise is not enabled prev_target_vel_ = {}; } } VelocityLimit PIDBasedPlanner::doCruise( const ObstacleCruisePlannerData & planner_data, const CruiseObstacleInfo & cruise_obstacle_info, std::vector<TargetObstacle> & debug_obstacles_to_cruise, visualization_msgs::msg::MarkerArray & debug_wall_marker) { const double dist_to_cruise = cruise_obstacle_info.dist_to_cruise; const double normalized_dist_to_cruise = cruise_obstacle_info.normalized_dist_to_cruise; const size_t ego_idx = findExtendedNearestIndex(planner_data.traj, planner_data.current_pose); // calculate target velocity with acceleration limit by PID controller const double pid_output_vel = pid_controller_->calc(normalized_dist_to_cruise); [[maybe_unused]] const double prev_vel = prev_target_vel_ ? prev_target_vel_.get() : planner_data.current_vel; const double additional_vel = [&]() { if (normalized_dist_to_cruise > 0) { return pid_output_vel * output_ratio_during_accel_; } return pid_output_vel; }(); const double positive_target_vel = std::max(min_cruise_target_vel_, planner_data.current_vel + additional_vel); // calculate target acceleration const double target_acc = vel_to_acc_weight_ * additional_vel; const double target_acc_with_acc_limit = std::clamp(target_acc, min_accel_during_cruise_, longitudinal_info_.max_accel); RCLCPP_INFO_EXPRESSION( rclcpp::get_logger("ObstacleCruisePlanner::PIDBasedPlanner"), is_showing_debug_info_, "target_velocity %f", positive_target_vel); prev_target_vel_ = positive_target_vel; // set target longitudinal motion const auto vel_limit = createVelocityLimitMsg( planner_data.current_time, positive_target_vel, target_acc_with_acc_limit, longitudinal_info_.max_jerk, longitudinal_info_.min_jerk); // virtual wall marker for cruise const double dist_to_rss_wall = dist_to_cruise + vehicle_info_.max_longitudinal_offset_m; const size_t wall_idx = getIndexWithLongitudinalOffset(planner_data.traj.points, dist_to_rss_wall, ego_idx); const auto markers = tier4_autoware_utils::createSlowDownVirtualWallMarker( planner_data.traj.points.at(wall_idx).pose, "obstacle cruise", planner_data.current_time, 0); tier4_autoware_utils::appendMarkerArray(markers, &debug_wall_marker); debug_obstacles_to_cruise.push_back(cruise_obstacle_info.obstacle); return vel_limit; } void PIDBasedPlanner::publishDebugValues(const ObstacleCruisePlannerData & planner_data) const { const auto debug_values_msg = convertDebugValuesToMsg(planner_data.current_time, debug_values_); debug_values_pub_->publish(debug_values_msg); } void PIDBasedPlanner::updateParam(const std::vector<rclcpp::Parameter> & parameters) { tier4_autoware_utils::updateParam<double>( parameters, "pid_based_planner.min_accel_during_cruise", min_accel_during_cruise_); // pid controller double kp = pid_controller_->getKp(); double ki = pid_controller_->getKi(); double kd = pid_controller_->getKd(); tier4_autoware_utils::updateParam<double>(parameters, "pid_based_planner.kp", kp); tier4_autoware_utils::updateParam<double>(parameters, "pid_based_planner.ki", ki); tier4_autoware_utils::updateParam<double>(parameters, "pid_based_planner.kd", kd); tier4_autoware_utils::updateParam<double>( parameters, "pid_based_planner.output_ratio_during_accel", output_ratio_during_accel_); // vel_to_acc_weight tier4_autoware_utils::updateParam<double>( parameters, "pid_based_planner.vel_to_acc_weight", vel_to_acc_weight_); // min_cruise_target_vel tier4_autoware_utils::updateParam<double>( parameters, "pid_based_planner.min_cruise_target_vel", min_cruise_target_vel_); pid_controller_->updateParam(kp, ki, kd); }
39.092937
100
0.762695
meliketanrikulu
5d2b1c78a5d1d15b83368bca74be19fd8364237f
1,811
cpp
C++
String/Reverse string with no change in words.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
1
2021-07-20T06:08:26.000Z
2021-07-20T06:08:26.000Z
String/Reverse string with no change in words.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
null
null
null
String/Reverse string with no change in words.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
null
null
null
// QUARANTINE DAYS..;) #include <bits/stdc++.h> using namespace std; #define endl "\n" #define test int tt;cin>>tt;while(tt--) #define fl(i,a,b) for( int i=a;i<b;i++) #define ll long long int #define pb push_back #define mp make_pair #define MOD 1000000007 #define PI acos(-1.0) #define assign(x,val) memset(x,val,sizeof(x)) #define pr(gg) cout<<gg<<endl #define mk(arr,n,type) type *arr=new type[n]; void lage_rho() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } /**********============########################============***********/ void rev(string& s) { int i = 0; for (int j = 0; j < s.size(); j++) { if (s[j] == ' ') reverse(s.begin() + i, s.end() + j); i = j + 1; } // Reverse the last word reverse(s.begin() + i, s.end()); // Reverse the entire string reverse(s.begin(), s.end()); } string reverseString(string str) { // Reverse str using inbuilt function reverse(str.begin(), str.end()); // Add space at the end so that the // last word is also reversed str.insert(str.end(), ' '); int n = str.length(); int j = 0; // Find spaces and reverse all words // before that for (int i = 0; i < n; i++) { // If a space is encountered if (str[i] == ' ') { reverse(str.begin() + j, str.begin() + i); // Update the starting index // for next word to reverse j = i + 1; } } // Remove spaces from the end of the // word that we appended str.pop_back(); // Return the reversed string return str; } void solve() { string s = " .aditya singh sisodiya"; // rev(s); string st = reverseString(s); cout << st; } int32_t main() { lage_rho(); solve(); return 0; }
19.684783
71
0.563777
scortier
5d2cdb5eed2575ef74e606ac0e99d16af6a15662
503
hpp
C++
plugins/opengl/include/sge/opengl/glx/visual/optional_srgb_flag.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/include/sge/opengl/glx/visual/optional_srgb_flag.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/include/sge/opengl/glx/visual/optional_srgb_flag.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_OPENGL_GLX_VISUAL_OPTIONAL_SRGB_FLAG_HPP_INCLUDED #define SGE_OPENGL_GLX_VISUAL_OPTIONAL_SRGB_FLAG_HPP_INCLUDED #include <sge/opengl/glx/visual/optional_srgb_flag_fwd.hpp> #include <sge/opengl/glx/visual/srgb_flag.hpp> #include <fcppt/optional/object_impl.hpp> #endif
35.928571
61
0.781312
cpreh
5d300fcbc8b3d333153f560939896bb5881e474e
247
hpp
C++
include/System/NonCopyable.hpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
include/System/NonCopyable.hpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
include/System/NonCopyable.hpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
#pragma once namespace ng { class NonCopyable { protected: NonCopyable() = default; ~NonCopyable() = default; private: NonCopyable(const NonCopyable &) = delete; NonCopyable &operator=(const NonCopyable &) = delete; }; } // namespace ng
17.642857
55
0.704453
Mac1512
5d308de96ca733a52327049c72673fcc2a7127e0
1,852
cpp
C++
src/hssh/global_metric/main.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
6
2020-03-29T09:37:01.000Z
2022-01-20T08:56:31.000Z
src/hssh/global_metric/main.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
1
2021-03-05T08:00:50.000Z
2021-03-05T08:00:50.000Z
src/hssh/global_metric/main.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
11
2019-05-13T00:04:38.000Z
2022-01-20T08:56:38.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, [email protected]. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ #include <system/module.h> #include <hssh/global_metric/director.h> #include <utils/config_file.h> #include <utils/command_line.h> #include <vector> using namespace vulcan; int main(int argc, char** argv) { std::vector<utils::command_line_argument_t> arguments; arguments.push_back({utils::kConfigFileArgument, "Configuration file controlling the module behavior", true, "local_metric_hssh.cfg"}); arguments.push_back({hssh::kEmulateLPMArg, "Turn on or off Local Metric level emulation", true, ""}); arguments.push_back({hssh::kUpdateRateArg, "Specify the update rate for the module (Hz) (optional, default = 20)", true, "20"}); arguments.push_back({hssh::kSavePosesArg, "Save generated poses to the specified file. Specify name if not using default.", true, ""}); arguments.push_back({hssh::kMapArg, "Map in which to localize. Optional, can specify via DebugUI. Also requires " "initial-rect to be specified in order to relocalize right away.", true, ""}); arguments.push_back({hssh::kInitialRectArg, "Optional initial bounding rect to relocalize in. Format: (bl_x,bl_y)," "(tr_x,tr_y)", true, ""}); utils::CommandLine commandLine(argc, argv, arguments); commandLine.verify(); utils::ConfigFile config(commandLine.configName()); system::Module<hssh::GlobalMetricDirector> module(commandLine, config); module.run(); return 0; }
43.069767
139
0.698164
h2ssh
5d3488bdbeda335cfe226761fdf45d6f937b3c0d
18,446
cpp
C++
Base/PLCore/src/Xml/XmlElement.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/src/Xml/XmlElement.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/src/Xml/XmlElement.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: XmlElement.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLCore/File/File.h" #include "PLCore/Xml/XmlParsingData.h" #include "PLCore/Xml/XmlAttribute.h" #include "PLCore/Xml/XmlDocument.h" #include "PLCore/Xml/XmlText.h" #include "PLCore/Xml/XmlElement.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ XmlElement::XmlElement(const String &sValue) : XmlNode(Element) { m_sValue = sValue; } /** * @brief * Copy constructor */ XmlElement::XmlElement(const XmlElement &cSource) : XmlNode(Element) { *this = cSource; } /** * @brief * Destructor */ XmlElement::~XmlElement() { ClearThis(); } /** * @brief * Copy operator */ XmlElement &XmlElement::operator =(const XmlElement &cSource) { ClearThis(); m_sValue = cSource.m_sValue; m_pUserData = cSource.m_pUserData; m_cCursor = cSource.m_cCursor; // Clone the attributes for (const XmlAttribute *pAttribute=cSource.m_cAttributeSet.GetFirst(); pAttribute; pAttribute=pAttribute->GetNext()) SetAttribute(pAttribute->GetName(), pAttribute->GetValue()); // Clone the children for (const XmlNode *pNode=cSource.GetFirstChild(); pNode; pNode=pNode->GetNextSibling()) { XmlNode *pClone = pNode->Clone(); if (pClone) LinkEndChild(*pClone); } // Return a reference to this instance return *this; } /** * @brief * Given an attribute name, 'GetAttribute()' returns the value * for the attribute of that name, or a null pointer if none exists */ String XmlElement::GetAttribute(const String &sName) const { const XmlAttribute *pNode = m_cAttributeSet.Find(sName); return pNode ? pNode->GetValue() : ""; } /** * @brief * Given an attribute name, 'GetAttribute()' returns the value * for the attribute of that name, or a null pointer if none exists */ String XmlElement::GetAttribute(const String &sName, int *pnValue) const { const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName); if (pAttribute) { const String sResult = pAttribute->GetValue(); if (pnValue) pAttribute->QueryIntValue(*pnValue); return sResult; } return ""; } /** * @brief * Given an attribute name, 'GetAttribute()' returns the value * for the attribute of that name, or a null pointer if none exists */ String XmlElement::GetAttribute(const String &sName, double *pdValue) const { const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName); if (pAttribute) { const String sResult = pAttribute->GetValue(); if (pdValue) pAttribute->QueryDoubleValue(*pdValue); return sResult; } return ""; } /** * @brief * Examines the attribute */ XmlBase::EQueryResult XmlElement::QueryIntAttribute(const String &sName, int *pnValue) const { const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName); if (pAttribute) return pnValue ? pAttribute->QueryIntValue(*pnValue) : Success; else return NoAttribute; // There's no attribute with the given name } /** * @brief * Examines the attribute */ XmlBase::EQueryResult XmlElement::QueryFloatAttribute(const String &sName, float *pfValue) const { const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName); if (pAttribute) { if (pfValue) { double d = 0.0f; EQueryResult nResult = pAttribute->QueryDoubleValue(d); *pfValue = static_cast<float>(d); return nResult; } else { return Success; } } else { // There's no attribute with the given name return NoAttribute; } } /** * @brief * Examines the attribute */ XmlBase::EQueryResult XmlElement::QueryDoubleAttribute(const String &sName, double *pdValue) const { const XmlAttribute *pAttribute = m_cAttributeSet.Find(sName); if (pAttribute) return pdValue ? pAttribute->QueryDoubleValue(*pdValue) : Success; else return NoAttribute; // There's no attribute with the given name } /** * @brief * Sets an attribute of name to a given value */ void XmlElement::SetAttribute(const String &sName, const String &sValue) { XmlAttribute *pAttribute = m_cAttributeSet.FindOrCreate(sName); if (pAttribute) pAttribute->SetValue(sValue); } /** * @brief * Sets an attribute of name to a given value */ void XmlElement::SetAttribute(const String &sName, int nValue) { XmlAttribute *pAttribute = m_cAttributeSet.FindOrCreate(sName); if (pAttribute) pAttribute->SetIntValue(nValue); } /** * @brief * Sets an attribute of name to a given value */ void XmlElement::SetDoubleAttribute(const String &sName, double dValue) { XmlAttribute *pAttribute = m_cAttributeSet.FindOrCreate(sName); if (pAttribute) pAttribute->SetDoubleValue(dValue); } /** * @brief * Deletes an attribute with the given name */ void XmlElement::RemoveAttribute(const String &sName) { XmlAttribute *pAttribute = m_cAttributeSet.Find(sName); if (pAttribute) { m_cAttributeSet.Remove(*pAttribute); delete pAttribute; } } /** * @brief * Convenience function for easy access to the text inside an element */ String XmlElement::GetText() const { const XmlNode *pChild = GetFirstChild(); if (pChild) { const XmlText *pChildText = pChild->ToText(); if (pChildText) return pChildText->GetValue(); } return ""; } //[-------------------------------------------------------] //[ Public virtual XmlBase functions ] //[-------------------------------------------------------] bool XmlElement::Save(File &cFile, uint32 nDepth) { /// Get the number of empty spaces const XmlDocument *pDocument = GetDocument(); const uint32 nNumOfSpaces = (pDocument ? pDocument->GetTabSize() : 4) * nDepth; // Print empty spaces for (uint32 i=0; i<nNumOfSpaces; i++) cFile.PutC(' '); // Print value cFile.Print('<' + m_sValue); // Print attributes for (XmlAttribute *pAttribute=GetFirstAttribute(); pAttribute; pAttribute=pAttribute->GetNext()) { cFile.PutC(' '); pAttribute->Save(cFile, nDepth); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. if (!GetFirstChild()) cFile.Print(" />"); else if (GetFirstChild() == GetLastChild() && GetFirstChild()->GetType() == Text) { cFile.PutC('>'); GetFirstChild()->Save(cFile, nDepth+1); cFile.Print("</" + m_sValue + '>'); } else { cFile.PutC('>'); for (XmlNode *pNode=GetFirstChild(); pNode; pNode=pNode->GetNextSibling()) { if (pNode->GetType() != Text) cFile.PutC('\n'); pNode->Save(cFile, nDepth+1); } cFile.PutC('\n'); // Print empty spaces for (uint32 i=0; i<nNumOfSpaces; i++) cFile.PutC(' '); // Print value cFile.Print("</" + m_sValue + '>'); } // Done return true; } String XmlElement::ToString(uint32 nDepth) const { // Get the number of empty spaces const XmlDocument *pDocument = GetDocument(); const uint32 nNumOfSpaces = (pDocument ? pDocument->GetTabSize() : 4) * nDepth; // Print empty spaces String sXml; for (uint32 i=0; i<nNumOfSpaces; i++) sXml += ' '; // Print value sXml += '<' + m_sValue; // Print attributes for (const XmlAttribute *pAttribute=GetFirstAttribute(); pAttribute; pAttribute=pAttribute->GetNext()) sXml += ' ' + pAttribute->ToString(nDepth); // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. if (!GetFirstChild()) sXml += " />"; else if (GetFirstChild() == GetLastChild() && GetFirstChild()->GetType() == Text) { sXml += '>' + GetFirstChild()->ToString(nDepth+1) + "</" + m_sValue + '>'; } else { sXml += '>'; for (const XmlNode *pNode=GetFirstChild(); pNode; pNode=pNode->GetNextSibling()) { if (pNode->GetType() != Text) sXml += '\n'; sXml += pNode->ToString(nDepth+1); } sXml += '\n'; // Print empty spaces for (uint32 i=0; i<nNumOfSpaces; i++) sXml += ' '; // Print value sXml += "</" + m_sValue + '>'; } // Done return sXml; } const char *XmlElement::Parse(const char *pszData, XmlParsingData *pData, EEncoding nEncoding) { pszData = SkipWhiteSpace(pszData, nEncoding); if (!pszData || !*pszData) { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorParsingElement, 0, 0, nEncoding); // Error! return nullptr; } if (pData) { pData->Stamp(pszData, nEncoding); m_cCursor = pData->Cursor(); } if (*pszData != '<') { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorParsingElement, pszData, pData, nEncoding); // Error! return nullptr; } pszData = SkipWhiteSpace(pszData + 1, nEncoding); // Read the name const char *pszError = pszData; pszData = ReadName(pszData, m_sValue, nEncoding); if (!pszData || !*pszData) { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorFailedToReadElementName, pszError, pData, nEncoding); // Error! return nullptr; } String sEndTag = "</"; sEndTag += m_sValue; // Check for and read attributes. Also look for an empty tag or an end tag while (pszData && *pszData) { pszError = pszData; pszData = SkipWhiteSpace(pszData, nEncoding); if (!pszData || !*pszData) { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorReadingAttributes, pszError, pData, nEncoding); // Error! return nullptr; } if (*pszData == '/') { ++pszData; // Empty tag if (*pszData != '>') { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorParsingEmpty, pszData, pData, nEncoding); // Error! return nullptr; } return (pszData + 1); } else if (*pszData == '>') { // Done with attributes (if there were any) // Read the value -- which can include other elements -- read the end tag, and return ++pszData; pszData = ReadValue(pszData, pData, nEncoding); // Note this is an Element method, and will set the error if one happens if (!pszData || !*pszData) { // We were looking for the end tag, but found nothing XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorReadingEndTag, pszData, pData, nEncoding); // Error! return nullptr; } // We should find the end tag now // Note that: // </foo > and // </foo> // are both valid end tags if (StringEqual(pszData, sEndTag, false, nEncoding)) { pszData += sEndTag.GetLength(); pszData = SkipWhiteSpace(pszData, nEncoding); if (pszData && *pszData && *pszData == '>') { ++pszData; return pszData; } // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorReadingEndTag, pszData, pData, nEncoding); // Error! return nullptr; } else { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorReadingEndTag, pszData, pData, nEncoding); // Error! return nullptr; } } else { // Try to read an attribute XmlAttribute *pAttribute = new XmlAttribute(); pAttribute->m_pDocument = GetDocument(); pszError = pszData; pszData = pAttribute->Parse(pszData, pData, nEncoding); if (!pszData || !*pszData) { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorParsingElement, pszError, pData, nEncoding); // Destroy the created attribute delete pAttribute; // Error! return nullptr; } // Handle the strange case of double attributes XmlAttribute *pNode = m_cAttributeSet.Find(pAttribute->GetName()); if (pNode) { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorParsingElement, pszError, pData, nEncoding); // Destroy the created attribute delete pAttribute; // Error! return nullptr; } // Register the created attribute m_cAttributeSet.Add(*pAttribute); } } // Done return pszData; } //[-------------------------------------------------------] //[ Public virtual XmlNode functions ] //[-------------------------------------------------------] XmlNode *XmlElement::Clone() const { return new XmlElement(*this); } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Like clear, but initializes 'this' object as well */ void XmlElement::ClearThis() { Clear(); while (m_cAttributeSet.GetFirst()) { XmlAttribute *pAttribute = m_cAttributeSet.GetFirst(); m_cAttributeSet.Remove(*pAttribute); delete pAttribute; } } /** * @brief * Reads the "value" of the element -- another element, or text */ const char *XmlElement::ReadValue(const char *pszData, XmlParsingData *pData, EEncoding nEncoding) { // Read in text and elements in any order const char *pWithWhiteSpace = pszData; pszData = SkipWhiteSpace(pszData, nEncoding); while (pszData && *pszData) { if (*pszData != '<') { // Take what we have, make a text element XmlText *pTextNode = new XmlText(""); if (IsWhiteSpaceCondensed()) pszData = pTextNode->Parse(pszData, pData, nEncoding); else { // Special case: we want to keep the white space so that leading spaces aren't removed pszData = pTextNode->Parse(pWithWhiteSpace, pData, nEncoding); } // Does the text value only contain white spaces? bool bIsBlank = true; { const String sValue = pTextNode->GetValue(); for (uint32 i=0; i<sValue.GetLength(); i++) { if (!IsWhiteSpace(sValue[i])) { bIsBlank = false; break; } } } if (bIsBlank) delete pTextNode; else LinkEndChild(*pTextNode); } else { // We hit a '<' // Have we hit a new element or an end tag? This could also be a XmlText in the "CDATA" style if (StringEqual(pszData, "</", false, nEncoding)) return pszData; else { XmlNode *pNode = Identify(pszData, nEncoding); if (pNode) { pszData = pNode->Parse(pszData, pData, nEncoding); LinkEndChild(*pNode); } else { return nullptr; } } } pWithWhiteSpace = pszData; pszData = SkipWhiteSpace(pszData, nEncoding); } if (!pszData) { // Set error code XmlDocument *pDocument = GetDocument(); if (pDocument) pDocument->SetError(ErrorReadingElementValue, 0, 0, nEncoding); } // Done return pszData; } //[-------------------------------------------------------] //[ Private XmlAttributeSet class ] //[-------------------------------------------------------] XmlElement::XmlAttributeSet::XmlAttributeSet() { cSentinel.m_pNextAttribute = &cSentinel; cSentinel.m_pPreviousAttribute = &cSentinel; } XmlElement::XmlAttributeSet::~XmlAttributeSet() { } void XmlElement::XmlAttributeSet::Add(XmlAttribute &cAttribute) { cAttribute.m_pNextAttribute = &cSentinel; cAttribute.m_pPreviousAttribute = cSentinel.m_pPreviousAttribute; cSentinel.m_pPreviousAttribute->m_pNextAttribute = &cAttribute; cSentinel.m_pPreviousAttribute = &cAttribute; } void XmlElement::XmlAttributeSet::Remove(XmlAttribute &cAttribute) { for (XmlAttribute *pAttribute=cSentinel.m_pNextAttribute; pAttribute!=&cSentinel; pAttribute=pAttribute->m_pNextAttribute) { if (pAttribute == &cAttribute) { pAttribute->m_pPreviousAttribute->m_pNextAttribute = pAttribute->m_pNextAttribute; pAttribute->m_pNextAttribute->m_pPreviousAttribute = pAttribute->m_pPreviousAttribute; pAttribute->m_pNextAttribute = nullptr; pAttribute->m_pPreviousAttribute = nullptr; // Get us out of here right now! return; } } } XmlAttribute *XmlElement::XmlAttributeSet::Find(const String &sName) const { for (XmlAttribute *pAttribute=cSentinel.m_pNextAttribute; pAttribute!=&cSentinel; pAttribute=pAttribute->m_pNextAttribute) { if (pAttribute->m_sName == sName) return pAttribute; } return nullptr; } XmlAttribute *XmlElement::XmlAttributeSet::FindOrCreate(const String &sName) { XmlAttribute *pAttribute = Find(sName); if (!pAttribute) { pAttribute = new XmlAttribute(); Add(*pAttribute); pAttribute->SetName(sName); } return pAttribute; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
27.449405
125
0.63629
ktotheoz
5d369d9507357ae3a82d7fd1db8f675e09dd3c7f
2,810
cpp
C++
src/Library/Library/sources/Functions/dencryptionFunctions.cpp
myNameIsAndrew00/Cryptographic-Hardware-Simulator
cfd5c9a75ba9461faf5fd48257ef9ac3b259365a
[ "MIT" ]
null
null
null
src/Library/Library/sources/Functions/dencryptionFunctions.cpp
myNameIsAndrew00/Cryptographic-Hardware-Simulator
cfd5c9a75ba9461faf5fd48257ef9ac3b259365a
[ "MIT" ]
null
null
null
src/Library/Library/sources/Functions/dencryptionFunctions.cpp
myNameIsAndrew00/Cryptographic-Hardware-Simulator
cfd5c9a75ba9461faf5fd48257ef9ac3b259365a
[ "MIT" ]
null
null
null
#include "../../include/pkcs11.h" #include "../../include/IPkcs11Token.h" #include <stdlib.h> #include <string.h> extern Abstractions::IPkcs11TokenReference Token; CK_DEFINE_FUNCTION(CK_RV, C_EncryptInit)(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (nullptr == pMechanism) return CKR_ARGUMENTS_BAD; auto encryptInitResult = Token->EncryptInit(hSession, hKey, pMechanism); return (CK_RV)encryptInitResult.GetCode(); } CK_DEFINE_FUNCTION(CK_RV, C_Encrypt)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { if (nullptr == pData || ulDataLen == 0) return CKR_ARGUMENTS_BAD; auto encrypResult = Token->Encrypt(hSession, pData, ulDataLen, nullptr == pEncryptedData); *pulEncryptedDataLen = encrypResult.GetValue().GetLength(); if (nullptr != pEncryptedData) { memcpy(pEncryptedData, encrypResult.GetValue().GetBytes(), *pulEncryptedDataLen); } return (CK_RV)encrypResult.GetCode(); } CK_DEFINE_FUNCTION(CK_RV, C_EncryptUpdate)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen) { if (nullptr == pPart || ulPartLen == 0) return CKR_ARGUMENTS_BAD; auto encrypResult = Token->EncryptUpdate(hSession, pPart, ulPartLen, nullptr == pEncryptedPart); *pulEncryptedPartLen = encrypResult.GetValue().GetLength(); if (nullptr != pEncryptedPart) { memcpy(pEncryptedPart, encrypResult.GetValue().GetBytes(), *pulEncryptedPartLen); } return (CK_RV)encrypResult.GetCode(); } CK_DEFINE_FUNCTION(CK_RV, C_EncryptFinal)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen) { auto encrypResult = Token->EncryptFinal(hSession, nullptr == pLastEncryptedPart); *pulLastEncryptedPartLen = encrypResult.GetValue().GetLength(); if (nullptr != pLastEncryptedPart) { memcpy(pLastEncryptedPart, encrypResult.GetValue().GetBytes(), *pulLastEncryptedPartLen); } return (CK_RV)encrypResult.GetCode(); } CK_DEFINE_FUNCTION(CK_RV, C_DecryptInit)(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_DEFINE_FUNCTION(CK_RV, C_DecryptUpdate)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_DEFINE_FUNCTION(CK_RV, C_DecryptFinal)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pLastPart, CK_ULONG_PTR pulLastPartLen) { return CKR_FUNCTION_NOT_SUPPORTED; } CK_DEFINE_FUNCTION(CK_RV, C_Decrypt)(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { return CKR_FUNCTION_NOT_SUPPORTED; }
33.855422
171
0.802847
myNameIsAndrew00
5d401c19452901ae86f32ac359aae3a8a22142fe
1,489
hpp
C++
src/parser/skip-to-sequence.hpp
aaron-michaux/giraffe
457b55d80f6d21616a5c40232c2f68ee9e2c8335
[ "MIT" ]
null
null
null
src/parser/skip-to-sequence.hpp
aaron-michaux/giraffe
457b55d80f6d21616a5c40232c2f68ee9e2c8335
[ "MIT" ]
null
null
null
src/parser/skip-to-sequence.hpp
aaron-michaux/giraffe
457b55d80f6d21616a5c40232c2f68ee9e2c8335
[ "MIT" ]
null
null
null
#pragma once #include "scanner/scanner.hpp" #include "utils/in-list.hpp" namespace giraffe::detail { template<typename T> bool match_worker(Scanner& tokens, T&& id) noexcept { if(in_list(tokens.current().id(), id)) { tokens.consume(); return true; } return false; } template<typename T, typename... Ts> bool match_worker(Scanner& tokens, T&& id, Ts&&... rest) noexcept { return match_worker(tokens, id) && match_worker(tokens, std::forward<Ts>(rest)...); } } // namespace giraffe::detail namespace giraffe { template<typename... Ts> bool skip_to_sequence(Scanner& tokens, Ts&&... ids) noexcept { while(tokens.has_next()) { const auto start_position = tokens.position(); const bool match = detail::match_worker(tokens, std::forward<Ts>(ids)...); tokens.set_position(start_position); if(match) return true; else tokens.consume(); // advance one token } return false; } template<typename O, typename... Ts> bool skip_to_sequence_omitting(Scanner& tokens, const O& omit, Ts&&... ids) noexcept { while(tokens.has_next() && !in_list(tokens.current().id(), omit)) { const auto start_position = tokens.position(); const bool match = detail::match_worker(tokens, std::forward<Ts>(ids)...); tokens.set_position(start_position); if(match) return true; else tokens.consume(); // advance one token } return false; } } // namespace giraffe
26.122807
89
0.648086
aaron-michaux
5d43ad0d9b3cf124ef0a593cbac87f07d63dce2e
3,753
cpp
C++
tests/longest_strictly_increasing_subsequence_tester.cpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
tests/longest_strictly_increasing_subsequence_tester.cpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
tests/longest_strictly_increasing_subsequence_tester.cpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
#include <vector> #include <gtest/gtest.h> #include "longest_monotonic_subsequence.hpp" namespace gt = testing; namespace pk { namespace testing { struct longest_strictly_increasing_subsequence_tester : public gt::Test { static const int MAX_SEQUENCE_SIZE = 9; // tested class: typedef longest_monotonic_subsequence<MAX_SEQUENCE_SIZE> lms; }; TEST_F(longest_strictly_increasing_subsequence_tester, tests_empty_sequence) { // given std::vector<int> numbers; // when and then EXPECT_EQ(0, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_one_element_sequence) { // given std::vector<int> numbers; numbers.push_back(42); // when and then EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_equal_elements) { // given std::vector<int> numbers; numbers.push_back(42); numbers.push_back(42); numbers.push_back(42); // when and then EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_strictly_decreasing_elements) { // given std::vector<int> numbers; numbers.push_back(33); numbers.push_back(11); numbers.push_back(0); numbers.push_back(-22); numbers.push_back(-55); // when and then EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_strictly_increasing_elements) { // given std::vector<int> numbers; numbers.push_back(-55); numbers.push_back(-22); numbers.push_back(0); numbers.push_back(11); numbers.push_back(33); // when and then EXPECT_EQ(5, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_weakly_decreasing_elements) { // given std::vector<int> numbers; numbers.push_back(33); numbers.push_back(22); numbers.push_back(22); numbers.push_back(11); numbers.push_back(11); // when and then EXPECT_EQ(1, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_all_weakly_increasing_elements) { // given std::vector<int> numbers; numbers.push_back(11); numbers.push_back(11); numbers.push_back(22); numbers.push_back(22); numbers.push_back(33); // when and then EXPECT_EQ(3, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_randomized_elements) { // given std::vector<int> numbers; numbers.push_back(55); numbers.push_back(-22); numbers.push_back(33); numbers.push_back(77); numbers.push_back(22); numbers.push_back(22); numbers.push_back(44); numbers.push_back(11); numbers.push_back(66); // when and then EXPECT_EQ(4, lms::strictly_increasing(numbers.begin(), numbers.end())); } TEST_F(longest_strictly_increasing_subsequence_tester, tests_sequence_of_floatoing_point_elements) { // given std::vector<double> numbers; numbers.push_back(-1.1); numbers.push_back(-1.2); numbers.push_back(-1.2); numbers.push_back(-1.1); numbers.push_back(0.0); numbers.push_back(0.0); numbers.push_back(0.0); numbers.push_back(0.1); numbers.push_back(0.3); // when and then EXPECT_EQ(5, lms::strictly_increasing(numbers.begin(), numbers.end())); } } // namespace testing } // namespace pk
23.45625
106
0.716227
pawel-kieliszczyk
5d48b709e6fdd41429967fe580ca39b047eab5fa
1,142
cpp
C++
test/priQue.cpp
DQiuLin/calculator
2717cdca1d6adb38d7ac4be3cf6f851f129fe3f6
[ "MIT" ]
null
null
null
test/priQue.cpp
DQiuLin/calculator
2717cdca1d6adb38d7ac4be3cf6f851f129fe3f6
[ "MIT" ]
null
null
null
test/priQue.cpp
DQiuLin/calculator
2717cdca1d6adb38d7ac4be3cf6f851f129fe3f6
[ "MIT" ]
null
null
null
#include "common.h" static bool cmp(const std::pair<int, int> &a, const std::pair<int, int> &b) { return a.second < b.second; } class MyCompare { public: bool operator()(const std::pair<int, int> &a, const std::pair<int, int> &b) { return a.second < b.second; } }; int main() { // priority_queue 默认使用 less (a < b),从大到小排列 (大根堆) // 使用 greater (a > b),从大到小排列 (小根堆) vector<std::pair<int, int>> vec = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}}; priority_queue<std::pair<int, int>, vector<std::pair<int, int>>, decltype(&cmp)> q(cmp); priority_queue<std::pair<int, int>, vector<std::pair<int, int>>, MyCompare> que(vec.begin(), vec.end()); for (auto &v: vec) { q.push(v); } while (!q.empty()) { cout << q.top().second << " "; q.pop(); } cout << endl; while (!que.empty()) { cout << que.top().second << " "; que.pop(); } return 0; }
29.282051
108
0.436077
DQiuLin
5d4b8388df4e5a976081a87e4f0385c478f2c995
6,187
cpp
C++
src/Core/QSafeguard.cpp
ericzh86/qt-toolkit
63ec071f8989d6efcc4afa30fa98ede695edba27
[ "MIT" ]
4
2020-01-07T07:05:18.000Z
2020-01-09T10:25:41.000Z
src/Core/QSafeguard.cpp
ericzh86/qt-toolkit
63ec071f8989d6efcc4afa30fa98ede695edba27
[ "MIT" ]
null
null
null
src/Core/QSafeguard.cpp
ericzh86/qt-toolkit
63ec071f8989d6efcc4afa30fa98ede695edba27
[ "MIT" ]
null
null
null
#include "QSafeguard.h" #include "QSafeguard_p.h" #include <QStringBuilder> #include <QLoggingCategory> Q_LOGGING_CATEGORY(lcSafeguard, "QSafeguard") // class QSafeguard QSafeguard::QSafeguard(const QString &dumpPath, QObject *parent) : QObject(parent) , d_ptr(new QSafeguardPrivate()) { d_ptr->q_ptr = this; d_ptr->dumpPath = dumpPath; } QSafeguard::QSafeguard(QObject *parent) : QObject(parent) , d_ptr(new QSafeguardPrivate()) { d_ptr->q_ptr = this; } QSafeguard::~QSafeguard() { } void QSafeguard::setDumpPath(const QString &path) { Q_D(QSafeguard); d->dumpPath = path; } void QSafeguard::setPipeName(const QString &name) { Q_D(QSafeguard); d->pipeName = name; } const QString &QSafeguard::dumpPath() const { Q_D(const QSafeguard); return d->dumpPath; } const QString &QSafeguard::pipeName() const { Q_D(const QSafeguard); return d->pipeName; } bool QSafeguard::createServer() { Q_D(QSafeguard); Q_ASSERT(!d->dumpPath.isEmpty()); Q_ASSERT(!d->pipeName.isEmpty()); #if defined(Q_OS_WIN32) QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName; QSharedPointer<google_breakpad::CrashGenerationServer> crashServer(new google_breakpad::CrashGenerationServer( pipeName.toStdWString(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, true, &d->dumpPath.toStdWString() )); if (!crashServer->Start()) { qWarning(lcSafeguard, "crash server start failed."); return false; } qInfo(lcSafeguard, "crash server ready..."); d->crashServer = crashServer; return true; #else /* QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName; QSharedPointer<google_breakpad::CrashGenerationServer> crashServer(new google_breakpad::CrashGenerationServer( pipeName.toStdString().c_str(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, true, d->dumpPath.toStdString())); */ #endif /* if (!crashServer->Start()) { qWarning(lcSafeguard, "crash server start failed."); return false; } qInfo(lcSafeguard, "crash server ready..."); d->crashServer = crashServer; */ return false; } void QSafeguard::createClient() { Q_D(QSafeguard); Q_ASSERT(!d->dumpPath.isEmpty()); Q_ASSERT(!d->pipeName.isEmpty()); #if defined(Q_OS_WIN32) QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName; d->exceptionHandler.reset(new google_breakpad::ExceptionHandler(d->dumpPath.toStdWString(), nullptr, nullptr, nullptr, google_breakpad::ExceptionHandler::HANDLER_ALL, MiniDumpNormal, pipeName.toStdWString().c_str(), nullptr)); if (d->exceptionHandler->IsOutOfProcess()) { qInfo(lcSafeguard, "daemon mode."); } else { qInfo(lcSafeguard, "normal mode."); } #else /* QString pipeName = QString::fromLatin1("\\\\.\\pipe\\") % d->pipeName; d->exceptionHandler.reset(new google_breakpad::ExceptionHandler(d->dumpPath.toStdString(), nullptr, nullptr, nullptr, true, pipeName.toStdString().c_str())); */ #endif /* if (d->exceptionHandler->IsOutOfProcess()) { qInfo(lcSafeguard, "daemon mode."); } else { qInfo(lcSafeguard, "normal mode."); } */ } void QSafeguard::makeSnapshot() { #if defined(Q_OS_WIN32) Q_D(QSafeguard); if (d->exceptionHandler) { d->exceptionHandler->WriteMinidump(); } #endif } // class QSafeguardPrivate QSafeguardPrivate::QSafeguardPrivate() : q_ptr(nullptr) { } QSafeguardPrivate::~QSafeguardPrivate() { }
33.625
115
0.390981
ericzh86
5d4caf277b27ba63bbb807483211bf2ceba71b87
1,990
cpp
C++
src/fireball.cpp
alohamora/legend-of-zelda
63b764ab27a171af1f809dcd8aa8e85b2c06accc
[ "MIT" ]
null
null
null
src/fireball.cpp
alohamora/legend-of-zelda
63b764ab27a171af1f809dcd8aa8e85b2c06accc
[ "MIT" ]
null
null
null
src/fireball.cpp
alohamora/legend-of-zelda
63b764ab27a171af1f809dcd8aa8e85b2c06accc
[ "MIT" ]
null
null
null
#include"main.h" #include"fireball.h" Fireball::Fireball(color_t color){ position = glm::vec3(0,-1,0); speed = 0.8; speed_up = 0; acc_y = 0; static const GLfloat vertex_buffer_data[] = { -0.5,-0.5,-0.5, // triangle 1 : begin -0.5,-0.5, 0.5, -0.5, 0.5, 0.5, // triangle 1 : end 0.5, 0.5,-0.5, // triangle 2 : begin -0.5,-0.5,-0.5, -0.5, 0.5,-0.5, // triangle 2 : end 0.5,-0.5, 0.5, -0.5,-0.5,-0.5, 0.5,-0.5,-0.5, 0.5, 0.5,-0.5, 0.5,-0.5,-0.5, -0.5,-0.5,-0.5, -0.5,-0.5,-0.5, -0.5, 0.5, 0.5, -0.5, 0.5,-0.5, 0.5,-0.5, 0.5, -0.5,-0.5, 0.5, -0.5,-0.5,-0.5, -0.5, 0.5, 0.5, -0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5, 0.5, 0.5,-0.5,-0.5, 0.5, 0.5,-0.5, 0.5,-0.5,-0.5, 0.5, 0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,-0.5, -0.5, 0.5,-0.5, 0.5, 0.5, 0.5, -0.5, 0.5,-0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5,-0.5, 0.5 }; this->fireball = create3DObject(GL_TRIANGLES, 36, vertex_buffer_data, color, GL_FILL); } void Fireball::draw(glm::mat4 VP){ Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); Matrices.model *= translate; glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->fireball); } void Fireball::tick() { this->position.x += speed*sin((rotation*M_PI)/180.0); this->position.z += speed*cos((rotation*M_PI)/180.0); this->position.y += speed_up; speed_up += acc_y; if(position.y < 0) flag = 0; } void Fireball::set_position(float x, float y, float z) { this->position = glm::vec3(x, y, z); }
24.875
90
0.443216
alohamora
5d4f1ab5241e92633625bb1351f5d8ead7776e17
15,807
cpp
C++
src/string_calculator.cpp
botn365/cpp-discord-bot
20cd173fa1a806a4c7fc44cf7e23163f78e88e79
[ "MIT" ]
null
null
null
src/string_calculator.cpp
botn365/cpp-discord-bot
20cd173fa1a806a4c7fc44cf7e23163f78e88e79
[ "MIT" ]
1
2021-12-19T01:46:40.000Z
2021-12-20T18:57:07.000Z
src/string_calculator.cpp
botn365/cpp-discord-bot
20cd173fa1a806a4c7fc44cf7e23163f78e88e79
[ "MIT" ]
null
null
null
// // Created by vanda on 12/10/2021. // #include <cmath> #include "../include/string_calculator.hpp" #include "../include/load_operators.hpp" static std::unordered_map<char32_t, Bot::Operator> unicodeToOperator; static std::unordered_map<char32_t, int> unicodeToNumber; static std::unordered_map<char32_t, bool> usedUnicodeMap; static std::unordered_map<std::string, double> constMap; static std::unordered_map<std::string, Bot::Function> stringToFunction; namespace Bot { using usedPair = std::pair<char32_t, bool>; using constPair = std::pair<std::string, double>; void StringCalculator::init(std::string numeTranslationFile) { Bot::LoadOperators::loadNumbers(numeTranslationFile); Bot::LoadOperators::loadOperators(); usedUnicodeMap.insert(usedPair('(', true)); usedUnicodeMap.insert(usedPair(')', true)); usedUnicodeMap.insert(usedPair('{', true)); usedUnicodeMap.insert(usedPair('}', true)); usedUnicodeMap.insert(usedPair(' ', true)); usedUnicodeMap.insert(usedPair('.', true)); usedUnicodeMap.insert(usedPair(',', true)); constMap.insert(constPair("pi", M_PI)); constMap.insert(constPair("e", M_E)); constMap.insert(constPair("g", 9.8)); constMap.insert(constPair("π", 3)); constMap.insert(constPair("een", 1)); constMap.insert(constPair("twee", 2)); constMap.insert(constPair("drie", 3)); constMap.insert(constPair("vier", 4)); constMap.insert(constPair("vijf", 5)); constMap.insert(constPair("zes", 6)); constMap.insert(constPair("zeven", 7)); constMap.insert(constPair("acht", 8)); constMap.insert(constPair("negen", 9)); } std::list<std::unique_ptr<Bot::CountObj>> Bot::StringCalculator::convertStringToRPNList(std::string_view &input) { std::list<std::unique_ptr<CountObj>> list; list.push_back(std::make_unique<Number>(0)); const char *end = input.data() + input.size(); auto index = list.begin(); int bracketPriorety = 0; bool indexUp = false; bool numberWasLast = false; auto *multOp = getOperator('*'); std::stack<std::pair<uint64_t, Function *>> functionStack; for (const char *i = input.data(); i < end;) { if (list.size() > 200) return {}; double number; if (getNumber(&i, number, end)) { if (numberWasLast) { insertOperatorInRPNList(list, index, multOp, bracketPriorety); } index = list.insert(++index, std::make_unique<Number>(number)); indexUp = false; numberWasLast = true; } else { char32_t unicode; const char *newIPos = getUnicode(i, unicode); if (unicode == 0) { i = newIPos; continue; } if (!numberWasLast && unicode == '-') unicode = '~'; auto operatorLambda = getOperator(unicode); if (operatorLambda != nullptr) { if (numberWasLast && !operatorLambda->canHaveNumber()) { insertOperatorInRPNList(list, index, multOp, bracketPriorety); } insertOperatorInRPNList(list, index, operatorLambda, bracketPriorety); if (operatorLambda->isReversed()) { index++; indexUp = false; } else { numberWasLast = false; indexUp = false; } i = newIPos; } else { int bracket = getParanthese(unicode); if (bracket > 0) { if (numberWasLast) { insertOperatorInRPNList(list, index, multOp, bracketPriorety); numberWasLast = false; } if (indexUp) { index--; indexUp = false; } bracketPriorety += bracket; i = newIPos; continue; } if (bracket < 0) { indexUp = false; bracketPriorety += bracket; i = newIPos; if (!functionStack.empty() && functionStack.top().first == bracketPriorety) { operatorLambda = functionStack.top().second; insertOperatorInRPNList(list, index, operatorLambda, bracketPriorety); functionStack.pop(); if (operatorLambda->isReversed()) { index++; indexUp = false; } else { numberWasLast = false; indexUp = false; } } continue; } if (unicode == ',') { do { index++; } while (shouldCommaIndexUp(index, bracketPriorety, list)); index--; numberWasLast = false; i = newIPos; continue; } if (unicode != ' ') { auto view = getFunctionString(&i, end); if (*(i) == '(') { auto functionPair = stringToFunction.find(std::string{view}); if (functionPair != stringToFunction.end()) { functionStack.push( std::pair<uint64_t, Function *>(bracketPriorety, &functionPair->second)); continue; } break; } else { auto value = getConst(view); if (value == value) { if (numberWasLast) { insertOperatorInRPNList(list, index, multOp, bracketPriorety); } index = list.insert(++index, std::make_unique<Number>(value)); indexUp = true; numberWasLast = true; continue; } break; } } i = newIPos; } } } list.pop_front(); return list; } using list = std::list<std::unique_ptr<CountObj>>; bool StringCalculator::shouldCommaIndexUp(list::iterator &index, uint64_t bracketPriorety, list &list) { if (index == list.end()) return false; CountObj *ptr = (*index).get(); if (ptr->isOperator()) { Operator *opPtr = (Operator *) ptr; if (opPtr->priority >= bracketPriorety) return true; } return false; } double Bot::StringCalculator::calculateFromRPNList(std::list<std::unique_ptr<CountObj>> &inputList) { std::stack<double> stack; for (std::unique_ptr<CountObj> &value: inputList) { if (value->isOperator()) { Operator *op = (Operator *) (value.get()); if (!op->run(stack)) { return NAN; } } else { Number *num = (Number *) (value.get()); stack.push(num->value); } } if (stack.size() != 1) return NAN; return stack.top(); } //add name operator pair to hashmap void Bot::StringCalculator::addOperator(std::string unicode, int priority, std::function<bool(std::stack<double> &)> run, bool canHaveNumber, bool isReversed) { char32_t unicodeValue; getUnicode(unicode.c_str(), unicodeValue); unicodeToOperator.insert( std::pair<char32_t, Operator>(unicodeValue, Operator(priority, unicode, run, canHaveNumber, isReversed))); auto used = usedUnicodeMap.find(unicodeValue); if (used == usedUnicodeMap.end()) { usedUnicodeMap.insert(usedPair(unicodeValue, false)); } } void StringCalculator::addFunction(std::string key, int priority, std::function<bool(std::stack<double> &)> run, bool canHaveNumber, bool isReversed) { stringToFunction.insert( std::pair<std::string, Function>(key, Function(priority, key, run, canHaveNumber, isReversed))); } //add name digit pair to hashmap void Bot::StringCalculator::addUnicodeNumber(char32_t unicode, int value) { unicodeToNumber.insert(std::pair<char32_t, int>(unicode, value)); usedUnicodeMap.insert(std::pair<char32_t, int>(unicode, true)); } int Bot::StringCalculator::getParanthese(char32_t &unicode) { if (unicode == '(') { return 10; } else if (unicode == ')') { return -10; } return 0; } //inserts an operator in to the list void Bot::StringCalculator::insertOperatorInRPNList(std::list<std::unique_ptr<CountObj>> &list, std::list<std::unique_ptr<CountObj>>::iterator &index, Bot::Operator *operand, int paranthesePriorety) { index++; while (index != list.end()) { if ((*index)->isOperator()) { auto *op = (Operator *) (*index).get(); int priorety = op->priority; if (priorety < operand->priority + paranthesePriorety) { index = list.insert(index, std::make_unique<Operator>(operand->priority + paranthesePriorety, operand->name, operand->run)); index--; return; } } index++; } index = list.insert(index, std::make_unique<Operator>(operand->priority + paranthesePriorety, operand->name, operand->run)); index--; } Bot::Operator *Bot::StringCalculator::getOperator(char32_t unicode) { auto result = unicodeToOperator.find(unicode); if (result == unicodeToOperator.end()) return nullptr; return &result->second; } int Bot::StringCalculator::getNumberFromUnicode(const char32_t &unicode) { auto result = unicodeToNumber.find(unicode); if (result == unicodeToNumber.end()) return -1; return result->second; } bool Bot::StringCalculator::getNumber(const char **input, double &number, const char *end) { number = 0; bool comma = false; bool hasNumber = false; unsigned int multiplyer = 10; const char *old = nullptr; while (*input < end) { char32_t unicode; const char *value = getUnicode(*input, unicode); if (value == old) return false; old = value; int result = getNumberFromUnicode(unicode); if (result == -1) { if (unicode == '_') { *input = value; continue; } if (unicode == '.') { *input = value; comma = true; } else { break; } } else { *input = value; if (comma) { number += ((double) result / multiplyer); multiplyer *= 10; } else { number *= multiplyer; number += result; hasNumber = true; } } } return hasNumber; } const char *Bot::StringCalculator::getUnicode(const char *input, char32_t &unicode) { if ((*input & 0x80) == 0) { unicode = *input; return ++input; } else if ((*input & 0xE0) == 192) { unicode = convertToUnicode(input, 2); return input += 2; } else if ((*input & 0xF0) == 224) { unicode = convertToUnicode(input, 3); return input += 3; } else if ((*input & 0xF8) == 240) { unicode = convertToUnicode(input, 4); return input += 4; } unicode = 0; return ++input; } //converts a char* to name while checking if it is formed correctly char32_t Bot::StringCalculator::convertToUnicode(const char *input, int len) { unsigned char value = *input; char32_t out = value; for (int i = 1; i < len; i++) { if (i == 0 || (*(input + i) & 0xc0) == 0x80) { out <<= 8; value = *(input + i); out += value; } else { return 0; } } return out; } std::string StringCalculator::unicodeToString(char32_t unicode) { std::string out; for (int i = 3; i >= 0; i--) { unsigned char ch = (unicode >> (i * 8)) % 256; if (ch != 0) { out += ch; } } return out; } bool StringCalculator::isUnicodeUsed(char32_t unicode) { return usedUnicodeMap.find(unicode) != usedUnicodeMap.end(); } std::string_view Bot::StringCalculator::getFunctionString(const char **currentChar, const char *end) { const char *newPos = *currentChar; while (newPos != end) { char32_t unicode; const char *tempPos = getUnicode(newPos, unicode); if (usedUnicodeMap.find(unicode) != usedUnicodeMap.end()) { std::string_view view(*currentChar, newPos - *currentChar); *currentChar = newPos; return view; } else { newPos = tempPos; } } std::string_view view(*currentChar, end - *currentChar); *currentChar = newPos; return view; } double Bot::StringCalculator::getConst(std::string_view &view) { auto value = constMap.find(std::string(view)); if (value != constMap.end()) { return value->second; } return NAN; } bool Bot::StringCalculator::hasFunction(std::string &str) { return stringToFunction.find(str) != stringToFunction.end(); } bool Bot::StringCalculator::hasConst(std::string &str) { return constMap.find(str) != constMap.end(); } double StringCalculator::floor(double in) { return std::floor(in + 0.000001); } std::unordered_map<char32_t, Bot::Operator> StringCalculator::getOperatorMap() { return unicodeToOperator; } std::unordered_map<char32_t, int> StringCalculator::getNumberMap() { return unicodeToNumber; } std::unordered_map<std::string, Bot::Function> StringCalculator::getFunctionMap() { return stringToFunction; } std::unordered_map<std::string, double> StringCalculator::getConstMap() { return constMap; } }
38.742647
120
0.486746
botn365
5d51795d9f817177e42f08b1df322aed162b9210
35,686
cpp
C++
src/validate.cpp
biologic/stylus
ae642bbb7e2205bab1ab1b4703ea037e996e13db
[ "Apache-2.0" ]
null
null
null
src/validate.cpp
biologic/stylus
ae642bbb7e2205bab1ab1b4703ea037e996e13db
[ "Apache-2.0" ]
null
null
null
src/validate.cpp
biologic/stylus
ae642bbb7e2205bab1ab1b4703ea037e996e13db
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * \file validate.cpp * \brief Stylus Gene class (validation methods) * * Stylus, Copyright 2006-2009 Biologic Institute * * 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. *******************************************************************************/ // Includes --------------------------------------------------------------------- #include "headers.hpp" using namespace std; using namespace stylus; //-------------------------------------------------------------------------------- // // Stroke // //-------------------------------------------------------------------------------- /* * Function: calcDimensions * */ void Stroke::calcDimensions(Gene& gene) { ENTER(VALIDATION,calcDimensions); const ACIDTYPEARRAY& vecAcids = gene.getAcids(); const POINTARRAY& vecPoints = gene.getPoints(); long iAcid = _rgAcids.getStart()-1; ASSERT(iAcid >= 0); // Strokes begin where the previous vector ends Point ptTopLeft(vecPoints[iAcid]); Point ptBottomRight(vecPoints[iAcid]); // Sum the lengths of vectors contained in the stroke ASSERT(_slVectors.getLength() == 0); for (++iAcid; iAcid <= _rgAcids.getEnd(); ++iAcid) { const Point& pt = vecPoints[iAcid]; if (pt.x() < ptTopLeft.x()) ptTopLeft.x() = pt.x(); if (pt.y() > ptTopLeft.y()) ptTopLeft.y() = pt.y(); if (pt.x() > ptBottomRight.x()) ptBottomRight.x() = pt.x(); if (pt.y() < ptBottomRight.y()) ptBottomRight.y() = pt.y(); _slVectors += vecAcids[iAcid]; } // Set the bounds to the extreme top/left and bottom/right encountered _rectBounds.set(ptTopLeft, ptBottomRight); TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld has bounds %s", (_id+1), _rectBounds.toString().c_str())); } /* * Function: calcScale * */ bool Stroke::calcScale(Gene& gene, const HStroke& hst) { ENTER(VALIDATION,calcScale); bool fDimensionMissing = false; const Rectangle& rectHBounds = hst.getBounds(); // Calculate the x/y scale factors // - If either the stroke or Han is missing profile along a dimension, skip it // (the stroke will eventually inherit the scale factor from its containing group) if (rectHBounds.getWidth() > 0 && _rectBounds.getWidth() > 0) _sxToHan = rectHBounds.getWidth() / _rectBounds.getWidth(); else { fDimensionMissing = true; _sxToHan.setUndefined(); } if (rectHBounds.getHeight() > 0 && _rectBounds.getHeight() > 0) _syToHan = rectHBounds.getHeight() / _rectBounds.getHeight(); else { fDimensionMissing = true; _syToHan.setUndefined(); } // Calculate the scale factor used with diagonal lengths if (!fDimensionMissing) _sxyToHan = ::sqrt((_sxToHan*_sxToHan)+(_syToHan*_syToHan)); else _sxyToHan.setUndefined(); TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld has sx/sy/sxy(%6.15f,%6.15f,%6.15f)", (_id+1), static_cast<UNIT>(_sxToHan), static_cast<UNIT>(_syToHan), static_cast<UNIT>(_sxyToHan))); ASSERT(fDimensionMissing || (_sxToHan.isDefined() && _syToHan.isDefined() && _sxyToHan.isDefined())); return fDimensionMissing; } /* * Function: promoteScale * */ void Stroke::promoteScale(UNIT sxToHan, UNIT syToHan) { ENTER(VALIDATION,promoteScale); // If a dimension lacked profile, take the passed scale for the dimension if (!_sxToHan.isDefined()) { TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld taking sxToHan(%f) from Group", (_id+1), sxToHan)); _sxIsInherited = true; _sxToHan = sxToHan; } if (!_syToHan.isDefined()) { TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld taking syToHan(%f) from Group", (_id+1), syToHan)); _syIsInherited = true; _syToHan = syToHan; } if (!_sxyToHan.isDefined()) _sxyToHan = ::sqrt((_sxToHan*_sxToHan)+(_syToHan*_syToHan)); } /* * Function: calcOffsets * */ void Stroke::calcOffsets(Group& grp, const HStroke& hst) { ENTER(VALIDATION,calcOffsets); const Rectangle& rectHBounds = hst.getBounds(); _dxToHan = rectHBounds.getCenter().x() - (_rectBounds.getCenter().x() * _sxToHan); _dyToHan = rectHBounds.getCenter().y() - (_rectBounds.getCenter().y() * _syToHan); _dxParentToHan = rectHBounds.getCenter().x() - (_rectBounds.getCenter().x() * grp.sxToHan()); _dyParentToHan = rectHBounds.getCenter().y() - (_rectBounds.getCenter().y() * grp.syToHan()); TDATA(VALIDATION,L3,(LLTRACE, "Stroke %ld has dx/dy(%6.15f,%6.15f) dx/dyParent(%6.15f,%6.15f)", (_id+1), static_cast<UNIT>(_dxToHan), static_cast<UNIT>(_dyToHan), static_cast<UNIT>(_dxParentToHan), static_cast<UNIT>(_dyParentToHan))); } //-------------------------------------------------------------------------------- // // Group // //-------------------------------------------------------------------------------- /* * Function: calcDimensions * */ void Group::calcDimensions(Gene& gene, const HGroup& hgrp) { ENTER(VALIDATION,calcDimensions); STROKEARRAY& vecStrokes = gene.getStrokes(); const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes(); ASSERT(vecContainedHStrokes.size() > 0); // Set group bounds to the union of all contained strokes for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke) { Stroke& st = vecStrokes[gene.mapHanToStroke(vecContainedHStrokes[iContainedStroke])]; st.calcDimensions(gene); if (iContainedStroke == 0) _rectBounds = st.getBounds(); else _rectBounds.combine(st.getBounds()); } TDATA(VALIDATION,L3,(LLTRACE, "Group %ld has bounds %s", (_id+1), _rectBounds.toString().c_str())); } /* * Function: calcScale * */ bool Group::calcScale(Gene& gene, const Han& han, const HGroup& hgrp) { ENTER(VALIDATION,calcScale); STROKEARRAY& vecStrokes = gene.getStrokes(); const HSTROKEARRAY& vecHStrokes = han.getStrokes(); const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes(); Unit nxToHan = 0; Unit nyToHan = 0; Unit sxToHan = 0; Unit syToHan = 0; bool fDimensionMissing = false; // Compute the mean sx/sy scale factors for the contained strokes // - Only strokes with profile along a dimension contribute to the mean for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke) { size_t iHStroke = vecContainedHStrokes[iContainedStroke]; Stroke& st = vecStrokes[gene.mapHanToStroke(iHStroke)]; const HStroke& hst = vecHStrokes[iHStroke]; fDimensionMissing = st.calcScale(gene, hst) || fDimensionMissing; if (hst.getBounds().getWidth() > 0 && st.getBounds().getWidth() > 0) { sxToHan += hst.getBounds().getWidth() * st.sxToHan(); nxToHan += hst.getBounds().getWidth(); } else fDimensionMissing = true; if (hst.getBounds().getHeight() > 0 && st.getBounds().getHeight() > 0) { syToHan += hst.getBounds().getHeight() * st.syToHan(); nyToHan += hst.getBounds().getHeight(); } else fDimensionMissing = true; } if (nxToHan > static_cast<UNIT>(0.0)) _sxToHan = sxToHan / nxToHan; else { fDimensionMissing = true; _sxToHan.setUndefined(); } if (nyToHan > static_cast<UNIT>(0.0)) _syToHan = syToHan / nyToHan; else { fDimensionMissing = true; _syToHan.setUndefined(); } ASSERT(fDimensionMissing || (_sxToHan.isDefined() && _syToHan.isDefined())); TDATA(VALIDATION,L3,(LLTRACE, "Group %ld has sx/sy(%6.15f,%6.15f)", (_id+1), static_cast<UNIT>(_sxToHan), static_cast<UNIT>(_syToHan))); return fDimensionMissing; } /* * Function: promoteScale * */ void Group::promoteScale(Gene& gene, const HGroup& hgrp, UNIT sxToHan, UNIT syToHan) { ENTER(VALIDATION,promoteScale); STROKEARRAY& vecStrokes = gene.getStrokes(); const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes(); // If a dimension lacked profile, take the passed scale for the dimension if (!_sxToHan.isDefined()) { TDATA(VALIDATION,L3,(LLTRACE, "Group %ld taking sxToHan(%f) from Gene", (_id+1), sxToHan)); _sxIsInherited = true; _sxToHan = sxToHan; } if (!_syToHan.isDefined()) { TDATA(VALIDATION,L3,(LLTRACE, "Group %ld taking syToHan(%f) from Gene", (_id+1), syToHan)); _syIsInherited = true; _syToHan = syToHan; } // Promote the group scale factors to any strokes missing scale factors TDATA(VALIDATION,L3,(LLTRACE, "Group %ld promoting sx/sy(%f,%f) to strokes", (_id+1), static_cast<UNIT>(_sxToHan), static_cast<UNIT>(_syToHan))); for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke) { vecStrokes[gene.mapHanToStroke(vecContainedHStrokes[iContainedStroke])].promoteScale(_sxToHan, _syToHan); } } /* * Function: calcOffsets * */ void Group::calcOffsets(Gene& gene, const Han& han, const HGroup& hgrp) { ENTER(VALIDATION,calcOffsets); ASSERT(_sxToHan.isDefined()); ASSERT(_syToHan.isDefined()); ASSERT(Unit(gene.sxToHan()).isDefined()); ASSERT(Unit(gene.syToHan()).isDefined()); ASSERT(_dxToHan == static_cast<UNIT>(0.0)); ASSERT(_dyToHan == static_cast<UNIT>(0.0)); STROKEARRAY& vecStrokes = gene.getStrokes(); const HSTROKEARRAY& vecHStrokes = han.getStrokes(); const NUMERICARRAY& vecContainedHStrokes = hgrp.getStrokes(); Unit dxToHan = 0.0; Unit dyToHan = 0.0; // Allow each stroke to determine its dx/dy translation offsets and accumulate the weighted sum of their centers for (size_t iContainedStroke=0; iContainedStroke < vecContainedHStrokes.size(); ++iContainedStroke) { size_t iHStroke = vecContainedHStrokes[iContainedStroke]; Stroke& st = vecStrokes[gene.mapHanToStroke(iHStroke)]; const HStroke& hst = vecHStrokes[iHStroke]; st.calcOffsets(*this, hst); const Point& ptStrokeCenter = st.getBounds().getCenter(); dxToHan += hst.getLength() * ptStrokeCenter.x(); dyToHan += hst.getLength() * ptStrokeCenter.y(); } // Convert the weighted sum into the dx/dy for the group by measuring it // against the weighted center of the Han group dxToHan /= hgrp.getLength(); dyToHan /= hgrp.getLength(); const Point& ptHanWeightedCenter = hgrp.getWeightedCenter(); _dxToHan = ptHanWeightedCenter.x() - (dxToHan * _sxToHan); _dyToHan = ptHanWeightedCenter.y() - (dyToHan * _syToHan); _dxParentToHan = ptHanWeightedCenter.x() - (dxToHan * gene.sxToHan()); _dyParentToHan = ptHanWeightedCenter.y() - (dyToHan * gene.syToHan()); TDATA(VALIDATION,L3,(LLTRACE, "Group %ld has dx/dy(%6.15f,%6.15f) dx/dyParent(%6.15f,%6.15f)", (_id+1), static_cast<UNIT>(_dxToHan), static_cast<UNIT>(_dyToHan), static_cast<UNIT>(_dxParentToHan), static_cast<UNIT>(_dyParentToHan))); } //-------------------------------------------------------------------------------- // // StrokeRangeChange // //-------------------------------------------------------------------------------- /* * Function: StrokeRangeChange * */ StrokeRangeChange::StrokeRangeChange(size_t idGene, const vector<Range>& vecStrokeRanges) { ASSERT(!Genome::isState(STGS_ROLLBACK) && !Genome::isState(STGS_RESTORING)); _idGene = idGene; _vecStrokeRanges = vecStrokeRanges; } /* * Function: undoChange * */ void StrokeRangeChange::undo() { ENTER(MUTATION,undoChange); TFLOW(MUTATION,L4,(LLTRACE, "Undoing %s", toString().c_str())); ASSERT(Genome::isState(STGS_ROLLBACK) || Genome::isState(STGS_RESTORING)); Gene& gene = Genome::getGeneById(_idGene); STROKEARRAY& vecStrokes = gene.getStrokes(); ASSERT(_vecStrokeRanges.size() == vecStrokes.size()); for (size_t iStroke=0; iStroke < vecStrokes.size(); ++iStroke) vecStrokes[iStroke].setRange(_vecStrokeRanges[iStroke]); gene.markInvalid(Gene::GI_STROKES); } /* * Function: toString * */ string StrokeRangeChange::toString() const { ENTER(MUTATION,toString); ostringstream ostr; ostr << "Stroke Ranges changed from: "; for (size_t iStroke=0; iStroke < _vecStrokeRanges.size(); ++iStroke) { ostr << iStroke << _vecStrokeRanges[iStroke].toString(); if (iStroke < _vecStrokeRanges.size()-1) ostr << Constants::s_chBLANK; } return ostr.str(); } //-------------------------------------------------------------------------------- // // Gene // //-------------------------------------------------------------------------------- /* * Function: ensureAcids * * Compile the codons into ACIDTYPEs and establish the point at the end * of each vector (the start vector is located at _ptOrigin). */ void Gene::ensureAcids(size_t iAcidChange, long cAcidsChanged) { ENTER(VALIDATION,ensureAcids); ASSERT(iAcidChange == 0 || !Genome::isState(STGS_VALIDATING)); ASSERT(iAcidChange == 0 || static_cast<long>(_vecAcids.size()) == Codon::numWholeCodons(_rgBases.getLength())); ASSERT(iAcidChange == 0 || _vecAcids.size() == _vecPoints.size()); if (_vecAcids.empty()) { size_t cAcids = Codon::numWholeCodons(_rgBases.getLength()); ASSERT(_rgBases.isEmpty() || cAcids >= 2); _vecAcids.resize(cAcids); _vecPoints.resize(cAcids); iAcidChange = 0; cAcidsChanged = _vecAcids.size(); } TFLOW(VALIDATION,L3,(LLTRACE, "Creating acids from %ld for %ld codons", (iAcidChange+1), cAcidsChanged)); ASSERT(_vecAcids.size() >= 2); ASSERT(_vecAcids.size() == _vecPoints.size()); ASSERT(_vecAcids.size() == static_cast<size_t>(_rgBases.getLength() / Codon::s_cchCODON)); // If acids were added, convert the corresponding bases to ACIDTYPEs if (cAcidsChanged > 0) { const char* pszBases = Genome::getBases().c_str(); size_t iBase = _rgBases.getStart() + (iAcidChange * Codon::s_cchCODON); size_t iAcid = iAcidChange; size_t iAcidEnd = iAcidChange + cAcidsChanged; for (; iAcid < iAcidEnd; iBase += Codon::s_cchCODON, ++iAcid) _vecAcids[iAcid] = Genome::codonToType(pszBases+iBase); } // Calculate the points associated with each acid from the point of change onward // - The point associated with the first codon is the origin of the gene; all others // are the value after applying the acid (that is, the start codon is treated as // a zero-length acid) Point pt; size_t iAcid = iAcidChange; if (iAcid <= 0) { _vecPoints[0] = _ptOrigin; iAcid++; } pt = _vecPoints[iAcid-1]; for (; iAcid < _vecPoints.size(); ++iAcid) { pt += _vecAcids[iAcid]; _vecPoints[iAcid] = pt; } // Calculate the total vector length of the gene // - The length excludes the start and stop codons _nUnits = 0; for (iAcid=1; iAcid < _vecAcids.size()-1; iAcid++) _nUnits += Acid::typeToAcid(_vecAcids[iAcid]).getLength(); TDATA(VALIDATION,L3,(LLTRACE, "Gene has %0.15f total units", static_cast<UNIT>(_nUnits))); markValid(GI_ACIDS | GI_POINTS); } /* * Function: ensureCoherence * * Determine the coherence of each vector by examining all possible trivectors. * For each vector is a coherence count, ranging from 0 to 3, indicating how * many trivectors within which it was found. */ void Gene::ensureCoherence() { ENTER(VALIDATION,ensureCoherence); ASSERT(isValid(GI_ACIDS)); ASSERT(_vecAcids.size() >= Codon::s_nTRIVECTOR+2); if (_vecCoherent.empty()) _vecCoherent.resize(_vecAcids.size()); ASSERT(_vecCoherent.size() >= Codon::s_nTRIVECTOR+2); ASSERT(_vecAcids.size() == _vecCoherent.size()); ASSERT(Acid::typeToAcid(_vecAcids[_vecAcids.size()-1]).isStop()); _vecCoherent[0] = 0; _vecCoherent[1] = 0; _vecCoherent[2] = 0; for (long iAcid=1; !Acid::typeToAcid(_vecAcids[iAcid+2]).isStop(); ++iAcid) { _vecCoherent[iAcid+2] = 0; if (Codon::isCoherent(_vecAcids[iAcid+0], _vecAcids[iAcid+1], _vecAcids[iAcid+2])) { ++_vecCoherent[iAcid+0]; ++_vecCoherent[iAcid+1]; ++_vecCoherent[iAcid+2]; } } markValid(GI_COHERENCE); } /* * Function: ensureSegments * * A segment is a continuous range of coherent or incoherent vectors. * This routine walks the coherence array, building as many segments * as necessary. * * NOTES: * - Strokes could be built up from the coherence array without directly * using the notion of segments; however, since strokes deal with coherent * ranges, first dividing the vectors into segments makes sense */ void Gene::ensureSegments() { ENTER(VALIDATION,ensureSegments); ASSERT(isValid(GI_ACIDS | GI_COHERENCE)); ASSERT(_vecAcids.size() >= Codon::s_nTRIVECTOR+2); ASSERT(_vecCoherent.size() >= Codon::s_nTRIVECTOR+2); ASSERT(_vecAcids.size() == _vecCoherent.size()); ASSERT(Acid::typeToAcid(_vecAcids[_vecAcids.size()-1]).isStop()); bool fWasCoherent = !(_vecCoherent[1] > 0); long iSegment = -1; _vecSegments.clear(); // Iterate across all vectors between the start and stop codon for (long iAcid=1; !Acid::typeToAcid(_vecAcids[iAcid]).isStop(); ++iAcid) { bool fIsCoherent = (_vecCoherent[iAcid] > 0); if (fWasCoherent != fIsCoherent) { fWasCoherent = fIsCoherent; ++iSegment; _vecSegments.resize(iSegment+1); if (fIsCoherent) ++_cCoherent; Segment& sg = _vecSegments.back(); sg.setRange(Range(iAcid,iAcid)); sg.setCoherent(fIsCoherent); sg = _vecAcids[iAcid]; } else { Segment& sg = _vecSegments.back(); sg += _vecAcids[iAcid]; sg.setEnd(iAcid); } } // Since, coherent and incoherent segments alternate, // their absolute difference should never exceed one ASSERT(::abs(static_cast<size_t>(_vecSegments.size() - (2 * _cCoherent))) <= 1); TFLOW(VALIDATION,L3,(LLTRACE, "%d segments created", _vecSegments.size())); TRACEDOIF(VALIDATION,DATA,L3,traceSegments()); markValid(GI_SEGMENTS); } /* * Function: ensureStrokes * * A stroke is a sequence of coherent vectors possibly separated by small, * incoherent regions (called "dropouts"). Generally, this routine maps the * coherent segments to the appropriate stroke (or treats them as strokes). * Coherent segments occurring outside of any stroke are referred to as * "marks". */ void Gene::ensureStrokes() { ENTER(VALIDATION,ensureStrokes); vector<Range> vecStrokeRanges(_vecStrokes.size()); NUMERICMAP vecPotentialStrokeSegments; size_t iStroke = 0; size_t iSegment = 0; // NOTE: // - For now, stroke locations must be assigned with the Han glyph. // Stroke discovery is possible, but requires mapping strokes to the Han // glyph while preserving the notion of dropouts and marks. ASSERT(_fStrokesAssigned); if (!_fStrokesAssigned) THROWRC((RC(ERROR), "Gene requires that stroke locations be assigned with the Han glyph")); // Each stroke requires at least one coherent segment if (_cCoherent < _vecStrokes.size()) { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Gene has too few coherent segments (%ld) for strokes (%ld)", _cCoherent, _vecStrokes.size()); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Gene has too few coherent segments (%ld) for strokes (%ld)", _cCoherent, _vecStrokes.size()); goto INVALID; } TFLOW(VALIDATION,L3,(LLTRACE, "Assigning %ld segments to %ld strokes", _vecSegments.size(), _vecStrokes.size())); // Save the current stroke ranges and ensure they are initially valid for (size_t iStroke=0; iStroke < _vecStrokes.size(); ++iStroke) { Stroke& st = _vecStrokes[iStroke]; if (st.getStart() <= 0 || st.getEnd() >= static_cast<long>(_vecAcids.size())-1 || st.getRange().getLength() < Codon::s_nTRIVECTOR) { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Stroke %ld has an invalid range of %s", (iStroke+1), st.getRange().toString().c_str()); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Stroke %ld has an invalid range of %s", (iStroke+1), st.getRange().toString().c_str()); goto INVALID; } vecStrokeRanges[iStroke] = st.getRange(); TDATA(VALIDATION,L4,(LLTRACE, "Stroke %ld has an expected range of %s", (iStroke+1), st.getRange().toString().c_str())); } //-------------------------------------------------------------------------------------------- // Generally, coherent segments map to strokes and incoherent segments to the moves between // strokes. However, allowing for small incoherent regions within strokes (dropouts) and // shifting stroke boundaries complicates matters. The relationship between a segment and a // stroke is characterized by their endpoints; the Stroke 'S' and the Segments 'A', 'B', // 'C', 'D', 'E' and 'F'... // // |---- A ----| |---- F ----| // |---- B ----| |---- E ----| // |---------- C ----------| // |---- D ----| // |-------- S --------| // // ... have the following relationships: // // fStartBefore fStartContained fStartAfter fEndBefore fEndContained fEndAfter // A x x // B x x // C x x // D x x // E x x // F x x // //-------------------------------------------------------------------------------------------- // Walk the segment array and determine stroke locations as long as strokes exist while (iSegment < _vecSegments.size() && iStroke < _vecStrokes.size()) { const Segment& sg = _vecSegments[iSegment]; Stroke& st = _vecStrokes[iStroke]; bool fStrokeStarted = false; // Adjoining segments can never have the same coherency ASSERT( iSegment >= _vecSegments.size()-1 || _vecSegments[iSegment+1].isCoherent() != sg.isCoherent()); // Coherent segments can never be smaller than a trivector ASSERT( !sg.isCoherent() || sg.getRange().getLength() >= Codon::s_nTRIVECTOR); // Determine endpoint relationships (see comments above) bool fStartBefore = (st.getStart() - sg.getStart()) > 0; bool fStartAfter = (sg.getStart() - st.getEnd()) > 0; bool fEndBefore = (st.getStart() - sg.getEnd()) > 0; bool fEndAfter = (sg.getEnd() - st.getEnd()) > 0; ASSERT(!(fStartBefore && fStartAfter)); ASSERT(!(fEndBefore && fEndAfter)); ASSERT(!fEndBefore || fStartBefore); ASSERT(!fStartAfter || fEndAfter); bool fStartContained = (!fStartBefore && !fStartAfter); bool fEndContained = (!fEndBefore && !fEndAfter); bool fAdvanceSegment = true; bool fAdvanceStroke = false; // Handle each segment/stroke case (see above), adjusting the stroke boundaries as needed // - For coherent segments, stroke boundaries are extend to co-extensive with the segment // - For incoherent segments, stroke boundaries are extend (in the appropriate direction) // one past the segment to either avoid the segment or reach past it into the next // coherent segment // Case A: Segment lies wholly before the stroke if (fEndBefore) { ASSERT(!st.getSegments()); if (sg.isCoherent()) { if ( iSegment < _vecSegments.size()-2 && _vecSegments[iSegment+1].getRange().getLength() <= s_cDROPOUT) vecPotentialStrokeSegments.push_back(iSegment); else { for (size_t iMark=0; iMark < vecPotentialStrokeSegments.size(); ++iMark) { _vecMarks.push_back(vecPotentialStrokeSegments[iMark]); TFLOW(VALIDATION,L4,(LLTRACE, "CASE A: Segment %ld is a mark and lies before stroke %ld", (vecPotentialStrokeSegments[iMark]+1), (iStroke+1))); } vecPotentialStrokeSegments.clear(); _vecMarks.push_back(iSegment); TFLOW(VALIDATION,L4,(LLTRACE, "CASE A: Segment %ld is a mark and lies before stroke %ld", (iSegment+1), (iStroke+1))); } } } // Case B: Segment overlaps stroke start else if (fStartBefore && fEndContained) { ASSERT(!st.getSegments()); if (sg.isCoherent()) { st.setStart(sg.getStart()); st.incSegments(); fStrokeStarted = true; } else { st.setEnd(max<long>(sg.getEnd()+1, st.getEnd())); st.setStart(sg.getEnd()+1); } TFLOW(VALIDATION,L4,(LLTRACE, "CASE B: Segment %ld set the start for stroke %ld", (iSegment+1), (iStroke+1))); } // Case C: Segment overlaps entire stroke else if (fStartBefore && fEndAfter) { ASSERT(!st.getSegments()); if (sg.isCoherent()) { st.setRange(sg.getRange()); st.incSegments(); fStrokeStarted = true; TFLOW(VALIDATION,L4,(LLTRACE, "CASE C: Segment %ld set the range for stroke %ld", (iSegment+1), (iStroke+1))); } else { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Stroke %ld lost to incoherent segment %ld %s", (iStroke+1), (iSegment+1), sg.getRange().toString().c_str()); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Stroke %ld lost to incoherent segment %ld %s", (iStroke+1), (iSegment+1), sg.getRange().toString().c_str()); goto RECORDUNDO; } } // Case D: Segment is wholly contained in the stroke // Case E: Segment overlaps stroke end else if (fStartContained && (fEndContained || fEndAfter)) { if (sg.isCoherent()) { if (!st.getSegments()) { st.setStart(sg.getStart()); fStrokeStarted = true; TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the start for stroke %ld", (iSegment+1), (iStroke+1))); } if (fEndAfter) { st.setEnd(sg.getEnd()); TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the end for stroke %ld", (iSegment+1), (iStroke+1))); } st.incSegments(); } else { if (!st.getSegments()) { if (fEndAfter) { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Stroke %ld lost to incoherent segment %ld %s", (iStroke+1), (iSegment+1), sg.getRange().toString().c_str()); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Stroke %ld lost to incoherent segment %ld %s", (iStroke+1), (iSegment+1), sg.getRange().toString().c_str()); goto RECORDUNDO; } st.setEnd(max<long>(sg.getEnd()+1, st.getEnd())); st.setStart(sg.getEnd()+1); TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the start for stroke %ld", (iSegment+1), (iStroke+1))); } else if ( iSegment < _vecSegments.size()-1 && sg.getRange().getLength() <= s_cDROPOUT) { st.setEnd(max<long>(sg.getEnd()+1, st.getEnd())); st.incSegments(); st.incDropouts(); } else { st.setEnd(sg.getStart()-1); fAdvanceSegment = false; fAdvanceStroke = true; TFLOW(VALIDATION,L4,(LLTRACE, "CASE D/E: Segment %ld set the end for stroke %ld", (iSegment+1), (iStroke+1))); } } } // Case F: Segment lies wholly after the stroke else { ASSERT(fStartAfter); ASSERT(!sg.isCoherent()); if (!st.getSegments()) { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Stroke %ld lost to incoherent segment %ld %s", (iStroke+1), (iSegment+1), sg.getRange().toString().c_str()); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Stroke %ld lost to incoherent segment %ld %s", (iStroke+1), (iSegment+1), sg.getRange().toString().c_str()); goto RECORDUNDO; } if ( iSegment < _vecSegments.size()-1 && sg.getRange().getLength() <= s_cDROPOUT) { st.setEnd(sg.getEnd()+1); st.incSegments(); st.incDropouts(); } else { st.setEnd(sg.getStart()-1); fAdvanceSegment = false; fAdvanceStroke = true; } TFLOW(VALIDATION,L4,(LLTRACE, "CASE F: Segment %ld set the end for stroke %ld", (iSegment+1), (iStroke+1))); } // If the segment set the start of a stroke, add to the stroke any outstanding potential stroke segments // - The collection is a series of coherent segments within dropout distance of one another (including // the segment that started the stroke). The number of segments added to the stroke is the total number // of collected coherent segments plus the intervening incoherent segments. if (fStrokeStarted && vecPotentialStrokeSegments.size()) { st.setStart(_vecSegments[vecPotentialStrokeSegments[0]].getStart()); st.incSegments(vecPotentialStrokeSegments.size() * 2); st.incDropouts(vecPotentialStrokeSegments.size()); TFLOW(VALIDATION,L4,(LLTRACE, "%ld possible marks assigned to stroke %ld", vecPotentialStrokeSegments.size(), (iStroke+1))); vecPotentialStrokeSegments.clear(); } // Advance to the next segment and stroke as needed if (fAdvanceSegment) ++iSegment; if (fAdvanceStroke) { ++iStroke; ASSERT(vecPotentialStrokeSegments.empty()); } } ASSERT(vecPotentialStrokeSegments.empty()); // Gene is invalid if not all strokes received at least one coherent segment if ( iStroke < _vecStrokes.size()-1 || ( iStroke == _vecStrokes.size()-1 && _vecStrokes[iStroke].getSegments() <= 0)) { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Unable to assign segments to all strokes"); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_STROKES, "Unable to assign segments to all strokes"); goto RECORDUNDO; } // Ensure the last stroke has been assigned its appropriate end position // - The loop above terminates a stroke when it encounters an incoherent // segment exceeding the dropout length; if it exhausted segments before // strokes, the last stroke will require termination ASSERT( iStroke >= _vecStrokes.size() || ( iStroke == _vecStrokes.size()-1 && iSegment >= _vecSegments.size() && ( _vecSegments.back().isCoherent() || _vecSegments.back().getRange().getLength() <= static_cast<long>(s_cDROPOUT)))); if (iStroke == _vecStrokes.size()-1) { TFLOW(VALIDATION,L4,(LLTRACE, "Segment %ld set the end for stroke %ld", iSegment, iStroke)); const Segment& sg = _vecSegments.back(); _vecStrokes.back().setEnd(sg.isCoherent() ? sg.getEnd() : sg.getStart()-1); } // Count all coherent segments occurring after all strokes as marks for (; iSegment < _vecSegments.size(); ++iSegment) { if (_vecSegments[iSegment].isCoherent()) _vecMarks.push_back(iSegment); } markValid(GI_STROKES); TRACEDOIF(VALIDATION,DATA,L3,traceStrokes()); RECORDUNDO: // If the stroke ranges changed, record the changes for (size_t iStroke=0; iStroke < _vecStrokes.size(); ++iStroke) { if (_vecStrokes[iStroke].getRange() != vecStrokeRanges[iStroke]) { Genome::recordModification(::new StrokeRangeChange(_id, vecStrokeRanges)); if (!Genome::isRollbackAllowed()) LOGWARNING((LLWARNING, "Change occured in stroke range for stroke %ld - %s to %s", iStroke+1, vecStrokeRanges[iStroke].toString().c_str(), _vecStrokes[iStroke].getRange().toString().c_str())); break; } } INVALID: ; } /* * Function: ensureDimensions * * Determine the bounding rectangles along with the scale factors and translation offsets * to align strokes, groups, and the gene against the Han. * * Processing works from the strokes up and establishes bounding rectangles, then scale * factors, and finally translation offsets. (Translation offsets are applied to scaled * coordinates.) If any element cannot calculate a scale factor (due to missing profile * along a dimension), a second scale pass promotes parent scale factors to children. */ void Gene::ensureDimensions() { ENTER(VALIDATION,ensureDimensions); const Han& han = Han::getDefinition(_strUnicode); const HGROUPARRAY& vecHGroups = han.getGroups(); // First, calculate all group and stroke dimensions (groups will invoke strokes) // - Determine the gene dimensions along the way for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup) { _vecGroups[iGroup].calcDimensions(*this, vecHGroups[iGroup]); if (iGroup == 0) _rectBounds.set(_vecGroups[iGroup].getBounds()); else _rectBounds.combine(_vecGroups[iGroup].getBounds()); } Unit nxToHan = 0; Unit nyToHan = 0; Unit sxToHan = 0; Unit syToHan = 0; Unit dxToHan = 0; Unit dyToHan = 0; bool fDimensionMissing = false; // Then, compute the scale factors for all groups and strokes // - If any child, group or stroke, cannot compute a scale factor, // it will return true (to indicate a missing dimension) for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup) { Group& grp = _vecGroups[iGroup]; const HGroup& hgrp = vecHGroups[iGroup]; fDimensionMissing = ( grp.calcScale(*this, han, hgrp) || fDimensionMissing); if (Unit(grp.sxToHan()).isDefined()) { sxToHan += hgrp.getBounds().getWidth() * grp.sxToHan(); nxToHan += hgrp.getBounds().getWidth(); } else fDimensionMissing = true; if (Unit(grp.syToHan()).isDefined()) { syToHan += hgrp.getBounds().getHeight() * grp.syToHan(); nyToHan += hgrp.getBounds().getHeight(); } else fDimensionMissing = true; } // At least one dimension must have profile, it is an error otherwise if (nxToHan <= static_cast<UNIT>(0.0) && nyToHan <= static_cast<UNIT>(0.0)) { Genome::recordAttempt(ST_FILELINE, STTR_VALIDATION, "Both dimensions lack profile"); Genome::recordTermination(NULL, STGT_VALIDATION, STGR_MEASUREMENT, "Both dimensions lack profile"); goto INVALID; } // Compute gene scale factors if (nxToHan > static_cast<UNIT>(0.0)) _sxToHan = sxToHan / nxToHan; else { fDimensionMissing = true; _sxToHan.setUndefined(); } if (nyToHan > static_cast<UNIT>(0.0)) _syToHan = syToHan / nyToHan; else { fDimensionMissing = true; _syToHan.setUndefined(); } // Promote scale factors, as needed, to compensate for those they could not calculate if (fDimensionMissing) { ASSERT(_sxToHan.isDefined() || _syToHan.isDefined()); if (!_sxToHan.isDefined()) { TDATA(VALIDATION,L3,(LLTRACE, "Gene is missing sxToHan dimension, taking syToHan(%f)", static_cast<UNIT>(_syToHan))); _sxToHan = _syToHan; } else if (!_syToHan.isDefined()) { TDATA(VALIDATION,L3,(LLTRACE, "Gene is missing syToHan dimension, taking sxToHan(%f)", static_cast<UNIT>(_sxToHan))); _syToHan = _sxToHan; } TDATA(VALIDATION,L3,(LLTRACE, "Gene promoting sx/sy(%f,%f) to groups", static_cast<UNIT>(_sxToHan), static_cast<UNIT>(_syToHan))); for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup) { _vecGroups[iGroup].promoteScale(*this, vecHGroups[iGroup], _sxToHan, _syToHan); } } ASSERT(_sxToHan.isDefined() && _syToHan.isDefined()); _sxyToHan = ::sqrt((_sxToHan*_sxToHan)+(_syToHan*_syToHan)); // Finally, compute the translation offsets for all elements (groups, strokes, and the gene) for (size_t iGroup=0; iGroup < _vecGroups.size(); ++iGroup) { Group& grp = _vecGroups[iGroup]; const HGroup& hgrp = vecHGroups[iGroup]; grp.calcOffsets(*this, han, hgrp); dxToHan += hgrp.getLength() * grp.dxParentToHan(); dyToHan += hgrp.getLength() * grp.dyParentToHan(); } _dxToHan = dxToHan / han.getLength(); _dyToHan = dyToHan / han.getLength(); markValid(GI_DIMENSIONS); INVALID: ; } /* * Function: ensureOverlaps * */ void Gene::ensureOverlaps() { ENTER(VALIDATION,ensureOverlaps); Overlaps overlaps(_vecAcids, _vecPoints, _vecStrokes); _setOverlaps = overlaps.getOverlaps(); TFLOW(VALIDATION,L3,(LLTRACE, "%ld overlapping strokes", _setOverlaps.size())); TRACEDOIF(VALIDATION,DATA,L3,traceStrokeOverlaps()); markValid(GI_OVERLAPS); }
31.44141
149
0.657989
biologic
5d558bb08d4ef14678f8a1be773aa5f48a93dd83
16,633
cpp
C++
tests/CppUTest/TestUTestStringMacro.cpp
aunitt/cpputest
c981ed449df76e8e769286663c1caab069da324e
[ "BSD-3-Clause" ]
2
2016-02-04T16:34:01.000Z
2021-05-27T17:48:15.000Z
tests/CppUTest/TestUTestStringMacro.cpp
aunitt/cpputest
c981ed449df76e8e769286663c1caab069da324e
[ "BSD-3-Clause" ]
null
null
null
tests/CppUTest/TestUTestStringMacro.cpp
aunitt/cpputest
c981ed449df76e8e769286663c1caab069da324e
[ "BSD-3-Clause" ]
1
2020-01-22T19:46:10.000Z
2020-01-22T19:46:10.000Z
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestTestingFixture.h" #define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__) TEST_GROUP(UnitTestStringMacros) { TestTestingFixture fixture; }; static void _STRCMP_EQUALWithActualIsNULLTestMethod() { STRCMP_EQUAL("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndActualIsNULL) { fixture.runTestWithMethod(_STRCMP_EQUALWithActualIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } static void _STRCMP_EQUALWithExpectedIsNULLTestMethod() { STRCMP_EQUAL(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUALAndExpectedIsNULL) { fixture.runTestWithMethod(_STRCMP_EQUALWithExpectedIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } static void _STRCMP_CONTAINSWithActualIsNULLTestMethod() { STRCMP_CONTAINS("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndActualIsNULL) { fixture.runTestWithMethod(_STRCMP_CONTAINSWithActualIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>"); } static void _STRCMP_CONTAINSWithExpectedIsNULLTestMethod() { STRCMP_CONTAINS(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINSAndExpectedIsNULL) { fixture.runTestWithMethod(_STRCMP_CONTAINSWithExpectedIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>"); } static void _STRNCMP_EQUALWithActualIsNULLTestMethod() { STRNCMP_EQUAL("ok", NULLPTR, 2); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndActualIsNULL) { fixture.runTestWithMethod(_STRNCMP_EQUALWithActualIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } static void _STRNCMP_EQUALWithExpectedIsNULLTestMethod() { STRNCMP_EQUAL(NULLPTR, "ok", 2); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUALAndExpectedIsNULL) { fixture.runTestWithMethod(_STRNCMP_EQUALWithExpectedIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } static void _STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod() { STRCMP_NOCASE_EQUAL("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndActualIsNULL) { fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithActualIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>"); } static void _STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod() { STRCMP_NOCASE_EQUAL(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndExpectedIsNULL) { fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithExpectedIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>"); } static void _STRCMP_NOCASE_EQUALWithUnequalInputTestMethod() { STRCMP_NOCASE_EQUAL("no", "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUALAndUnequalInput) { fixture.runTestWithMethod(_STRCMP_NOCASE_EQUALWithUnequalInputTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <ok>"); } static void _STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod() { STRCMP_NOCASE_CONTAINS("ok", NULLPTR); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndActualIsNULL) { fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithActualIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <ok>"); } static void _STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod() { STRCMP_NOCASE_CONTAINS(NULLPTR, "ok"); } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINSAndExpectedIsNULL) { fixture.runTestWithMethod(_STRCMP_NOCASE_CONTAINSWithExpectedIsNULLTestMethod); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <>"); } static void _failingTestMethodWithSTRCMP_EQUAL() { STRCMP_EQUAL("hello", "hell"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>"); } TEST(UnitTestStringMacros, STRCMP_EQUALBehavesAsProperMacro) { if (false) STRCMP_EQUAL("1", "2"); else STRCMP_EQUAL("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUALWorksInAnIgnoredTest) { STRCMP_EQUAL("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_EQUAL_TEXT() { STRCMP_EQUAL_TEXT("hello", "hell", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_EQUAL_TEXT) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_EQUAL_TEXT); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTBehavesAsProperMacro) { if (false) STRCMP_EQUAL_TEXT("1", "2", "Failed because it failed"); else STRCMP_EQUAL_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_EQUAL_TEXTWorksInAnIgnoredTest) { STRCMP_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRNCMP_EQUAL() { STRNCMP_EQUAL("hello", "hallo", 5); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL) { fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>"); } TEST(UnitTestStringMacros, STRNCMP_EQUALBehavesAsProperMacro) { if (false) STRNCMP_EQUAL("1", "2", 1); else STRNCMP_EQUAL("1", "1", 1); } IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUALWorksInAnIgnoredTest) { STRNCMP_EQUAL("Hello", "World", 3); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRNCMP_EQUAL_TEXT() { STRNCMP_EQUAL_TEXT("hello", "hallo", 5, "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRNCMP_EQUAL_TEXT) { fixture.runTestWithMethod(_failingTestMethodWithSTRNCMP_EQUAL_TEXT); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hallo>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTBehavesAsProperMacro) { if (false) STRNCMP_EQUAL_TEXT("1", "2", 1, "Failed because it failed"); else STRNCMP_EQUAL_TEXT("1", "1", 1, "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRNCMP_EQUAL_TEXTWorksInAnIgnoredTest) { STRNCMP_EQUAL_TEXT("Hello", "World", 3, "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL() { STRCMP_NOCASE_EQUAL("hello", "Hell"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hell>"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALBehavesAsProperMacro) { if (false) STRCMP_NOCASE_EQUAL("1", "2"); else STRCMP_NOCASE_EQUAL("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUALWorksInAnIgnoredTest) { STRCMP_NOCASE_EQUAL("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT() { STRCMP_NOCASE_EQUAL_TEXT("hello", "hell", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_EQUAL_TEXT) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_EQUAL_TEXT); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <hell>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTBehavesAsProperMacro) { if (false) STRCMP_NOCASE_EQUAL_TEXT("1", "2", "Failed because it failed"); else STRCMP_NOCASE_EQUAL_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NOCASE_EQUAL_TEXTWorksInAnIgnoredTest) { STRCMP_NOCASE_EQUAL_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_CONTAINS() { STRCMP_CONTAINS("hello", "world"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); } TEST(UnitTestStringMacros, STRCMP_CONTAINSBehavesAsProperMacro) { if (false) STRCMP_CONTAINS("1", "2"); else STRCMP_CONTAINS("1", "1"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINSWorksInAnIgnoredTest) { STRCMP_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_CONTAINS_TEXT() { STRCMP_CONTAINS_TEXT("hello", "world", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, FailureWithSTRCMP_CONTAINS_TEXT) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_CONTAINS_TEXT); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <world>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTBehavesAsProperMacro) { if (false) STRCMP_CONTAINS_TEXT("1", "2", "Failed because it failed"); else STRCMP_CONTAINS_TEXT("1", "1", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_CONTAINS_TEXTWorksInAnIgnoredTest) { STRCMP_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS() { STRCMP_NOCASE_CONTAINS("hello", "WORLD"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINSBehavesAsProperMacro) { if (false) STRCMP_NOCASE_CONTAINS("never", "executed"); else STRCMP_NOCASE_CONTAINS("hello", "HELLO WORLD"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINSWorksInAnIgnoredTest) { STRCMP_NOCASE_CONTAINS("Hello", "World"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE static void _failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT() { STRCMP_NOCASE_CONTAINS_TEXT("hello", "WORLD", "Failed because it failed"); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } TEST(UnitTestStringMacros, FailureWithSTRCMP_NOCASE_CONTAINS_TEXT) { fixture.runTestWithMethod(_failingTestMethodWithSTRCMP_NOCASE_CONTAINS_TEXT); CHECK_TEST_FAILS_PROPER_WITH_TEXT("actual <WORLD>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("did not contain <hello>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed"); } TEST(UnitTestStringMacros, STRCMP_NOCASE_CONTAINS_TEXTBehavesAsProperMacro) { if (false) STRCMP_NOCASE_CONTAINS_TEXT("never", "executed", "Failed because it failed"); else STRCMP_NOCASE_CONTAINS_TEXT("hello", "HELLO WORLD", "Failed because it failed"); } IGNORE_TEST(UnitTestStringMacros, STRCMP_NO_CASE_CONTAINS_TEXTWorksInAnIgnoredTest) { STRCMP_NOCASE_CONTAINS_TEXT("Hello", "World", "Failed because it failed"); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, NFirstCharsComparison) { STRNCMP_EQUAL("Hello World!", "Hello Peter!", 0); STRNCMP_EQUAL("Hello World!", "Hello Peter!", 1); STRNCMP_EQUAL("Hello World!", "Hello Peter!", 6); STRNCMP_EQUAL("Hello World!", "Hello", 5); } static void _compareNFirstCharsWithUpperAndLowercase() { STRNCMP_EQUAL("hello world!", "HELLO WORLD!", 12); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithUpperAndLowercase) { fixture.runTestWithMethod(_compareNFirstCharsWithUpperAndLowercase); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <hello world!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <HELLO WORLD!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0"); } static void _compareNFirstCharsWithDifferenceInTheMiddle() { STRNCMP_EQUAL("Hello World!", "Hello Peter!", 12); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithDifferenceInTheMiddle) { fixture.runTestWithMethod(_compareNFirstCharsWithDifferenceInTheMiddle); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Hello World!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Hello Peter!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 6"); } static void _compareNFirstCharsWithEmptyString() { STRNCMP_EQUAL("", "Not empty string", 5); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithEmptyString) { fixture.runTestWithMethod(_compareNFirstCharsWithEmptyString); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 0"); } static void _compareNFirstCharsWithLastCharDifferent() { STRNCMP_EQUAL("Not empty string?", "Not empty string!", 17); TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE } // LCOV_EXCL_LINE TEST(UnitTestStringMacros, CompareNFirstCharsWithLastCharDifferent) { fixture.runTestWithMethod(_compareNFirstCharsWithLastCharDifferent); CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <Not empty string?>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <Not empty string!>"); CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 16"); }
35.464819
118
0.788252
aunitt
5d5edeafb6b57aacc1a54a3edb36df001c920da1
20,107
cpp
C++
Game/OGRE/OgreMain/src/OgreHardwareBufferManager.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/OGRE/OgreMain/src/OgreHardwareBufferManager.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/OGRE/OgreMain/src/OgreHardwareBufferManager.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreHardwareBufferManager.h" #include "OgreVertexIndexData.h" #include "OgreLogManager.h" namespace Ogre { //----------------------------------------------------------------------- template<> HardwareBufferManager* Singleton<HardwareBufferManager>::ms_Singleton = 0; HardwareBufferManager* HardwareBufferManager::getSingletonPtr(void) { return ms_Singleton; } HardwareBufferManager& HardwareBufferManager::getSingleton(void) { assert( ms_Singleton ); return ( *ms_Singleton ); } // Free temporary vertex buffers every 5 minutes on 100fps const size_t HardwareBufferManager::UNDER_USED_FRAME_THRESHOLD = 30000; const size_t HardwareBufferManager::EXPIRED_DELAY_FRAME_THRESHOLD = 5; //----------------------------------------------------------------------- HardwareBufferManager::HardwareBufferManager() : mUnderUsedFrameCount(0) { } //----------------------------------------------------------------------- HardwareBufferManager::~HardwareBufferManager() { // Clear vertex/index buffer list first, avoid destroyed notify do // unnecessary work, and we'll destroy everything here. mVertexBuffers.clear(); mIndexBuffers.clear(); // Destroy everything destroyAllDeclarations(); destroyAllBindings(); // No need to destroy main buffers - they will be destroyed by removal of bindings // No need to destroy temp buffers - they will be destroyed automatically. } //----------------------------------------------------------------------- VertexDeclaration* HardwareBufferManager::createVertexDeclaration(void) { VertexDeclaration* decl = createVertexDeclarationImpl(); mVertexDeclarations.insert(decl); return decl; } //----------------------------------------------------------------------- void HardwareBufferManager::destroyVertexDeclaration(VertexDeclaration* decl) { mVertexDeclarations.erase(decl); destroyVertexDeclarationImpl(decl); } //----------------------------------------------------------------------- VertexBufferBinding* HardwareBufferManager::createVertexBufferBinding(void) { VertexBufferBinding* ret = createVertexBufferBindingImpl(); mVertexBufferBindings.insert(ret); return ret; } //----------------------------------------------------------------------- void HardwareBufferManager::destroyVertexBufferBinding(VertexBufferBinding* binding) { mVertexBufferBindings.erase(binding); destroyVertexBufferBindingImpl(binding); } //----------------------------------------------------------------------- VertexDeclaration* HardwareBufferManager::createVertexDeclarationImpl(void) { return new VertexDeclaration(); } //----------------------------------------------------------------------- void HardwareBufferManager::destroyVertexDeclarationImpl(VertexDeclaration* decl) { delete decl; } //----------------------------------------------------------------------- VertexBufferBinding* HardwareBufferManager::createVertexBufferBindingImpl(void) { return new VertexBufferBinding(); } //----------------------------------------------------------------------- void HardwareBufferManager::destroyVertexBufferBindingImpl(VertexBufferBinding* binding) { delete binding; } //----------------------------------------------------------------------- void HardwareBufferManager::destroyAllDeclarations(void) { VertexDeclarationList::iterator decl; for (decl = mVertexDeclarations.begin(); decl != mVertexDeclarations.end(); ++decl) { destroyVertexDeclarationImpl(*decl); } mVertexDeclarations.clear(); } //----------------------------------------------------------------------- void HardwareBufferManager::destroyAllBindings(void) { VertexBufferBindingList::iterator bind; for (bind = mVertexBufferBindings.begin(); bind != mVertexBufferBindings.end(); ++bind) { destroyVertexBufferBindingImpl(*bind); } mVertexBufferBindings.clear(); } //----------------------------------------------------------------------- void HardwareBufferManager::registerVertexBufferSourceAndCopy( const HardwareVertexBufferSharedPtr& sourceBuffer, const HardwareVertexBufferSharedPtr& copy) { // Add copy to free temporary vertex buffers mFreeTempVertexBufferMap.insert( FreeTemporaryVertexBufferMap::value_type(sourceBuffer.get(), copy)); } //----------------------------------------------------------------------- HardwareVertexBufferSharedPtr HardwareBufferManager::allocateVertexBufferCopy( const HardwareVertexBufferSharedPtr& sourceBuffer, BufferLicenseType licenseType, HardwareBufferLicensee* licensee, bool copyData) { HardwareVertexBufferSharedPtr vbuf; // Locate existing buffer copy in temporary vertex buffers FreeTemporaryVertexBufferMap::iterator i = mFreeTempVertexBufferMap.find(sourceBuffer.get()); if (i == mFreeTempVertexBufferMap.end()) { // copy buffer, use shadow buffer and make dynamic vbuf = makeBufferCopy( sourceBuffer, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, true); } else { // Allocate existing copy vbuf = i->second; mFreeTempVertexBufferMap.erase(i); } // Copy data? if (copyData) { vbuf->copyData(*(sourceBuffer.get()), 0, 0, sourceBuffer->getSizeInBytes(), true); } // Insert copy into licensee list mTempVertexBufferLicenses.insert( TemporaryVertexBufferLicenseMap::value_type( vbuf.get(), VertexBufferLicense(sourceBuffer.get(), licenseType, EXPIRED_DELAY_FRAME_THRESHOLD, vbuf, licensee))); return vbuf; } //----------------------------------------------------------------------- void HardwareBufferManager::releaseVertexBufferCopy( const HardwareVertexBufferSharedPtr& bufferCopy) { TemporaryVertexBufferLicenseMap::iterator i = mTempVertexBufferLicenses.find(bufferCopy.get()); if (i != mTempVertexBufferLicenses.end()) { const VertexBufferLicense& vbl = i->second; vbl.licensee->licenseExpired(vbl.buffer.get()); mFreeTempVertexBufferMap.insert( FreeTemporaryVertexBufferMap::value_type(vbl.originalBufferPtr, vbl.buffer)); mTempVertexBufferLicenses.erase(i); } } //----------------------------------------------------------------------- void HardwareBufferManager::touchVertexBufferCopy( const HardwareVertexBufferSharedPtr& bufferCopy) { TemporaryVertexBufferLicenseMap::iterator i = mTempVertexBufferLicenses.find(bufferCopy.get()); if (i != mTempVertexBufferLicenses.end()) { VertexBufferLicense& vbl = i->second; assert(vbl.licenseType == BLT_AUTOMATIC_RELEASE); vbl.expiredDelay = EXPIRED_DELAY_FRAME_THRESHOLD; } } //----------------------------------------------------------------------- void HardwareBufferManager::_freeUnusedBufferCopies(void) { size_t numFreed = 0; // Free unused temporary buffers FreeTemporaryVertexBufferMap::iterator i; i = mFreeTempVertexBufferMap.begin(); while (i != mFreeTempVertexBufferMap.end()) { FreeTemporaryVertexBufferMap::iterator icur = i++; // Free the temporary buffer that referenced by ourself only. // TODO: Some temporary buffers are bound to vertex buffer bindings // but not checked out, need to sort out method to unbind them. if (icur->second.useCount() <= 1) { ++numFreed; mFreeTempVertexBufferMap.erase(icur); } } StringUtil::StrStreamType str; if (numFreed) { str << "HardwareBufferManager: Freed " << numFreed << " unused temporary vertex buffers."; } else { str << "HardwareBufferManager: No unused temporary vertex buffers found."; } LogManager::getSingleton().logMessage(str.str(), LML_TRIVIAL); } //----------------------------------------------------------------------- void HardwareBufferManager::_releaseBufferCopies(bool forceFreeUnused) { size_t numUnused = mFreeTempVertexBufferMap.size(); size_t numUsed = mTempVertexBufferLicenses.size(); // Erase the copies which are automatic licensed out TemporaryVertexBufferLicenseMap::iterator i; i = mTempVertexBufferLicenses.begin(); while (i != mTempVertexBufferLicenses.end()) { TemporaryVertexBufferLicenseMap::iterator icur = i++; VertexBufferLicense& vbl = icur->second; if (vbl.licenseType == BLT_AUTOMATIC_RELEASE && (forceFreeUnused || --vbl.expiredDelay <= 0)) { vbl.licensee->licenseExpired(vbl.buffer.get()); mFreeTempVertexBufferMap.insert( FreeTemporaryVertexBufferMap::value_type(vbl.originalBufferPtr, vbl.buffer)); mTempVertexBufferLicenses.erase(icur); } } // Check whether or not free unused temporary vertex buffers. if (forceFreeUnused) { _freeUnusedBufferCopies(); mUnderUsedFrameCount = 0; } else { if (numUsed < numUnused) { // Free temporary vertex buffers if too many unused for a long time. // Do overall temporary vertex buffers instead of per source buffer // to avoid overhead. ++mUnderUsedFrameCount; if (mUnderUsedFrameCount >= UNDER_USED_FRAME_THRESHOLD) { _freeUnusedBufferCopies(); mUnderUsedFrameCount = 0; } } else { mUnderUsedFrameCount = 0; } } } //----------------------------------------------------------------------- void HardwareBufferManager::_forceReleaseBufferCopies( const HardwareVertexBufferSharedPtr& sourceBuffer) { _forceReleaseBufferCopies(sourceBuffer.get()); } //----------------------------------------------------------------------- void HardwareBufferManager::_forceReleaseBufferCopies( HardwareVertexBuffer* sourceBuffer) { // Erase the copies which are licensed out TemporaryVertexBufferLicenseMap::iterator i; i = mTempVertexBufferLicenses.begin(); while (i != mTempVertexBufferLicenses.end()) { TemporaryVertexBufferLicenseMap::iterator icur = i++; const VertexBufferLicense& vbl = icur->second; if (vbl.originalBufferPtr == sourceBuffer) { // Just tell the owner that this is being released vbl.licensee->licenseExpired(vbl.buffer.get()); mTempVertexBufferLicenses.erase(icur); } } // Erase the free copies // // Why we need this unusual code? It's for resolve reenter problem. // // Using mFreeTempVertexBufferMap.erase(sourceBuffer) directly will // cause reenter into here because vertex buffer destroyed notify. // In most time there are no problem. But when sourceBuffer is the // last item of the mFreeTempVertexBufferMap, some STL multimap // implementation (VC and STLport) will call to clear(), which will // causing intermediate state of mFreeTempVertexBufferMap, in that // time destroyed notify back to here cause illegal accessing in // the end. // // For safely reason, use following code to resolve reenter problem. // typedef FreeTemporaryVertexBufferMap::iterator _Iter; std::pair<_Iter, _Iter> range = mFreeTempVertexBufferMap.equal_range(sourceBuffer); if (range.first != range.second) { std::list<HardwareVertexBufferSharedPtr> holdForDelayDestroy; for (_Iter it = range.first; it != range.second; ++it) { if (it->second.useCount() <= 1) { holdForDelayDestroy.push_back(it->second); } } mFreeTempVertexBufferMap.erase(range.first, range.second); // holdForDelayDestroy will destroy auto. } } //----------------------------------------------------------------------- void HardwareBufferManager::_notifyVertexBufferDestroyed(HardwareVertexBuffer* buf) { VertexBufferList::iterator i = mVertexBuffers.find(buf); if (i != mVertexBuffers.end()) { // release vertex buffer copies mVertexBuffers.erase(i); _forceReleaseBufferCopies(buf); } } //----------------------------------------------------------------------- void HardwareBufferManager::_notifyIndexBufferDestroyed(HardwareIndexBuffer* buf) { IndexBufferList::iterator i = mIndexBuffers.find(buf); if (i != mIndexBuffers.end()) { mIndexBuffers.erase(i); } } //----------------------------------------------------------------------- HardwareVertexBufferSharedPtr HardwareBufferManager::makeBufferCopy( const HardwareVertexBufferSharedPtr& source, HardwareBuffer::Usage usage, bool useShadowBuffer) { return this->createVertexBuffer( source->getVertexSize(), source->getNumVertices(), usage, useShadowBuffer); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TempBlendedBufferInfo::~TempBlendedBufferInfo(void) { // check that temp buffers have been released HardwareBufferManager &mgr = HardwareBufferManager::getSingleton(); if (!destPositionBuffer.isNull()) mgr.releaseVertexBufferCopy(destPositionBuffer); if (!destNormalBuffer.isNull()) mgr.releaseVertexBufferCopy(destNormalBuffer); } //----------------------------------------------------------------------------- void TempBlendedBufferInfo::extractFrom(const VertexData* sourceData) { // Release old buffer copies first HardwareBufferManager &mgr = HardwareBufferManager::getSingleton(); if (!destPositionBuffer.isNull()) { mgr.releaseVertexBufferCopy(destPositionBuffer); assert(destPositionBuffer.isNull()); } if (!destNormalBuffer.isNull()) { mgr.releaseVertexBufferCopy(destNormalBuffer); assert(destNormalBuffer.isNull()); } VertexDeclaration* decl = sourceData->vertexDeclaration; VertexBufferBinding* bind = sourceData->vertexBufferBinding; const VertexElement *posElem = decl->findElementBySemantic(VES_POSITION); const VertexElement *normElem = decl->findElementBySemantic(VES_NORMAL); assert(posElem && "Positions are required"); posBindIndex = posElem->getSource(); srcPositionBuffer = bind->getBuffer(posBindIndex); if (!normElem) { posNormalShareBuffer = false; srcNormalBuffer.setNull(); } else { normBindIndex = normElem->getSource(); if (normBindIndex == posBindIndex) { posNormalShareBuffer = true; srcNormalBuffer.setNull(); } else { posNormalShareBuffer = false; srcNormalBuffer = bind->getBuffer(normBindIndex); } } } //----------------------------------------------------------------------------- void TempBlendedBufferInfo::checkoutTempCopies(bool positions, bool normals) { bindPositions = positions; bindNormals = normals; HardwareBufferManager &mgr = HardwareBufferManager::getSingleton(); if (positions && destPositionBuffer.isNull()) { destPositionBuffer = mgr.allocateVertexBufferCopy(srcPositionBuffer, HardwareBufferManager::BLT_AUTOMATIC_RELEASE, this); } if (normals && !posNormalShareBuffer && !srcNormalBuffer.isNull() && destNormalBuffer.isNull()) { destNormalBuffer = mgr.allocateVertexBufferCopy(srcNormalBuffer, HardwareBufferManager::BLT_AUTOMATIC_RELEASE, this); } } //----------------------------------------------------------------------------- bool TempBlendedBufferInfo::buffersCheckedOut(bool positions, bool normals) const { HardwareBufferManager &mgr = HardwareBufferManager::getSingleton(); if (positions || (normals && posNormalShareBuffer)) { if (destPositionBuffer.isNull()) return false; mgr.touchVertexBufferCopy(destPositionBuffer); } if (normals && !posNormalShareBuffer) { if (destNormalBuffer.isNull()) return false; mgr.touchVertexBufferCopy(destNormalBuffer); } return true; } //----------------------------------------------------------------------------- void TempBlendedBufferInfo::bindTempCopies(VertexData* targetData, bool suppressHardwareUpload) { this->destPositionBuffer->suppressHardwareUpdate(suppressHardwareUpload); targetData->vertexBufferBinding->setBinding( this->posBindIndex, this->destPositionBuffer); if (bindNormals && !posNormalShareBuffer && !destNormalBuffer.isNull()) { this->destNormalBuffer->suppressHardwareUpdate(suppressHardwareUpload); targetData->vertexBufferBinding->setBinding( this->normBindIndex, this->destNormalBuffer); } } //----------------------------------------------------------------------------- void TempBlendedBufferInfo::licenseExpired(HardwareBuffer* buffer) { assert(buffer == destPositionBuffer.get() || buffer == destNormalBuffer.get()); if (buffer == destPositionBuffer.get()) destPositionBuffer.setNull(); if (buffer == destNormalBuffer.get()) destNormalBuffer.setNull(); } }
39.194932
118
0.561198
hackerlank
5d60f4453a4e2c0bff29e205fc60cc7dd8f2b7f5
5,548
cpp
C++
src/core/transform/ojph_colour_sse2.cpp
jpambrun/OpenJPH
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
[ "BSD-2-Clause" ]
null
null
null
src/core/transform/ojph_colour_sse2.cpp
jpambrun/OpenJPH
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
[ "BSD-2-Clause" ]
null
null
null
src/core/transform/ojph_colour_sse2.cpp
jpambrun/OpenJPH
9cce6ed4a74b3dd0f0cdc48d90b595cd0b8d9030
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************/ // This software is released under the 2-Clause BSD license, included // below. // // Copyright (c) 2019, Aous Naman // Copyright (c) 2019, Kakadu Software Pty Ltd, Australia // Copyright (c) 2019, The University of New South Wales, Australia // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /****************************************************************************/ // This file is part of the OpenJPH software implementation. // File: ojph_colour_sse2.cpp // Author: Aous Naman // Date: 11 October 2019 /****************************************************************************/ #include <cmath> #include "ojph_defs.h" #include "ojph_arch.h" #include "ojph_colour.h" #ifdef OJPH_COMPILER_MSVC #include <intrin.h> #else #include <x86intrin.h> #endif namespace ojph { namespace local { ////////////////////////////////////////////////////////////////////////// void sse2_cnvrt_float_to_si32_shftd(const float *sp, si32 *dp, float mul, int width) { uint32_t rounding_mode = _MM_GET_ROUNDING_MODE(); _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); __m128 shift = _mm_set1_ps(0.5f); __m128 m = _mm_set1_ps(mul); for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4) { __m128 t = _mm_loadu_ps(sp); __m128 s = _mm_add_ps(t, shift); s = _mm_mul_ps(s, m); _mm_storeu_si128((__m128i*)dp, _mm_cvtps_epi32(s)); } _MM_SET_ROUNDING_MODE(rounding_mode); } ////////////////////////////////////////////////////////////////////////// void sse2_cnvrt_float_to_si32(const float *sp, si32 *dp, float mul, int width) { uint32_t rounding_mode = _MM_GET_ROUNDING_MODE(); _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); __m128 m = _mm_set1_ps(mul); for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4) { __m128 t = _mm_loadu_ps(sp); __m128 s = _mm_mul_ps(t, m); _mm_storeu_si128((__m128i*)dp, _mm_cvtps_epi32(s)); } _MM_SET_ROUNDING_MODE(rounding_mode); } ////////////////////////////////////////////////////////////////////////// void sse2_cnvrt_si32_to_si32_shftd(const si32 *sp, si32 *dp, int shift, int width) { __m128i sh = _mm_set1_epi32(shift); for (int i = (width + 3) >> 2; i > 0; --i, sp+=4, dp+=4) { __m128i s = _mm_loadu_si128((__m128i*)sp); s = _mm_add_epi32(s, sh); _mm_storeu_si128((__m128i*)dp, s); } } ////////////////////////////////////////////////////////////////////////// void sse2_rct_forward(const si32 *r, const si32 *g, const si32 *b, si32 *y, si32 *cb, si32 *cr, int repeat) { for (int i = (repeat + 3) >> 2; i > 0; --i) { __m128i mr = _mm_load_si128((__m128i*)r); __m128i mg = _mm_load_si128((__m128i*)g); __m128i mb = _mm_load_si128((__m128i*)b); __m128i t = _mm_add_epi32(mr, mb); t = _mm_add_epi32(t, _mm_slli_epi32(mg, 1)); _mm_store_si128((__m128i*)y, _mm_srai_epi32(t, 2)); t = _mm_sub_epi32(mb, mg); _mm_store_si128((__m128i*)cb, t); t = _mm_sub_epi32(mr, mg); _mm_store_si128((__m128i*)cr, t); r += 4; g += 4; b += 4; y += 4; cb += 4; cr += 4; } } ////////////////////////////////////////////////////////////////////////// void sse2_rct_backward(const si32 *y, const si32 *cb, const si32 *cr, si32 *r, si32 *g, si32 *b, int repeat) { for (int i = (repeat + 3) >> 2; i > 0; --i) { __m128i my = _mm_load_si128((__m128i*)y); __m128i mcb = _mm_load_si128((__m128i*)cb); __m128i mcr = _mm_load_si128((__m128i*)cr); __m128i t = _mm_add_epi32(mcb, mcr); t = _mm_sub_epi32(my, _mm_srai_epi32(t, 2)); _mm_store_si128((__m128i*)g, t); __m128i u = _mm_add_epi32(mcb, t); _mm_store_si128((__m128i*)b, u); u = _mm_add_epi32(mcr, t); _mm_store_si128((__m128i*)r, u); y += 4; cb += 4; cr += 4; r += 4; g += 4; b += 4; } } } }
37.486486
78
0.550108
jpambrun
5d63312817b6c5ab1f5ff2e5a7de4c3775eff77e
8,319
cpp
C++
src/linux/InotifyEventLoop.cpp
dacap/panoptes
f7d4756f18ff610f0ef2c160d56cd00cc3582939
[ "MIT" ]
null
null
null
src/linux/InotifyEventLoop.cpp
dacap/panoptes
f7d4756f18ff610f0ef2c160d56cd00cc3582939
[ "MIT" ]
null
null
null
src/linux/InotifyEventLoop.cpp
dacap/panoptes
f7d4756f18ff610f0ef2c160d56cd00cc3582939
[ "MIT" ]
null
null
null
#include "pfw/linux/InotifyEventLoop.h" #include <sys/ioctl.h> #include <csignal> #include <iostream> using namespace pfw; InotifyEventLoop::InotifyEventLoop(int inotifyInstance, InotifyService *inotifyService) : mInotifyService(inotifyService) , mInotifyInstance(inotifyInstance) , mStopped(true) { int result = pthread_create(&mEventLoop, nullptr, work, this); if (result != 0) { mInotifyService->sendError( "Could not start InotifyEventLoop thread. ErrorCode: " + std::string(strerror(errno))); return; } mThreadStartedSemaphore.wait(); } bool InotifyEventLoop::isLooping() { return !mStopped; } void InotifyEventLoop::created(inotify_event *event, bool isDirectoryEvent, bool sendInitEvents) { if (event == NULL || mStopped) { return; } if (isDirectoryEvent) { mInotifyService->createDirectory(event->wd, strdup(event->name), sendInitEvents); } else { mInotifyService->create(event->wd, strdup(event->name)); } } void InotifyEventLoop::modified(inotify_event *event) { if (event == NULL || mStopped) { return; } mInotifyService->modify(event->wd, strdup(event->name)); } void InotifyEventLoop::deleted(inotify_event *event, bool isDirectoryRemoval) { if (event == NULL || mStopped) { return; } if (isDirectoryRemoval) { mInotifyService->removeDirectory(event->wd); } else { mInotifyService->remove(event->wd, strdup(event->name)); } } void InotifyEventLoop::moveStart(inotify_event * event, bool isDirectoryEvent, InotifyRenameEvent &renameEvent) { if (mStopped) { return; } renameEvent = InotifyRenameEvent(event, isDirectoryEvent); } void InotifyEventLoop::moveEnd(inotify_event * event, bool isDirectoryEvent, InotifyRenameEvent &renameEvent) { if (mStopped) { return; } if (!renameEvent.isGood) { return created(event, isDirectoryEvent, false); } renameEvent.isGood = false; if (renameEvent.cookie != event->cookie) { if (renameEvent.isDirectory) { mInotifyService->removeDirectory(renameEvent.wd, renameEvent.name); } mInotifyService->remove(renameEvent.wd, renameEvent.name); return created(event, isDirectoryEvent, false); } if (renameEvent.isDirectory) { mInotifyService->moveDirectory(renameEvent.wd, renameEvent.name, event->wd, event->name); } else { mInotifyService->move(renameEvent.wd, renameEvent.name, event->wd, event->name); } } void InotifyEventLoop::finish(void *args) { InotifyEventLoop *eventLoop = reinterpret_cast<InotifyEventLoop *>(args); eventLoop->mStopped = true; } void *InotifyEventLoop::work(void *args) { pthread_cleanup_push(InotifyEventLoop::finish, args); static const int BUFFER_SIZE = 16384; InotifyEventLoop *eventLoop = reinterpret_cast<InotifyEventLoop *>(args); eventLoop->mStopped = false; eventLoop->mThreadStartedSemaphore.signal(); InotifyRenameEvent renameEvent; while (!eventLoop->mStopped) { char buffer[BUFFER_SIZE]; auto bytesRead = read(eventLoop->mInotifyInstance, &buffer, BUFFER_SIZE); if (eventLoop->mStopped) { break; } else if (bytesRead == 0) { eventLoop->mInotifyService->sendError( "InotifyEventLoop thread mStopped because read returned 0."); break; } else if (bytesRead == -1) { // read was interrupted if (errno == EINTR) { break; } eventLoop->mInotifyService->sendError( "Read on inotify fails because of error: " + std::string(strerror(errno))); break; } ssize_t position = 0; inotify_event *event = nullptr; do { if (eventLoop->mStopped) { break; } event = (struct inotify_event *)(buffer + position); bool isDirectoryRemoval = event->mask & (uint32_t)(IN_IGNORED | IN_DELETE_SELF); bool isDirectoryEvent = event->mask & (uint32_t)(IN_ISDIR); if (renameEvent.isGood && event->cookie != renameEvent.cookie) { eventLoop->moveEnd(event, isDirectoryEvent, renameEvent); } else if (event->mask & (uint32_t)(IN_ATTRIB | IN_MODIFY)) { eventLoop->modified(event); } else if (event->mask & (uint32_t)IN_CREATE) { eventLoop->created(event, isDirectoryEvent); } else if (event->mask & (uint32_t)(IN_DELETE | IN_DELETE_SELF)) { eventLoop->deleted(event, isDirectoryRemoval); } else if (event->mask & (uint32_t)IN_MOVED_TO) { if (event->cookie == 0) { eventLoop->created(event, isDirectoryEvent); continue; } eventLoop->moveEnd(event, isDirectoryEvent, renameEvent); } else if (event->mask & (uint32_t)IN_MOVED_FROM) { if (event->cookie == 0) { eventLoop->deleted(event, isDirectoryRemoval); continue; } eventLoop->moveStart(event, isDirectoryEvent, renameEvent); } else if (event->mask & (uint32_t)IN_MOVE_SELF) { eventLoop->mInotifyService->remove(event->wd, strdup(event->name)); eventLoop->mInotifyService->removeDirectory(event->wd); } } while ((position += sizeof(struct inotify_event) + event->len) < bytesRead); if (eventLoop->mStopped) { break; } size_t bytesAvailable = 0; if (ioctl(eventLoop->mInotifyInstance, FIONREAD, &bytesAvailable) < 0) { continue; } if (bytesAvailable == 0) { // If we have a trailing renameEvent and not another event is in the // pipeline, then we need to finish this renameEvent. Otherwise we // will loose the information of pending rename event. if (renameEvent.isGood) { if (renameEvent.isDirectory) { eventLoop->mInotifyService->removeDirectory( renameEvent.wd, renameEvent.name); } eventLoop->mInotifyService->remove(renameEvent.wd, renameEvent.name); } } } pthread_cleanup_pop(1); return nullptr; } InotifyEventLoop::~InotifyEventLoop() { if (mStopped) { return; } mStopped = true; // \note(mathias): To be sure, that canceling the thread does not causes // abortion of the whole programm, because another lib reacts on signal 32, // we ignore the signal extra. Additionally we are saving the previous // handler to register this handler to signal 32 again at the end. (This is // only a assumption, because we was seeing this behaviour (abort of the // whole programm when calling dtor of NotifyEventLoop) in combination with // other libs without finding the root causes. auto previousHandler = std::signal(32, SIG_IGN); auto errorCode = pthread_cancel(mEventLoop); if (errorCode != 0) { mInotifyService->sendError( "Could not cancel InotifyEventLoop thread. ErrorCode: " + std::to_string(errorCode)); return; } errorCode = pthread_join(mEventLoop, NULL); if (errorCode != 0) { mInotifyService->sendError( "Could not join InotifyEventLoop thread. ErrorCode: " + std::to_string(errorCode)); } if (previousHandler != SIG_ERR) { std::signal(32, previousHandler); } }
33.011905
80
0.572184
dacap
5d6564bb0a711a45cfb9ec66e881bf51ebc78c8a
1,103
cpp
C++
src/worker/ProgressReporter.cpp
rosneru/ADiffView
5f7d6cf4c7b5c65ba1221370d272ba12c21f4911
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/worker/ProgressReporter.cpp
rosneru/ADiffView
5f7d6cf4c7b5c65ba1221370d272ba12c21f4911
[ "BSD-3-Clause", "MIT" ]
7
2019-02-09T18:27:06.000Z
2021-07-13T09:47:18.000Z
src/worker/ProgressReporter.cpp
rosneru/ADiffView
5f7d6cf4c7b5c65ba1221370d272ba12c21f4911
[ "BSD-3-Clause", "MIT" ]
null
null
null
#ifdef __clang__ #include <clib/exec_protos.h> #else #include <proto/exec.h> #endif #include <stddef.h> #include "ProgressMessage.h" #include "ProgressReporter.h" ProgressReporter::ProgressReporter(struct MsgPort* pProgressPort, struct MsgPort*& pReplyPort) : m_pProgressPort(pProgressPort), m_pReplyPort(pReplyPort), m_pProgressDescription("Progress..") { } void ProgressReporter::SetDescription(const char *pProgressDescription) { m_pProgressDescription = pProgressDescription; } void ProgressReporter::SetValue(int progress) { if ((m_pProgressPort == NULL) || (m_pReplyPort == NULL)) { return; } // Creating and initializing the progress message struct ProgressMessage progressMessage; progressMessage.mn_ReplyPort = m_pReplyPort; progressMessage.progress = progress; progressMessage.pDescription = m_pProgressDescription; // Sending the progress message, waiting for the answer and taking the // answer off the queue PutMsg(m_pProgressPort, &progressMessage); WaitPort(m_pReplyPort); GetMsg(m_pReplyPort); }
23.468085
72
0.738894
rosneru
5d680959dcb71b868b23f43aa85a4f3640be88cc
1,545
cc
C++
src/camera.cc
paly2/VESPID
aebfc05b7f9d152a69a168b9e31685de1abe48fa
[ "MIT" ]
1
2018-05-08T07:40:57.000Z
2018-05-08T07:40:57.000Z
src/camera.cc
paly2/VESPID
aebfc05b7f9d152a69a168b9e31685de1abe48fa
[ "MIT" ]
null
null
null
src/camera.cc
paly2/VESPID
aebfc05b7f9d152a69a168b9e31685de1abe48fa
[ "MIT" ]
null
null
null
#include <raspicam/raspicam_cv.h> #include <cxcore.hpp> #include <SDL_thread.h> #include <SDL_mutex.h> #include "camera.hh" #include "util.hh" namespace Camera { Camera::Camera() : m_newimage_tracker(CAMERA_CLASER_ONSUMERS) { m_thread.launch("CameraThread"); } bool Camera::newImage(int src_id) { if (m_newimage_tracker.getSingle(src_id)) { return true; } else if (SDL_SemTryWait(m_thread.newimage_sem) != SDL_MUTEX_TIMEDOUT) { m_newimage_tracker.setAllTrue(); return true; } return false; } void Camera::waitForImage(int src_id) { if (m_newimage_tracker.getSingle(src_id)) return; SDL_SemWait(m_thread.newimage_sem); m_newimage_tracker.setAllTrue(); } void Camera::retrieve(cv::Mat &image, int src_id) { SDL_LockMutex(m_thread.mutex); image = m_thread.image; SDL_UnlockMutex(m_thread.mutex); m_newimage_tracker.setSingleFalse(src_id); } void CameraThread::construct() { mutex = SDL_CreateMutex(); newimage_sem = SDL_CreateSemaphore(0); } CameraThread::~CameraThread() { destruct(); if (newimage_sem != NULL) SDL_DestroySemaphore(newimage_sem); if (mutex != NULL) SDL_DestroyMutex(mutex); } void CameraThread::onStart() { camera.set(CV_CAP_PROP_FORMAT, CV_8UC3); if (!camera.open()) throw CameraException(); } void CameraThread::onEnd() { camera.release(); } void CameraThread::loop() { camera.grab(); SDL_LockMutex(mutex); camera.retrieve(image); SDL_UnlockMutex(mutex); if (SDL_SemValue(newimage_sem) == 0) SDL_SemPost(newimage_sem); } }
21.164384
75
0.716505
paly2
5d6fe65c08f398e3f90cb09b236e570fdce17ca2
6,612
cpp
C++
Graph/10numberOfOpsToMakeNetworkConnected.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
1
2021-01-18T14:51:20.000Z
2021-01-18T14:51:20.000Z
Graph/10numberOfOpsToMakeNetworkConnected.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
Graph/10numberOfOpsToMakeNetworkConnected.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
class Solution { public: // Method 1: Using adjacency matrix and DFS/BFS to traverse for each nodes // By traversing each nodes we find the components of a graph // then check if atleast component-1 redundant edges are present or not // if present we return ans as component-1 as that many edges are // required to create MST of all components map<int,vector<int>> makeAdj(int n,vector<vector<int>> connections){ map<int,vector<int>> adjList; for(auto v:connections){ int node1 = v[0], node2 = v[1]; adjList[node1].push_back(node2); adjList[node2].push_back(node1); } return adjList; } int DFS(map<int,vector<int>> adjList, int u, vector<bool> &visited){ int ans = 0; if(visited[u]) return ans; else{ ans++; visited[u] = true; for(auto e:adjList[u]){ if(!visited[e]) ans += DFS(adjList,e,visited); } } return ans; } int makeConnected1(int n, vector<vector<int>>& connections) { // total edges present in graph int E = connections.size(); // if edges are less than n-1(i.e. no. of nodes-1) then no Minimum // spanning tree(MST) is possible if(E<n-1) return -1; // Make adjacency list of graph map<int,vector<int>> adjList = makeAdj(n,connections); vector<bool> visited(n,false); // components are the individual elements present in a graph // components include standalone nodes, connected graph, group // of connected graphs // Example given graph below: // 0-------1 3 // \ / 5 // \ / \ // \ / 4 \ // 2 6 // This graph has 4 components, (0,1,2),(3),(4),(5,6) int components = 0; for(int i=0;i<n;i++){ // If not visited node appears means it is a new component if(!visited[i]){ components++; // DFS will mark the rest nodes of the current component // (if present) as visited // Here DFS returns the no. of nodes in each component DFS(adjList,i,visited); } } // Redundant edges are the edges that which even if remove won't // break the connetivity of nodes // For example in above graph any of (0,1) or (0,2) or (1,2) edge can // be removed without breaking the connectivity of the nodes // Also removing any of the above edges makes that component a MST // n-1 => minimum no.of edges to make MST of all nodes // components-1 => minimum no. of edges to make MST of all components // thus (n-1)-(components-1) gives the possible MSTs in graph without // adding extra edges(i.e. the minimum no. of edges in graph to maintain // the connectivity of nodes as present) // In above graph this value is 3 means that (0,1,2) and (5,6) maintains // connectivity as same with 3 edges // Thus we get total redundant nodes as total nodes - ((n-1)-(components-1)) int redundantEdges = E-((n-1)-(components-1)); // If redundant nodes are less then total components no connection possible if(redundantEdges<components-1) return -1; return (components-1); } // Method 2: Using Union Find Algorithm // In this method firstly all nodes are standalone then using parent vector // we start connecting the nodes to their parents and thus to their ultimate // parents, this way we can find the nodes joined to each other and the nodes // that are standalone // Keeps track of immediate parent of each node // i.e. for connected nodes they will have same parent(may not be immediate), // for standalone they will have themselves as the parent vector<int> parent; // Finds parent of given node recursively in parent vector as parent stores // the immediated parent of each node so recursion is used to find the ultimate // parent int find(int v){ if(parent[v]!=v) return find(parent[v]); else return v; } int makeConnected(int n, vector<vector<int>>& connections) { // total edges present in graph int E = connections.size(); // if edges are less than n-1(i.e. no. of nodes-1) then no Minimum // spanning tree(MST) is possible if(E<n-1) return -1; // Initially we consider every node is standalone for(int i=0;i<n;i++) parent.push_back(i); for(auto connection:connections){ int node1 = connection[0], node2 = connection[1]; // Ultimate parent of both node is found int p1 = find(node1), p2 = find(node2); // If ultimate parent isn't same then, ultimate parent of // node1 is assigned as ultimate parent of node2 // This is naive union set finding // this procedure takes linear time to find the disjoint // sets, using rank decreases T(n) to logarithmic scale // and using rank along with path compression reduces T(n) // to constant if(p1!=p2) parent[p2] = parent[p1]; } int component = 0; // Counting the components, nodes with same parent belong to same component // thus when node's parent found as same node denotes its a new component's // parent, else when not equal means node has some other parent for(int i=0;i<n;i++) if(parent[i]==i) component++; // Uncomment to see immediate parent of each node // for(int i=0;i<n;i++) cout<<i<<" "<<parent[i]<<endl; return component-1; } // For input: // 12 // [[1,5],[1,7],[1,2],[1,4],[3,7],[4,7],[3,5],[0,6],[0,1],[0,4],[2,6],[0,3],[0,2]] // The parent-node relation comes out to be: // 0 // / \ // 3 6 // / // 1 // / / \ \ // 5 7 2 4 // Thus the standalone nodes are 8,9,10,11 // Thus total components are 5 };
37.355932
86
0.540532
Coderangshu
5d72959b82f3512f3036468d26d20a78356e82a3
1,517
hpp
C++
src/Numerical/RootFinding/RootFinder.hpp
wthrowe/spectre
0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15
[ "MIT" ]
null
null
null
src/Numerical/RootFinding/RootFinder.hpp
wthrowe/spectre
0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15
[ "MIT" ]
null
null
null
src/Numerical/RootFinding/RootFinder.hpp
wthrowe/spectre
0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. /// \file /// Declares function find_root_of_function #pragma once #include <functional> #include <limits> #include <boost/math/tools/toms748_solve.hpp> /*! \ingroup Functors * \brief Finds the root of the function f with the TOMS_748 method. * * \requires Function f be callable */ template <typename Function> double find_root_of_function(Function f, const double lower_bound, const double upper_bound, const double absolute_tolerance, const double relative_tolerance, const size_t max_iterations = 100) { boost::uintmax_t max_iter = max_iterations; // This solver requires tol to be passed as a termination condition. This // termination condition is equivalent to the convergence criteria used by the // GSL auto tol = [absolute_tolerance, relative_tolerance](double lhs, double rhs) { return (fabs(lhs - rhs) <= absolute_tolerance + relative_tolerance * fmin(fabs(lhs), fabs(rhs))); }; // Lower and upper bound are shifted by absolute tolerance so that the root // find does not fail if upper or lower bound are equal to the root within // tolerance auto result = boost::math::tools::toms748_solve( f, lower_bound - absolute_tolerance, upper_bound + absolute_tolerance, tol, max_iter); return result.first + 0.5 * (result.second - result.first); }
35.27907
80
0.673698
wthrowe
5d749b35c084fdd829b8b299179b46a3a95a6714
1,870
hpp
C++
external/caramel-poly/include/caramel-poly/detail/ConstexprPair.hpp
mikosz/caramel-engine
7dbf1bbe4ece9c1f6813723a0bb5872e33e0284a
[ "MIT" ]
1
2019-01-12T22:37:21.000Z
2019-01-12T22:37:21.000Z
external/caramel-poly/include/caramel-poly/detail/ConstexprPair.hpp
mikosz/caramel-engine
7dbf1bbe4ece9c1f6813723a0bb5872e33e0284a
[ "MIT" ]
null
null
null
external/caramel-poly/include/caramel-poly/detail/ConstexprPair.hpp
mikosz/caramel-engine
7dbf1bbe4ece9c1f6813723a0bb5872e33e0284a
[ "MIT" ]
null
null
null
// Copyright Mikolaj Radwan 2018 // Distributed under the MIT license (See accompanying file LICENSE) #ifndef CARAMELPOLY_DETAIL_CONSTEXPRPAIR_HPP__ #define CARAMELPOLY_DETAIL_CONSTEXPRPAIR_HPP__ #include <type_traits> namespace caramel::poly::detail { template <class FirstT, class SecondT, class = void> class ConstexprPairStorage; template <class FirstT, class SecondT> class ConstexprPairStorage<FirstT, SecondT, std::enable_if_t<std::is_empty_v<FirstT> && std::is_empty_v<SecondT>>> { public: constexpr ConstexprPairStorage() = default; constexpr ConstexprPairStorage(FirstT, SecondT) { } constexpr FirstT first() const { return FirstT{}; } constexpr SecondT second() const { return SecondT{}; } }; template <class FirstT, class SecondT> class ConstexprPairStorage<FirstT, SecondT, std::enable_if_t<std::is_empty_v<FirstT> && !std::is_empty_v<SecondT>>> { public: constexpr ConstexprPairStorage() = default; constexpr ConstexprPairStorage(FirstT, SecondT s) : second_(std::move(s)) { } constexpr FirstT first() const { return FirstT{}; } constexpr SecondT second() const { return second_; } private: SecondT second_; }; template <class FirstT, class SecondT> class ConstexprPair : public ConstexprPairStorage<FirstT, SecondT> { public: using First = FirstT; using Second = SecondT; constexpr ConstexprPair() = default; constexpr ConstexprPair(First f, Second s) : ConstexprPairStorage<FirstT, SecondT>(std::move(f), std::move(s)) { } }; template <class First, class Second> constexpr auto makeConstexprPair(First f, Second s) { return ConstexprPair<First, Second>{ std::move(f), std::move(s) }; } constexpr auto first = [](auto p) { return p.first(); }; constexpr auto second = [](auto p) { return p.second(); }; } // namespace caramel::poly::detail #endif /* CARAMELPOLY_DETAIL_CONSTEXPRPAIR_HPP__ */
21.744186
117
0.738503
mikosz
5d74f56001e927aab9dae7bfaf5bcd2e6d6e99ed
554
inl
C++
GameEngine/GameEngine/src/Resources.inl
SamCooksley/GameEngine
3c32eba545428c8aa3227abcb815d8d799ab92d9
[ "Apache-2.0" ]
null
null
null
GameEngine/GameEngine/src/Resources.inl
SamCooksley/GameEngine
3c32eba545428c8aa3227abcb815d8d799ab92d9
[ "Apache-2.0" ]
null
null
null
GameEngine/GameEngine/src/Resources.inl
SamCooksley/GameEngine
3c32eba545428c8aa3227abcb815d8d799ab92d9
[ "Apache-2.0" ]
null
null
null
namespace engine { template <class T> std::shared_ptr<T> Resources::Load(const String & _path) { static_assert(std::is_base_of<Asset, T>::value, "Resource must be type of Object."); auto res = Application::s_context->resources.find(_path); if (res != Application::s_context->resources.end()) { return std::dynamic_pointer_cast<T>(res->second); } auto asset = T::Load(_path); if (!asset) { return nullptr; } Application::s_context->resources[_path] = asset; return asset; } } // engine
22.16
88
0.633574
SamCooksley
5d78dee24835002659c1dc33aa0a35839be4b565
3,773
cpp
C++
ngraph/core/reference/src/runtime/reference/tile.cpp
szabi-luxonis/openvino
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
[ "Apache-2.0" ]
2
2020-11-18T14:14:06.000Z
2020-11-28T04:55:57.000Z
ngraph/core/reference/src/runtime/reference/tile.cpp
szabi-luxonis/openvino
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
[ "Apache-2.0" ]
30
2020-11-13T11:44:07.000Z
2022-02-21T13:03:16.000Z
ngraph/core/reference/src/runtime/reference/tile.cpp
szabi-luxonis/openvino
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
[ "Apache-2.0" ]
1
2020-12-18T15:47:45.000Z
2020-12-18T15:47:45.000Z
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <algorithm> #include <cmath> #include <cstdio> #include <numeric> #include "ngraph/check.hpp" #include "ngraph/runtime/reference/tile.hpp" using namespace ngraph; namespace { /// \brief For each axis calculates the product of inner axes /// If dims has shape (2, 3, 4) then for 2 (first axis) the inner axes would be (3, 4) /// and for 3 (second axis) it would be (4) /// If dims has shape(2, 3, 4) then the output vector would be (3 * 4, 4, 1) /// The outermost axis is not used. For innermost axis it is always 1. /// \param[in] dims Shape of the output /// /// \return Vector containing calculated values for each axis. std::vector<int64_t> create_pitches(const Shape& dims) { std::vector<int64_t> pitch; pitch.resize(dims.size() - 1); std::partial_sum( dims.rbegin(), dims.rend() - 1, pitch.rbegin(), std::multiplies<int64_t>()); pitch.push_back(1); return pitch; } } void runtime::reference::tile(const char* arg, char* out, const Shape& in_shape, const Shape& out_shape, const size_t elem_size, const std::vector<int64_t>& repeats) { Shape in_shape_expanded(in_shape); in_shape_expanded.insert(in_shape_expanded.begin(), out_shape.size() - in_shape.size(), 1); size_t block_size = 0; int64_t num_repeats = 0; const int input_rank = in_shape_expanded.size(); const int64_t last_dim = in_shape_expanded[input_rank - 1]; const std::vector<int64_t> pitches = create_pitches(out_shape); const char* copy = nullptr; std::vector<int64_t> indices(in_shape_expanded.size() - 1, 0); size_t axis = indices.size(); // Copy and repeat data for innermost axis as many times as described in the repeats parameter while (axis <= indices.size()) { block_size = last_dim * elem_size; memcpy(out, arg, block_size); out += block_size; arg += block_size; copy = out - block_size; num_repeats = repeats[input_rank - 1] - 1; for (int64_t i = 0; i < num_repeats; ++i) { memcpy(out, copy, block_size); out += block_size; } // Copy and repeat data for other axes as many times as described in the repeats parameter while (axis-- != 0) { if (++indices[axis] != in_shape_expanded[axis]) { axis = indices.size(); break; } indices[axis] = 0; ptrdiff_t pitch = pitches[axis] * in_shape_expanded[axis]; block_size = pitch * elem_size; copy = out - block_size; num_repeats = repeats[axis] - 1; for (int64_t i = 0; i < num_repeats; i++) { memcpy(out, copy, block_size); out += block_size; } } } }
35.933333
98
0.571694
szabi-luxonis
5d7af16dd1a8576e69027603e04837e44e0044ba
2,066
cpp
C++
GameServer/Source/MapRateInfo.cpp
sp3cialk/MU-S8EP2-Repack
202856a74c905c203b9b2795fd161f564ca8b257
[ "MIT" ]
10
2019-04-09T23:36:43.000Z
2022-02-10T19:20:52.000Z
GameServer/Source/MapRateInfo.cpp
microvn/mu-s8ep2-repack
202856a74c905c203b9b2795fd161f564ca8b257
[ "MIT" ]
1
2019-09-25T17:12:36.000Z
2019-09-25T17:12:36.000Z
GameServer/Source/MapRateInfo.cpp
microvn/mu-s8ep2-repack
202856a74c905c203b9b2795fd161f564ca8b257
[ "MIT" ]
9
2019-09-25T17:12:57.000Z
2021-08-18T01:21:25.000Z
#include "stdafx.h" #include "MapRateInfo.h" #include "..\pugixml\pugixml.hpp" #include "GameMain.h" #include "MasterSkillSystem.h" using namespace pugi; MapRateInfo g_MapRateInfo; MapRateInfo::MapRateInfo() { } MapRateInfo::~MapRateInfo() { } void MapRateInfo::Init() { this->m_RateInfo.clear(); if( this->m_RateInfo.capacity() > 0 ) { std::vector<MapRateData>().swap(this->m_RateInfo); } } void MapRateInfo::Load() { this->Init(); this->Read(gDirPath.GetNewPath(FILE_CUSTOM_MAPRATEINFO)); } void MapRateInfo::Read(LPSTR File) { xml_document Document; xml_parse_result Result = Document.load_file(File); // ---- if( Result.status != status_ok ) { MsgBox("[MapRateInfo] File %s not found!", File); return; } // ---- xml_node MapRateInfo = Document.child("maprateinfo"); // ---- for( xml_node Node = MapRateInfo.child("map"); Node; Node = Node.next_sibling() ) { MapRateData lpInfo; lpInfo.MapNumber = Node.attribute("id").as_int(); lpInfo.ExpIncrease = Node.attribute("exp").as_int(); lpInfo.MasterExpIncrease = Node.attribute("masterexp").as_int(); lpInfo.MoneyIncrease = Node.attribute("money").as_int(); this->m_RateInfo.push_back(lpInfo); } } float MapRateInfo::GetExp(short MapNumber) { for( int i = 0; i < this->m_RateInfo.size(); i++ ) { if( this->m_RateInfo[i].MapNumber == MapNumber && this->m_RateInfo[i].ExpIncrease != 0 ) { return this->m_RateInfo[i].ExpIncrease; } } // ---- return gAddExperience; } float MapRateInfo::GetMasterExp(short MapNumber) { for( int i = 0; i < this->m_RateInfo.size(); i++ ) { if( this->m_RateInfo[i].MapNumber == MapNumber && this->m_RateInfo[i].MasterExpIncrease != 0 ) { return this->m_RateInfo[i].MasterExpIncrease; } } // ---- return g_MasterExp.m_AddExp; } float MapRateInfo::GetMoney(short MapNumber) { for( int i = 0; i < this->m_RateInfo.size(); i++ ) { if( this->m_RateInfo[i].MapNumber == MapNumber && this->m_RateInfo[i].MoneyIncrease != 0 ) { return this->m_RateInfo[i].MoneyIncrease; } } // ---- return gAddZen; }
20.868687
82
0.671346
sp3cialk
5d7c098b2c29bc5c4548848c198e47fd3d847a75
2,573
cc
C++
linux/flutter_jscore_plugin.cc
xuelongqy/flutter_jscore
dd8bf1153c7a8bfc78adfd24accb129740b8aa29
[ "MIT" ]
122
2020-02-26T06:27:46.000Z
2022-03-25T08:37:54.000Z
linux/flutter_jscore_plugin.cc
xuelongqy/flutter_jscore
dd8bf1153c7a8bfc78adfd24accb129740b8aa29
[ "MIT" ]
11
2020-03-15T10:36:57.000Z
2022-01-19T06:28:08.000Z
linux/flutter_jscore_plugin.cc
xuelongqy/flutter_jscore
dd8bf1153c7a8bfc78adfd24accb129740b8aa29
[ "MIT" ]
19
2020-03-10T15:30:13.000Z
2021-11-23T14:52:25.000Z
#include "include/flutter_jscore/flutter_jscore_plugin.h" #include <flutter_linux/flutter_linux.h> #include <gtk/gtk.h> #include <sys/utsname.h> #include <cstring> #define FLUTTER_JSCORE_PLUGIN(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), flutter_jscore_plugin_get_type(), \ FlutterJscorePlugin)) struct _FlutterJscorePlugin { GObject parent_instance; }; G_DEFINE_TYPE(FlutterJscorePlugin, flutter_jscore_plugin, g_object_get_type()) // Called when a method call is received from Flutter. static void flutter_jscore_plugin_handle_method_call( FlutterJscorePlugin* self, FlMethodCall* method_call) { g_autoptr(FlMethodResponse) response = nullptr; const gchar* method = fl_method_call_get_name(method_call); if (strcmp(method, "getPlatformVersion") == 0) { struct utsname uname_data = {}; uname(&uname_data); g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); g_autoptr(FlValue) result = fl_value_new_string(version); response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } fl_method_call_respond(method_call, response, nullptr); } static void flutter_jscore_plugin_dispose(GObject* object) { G_OBJECT_CLASS(flutter_jscore_plugin_parent_class)->dispose(object); } static void flutter_jscore_plugin_class_init(FlutterJscorePluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = flutter_jscore_plugin_dispose; } static void flutter_jscore_plugin_init(FlutterJscorePlugin* self) {} static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlutterJscorePlugin* plugin = FLUTTER_JSCORE_PLUGIN(user_data); flutter_jscore_plugin_handle_method_call(plugin, method_call); } void flutter_jscore_plugin_register_with_registrar(FlPluginRegistrar* registrar) { FlutterJscorePlugin* plugin = FLUTTER_JSCORE_PLUGIN( g_object_new(flutter_jscore_plugin_get_type(), nullptr)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), "flutter_jscore", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_cb, g_object_ref(plugin), g_object_unref); g_object_unref(plugin); }
36.239437
82
0.743101
xuelongqy
5d8351b210297e42b59a3a9f4d8cef979bbf537a
497
cpp
C++
CsWeapon/Source/CsWp/Public/Trace/Data/Sound/CsData_TraceWeapon_SoundFire.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsWeapon/Source/CsWp/Public/Trace/Data/Sound/CsData_TraceWeapon_SoundFire.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsWeapon/Source/CsWp/Public/Trace/Data/Sound/CsData_TraceWeapon_SoundFire.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Trace/Data/Sound/CsData_TraceWeapon_SoundFire.h" #include "CsWp.h" const FName ICsData_TraceWeapon_SoundFire::Name = FName("ICsData_TraceWeapon_SoundFire"); UCsData_TraceWeapon_SoundFire::UCsData_TraceWeapon_SoundFire(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } const FName NCsWeapon::NTrace::NData::NSound::NFire::IFire::Name = FName("NCsWeapon::NTrace::NData::NSound::NFire::IFire");
45.181818
132
0.806841
closedsum
5d8526bbc9ca05b3cea9dc75b261669fe244cff1
6,971
hpp
C++
Code/Foundation/Common/Containers/SlotMap.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Code/Foundation/Common/Containers/SlotMap.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
Code/Foundation/Common/Containers/SlotMap.hpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once #include "ContainerCommon.hpp" #include "Memory/Allocator.hpp" namespace Zero { /// Intrusive slot map container. Uses an array of slots combined with // a unique id. Value Type MUST be a pointer. template <typename keyType, typename dataType, typename slotPolicy, typename Allocator = DefaultAllocator> class Slotmap : public AllocationContainer<Allocator> { public: typedef dataType data_type; typedef dataType* pointer; typedef const dataType* const_pointer; typedef dataType& reference; typedef const dataType& const_reference; typedef ptrdiff_t difference_type; typedef Slotmap<keyType, dataType, slotPolicy> this_type; typedef AllocationContainer<Allocator> base_type; using base_type::mAllocator; static const size_t InvalidSlotIndex = 0xFFFFFFFF; pointer mData; data_type mNextFree; size_t mLargestSize; size_t mMaxSize; size_t mSize; pointer mBegin; pointer mEnd; Slotmap() { mSize = 0; mMaxSize = 0; mLargestSize = 0; mNextFree = nullptr; mBegin = nullptr; mEnd = nullptr; mData = nullptr; } ~Slotmap() { Deallocate(); } // The range/iterator for this container may not be intuitive. // We move over an array of slots just like iterating over // array of object pointers. The difference is that // invalid slots must be skipped over. struct range { public: typedef dataType value_type; typedef data_type FrontResult; range(pointer b, pointer e, this_type* owner) : begin(b), end(e), owner(owner) { } bool Empty() { return begin == end; } // NOT a reference data_type Front() { ErrorIf(Empty(), "Accessed empty range."); return *begin; } void PopFront() { ErrorIf(Empty(), "Popped empty range."); ++begin; // Skip over slots begin = owner->SkipInvalid(begin, end); } range& All() { return *this; } const range& All() const { return *this; } private: pointer begin; pointer end; this_type* owner; }; range All() { pointer begin = PointerBegin(); pointer end = PointerEnd(); begin = SkipInvalid(begin, end); return range(begin, end, this); } bool IsValid(data_type objPointer) { if (objPointer == nullptr) return false; size_t* valueTableBase = (size_t*)mBegin; size_t* endOfValueTable = (size_t*)mEnd; if ((size_t*)objPointer < endOfValueTable && (size_t*)objPointer >= valueTableBase) return false; else return true; } data_type FindValue(keyType& id) { // Get the slot index from the id size_t slotIndex = id.GetSlot(); if (slotIndex > mMaxSize) return nullptr; // Get the value from the table data_type objPointer = mData[slotIndex]; // This value may be a part of the internal free slot list // not a valid object pointer if (IsValid(objPointer)) { // The pointer is valid by it may point to a object // that has replaced the deleted object in the slot. // Check to see if the id is equal. keyType& foundId = slotPolicy::AccessId(objPointer); // Use operator equals for the id. if (foundId == id) { // id and object match this is correct object return objPointer; } } return nullptr; } range Find(keyType& id) { if (mData == nullptr) return range(PointerEnd(), PointerEnd(), this); data_type value = FindValue(id); if (value == nullptr) return range(PointerEnd(), PointerEnd(), this); else { pointer b = PointerBegin() + id.GetSlot(); return range(b, b + 1, this); } } /// Is the container empty? bool Empty() { return mSize == 0; } // How many elements are stored in the container. size_t Size() { return mSize; } void Clear() { mSize = 0; InitializeSlots(0, mMaxSize); } void Erase(keyType& eraseId) { // This slot index is now free size_t slotIndex = eraseId.GetSlot(); ErrorIf(slotIndex > mMaxSize, "Invalid slot index."); // Get the value from the table data_type pointer = mData[slotIndex]; keyType& foundId = slotPolicy::AccessId(pointer); if (foundId == eraseId) { AddToFreeList(eraseId.GetSlot()); // Reduce the size --mSize; #ifdef ZeroDebug eraseId.GetSlot() = InvalidSlotIndex; #endif } } void Erase(data_type objectToErase) { keyType& eraseId = slotPolicy::AccessId(objectToErase); return Erase(eraseId); } void Deallocate() { if (mMaxSize != 0) { mAllocator.Deallocate(mData, mMaxSize * sizeof(data_type)); mSize = 0; mMaxSize = 0; mData = nullptr; mNextFree = nullptr; } } // Must already have a unique id void Insert(data_type object) { keyType& insertKey = slotPolicy::AccessId(object); if (mNextFree == nullptr) { // Need more slots size_t currentSize = mMaxSize; size_t newMaxSize = mMaxSize * 2; if (newMaxSize == 0) newMaxSize = 4; pointer newTable = (pointer)mAllocator.Allocate(newMaxSize * sizeof(dataType)); // Copy over old elements if (mMaxSize != 0) { mAllocator.MemCopy(newTable, mData, mMaxSize * sizeof(dataType)); mAllocator.Deallocate(mData, mMaxSize * sizeof(data_type)); } mData = newTable; mMaxSize = newMaxSize; InitializeSlots(currentSize, newMaxSize); mBegin = mData; mEnd = mData + mMaxSize; } size_t* base = (size_t*)mBegin; size_t index = (size_t*)mNextFree - base; mNextFree = *(data_type*)mNextFree; insertKey.Slot = index; mData[index] = object; // increase the size ++mSize; // increase the watermark size if (mSize > mLargestSize) mLargestSize = mSize; } private: void InitializeSlots(size_t startIndex, size_t endIndex) { for (size_t i = startIndex; i < endIndex - 1; ++i) { data_type next = (data_type)&mData[i + 1]; mData[i] = next; } mData[endIndex - 1] = nullptr; mNextFree = (data_type)&mData[startIndex]; } void AddToFreeList(size_t slotIndex) { // Get a pointer to the slot size_t* base = (size_t*)mBegin; size_t* next = base + slotIndex; // Set it to the current free and the next // free to this one. mData[slotIndex] = (data_type)mNextFree; mNextFree = (data_type)next; } pointer SkipInvalid(pointer cur, pointer end) { // While not at the end of the list // and the slot is invalid move the pointer forward. while (cur != end && !IsValid(*cur)) ++cur; return cur; } pointer PointerBegin() { return mBegin; } pointer PointerEnd() { return mEnd; } // non copyable Slotmap(const Slotmap& other); void operator=(const Slotmap& other); }; } // namespace Zero
22.130159
106
0.629465
WelderUpdates
5d8656a057e698ddcbb02984eabfb6bfd9f7493b
3,334
cpp
C++
src/cpp/23. Merge k Sorted Lists.cpp
yjjnls/D.S.A-Leet
be19c3ccc1f704e75590786fdfd4cd3ab4818d4f
[ "MIT" ]
222
2018-09-25T08:46:31.000Z
2022-02-07T12:33:42.000Z
src/cpp/23. Merge k Sorted Lists.cpp
yjjnls/D.S.A-Leet
be19c3ccc1f704e75590786fdfd4cd3ab4818d4f
[ "MIT" ]
1
2017-11-23T04:39:48.000Z
2017-11-23T04:39:48.000Z
src/cpp/23. Merge k Sorted Lists.cpp
yjjnls/D.S.A-Leet
be19c3ccc1f704e75590786fdfd4cd3ab4818d4f
[ "MIT" ]
12
2018-10-05T03:16:05.000Z
2020-12-19T04:25:33.000Z
/* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <common.hpp> using std::priority_queue; class Solution { public: struct compare { bool operator()(const ListNode *l, const ListNode *r) { if (l == NULL || r == NULL) { return false; } return l->val > r->val; } }; ListNode *mergeKLists(vector<ListNode *> &lists) { if (lists.empty()) { return NULL; } priority_queue<ListNode *, vector<ListNode *>, compare> q; for (auto it : lists) { //这一句很重要 if (it != NULL) { q.push(it); } } ListNode dummy(0); ListNode *result = &dummy; while (!q.empty()) { result->next = q.top(); result = result->next; q.pop(); if (result != NULL && result->next != NULL) { q.push(result->next); } } return dummy.next; } }; /* solution 1 merge the list one by one, each process is a `merge 2 sorted lists` problem. time:O(N^2) solution 2 手动比较每个链表的当前第一个节点,选一个最小的合并 time:O(Nk) solution 3 use priority_queue time:O(Nlogk) k个链表一共有N个结点 space:O(N) 主要分配priority_queue的内存 该方法可能比较耗内存 solution 4 divide and conquer 原理和solution 1一样,但是合并过程用分治 这里的分治的意思是每两个链表合并一次,合并之后产生的新链表再重复这样的操作 两个链表合并还是按照solution 2的逐个比较元素,时间复杂度为O(n) k个链表,两两合并,最终的复杂度为O(logk) time:O(NlogK) space:O(1) */ class Solution4 { public: ListNode *mergeKLists(vector<ListNode *> &lists) { if (lists.empty()) return NULL; while (lists.size() > 1) { lists.push_back(mergeTwoLists(lists[0], lists[1])); lists.erase(lists.begin()); lists.erase(lists.begin()); } return lists.front(); } //可以用递归,也可以用迭代 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; if (l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } } }; #ifdef USE_GTEST TEST(DSA, 23_mergeKLists) { ListNode *l1 = create_list(vector<int>{1, 3, 5, 7}); ListNode *l2 = create_list(vector<int>{2, 4, 8}); ListNode *l3 = create_list(vector<int>{6, 9, 10}); vector<ListNode *> lists1 = {l1, l2, l3}; ListNode *result = create_list(vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); Solution s1; ListNode *res = s1.mergeKLists(lists1); compare_lists(res, result); free_list(res); ListNode *l4 = create_list(vector<int>{1, 3, 5, 7}); ListNode *l5 = create_list(vector<int>{2, 4, 8}); ListNode *l6 = create_list(vector<int>{6, 9, 10}); vector<ListNode *> lists2 = {l4, l5, l6}; Solution4 s4; res = s4.mergeKLists(lists2); compare_lists(res, result); free_list(res); free_list(result); } #endif
22.375839
98
0.538092
yjjnls
5d8d483cde66fb01c4dea11926a7591741ad3c7c
551
hpp
C++
library/ATF/__TEMP_WAIT_TOWER.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/__TEMP_WAIT_TOWER.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/__TEMP_WAIT_TOWER.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CMapData.hpp> START_ATF_NAMESPACE #pragma pack(push, 8) struct __TEMP_WAIT_TOWER { unsigned int dwMasterSerial; char byItemIndex; CMapData *pMap; float fPos[3]; unsigned int dwPushTime; bool bComplete; public: __TEMP_WAIT_TOWER(); void ctor___TEMP_WAIT_TOWER(); }; #pragma pack(pop) END_ATF_NAMESPACE
22.958333
108
0.662432
lemkova
5d90e81bf19edf19ce57074503f29e43b805b7df
996
hpp
C++
include/ShaderAST/Expr/ExprQuestion.hpp
jarrodmky/ShaderWriter
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
[ "MIT" ]
148
2018-10-11T16:51:37.000Z
2022-03-26T13:55:08.000Z
include/ShaderAST/Expr/ExprQuestion.hpp
jarrodmky/ShaderWriter
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
[ "MIT" ]
30
2019-11-30T11:43:07.000Z
2022-01-25T21:09:47.000Z
include/ShaderAST/Expr/ExprQuestion.hpp
jarrodmky/ShaderWriter
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
[ "MIT" ]
8
2020-04-17T13:18:30.000Z
2021-11-20T06:24:44.000Z
/* See LICENSE file in root folder */ #ifndef ___AST_ExprQuestion_H___ #define ___AST_ExprQuestion_H___ #pragma once #include "Expr.hpp" namespace ast::expr { class Question : public Expr { public: SDAST_API Question( type::TypePtr type , ExprPtr ctrlExpr , ExprPtr trueExpr , ExprPtr falseExpr ); SDAST_API void accept( VisitorPtr vis )override; inline Expr * getCtrlExpr()const { return m_ctrlExpr.get(); } inline Expr * getTrueExpr()const { return m_trueExpr.get(); } inline Expr * getFalseExpr()const { return m_falseExpr.get(); } private: ExprPtr m_ctrlExpr; ExprPtr m_trueExpr; ExprPtr m_falseExpr; }; using QuestionPtr = std::unique_ptr< Question >; inline QuestionPtr makeQuestion( type::TypePtr type , ExprPtr ctrlExpr , ExprPtr trueExpr , ExprPtr falseExpr ) { return std::make_unique< Question >( std::move( type ) , std::move( ctrlExpr ) , std::move( trueExpr ) , std::move( falseExpr ) ); } } #endif
17.172414
56
0.688755
jarrodmky
5d91476154f3b00ee3a98cb9c21e624303f71476
4,846
hpp
C++
include/Org/BouncyCastle/Math/EC/Rfc7748/X448Field.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/Org/BouncyCastle/Math/EC/Rfc7748/X448Field.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/Org/BouncyCastle/Math/EC/Rfc7748/X448Field.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Type namespace: Org.BouncyCastle.Math.EC.Rfc7748 namespace Org::BouncyCastle::Math::EC::Rfc7748 { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: Org.BouncyCastle.Math.EC.Rfc7748.X448Field // [CLSCompliantAttribute] Offset: DE2034 class X448Field : public ::Il2CppObject { public: // Creating value type constructor for type: X448Field X448Field() noexcept {} // static public System.Void Add(System.UInt32[] x, System.UInt32[] y, System.UInt32[] z) // Offset: 0x1D0E704 static void Add(::Array<uint>* x, ::Array<uint>* y, ::Array<uint>* z); // static public System.Void Carry(System.UInt32[] z) // Offset: 0x1D0E784 static void Carry(::Array<uint>* z); // static public System.Void CMov(System.Int32 cond, System.UInt32[] x, System.Int32 xOff, System.UInt32[] z, System.Int32 zOff) // Offset: 0x1D0E910 static void CMov(int cond, ::Array<uint>* x, int xOff, ::Array<uint>* z, int zOff); // static public System.Void CNegate(System.Int32 negate, System.UInt32[] z) // Offset: 0x1D0E99C static void CNegate(int negate, ::Array<uint>* z); // static public System.Void Copy(System.UInt32[] x, System.Int32 xOff, System.UInt32[] z, System.Int32 zOff) // Offset: 0x1D0EDCC static void Copy(::Array<uint>* x, int xOff, ::Array<uint>* z, int zOff); // static public System.UInt32[] Create() // Offset: 0x1D0E9EC static ::Array<uint>* Create(); // static public System.Void Encode(System.UInt32[] x, System.Byte[] z, System.Int32 zOff) // Offset: 0x1D0EE48 static void Encode(::Array<uint>* x, ::Array<uint8_t>* z, int zOff); // static private System.Void Encode24(System.UInt32 n, System.Byte[] bs, System.Int32 off) // Offset: 0x1D0EF88 static void Encode24(uint n, ::Array<uint8_t>* bs, int off); // static private System.Void Encode32(System.UInt32 n, System.Byte[] bs, System.Int32 off) // Offset: 0x1D0EFF8 static void Encode32(uint n, ::Array<uint8_t>* bs, int off); // static private System.Void Encode56(System.UInt32[] x, System.Int32 xOff, System.Byte[] bs, System.Int32 off) // Offset: 0x1D0EF0C static void Encode56(::Array<uint>* x, int xOff, ::Array<uint8_t>* bs, int off); // static public System.Void Inv(System.UInt32[] x, System.UInt32[] z) // Offset: 0x1D0F084 static void Inv(::Array<uint>* x, ::Array<uint>* z); // static public System.Int32 IsZero(System.UInt32[] x) // Offset: 0x1D0FC8C static int IsZero(::Array<uint>* x); // static public System.Void Mul(System.UInt32[] x, System.UInt32 y, System.UInt32[] z) // Offset: 0x1D0FCEC static void Mul(::Array<uint>* x, uint y, ::Array<uint>* z); // static public System.Void Mul(System.UInt32[] x, System.UInt32[] y, System.UInt32[] z) // Offset: 0x1D0F324 static void Mul(::Array<uint>* x, ::Array<uint>* y, ::Array<uint>* z); // static public System.Void Normalize(System.UInt32[] z) // Offset: 0x1D0FEF0 static void Normalize(::Array<uint>* z); // static public System.Void One(System.UInt32[] z) // Offset: 0x1D0FFD4 static void One(::Array<uint>* z); // static private System.Void PowPm3d4(System.UInt32[] x, System.UInt32[] z) // Offset: 0x1D0F0DC static void PowPm3d4(::Array<uint>* x, ::Array<uint>* z); // static private System.Void Reduce(System.UInt32[] z, System.Int32 x) // Offset: 0x1D0FF1C static void Reduce(::Array<uint>* z, int x); // static public System.Void Sqr(System.UInt32[] x, System.UInt32[] z) // Offset: 0x1D10030 static void Sqr(::Array<uint>* x, ::Array<uint>* z); // static public System.Void Sqr(System.UInt32[] x, System.Int32 n, System.UInt32[] z) // Offset: 0x1D0F2D8 static void Sqr(::Array<uint>* x, int n, ::Array<uint>* z); // static public System.Void Sub(System.UInt32[] x, System.UInt32[] y, System.UInt32[] z) // Offset: 0x1D0EA38 static void Sub(::Array<uint>* x, ::Array<uint>* y, ::Array<uint>* z); // static public System.Void SubOne(System.UInt32[] z) // Offset: 0x1D105EC static void SubOne(::Array<uint>* z); // static public System.Void Zero(System.UInt32[] z) // Offset: 0x1D1063C static void Zero(::Array<uint>* z); }; // Org.BouncyCastle.Math.EC.Rfc7748.X448Field #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Math::EC::Rfc7748::X448Field*, "Org.BouncyCastle.Math.EC.Rfc7748", "X448Field");
52.673913
133
0.647751
darknight1050
4b6b6b0da66e98c0b06eae7ea6b4d0052f4684ef
562
cpp
C++
test/test_main.cpp
polestar/audio_utils
9f5aedb2e21475b4b86e0adfab2da13fbf539930
[ "MIT" ]
1
2020-02-23T09:53:27.000Z
2020-02-23T09:53:27.000Z
test/test_main.cpp
polestar/audio_utils
9f5aedb2e21475b4b86e0adfab2da13fbf539930
[ "MIT" ]
1
2022-03-06T09:04:17.000Z
2022-03-06T09:04:17.000Z
test/test_main.cpp
cfogelklou/sweet_osal_platform
3ebb0ccc37910caf09fd7d2974c742cbdb57171e
[ "MIT" ]
1
2021-12-16T04:26:49.000Z
2021-12-16T04:26:49.000Z
#include <gtest/gtest.h> #include <gmock/gmock.h> using namespace testing; #ifdef WIN32 #include <Windows.h> #define usleep(x) Sleep(x/1000) #endif static void stupidRandom(uint8_t *buf, int cnt) { for (int i = 0; i < cnt; i++) { buf[i] = rand() % 255; } } TEST(TestAudioLib, bleah){ } int main(int argc, char** argv){ // The following line must be executed to initialize Google Mock // (and Google Test) before running the tests. ::testing::InitGoogleMock(&argc, argv); const int gtest_rval = RUN_ALL_TESTS(); return gtest_rval; }
18.733333
66
0.670819
polestar
4b6f9ef0f862da502aaa6a2bd64d1b87072fd18e
2,606
cpp
C++
mbed-glove-firmware/drivers/collector.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/collector.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/drivers/collector.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
1
2019-01-09T05:16:42.000Z
2019-01-09T05:16:42.000Z
/* * Filename: collector.cpp * Project: EECS 473 - Team GLOVE * Date: Fall 2016 * Authors: * Nick Bertoldi * Ben Heckathorn * Ryan O’Keefe * Adrian Padin * Tim Schumacher * * Purpose: * Implementation of collector.h * * Copyright (c) 2016 by Nick Bertoldi, Ben Heckathorn, Ryan O'Keefe, * Adrian Padin, Timothy Schumacher * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "collector.h" #include "string.h" Collector::Collector(FlexSensors& _flex, IMU_BNO055& _imu, TouchSensor& _touch, AdvertBLE& _adble) : flex(_flex), imu(_imu), touch(_touch), adble(_adble) { flex_data = glove_data.flex_sensors; // ptr to the first flex_sensor_t touch_data = &(glove_data.touch_sensor); // ptr to the key_states_t struct imu_data = &(glove_data.imu); // ptr to the bno_imu_t struct in glove data update_task_timer = new RtosTimer(this, &Collector::updateAndAdvertise, osTimerPeriodic); } void Collector::updateAndAdvertise() { imu.updateAndWrite(imu_data); flex.updateAndWrite(flex_data); touch.spawnUpdateThread(); Thread::wait(8); touch.writeKeys(touch_data); compressGloveSensors(&glove_data, &glove_data_compressed); adble.update((uint8_t*)&glove_data_compressed, glove_sensors_compressed_size); touch.terminateUpdateThreadIfBlocking(); adble.waitForEvent(); } void Collector::startUpdateTask(uint32_t ms) { update_task_timer->start(ms); } void Collector::stopUpdateTask() { update_task_timer->stop(); }
34.289474
82
0.719493
apadin1
4b735d80b365f4d2664e4cc049e18481dfc5751f
1,333
hpp
C++
irohad/model/commands/transfer_asset.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
irohad/model/commands/transfer_asset.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
irohad/model/commands/transfer_asset.hpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_TRANSFER_ASSET_HPP #define IROHA_TRANSFER_ASSET_HPP #include <string> #include "model/command.hpp" namespace iroha { namespace model { /** * Transfer asset from one account to another */ struct TransferAsset : public Command { /** * Source account */ std::string src_account_id; /** * Destination account */ std::string dest_account_id; /** * Asset to transfer. Identifier is asset_id */ std::string asset_id; /** * Transfer description */ std::string description; /** * Amount of transferred asset */ std::string amount; bool operator==(const Command &command) const override; TransferAsset() {} TransferAsset(const std::string &src_account_id, const std::string &dest_account_id, const std::string &asset_id, const std::string &amount) : src_account_id(src_account_id), dest_account_id(dest_account_id), asset_id(asset_id), amount(amount) {} }; } // namespace model } // namespace iroha #endif // IROHA_TRANSFER_ASSET_HPP
22.216667
61
0.585146
akshatkarani
4b7415838596cae7fdb9101e92160b495319b9b4
570
cpp
C++
13-stencil-buffered/project/src/stencil.cpp
walkieq/fccm2021-tutorial
f0eb2976a657f5a7c5a54be0ebb5d19b79fe93ee
[ "Apache-2.0" ]
2
2021-05-07T22:12:42.000Z
2021-05-09T04:36:28.000Z
13-stencil-buffered/project/src/stencil.cpp
yluo39github/fccm2021-tutorial
af341027d6302deead2a6666254c60d3a46dc6d2
[ "Apache-2.0" ]
null
null
null
13-stencil-buffered/project/src/stencil.cpp
yluo39github/fccm2021-tutorial
af341027d6302deead2a6666254c60d3a46dc6d2
[ "Apache-2.0" ]
2
2021-05-09T14:42:51.000Z
2021-12-05T22:32:10.000Z
#define DATA_SIZE 1024 #define STENCIL_SIZE 16 extern "C" { void stencil(int *in1, int *out) { int buffer[STENCIL_SIZE]; for(unsigned int i = 0; i < (STENCIL_SIZE - 1); i++) buffer[i + 1] = in1[i]; for(unsigned int i = 0; i < DATA_SIZE; i++) { for(unsigned int j = 0; j < (STENCIL_SIZE - 1); j++) buffer[j] = buffer[j + 1]; buffer[STENCIL_SIZE - 1] = in1[i + STENCIL_SIZE - 1]; int acc = 0; for(unsigned int j = 0; j < STENCIL_SIZE; j++) acc += buffer[j]; out[i] = acc; } } }
22.8
61
0.519298
walkieq