hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a9918e4f7a72bf0be080b310ff028b658ad8ef5e
8,353
cpp
C++
build/linux-build/Sources/src/zpp_nape/util/ZNPNode_ZPP_Constraint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPNode_ZPP_Constraint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/util/ZNPNode_ZPP_Constraint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_zpp_nape_constraint_ZPP_Constraint #include <hxinc/zpp_nape/constraint/ZPP_Constraint.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPNode_ZPP_Constraint #include <hxinc/zpp_nape/util/ZNPNode_ZPP_Constraint.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_985aee786169fab8_14943_new,"zpp_nape.util.ZNPNode_ZPP_Constraint","new",0xdd42d2a0,"zpp_nape.util.ZNPNode_ZPP_Constraint.new","zpp_nape/util/Lists.hx",14943,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14971_alloc,"zpp_nape.util.ZNPNode_ZPP_Constraint","alloc",0x59f7b6b5,"zpp_nape.util.ZNPNode_ZPP_Constraint.alloc","zpp_nape/util/Lists.hx",14971,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14975_free,"zpp_nape.util.ZNPNode_ZPP_Constraint","free",0xb7f5926c,"zpp_nape.util.ZNPNode_ZPP_Constraint.free","zpp_nape/util/Lists.hx",14975,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14982_elem,"zpp_nape.util.ZNPNode_ZPP_Constraint","elem",0xb747ce4f,"zpp_nape.util.ZNPNode_ZPP_Constraint.elem","zpp_nape/util/Lists.hx",14982,0x9f4e6754) HX_LOCAL_STACK_FRAME(_hx_pos_985aee786169fab8_14944_boot,"zpp_nape.util.ZNPNode_ZPP_Constraint","boot",0xb54e79f2,"zpp_nape.util.ZNPNode_ZPP_Constraint.boot","zpp_nape/util/Lists.hx",14944,0x9f4e6754) namespace zpp_nape{ namespace util{ void ZNPNode_ZPP_Constraint_obj::__construct(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14943_new) HXLINE(14977) this->elt = null(); HXLINE(14968) this->next = null(); } Dynamic ZNPNode_ZPP_Constraint_obj::__CreateEmpty() { return new ZNPNode_ZPP_Constraint_obj; } void *ZNPNode_ZPP_Constraint_obj::_hx_vtable = 0; Dynamic ZNPNode_ZPP_Constraint_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > _hx_result = new ZNPNode_ZPP_Constraint_obj(); _hx_result->__construct(); return _hx_result; } bool ZNPNode_ZPP_Constraint_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6111d1f2; } void ZNPNode_ZPP_Constraint_obj::alloc(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14971_alloc) } HX_DEFINE_DYNAMIC_FUNC0(ZNPNode_ZPP_Constraint_obj,alloc,(void)) void ZNPNode_ZPP_Constraint_obj::free(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14975_free) HXDLIN(14975) this->elt = null(); } HX_DEFINE_DYNAMIC_FUNC0(ZNPNode_ZPP_Constraint_obj,free,(void)) ::zpp_nape::constraint::ZPP_Constraint ZNPNode_ZPP_Constraint_obj::elem(){ HX_STACKFRAME(&_hx_pos_985aee786169fab8_14982_elem) HXDLIN(14982) return this->elt; } HX_DEFINE_DYNAMIC_FUNC0(ZNPNode_ZPP_Constraint_obj,elem,return ) ::zpp_nape::util::ZNPNode_ZPP_Constraint ZNPNode_ZPP_Constraint_obj::zpp_pool; hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > ZNPNode_ZPP_Constraint_obj::__new() { hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > __this = new ZNPNode_ZPP_Constraint_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZNPNode_ZPP_Constraint_obj > ZNPNode_ZPP_Constraint_obj::__alloc(hx::Ctx *_hx_ctx) { ZNPNode_ZPP_Constraint_obj *__this = (ZNPNode_ZPP_Constraint_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZNPNode_ZPP_Constraint_obj), true, "zpp_nape.util.ZNPNode_ZPP_Constraint")); *(void **)__this = ZNPNode_ZPP_Constraint_obj::_hx_vtable; __this->__construct(); return __this; } ZNPNode_ZPP_Constraint_obj::ZNPNode_ZPP_Constraint_obj() { } void ZNPNode_ZPP_Constraint_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZNPNode_ZPP_Constraint); HX_MARK_MEMBER_NAME(next,"next"); HX_MARK_MEMBER_NAME(elt,"elt"); HX_MARK_END_CLASS(); } void ZNPNode_ZPP_Constraint_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(next,"next"); HX_VISIT_MEMBER_NAME(elt,"elt"); } hx::Val ZNPNode_ZPP_Constraint_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"elt") ) { return hx::Val( elt ); } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { return hx::Val( next ); } if (HX_FIELD_EQ(inName,"free") ) { return hx::Val( free_dyn() ); } if (HX_FIELD_EQ(inName,"elem") ) { return hx::Val( elem_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"alloc") ) { return hx::Val( alloc_dyn() ); } } return super::__Field(inName,inCallProp); } bool ZNPNode_ZPP_Constraint_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { outValue = ( zpp_pool ); return true; } } return false; } hx::Val ZNPNode_ZPP_Constraint_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"elt") ) { elt=inValue.Cast< ::zpp_nape::constraint::ZPP_Constraint >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { next=inValue.Cast< ::zpp_nape::util::ZNPNode_ZPP_Constraint >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool ZNPNode_ZPP_Constraint_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { zpp_pool=ioValue.Cast< ::zpp_nape::util::ZNPNode_ZPP_Constraint >(); return true; } } return false; } void ZNPNode_ZPP_Constraint_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("next",f3,84,02,49)); outFields->push(HX_("elt",2d,02,4d,00)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZNPNode_ZPP_Constraint_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::zpp_nape::util::ZNPNode_ZPP_Constraint */ ,(int)offsetof(ZNPNode_ZPP_Constraint_obj,next),HX_("next",f3,84,02,49)}, {hx::fsObject /* ::zpp_nape::constraint::ZPP_Constraint */ ,(int)offsetof(ZNPNode_ZPP_Constraint_obj,elt),HX_("elt",2d,02,4d,00)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo ZNPNode_ZPP_Constraint_obj_sStaticStorageInfo[] = { {hx::fsObject /* ::zpp_nape::util::ZNPNode_ZPP_Constraint */ ,(void *) &ZNPNode_ZPP_Constraint_obj::zpp_pool,HX_("zpp_pool",81,5d,d4,38)}, { hx::fsUnknown, 0, null()} }; #endif static ::String ZNPNode_ZPP_Constraint_obj_sMemberFields[] = { HX_("next",f3,84,02,49), HX_("alloc",75,a4,93,21), HX_("free",ac,9c,c2,43), HX_("elt",2d,02,4d,00), HX_("elem",8f,d8,14,43), ::String(null()) }; static void ZNPNode_ZPP_Constraint_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ZNPNode_ZPP_Constraint_obj::zpp_pool,"zpp_pool"); }; #ifdef HXCPP_VISIT_ALLOCS static void ZNPNode_ZPP_Constraint_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ZNPNode_ZPP_Constraint_obj::zpp_pool,"zpp_pool"); }; #endif hx::Class ZNPNode_ZPP_Constraint_obj::__mClass; static ::String ZNPNode_ZPP_Constraint_obj_sStaticFields[] = { HX_("zpp_pool",81,5d,d4,38), ::String(null()) }; void ZNPNode_ZPP_Constraint_obj::__register() { ZNPNode_ZPP_Constraint_obj _hx_dummy; ZNPNode_ZPP_Constraint_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.util.ZNPNode_ZPP_Constraint",ae,42,05,36); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &ZNPNode_ZPP_Constraint_obj::__GetStatic; __mClass->mSetStaticField = &ZNPNode_ZPP_Constraint_obj::__SetStatic; __mClass->mMarkFunc = ZNPNode_ZPP_Constraint_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(ZNPNode_ZPP_Constraint_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(ZNPNode_ZPP_Constraint_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZNPNode_ZPP_Constraint_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ZNPNode_ZPP_Constraint_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZNPNode_ZPP_Constraint_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZNPNode_ZPP_Constraint_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void ZNPNode_ZPP_Constraint_obj::__boot() { { HX_STACKFRAME(&_hx_pos_985aee786169fab8_14944_boot) HXDLIN(14944) zpp_pool = null(); } } } // end namespace zpp_nape } // end namespace util
36.960177
203
0.774213
HedgehogFog
a9920d621af1be84ba993ce5ef5078ca74ef1c23
4,331
hpp
C++
cell_based/test/simulation/Test2dVertexBasedSimulationWithFreeBoundary.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
100
2015-02-23T08:32:23.000Z
2022-02-25T11:39:26.000Z
cell_based/test/simulation/Test2dVertexBasedSimulationWithFreeBoundary.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
11
2017-06-14T13:48:43.000Z
2022-03-10T10:42:07.000Z
cell_based/test/simulation/Test2dVertexBasedSimulationWithFreeBoundary.hpp
mdp19pn/Chaste
f7b6bafa64287d567125b587b29af6d8bd7aeb90
[ "Apache-2.0", "BSD-3-Clause" ]
53
2015-02-23T13:52:44.000Z
2022-02-28T18:57:35.000Z
/* Copyright (c) 2005-2021, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TEST2DVERTEXBASEDSIMULATIONWITHFREEBOUNDARY_HPP_ #define TEST2DVERTEXBASEDSIMULATIONWITHFREEBOUNDARY_HPP_ #include "AbstractCellBasedTestSuite.hpp" #include "CheckpointArchiveTypes.hpp" #include "OffLatticeSimulation.hpp" #include "VertexBasedCellPopulation.hpp" #include "FarhadifarForce.hpp" #include "TargetAreaLinearGrowthModifier.hpp" #include "CellsGenerator.hpp" #include "VoronoiVertexMeshGenerator.hpp" #include "DifferentiatedCellProliferativeType.hpp" #include "NoCellCycleModel.hpp" #include "SmartPointers.hpp" #include "FakePetscSetup.hpp" /** * This class consists of a single test, in which a 2D model * of a growing monolayer of cells is simulated for a fixed * period of time. * * This test is used for profiling, to establish the run time * variation as the code is developed. */ class Test2DVertexSimulationWithFreeBoundary : public AbstractCellBasedTestSuite { public: void Test2DFreeBoundaryVertexSimulationForProfiling() { // make the simulation std::vector<CellPtr> cells; MutableVertexMesh<2,2>* p_mesh; VoronoiVertexMeshGenerator mesh_generator = VoronoiVertexMeshGenerator(35,35,1,1.0); p_mesh = mesh_generator.GetMesh(); MAKE_PTR(DifferentiatedCellProliferativeType, p_differentiated_type); CellsGenerator<NoCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, p_mesh->GetNumElements(), p_differentiated_type); VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); double initial_target_area = 1.0; for (typename AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { // target areas cell_iter->GetCellData()->SetItem("target area", initial_target_area); } OffLatticeSimulation<2> simulator(cell_population); // Make the Farhadifar force MAKE_PTR(FarhadifarForce<2>, p_force); // before passing the force to the simulation simulator.AddForce(p_force); // We need a FarhadifarType target area modifier MAKE_PTR(TargetAreaLinearGrowthModifier<2>, p_growth_modifier); simulator.AddSimulationModifier(p_growth_modifier); simulator.SetEndTime(20); simulator.SetDt(0.01); // mpSimulator->SetSamplingTimestepMultiple( 100 ); simulator.SetOutputDirectory("VertexSimulationWithFreeBoundary"); simulator.Solve(); } }; #endif /*TEST2DVERTEXBASEDSIMULATIONWITHFREEBOUNDARY_HPP_*/
37.991228
100
0.758947
mdp19pn
a9931a90720b29f85ceec2f45caa1693d9b75a25
291
cpp
C++
1-6-6z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-6z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-6z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { double n, sum, k; cin >> n; while (n != 0){ sum = sum + n; k++; cin >> n; } cout << setprecision(11) << fixed; cout << sum/k << endl; return 0; }
14.55
38
0.484536
Kaermor
a9943c77e79fd002974dacddcc2ee90d6d34ea9c
3,921
cpp
C++
vm/objects.cpp
dch/factor
faacbb58e0738a0612a04b792a3f6ff4929134ff
[ "BSD-2-Clause" ]
null
null
null
vm/objects.cpp
dch/factor
faacbb58e0738a0612a04b792a3f6ff4929134ff
[ "BSD-2-Clause" ]
null
null
null
vm/objects.cpp
dch/factor
faacbb58e0738a0612a04b792a3f6ff4929134ff
[ "BSD-2-Clause" ]
null
null
null
#include "master.hpp" namespace factor { void factor_vm::primitive_special_object() { fixnum n = untag_fixnum(ctx->peek()); ctx->replace(special_objects[n]); } void factor_vm::primitive_set_special_object() { fixnum n = untag_fixnum(ctx->pop()); cell value = ctx->pop(); special_objects[n] = value; } void factor_vm::primitive_identity_hashcode() { cell tagged = ctx->peek(); object* obj = untag<object>(tagged); ctx->replace(tag_fixnum(obj->hashcode())); } void factor_vm::compute_identity_hashcode(object* obj) { object_counter++; if (object_counter == 0) object_counter++; obj->set_hashcode((cell)obj ^ object_counter); } void factor_vm::primitive_compute_identity_hashcode() { object* obj = untag<object>(ctx->pop()); compute_identity_hashcode(obj); } void factor_vm::primitive_set_slot() { fixnum slot = untag_fixnum(ctx->pop()); object* obj = untag<object>(ctx->pop()); cell value = ctx->pop(); cell* slot_ptr = &obj->slots()[slot]; *slot_ptr = value; write_barrier(slot_ptr); } /* Allocates memory */ cell factor_vm::clone_object(cell obj_) { data_root<object> obj(obj_, this); if (immediate_p(obj.value())) return obj.value(); else { cell size = object_size(obj.value()); object* new_obj = allot_object(obj.type(), size); memcpy(new_obj, obj.untagged(), size); new_obj->set_hashcode(0); return tag_dynamic(new_obj); } } /* Allocates memory */ void factor_vm::primitive_clone() { ctx->replace(clone_object(ctx->peek())); } /* Size of the object pointed to by a tagged pointer */ cell factor_vm::object_size(cell tagged) { if (immediate_p(tagged)) return 0; else return untag<object>(tagged)->size(); } /* Allocates memory */ void factor_vm::primitive_size() { ctx->replace(from_unsigned_cell(object_size(ctx->peek()))); } struct slot_become_fixup : no_fixup { std::map<object*, object*>* become_map; slot_become_fixup(std::map<object*, object*>* become_map) : become_map(become_map) {} object* fixup_data(object* old) { std::map<object*, object*>::const_iterator iter = become_map->find(old); if (iter != become_map->end()) return iter->second; else return old; } }; /* classes.tuple uses this to reshape tuples; tools.deploy.shaker uses this to coalesce equal but distinct quotations and wrappers. */ /* Calls gc */ void factor_vm::primitive_become() { primitive_minor_gc(); array* new_objects = untag_check<array>(ctx->pop()); array* old_objects = untag_check<array>(ctx->pop()); cell capacity = array_capacity(new_objects); if (capacity != array_capacity(old_objects)) critical_error("bad parameters to become", 0); /* Build the forwarding map */ std::map<object*, object*> become_map; for (cell i = 0; i < capacity; i++) { tagged<object> old_obj(array_nth(old_objects, i)); tagged<object> new_obj(array_nth(new_objects, i)); if (old_obj != new_obj) become_map[old_obj.untagged()] = new_obj.untagged(); } /* Update all references to old objects to point to new objects */ { slot_visitor<slot_become_fixup> visitor(this, slot_become_fixup(&become_map)); visitor.visit_all_roots(); auto object_become_visitor = [&](object* obj) { visitor.visit_slots(obj); }; each_object(object_become_visitor); auto code_block_become_visitor = [&](code_block* compiled, cell size) { visitor.visit_code_block_objects(compiled); visitor.visit_embedded_literals(compiled); }; each_code_block(code_block_become_visitor); } /* Since we may have introduced old->new references, need to revisit all objects and code blocks on a minor GC. */ data->mark_all_cards(); { auto code_block_visitor = [&](code_block* compiled, cell size) { code->write_barrier(compiled); }; each_code_block(code_block_visitor); } } }
27.229167
78
0.680949
dch
a9978a041f6824ddab4134a91bc9b57c1b799da7
4,167
cpp
C++
unittests/tdfs.cpp
hungptit/graph
8f39e8af1ea3bd3ad36190559553da5c55648aae
[ "MIT" ]
null
null
null
unittests/tdfs.cpp
hungptit/graph
8f39e8af1ea3bd3ad36190559553da5c55648aae
[ "MIT" ]
null
null
null
unittests/tdfs.cpp
hungptit/graph
8f39e8af1ea3bd3ad36190559553da5c55648aae
[ "MIT" ]
null
null
null
#include <iostream> #include <tuple> #include <vector> #include "fmt/format.h" #include "graph/graph.hpp" #include "Data.hpp" #include "cereal/archives/binary.hpp" #include "cereal/archives/json.hpp" #include "cereal/archives/portable_binary.hpp" #include "cereal/archives/xml.hpp" #include "cereal/types/array.hpp" #include "cereal/types/deque.hpp" #include "cereal/types/string.hpp" #include "cereal/types/set.hpp" #include "cereal/types/unordered_map.hpp" #include "cereal/types/unordered_set.hpp" #include "cereal/types/vector.hpp" #define CATCH_CONFIG_MAIN #include "catch/catch.hpp" std::vector<std::string> expectedResultsPostOrdering{ "D", "E", "F", "B", "G", "C", "A" }; std::vector<std::string> expectedResultsPreOrdering{ "A", "B", "D", "F", "E", "C", "G" }; TEST_CASE("dfs_preordering", "Positive") { using index_type = size_t; auto data = simpleDirectedGraph<index_type>(); auto edges = std::get<0>(data); auto labels = std::get<1>(data); auto N = std::get<2>(data); std::stringstream output; graph::SparseGraph<index_type, decltype(edges)::value_type> g(edges, N, true); index_type rootVid = 0; auto vids = graph::dfs_preordering<std::vector<index_type>>(g, {rootVid}); std::vector<std::string> results; for (auto vid : vids) { results.push_back(labels[vid]); } REQUIRE(expectedResultsPreOrdering == results); { cereal::JSONOutputArchive oar(output); oar(cereal::make_nvp("dfs results", results)); } fmt::print("{}\n", output.str()); } TEST_CASE("dfs_postordering", "Positive") { using index_type = size_t; auto data = simpleDirectedGraph<index_type>(); auto edges = std::get<0>(data); auto labels = std::get<1>(data); auto N = std::get<2>(data); std::stringstream output; graph::SparseGraph<index_type, decltype(edges)::value_type> g(edges, N, true); index_type rootVid = 0; auto vids = graph::dfs_postordering<std::vector<index_type>>(g, {rootVid}); std::vector<std::string> results; for (auto vid : vids) { results.push_back(labels[vid]); } REQUIRE(expectedResultsPostOrdering == results); { cereal::JSONOutputArchive oar(output); oar(cereal::make_nvp("dfs results", results)); } fmt::print("{}\n", output.str()); } TEST_CASE("dfs_recursive_preordering", "Positive") { using index_type = size_t; auto data = simpleDirectedGraph<index_type>(); auto edges = std::get<0>(data); auto labels = std::get<1>(data); auto N = std::get<2>(data); std::stringstream output; graph::SparseGraph<index_type, decltype(edges)::value_type> g(edges, N, true); index_type rootVid = 0; std::vector<graph::NodeStatus> status(N, graph::NodeStatus::UNDISCOVERED); std::vector<index_type> vids; vids.reserve(N); graph::dfs_recursive_preordering(g, rootVid, status, vids); std::vector<std::string> results; for (auto vid : vids) { results.push_back(labels[vid]); } REQUIRE(expectedResultsPreOrdering == results); { cereal::JSONOutputArchive oar(output); oar(cereal::make_nvp("dfs_recursive results", results)); } fmt::print("{}\n", output.str()); } TEST_CASE("dfs_recursive_postordering", "Positive") { using index_type = size_t; auto data = simpleDirectedGraph<index_type>(); auto edges = std::get<0>(data); auto labels = std::get<1>(data); auto N = std::get<2>(data); std::stringstream output; graph::SparseGraph<index_type, decltype(edges)::value_type> g(edges, N, true); index_type rootVid = 0; std::vector<graph::NodeStatus> status(N, graph::NodeStatus::UNDISCOVERED); std::vector<index_type> vids; vids.reserve(N); graph::dfs_recursive_postordering(g, rootVid, status, vids); std::vector<std::string> results; for (auto vid : vids) { results.push_back(labels[vid]); } REQUIRE(expectedResultsPostOrdering == results); { cereal::JSONOutputArchive oar(output); oar(cereal::make_nvp("dfs_recursive_postordering results", results)); } fmt::print("{}\n", output.str()); }
29.764286
90
0.658987
hungptit
a9986869f1116f9bdfa4c7d1f673bba821397e21
884
hpp
C++
src/include/duckdb/planner/operator/logical_filter.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
2
2020-01-07T17:19:02.000Z
2020-01-09T22:04:04.000Z
src/include/duckdb/planner/operator/logical_filter.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
src/include/duckdb/planner/operator/logical_filter.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // planner/operator/logical_filter.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/planner/logical_operator.hpp" namespace duckdb { //! LogicalFilter represents a filter operation (e.g. WHERE or HAVING clause) class LogicalFilter : public LogicalOperator { public: LogicalFilter(unique_ptr<Expression> expression); LogicalFilter(); bool SplitPredicates() { return SplitPredicates(expressions); } //! Splits up the predicates of the LogicalFilter into a set of predicates //! separated by AND Returns whether or not any splits were made static bool SplitPredicates(vector<unique_ptr<Expression>> &expressions); protected: void ResolveTypes() override; }; } // namespace duckdb
26.787879
80
0.602941
RelationalAI-oss
a99b9072f61187f3b72202784af1d6be9ffcb9ca
1,006
hpp
C++
core/network/grandpa_transmitter.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
110
2019-04-03T13:39:39.000Z
2022-03-09T11:54:42.000Z
core/network/grandpa_transmitter.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
890
2019-03-22T21:33:30.000Z
2022-03-31T14:31:22.000Z
core/network/grandpa_transmitter.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
27
2019-06-25T06:21:47.000Z
2021-11-01T14:12:10.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_NETWORK_GRANDPATRANSMITTER #define KAGOME_NETWORK_GRANDPATRANSMITTER #include <libp2p/peer/peer_id.hpp> #include "network/types/grandpa_message.hpp" namespace kagome::network { /** * Send/broadcast grandpa messages */ class GrandpaTransmitter { public: virtual ~GrandpaTransmitter() = default; virtual void sendNeighborMessage(GrandpaNeighborMessage &&message) = 0; virtual void sendVoteMessage(GrandpaVote &&message) = 0; virtual void sendCommitMessage(FullCommitMessage &&message) = 0; virtual void sendCatchUpRequest(const libp2p::peer::PeerId &peer_id, CatchUpRequest &&message) = 0; virtual void sendCatchUpResponse(const libp2p::peer::PeerId &peer_id, CatchUpResponse &&message) = 0; }; } // namespace kagome::network #endif // KAGOME_NETWORK_GRANDPATRANSMITTER
29.588235
75
0.695825
soramitsu
a99bae105113f72886b8e3cdefc10d046f88b6d7
676
hh
C++
src/plugin/input/input/api/bugengine/plugin.input.input/controllers/wincontrol.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
4
2015-05-13T16:28:36.000Z
2017-05-24T15:34:14.000Z
src/plugin/input/input/api/bugengine/plugin.input.input/controllers/wincontrol.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
null
null
null
src/plugin/input/input/api/bugengine/plugin.input.input/controllers/wincontrol.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
1
2017-03-21T08:28:07.000Z
2017-03-21T08:28:07.000Z
/* BugEngine <bugengine.devel@gmail.com> see LICENSE for detail */ #ifndef BE_INPUT_CONTROLLERS_WINCONTROL_HH_ #define BE_INPUT_CONTROLLERS_WINCONTROL_HH_ /**************************************************************************************************/ #include <bugengine/plugin.input.input/stdafx.h> #include <bugengine/plugin.input.input/controllers/controller.hh> namespace BugEngine { namespace Input { class Wincontrol : public Controller { BE_NOCOPY(Wincontrol); public: Wincontrol(); ~Wincontrol(); }; }} // namespace BugEngine::Input /**************************************************************************************************/ #endif
27.04
100
0.535503
bugengine
a99d47c3839c2f8354c85adb473725281fe17ebc
5,251
cc
C++
stack/mcap/mca_dact.cc
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
null
null
null
stack/mcap/mca_dact.cc
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
null
null
null
stack/mcap/mca_dact.cc
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
2
2019-05-30T08:37:28.000Z
2019-10-01T16:39:33.000Z
/****************************************************************************** * * Copyright (C) 2009-2012 Broadcom 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. * ******************************************************************************/ /****************************************************************************** * * This is the implementation file for the MCAP Data Channel Action * Functions. * ******************************************************************************/ #include <stddef.h> #include "bt_common.h" #include "bt_target.h" #include "bt_utils.h" #include "mca_api.h" #include "mca_int.h" #include "osi/include/osi.h" /******************************************************************************* * * Function mca_dcb_report_cong * * Description This function is called to report the congestion flag. * * Returns void. * ******************************************************************************/ void mca_dcb_report_cong(tMCA_DCB* p_dcb) { tMCA_CTRL evt_data; evt_data.cong_chg.cong = p_dcb->cong; evt_data.cong_chg.mdl = mca_dcb_to_hdl(p_dcb); evt_data.cong_chg.mdl_id = p_dcb->mdl_id; mca_ccb_report_event(p_dcb->p_ccb, MCA_CONG_CHG_EVT, &evt_data); } /******************************************************************************* * * Function mca_dcb_tc_open * * Description This function is called to report MCA_OPEN_IND_EVT or * MCA_OPEN_CFM_EVT event. * It also clears the congestion flag (dcb.cong). * * Returns void. * ******************************************************************************/ void mca_dcb_tc_open(tMCA_DCB* p_dcb, tMCA_DCB_EVT* p_data) { tMCA_CTRL evt_data; tMCA_CCB* p_ccb = p_dcb->p_ccb; uint8_t event = MCA_OPEN_IND_EVT; if (p_data->open.param == MCA_INT) event = MCA_OPEN_CFM_EVT; p_dcb->cong = false; evt_data.open_cfm.mtu = p_data->open.peer_mtu; evt_data.open_cfm.mdl_id = p_dcb->mdl_id; evt_data.open_cfm.mdl = mca_dcb_to_hdl(p_dcb); mca_ccb_event(p_ccb, MCA_CCB_DL_OPEN_EVT, NULL); mca_ccb_report_event(p_ccb, event, &evt_data); } /******************************************************************************* * * Function mca_dcb_cong * * Description This function sets the congestion state for the DCB. * * Returns void. * ******************************************************************************/ void mca_dcb_cong(tMCA_DCB* p_dcb, tMCA_DCB_EVT* p_data) { p_dcb->cong = p_data->llcong; mca_dcb_report_cong(p_dcb); } /******************************************************************************* * * Function mca_dcb_free_data * * Description This function frees the received message. * * Returns void. * ******************************************************************************/ void mca_dcb_free_data(UNUSED_ATTR tMCA_DCB* p_dcb, tMCA_DCB_EVT* p_data) { osi_free(p_data); } /******************************************************************************* * * Function mca_dcb_do_disconn * * Description This function closes a data channel. * * Returns void. * ******************************************************************************/ void mca_dcb_do_disconn(tMCA_DCB* p_dcb, UNUSED_ATTR tMCA_DCB_EVT* p_data) { tMCA_CLOSE close; if ((p_dcb->lcid == 0) || (L2CA_DisconnectReq(p_dcb->lcid) == false)) { close.param = MCA_INT; close.reason = L2CAP_DISC_OK; close.lcid = 0; mca_dcb_event(p_dcb, MCA_DCB_TC_CLOSE_EVT, (tMCA_DCB_EVT*)&close); } } /******************************************************************************* * * Function mca_dcb_snd_data * * Description Send the data from application to the peer device. * * Returns void. * ******************************************************************************/ void mca_dcb_snd_data(tMCA_DCB* p_dcb, tMCA_DCB_EVT* p_data) { uint8_t status; /* do not need to check cong, because API already checked the status */ status = L2CA_DataWrite(p_dcb->lcid, p_data->p_pkt); if (status == L2CAP_DW_CONGESTED) { p_dcb->cong = true; mca_dcb_report_cong(p_dcb); } } /******************************************************************************* * * Function mca_dcb_hdl_data * * Description This function reports the received data through the data * callback function. * * Returns void. * ******************************************************************************/ void mca_dcb_hdl_data(tMCA_DCB* p_dcb, tMCA_DCB_EVT* p_data) { (*p_dcb->p_cs->p_data_cback)(mca_dcb_to_hdl(p_dcb), (BT_HDR*)p_data); }
33.44586
80
0.496477
digi-embedded
a99e0afd23777c3561f350d3aceb141b1c9b3664
72,093
cc
C++
chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/predictors/resource_prefetch_predictor.h" #include <iostream> #include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/time/time.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/predictors/resource_prefetch_predictor_tables.h" #include "chrome/browser/predictors/resource_prefetch_predictor_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_types.h" #include "content/public/browser/resource_request_info.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_job.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::ContainerEq; using testing::Pointee; using testing::SetArgPointee; using testing::StrictMock; using testing::UnorderedElementsAre; namespace predictors { using URLRequestSummary = ResourcePrefetchPredictor::URLRequestSummary; using PageRequestSummary = ResourcePrefetchPredictor::PageRequestSummary; using PrefetchDataMap = ResourcePrefetchPredictorTables::PrefetchDataMap; using RedirectDataMap = ResourcePrefetchPredictorTables::RedirectDataMap; scoped_refptr<net::HttpResponseHeaders> MakeResponseHeaders( const char* headers) { return make_scoped_refptr(new net::HttpResponseHeaders( net::HttpUtil::AssembleRawHeaders(headers, strlen(headers)))); } class EmptyURLRequestDelegate : public net::URLRequest::Delegate { void OnResponseStarted(net::URLRequest* request, int net_error) override {} void OnReadCompleted(net::URLRequest* request, int bytes_read) override {} }; class MockURLRequestJob : public net::URLRequestJob { public: MockURLRequestJob(net::URLRequest* request, const net::HttpResponseInfo& response_info, const std::string& mime_type) : net::URLRequestJob(request, nullptr), response_info_(response_info), mime_type_(mime_type) {} bool GetMimeType(std::string* mime_type) const override { *mime_type = mime_type_; return true; } protected: void Start() override { NotifyHeadersComplete(); } int GetResponseCode() const override { return 200; } void GetResponseInfo(net::HttpResponseInfo* info) override { *info = response_info_; } private: net::HttpResponseInfo response_info_; std::string mime_type_; }; class MockURLRequestJobFactory : public net::URLRequestJobFactory { public: MockURLRequestJobFactory() {} ~MockURLRequestJobFactory() override {} net::URLRequestJob* MaybeCreateJobWithProtocolHandler( const std::string& scheme, net::URLRequest* request, net::NetworkDelegate* network_delegate) const override { return new MockURLRequestJob(request, response_info_, mime_type_); } net::URLRequestJob* MaybeInterceptRedirect( net::URLRequest* request, net::NetworkDelegate* network_delegate, const GURL& location) const override { return nullptr; } net::URLRequestJob* MaybeInterceptResponse( net::URLRequest* request, net::NetworkDelegate* network_delegate) const override { return nullptr; } bool IsHandledProtocol(const std::string& scheme) const override { return true; } bool IsHandledURL(const GURL& url) const override { return true; } bool IsSafeRedirectTarget(const GURL& location) const override { return true; } void set_response_info(const net::HttpResponseInfo& response_info) { response_info_ = response_info; } void set_mime_type(const std::string& mime_type) { mime_type_ = mime_type; } private: net::HttpResponseInfo response_info_; std::string mime_type_; }; class MockResourcePrefetchPredictorTables : public ResourcePrefetchPredictorTables { public: MockResourcePrefetchPredictorTables() { } MOCK_METHOD4(GetAllData, void(PrefetchDataMap* url_data_map, PrefetchDataMap* host_data_map, RedirectDataMap* url_redirect_data_map, RedirectDataMap* host_redirect_data_map)); MOCK_METHOD4(UpdateData, void(const PrefetchData& url_data, const PrefetchData& host_data, const RedirectData& url_redirect_data, const RedirectData& host_redirect_data)); MOCK_METHOD2(DeleteResourceData, void(const std::vector<std::string>& urls, const std::vector<std::string>& hosts)); MOCK_METHOD2(DeleteSingleResourceDataPoint, void(const std::string& key, PrefetchKeyType key_type)); MOCK_METHOD2(DeleteRedirectData, void(const std::vector<std::string>& urls, const std::vector<std::string>& hosts)); MOCK_METHOD2(DeleteSingleRedirectDataPoint, void(const std::string& key, PrefetchKeyType key_type)); MOCK_METHOD0(DeleteAllData, void()); protected: ~MockResourcePrefetchPredictorTables() { } }; class MockResourcePrefetchPredictorObserver : public TestObserver { public: explicit MockResourcePrefetchPredictorObserver( ResourcePrefetchPredictor* predictor) : TestObserver(predictor) {} MOCK_METHOD2( OnNavigationLearned, void(size_t url_visit_count, const ResourcePrefetchPredictor::PageRequestSummary& summary)); }; class ResourcePrefetchPredictorTest : public testing::Test { public: ResourcePrefetchPredictorTest(); ~ResourcePrefetchPredictorTest() override; void SetUp() override; void TearDown() override; protected: void AddUrlToHistory(const std::string& url, int visit_count) { HistoryServiceFactory::GetForProfile(profile_.get(), ServiceAccessType::EXPLICIT_ACCESS)-> AddPageWithDetails( GURL(url), base::string16(), visit_count, 0, base::Time::Now(), false, history::SOURCE_BROWSED); profile_->BlockUntilHistoryProcessesPendingRequests(); } URLRequestSummary CreateRedirectRequestSummary( int process_id, int render_frame_id, const std::string& main_frame_url, const std::string& redirect_url) { URLRequestSummary summary = CreateURLRequestSummary(process_id, render_frame_id, main_frame_url); summary.redirect_url = GURL(redirect_url); return summary; } std::unique_ptr<net::URLRequest> CreateURLRequest( const GURL& url, net::RequestPriority priority, content::ResourceType resource_type, int render_process_id, int render_frame_id, bool is_main_frame) { std::unique_ptr<net::URLRequest> request = url_request_context_.CreateRequest(url, priority, &url_request_delegate_); request->set_first_party_for_cookies(url); content::ResourceRequestInfo::AllocateForTesting( request.get(), resource_type, nullptr, render_process_id, -1, render_frame_id, is_main_frame, false, false, true, false); request->Start(); return request; } void InitializePredictor() { predictor_->StartInitialization(); base::RunLoop loop; loop.RunUntilIdle(); // Runs the DB lookup. profile_->BlockUntilHistoryProcessesPendingRequests(); } bool URLRequestSummaryAreEqual(const URLRequestSummary& lhs, const URLRequestSummary& rhs) { return lhs.navigation_id == rhs.navigation_id && lhs.resource_url == rhs.resource_url && lhs.resource_type == rhs.resource_type && lhs.mime_type == rhs.mime_type && lhs.was_cached == rhs.was_cached; } void ResetPredictor() { ResourcePrefetchPredictorConfig config; config.max_urls_to_track = 3; config.max_hosts_to_track = 2; config.min_url_visit_count = 2; config.max_resources_per_entry = 4; config.max_consecutive_misses = 2; config.min_resource_confidence_to_trigger_prefetch = 0.5; // TODO(shishir): Enable the prefetching mode in the tests. config.mode |= ResourcePrefetchPredictorConfig::URL_LEARNING; config.mode |= ResourcePrefetchPredictorConfig::HOST_LEARNING; predictor_.reset(new ResourcePrefetchPredictor(config, profile_.get())); predictor_->set_mock_tables(mock_tables_); } void InitializeSampleData(); content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<TestingProfile> profile_; net::TestURLRequestContext url_request_context_; std::unique_ptr<ResourcePrefetchPredictor> predictor_; scoped_refptr<StrictMock<MockResourcePrefetchPredictorTables> > mock_tables_; PrefetchDataMap test_url_data_; PrefetchDataMap test_host_data_; RedirectDataMap test_url_redirect_data_; RedirectDataMap test_host_redirect_data_; PrefetchData empty_resource_data_; RedirectData empty_redirect_data_; MockURLRequestJobFactory url_request_job_factory_; EmptyURLRequestDelegate url_request_delegate_; }; ResourcePrefetchPredictorTest::ResourcePrefetchPredictorTest() : thread_bundle_(), profile_(new TestingProfile()), mock_tables_(new StrictMock<MockResourcePrefetchPredictorTables>()), empty_resource_data_(), empty_redirect_data_() {} ResourcePrefetchPredictorTest::~ResourcePrefetchPredictorTest() { profile_.reset(NULL); base::RunLoop().RunUntilIdle(); } void ResourcePrefetchPredictorTest::SetUp() { InitializeSampleData(); ASSERT_TRUE(profile_->CreateHistoryService(true, false)); profile_->BlockUntilHistoryProcessesPendingRequests(); EXPECT_TRUE(HistoryServiceFactory::GetForProfile( profile_.get(), ServiceAccessType::EXPLICIT_ACCESS)); // Initialize the predictor with empty data. ResetPredictor(); EXPECT_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::NOT_INITIALIZED); EXPECT_CALL(*mock_tables_.get(), GetAllData(Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(RedirectDataMap())), Pointee(ContainerEq(RedirectDataMap())))); InitializePredictor(); EXPECT_TRUE(predictor_->inflight_navigations_.empty()); EXPECT_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::INITIALIZED); url_request_context_.set_job_factory(&url_request_job_factory_); } void ResourcePrefetchPredictorTest::TearDown() { predictor_.reset(NULL); profile_->DestroyHistoryService(); } void ResourcePrefetchPredictorTest::InitializeSampleData() { { // Url data. PrefetchData google = CreatePrefetchData("http://www.google.com/", 1); InitializeResourceData(google.add_resources(), "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 3, 2, 1, 1.0, net::MEDIUM, false, false); InitializeResourceData( google.add_resources(), "http://google.com/script3.js", content::RESOURCE_TYPE_SCRIPT, 4, 0, 1, 2.1, net::MEDIUM, false, false); InitializeResourceData(google.add_resources(), "http://google.com/script4.js", content::RESOURCE_TYPE_SCRIPT, 11, 0, 0, 2.1, net::MEDIUM, false, false); InitializeResourceData( google.add_resources(), "http://google.com/image1.png", content::RESOURCE_TYPE_IMAGE, 6, 3, 0, 2.2, net::MEDIUM, false, false); InitializeResourceData(google.add_resources(), "http://google.com/a.font", content::RESOURCE_TYPE_LAST_TYPE, 2, 0, 0, 5.1, net::MEDIUM, false, false); PrefetchData reddit = CreatePrefetchData("http://www.reddit.com/", 2); InitializeResourceData( reddit.add_resources(), "http://reddit-resource.com/script1.js", content::RESOURCE_TYPE_SCRIPT, 4, 0, 1, 1.0, net::MEDIUM, false, false); InitializeResourceData( reddit.add_resources(), "http://reddit-resource.com/script2.js", content::RESOURCE_TYPE_SCRIPT, 2, 0, 0, 2.1, net::MEDIUM, false, false); PrefetchData yahoo = CreatePrefetchData("http://www.yahoo.com/", 3); InitializeResourceData(yahoo.add_resources(), "http://google.com/image.png", content::RESOURCE_TYPE_IMAGE, 20, 1, 0, 10.0, net::MEDIUM, false, false); test_url_data_.clear(); test_url_data_.insert(std::make_pair(google.primary_key(), google)); test_url_data_.insert(std::make_pair(reddit.primary_key(), reddit)); test_url_data_.insert(std::make_pair(yahoo.primary_key(), yahoo)); } { // Host data. PrefetchData facebook = CreatePrefetchData("www.facebook.com", 4); InitializeResourceData(facebook.add_resources(), "http://www.facebook.com/style.css", content::RESOURCE_TYPE_STYLESHEET, 5, 2, 1, 1.1, net::MEDIUM, false, false); InitializeResourceData( facebook.add_resources(), "http://www.facebook.com/script.js", content::RESOURCE_TYPE_SCRIPT, 4, 0, 1, 2.1, net::MEDIUM, false, false); InitializeResourceData( facebook.add_resources(), "http://www.facebook.com/image.png", content::RESOURCE_TYPE_IMAGE, 6, 3, 0, 2.2, net::MEDIUM, false, false); InitializeResourceData(facebook.add_resources(), "http://www.facebook.com/a.font", content::RESOURCE_TYPE_LAST_TYPE, 2, 0, 0, 5.1, net::MEDIUM, false, false); InitializeResourceData(facebook.add_resources(), "http://www.resources.facebook.com/script.js", content::RESOURCE_TYPE_SCRIPT, 11, 0, 0, 8.5, net::MEDIUM, false, false); PrefetchData yahoo = CreatePrefetchData("www.yahoo.com", 5); InitializeResourceData(yahoo.add_resources(), "http://google.com/image.png", content::RESOURCE_TYPE_IMAGE, 20, 1, 0, 10.0, net::MEDIUM, false, false); test_host_data_.clear(); test_host_data_.insert(std::make_pair(facebook.primary_key(), facebook)); test_host_data_.insert(std::make_pair(yahoo.primary_key(), yahoo)); } { // Url redirect data. RedirectData facebook = CreateRedirectData("http://fb.com/google", 6); InitializeRedirectStat(facebook.add_redirect_endpoints(), "https://facebook.com/google", 5, 1, 0); InitializeRedirectStat(facebook.add_redirect_endpoints(), "https://facebook.com/login", 3, 5, 1); RedirectData nytimes = CreateRedirectData("http://nyt.com", 7); InitializeRedirectStat(nytimes.add_redirect_endpoints(), "https://nytimes.com", 2, 0, 0); RedirectData google = CreateRedirectData("http://google.com", 8); InitializeRedirectStat(google.add_redirect_endpoints(), "https://google.com", 3, 0, 0); test_url_redirect_data_.clear(); test_url_redirect_data_.insert( std::make_pair(facebook.primary_key(), facebook)); test_url_redirect_data_.insert( std::make_pair(nytimes.primary_key(), nytimes)); test_url_redirect_data_.insert( std::make_pair(google.primary_key(), google)); } { // Host redirect data. RedirectData bbc = CreateRedirectData("bbc.com", 9); InitializeRedirectStat(bbc.add_redirect_endpoints(), "www.bbc.com", 8, 4, 1); InitializeRedirectStat(bbc.add_redirect_endpoints(), "m.bbc.com", 5, 8, 0); InitializeRedirectStat(bbc.add_redirect_endpoints(), "bbc.co.uk", 1, 3, 0); RedirectData microsoft = CreateRedirectData("microsoft.com", 10); InitializeRedirectStat(microsoft.add_redirect_endpoints(), "www.microsoft.com", 10, 0, 0); test_host_redirect_data_.clear(); test_host_redirect_data_.insert(std::make_pair(bbc.primary_key(), bbc)); test_host_redirect_data_.insert( std::make_pair(microsoft.primary_key(), microsoft)); } } // Confirm that there's been no shift in the // ResourceData_Priority/net::RequestPriority equivalence. static_assert(static_cast<int>(net::MINIMUM_PRIORITY) == static_cast<int>( ResourceData_Priority_REQUEST_PRIORITY_THROTTLED), "Database/Net priority mismatch: Minimum"); static_assert(static_cast<int>(net::MAXIMUM_PRIORITY) == static_cast<int>(ResourceData_Priority_REQUEST_PRIORITY_HIGHEST), "Database/Net priority mismatch: Maximum"); // Tests that the predictor initializes correctly without any data. TEST_F(ResourcePrefetchPredictorTest, LazilyInitializeEmpty) { EXPECT_TRUE(predictor_->url_table_cache_->empty()); EXPECT_TRUE(predictor_->host_table_cache_->empty()); EXPECT_TRUE(predictor_->url_redirect_table_cache_->empty()); EXPECT_TRUE(predictor_->host_redirect_table_cache_->empty()); } // Tests that the history and the db tables data are loaded correctly. TEST_F(ResourcePrefetchPredictorTest, LazilyInitializeWithData) { AddUrlToHistory("http://www.google.com/", 4); AddUrlToHistory("http://www.yahoo.com/", 2); EXPECT_CALL(*mock_tables_.get(), GetAllData(Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(RedirectDataMap())), Pointee(ContainerEq(RedirectDataMap())))) .WillOnce(DoAll(SetArgPointee<0>(test_url_data_), SetArgPointee<1>(test_host_data_), SetArgPointee<2>(test_url_redirect_data_), SetArgPointee<3>(test_host_redirect_data_))); ResetPredictor(); InitializePredictor(); // Test that the internal variables correctly initialized. EXPECT_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::INITIALIZED); EXPECT_TRUE(predictor_->inflight_navigations_.empty()); EXPECT_EQ(test_url_data_, *predictor_->url_table_cache_); EXPECT_EQ(test_host_data_, *predictor_->host_table_cache_); EXPECT_EQ(test_url_redirect_data_, *predictor_->url_redirect_table_cache_); EXPECT_EQ(test_host_redirect_data_, *predictor_->host_redirect_table_cache_); } // Single navigation but history count is low, so should not record. TEST_F(ResourcePrefetchPredictorTest, NavigationNotRecorded) { const int kVisitCount = 1; AddUrlToHistory("https://www.google.com", kVisitCount); URLRequestSummary main_frame = CreateURLRequestSummary(1, 1, "http://www.google.com"); predictor_->RecordURLRequest(main_frame); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); URLRequestSummary main_frame_redirect = CreateRedirectRequestSummary( 1, 1, "http://www.google.com", "https://www.google.com"); predictor_->RecordURLRedirect(main_frame_redirect); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); main_frame = CreateURLRequestSummary(1, 1, "https://www.google.com"); // Now add a few subresources. URLRequestSummary resource1 = CreateURLRequestSummary( 1, 1, "https://www.google.com", "https://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", false); predictor_->RecordURLResponse(resource1); URLRequestSummary resource2 = CreateURLRequestSummary( 1, 1, "https://www.google.com", "https://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false); predictor_->RecordURLResponse(resource2); URLRequestSummary resource3 = CreateURLRequestSummary( 1, 1, "https://www.google.com", "https://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false); predictor_->RecordURLResponse(resource3); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer( predictor_.get()); EXPECT_CALL( mock_observer, OnNavigationLearned(kVisitCount, CreatePageRequestSummary( "https://www.google.com", "http://www.google.com", {resource1, resource2, resource3}))); PrefetchData host_data = CreatePrefetchData("www.google.com"); InitializeResourceData(host_data.add_resources(), "https://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 1, 0, 0, 1.0, net::MEDIUM, false, false); InitializeResourceData( host_data.add_resources(), "https://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 2.0, net::MEDIUM, false, false); InitializeResourceData( host_data.add_resources(), "https://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 3.0, net::MEDIUM, false, false); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, host_data, empty_redirect_data_, empty_redirect_data_)); predictor_->RecordMainFrameLoadComplete(main_frame.navigation_id); profile_->BlockUntilHistoryProcessesPendingRequests(); } // Single navigation that will be recorded. Will check for duplicate // resources and also for number of resources saved. TEST_F(ResourcePrefetchPredictorTest, NavigationUrlNotInDB) { const int kVisitCount = 4; AddUrlToHistory("http://www.google.com", kVisitCount); URLRequestSummary main_frame = CreateURLRequestSummary(1, 1, "http://www.google.com"); predictor_->RecordURLRequest(main_frame); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); std::vector<URLRequestSummary> resources; resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", true)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/image1.png", content::RESOURCE_TYPE_IMAGE, net::MEDIUM, "image/png", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/image2.png", content::RESOURCE_TYPE_IMAGE, net::MEDIUM, "image/png", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/style2.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", true)); predictor_->RecordURLResponse(resources.back()); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer( predictor_.get()); EXPECT_CALL(mock_observer, OnNavigationLearned( kVisitCount, CreatePageRequestSummary("http://www.google.com", "http://www.google.com", resources))); PrefetchData url_data = CreatePrefetchData("http://www.google.com/"); InitializeResourceData(url_data.add_resources(), "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 1, 0, 0, 1.0, net::MEDIUM, false, false); InitializeResourceData( url_data.add_resources(), "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 2.0, net::MEDIUM, false, false); InitializeResourceData( url_data.add_resources(), "http://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 3.0, net::MEDIUM, false, false); InitializeResourceData(url_data.add_resources(), "http://google.com/style2.css", content::RESOURCE_TYPE_STYLESHEET, 1, 0, 0, 7.0, net::MEDIUM, false, false); EXPECT_CALL(*mock_tables_.get(), UpdateData(url_data, empty_resource_data_, empty_redirect_data_, empty_redirect_data_)); PrefetchData host_data = CreatePrefetchData("www.google.com"); host_data.mutable_resources()->CopyFrom(url_data.resources()); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, host_data, empty_redirect_data_, empty_redirect_data_)); predictor_->RecordMainFrameLoadComplete(main_frame.navigation_id); profile_->BlockUntilHistoryProcessesPendingRequests(); } // Tests that navigation is recorded correctly for URL already present in // the database cache. TEST_F(ResourcePrefetchPredictorTest, NavigationUrlInDB) { const int kVisitCount = 4; AddUrlToHistory("http://www.google.com", kVisitCount); EXPECT_CALL(*mock_tables_.get(), GetAllData(Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(RedirectDataMap())), Pointee(ContainerEq(RedirectDataMap())))) .WillOnce(DoAll(SetArgPointee<0>(test_url_data_), SetArgPointee<1>(test_host_data_))); ResetPredictor(); InitializePredictor(); EXPECT_EQ(3U, predictor_->url_table_cache_->size()); EXPECT_EQ(2U, predictor_->host_table_cache_->size()); URLRequestSummary main_frame = CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://www.google.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); predictor_->RecordURLRequest(main_frame); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); std::vector<URLRequestSummary> resources; resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", true)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/image1.png", content::RESOURCE_TYPE_IMAGE, net::MEDIUM, "image/png", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/image2.png", content::RESOURCE_TYPE_IMAGE, net::MEDIUM, "image/png", false)); predictor_->RecordURLResponse(resources.back()); resources.push_back(CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/style2.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", true)); predictor_->RecordURLResponse(resources.back()); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer( predictor_.get()); EXPECT_CALL(mock_observer, OnNavigationLearned( kVisitCount, CreatePageRequestSummary("http://www.google.com", "http://www.google.com", resources))); PrefetchData url_data = CreatePrefetchData("http://www.google.com/"); InitializeResourceData(url_data.add_resources(), "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 4, 2, 0, 1.0, net::MEDIUM, false, false); InitializeResourceData( url_data.add_resources(), "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 2.0, net::MEDIUM, false, false); InitializeResourceData( url_data.add_resources(), "http://google.com/script4.js", content::RESOURCE_TYPE_SCRIPT, 11, 1, 1, 2.1, net::MEDIUM, false, false); InitializeResourceData( url_data.add_resources(), "http://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 3.0, net::MEDIUM, false, false); EXPECT_CALL(*mock_tables_.get(), UpdateData(url_data, empty_resource_data_, empty_redirect_data_, empty_redirect_data_)); EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint("www.facebook.com", PREFETCH_KEY_TYPE_HOST)); PrefetchData host_data = CreatePrefetchData("www.google.com"); InitializeResourceData(host_data.add_resources(), "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 1, 0, 0, 1.0, net::MEDIUM, false, false); InitializeResourceData( host_data.add_resources(), "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 2.0, net::MEDIUM, false, false); InitializeResourceData( host_data.add_resources(), "http://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 0, 3.0, net::MEDIUM, false, false); InitializeResourceData(host_data.add_resources(), "http://google.com/style2.css", content::RESOURCE_TYPE_STYLESHEET, 1, 0, 0, 7.0, net::MEDIUM, false, false); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, host_data, empty_redirect_data_, empty_redirect_data_)); predictor_->RecordMainFrameLoadComplete(main_frame.navigation_id); profile_->BlockUntilHistoryProcessesPendingRequests(); } // Tests that a URL is deleted before another is added if the cache is full. TEST_F(ResourcePrefetchPredictorTest, NavigationUrlNotInDBAndDBFull) { const int kVisitCount = 4; AddUrlToHistory("http://www.nike.com/", kVisitCount); EXPECT_CALL(*mock_tables_.get(), GetAllData(Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(RedirectDataMap())), Pointee(ContainerEq(RedirectDataMap())))) .WillOnce(DoAll(SetArgPointee<0>(test_url_data_), SetArgPointee<1>(test_host_data_))); ResetPredictor(); InitializePredictor(); EXPECT_EQ(3U, predictor_->url_table_cache_->size()); EXPECT_EQ(2U, predictor_->host_table_cache_->size()); URLRequestSummary main_frame = CreateURLRequestSummary( 1, 1, "http://www.nike.com", "http://www.nike.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); predictor_->RecordURLRequest(main_frame); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); URLRequestSummary resource1 = CreateURLRequestSummary( 1, 1, "http://www.nike.com", "http://nike.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", false); predictor_->RecordURLResponse(resource1); URLRequestSummary resource2 = CreateURLRequestSummary( 1, 1, "http://www.nike.com", "http://nike.com/image2.png", content::RESOURCE_TYPE_IMAGE, net::MEDIUM, "image/png", false); predictor_->RecordURLResponse(resource2); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer( predictor_.get()); EXPECT_CALL(mock_observer, OnNavigationLearned( kVisitCount, CreatePageRequestSummary( "http://www.nike.com", "http://www.nike.com", {resource1, resource2}))); EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint("http://www.google.com/", PREFETCH_KEY_TYPE_URL)); EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint("www.facebook.com", PREFETCH_KEY_TYPE_HOST)); PrefetchData url_data = CreatePrefetchData("http://www.nike.com/"); InitializeResourceData(url_data.add_resources(), "http://nike.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 1, 0, 0, 1.0, net::MEDIUM, false, false); InitializeResourceData(url_data.add_resources(), "http://nike.com/image2.png", content::RESOURCE_TYPE_IMAGE, 1, 0, 0, 2.0, net::MEDIUM, false, false); EXPECT_CALL(*mock_tables_.get(), UpdateData(url_data, empty_resource_data_, empty_redirect_data_, empty_redirect_data_)); PrefetchData host_data = CreatePrefetchData("www.nike.com"); host_data.mutable_resources()->CopyFrom(url_data.resources()); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, host_data, empty_redirect_data_, empty_redirect_data_)); predictor_->RecordMainFrameLoadComplete(main_frame.navigation_id); profile_->BlockUntilHistoryProcessesPendingRequests(); } TEST_F(ResourcePrefetchPredictorTest, RedirectUrlNotInDB) { const int kVisitCount = 4; AddUrlToHistory("https://facebook.com/google", kVisitCount); URLRequestSummary fb1 = CreateURLRequestSummary(1, 1, "http://fb.com/google"); predictor_->RecordURLRequest(fb1); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); URLRequestSummary fb2 = CreateRedirectRequestSummary( 1, 1, "http://fb.com/google", "http://facebook.com/google"); predictor_->RecordURLRedirect(fb2); URLRequestSummary fb3 = CreateRedirectRequestSummary( 1, 1, "http://facebook.com/google", "https://facebook.com/google"); predictor_->RecordURLRedirect(fb3); NavigationID fb_end = CreateNavigationID(1, 1, "https://facebook.com/google"); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer( predictor_.get()); EXPECT_CALL( mock_observer, OnNavigationLearned(kVisitCount, CreatePageRequestSummary( "https://facebook.com/google", "http://fb.com/google", std::vector<URLRequestSummary>()))); // Since the navigation hasn't resources, corresponding entry // in resource table will be deleted. EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint("https://facebook.com/google", PREFETCH_KEY_TYPE_URL)); EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint( "facebook.com", PREFETCH_KEY_TYPE_HOST)); RedirectData url_redirect_data = CreateRedirectData("http://fb.com/google"); InitializeRedirectStat(url_redirect_data.add_redirect_endpoints(), "https://facebook.com/google", 1, 0, 0); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, empty_resource_data_, url_redirect_data, empty_redirect_data_)); RedirectData host_redirect_data = CreateRedirectData("fb.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), "facebook.com", 1, 0, 0); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, empty_resource_data_, empty_redirect_data_, host_redirect_data)); predictor_->RecordMainFrameLoadComplete(fb_end); profile_->BlockUntilHistoryProcessesPendingRequests(); } // Tests that redirect is recorded correctly for URL already present in // the database cache. TEST_F(ResourcePrefetchPredictorTest, RedirectUrlInDB) { const int kVisitCount = 7; AddUrlToHistory("https://facebook.com/google", kVisitCount); EXPECT_CALL(*mock_tables_.get(), GetAllData(Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(PrefetchDataMap())), Pointee(ContainerEq(RedirectDataMap())), Pointee(ContainerEq(RedirectDataMap())))) .WillOnce(DoAll(SetArgPointee<2>(test_url_redirect_data_), SetArgPointee<3>(test_host_redirect_data_))); ResetPredictor(); InitializePredictor(); EXPECT_EQ(3U, predictor_->url_redirect_table_cache_->size()); EXPECT_EQ(2U, predictor_->host_redirect_table_cache_->size()); URLRequestSummary fb1 = CreateURLRequestSummary(1, 1, "http://fb.com/google"); predictor_->RecordURLRequest(fb1); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); URLRequestSummary fb2 = CreateRedirectRequestSummary( 1, 1, "http://fb.com/google", "http://facebook.com/google"); predictor_->RecordURLRedirect(fb2); URLRequestSummary fb3 = CreateRedirectRequestSummary( 1, 1, "http://facebook.com/google", "https://facebook.com/google"); predictor_->RecordURLRedirect(fb3); NavigationID fb_end = CreateNavigationID(1, 1, "https://facebook.com/google"); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer( predictor_.get()); EXPECT_CALL( mock_observer, OnNavigationLearned(kVisitCount, CreatePageRequestSummary( "https://facebook.com/google", "http://fb.com/google", std::vector<URLRequestSummary>()))); // Oldest entries in tables will be superseded and deleted. EXPECT_CALL(*mock_tables_.get(), DeleteSingleRedirectDataPoint("bbc.com", PREFETCH_KEY_TYPE_HOST)); // Since the navigation hasn't resources, corresponding entry // in resource table will be deleted. EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint("https://facebook.com/google", PREFETCH_KEY_TYPE_URL)); EXPECT_CALL(*mock_tables_.get(), DeleteSingleResourceDataPoint( "facebook.com", PREFETCH_KEY_TYPE_HOST)); RedirectData url_redirect_data = CreateRedirectData("http://fb.com/google"); InitializeRedirectStat(url_redirect_data.add_redirect_endpoints(), "https://facebook.com/google", 6, 1, 0); // Existing redirect to https://facebook.com/login will be deleted because of // too many consecutive misses. EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, empty_resource_data_, url_redirect_data, empty_redirect_data_)); RedirectData host_redirect_data = CreateRedirectData("fb.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), "facebook.com", 1, 0, 0); EXPECT_CALL(*mock_tables_.get(), UpdateData(empty_resource_data_, empty_resource_data_, empty_redirect_data_, host_redirect_data)); predictor_->RecordMainFrameLoadComplete(fb_end); profile_->BlockUntilHistoryProcessesPendingRequests(); } TEST_F(ResourcePrefetchPredictorTest, DeleteUrls) { // Add some dummy entries to cache. predictor_->url_table_cache_->insert( std::make_pair("http://www.google.com/page1.html", CreatePrefetchData("http://www.google.com/page1.html"))); predictor_->url_table_cache_->insert( std::make_pair("http://www.google.com/page2.html", CreatePrefetchData("http://www.google.com/page2.html"))); predictor_->url_table_cache_->insert(std::make_pair( "http://www.yahoo.com/", CreatePrefetchData("http://www.yahoo.com/"))); predictor_->url_table_cache_->insert(std::make_pair( "http://www.apple.com/", CreatePrefetchData("http://www.apple.com/"))); predictor_->url_table_cache_->insert(std::make_pair( "http://www.nike.com/", CreatePrefetchData("http://www.nike.com/"))); predictor_->host_table_cache_->insert( std::make_pair("www.google.com", CreatePrefetchData("www.google.com"))); predictor_->host_table_cache_->insert( std::make_pair("www.yahoo.com", CreatePrefetchData("www.yahoo.com"))); predictor_->host_table_cache_->insert( std::make_pair("www.apple.com", CreatePrefetchData("www.apple.com"))); predictor_->url_redirect_table_cache_->insert( std::make_pair("http://www.google.com/page1.html", CreateRedirectData("http://www.google.com/page1.html"))); predictor_->url_redirect_table_cache_->insert( std::make_pair("http://www.google.com/page2.html", CreateRedirectData("http://www.google.com/page2.html"))); predictor_->url_redirect_table_cache_->insert(std::make_pair( "http://www.apple.com/", CreateRedirectData("http://www.apple.com/"))); predictor_->url_redirect_table_cache_->insert( std::make_pair("http://nyt.com/", CreateRedirectData("http://nyt.com/"))); predictor_->host_redirect_table_cache_->insert( std::make_pair("www.google.com", CreateRedirectData("www.google.com"))); predictor_->host_redirect_table_cache_->insert( std::make_pair("www.nike.com", CreateRedirectData("www.nike.com"))); predictor_->host_redirect_table_cache_->insert(std::make_pair( "www.wikipedia.org", CreateRedirectData("www.wikipedia.org"))); history::URLRows rows; rows.push_back(history::URLRow(GURL("http://www.google.com/page2.html"))); rows.push_back(history::URLRow(GURL("http://www.apple.com"))); rows.push_back(history::URLRow(GURL("http://www.nike.com"))); std::vector<std::string> urls_to_delete, hosts_to_delete, url_redirects_to_delete, host_redirects_to_delete; urls_to_delete.push_back("http://www.google.com/page2.html"); urls_to_delete.push_back("http://www.apple.com/"); urls_to_delete.push_back("http://www.nike.com/"); hosts_to_delete.push_back("www.google.com"); hosts_to_delete.push_back("www.apple.com"); url_redirects_to_delete.push_back("http://www.google.com/page2.html"); url_redirects_to_delete.push_back("http://www.apple.com/"); host_redirects_to_delete.push_back("www.google.com"); host_redirects_to_delete.push_back("www.nike.com"); EXPECT_CALL(*mock_tables_.get(), DeleteResourceData(ContainerEq(urls_to_delete), ContainerEq(hosts_to_delete))); EXPECT_CALL(*mock_tables_.get(), DeleteRedirectData(ContainerEq(url_redirects_to_delete), ContainerEq(host_redirects_to_delete))); predictor_->DeleteUrls(rows); EXPECT_EQ(2U, predictor_->url_table_cache_->size()); EXPECT_EQ(1U, predictor_->host_table_cache_->size()); EXPECT_EQ(2U, predictor_->url_redirect_table_cache_->size()); EXPECT_EQ(1U, predictor_->host_redirect_table_cache_->size()); EXPECT_CALL(*mock_tables_.get(), DeleteAllData()); predictor_->DeleteAllUrls(); EXPECT_TRUE(predictor_->url_table_cache_->empty()); EXPECT_TRUE(predictor_->host_table_cache_->empty()); EXPECT_TRUE(predictor_->url_redirect_table_cache_->empty()); EXPECT_TRUE(predictor_->host_redirect_table_cache_->empty()); } TEST_F(ResourcePrefetchPredictorTest, OnMainFrameRequest) { URLRequestSummary summary1 = CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://www.google.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); URLRequestSummary summary2 = CreateURLRequestSummary( 1, 2, "http://www.google.com", "http://www.google.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); URLRequestSummary summary3 = CreateURLRequestSummary( 2, 1, "http://www.yahoo.com", "http://www.yahoo.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); predictor_->OnMainFrameRequest(summary1); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); predictor_->OnMainFrameRequest(summary2); EXPECT_EQ(2U, predictor_->inflight_navigations_.size()); predictor_->OnMainFrameRequest(summary3); EXPECT_EQ(3U, predictor_->inflight_navigations_.size()); // Insert another with same navigation id. It should replace. URLRequestSummary summary4 = CreateURLRequestSummary( 1, 1, "http://www.nike.com", "http://www.nike.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); URLRequestSummary summary5 = CreateURLRequestSummary( 1, 2, "http://www.google.com", "http://www.google.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); predictor_->OnMainFrameRequest(summary4); EXPECT_EQ(3U, predictor_->inflight_navigations_.size()); // Change this creation time so that it will go away on the next insert. summary5.navigation_id.creation_time = base::TimeTicks::Now() - base::TimeDelta::FromDays(1); predictor_->OnMainFrameRequest(summary5); EXPECT_EQ(3U, predictor_->inflight_navigations_.size()); URLRequestSummary summary6 = CreateURLRequestSummary( 3, 1, "http://www.shoes.com", "http://www.shoes.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); predictor_->OnMainFrameRequest(summary6); EXPECT_EQ(3U, predictor_->inflight_navigations_.size()); EXPECT_TRUE(predictor_->inflight_navigations_.find(summary3.navigation_id) != predictor_->inflight_navigations_.end()); EXPECT_TRUE(predictor_->inflight_navigations_.find(summary4.navigation_id) != predictor_->inflight_navigations_.end()); EXPECT_TRUE(predictor_->inflight_navigations_.find(summary6.navigation_id) != predictor_->inflight_navigations_.end()); } TEST_F(ResourcePrefetchPredictorTest, OnMainFrameRedirect) { URLRequestSummary yahoo = CreateURLRequestSummary(1, 1, "http://yahoo.com"); URLRequestSummary bbc1 = CreateURLRequestSummary(2, 2, "http://bbc.com"); URLRequestSummary bbc2 = CreateRedirectRequestSummary(2, 2, "http://bbc.com", "https://www.bbc.com"); NavigationID bbc_end = CreateNavigationID(2, 2, "https://www.bbc.com"); URLRequestSummary youtube1 = CreateURLRequestSummary(1, 2, "http://youtube.com"); URLRequestSummary youtube2 = CreateRedirectRequestSummary( 1, 2, "http://youtube.com", "https://youtube.com"); NavigationID youtube_end = CreateNavigationID(1, 2, "https://youtube.com"); URLRequestSummary nyt1 = CreateURLRequestSummary(2, 1, "http://nyt.com"); URLRequestSummary nyt2 = CreateRedirectRequestSummary(2, 1, "http://nyt.com", "http://nytimes.com"); URLRequestSummary nyt3 = CreateRedirectRequestSummary( 2, 1, "http://nytimes.com", "http://m.nytimes.com"); NavigationID nyt_end = CreateNavigationID(2, 1, "http://m.nytimes.com"); URLRequestSummary fb1 = CreateURLRequestSummary(1, 3, "http://fb.com"); URLRequestSummary fb2 = CreateRedirectRequestSummary(1, 3, "http://fb.com", "http://facebook.com"); URLRequestSummary fb3 = CreateRedirectRequestSummary( 1, 3, "http://facebook.com", "https://facebook.com"); URLRequestSummary fb4 = CreateRedirectRequestSummary( 1, 3, "https://facebook.com", "https://m.facebook.com/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&_rdr"); NavigationID fb_end = CreateNavigationID( 1, 3, "https://m.facebook.com/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&_rdr"); // Redirect with empty redirect_url will be deleted. predictor_->OnMainFrameRequest(yahoo); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); predictor_->OnMainFrameRedirect(yahoo); EXPECT_TRUE(predictor_->inflight_navigations_.empty()); // Redirect without previous request works fine. // predictor_->OnMainFrameRequest(bbc1) missing. predictor_->OnMainFrameRedirect(bbc2); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); EXPECT_EQ(bbc1.navigation_id.main_frame_url, predictor_->inflight_navigations_[bbc_end]->initial_url); // http://youtube.com -> https://youtube.com. predictor_->OnMainFrameRequest(youtube1); EXPECT_EQ(2U, predictor_->inflight_navigations_.size()); predictor_->OnMainFrameRedirect(youtube2); EXPECT_EQ(2U, predictor_->inflight_navigations_.size()); EXPECT_EQ(youtube1.navigation_id.main_frame_url, predictor_->inflight_navigations_[youtube_end]->initial_url); // http://nyt.com -> http://nytimes.com -> http://m.nytimes.com. predictor_->OnMainFrameRequest(nyt1); EXPECT_EQ(3U, predictor_->inflight_navigations_.size()); predictor_->OnMainFrameRedirect(nyt2); predictor_->OnMainFrameRedirect(nyt3); EXPECT_EQ(3U, predictor_->inflight_navigations_.size()); EXPECT_EQ(nyt1.navigation_id.main_frame_url, predictor_->inflight_navigations_[nyt_end]->initial_url); // http://fb.com -> http://facebook.com -> https://facebook.com -> // https://m.facebook.com/?refsrc=https%3A%2F%2Fwww.facebook.com%2F&_rdr. predictor_->OnMainFrameRequest(fb1); EXPECT_EQ(4U, predictor_->inflight_navigations_.size()); predictor_->OnMainFrameRedirect(fb2); predictor_->OnMainFrameRedirect(fb3); predictor_->OnMainFrameRedirect(fb4); EXPECT_EQ(4U, predictor_->inflight_navigations_.size()); EXPECT_EQ(fb1.navigation_id.main_frame_url, predictor_->inflight_navigations_[fb_end]->initial_url); } TEST_F(ResourcePrefetchPredictorTest, OnSubresourceResponse) { // If there is no inflight navigation, nothing happens. URLRequestSummary resource1 = CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, net::MEDIUM, "text/css", false); predictor_->OnSubresourceResponse(resource1); EXPECT_TRUE(predictor_->inflight_navigations_.empty()); // Add an inflight navigation. URLRequestSummary main_frame1 = CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://www.google.com", content::RESOURCE_TYPE_MAIN_FRAME, net::MEDIUM, std::string(), false); predictor_->OnMainFrameRequest(main_frame1); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); // Now add a few subresources. URLRequestSummary resource2 = CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script1.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false); URLRequestSummary resource3 = CreateURLRequestSummary( 1, 1, "http://www.google.com", "http://google.com/script2.js", content::RESOURCE_TYPE_SCRIPT, net::MEDIUM, "text/javascript", false); predictor_->OnSubresourceResponse(resource1); predictor_->OnSubresourceResponse(resource2); predictor_->OnSubresourceResponse(resource3); EXPECT_EQ(1U, predictor_->inflight_navigations_.size()); EXPECT_EQ(3U, predictor_->inflight_navigations_[main_frame1.navigation_id] ->subresource_requests.size()); EXPECT_TRUE(URLRequestSummaryAreEqual( resource1, predictor_->inflight_navigations_[main_frame1.navigation_id] ->subresource_requests[0])); EXPECT_TRUE(URLRequestSummaryAreEqual( resource2, predictor_->inflight_navigations_[main_frame1.navigation_id] ->subresource_requests[1])); EXPECT_TRUE(URLRequestSummaryAreEqual( resource3, predictor_->inflight_navigations_[main_frame1.navigation_id] ->subresource_requests[2])); } TEST_F(ResourcePrefetchPredictorTest, HandledResourceTypes) { EXPECT_TRUE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_STYLESHEET, "bogus/mime-type")); EXPECT_TRUE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_STYLESHEET, "")); EXPECT_FALSE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_WORKER, "text/css")); EXPECT_FALSE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_WORKER, "")); EXPECT_TRUE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_PREFETCH, "text/css")); EXPECT_FALSE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_PREFETCH, "bogus/mime-type")); EXPECT_FALSE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_PREFETCH, "")); EXPECT_TRUE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_PREFETCH, "application/font-woff")); EXPECT_TRUE(ResourcePrefetchPredictor::IsHandledResourceType( content::RESOURCE_TYPE_PREFETCH, "font/woff2")); } TEST_F(ResourcePrefetchPredictorTest, ShouldRecordRequestMainFrame) { std::unique_ptr<net::URLRequest> http_request = CreateURLRequest(GURL("http://www.google.com"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); EXPECT_TRUE(ResourcePrefetchPredictor::ShouldRecordRequest( http_request.get(), content::RESOURCE_TYPE_MAIN_FRAME)); std::unique_ptr<net::URLRequest> https_request = CreateURLRequest(GURL("https://www.google.com"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); EXPECT_TRUE(ResourcePrefetchPredictor::ShouldRecordRequest( https_request.get(), content::RESOURCE_TYPE_MAIN_FRAME)); std::unique_ptr<net::URLRequest> file_request = CreateURLRequest(GURL("file://www.google.com"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordRequest( file_request.get(), content::RESOURCE_TYPE_MAIN_FRAME)); } TEST_F(ResourcePrefetchPredictorTest, ShouldRecordRequestSubResource) { std::unique_ptr<net::URLRequest> http_request = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, false); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordRequest( http_request.get(), content::RESOURCE_TYPE_IMAGE)); std::unique_ptr<net::URLRequest> https_request = CreateURLRequest(GURL("https://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, false); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordRequest( https_request.get(), content::RESOURCE_TYPE_IMAGE)); std::unique_ptr<net::URLRequest> file_request = CreateURLRequest(GURL("file://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, false); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordRequest( file_request.get(), content::RESOURCE_TYPE_IMAGE)); } TEST_F(ResourcePrefetchPredictorTest, ShouldRecordResponseMainFrame) { net::HttpResponseInfo response_info; response_info.headers = MakeResponseHeaders(""); url_request_job_factory_.set_response_info(response_info); std::unique_ptr<net::URLRequest> http_request = CreateURLRequest(GURL("http://www.google.com"), net::MEDIUM, content::RESOURCE_TYPE_MAIN_FRAME, 1, 1, true); EXPECT_TRUE( ResourcePrefetchPredictor::ShouldRecordResponse(http_request.get())); std::unique_ptr<net::URLRequest> https_request = CreateURLRequest(GURL("https://www.google.com"), net::MEDIUM, content::RESOURCE_TYPE_MAIN_FRAME, 1, 1, true); EXPECT_TRUE( ResourcePrefetchPredictor::ShouldRecordResponse(https_request.get())); std::unique_ptr<net::URLRequest> file_request = CreateURLRequest(GURL("file://www.google.com"), net::MEDIUM, content::RESOURCE_TYPE_MAIN_FRAME, 1, 1, true); EXPECT_FALSE( ResourcePrefetchPredictor::ShouldRecordResponse(file_request.get())); } TEST_F(ResourcePrefetchPredictorTest, ShouldRecordResponseSubresource) { net::HttpResponseInfo response_info; response_info.headers = MakeResponseHeaders("HTTP/1.1 200 OK\n\nSome: Headers\n"); response_info.was_cached = true; url_request_job_factory_.set_response_info(response_info); // Protocol. std::unique_ptr<net::URLRequest> http_image_request = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); EXPECT_TRUE(ResourcePrefetchPredictor::ShouldRecordResponse( http_image_request.get())); std::unique_ptr<net::URLRequest> https_image_request = CreateURLRequest(GURL("https://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); EXPECT_TRUE(ResourcePrefetchPredictor::ShouldRecordResponse( https_image_request.get())); std::unique_ptr<net::URLRequest> file_image_request = CreateURLRequest(GURL("file://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordResponse( file_image_request.get())); // ResourceType. std::unique_ptr<net::URLRequest> sub_frame_request = CreateURLRequest(GURL("http://www.google.com/frame.html"), net::MEDIUM, content::RESOURCE_TYPE_SUB_FRAME, 1, 1, true); EXPECT_FALSE( ResourcePrefetchPredictor::ShouldRecordResponse(sub_frame_request.get())); std::unique_ptr<net::URLRequest> font_request = CreateURLRequest( GURL("http://www.google.com/comic-sans-ms.woff"), net::MEDIUM, content::RESOURCE_TYPE_FONT_RESOURCE, 1, 1, true); EXPECT_TRUE( ResourcePrefetchPredictor::ShouldRecordResponse(font_request.get())); // From MIME Type. url_request_job_factory_.set_mime_type("image/png"); std::unique_ptr<net::URLRequest> prefetch_image_request = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); EXPECT_TRUE(ResourcePrefetchPredictor::ShouldRecordResponse( prefetch_image_request.get())); url_request_job_factory_.set_mime_type("image/my-wonderful-format"); std::unique_ptr<net::URLRequest> prefetch_unknown_image_request = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordResponse( prefetch_unknown_image_request.get())); url_request_job_factory_.set_mime_type("font/woff"); std::unique_ptr<net::URLRequest> prefetch_font_request = CreateURLRequest( GURL("http://www.google.com/comic-sans-ms.woff"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); EXPECT_TRUE(ResourcePrefetchPredictor::ShouldRecordResponse( prefetch_font_request.get())); url_request_job_factory_.set_mime_type("font/woff-woff"); std::unique_ptr<net::URLRequest> prefetch_unknown_font_request = CreateURLRequest(GURL("http://www.google.com/comic-sans-ms.woff"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordResponse( prefetch_unknown_font_request.get())); // Not main frame. std::unique_ptr<net::URLRequest> font_request_sub_frame = CreateURLRequest( GURL("http://www.google.com/comic-sans-ms.woff"), net::MEDIUM, content::RESOURCE_TYPE_FONT_RESOURCE, 1, 1, false); EXPECT_FALSE(ResourcePrefetchPredictor::ShouldRecordResponse( font_request_sub_frame.get())); } TEST_F(ResourcePrefetchPredictorTest, SummarizeResponse) { net::HttpResponseInfo response_info; response_info.headers = MakeResponseHeaders("HTTP/1.1 200 OK\n\nSome: Headers\n"); response_info.was_cached = true; url_request_job_factory_.set_response_info(response_info); GURL url("http://www.google.com/cat.png"); std::unique_ptr<net::URLRequest> request = CreateURLRequest( url, net::MEDIUM, content::RESOURCE_TYPE_IMAGE, 1, 1, true); URLRequestSummary summary; EXPECT_TRUE(URLRequestSummary::SummarizeResponse(*request, &summary)); EXPECT_EQ(1, summary.navigation_id.render_process_id); EXPECT_EQ(1, summary.navigation_id.render_frame_id); EXPECT_EQ(url, summary.navigation_id.main_frame_url); EXPECT_EQ(url, summary.resource_url); EXPECT_EQ(content::RESOURCE_TYPE_IMAGE, summary.resource_type); EXPECT_TRUE(summary.was_cached); EXPECT_FALSE(summary.has_validators); EXPECT_FALSE(summary.always_revalidate); } TEST_F(ResourcePrefetchPredictorTest, SummarizeResponseContentType) { net::HttpResponseInfo response_info; response_info.headers = MakeResponseHeaders( "HTTP/1.1 200 OK\n\n" "Some: Headers\n" "Content-Type: image/whatever\n"); url_request_job_factory_.set_response_info(response_info); url_request_job_factory_.set_mime_type("image/png"); std::unique_ptr<net::URLRequest> request = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); URLRequestSummary summary; EXPECT_TRUE(URLRequestSummary::SummarizeResponse(*request, &summary)); EXPECT_EQ(content::RESOURCE_TYPE_IMAGE, summary.resource_type); } TEST_F(ResourcePrefetchPredictorTest, SummarizeResponseCachePolicy) { net::HttpResponseInfo response_info; response_info.headers = MakeResponseHeaders( "HTTP/1.1 200 OK\n" "Some: Headers\n"); url_request_job_factory_.set_response_info(response_info); std::unique_ptr<net::URLRequest> request_no_validators = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); URLRequestSummary summary; EXPECT_TRUE( URLRequestSummary::SummarizeResponse(*request_no_validators, &summary)); EXPECT_FALSE(summary.has_validators); response_info.headers = MakeResponseHeaders( "HTTP/1.1 200 OK\n" "ETag: \"Cr66\"\n" "Cache-Control: no-cache\n"); url_request_job_factory_.set_response_info(response_info); std::unique_ptr<net::URLRequest> request_etag = CreateURLRequest(GURL("http://www.google.com/cat.png"), net::MEDIUM, content::RESOURCE_TYPE_PREFETCH, 1, 1, true); EXPECT_TRUE(URLRequestSummary::SummarizeResponse(*request_etag, &summary)); EXPECT_TRUE(summary.has_validators); EXPECT_TRUE(summary.always_revalidate); } TEST_F(ResourcePrefetchPredictorTest, PopulatePrefetcherRequest) { // The data that will be used in populating. PrefetchData google = CreatePrefetchData("http://www.google.com/", 1); InitializeResourceData(google.add_resources(), "http://google.com/image1.png", content::RESOURCE_TYPE_IMAGE, 10, 0, 0, 2.2, net::MEDIUM, false, false); // good InitializeResourceData(google.add_resources(), "http://google.com/style1.css", content::RESOURCE_TYPE_STYLESHEET, 2, 2, 1, 1.0, net::MEDIUM, false, false); // still good InitializeResourceData(google.add_resources(), "http://google.com/script3.js", content::RESOURCE_TYPE_SCRIPT, 1, 0, 1, 2.1, net::MEDIUM, false, false); // bad - not enough hits InitializeResourceData( google.add_resources(), "http://google.com/script4.js", content::RESOURCE_TYPE_SCRIPT, 4, 5, 0, 2.1, net::MEDIUM, false, false); // bad - more misses than hits (min_confidence = 0.5) // The data to be sure that other PrefetchData won't be affected. PrefetchData twitter = CreatePrefetchData("http://twitter.com", 2); InitializeResourceData( twitter.add_resources(), "http://twitter.com/image.jpg", content::RESOURCE_TYPE_IMAGE, 10, 0, 0, 1.0, net::MEDIUM, false, false); // The data to check negative result. PrefetchData nyt = CreatePrefetchData("http://nyt.com", 3); InitializeResourceData(nyt.add_resources(), "http://nyt.com/old_script.js", content::RESOURCE_TYPE_SCRIPT, 5, 7, 7, 1.0, net::MEDIUM, false, false); PrefetchDataMap test_data; test_data.insert(std::make_pair(google.primary_key(), google)); test_data.insert(std::make_pair(twitter.primary_key(), twitter)); test_data.insert(std::make_pair(nyt.primary_key(), nyt)); std::vector<GURL> urls; EXPECT_TRUE(predictor_->PopulatePrefetcherRequest(google.primary_key(), test_data, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL("http://google.com/image1.png"), GURL("http://google.com/style1.css"))); urls.clear(); EXPECT_FALSE(predictor_->PopulatePrefetcherRequest(nyt.primary_key(), test_data, &urls)); EXPECT_TRUE(urls.empty()); urls.clear(); EXPECT_FALSE(predictor_->PopulatePrefetcherRequest("http://404.com", test_data, &urls)); EXPECT_TRUE(urls.empty()); } TEST_F(ResourcePrefetchPredictorTest, GetRedirectEndpoint) { // The data to be requested for the most confident endpoint. RedirectData google = CreateRedirectData("http://google.com/", 1); InitializeRedirectStat(google.add_redirect_endpoints(), "https://google.com", 10, 0, 0); InitializeRedirectStat(google.add_redirect_endpoints(), "https://google.fr", 10, 1, 0); InitializeRedirectStat(google.add_redirect_endpoints(), "https://google.ws", 20, 20, 0); // The data to be sure that other RedirectData won't be affected. RedirectData gogle = CreateRedirectData("http://gogle.com", 2); InitializeRedirectStat(gogle.add_redirect_endpoints(), "https://google.com", 100, 0, 0); // The data to check negative result. RedirectData facebook = CreateRedirectData("http://fb.com/", 3); InitializeRedirectStat(facebook.add_redirect_endpoints(), "http://facebook.com", 5, 5, 0); // not enough confidence RedirectDataMap data_map; data_map.insert(std::make_pair(google.primary_key(), google)); data_map.insert(std::make_pair(gogle.primary_key(), gogle)); data_map.insert(std::make_pair(facebook.primary_key(), facebook)); std::string redirect_endpoint; EXPECT_TRUE(predictor_->GetRedirectEndpoint("http://google.com/", data_map, &redirect_endpoint)); EXPECT_EQ(redirect_endpoint, "https://google.com"); EXPECT_FALSE(predictor_->GetRedirectEndpoint("http://fb.com", data_map, &redirect_endpoint)); EXPECT_FALSE(predictor_->GetRedirectEndpoint("http://404.com", data_map, &redirect_endpoint)); } TEST_F(ResourcePrefetchPredictorTest, GetPrefetchData) { const GURL main_frame_url("http://google.com/?query=cats"); std::vector<GURL> urls; // No prefetch data. EXPECT_FALSE(predictor_->GetPrefetchData(main_frame_url, &urls)); // Add a resource associated with the main frame host. PrefetchData google_host = CreatePrefetchData("google.com", 1); const std::string script_url = "https://cdn.google.com/script.js"; InitializeResourceData(google_host.add_resources(), script_url, content::RESOURCE_TYPE_SCRIPT, 10, 0, 1, 2.1, net::MEDIUM, false, false); predictor_->host_table_cache_->insert( std::make_pair(google_host.primary_key(), google_host)); urls.clear(); EXPECT_TRUE(predictor_->GetPrefetchData(main_frame_url, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL(script_url))); // Add a resource associated with the main frame url. PrefetchData google_url = CreatePrefetchData("http://google.com/?query=cats", 2); const std::string image_url = "https://cdn.google.com/image.png"; InitializeResourceData(google_url.add_resources(), image_url, content::RESOURCE_TYPE_IMAGE, 10, 0, 1, 2.1, net::MEDIUM, false, false); predictor_->url_table_cache_->insert( std::make_pair(google_url.primary_key(), google_url)); urls.clear(); EXPECT_TRUE(predictor_->GetPrefetchData(main_frame_url, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL(image_url))); // Add host-based redirect. RedirectData host_redirect = CreateRedirectData("google.com", 3); InitializeRedirectStat(host_redirect.add_redirect_endpoints(), "www.google.com", 10, 0, 0); predictor_->host_redirect_table_cache_->insert( std::make_pair(host_redirect.primary_key(), host_redirect)); // Nothing changed: new redirect endpoint doesn't have any associated // resources urls.clear(); EXPECT_TRUE(predictor_->GetPrefetchData(main_frame_url, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL(image_url))); // Add a resource associated with host redirect endpoint. PrefetchData www_google_host = CreatePrefetchData("www.google.com", 4); const std::string style_url = "https://cdn.google.com/style.css"; InitializeResourceData(www_google_host.add_resources(), style_url, content::RESOURCE_TYPE_STYLESHEET, 10, 0, 1, 2.1, net::MEDIUM, false, false); predictor_->host_table_cache_->insert( std::make_pair(www_google_host.primary_key(), www_google_host)); urls.clear(); EXPECT_TRUE(predictor_->GetPrefetchData(main_frame_url, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL(style_url))); // Add url-based redirect. RedirectData url_redirect = CreateRedirectData("http://google.com/?query=cats", 5); InitializeRedirectStat(url_redirect.add_redirect_endpoints(), "https://www.google.com/?query=cats", 10, 0, 0); predictor_->url_redirect_table_cache_->insert( std::make_pair(url_redirect.primary_key(), url_redirect)); // Url redirect endpoint doesn't have associated resources. urls.clear(); EXPECT_TRUE(predictor_->GetPrefetchData(main_frame_url, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL(style_url))); // Add a resource associated with url redirect endpoint. PrefetchData www_google_url = CreatePrefetchData("https://www.google.com/?query=cats", 4); const std::string font_url = "https://cdn.google.com/comic-sans-ms.woff"; InitializeResourceData(www_google_url.add_resources(), font_url, content::RESOURCE_TYPE_FONT_RESOURCE, 10, 0, 1, 2.1, net::MEDIUM, false, false); predictor_->url_table_cache_->insert( std::make_pair(www_google_url.primary_key(), www_google_url)); urls.clear(); EXPECT_TRUE(predictor_->GetPrefetchData(main_frame_url, &urls)); EXPECT_THAT(urls, UnorderedElementsAre(GURL(font_url))); } } // namespace predictors
46.391892
80
0.693022
xzhan96
a99e0b809be646f6f08f77c79fc13623288e49ee
1,115
cpp
C++
tmp/binary_value.cpp
Ahmed-Zamouche/cpp
73136b5a350d3b95f0ae7e9ff007402e8f8214df
[ "MIT" ]
null
null
null
tmp/binary_value.cpp
Ahmed-Zamouche/cpp
73136b5a350d3b95f0ae7e9ff007402e8f8214df
[ "MIT" ]
null
null
null
tmp/binary_value.cpp
Ahmed-Zamouche/cpp
73136b5a350d3b95f0ae7e9ff007402e8f8214df
[ "MIT" ]
null
null
null
#include <iostream> #include <type_traits> #include <vector> #define NDEBUG template <bool a_0> int reversed_binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << a_0 << std::endl; #endif return a_0; } template <bool a_n_minus_1, bool a_n_minus_2, bool... digits> int reversed_binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << sizeof...(digits) << std::endl; #endif return (reversed_binary_value<a_n_minus_2, digits...>() << 1) + a_n_minus_1; } template <bool a_0> int binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << a_0 << std::endl; #endif return a_0; } template <bool a_n_minus_1, bool a_n_minus_2, bool... digits> int binary_value() { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << ": " << sizeof...(digits) << std::endl; #endif return a_n_minus_1 * (1 << (sizeof...(digits) + 1)) + binary_value<a_n_minus_2, digits...>(); } using namespace std; int main() { cout << binary_value<1, 0, 1, 0, 1, 0, 1, 0>() << endl; cout << reversed_binary_value<1, 0, 1, 0, 1, 0, 1, 0>() << endl; return 0; }
23.229167
78
0.647534
Ahmed-Zamouche
a9a13018a1376f05beec1401a95ea8ad5a6be308
11,688
cpp
C++
src/jbdl/experimental/cuosqp/osqp_sources/src/util.cpp
yz-mao/jbdl
a5380233b3795c8aaa9acd9e5c07fa44f8a5dadb
[ "MIT" ]
21
2021-08-29T06:59:18.000Z
2022-01-13T22:53:02.000Z
src/jbdl/experimental/cuosqp/osqp_sources/src/util.cpp
yz-mao/jbdl
a5380233b3795c8aaa9acd9e5c07fa44f8a5dadb
[ "MIT" ]
2
2021-08-31T08:34:09.000Z
2021-09-06T07:40:51.000Z
src/jbdl/experimental/cuosqp/osqp_sources/src/util.cpp
yz-mao/jbdl
a5380233b3795c8aaa9acd9e5c07fa44f8a5dadb
[ "MIT" ]
4
2021-08-29T06:59:22.000Z
2021-10-04T05:59:41.000Z
#include "osqp.h" #include "util.h" #include "algebra_vector.h" /************************************ * Printing Constants to set Layout * ************************************/ #ifdef PRINTING # define HEADER_LINE_LEN 65 #endif /* ifdef PRINTING */ /********************** * Utility Functions * **********************/ void c_strcpy(char dest[], const char source[]) { int i = 0; while (1) { dest[i] = source[i]; if (dest[i] == '\0') break; i++; } } #ifdef PRINTING static void print_line(void) { char the_line[HEADER_LINE_LEN + 1]; c_int i; for (i = 0; i < HEADER_LINE_LEN; ++i) the_line[i] = '-'; the_line[HEADER_LINE_LEN] = '\0'; c_print("%s\n", the_line); } void print_header(void) { // Different indentation required for windows #if defined(IS_WINDOWS) && !defined(PYTHON) c_print("iter "); #else c_print("iter "); #endif // Main information c_print("objective pri res dua res rho"); # ifdef PROFILING c_print(" time"); # endif /* ifdef PROFILING */ c_print("\n"); } void print_setup_header(const OSQPSolver *solver) { OSQPWorkspace *work; OSQPData *data; OSQPSettings *settings; c_int nnz; // Number of nonzeros in the problem work = solver->work; data = solver->work->data; settings = solver->settings; // Number of nonzeros nnz = OSQPMatrix_get_nz(data->P) + OSQPMatrix_get_nz(data->A); print_line(); c_print(" OSQP v%s - Operator Splitting QP Solver\n" " (c) Bartolomeo Stellato, Goran Banjac\n" " University of Oxford - Stanford University 2019\n", OSQP_VERSION); print_line(); // Print variables and constraints c_print("problem: "); c_print("variables n = %i, constraints m = %i\n ", (int)data->n, (int)data->m); c_print("nnz(P) + nnz(A) = %i\n", (int)nnz); // Print Settings c_print("settings: "); c_print("linear system solver = %s", LINSYS_SOLVER_NAME[settings->linsys_solver]); if (work->linsys_solver->nthreads != 1) { c_print(" (%d threads)", (int)work->linsys_solver->nthreads); } c_print(",\n "); c_print("eps_abs = %.1e, eps_rel = %.1e,\n ", settings->eps_abs, settings->eps_rel); c_print("eps_prim_inf = %.1e, eps_dual_inf = %.1e,\n ", settings->eps_prim_inf, settings->eps_dual_inf); c_print("rho = %.2e ", settings->rho); if (settings->adaptive_rho) c_print("(adaptive)"); c_print(",\n "); c_print("sigma = %.2e, alpha = %.2f, ", settings->sigma, settings->alpha); c_print("max_iter = %i\n", (int)settings->max_iter); if (settings->check_termination) c_print( " check_termination: on (interval %i),\n", (int)settings->check_termination); else c_print(" check_termination: off,\n"); # ifdef PROFILING if (settings->time_limit) c_print(" time_limit: %.2e sec,\n", settings->time_limit); # endif /* ifdef PROFILING */ if (settings->scaling) c_print(" scaling: on, "); else c_print(" scaling: off, "); if (settings->scaled_termination) c_print("scaled_termination: on\n"); else c_print("scaled_termination: off\n"); if (settings->warm_start) c_print(" warm start: on, "); else c_print(" warm start: off, "); if (settings->polish) c_print("polish: on, "); else c_print("polish: off, "); if (settings->time_limit) c_print("time_limit: %.2e sec\n", settings->time_limit); else c_print("time_limit: off\n"); c_print("\n"); } void print_summary(OSQPSolver *solver) { OSQPInfo* info = solver->info; OSQPSettings* settings = solver->settings; OSQPWorkspace* work = solver->work; c_print("%4i", (int)info->iter); c_print(" %12.4e", info->obj_val); c_print(" %9.2e", info->pri_res); c_print(" %9.2e", info->dua_res); c_print(" %9.2e", settings->rho); # ifdef PROFILING if (work->first_run) { // total time: setup + solve c_print(" %9.2es", info->setup_time + info->solve_time); } else { // total time: update + solve c_print(" %9.2es", info->update_time + info->solve_time); } # endif /* ifdef PROFILING */ c_print("\n"); work->summary_printed = 1; // Summary has been printed } void print_polish(OSQPSolver *solver) { OSQPInfo* info = solver->info; OSQPWorkspace* work = solver->work; c_print("%4s", "plsh"); c_print(" %12.4e", info->obj_val); c_print(" %9.2e", info->pri_res); c_print(" %9.2e", info->dua_res); // Different characters for windows/unix #if defined(IS_WINDOWS) && !defined(PYTHON) c_print(" ---------"); #else c_print(" --------"); #endif # ifdef PROFILING if (work->first_run) { // total time: setup + solve c_print(" %9.2es", info->setup_time + info->solve_time + info->polish_time); } else { // total time: update + solve c_print(" %9.2es", info->update_time + info->solve_time + info->polish_time); } # endif /* ifdef PROFILING */ c_print("\n"); } void print_footer(OSQPInfo *info, c_int polish) { c_print("\n"); // Add space after iterations c_print("status: %s\n", info->status); if (polish && (info->status_val == OSQP_SOLVED)) { if (info->status_polish == 1) { c_print("solution polish: successful\n"); } else if (info->status_polish < 0) { c_print("solution polish: unsuccessful\n"); } } c_print("number of iterations: %i\n", (int)info->iter); if ((info->status_val == OSQP_SOLVED) || (info->status_val == OSQP_SOLVED_INACCURATE)) { c_print("optimal objective: %.4f\n", info->obj_val); } # ifdef PROFILING c_print("run time: %.2es\n", info->run_time); # endif /* ifdef PROFILING */ # if EMBEDDED != 1 c_print("optimal rho estimate: %.2e\n", info->rho_estimate); # endif /* if EMBEDDED != 1 */ c_print("\n"); } #endif /* End #ifdef PRINTING */ #ifndef EMBEDDED OSQPSettings* copy_settings(const OSQPSettings *settings) { OSQPSettings *new = c_malloc(sizeof(OSQPSettings)); if (!new) return OSQP_NULL; // Copy settings // NB. Copying them explicitly because memcpy is not // defined when PRINTING is disabled (appears in string.h) new->rho = settings->rho; new->rho_is_vec = settings->rho_is_vec; new->sigma = settings->sigma; new->scaling = settings->scaling; # if EMBEDDED != 1 new->adaptive_rho = settings->adaptive_rho; new->adaptive_rho_interval = settings->adaptive_rho_interval; new->adaptive_rho_tolerance = settings->adaptive_rho_tolerance; # ifdef PROFILING new->adaptive_rho_fraction = settings->adaptive_rho_fraction; # endif # endif // EMBEDDED != 1 new->max_iter = settings->max_iter; new->eps_abs = settings->eps_abs; new->eps_rel = settings->eps_rel; new->eps_prim_inf = settings->eps_prim_inf; new->eps_dual_inf = settings->eps_dual_inf; new->alpha = settings->alpha; new->linsys_solver = settings->linsys_solver; new->delta = settings->delta; new->polish = settings->polish; new->polish_refine_iter = settings->polish_refine_iter; new->verbose = settings->verbose; new->scaled_termination = settings->scaled_termination; new->check_termination = settings->check_termination; new->warm_start = settings->warm_start; # ifdef PROFILING new->time_limit = settings->time_limit; # endif return new; } #endif // #ifndef EMBEDDED /******************* * Timer Functions * *******************/ #ifdef PROFILING // Windows # ifdef IS_WINDOWS void osqp_tic(OSQPTimer *t) { QueryPerformanceFrequency(&t->freq); QueryPerformanceCounter(&t->tic); } c_float osqp_toc(OSQPTimer *t) { QueryPerformanceCounter(&t->toc); return (t->toc.QuadPart - t->tic.QuadPart) / (c_float)t->freq.QuadPart; } // Mac # elif defined IS_MAC void osqp_tic(OSQPTimer *t) { /* read current clock cycles */ t->tic = mach_absolute_time(); } c_float osqp_toc(OSQPTimer *t) { uint64_t duration; /* elapsed time in clock cycles*/ t->toc = mach_absolute_time(); duration = t->toc - t->tic; /*conversion from clock cycles to nanoseconds*/ mach_timebase_info(&(t->tinfo)); duration *= t->tinfo.numer; duration /= t->tinfo.denom; return (c_float)duration / 1e9; } // Linux # else /* ifdef IS_WINDOWS */ /* read current time */ void osqp_tic(OSQPTimer *t) { clock_gettime(CLOCK_MONOTONIC, &t->tic); } /* return time passed since last call to tic on this timer */ c_float osqp_toc(OSQPTimer *t) { struct timespec temp; clock_gettime(CLOCK_MONOTONIC, &t->toc); if ((t->toc.tv_nsec - t->tic.tv_nsec) < 0) { temp.tv_sec = t->toc.tv_sec - t->tic.tv_sec - 1; temp.tv_nsec = 1e9 + t->toc.tv_nsec - t->tic.tv_nsec; } else { temp.tv_sec = t->toc.tv_sec - t->tic.tv_sec; temp.tv_nsec = t->toc.tv_nsec - t->tic.tv_nsec; } return (c_float)temp.tv_sec + (c_float)temp.tv_nsec / 1e9; } # endif /* ifdef IS_WINDOWS */ #endif // If Profiling end /* ==================== DEBUG FUNCTIONS ======================= */ // If debug mode enabled #ifdef DDEBUG #ifdef PRINTING void print_csc_matrix(const csc *M, const char *name) { c_int j, i, row_start, row_stop; c_int k = 0; // Print name c_print("%s :\n", name); for (j = 0; j < M->n; j++) { row_start = M->p[j]; row_stop = M->p[j + 1]; if (row_start == row_stop) continue; else { for (i = row_start; i < row_stop; i++) { c_print("\t[%3u,%3u] = %.3g\n", (int)M->i[i], (int)j, M->x[k++]); } } } } void dump_csc_matrix(csc *M, const char *file_name) { c_int j, i, row_strt, row_stop; c_int k = 0; FILE *f = fopen(file_name, "w"); if (f) { for (j = 0; j < M->n; j++) { row_strt = M->p[j]; row_stop = M->p[j + 1]; if (row_strt == row_stop) continue; else { for (i = row_strt; i < row_stop; i++) { fprintf(f, "%d\t%d\t%20.18e\n", (int)M->i[i] + 1, (int)j + 1, M->x[k++]); } } } fprintf(f, "%d\t%d\t%20.18e\n", (int)M->m, (int)M->n, 0.0); fclose(f); c_print("File %s successfully written.\n", file_name); } else { c_eprint("Error during writing file %s.\n", file_name); } } void print_trip_matrix(csc *M, const char *name) { c_int k = 0; // Print name c_print("%s :\n", name); for (k = 0; k < M->nz; k++) { c_print("\t[%3u, %3u] = %.3g\n", (int)M->i[k], (int)M->p[k], M->x[k]); } } void print_dns_matrix(c_float *M, c_int m, c_int n, const char *name) { c_int i, j; c_print("%s : \n\t", name); for (i = 0; i < m; i++) { // Cycle over rows for (j = 0; j < n; j++) { // Cycle over columns if (j < n - 1) // c_print("% 14.12e, ", M[j*m+i]); c_print("% .3g, ", M[j * m + i]); else // c_print("% 14.12e; ", M[j*m+i]); c_print("% .3g; ", M[j * m + i]); } if (i < m - 1) { c_print("\n\t"); } } c_print("\n"); } void print_vec(c_float *v, c_int n, const char *name) { print_dns_matrix(v, 1, n, name); } void dump_vec(c_float *v, c_int len, const char *file_name) { c_int i; FILE *f = fopen(file_name, "w"); if (f) { for (i = 0; i < len; i++) { fprintf(f, "%20.18e\n", v[i]); } fclose(f); c_print("File %s successfully written.\n", file_name); } else { c_print("Error during writing file %s.\n", file_name); } } void print_vec_int(c_int *x, c_int n, const char *name) { c_int i; c_print("%s = [", name); for (i = 0; i < n; i++) { c_print(" %i ", (int)x[i]); } c_print("]\n"); } #endif // PRINTING #endif // DEBUG MODE
24.710359
84
0.590178
yz-mao
a9a17d3ffdc8214ced17d14a2f2323433b90dba8
12,372
cpp
C++
tdmq/src/v20200217/model/AMQPQueueDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tdmq/src/v20200217/model/AMQPQueueDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tdmq/src/v20200217/model/AMQPQueueDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tdmq/v20200217/model/AMQPQueueDetail.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tdmq::V20200217::Model; using namespace std; AMQPQueueDetail::AMQPQueueDetail() : m_nameHasBeenSet(false), m_remarkHasBeenSet(false), m_destBindedNumHasBeenSet(false), m_createTimeHasBeenSet(false), m_updateTimeHasBeenSet(false), m_onlineConsumerNumHasBeenSet(false), m_tpsHasBeenSet(false), m_accumulativeMsgNumHasBeenSet(false), m_autoDeleteHasBeenSet(false), m_deadLetterExchangeHasBeenSet(false), m_deadLetterRoutingKeyHasBeenSet(false) { } CoreInternalOutcome AMQPQueueDetail::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("Remark") && !value["Remark"].IsNull()) { if (!value["Remark"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.Remark` IsString=false incorrectly").SetRequestId(requestId)); } m_remark = string(value["Remark"].GetString()); m_remarkHasBeenSet = true; } if (value.HasMember("DestBindedNum") && !value["DestBindedNum"].IsNull()) { if (!value["DestBindedNum"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.DestBindedNum` IsUint64=false incorrectly").SetRequestId(requestId)); } m_destBindedNum = value["DestBindedNum"].GetUint64(); m_destBindedNumHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.CreateTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_createTime = value["CreateTime"].GetUint64(); m_createTimeHasBeenSet = true; } if (value.HasMember("UpdateTime") && !value["UpdateTime"].IsNull()) { if (!value["UpdateTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.UpdateTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_updateTime = value["UpdateTime"].GetUint64(); m_updateTimeHasBeenSet = true; } if (value.HasMember("OnlineConsumerNum") && !value["OnlineConsumerNum"].IsNull()) { if (!value["OnlineConsumerNum"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.OnlineConsumerNum` IsUint64=false incorrectly").SetRequestId(requestId)); } m_onlineConsumerNum = value["OnlineConsumerNum"].GetUint64(); m_onlineConsumerNumHasBeenSet = true; } if (value.HasMember("Tps") && !value["Tps"].IsNull()) { if (!value["Tps"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.Tps` IsUint64=false incorrectly").SetRequestId(requestId)); } m_tps = value["Tps"].GetUint64(); m_tpsHasBeenSet = true; } if (value.HasMember("AccumulativeMsgNum") && !value["AccumulativeMsgNum"].IsNull()) { if (!value["AccumulativeMsgNum"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.AccumulativeMsgNum` IsUint64=false incorrectly").SetRequestId(requestId)); } m_accumulativeMsgNum = value["AccumulativeMsgNum"].GetUint64(); m_accumulativeMsgNumHasBeenSet = true; } if (value.HasMember("AutoDelete") && !value["AutoDelete"].IsNull()) { if (!value["AutoDelete"].IsBool()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.AutoDelete` IsBool=false incorrectly").SetRequestId(requestId)); } m_autoDelete = value["AutoDelete"].GetBool(); m_autoDeleteHasBeenSet = true; } if (value.HasMember("DeadLetterExchange") && !value["DeadLetterExchange"].IsNull()) { if (!value["DeadLetterExchange"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.DeadLetterExchange` IsString=false incorrectly").SetRequestId(requestId)); } m_deadLetterExchange = string(value["DeadLetterExchange"].GetString()); m_deadLetterExchangeHasBeenSet = true; } if (value.HasMember("DeadLetterRoutingKey") && !value["DeadLetterRoutingKey"].IsNull()) { if (!value["DeadLetterRoutingKey"].IsString()) { return CoreInternalOutcome(Core::Error("response `AMQPQueueDetail.DeadLetterRoutingKey` IsString=false incorrectly").SetRequestId(requestId)); } m_deadLetterRoutingKey = string(value["DeadLetterRoutingKey"].GetString()); m_deadLetterRoutingKeyHasBeenSet = true; } return CoreInternalOutcome(true); } void AMQPQueueDetail::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_nameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator); } if (m_remarkHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Remark"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator); } if (m_destBindedNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DestBindedNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_destBindedNum, allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_createTime, allocator); } if (m_updateTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UpdateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_updateTime, allocator); } if (m_onlineConsumerNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OnlineConsumerNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_onlineConsumerNum, allocator); } if (m_tpsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tps"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_tps, allocator); } if (m_accumulativeMsgNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AccumulativeMsgNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_accumulativeMsgNum, allocator); } if (m_autoDeleteHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoDelete"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_autoDelete, allocator); } if (m_deadLetterExchangeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeadLetterExchange"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_deadLetterExchange.c_str(), allocator).Move(), allocator); } if (m_deadLetterRoutingKeyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeadLetterRoutingKey"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_deadLetterRoutingKey.c_str(), allocator).Move(), allocator); } } string AMQPQueueDetail::GetName() const { return m_name; } void AMQPQueueDetail::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool AMQPQueueDetail::NameHasBeenSet() const { return m_nameHasBeenSet; } string AMQPQueueDetail::GetRemark() const { return m_remark; } void AMQPQueueDetail::SetRemark(const string& _remark) { m_remark = _remark; m_remarkHasBeenSet = true; } bool AMQPQueueDetail::RemarkHasBeenSet() const { return m_remarkHasBeenSet; } uint64_t AMQPQueueDetail::GetDestBindedNum() const { return m_destBindedNum; } void AMQPQueueDetail::SetDestBindedNum(const uint64_t& _destBindedNum) { m_destBindedNum = _destBindedNum; m_destBindedNumHasBeenSet = true; } bool AMQPQueueDetail::DestBindedNumHasBeenSet() const { return m_destBindedNumHasBeenSet; } uint64_t AMQPQueueDetail::GetCreateTime() const { return m_createTime; } void AMQPQueueDetail::SetCreateTime(const uint64_t& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool AMQPQueueDetail::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } uint64_t AMQPQueueDetail::GetUpdateTime() const { return m_updateTime; } void AMQPQueueDetail::SetUpdateTime(const uint64_t& _updateTime) { m_updateTime = _updateTime; m_updateTimeHasBeenSet = true; } bool AMQPQueueDetail::UpdateTimeHasBeenSet() const { return m_updateTimeHasBeenSet; } uint64_t AMQPQueueDetail::GetOnlineConsumerNum() const { return m_onlineConsumerNum; } void AMQPQueueDetail::SetOnlineConsumerNum(const uint64_t& _onlineConsumerNum) { m_onlineConsumerNum = _onlineConsumerNum; m_onlineConsumerNumHasBeenSet = true; } bool AMQPQueueDetail::OnlineConsumerNumHasBeenSet() const { return m_onlineConsumerNumHasBeenSet; } uint64_t AMQPQueueDetail::GetTps() const { return m_tps; } void AMQPQueueDetail::SetTps(const uint64_t& _tps) { m_tps = _tps; m_tpsHasBeenSet = true; } bool AMQPQueueDetail::TpsHasBeenSet() const { return m_tpsHasBeenSet; } uint64_t AMQPQueueDetail::GetAccumulativeMsgNum() const { return m_accumulativeMsgNum; } void AMQPQueueDetail::SetAccumulativeMsgNum(const uint64_t& _accumulativeMsgNum) { m_accumulativeMsgNum = _accumulativeMsgNum; m_accumulativeMsgNumHasBeenSet = true; } bool AMQPQueueDetail::AccumulativeMsgNumHasBeenSet() const { return m_accumulativeMsgNumHasBeenSet; } bool AMQPQueueDetail::GetAutoDelete() const { return m_autoDelete; } void AMQPQueueDetail::SetAutoDelete(const bool& _autoDelete) { m_autoDelete = _autoDelete; m_autoDeleteHasBeenSet = true; } bool AMQPQueueDetail::AutoDeleteHasBeenSet() const { return m_autoDeleteHasBeenSet; } string AMQPQueueDetail::GetDeadLetterExchange() const { return m_deadLetterExchange; } void AMQPQueueDetail::SetDeadLetterExchange(const string& _deadLetterExchange) { m_deadLetterExchange = _deadLetterExchange; m_deadLetterExchangeHasBeenSet = true; } bool AMQPQueueDetail::DeadLetterExchangeHasBeenSet() const { return m_deadLetterExchangeHasBeenSet; } string AMQPQueueDetail::GetDeadLetterRoutingKey() const { return m_deadLetterRoutingKey; } void AMQPQueueDetail::SetDeadLetterRoutingKey(const string& _deadLetterRoutingKey) { m_deadLetterRoutingKey = _deadLetterRoutingKey; m_deadLetterRoutingKeyHasBeenSet = true; } bool AMQPQueueDetail::DeadLetterRoutingKeyHasBeenSet() const { return m_deadLetterRoutingKeyHasBeenSet; }
28.974239
154
0.696492
suluner
a9a3e31e8459ce3f87fb327f70d7c40e297d4d6c
880
cpp
C++
18_List_Kullanimi/src/main.cpp
KMACEL/TR-Cpp
dac7bebd1d5fd2d69a76be5a9809417333f01817
[ "Apache-2.0" ]
1
2021-05-25T22:11:13.000Z
2021-05-25T22:11:13.000Z
18_List_Kullanimi/src/main.cpp
KMACEL/TR-Cpp
dac7bebd1d5fd2d69a76be5a9809417333f01817
[ "Apache-2.0" ]
null
null
null
18_List_Kullanimi/src/main.cpp
KMACEL/TR-Cpp
dac7bebd1d5fd2d69a76be5a9809417333f01817
[ "Apache-2.0" ]
null
null
null
//============================================================================ // İsim : 18_List_Kullanımı // Yazan : Mert AceL // Version : 1.0 // Copyright : AceL // Açıklama : Listelere Giriş //============================================================================ #include <iostream> #include <list> using namespace std; int main() { list<int> sayi; sayi.push_back(4); sayi.push_back(7); sayi.push_back(1); sayi.push_back(5); sayi.push_back(12); sayi.push_front(2); list<int>::iterator it = sayi.begin(); cout << "Sayı : " << *it << endl; *it++; cout << "Sayı : " << *it << endl; sayi.insert(it, 55); for (list<int>::iterator itF = sayi.begin(); itF != sayi.end(); itF++) { cout << "Sayi For : " << *itF << endl; } cout << "--------------------------------------------------------" << endl; return 0; }
22.564103
78
0.421591
KMACEL
a9a66f8e56e123a1234a549f9e95dce921456214
1,764
cpp
C++
src/section.cpp
YureiResearchInstitute/Yo-kai_Editor_B2
990809487492a95dec388ee04d2eab80e190c88d
[ "MIT" ]
2
2021-06-21T21:42:30.000Z
2021-06-21T21:42:33.000Z
src/section.cpp
YureiResearchInstitute/Yo-kai_Editor_B2
990809487492a95dec388ee04d2eab80e190c88d
[ "MIT" ]
null
null
null
src/section.cpp
YureiResearchInstitute/Yo-kai_Editor_B2
990809487492a95dec388ee04d2eab80e190c88d
[ "MIT" ]
4
2019-11-07T04:23:58.000Z
2021-08-29T01:17:21.000Z
#include "section.h" Section::Section(QTreeWidget* parent, quint32 id, quint32 size, quint32 offset) : QTreeWidgetItem(parent, Section::Type) , id(id) , size(size) , offset(offset) { this->setText(0, QString::number(id)); } Section::~Section() { } quint32 Section::getId() const { return id; } void Section::setId(const quint32& value) { id = value; } quint32 Section::getSize() const { return size; } void Section::setSize(const quint32& value) { size = value; } quint32 Section::getOffset() const { return offset; } void Section::setOffset(const quint32& value) { offset = value; } QString Section::getPath() const { const QTreeWidgetItem* t = this; QStringList l; do { l.prepend(t->text(0)); } while ((t = t->parent())); return l.join("/"); } Section* Section::child(int index) { QTreeWidgetItem* child = this->QTreeWidgetItem::child(index); if (child && child->type() == Section::Type) { return static_cast<Section*>(child); } return 0; } Section* Section::nextSibling() { QTreeWidgetItem* parent = this->parent(); QTreeWidgetItem* nextSibling; if (parent) { nextSibling = parent->child(parent->indexOfChild(this) + 1); } else { QTreeWidget* treeWidget = this->treeWidget(); nextSibling = treeWidget->topLevelItem(treeWidget->indexOfTopLevelItem(this) + 1); } if (nextSibling && nextSibling->type() == Section::Type) { return static_cast<Section*>(nextSibling); } return 0; } Section* Section::parent() { QTreeWidgetItem* parent = this->QTreeWidgetItem::parent(); if (parent && parent->type() == Section::Type) { return static_cast<Section*>(parent); } return 0; }
20.045455
90
0.630385
YureiResearchInstitute
a9a6b4e487a279ddea9a36cfeca9790624b3242c
4,424
cpp
C++
main.cpp
budacalorin/BomberMan
715aeaa0d43b1f887ddd8202c75e7f5380657ff8
[ "Apache-2.0" ]
null
null
null
main.cpp
budacalorin/BomberMan
715aeaa0d43b1f887ddd8202c75e7f5380657ff8
[ "Apache-2.0" ]
null
null
null
main.cpp
budacalorin/BomberMan
715aeaa0d43b1f887ddd8202c75e7f5380657ff8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <cstdlib> #include "init.h" //#include "scena_meniu.h" //#include "scena_joc.h" //#include "player.h" using namespace std; ///////////////////////////////////////////////////////////// int latime_pereti_exterior=30; int hight=510+latime_pereti_exterior*2; int width=510+latime_pereti_exterior*2; int game_on=1; int player_x=30; int player_y=30; int pixel_per_frame=1; int bomba_x=30; int bomba_y=30; sf::Texture *pt_inima; sf::Texture *pt_bomba; sf::Texture *pt_shoe; sf::Texture *pt_foc; sf::Texture t_inima; sf::Texture t_bomba; sf::Texture t_shoe; sf::Texture t_foc; sf::Texture harta; sf::Sprite sprite_harta; sf::Texture zid_solid; sf::Texture *pzid_solid; sf::Texture zid_fragil; sf::Texture *pzid_fragil; sf::Texture *p_player1_dreapta; sf::Texture player1_dreapta; sf::Texture *p_player1_stanga; sf::Texture player1_stanga; sf::Texture *p_player2_dreapta; sf::Texture player2_dreapta; sf::Texture *p_player2_stanga; sf::Texture player2_stanga; sf::Texture *p_player3_dreapta; sf::Texture player3_dreapta; sf::Texture *p_player3_stanga; sf::Texture player3_stanga; sf::Texture *p_player4_dreapta; sf::Texture player4_dreapta; sf::Texture *p_player4_stanga; sf::Texture player4_stanga; sf::Texture *pt0,*pt1,*pt2,*pt3,*pt4,*pt5,*pt6,*pt7,*pt8,*pt9; sf::Texture t0,t1,t2,t3,t4,t5,t6,t7,t8,t9; ///////////////////////////////////////////////////////////// sf::Clock ceas; sf::RenderWindow window(sf::VideoMode(1366,768),"BOMBER MAN",sf::Style::Fullscreen); scena_meniu meniu_principal; scena_joc joc_principal; int scena_curenta=1; int main() { meniu_principal.adaugare_optiune("PLAY"); meniu_principal.adaugare_optiune("EXIT"); t_bomba.loadFromFile("img/power_up_bomba.png"); t_foc.loadFromFile("img/power_up_foc.png"); t_shoe.loadFromFile("img/power_up_shoe.png"); t_inima.loadFromFile("img/power_up_inima.png"); harta.loadFromFile("img/atempt2.png"); sprite_harta.setTexture(harta); //sprite_harta.setPosition(sf::Vector2f(latime_pereti_exterior,latime_pereti_exterior)); zid_solid.loadFromFile("img/zid_solid_3.png"); pzid_solid=&zid_solid; zid_fragil.loadFromFile("img/zid_fragil.png"); pzid_fragil=&zid_fragil; player1_dreapta.loadFromFile("img/player1_dreapta.png"); p_player1_dreapta=&player1_dreapta; player1_stanga.loadFromFile("img/player1_stanga.png"); p_player1_stanga=&player1_stanga; player2_dreapta.loadFromFile("img/player2_dreapta.png"); p_player2_dreapta=&player2_dreapta; player2_stanga.loadFromFile("img/player2_stanga.png"); p_player2_stanga=&player2_stanga; player3_dreapta.loadFromFile("img/player3_dreapta.png"); p_player3_dreapta=&player3_dreapta; player3_stanga.loadFromFile("img/player3_stanga.png"); p_player3_stanga=&player3_stanga; player4_dreapta.loadFromFile("img/player4_dreapta.png"); p_player4_dreapta=&player4_dreapta; player4_stanga.loadFromFile("img/player4_stanga.png"); p_player4_stanga=&player4_stanga; t0.loadFromFile("img/0.png"); pt0=&t0; t1.loadFromFile("img/1.png"); pt1=&t1; t2.loadFromFile("img/2.png"); pt2=&t2; t3.loadFromFile("img/3.png"); pt3=&t3; t4.loadFromFile("img/4.png"); pt4=&t4; t5.loadFromFile("img/5.png"); pt5=&t5; t6.loadFromFile("img/6.png"); pt6=&t6; t7.loadFromFile("img/7.png"); pt7=&t7; t8.loadFromFile("img/8.png"); pt8=&t8; t9.loadFromFile("img/9.png"); pt9=&t9; pt_bomba=&t_bomba; pt_foc=&t_foc; pt_shoe=&t_shoe; pt_inima=&t_inima; //ceas.restart(); //sf::Clock clock; //clock.restart(); // int timp; //int timp_per_frame; //timp_per_frame=100000/6; while (game_on==1) { //timp=clock.getElapsedTime().asMicroseconds(); if (scena_curenta==1) meniu_principal.update(); if (scena_curenta==2) { joc_principal.update(); sf::Event event; while (window.pollEvent(event)) { if (event.type==sf::Event::Closed) game_on=0; } } //if (clock.getElapsedTime().asMicroseconds()-timp<timp_per_frame) // sf::sleep(sf::microseconds(timp_per_frame-(clock.getElapsedTime().asMicroseconds()-timp))); //clock.restart(); } return 0; }
26.812121
105
0.676085
budacalorin
a9a6f3cec6bc5f7f3e2f303a0fa454bd91800561
6,823
hpp
C++
alpaka/include/alpaka/meta/CudaVectorArrayWrapper.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
25
2015-01-30T12:19:48.000Z
2020-10-30T07:52:45.000Z
alpaka/include/alpaka/meta/CudaVectorArrayWrapper.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
101
2015-01-06T11:31:26.000Z
2020-11-09T13:51:19.000Z
alpaka/include/alpaka/meta/CudaVectorArrayWrapper.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
10
2015-06-10T07:54:30.000Z
2020-05-06T10:07:39.000Z
/* Copyright 2022 Jiří Vyskočil, Jan Stephan, Bernhard Manfred Gruber * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #if defined(ALPAKA_ACC_GPU_HIP_ENABLED) || defined(ALPAKA_ACC_GPU_CUDA_ENABLED) # include <alpaka/core/Common.hpp> # include <functional> # include <initializer_list> # include <numeric> # include <type_traits> namespace alpaka::meta { namespace detail { template<typename TScalar, unsigned N> struct CudaVectorArrayTypeTraits; template<> struct CudaVectorArrayTypeTraits<float, 1> { using type = float1; }; template<> struct CudaVectorArrayTypeTraits<float, 2> { using type = float2; }; template<> struct CudaVectorArrayTypeTraits<float, 3> { using type = float3; }; template<> struct CudaVectorArrayTypeTraits<float, 4> { using type = float4; }; template<> struct CudaVectorArrayTypeTraits<double, 1> { using type = double1; }; template<> struct CudaVectorArrayTypeTraits<double, 2> { using type = double2; }; template<> struct CudaVectorArrayTypeTraits<double, 3> { using type = double3; }; template<> struct CudaVectorArrayTypeTraits<double, 4> { using type = double4; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 1> { using type = uint1; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 2> { using type = uint2; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 3> { using type = uint3; }; template<> struct CudaVectorArrayTypeTraits<unsigned, 4> { using type = uint4; }; template<> struct CudaVectorArrayTypeTraits<int, 1> { using type = int1; }; template<> struct CudaVectorArrayTypeTraits<int, 2> { using type = int2; }; template<> struct CudaVectorArrayTypeTraits<int, 3> { using type = int3; }; template<> struct CudaVectorArrayTypeTraits<int, 4> { using type = int4; }; } // namespace detail /// Helper struct providing [] subscript access to CUDA vector types template<typename TScalar, unsigned N> struct CudaVectorArrayWrapper; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 4> : public detail::CudaVectorArrayTypeTraits<TScalar, 4>::type { using value_type = TScalar; constexpr static unsigned size = 4; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it++; this->y = *it++; this->z = *it++; this->w = *it++; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[](int const k) noexcept { assert(k >= 0 && k < 4); return k == 0 ? this->x : (k == 1 ? this->y : (k == 2 ? this->z : this->w)); } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[](int const k) const noexcept { assert(k >= 0 && k < 4); return k == 0 ? this->x : (k == 1 ? this->y : (k == 2 ? this->z : this->w)); } }; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 3> : public detail::CudaVectorArrayTypeTraits<TScalar, 3>::type { using value_type = TScalar; constexpr static unsigned size = 3; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it++; this->y = *it++; this->z = *it++; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[](int const k) noexcept { assert(k >= 0 && k < 3); return k == 0 ? this->x : (k == 1 ? this->y : this->z); } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[](int const k) const noexcept { assert(k >= 0 && k < 3); return k == 0 ? this->x : (k == 1 ? this->y : this->z); } }; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 2> : public detail::CudaVectorArrayTypeTraits<TScalar, 2>::type { using value_type = TScalar; constexpr static unsigned size = 2; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it++; this->y = *it++; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[](int const k) noexcept { assert(k >= 0 && k < 2); return k == 0 ? this->x : this->y; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[](int const k) const noexcept { assert(k >= 0 && k < 2); return k == 0 ? this->x : this->y; } }; template<typename TScalar> struct CudaVectorArrayWrapper<TScalar, 1> : public detail::CudaVectorArrayTypeTraits<TScalar, 1>::type { using value_type = TScalar; constexpr static unsigned size = 1; ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE CudaVectorArrayWrapper(std::initializer_list<TScalar> init) { auto it = std::begin(init); this->x = *it; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr value_type& operator[]([[maybe_unused]] int const k) noexcept { assert(k == 0); return this->x; } ALPAKA_FN_HOST_ACC ALPAKA_FN_INLINE constexpr const value_type& operator[]( [[maybe_unused]] int const k) const noexcept { assert(k == 0); return this->x; } }; } // namespace alpaka::meta namespace std { /// Specialization of std::tuple_size for \a float4_array template<typename T, unsigned N> struct tuple_size<alpaka::meta::CudaVectorArrayWrapper<T, N>> : integral_constant<size_t, N> { }; } // namespace std #endif
28.548117
115
0.56163
ComputationalRadiationPhysics
a9a7979da7f2ac3c8fb0c5591875f08c287659ef
2,173
cpp
C++
deps/src/boost_1_65_1/libs/type_traits/test/is_volatile_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
deps/src/boost_1_65_1/libs/type_traits/test/is_volatile_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
deps/src/boost_1_65_1/libs/type_traits/test/is_volatile_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2020-10-21T17:46:28.000Z
2020-10-21T17:46:28.000Z
// (C) Copyright John Maddock 2000. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include "check_integral_constant.hpp" #ifdef TEST_STD # include <type_traits> #else # include <boost/type_traits/is_volatile.hpp> #endif TT_TEST_BEGIN(is_volatile) BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<void>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile void>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<test_abc1>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile test_abc1>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<int>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile int>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile UDT>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile const UDT>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<incomplete_type>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile int[2]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<int[2]>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<const int[2]>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<const volatile int[2]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<const volatile int[]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<const int[]>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile int[]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<int[]>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<int&>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile int&>::value, false); #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<int&&>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_volatile<volatile int&&>::value, false); #endif TT_TEST_END
50.534884
85
0.790612
shreyasvj25
a9a89923e3ebcf662babeca9efe65b59f738bb96
47,495
cc
C++
camera/features/hdrnet/hdrnet_stream_manipulator.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
camera/features/hdrnet/hdrnet_stream_manipulator.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
camera/features/hdrnet/hdrnet_stream_manipulator.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2021 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "features/hdrnet/hdrnet_stream_manipulator.h" #include <algorithm> #include <optional> #include <string> #include <utility> #include <base/files/file_util.h> #include <sync/sync.h> #include <system/camera_metadata.h> #include "common/still_capture_processor_impl.h" #include "cros-camera/camera_buffer_manager.h" #include "cros-camera/camera_metadata_utils.h" #include "cros-camera/common.h" #include "cros-camera/texture_2d_descriptor.h" #include "features/hdrnet/hdrnet_processor_impl.h" #include "gpu/egl/egl_fence.h" #include "gpu/egl/utils.h" #include "gpu/gles/texture_2d.h" #include "gpu/gles/utils.h" namespace cros { namespace { constexpr int kDefaultSyncWaitTimeoutMs = 300; constexpr char kMetadataDumpPath[] = "/run/camera/hdrnet_frame_metadata.json"; constexpr char kDumpBufferKey[] = "dump_buffer"; constexpr char kHdrNetEnableKey[] = "hdrnet_enable"; constexpr char kLogFrameMetadataKey[] = "log_frame_metadata"; constexpr char kHdrRatioKey[] = "hdr_ratio"; constexpr char kMaxGainBlendThresholdKey[] = "max_gain_blend_threshold"; constexpr char kSpatialFilterSigma[] = "spatial_filter_sigma"; constexpr char kRangeFilterSigma[] = "range_filter_sigma"; constexpr char kIirFilterStrength[] = "iir_filter_strength"; constexpr char kDenoiserEnable[] = "denoiser_enable"; constexpr char kDenoiserIirTemporalConvergence[] = "denoiser_iir_temporal_convergence"; constexpr char kDenoiserNumSpatialPasses[] = "num_spatial_passes"; constexpr char kDenoiserSpatialStrength[] = "spatial_strength"; // Allocate one buffer for denoiser because we run the denoiser in IIR filter // mode. We'll need to have more buffers if we run the burst denoising mode. constexpr int kMaxDenoiserBurstLength = 1; } // namespace // // HdrNetStreamManipulator::HdrNetStreamContext implementations. // std::optional<int> HdrNetStreamManipulator::HdrNetStreamContext::PopBuffer() { if (usable_buffer_list.empty()) { LOGF(ERROR) << "Buffer underrun"; return std::nullopt; } HdrNetStreamContext::UsableBufferInfo buffer_info = std::move(usable_buffer_list.front()); usable_buffer_list.pop(); if (buffer_info.acquire_fence.is_valid() && sync_wait(buffer_info.acquire_fence.get(), kDefaultSyncWaitTimeoutMs) != 0) { LOGF(WARNING) << "sync_wait timeout on acquiring usable HDRnet buffer"; NOTREACHED(); } return buffer_info.index; } void HdrNetStreamManipulator::HdrNetStreamContext::PushBuffer( int index, base::ScopedFD acquire_fence) { usable_buffer_list.push( {.index = index, .acquire_fence = std::move(acquire_fence)}); } // // HdrNetStreamManipulator::HdrNetRequestBufferInfo implementations. // HdrNetStreamManipulator::HdrNetRequestBufferInfo::HdrNetRequestBufferInfo( HdrNetStreamManipulator::HdrNetStreamContext* context, std::vector<camera3_stream_buffer_t>&& buffers) : stream_context(context), client_requested_yuv_buffers(std::move(buffers)) {} HdrNetStreamManipulator::HdrNetRequestBufferInfo::HdrNetRequestBufferInfo( HdrNetStreamManipulator::HdrNetRequestBufferInfo&& other) { *this = std::move(other); } HdrNetStreamManipulator::HdrNetRequestBufferInfo& HdrNetStreamManipulator::HdrNetRequestBufferInfo::operator=( HdrNetStreamManipulator::HdrNetRequestBufferInfo&& other) { if (this != &other) { Invalidate(); stream_context = other.stream_context; buffer_index = other.buffer_index; other.buffer_index = kInvalidBufferIndex; release_fence = std::move(other.release_fence); client_requested_yuv_buffers.swap(other.client_requested_yuv_buffers); blob_result_pending = other.blob_result_pending; blob_intermediate_yuv_pending = other.blob_intermediate_yuv_pending; skip_hdrnet_processing = other.skip_hdrnet_processing; other.Invalidate(); } return *this; } HdrNetStreamManipulator::HdrNetRequestBufferInfo::~HdrNetRequestBufferInfo() { Invalidate(); } void HdrNetStreamManipulator::HdrNetRequestBufferInfo::Invalidate() { if (stream_context && buffer_index != kInvalidBufferIndex) { stream_context->PushBuffer(buffer_index, std::move(release_fence)); } stream_context = nullptr; buffer_index = kInvalidBufferIndex; release_fence.reset(); client_requested_yuv_buffers.clear(); blob_result_pending = false; blob_intermediate_yuv_pending = false; skip_hdrnet_processing = false; } // // HdrNetStreamManipulator implementations. // HdrNetStreamManipulator::HdrNetStreamManipulator( base::FilePath config_file_path, std::unique_ptr<StillCaptureProcessor> still_capture_processor, HdrNetProcessor::Factory hdrnet_processor_factory) : gpu_thread_("HdrNetPipelineGpuThread"), hdrnet_processor_factory_( !hdrnet_processor_factory.is_null() ? std::move(hdrnet_processor_factory) : base::BindRepeating(HdrNetProcessorImpl::CreateInstance)), config_(config_file_path, base::FilePath(HdrNetConfig::kOverrideHdrNetConfigFile)), still_capture_processor_(std::move(still_capture_processor)), camera_metrics_(CameraMetrics::New()), metadata_logger_({.dump_path = base::FilePath(kMetadataDumpPath)}) { CHECK(gpu_thread_.Start()); config_.SetCallback(base::BindRepeating( &HdrNetStreamManipulator::OnOptionsUpdated, base::Unretained(this))); } HdrNetStreamManipulator::~HdrNetStreamManipulator() { gpu_thread_.PostTaskAsync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::ResetStateOnGpuThread, base::Unretained(this))); gpu_thread_.Stop(); } bool HdrNetStreamManipulator::Initialize( const camera_metadata_t* static_info, CaptureResultCallback result_callback) { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::InitializeOnGpuThread, base::Unretained(this), base::Unretained(static_info), std::move(result_callback)), &ret); return ret; } bool HdrNetStreamManipulator::ConfigureStreams( Camera3StreamConfiguration* stream_config) { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::ConfigureStreamsOnGpuThread, base::Unretained(this), base::Unretained(stream_config)), &ret); return ret; } bool HdrNetStreamManipulator::OnConfiguredStreams( Camera3StreamConfiguration* stream_config) { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::OnConfiguredStreamsOnGpuThread, base::Unretained(this), base::Unretained(stream_config)), &ret); return ret; } bool HdrNetStreamManipulator::ConstructDefaultRequestSettings( android::CameraMetadata* default_request_settings, int type) { return true; } bool HdrNetStreamManipulator::ProcessCaptureRequest( Camera3CaptureDescriptor* request) { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::ProcessCaptureRequestOnGpuThread, base::Unretained(this), base::Unretained(request)), &ret); return ret; } bool HdrNetStreamManipulator::ProcessCaptureResult( Camera3CaptureDescriptor* result) { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::ProcessCaptureResultOnGpuThread, base::Unretained(this), base::Unretained(result)), &ret); return ret; } bool HdrNetStreamManipulator::Notify(camera3_notify_msg_t* msg) { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::NotifyOnGpuThread, base::Unretained(this), base::Unretained(msg)), &ret); return ret; } bool HdrNetStreamManipulator::Flush() { bool ret; gpu_thread_.PostTaskSync( FROM_HERE, base::BindOnce(&HdrNetStreamManipulator::FlushOnGpuThread, base::Unretained(this)), &ret); return ret; } // static HdrNetStreamManipulator::HdrNetBufferInfoList::iterator HdrNetStreamManipulator::FindMatchingBufferInfo( HdrNetStreamManipulator::HdrNetBufferInfoList* list, const HdrNetStreamManipulator::HdrNetStreamContext* const context) { auto it = std::find_if(list->begin(), list->end(), [context](const HdrNetRequestBufferInfo& buf_info) { return buf_info.stream_context == context; }); return it; } HdrNetStreamManipulator::HdrNetRequestBufferInfo* HdrNetStreamManipulator::GetBufferInfoWithPendingBlobStream( int frame_number, const camera3_stream_t* blob_stream) { auto iter = request_buffer_info_.find(frame_number); if (iter == request_buffer_info_.end()) { return nullptr; } for (auto& entry : iter->second) { if (entry.blob_result_pending && entry.stream_context->original_stream == blob_stream) { return &entry; } } return nullptr; } bool HdrNetStreamManipulator::InitializeOnGpuThread( const camera_metadata_t* static_info, CaptureResultCallback result_callback) { DCHECK(gpu_thread_.IsCurrentThread()); static_info_.acquire(clone_camera_metadata(static_info)); result_callback_ = std::move(result_callback); return true; } bool HdrNetStreamManipulator::ConfigureStreamsOnGpuThread( Camera3StreamConfiguration* stream_config) { DCHECK(gpu_thread_.IsCurrentThread()); // Clear the stream configuration from the previous session. ResetStateOnGpuThread(); if (VLOG_IS_ON(1)) { VLOGF(1) << "Before stream manipulation:"; for (const auto* s : stream_config->GetStreams()) { VLOGF(1) << GetDebugString(s); } } base::span<camera3_stream_t* const> client_requested_streams = stream_config->GetStreams(); std::vector<camera3_stream_t*> modified_streams; int num_yuv_streams = 0; int num_blob_streams = 0; for (size_t i = 0; i < client_requested_streams.size(); ++i) { camera3_stream_t* s = client_requested_streams[i]; if (s->stream_type != CAMERA3_STREAM_OUTPUT) { // Only output buffers are supported. modified_streams.push_back(s); continue; } if (s->format == HAL_PIXEL_FORMAT_YCbCr_420_888 || s->format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED || s->format == HAL_PIXEL_FORMAT_BLOB) { if (s->format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED && (s->usage & GRALLOC_USAGE_HW_CAMERA_ZSL) == GRALLOC_USAGE_HW_CAMERA_ZSL) { // Ignore ZSL streams. modified_streams.push_back(s); continue; } // TODO(jcliang): See if we need to use 10-bit YUV (i.e. with format // HAL_PIXEL_FORMAT_YCBCR_P010); HdrNetStreamContext* context = CreateHdrNetStreamContext(s, HAL_PIXEL_FORMAT_YCbCr_420_888); // TODO(jcliang): We may need to treat YUV stream with maximum resolution // specially and mark it here, since it's what we use in YUV reprocessing. switch (context->mode) { case HdrNetStreamContext::Mode::kReplaceYuv: modified_streams.push_back(context->hdrnet_stream.get()); ++num_yuv_streams; hdrnet_metrics_.max_yuv_stream_size = std::max(static_cast<int>(context->hdrnet_stream->width * context->hdrnet_stream->height), hdrnet_metrics_.max_yuv_stream_size); break; case HdrNetStreamContext::Mode::kAppendWithBlob: DCHECK_EQ(s->format, HAL_PIXEL_FORMAT_BLOB); still_capture_processor_->Initialize(s, result_callback_); modified_streams.push_back(s); modified_streams.push_back(context->hdrnet_stream.get()); ++num_blob_streams; hdrnet_metrics_.max_blob_stream_size = std::max(static_cast<int>(context->hdrnet_stream->width * context->hdrnet_stream->height), hdrnet_metrics_.max_blob_stream_size); break; } } } stream_config->SetStreams(modified_streams); hdrnet_metrics_.num_concurrent_hdrnet_streams = hdrnet_stream_context_.size(); bool has_different_aspect_ratio = false; for (size_t i = 1; i < hdrnet_stream_context_.size(); ++i) { const auto* s1 = hdrnet_stream_context_[i - 1]->hdrnet_stream.get(); const auto* s2 = hdrnet_stream_context_[i]->hdrnet_stream.get(); if (s1->width * s2->height != s2->width * s1->height) { has_different_aspect_ratio = true; break; } } if (num_yuv_streams == 1) { if (num_blob_streams == 0) { hdrnet_metrics_.stream_config = HdrnetStreamConfiguration::kSingleYuvStream; } else { hdrnet_metrics_.stream_config = HdrnetStreamConfiguration::kSingleYuvStreamWithBlob; } } else if (num_yuv_streams > 1) { if (num_blob_streams == 0) { hdrnet_metrics_.stream_config = has_different_aspect_ratio ? HdrnetStreamConfiguration:: kMultipleYuvStreamsOfDifferentAspectRatio : HdrnetStreamConfiguration::kMultipleYuvStreams; } else { hdrnet_metrics_.stream_config = has_different_aspect_ratio ? HdrnetStreamConfiguration:: kMultipleYuvStreamsOfDifferentAspectRatioWithBlob : HdrnetStreamConfiguration::kMultipleYuvStreamsWithBlob; } } if (VLOG_IS_ON(1)) { VLOGF(1) << "After stream manipulation:"; for (const auto* s : stream_config->GetStreams()) { VLOGF(1) << GetDebugString(s); } } return true; } bool HdrNetStreamManipulator::OnConfiguredStreamsOnGpuThread( Camera3StreamConfiguration* stream_config) { DCHECK(gpu_thread_.IsCurrentThread()); // Restore HDRnet streams to the original streams. if (VLOG_IS_ON(1)) { VLOGF(1) << "Before stream manipulation:"; for (const auto* s : stream_config->GetStreams()) { VLOGF(1) << GetDebugString(s); } } base::span<camera3_stream_t* const> modified_streams = stream_config->GetStreams(); std::vector<camera3_stream_t*> restored_streams; for (auto* modified_stream : modified_streams) { HdrNetStreamContext* context = GetHdrNetContextFromHdrNetStream(modified_stream); if (!context) { // Not a stream that we replaced, so pass to client directly. restored_streams.push_back(modified_stream); continue; } switch (context->mode) { case HdrNetStreamContext::Mode::kReplaceYuv: { // Propagate the fields set by HAL back to the client. camera3_stream_t* original_stream = context->original_stream; original_stream->max_buffers = modified_stream->max_buffers; original_stream->usage = modified_stream->usage; original_stream->priv = modified_stream->priv; restored_streams.push_back(original_stream); break; } case HdrNetStreamContext::Mode::kAppendWithBlob: // Skip the HDRnet stream we added for BLOB. break; } } stream_config->SetStreams(restored_streams); if (VLOG_IS_ON(1)) { VLOGF(1) << "After stream manipulation:"; for (const auto* s : stream_config->GetStreams()) { VLOGF(1) << GetDebugString(s); } } bool success = SetUpPipelineOnGpuThread(); if (!success) { LOGF(ERROR) << "Cannot set up HDRnet pipeline"; return false; } return true; } bool HdrNetStreamManipulator::ProcessCaptureRequestOnGpuThread( Camera3CaptureDescriptor* request) { DCHECK(gpu_thread_.IsCurrentThread()); if (VLOG_IS_ON(2)) { VLOGFID(2, request->frame_number()) << " Got request:"; if (request->GetInputBuffer()) { VLOGF(2) << "\t" << GetDebugString(request->GetInputBuffer()->stream); } for (const auto& request_buffer : request->GetOutputBuffers()) { VLOGF(2) << "\t" << GetDebugString(request_buffer.stream); } } bool skip_hdrnet_processing = false; base::span<const uint8_t> tm_mode = request->GetMetadata<uint8_t>(ANDROID_TONEMAP_MODE); if (!tm_mode.empty() && (tm_mode[0] == ANDROID_TONEMAP_MODE_CONTRAST_CURVE || tm_mode[0] == ANDROID_TONEMAP_MODE_GAMMA_VALUE || tm_mode[0] == ANDROID_TONEMAP_MODE_PRESET_CURVE)) { skip_hdrnet_processing = true; } if (request->GetInputBuffer() != nullptr) { // Skip reprocessing requests. We can't touch the output buffers of a // reprocessing request since they have to be produced from the given input // buffer. return true; } for (auto& context : hdrnet_stream_context_) { context->processor->SetOptions( {.metadata_logger = options_.log_frame_metadata ? &metadata_logger_ : nullptr}); } // First, pick the set of HDRnet stream that we will put into the request. base::span<const camera3_stream_buffer_t> client_output_buffers = request->GetOutputBuffers(); std::vector<camera3_stream_buffer_t> modified_output_buffers; HdrNetBufferInfoList hdrnet_buf_to_add; for (const auto& request_buffer : client_output_buffers) { HdrNetStreamContext* stream_context = GetHdrNetContextFromRequestedStream(request_buffer.stream); if (!stream_context) { // Not a stream that we care, so simply pass through to HAL. modified_output_buffers.push_back(request_buffer); continue; } // Only change the metadata when the client request settings is not null. // This is mainly to make the CTS tests happy, as some test cases set null // settings and if we change that the vendor camera HAL may not handle the // incremental changes well. if (request->has_metadata()) { stream_context->processor->WriteRequestParameters(request); } switch (stream_context->mode) { case HdrNetStreamContext::Mode::kReplaceYuv: { auto is_compatible = [stream_context](const HdrNetRequestBufferInfo& buf_info) { return (buf_info.stream_context->mode == HdrNetStreamContext::Mode::kReplaceYuv) && HaveSameAspectRatio( buf_info.stream_context->hdrnet_stream.get(), stream_context->hdrnet_stream.get()); }; auto it = std::find_if(hdrnet_buf_to_add.begin(), hdrnet_buf_to_add.end(), is_compatible); if (it != hdrnet_buf_to_add.end()) { // Request only one stream and produce the other smaller buffers // through downscaling. This is more efficient than running HDRnet // processor for each buffer. if (stream_context->hdrnet_stream->width > it->stream_context->hdrnet_stream->width) { it->stream_context = stream_context; } it->client_requested_yuv_buffers.push_back(request_buffer); } else { HdrNetRequestBufferInfo buf_info(stream_context, {request_buffer}); buf_info.skip_hdrnet_processing = skip_hdrnet_processing; hdrnet_buf_to_add.emplace_back(std::move(buf_info)); } break; } case HdrNetStreamContext::Mode::kAppendWithBlob: { DCHECK_EQ(request_buffer.stream->format, HAL_PIXEL_FORMAT_BLOB); // Defer the final BLOB buffer to the StillCaptureProcessor as we'll be // handling the BLOB metadata and YUV buffer asynchronously. camera3_capture_request_t* locked_request = request->LockForRequest(); still_capture_processor_->QueuePendingOutputBuffer( request->frame_number(), request_buffer, locked_request->settings); request->Unlock(); // Still queue the BLOB buffer so that we can extract the metadata. modified_output_buffers.push_back(request_buffer); // Finally queue the HDRnet YUV buffer that will be used to produce the // BLOB image. HdrNetRequestBufferInfo buf_info(stream_context, {}); buf_info.blob_result_pending = true; buf_info.blob_intermediate_yuv_pending = true; buf_info.skip_hdrnet_processing = skip_hdrnet_processing; hdrnet_buf_to_add.emplace_back(std::move(buf_info)); break; } } } // After we have the set of HdrNet streams, allocate the HdrNet buffers for // the request. for (auto& info : hdrnet_buf_to_add) { std::optional<int> buffer_index = info.stream_context->PopBuffer(); if (!buffer_index) { // TODO(jcliang): This is unlikely, but we should report a buffer error in // this case. return false; } info.buffer_index = *buffer_index; modified_output_buffers.push_back(camera3_stream_buffer_t{ .stream = info.stream_context->hdrnet_stream.get(), .buffer = const_cast<buffer_handle_t*>( &info.stream_context->shared_images[*buffer_index].buffer()), .status = CAMERA3_BUFFER_STATUS_OK, .acquire_fence = -1, .release_fence = -1, }); } uint32_t frame_number = request->frame_number(); request_buffer_info_.insert({frame_number, std::move(hdrnet_buf_to_add)}); request->SetOutputBuffers(modified_output_buffers); if (VLOG_IS_ON(2)) { VLOGFID(2, frame_number) << "Modified request:"; base::span<const camera3_stream_buffer_t> output_buffers = request->GetOutputBuffers(); for (const auto& request_buffer : output_buffers) { VLOGF(2) << "\t" << GetDebugString(request_buffer.stream); } } return true; } bool HdrNetStreamManipulator::ProcessCaptureResultOnGpuThread( Camera3CaptureDescriptor* result) { DCHECK(gpu_thread_.IsCurrentThread()); if (VLOG_IS_ON(2)) { VLOGFID(2, result->frame_number()) << "Got result:"; if (result->GetInputBuffer()) { VLOGF(2) << "\t" << GetDebugString(result->GetInputBuffer()->stream); } for (const auto& hal_result_buffer : result->GetOutputBuffers()) { VLOGF(2) << "\t" << GetDebugString(hal_result_buffer.stream); } } if (result->has_metadata()) { if (options_.hdrnet_enable) { // Result metadata may come before the buffers due to partial results. for (const auto& context : hdrnet_stream_context_) { // TODO(jcliang): Update the LUT textures once and share it with all // processors. context->processor->ProcessResultMetadata(result); } } } if (result->num_output_buffers() == 0) { return true; } std::vector<camera3_stream_buffer_t> hdrnet_buffer_to_process; std::vector<camera3_stream_buffer_t> output_buffers_to_client; ExtractHdrNetBuffersToProcess( result->frame_number(), result->GetOutputBuffers(), &hdrnet_buffer_to_process, &output_buffers_to_client); auto clean_up = [&]() { // Send back the buffers with our buffer set. result->SetOutputBuffers(output_buffers_to_client); // Remove a pending request if the YUV buffers are done rendering and the // pending BLOB buffer is received. HdrNetBufferInfoList& pending_request_buffers = request_buffer_info_[result->frame_number()]; for (auto it = pending_request_buffers.begin(); it != pending_request_buffers.end();) { if (it->client_requested_yuv_buffers.empty() && !it->blob_result_pending && !it->blob_intermediate_yuv_pending) { it = pending_request_buffers.erase(it); } else { ++it; } } if (pending_request_buffers.empty()) { VLOGFID(2, result->frame_number()) << "Done processing all pending buffers"; request_buffer_info_.erase(result->frame_number()); } if (VLOG_IS_ON(2)) { VLOGFID(2, result->frame_number()) << "Modified result:"; base::span<const camera3_stream_buffer_t> output_buffers = result->GetOutputBuffers(); for (const auto& buffer : output_buffers) { VLOGF(2) << "\t" << GetDebugString(buffer.stream); } } }; if (hdrnet_buffer_to_process.empty()) { clean_up(); return true; } HdrNetBufferInfoList& pending_request_buffers = request_buffer_info_[result->frame_number()]; // Process each HDRnet buffer in this capture result and produce the client // requested output buffers associated with each HDRnet buffer. for (auto& hdrnet_buffer : hdrnet_buffer_to_process) { HdrNetStreamContext* stream_context = GetHdrNetContextFromHdrNetStream(hdrnet_buffer.stream); auto request_buffer_info = FindMatchingBufferInfo(&pending_request_buffers, stream_context); DCHECK(request_buffer_info != pending_request_buffers.end()); if (options_.denoiser_enable) { // Run the denoiser. SharedImage& input_img = stream_context->shared_images[request_buffer_info->buffer_index]; Texture2DDescriptor input_luma = { .id = static_cast<GLint>(input_img.y_texture().handle()), .internal_format = input_img.y_texture().internal_format(), .width = input_img.y_texture().width(), .height = input_img.y_texture().height(), }; Texture2DDescriptor input_chroma = { .id = static_cast<GLint>(input_img.uv_texture().handle()), .internal_format = input_img.uv_texture().internal_format(), .width = input_img.uv_texture().width(), .height = input_img.uv_texture().height(), }; SharedImage& output_img = stream_context->denoiser_intermediate; Texture2DDescriptor output_luma = { .id = static_cast<GLint>(output_img.y_texture().handle()), .internal_format = output_img.y_texture().internal_format(), .width = output_img.y_texture().width(), .height = output_img.y_texture().height(), }; Texture2DDescriptor output_chroma = { .id = static_cast<GLint>(output_img.uv_texture().handle()), .internal_format = output_img.uv_texture().internal_format(), .width = output_img.uv_texture().width(), .height = output_img.uv_texture().height(), }; stream_context->denoiser->RunIirDenoise( input_luma, input_chroma, output_luma, output_chroma, {.iir_temporal_convergence = options_.iir_temporal_convergence, .spatial_strength = options_.spatial_strength, .num_spatial_passes = options_.num_spatial_passes, .reset_temporal_buffer = stream_context->should_reset_temporal_buffer}); if (stream_context->should_reset_temporal_buffer) { stream_context->should_reset_temporal_buffer = false; } } std::vector<buffer_handle_t> buffers_to_render; if (!GetBuffersToRender(stream_context, &(*request_buffer_info), &buffers_to_render)) { return false; } // Run the HDRNet pipeline and write to the buffers. HdrNetConfig::Options processor_config = PrepareProcessorConfig(result, *request_buffer_info); const SharedImage& image = options_.denoiser_enable ? stream_context->denoiser_intermediate : stream_context->shared_images[request_buffer_info->buffer_index]; request_buffer_info->release_fence = stream_context->processor->Run( result->frame_number(), processor_config, image, base::ScopedFD(hdrnet_buffer.release_fence), buffers_to_render, &hdrnet_metrics_); OnBuffersRendered(result->frame_number(), stream_context, &(*request_buffer_info), &output_buffers_to_client); } clean_up(); return true; } bool HdrNetStreamManipulator::NotifyOnGpuThread(camera3_notify_msg_t* msg) { DCHECK(gpu_thread_.IsCurrentThread()); // Free up buffers in case of error. if (msg->type == CAMERA3_MSG_ERROR) { camera3_error_msg_t& error = msg->message.error; VLOGFID(1, error.frame_number) << "Got error notify:" << " stream=" << error.error_stream << " errorcode=" << error.error_code; HdrNetStreamContext* stream_context = GetHdrNetContextFromHdrNetStream(error.error_stream); switch (error.error_code) { case CAMERA3_MSG_ERROR_DEVICE: // Nothing we can do here. Simply restore the stream and forward the // error. case CAMERA3_MSG_ERROR_RESULT: // Result metadata may not be available. We can still produce the // processed frame using metadata from previous frame. break; case CAMERA3_MSG_ERROR_REQUEST: // There will be no capture result, so simply destroy the associated // RequestContext to free the HdrNet buffers. if (request_buffer_info_.count(error.frame_number) == 0) { break; } request_buffer_info_.erase(error.frame_number); break; case CAMERA3_MSG_ERROR_BUFFER: { // The result buffer will not be available, so recycle the hdrnet // buffer. if (request_buffer_info_.count(error.frame_number) == 0) { break; } HdrNetBufferInfoList& buf_info = request_buffer_info_[error.frame_number]; auto it = FindMatchingBufferInfo(&buf_info, stream_context); if (it != buf_info.end()) { buf_info.erase(it); } if (buf_info.empty()) { request_buffer_info_.erase(error.frame_number); } break; } } // Restore the original stream so the message makes sense to the client. if (stream_context) { error.error_stream = stream_context->original_stream; } ++hdrnet_metrics_.errors[HdrnetError::kCameraHal3Error]; } return true; } bool HdrNetStreamManipulator::FlushOnGpuThread() { DCHECK(gpu_thread_.IsCurrentThread()); return true; } void HdrNetStreamManipulator::ExtractHdrNetBuffersToProcess( int frame_number, base::span<const camera3_stream_buffer_t> raw_result_buffers, std::vector<camera3_stream_buffer_t>* hdrnet_buffer_to_process, std::vector<camera3_stream_buffer_t>* output_buffers_to_client) { DCHECK(hdrnet_buffer_to_process); DCHECK(output_buffers_to_client); for (const auto& hal_result_buffer : raw_result_buffers) { HdrNetStreamContext* hdrnet_stream_context = GetHdrNetContextFromHdrNetStream(hal_result_buffer.stream); if (hdrnet_stream_context) { hdrnet_buffer_to_process->push_back(hal_result_buffer); continue; } // The buffer is not a HDRnet buffer we added, but it may be a BLOB // buffer that a kAppendWithBlob HDRnet stream is associated with. if (hal_result_buffer.stream->format == HAL_PIXEL_FORMAT_BLOB) { HdrNetStreamContext* associated_stream_context = GetHdrNetContextFromRequestedStream(hal_result_buffer.stream); HdrNetRequestBufferInfo* request_info = GetBufferInfoWithPendingBlobStream(frame_number, hal_result_buffer.stream); if (associated_stream_context && request_info) { DCHECK_EQ(associated_stream_context->mode, HdrNetStreamContext::Mode::kAppendWithBlob); still_capture_processor_->QueuePendingAppsSegments( frame_number, *hal_result_buffer.buffer); request_info->blob_result_pending = false; continue; } } // Not a buffer that we added or depend on, so pass to the client // directly. output_buffers_to_client->push_back(hal_result_buffer); } } bool HdrNetStreamManipulator::GetBuffersToRender( HdrNetStreamContext* stream_context, HdrNetRequestBufferInfo* request_buffer_info, std::vector<buffer_handle_t>* buffers_to_write) { DCHECK(stream_context); DCHECK(request_buffer_info); DCHECK(buffers_to_write); switch (stream_context->mode) { case HdrNetStreamContext::Mode::kReplaceYuv: // For normal YUV buffers: HDRnet pipeline writes to the client output // buffers directly. All the buffers in |request_buffer_info| having the // same aspect ratio as |stream_context| can be rendered in the same // batch. for (auto& requested_buffer : request_buffer_info->client_requested_yuv_buffers) { if (!HaveSameAspectRatio(stream_context->hdrnet_stream.get(), requested_buffer.stream)) { continue; } if (requested_buffer.acquire_fence != -1) { if (sync_wait(requested_buffer.acquire_fence, kDefaultSyncWaitTimeoutMs) != 0) { LOGF(WARNING) << "sync_wait timeout on acquiring requested buffer"; // TODO(jcliang): We should trigger a notify message of // buffer error here. ++hdrnet_metrics_.errors[HdrnetError::kSyncWaitError]; return false; } close(requested_buffer.acquire_fence); requested_buffer.acquire_fence = -1; } buffers_to_write->push_back(*requested_buffer.buffer); } hdrnet_metrics_.max_output_buffers_rendered = std::max(static_cast<int>(buffers_to_write->size()), hdrnet_metrics_.max_output_buffers_rendered); break; case HdrNetStreamContext::Mode::kAppendWithBlob: // For BLOB buffers: HDRnet writes to the intermediate buffer, // which will then be encoded into the JPEG image client // requested. buffers_to_write->push_back(*stream_context->still_capture_intermediate); ++hdrnet_metrics_.num_still_shot_taken; break; } return true; } HdrNetConfig::Options HdrNetStreamManipulator::PrepareProcessorConfig( Camera3CaptureDescriptor* result, const HdrNetRequestBufferInfo& buf_info) const { // Run the HDRNet pipeline and write to the buffers. HdrNetConfig::Options run_options = options_; // Use the HDR ratio calculated by Gcam AE if available. std::optional<float> gcam_ae_hdr_ratio = result->feature_metadata().hdr_ratio; if (gcam_ae_hdr_ratio) { run_options.hdr_ratio = *result->feature_metadata().hdr_ratio; DVLOGFID(1, result->frame_number()) << "Using HDR ratio=" << run_options.hdr_ratio; } // Disable HDRnet processing completely if the tonemap mode is set to contrast // curve, gamma value, or preset curve. if (buf_info.skip_hdrnet_processing) { run_options.hdrnet_enable = false; DVLOGFID(1, result->frame_number()) << "Disable HDRnet processing"; } return run_options; } void HdrNetStreamManipulator::OnBuffersRendered( int frame_number, HdrNetStreamContext* stream_context, HdrNetRequestBufferInfo* request_buffer_info, std::vector<camera3_stream_buffer_t>* output_buffers_to_client) { DCHECK(stream_context); DCHECK(request_buffer_info); DCHECK(output_buffers_to_client); switch (stream_context->mode) { case HdrNetStreamContext::Mode::kReplaceYuv: // Assign the release fence to all client-requested buffers the // HDRnet pipeline writes to. The FD ownership will be passed to // the client. for (auto& requested_buffer : request_buffer_info->client_requested_yuv_buffers) { if (!HaveSameAspectRatio(stream_context->hdrnet_stream.get(), requested_buffer.stream)) { continue; } requested_buffer.release_fence = DupWithCloExec(request_buffer_info->release_fence.get()).release(); output_buffers_to_client->push_back(requested_buffer); } request_buffer_info->client_requested_yuv_buffers.clear(); break; case HdrNetStreamContext::Mode::kAppendWithBlob: // The JPEG result buffer will be produced by // |still_capture_processor_| asynchronously. still_capture_processor_->QueuePendingYuvImage( frame_number, *stream_context->still_capture_intermediate); request_buffer_info->blob_intermediate_yuv_pending = false; break; } } bool HdrNetStreamManipulator::SetUpPipelineOnGpuThread() { DCHECK(gpu_thread_.IsCurrentThread()); if (!egl_context_) { egl_context_ = EglContext::GetSurfacelessContext(); if (!egl_context_->IsValid()) { LOGF(ERROR) << "Failed to create EGL context"; ++hdrnet_metrics_.errors[HdrnetError::kInitializationError]; return false; } } if (!egl_context_->MakeCurrent()) { LOGF(ERROR) << "Failed to make EGL context current"; ++hdrnet_metrics_.errors[HdrnetError::kInitializationError]; return false; } std::vector<Size> all_output_sizes; for (const auto& context : hdrnet_stream_context_) { all_output_sizes.push_back( Size(context->hdrnet_stream->width, context->hdrnet_stream->height)); } const camera_metadata_t* locked_static_info = static_info_.getAndLock(); for (const auto& context : hdrnet_stream_context_) { camera3_stream_t* stream = context->hdrnet_stream.get(); Size stream_size(stream->width, stream->height); std::vector<Size> viable_output_sizes; for (const auto& s : all_output_sizes) { if (s.width <= stream_size.width && s.height <= stream_size.height) { viable_output_sizes.push_back(s); } } context->processor = hdrnet_processor_factory_.Run( locked_static_info, gpu_thread_.task_runner()); context->denoiser = SpatiotemporalDenoiser::CreateInstance( {.frame_width = static_cast<int>(stream_size.width), .frame_height = static_cast<int>(stream_size.height), .mode = SpatiotemporalDenoiser::Mode::kIirMode}); if (!context->denoiser) { LOGF(ERROR) << "Failed to initialize Spatiotemporal denoiser"; ++hdrnet_metrics_.errors[HdrnetError::kInitializationError]; return false; } context->processor->Initialize(stream_size, viable_output_sizes); if (!context->processor) { LOGF(ERROR) << "Failed to initialize HDRnet processor"; ++hdrnet_metrics_.errors[HdrnetError::kInitializationError]; return false; } constexpr uint32_t kBufferUsage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_TEXTURE; // Allocate the hdrnet buffers. constexpr int kNumExtraBuffer = kMaxDenoiserBurstLength + 5; for (int i = 0; i < stream->max_buffers + kNumExtraBuffer; ++i) { ScopedBufferHandle buffer = CameraBufferManager::AllocateScopedBuffer( stream->width, stream->height, stream->format, kBufferUsage); if (!buffer) { LOGF(ERROR) << "Cannot allocate HDRnet buffers"; ++hdrnet_metrics_.errors[HdrnetError::kInitializationError]; return false; } SharedImage shared_image = SharedImage::CreateFromBuffer( *buffer, Texture2D::Target::kTarget2D, true); if (!shared_image.y_texture().IsValid() || !shared_image.uv_texture().IsValid()) { LOGF(ERROR) << "Cannot create SharedImage for the HDRnet buffer"; ++hdrnet_metrics_.errors[HdrnetError::kInitializationError]; return false; } // Let the SharedImage own the buffer. shared_image.SetDestructionCallback( base::BindOnce([](ScopedBufferHandle buffer) {}, std::move(buffer))); context->shared_images.emplace_back(std::move(shared_image)); context->PushBuffer(i, base::ScopedFD()); } if (context->original_stream->format == HAL_PIXEL_FORMAT_BLOB) { LOGF(INFO) << "Allocate still capture intermediate"; context->still_capture_intermediate = CameraBufferManager::AllocateScopedBuffer( stream->width, stream->height, HAL_PIXEL_FORMAT_YCBCR_420_888, kBufferUsage); } { ScopedBufferHandle buffer = CameraBufferManager::AllocateScopedBuffer( stream->width, stream->height, stream->format, kBufferUsage); if (!buffer) { LOGF(ERROR) << "Cannot allocate denoiser intermediate buffer"; return false; } SharedImage shared_image = SharedImage::CreateFromBuffer( *buffer, Texture2D::Target::kTarget2D, true); if (!shared_image.y_texture().IsValid() || !shared_image.uv_texture().IsValid()) { LOGF(ERROR) << "Cannot create SharedImage for the denoiser intermediate buffer"; return false; } // Let the SharedImage own the buffer. shared_image.SetDestructionCallback( base::BindOnce([](ScopedBufferHandle buffer) {}, std::move(buffer))); context->denoiser_intermediate = std::move(shared_image); } } static_info_.unlock(locked_static_info); return true; } void HdrNetStreamManipulator::ResetStateOnGpuThread() { DCHECK(gpu_thread_.IsCurrentThread()); still_capture_processor_->Reset(); request_buffer_info_.clear(); hdrnet_stream_context_.clear(); request_stream_mapping_.clear(); result_stream_mapping_.clear(); UploadMetrics(); hdrnet_metrics_ = HdrnetMetrics(); } HdrNetStreamManipulator::HdrNetStreamContext* HdrNetStreamManipulator::CreateHdrNetStreamContext(camera3_stream_t* requested, uint32_t replace_format) { std::unique_ptr<HdrNetStreamContext> context = std::make_unique<HdrNetStreamContext>(); context->original_stream = requested; context->hdrnet_stream = std::make_unique<camera3_stream_t>(*requested); context->hdrnet_stream->format = replace_format; if (requested->format == HAL_PIXEL_FORMAT_BLOB) { // We still need the BLOB stream for extracting the JPEG APPs segments, so // we add a new YUV stream instead of replacing the BLOB stream. context->mode = HdrNetStreamContext::Mode::kAppendWithBlob; } HdrNetStreamContext* addr = context.get(); request_stream_mapping_[requested] = addr; result_stream_mapping_[context->hdrnet_stream.get()] = addr; hdrnet_stream_context_.emplace_back(std::move(context)); return addr; } HdrNetStreamManipulator::HdrNetStreamContext* HdrNetStreamManipulator::GetHdrNetContextFromRequestedStream( camera3_stream_t* requested) { auto iter = request_stream_mapping_.find(requested); if (iter == request_stream_mapping_.end()) { return nullptr; } return iter->second; } HdrNetStreamManipulator::HdrNetStreamContext* HdrNetStreamManipulator::GetHdrNetContextFromHdrNetStream( camera3_stream_t* hdrnet) { auto iter = result_stream_mapping_.find(hdrnet); if (iter == result_stream_mapping_.end()) { return nullptr; } return iter->second; } void HdrNetStreamManipulator::OnOptionsUpdated(const base::Value& json_values) { LoadIfExist(json_values, kHdrNetEnableKey, &options_.hdrnet_enable); LoadIfExist(json_values, kDumpBufferKey, &options_.dump_buffer); LoadIfExist(json_values, kHdrRatioKey, &options_.hdr_ratio); LoadIfExist(json_values, kMaxGainBlendThresholdKey, &options_.max_gain_blend_threshold); LoadIfExist(json_values, kSpatialFilterSigma, &options_.spatial_filter_sigma); LoadIfExist(json_values, kRangeFilterSigma, &options_.range_filter_sigma); LoadIfExist(json_values, kIirFilterStrength, &options_.iir_filter_strength); bool denoiser_enable; if (LoadIfExist(json_values, kDenoiserEnable, &denoiser_enable)) { if (!options_.denoiser_enable && options_.denoiser_enable) { // Reset the denoiser temporal buffer whenever we switch on the denoiser // to avoid artifacts caused by stale data. for (auto& c : hdrnet_stream_context_) { c->should_reset_temporal_buffer = true; } } options_.denoiser_enable = denoiser_enable; } LoadIfExist(json_values, kDenoiserIirTemporalConvergence, &options_.iir_temporal_convergence); LoadIfExist(json_values, kDenoiserNumSpatialPasses, &options_.num_spatial_passes); LoadIfExist(json_values, kDenoiserSpatialStrength, &options_.spatial_strength); DCHECK_GE(options_.hdr_ratio, 1.0f); DCHECK_LE(options_.max_gain_blend_threshold, 1.0f); DCHECK_GE(options_.max_gain_blend_threshold, 0.0f); DCHECK_LE(options_.iir_filter_strength, 1.0f); DCHECK_GE(options_.iir_filter_strength, 0.0f); bool log_frame_metadata; if (LoadIfExist(json_values, kLogFrameMetadataKey, &log_frame_metadata)) { if (options_.log_frame_metadata && !log_frame_metadata) { // Dump frame metadata when metadata logging if turned off. metadata_logger_.DumpMetadata(); metadata_logger_.Clear(); } options_.log_frame_metadata = log_frame_metadata; } DVLOGF(1) << "HDRnet config:" << " hdrnet_enable=" << options_.hdrnet_enable << " dump_buffer=" << options_.dump_buffer << " log_frame_metadata=" << options_.log_frame_metadata << " hdr_ratio=" << options_.hdr_ratio << " max_gain_blend_threshold=" << options_.max_gain_blend_threshold << " spatial_filter_sigma=" << options_.spatial_filter_sigma << " range_filter_sigma=" << options_.range_filter_sigma << " iir_filter_strength=" << options_.iir_filter_strength; } void HdrNetStreamManipulator::UploadMetrics() { if (hdrnet_metrics_.errors.empty() && (hdrnet_metrics_.num_concurrent_hdrnet_streams == 0 || hdrnet_metrics_.num_frames_processed == 0)) { // Avoid uploading metrics short-lived session that does not really do // anything. Short-lived session can happen when we first open a camera, // where the framework and the HAL may re-configure the streams more than // once. return; } camera_metrics_->SendHdrnetStreamConfiguration(hdrnet_metrics_.stream_config); camera_metrics_->SendHdrnetMaxStreamSize(HdrnetStreamType::kYuv, hdrnet_metrics_.max_yuv_stream_size); camera_metrics_->SendHdrnetMaxStreamSize( HdrnetStreamType::kBlob, hdrnet_metrics_.max_blob_stream_size); camera_metrics_->SendHdrnetNumConcurrentStreams( hdrnet_metrics_.num_concurrent_hdrnet_streams); camera_metrics_->SendHdrnetMaxOutputBuffersRendered( hdrnet_metrics_.max_output_buffers_rendered); camera_metrics_->SendHdrnetNumStillShotsTaken( hdrnet_metrics_.num_still_shot_taken); if (hdrnet_metrics_.errors.empty()) { camera_metrics_->SendHdrnetError(HdrnetError::kNoError); } else { for (auto [e, c] : hdrnet_metrics_.errors) { if (e == HdrnetError::kNoError) { NOTREACHED(); continue; } if (c > 0) { // Since we want to normalize all our metrics by camera sessions, we // only report whether an type of error is happened and print the number // of error occurrences as error. LOGF(ERROR) << "There were " << c << " occurrences of error " << static_cast<int>(e); camera_metrics_->SendHdrnetError(e); } } } if (hdrnet_metrics_.num_frames_processed > 0) { camera_metrics_->SendHdrnetAvgLatency( HdrnetProcessingType::kPreprocessing, hdrnet_metrics_.accumulated_preprocessing_latency_us / hdrnet_metrics_.num_frames_processed); camera_metrics_->SendHdrnetAvgLatency( HdrnetProcessingType::kRgbPipeline, hdrnet_metrics_.accumulated_rgb_pipeline_latency_us / hdrnet_metrics_.num_frames_processed); camera_metrics_->SendHdrnetAvgLatency( HdrnetProcessingType::kPostprocessing, hdrnet_metrics_.accumulated_postprocessing_latency_us / hdrnet_metrics_.num_frames_processed); } } } // namespace cros
38.08741
80
0.696789
ascii33
a9a93353a3714a7d91319cba525ccf23fcded2fc
6,778
hpp
C++
Nacro/SDK/FN_GameplayTasks_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_GameplayTasks_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_GameplayTasks_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function GameplayTasks.GameplayTasksComponent.OnRep_SimulatedTasks struct UGameplayTasksComponent_OnRep_SimulatedTasks_Params { }; // Function GameplayTasks.GameplayTasksComponent.K2_RunGameplayTask struct UGameplayTasksComponent_K2_RunGameplayTask_Params { TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask* Task; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char Priority; // (Parm, ZeroConstructor, IsPlainOldData) TArray<class UClass*> AdditionalRequiredResources; // (Parm, ZeroConstructor) TArray<class UClass*> AdditionalClaimedResources; // (Parm, ZeroConstructor) EGameplayTaskRunResult ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask.ReadyForActivation struct UGameplayTask_ReadyForActivation_Params { }; // DelegateFunction GameplayTasks.GameplayTask.GenericGameplayTaskDelegate__DelegateSignature struct UGameplayTask_GenericGameplayTaskDelegate__DelegateSignature_Params { }; // Function GameplayTasks.GameplayTask.EndTask struct UGameplayTask_EndTask_Params { }; // Function GameplayTasks.GameplayTask_ClaimResource.ClaimResources struct UGameplayTask_ClaimResource_ClaimResources_Params { TScriptInterface<class UGameplayTaskOwnerInterface> InTaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) TArray<class UClass*> ResourceClasses; // (Parm, ZeroConstructor) unsigned char Priority; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) struct FName TaskInstanceName; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_ClaimResource* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_ClaimResource.ClaimResource struct UGameplayTask_ClaimResource_ClaimResource_Params { TScriptInterface<class UGameplayTaskOwnerInterface> InTaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) class UClass* ResourceClass; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char Priority; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) struct FName TaskInstanceName; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_ClaimResource* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_SpawnActor.SpawnActor struct UGameplayTask_SpawnActor_SpawnActor_Params { TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) struct FVector SpawnLocation; // (Parm, IsPlainOldData) struct FRotator SpawnRotation; // (Parm, IsPlainOldData) class UClass* Class; // (Parm, ZeroConstructor, IsPlainOldData) bool bSpawnOnlyOnAuthority; // (Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_SpawnActor* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_SpawnActor.FinishSpawningActor struct UGameplayTask_SpawnActor_FinishSpawningActor_Params { class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData) class AActor* SpawnedActor; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_SpawnActor.BeginSpawningActor struct UGameplayTask_SpawnActor_BeginSpawningActor_Params { class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData) class AActor* SpawnedActor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GameplayTasks.GameplayTask_WaitDelay.TaskWaitDelay struct UGameplayTask_WaitDelay_TaskWaitDelay_Params { TScriptInterface<class UGameplayTaskOwnerInterface> TaskOwner; // (Parm, ZeroConstructor, IsPlainOldData) float Time; // (Parm, ZeroConstructor, IsPlainOldData) unsigned char Priority; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) class UGameplayTask_WaitDelay* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // DelegateFunction GameplayTasks.GameplayTask_WaitDelay.TaskDelayDelegate__DelegateSignature struct UGameplayTask_WaitDelay_TaskDelayDelegate__DelegateSignature_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
59.982301
173
0.537179
Milxnor
a9a9d46b58bdec91c41d4ec820adf91b9dc9f15a
2,622
cpp
C++
COGengine/src/Behaviors/Slider.cpp
dodoknight/CogEngine
fda1193c2d1258ba9780e1025933d33a8dce2284
[ "MIT" ]
3
2016-06-01T10:14:00.000Z
2016-10-11T15:53:45.000Z
COGengine/src/Behaviors/Slider.cpp
dormantor/ofxCogEngine
fda1193c2d1258ba9780e1025933d33a8dce2284
[ "MIT" ]
null
null
null
COGengine/src/Behaviors/Slider.cpp
dormantor/ofxCogEngine
fda1193c2d1258ba9780e1025933d33a8dce2284
[ "MIT" ]
1
2020-08-15T17:01:00.000Z
2020-08-15T17:01:00.000Z
#include "Slider.h" #include "MsgPayloads.h" #include "ofxCogEngine.h" #include "Scene.h" #include "Node.h" namespace Cog { Slider::Slider(Node* body, Node* text) :body(body), text(text) { } void Slider::Load(Setting& setting) { this->bodyNodeTag = setting.GetItemVal("body"); this->textNodeTag = setting.GetItemVal("text"); if (this->bodyNodeTag.empty()) CogLogError("Slider","Error while loading Slider behavior; expected 'body' attribute in settings"); } void Slider::OnInit() { SubscribeForMessages(ACT_OBJECT_HIT_LOST, ACT_OBJECT_HIT_ENDED, ACT_OBJECT_HIT_OVER, ACT_ATTR_CHANGED); } void Slider::OnStart() { if (body == nullptr) body = owner->GetScene()->FindNodeByTag(bodyNodeTag); if (text == nullptr && !textNodeTag.empty()) text = owner->GetScene()->FindNodeByTag(textNodeTag); if (!body->HasAttr(ATTR_IMGBOUNDS)) { auto image = body->GetMesh<Image>(); body->AddAttr(ATTR_IMGBOUNDS, ofRectangle(0,0,image->GetWidth(), image->GetHeight())); } if (!owner->HasAttr(ATTR_SLIDER_VALUE)) { body->AddAttr(ATTR_SLIDER_VALUE, (int)0); SetValue(0); } } void Slider::SetValue(int percentage) { auto bounds = body->GetAttr<ofRectangle>(ATTR_IMGBOUNDS); string percText = ofToString(percentage) + "%"; text->GetMesh<Text>()->SetText(percText); auto image = body->GetMesh<Image>(); bounds.width = image->GetWidth()*(percentage/100.0f); body->ChangeAttr(ATTR_IMGBOUNDS, bounds); } void Slider::OnMessage(Msg& msg) { if (!msgLocked) { msgLocked = true; if (msg.GetContextNode()->GetId() == owner->GetId()) { if (msg.HasAction(ACT_OBJECT_HIT_OVER)) { // set value according to the position of the mouse auto evt = msg.GetDataPtr<InputEvent>(); auto image = body->GetMesh<Image>(); int width = image->GetWidth(); int absoluteWidth = image->GetWidth()*body->GetTransform().absScale.x*body->GetTransform().scale.x; int absolutePosX = body->GetTransform().absPos.x; float ratio = ofClamp((evt->input->position.x - absolutePosX) / ((float)absoluteWidth), 0, 1); int percentage = ratio * 100; this->SetValue(percentage); owner->ChangeAttr(ATTR_SLIDER_VALUE, (int)percentage); } else if ((msg.HasAction(ACT_OBJECT_HIT_ENDED) || msg.HasAction(ACT_OBJECT_HIT_LOST))) { } else if (msg.HasAction(ACT_ATTR_CHANGED)) { auto changeEvt = msg.GetDataPtr<AttributeChangeEvent>(); if (changeEvt->attribute == ATTR_SLIDER_VALUE) { int percentage = owner->GetAttr<int>(ATTR_SLIDER_VALUE); SetValue(percentage); } } } msgLocked = false; } } }// namespace
30.847059
132
0.681159
dodoknight
a9aaf8fa812fa1b5d662cf452122ccc7c4e2502a
1,065
cpp
C++
2524/5364663_AC_329MS_448K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
2524/5364663_AC_329MS_448K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
2524/5364663_AC_329MS_448K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<cstdio> int GetRoot(int ID,int *father){ if(father[ID]==ID) return ID; return father[ID]=GetRoot(father[ID],father); } int main(){ const int STUDENT_MAX=50000; int studentNum,pairNum,caseID=1; int father[STUDENT_MAX]; bool religionRoot[STUDENT_MAX]; while(true){ scanf("%d%d",&studentNum,&pairNum); if(studentNum==0 && pairNum==0) break; //int *father=new int[studentNum]; for(int i=0;i<studentNum;i++) father[i]=i; while(pairNum-->0){ int left,right; scanf("%d%d",&left,&right); left=GetRoot(left-1,father); right=GetRoot(right-1,father); if(left!=right) father[right]=left; } //bool *religionRoot=new bool[studentNum]; for(int i=0;i<studentNum;i++) religionRoot[i]=false; for(int i=0;i<studentNum;i++) religionRoot[GetRoot(i,father)]=true; int religionCount=0; for(int i=0;i<studentNum;i++) if(religionRoot[i]) religionCount++; printf("Case %d: %d\n",caseID++,religionCount); //delete[] religionRoot; //delete[] father; } return 0; }
24.767442
50
0.635681
vandreas19
a9afacebb66aa4577dfe6c76d84fcddfdd9d3529
16,503
cpp
C++
src/framework/shared/irphandlers/pnp/notpowerpolicyownerstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
994
2015-03-18T21:37:07.000Z
2019-04-26T04:04:14.000Z
src/framework/shared/irphandlers/pnp/notpowerpolicyownerstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
13
2019-06-13T15:58:03.000Z
2022-02-18T22:53:35.000Z
src/framework/shared/irphandlers/pnp/notpowerpolicyownerstatemachine.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
350
2015-03-19T04:29:46.000Z
2019-05-05T23:26:50.000Z
/*++ Copyright (c) Microsoft. All rights reserved. Module Name: NotPowerPolicyOwnerStateMachine.cpp Abstract: This module implements the Not Power Policy Owner state machine for the driver framework. This code was split out from PowerPolicyStateMachine.cpp Author: Environment: Both kernel and user mode Revision History: --*/ #include "pnppriv.hpp" extern "C" { #if defined(EVENT_TRACING) #include "NotPowerPolicyOwnerStateMachine.tmh" #endif } const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerObjectCreatedStates[] = { { PwrPolStart, WdfDevStatePwrPolStarting DEBUGGED_EVENT }, { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStartingStates[] = { { PwrPolPowerUp, WdfDevStatePwrPolStarted DEBUGGED_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStartingFailed DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStartingSucceededStates[] = { { PwrPolPowerDownIoStopped, WdfDevStatePwrPolGotoDx DEBUGGED_EVENT }, { PwrPolStop, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolSurpriseRemove, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolPowerUpHwStarted, WdfDevStatePwrPolGotoD0InD0 TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStartingFailedStates[] = { { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoDxStates[] = { { PwrPolPowerDown, WdfDevStatePwrPolDx DEBUGGED_EVENT }, { PwrPolPowerDownFailed, WdfDevStatePwrPolStartingSucceeded DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoDxInDxStates[] = { { PwrPolPowerDown, WdfDevStatePwrPolDx TRAP_ON_EVENT }, { PwrPolPowerDownFailed, WdfDevStatePwrPolDx TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerDxStates[] = { { PwrPolPowerUpHwStarted, WdfDevStatePwrPolGotoD0 DEBUGGED_EVENT }, { PwrPolStop, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolSurpriseRemove, WdfDevStatePwrPolStopping DEBUGGED_EVENT }, { PwrPolPowerDownIoStopped, WdfDevStatePwrPolGotoDxInDx TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoD0States[] = { { PwrPolPowerUp, WdfDevStatePwrPolStartingSucceeded DEBUGGED_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStartingSucceeded TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerGotoD0InD0States[] = { { PwrPolPowerUp, WdfDevStatePwrPolStartingSucceeded TRAP_ON_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStartingSucceeded TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppedStates[] = { { PwrPolStart, WdfDevStatePwrPolStarting DEBUGGED_EVENT }, { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppingWaitForImplicitPowerDownStates[] = { { PwrPolImplicitPowerDown, WdfDevStatePwrPolStoppingSendStatus DEBUGGED_EVENT }, { PwrPolImplicitPowerDownFailed, WdfDevStatePwrPolStoppingFailed DEBUGGED_EVENT }, { PwrPolPowerDownIoStopped, WdfDevStatePwrPolStoppingPoweringDown DEBUGGED_EVENT }, { PwrPolPowerUpHwStarted, WdfDevStatePwrPolStoppingPoweringUp DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringUpStates[] = { { PwrPolPowerUp, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown DEBUGGED_EVENT }, { PwrPolPowerUpFailed, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown TRAP_ON_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringDownStates[] = { { PwrPolPowerDown, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown DEBUGGED_EVENT }, { PwrPolPowerDownFailed, WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown DEBUGGED_EVENT }, }; const POWER_POLICY_EVENT_TARGET_STATE FxPkgPnp::m_NotPowerPolOwnerRemovedStates[] = { { PwrPolStart, WdfDevStatePwrPolStarting DEBUGGED_EVENT }, { PwrPolRemove, WdfDevStatePwrPolRemoved DEBUGGED_EVENT }, }; const NOT_POWER_POLICY_OWNER_STATE_TABLE FxPkgPnp::m_WdfNotPowerPolicyOwnerStates[] = { // current state // transition function, // target states // count of target states // Queue state // { WdfDevStatePwrPolObjectCreated, NULL, FxPkgPnp::m_NotPowerPolOwnerObjectCreatedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerObjectCreatedStates), TRUE, }, { WdfDevStatePwrPolStarting, FxPkgPnp::NotPowerPolOwnerStarting, FxPkgPnp::m_NotPowerPolOwnerStartingStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStartingStates), FALSE, }, { WdfDevStatePwrPolStarted, FxPkgPnp::NotPowerPolOwnerStarted, NULL, 0, FALSE, }, { WdfDevStatePwrPolStartingSucceeded, NULL, FxPkgPnp::m_NotPowerPolOwnerStartingSucceededStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStartingSucceededStates), TRUE, }, { WdfDevStatePwrPolGotoDx, FxPkgPnp::NotPowerPolOwnerGotoDx, FxPkgPnp::m_NotPowerPolOwnerGotoDxStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoDxStates), FALSE, }, { WdfDevStatePwrPolGotoDxInDx, FxPkgPnp::NotPowerPolOwnerGotoDxInDx, FxPkgPnp::m_NotPowerPolOwnerGotoDxInDxStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoDxInDxStates), FALSE, }, { WdfDevStatePwrPolDx, NULL, FxPkgPnp::m_NotPowerPolOwnerDxStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerDxStates), TRUE, }, { WdfDevStatePwrPolGotoD0, FxPkgPnp::NotPowerPolOwnerGotoD0, FxPkgPnp::m_NotPowerPolOwnerGotoD0States, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoD0States), FALSE, }, { WdfDevStatePwrPolGotoD0InD0, FxPkgPnp::NotPowerPolOwnerGotoD0InD0, FxPkgPnp::m_NotPowerPolOwnerGotoD0InD0States, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerGotoD0InD0States), FALSE, }, { WdfDevStatePwrPolStopping, FxPkgPnp::NotPowerPolOwnerStopping, NULL, 0, FALSE, }, { WdfDevStatePwrPolStoppingSendStatus, FxPkgPnp::NotPowerPolOwnerStoppingSendStatus, NULL, 0, FALSE, }, { WdfDevStatePwrPolStartingFailed, FxPkgPnp::NotPowerPolOwnerStartingFailed, FxPkgPnp::m_NotPowerPolOwnerStartingFailedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStartingFailedStates), TRUE, }, { WdfDevStatePwrPolStoppingFailed, FxPkgPnp::NotPowerPolOwnerStoppingFailed, NULL, 0, FALSE, }, { WdfDevStatePwrPolStopped, NULL, FxPkgPnp::m_NotPowerPolOwnerStoppedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppedStates), TRUE, }, { WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown, NULL, FxPkgPnp::m_NotPowerPolOwnerStoppingWaitForImplicitPowerDownStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppingWaitForImplicitPowerDownStates), TRUE, }, { WdfDevStatePwrPolStoppingPoweringUp, FxPkgPnp::NotPowerPolOwnerStoppingPoweringUp, FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringUpStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringUpStates), FALSE, }, { WdfDevStatePwrPolStoppingPoweringDown, FxPkgPnp::NotPowerPolOwnerStoppingPoweringDown, FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringDownStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerStoppingPoweringDownStates), FALSE, }, { WdfDevStatePwrPolRemoved, FxPkgPnp::NotPowerPolOwnerRemoved, FxPkgPnp::m_NotPowerPolOwnerRemovedStates, ARRAY_SIZE(FxPkgPnp::m_NotPowerPolOwnerRemovedStates), TRUE, }, // the last entry must have WdfDevStatePwrPolNull as the current state { WdfDevStatePwrPolNull, NULL, NULL, 0, FALSE, }, }; VOID FxPkgPnp::NotPowerPolicyOwnerEnterNewState( __in WDF_DEVICE_POWER_POLICY_STATE NewState ) { CPNOT_POWER_POLICY_OWNER_STATE_TABLE entry; WDF_DEVICE_POWER_POLICY_STATE currentState, newState; WDF_DEVICE_POWER_POLICY_NOTIFICATION_DATA data; currentState = m_Device->GetDevicePowerPolicyState(); newState = NewState; while (newState != WdfDevStatePwrPolNull) { DoTraceLevelMessage( GetDriverGlobals(), TRACE_LEVEL_INFORMATION, TRACINGPNPPOWERSTATES, "WDFDEVICE 0x%p !devobj 0x%p entering not power policy owner state " "%!WDF_DEVICE_POWER_POLICY_STATE! from " "%!WDF_DEVICE_POWER_POLICY_STATE!", m_Device->GetHandle(), m_Device->GetDeviceObject(), newState, currentState); if (m_PowerPolicyStateCallbacks != NULL) { // // Callback for leaving the old state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationLeaveState; data.Data.LeaveState.CurrentState = currentState; data.Data.LeaveState.NewState = newState; m_PowerPolicyStateCallbacks->Invoke(currentState, StateNotificationLeaveState, m_Device->GetHandle(), &data); } m_PowerPolicyMachine.m_States.History[ m_PowerPolicyMachine.IncrementHistoryIndex()] = (USHORT) newState; if (m_PowerPolicyStateCallbacks != NULL) { // // Callback for entering the new state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationEnterState; data.Data.EnterState.CurrentState = currentState; data.Data.EnterState.NewState = newState; m_PowerPolicyStateCallbacks->Invoke(newState, StateNotificationEnterState, m_Device->GetHandle(), &data); } m_Device->SetDevicePowerPolicyState(newState); currentState = newState; entry = GetNotPowerPolicyOwnerTableEntry(currentState); // // Call the state handler, if there is one. // if (entry->StateFunc != NULL) { newState = entry->StateFunc(this); } else { newState = WdfDevStatePwrPolNull; } if (m_PowerPolicyStateCallbacks != NULL) { // // Callback for post processing the new state // RtlZeroMemory(&data, sizeof(data)); data.Type = StateNotificationPostProcessState; data.Data.PostProcessState.CurrentState = currentState; m_PowerPolicyStateCallbacks->Invoke(currentState, StateNotificationPostProcessState, m_Device->GetHandle(), &data); } } } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStarting( __inout FxPkgPnp* This ) /*++ Routine Description: Starting the power policy state machine for a device which is not the power policy owner. Tell the power state machine to start up. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PowerProcessEvent(PowerImplicitD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStarted( __inout FxPkgPnp* This ) /*++ Routine Description: Starting the power policy state machine for a device which is not the power policy owner has succeeded. Indicate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PnpProcessEvent(PnpEventPwrPolStarted); return WdfDevStatePwrPolStartingSucceeded; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoDx( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteDx); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoDxInDx( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteDx); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoD0( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerGotoD0InD0( __inout FxPkgPnp* This ) { This->PowerProcessEvent(PowerCompleteD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStopping( __inout FxPkgPnp* This ) /*++ Routine Description: Stopping the power policy state machine for a device which is not the power policy owner. Tell the power state machine to power down. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown --*/ { This->PowerProcessEvent(PowerImplicitD3); return WdfDevStatePwrPolStoppingWaitingForImplicitPowerDown; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingSendStatus( __inout FxPkgPnp* This ) /*++ Routine Description: Stopping the power policy state machine for a device which is not the power policy owner has succeeded. Inidcate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolStopped --*/ { This->PnpProcessEvent(PnpEventPwrPolStopped); return WdfDevStatePwrPolStopped; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStartingFailed( __inout FxPkgPnp* This ) /*++ Routine Description: Starting the power policy state machine for a device which is not the power policy owner has failed. Inidcate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PnpProcessEvent(PnpEventPwrPolStartFailed); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingFailed( __inout FxPkgPnp* This ) /*++ Routine Description: Stopping the power policy state machine for a device which is not the power policy owner has failed. Inidcate status to the pnp state machine. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolStopped --*/ { This->PnpProcessEvent(PnpEventPwrPolStopFailed); return WdfDevStatePwrPolStopped; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingPoweringUp( __inout FxPkgPnp* This ) /*++ Routine Description: Right as we attempted to implicitly power down, a real D0 irp came into the stack. Complete the D0 irp in the power state machine so that the power state machine can process the implicit power irp Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PowerProcessEvent(PowerCompleteD0); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerStoppingPoweringDown( __inout FxPkgPnp* This ) /*++ Routine Description: Right as we attempted to implicitly power down, a real Dx irp came into the stack. Complete the Dx irp in the power state machine so that the power state machine can process the implicit power irp Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { This->PowerProcessEvent(PowerCompleteDx); return WdfDevStatePwrPolNull; } WDF_DEVICE_POWER_POLICY_STATE FxPkgPnp::NotPowerPolOwnerRemoved( __inout FxPkgPnp* This ) /*++ Routine Description: The device is being removed, so prepare for removal. Arguments: This - instance of the state machine Return Value: WdfDevStatePwrPolNull --*/ { // // Since we are not the power policy owner, there is nothing to be done. // Indicate to the PNP state machine that we are ready for removal. // This->PnpProcessEvent(PnpEventPwrPolRemoved); return WdfDevStatePwrPolNull; }
27.782828
108
0.722535
IT-Enthusiast-Nepal
a9b2b139c0e272b416107068aacde7049df4e8de
4,599
hpp
C++
include/System/Xml/Serialization/SerializationSource.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Serialization/SerializationSource.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Serialization/SerializationSource.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Xml.Serialization namespace System::Xml::Serialization { // Forward declaring type: SerializationSource class SerializationSource; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Xml::Serialization::SerializationSource); DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Serialization::SerializationSource*, "System.Xml.Serialization", "SerializationSource"); // Type namespace: System.Xml.Serialization namespace System::Xml::Serialization { // Size: 0x21 #pragma pack(push, 1) // Autogenerated type: System.Xml.Serialization.SerializationSource // [TokenAttribute] Offset: FFFFFFFF class SerializationSource : public ::Il2CppObject { public: public: // private System.Type[] includedTypes // Size: 0x8 // Offset: 0x10 ::ArrayW<::System::Type*> includedTypes; // Field size check static_assert(sizeof(::ArrayW<::System::Type*>) == 0x8); // private System.String namspace // Size: 0x8 // Offset: 0x18 ::StringW namspace; // Field size check static_assert(sizeof(::StringW) == 0x8); // private System.Boolean canBeGenerated // Size: 0x1 // Offset: 0x20 bool canBeGenerated; // Field size check static_assert(sizeof(bool) == 0x1); public: // Get instance field reference: private System.Type[] includedTypes [[deprecated("Use field access instead!")]] ::ArrayW<::System::Type*>& dyn_includedTypes(); // Get instance field reference: private System.String namspace [[deprecated("Use field access instead!")]] ::StringW& dyn_namspace(); // Get instance field reference: private System.Boolean canBeGenerated [[deprecated("Use field access instead!")]] bool& dyn_canBeGenerated(); // public System.Void .ctor(System.String namspace, System.Type[] includedTypes) // Offset: 0xF6D960 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static SerializationSource* New_ctor(::StringW namspace, ::ArrayW<::System::Type*> includedTypes) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Serialization::SerializationSource::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<SerializationSource*, creationType>(namspace, includedTypes))); } // protected System.Boolean BaseEquals(System.Xml.Serialization.SerializationSource other) // Offset: 0xF6D9A0 bool BaseEquals(::System::Xml::Serialization::SerializationSource* other); }; // System.Xml.Serialization.SerializationSource #pragma pack(pop) static check_size<sizeof(SerializationSource), 32 + sizeof(bool)> __System_Xml_Serialization_SerializationSourceSizeCheck; static_assert(sizeof(SerializationSource) == 0x21); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Xml::Serialization::SerializationSource::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Xml::Serialization::SerializationSource::BaseEquals // Il2CppName: BaseEquals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Xml::Serialization::SerializationSource::*)(::System::Xml::Serialization::SerializationSource*)>(&System::Xml::Serialization::SerializationSource::BaseEquals)> { static const MethodInfo* get() { static auto* other = &::il2cpp_utils::GetClassFromName("System.Xml.Serialization", "SerializationSource")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::Serialization::SerializationSource*), "BaseEquals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other}); } };
49.451613
244
0.736682
v0idp
a9b3ad1226ae42c3627be2ad3e8576037e005f94
1,778
cpp
C++
GAMES/SFZ/font.cpp
prashantkamdar/ESPboy_Arduboy2_lib
ee0483c84c21a235e6930597f7839be30fd7a7b1
[ "MIT" ]
16
2020-03-03T12:58:41.000Z
2022-03-21T06:56:48.000Z
GAMES/SFZ/font.cpp
prashantkamdar/ESPboy_Arduboy2_lib
ee0483c84c21a235e6930597f7839be30fd7a7b1
[ "MIT" ]
1
2021-04-25T19:38:21.000Z
2021-04-25T19:38:21.000Z
GAMES/SFZ/font.cpp
prashantkamdar/ESPboy_Arduboy2_lib
ee0483c84c21a235e6930597f7839be30fd7a7b1
[ "MIT" ]
5
2020-03-18T13:56:02.000Z
2021-11-23T08:16:02.000Z
// font.chr // #include "font.h" const unsigned char fontTable[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x1f, 0x0a, 0x1f, 0x00, 0x16, 0x1f, 0x0d, 0x00, 0x0b, 0x04, 0x1a, 0x00, 0x0a, 0x15, 0x1a, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0e, 0x11, 0x00, 0x11, 0x0e, 0x00, 0x00, 0x0a, 0x04, 0x0a, 0x00, 0x04, 0x0e, 0x04, 0x00, 0x10, 0x08, 0x00, 0x00, 0x04, 0x04, 0x04, 0x00, 0x00, 0x10, 0x00, 0x00, 0x08, 0x04, 0x02, 0x00, 0x1f, 0x11, 0x1f, 0x00, 0x01, 0x1f, 0x00, 0x00, 0x1d, 0x15, 0x17, 0x00, 0x15, 0x15, 0x1f, 0x00, 0x07, 0x04, 0x1f, 0x00, 0x17, 0x15, 0x1d, 0x00, 0x1f, 0x15, 0x1d, 0x00, 0x01, 0x01, 0x1f, 0x00, 0x1f, 0x15, 0x1f, 0x00, 0x17, 0x15, 0x1f, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x10, 0x0a, 0x00, 0x00, 0x04, 0x0a, 0x11, 0x00, 0x0a, 0x0a, 0x0a, 0x00, 0x11, 0x0a, 0x04, 0x00, 0x01, 0x15, 0x03, 0x00, 0x1f, 0x15, 0x17, 0x00, 0x1e, 0x05, 0x1e, 0x00, 0x1f, 0x15, 0x0a, 0x00, 0x0e, 0x11, 0x11, 0x00, 0x1f, 0x11, 0x0e, 0x00, 0x1f, 0x15, 0x15, 0x00, 0x1f, 0x05, 0x05, 0x00, 0x0e, 0x11, 0x1d, 0x00, 0x1f, 0x04, 0x1f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x08, 0x10, 0x0f, 0x00, 0x1f, 0x04, 0x1b, 0x00, 0x1f, 0x10, 0x10, 0x00, 0x1f, 0x06, 0x1f, 0x00, 0x1e, 0x04, 0x0f, 0x00, 0x0e, 0x11, 0x0e, 0x00, 0x1f, 0x05, 0x02, 0x00, 0x0e, 0x11, 0x16, 0x00, 0x1f, 0x05, 0x1a, 0x00, 0x12, 0x15, 0x09, 0x00, 0x01, 0x1f, 0x01, 0x00, 0x1f, 0x10, 0x1f, 0x00, 0x0f, 0x10, 0x0f, 0x00, 0x1f, 0x0c, 0x1f, 0x00, 0x1b, 0x04, 0x1b, 0x00, 0x03, 0x1c, 0x03, 0x00, 0x19, 0x15, 0x13, 0x00, 0x00, 0x1f, 0x11, 0x00, 0x02, 0x04, 0x08, 0x00, 0x11, 0x1f, 0x00, 0x00, 0x02, 0x01, 0x02, 0x00, 0x10, 0x10, 0x10, 0x00, };
44.45
52
0.605174
prashantkamdar
a9b5fe775435d0edad617bf0759c549a9ed39bbe
3,743
hpp
C++
src/game/sys/physics/physics_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/sys/physics/physics_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/sys/physics/physics_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
/** An entity that participates in collision resolution ********************** * * * Copyright (c) 2016 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include <core/engine.hpp> #include <core/units.hpp> #include <core/ecs/component.hpp> class b2Body; class b2Fixture; class b2World; class b2RevoluteJoint; namespace lux { namespace sys { namespace physics { class Physics_system; enum class Body_shape { polygon, //< vertices are based on the graphical representation humanoid, circle }; struct Body_definition { bool active = true; bool kinematic=false; Body_shape shape = Body_shape::polygon; float linear_damping = 0.f; float angular_damping = 0.f; bool fixed_rotation = false; bool bullet = false; float friction = 1.f; float resitution = 0.3f; float density = 2.f; glm::vec2 size; bool sensor = false; glm::vec2 velocity{}; float keep_position_force = 0.f; std::vector<glm::vec2> vertices; }; class Dynamic_body_comp : public ecs::Component<Dynamic_body_comp, ecs::Compact_index_policy, ecs::Pool_storage_policy<64, Dynamic_body_comp>> { public: static constexpr const char* name() {return "Dynamic_body";} friend void load_component(ecs::Deserializer& state, Dynamic_body_comp&); friend void save_component(ecs::Serializer& state, const Dynamic_body_comp&); Dynamic_body_comp() = default; Dynamic_body_comp(ecs::Entity_manager& manager, ecs::Entity_handle owner); void apply_force(glm::vec2 f); void foot_friction(bool enable);//< only for humanoids bool has_ground_contact()const; void active(bool e) {_def.active = e;} void kinematic(bool e) {_dirty|=_def.kinematic!=e; _def.kinematic=e;} auto kinematic()const noexcept {return _def.kinematic;} auto velocity()const -> glm::vec2; void velocity(glm::vec2 v)const; auto mass()const -> float; auto size()const {return _size;} auto grounded()const {return _grounded;} auto ground_normal()const {return _ground_normal;} auto calc_aabb()const -> glm::vec4; private: friend class Physics_system; mutable Body_definition _def; std::unique_ptr<b2Body, void(*)(b2Body*)> _body {nullptr, +[](b2Body*){}}; b2Fixture* _fixture_foot = nullptr; bool _dirty = true; glm::vec2 _size; bool _grounded = true; glm::vec2 _ground_normal{0,1}; glm::vec2 _last_body_position; uint_fast32_t _transform_revision = 0; glm::vec2 _initial_position; void _update_body(b2World& world); void _update_ground_info(Physics_system&); }; class Static_body_comp : public ecs::Component<Static_body_comp, ecs::Compact_index_policy, ecs::Pool_storage_policy<128, Static_body_comp>> { public: static constexpr const char* name() {return "Static_body";} friend void load_component(ecs::Deserializer& state, Static_body_comp&); friend void save_component(ecs::Serializer& state, const Static_body_comp&); Static_body_comp() = default; Static_body_comp(ecs::Entity_manager& manager, ecs::Entity_handle owner); void active(bool e) {_def.active = e;} private: friend class Physics_system; Body_definition _def; std::unique_ptr<b2Body, void(*)(b2Body*)> _body {nullptr, +[](b2Body*){}}; bool _dirty = true; uint_fast32_t _transform_revision = 0; void _update_body(b2World& world); }; } } }
30.680328
99
0.64841
lowkey42
a9b71c5db9af607c9172b0124ecd1f6ccd9bc67a
41,251
cc
C++
src/tensorflow/ops/image/image.cc
MartinR20/tensorflow.nim
081f558396461bd57d55c00cda91e8dfc339c09c
[ "Apache-2.0" ]
8
2019-11-26T20:50:46.000Z
2021-02-21T18:20:00.000Z
src/tensorflow/ops/image/image.cc
MartinR20/tensorflow.nim
081f558396461bd57d55c00cda91e8dfc339c09c
[ "Apache-2.0" ]
3
2019-11-07T15:16:06.000Z
2020-03-11T21:42:59.000Z
src/tensorflow/ops/image/image.cc
MartinR20/tensorflow.nim
081f558396461bd57d55c00cda91e8dfc339c09c
[ "Apache-2.0" ]
2
2019-11-07T15:18:56.000Z
2020-10-09T13:51:41.000Z
#include "tensorflow/cc/ops/const_op.h" #include "image.h" AdjustContrast::AdjustContrast(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input contrast_factor, tensorflow::Input min_value, tensorflow::Input max_value) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _contrast_factor = ::tensorflow::ops::AsNodeOut(scope, contrast_factor); if (!scope.ok()) return; auto _min_value = ::tensorflow::ops::AsNodeOut(scope, min_value); if (!scope.ok()) return; auto _max_value = ::tensorflow::ops::AsNodeOut(scope, max_value); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustContrast"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustContrast") .Input(_images) .Input(_contrast_factor) .Input(_min_value) .Input(_max_value) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } AdjustContrastv2::AdjustContrastv2(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input contrast_factor) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _contrast_factor = ::tensorflow::ops::AsNodeOut(scope, contrast_factor); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustContrastv2"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustContrastv2") .Input(_images) .Input(_contrast_factor) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } AdjustHue::AdjustHue(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input delta) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _delta = ::tensorflow::ops::AsNodeOut(scope, delta); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustHue"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustHue") .Input(_images) .Input(_delta) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } AdjustSaturation::AdjustSaturation(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input scale) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _scale = ::tensorflow::ops::AsNodeOut(scope, scale); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("AdjustSaturation"); auto builder = ::tensorflow::NodeBuilder(unique_name, "AdjustSaturation") .Input(_images) .Input(_scale) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } CropAndResize::CropAndResize(tensorflow::Scope& scope, tensorflow::Input image, tensorflow::Input boxes, tensorflow::Input box_ind, tensorflow::Input crop_size, float extrapolation_value, tensorflow::string method) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _box_ind = ::tensorflow::ops::AsNodeOut(scope, box_ind); if (!scope.ok()) return; auto _crop_size = ::tensorflow::ops::AsNodeOut(scope, crop_size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("CropAndResize"); auto builder = ::tensorflow::NodeBuilder(unique_name, "CropAndResize") .Input(_image) .Input(_boxes) .Input(_box_ind) .Input(_crop_size) .Attr("extrapolation_value", extrapolation_value) .Attr("method", method) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } CropAndResizeGradImage::CropAndResizeGradImage(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input boxes, tensorflow::Input box_ind, tensorflow::Input image_size, tensorflow::DataType T, tensorflow::string method) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _box_ind = ::tensorflow::ops::AsNodeOut(scope, box_ind); if (!scope.ok()) return; auto _image_size = ::tensorflow::ops::AsNodeOut(scope, image_size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("CropAndResizeGradImage"); auto builder = ::tensorflow::NodeBuilder(unique_name, "CropAndResizeGradImage") .Input(_grads) .Input(_boxes) .Input(_box_ind) .Input(_image_size) .Attr("T", T) .Attr("method", method) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeAndCropJpeg::DecodeAndCropJpeg(tensorflow::Scope& scope, tensorflow::Input contents, tensorflow::Input crop_window, tensorflow::string dct_method, int64_t channels, int64_t ratio, bool fancy_upscaling, bool try_recover_truncated, float acceptable_fraction) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); if (!scope.ok()) return; auto _crop_window = ::tensorflow::ops::AsNodeOut(scope, crop_window); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeAndCropJpeg"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeAndCropJpeg") .Input(_contents) .Input(_crop_window) .Attr("dct_method", dct_method) .Attr("channels", channels) .Attr("ratio", ratio) .Attr("fancy_upscaling", fancy_upscaling) .Attr("try_recover_truncated", try_recover_truncated) .Attr("acceptable_fraction", acceptable_fraction) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeBmp::DecodeBmp(tensorflow::Scope& scope, tensorflow::Input contents, int64_t channels) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeBmp"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeBmp") .Input(_contents) .Attr("channels", channels) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeCSV::DecodeCSV(tensorflow::Scope& scope, tensorflow::Input records, tensorflow::InputList record_defaults, tensorflow::gtl::ArraySlice<tensorflow::DataType> OUT_TYPE, tensorflow::string na_value, tensorflow::gtl::ArraySlice<int64_t> select_cols, tensorflow::string field_delim, bool use_quote_delim) { if (!scope.ok()) return; auto _records = ::tensorflow::ops::AsNodeOut(scope, records); if (!scope.ok()) return; auto _record_defaults = ::tensorflow::ops::AsNodeOutList(scope, record_defaults); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeCSV"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeCSV") .Input(_records) .Input(_record_defaults) .Attr("OUT_TYPE", OUT_TYPE) .Attr("na_value", na_value) .Attr("select_cols", select_cols) .Attr("field_delim", field_delim) .Attr("use_quote_delim", use_quote_delim) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); for (tensorflow::int32 i = 0; i < ret->num_outputs(); ++i) this->output.push_back(tensorflow::Output(ret, i)); } DecodeGif::DecodeGif(tensorflow::Scope& scope, tensorflow::Input contents) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeGif"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeGif") .Input(_contents) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeJpeg::DecodeJpeg(tensorflow::Scope& scope, tensorflow::Input contents, tensorflow::string dct_method, int64_t channels, int64_t ratio, bool fancy_upscaling, bool try_recover_truncated, float acceptable_fraction) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeJpeg"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeJpeg") .Input(_contents) .Attr("dct_method", dct_method) .Attr("channels", channels) .Attr("ratio", ratio) .Attr("fancy_upscaling", fancy_upscaling) .Attr("try_recover_truncated", try_recover_truncated) .Attr("acceptable_fraction", acceptable_fraction) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodePng::DecodePng(tensorflow::Scope& scope, tensorflow::Input contents, int64_t channels, tensorflow::DataType dtype) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodePng"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodePng") .Input(_contents) .Attr("channels", channels) .Attr("dtype", dtype) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DecodeRaw::DecodeRaw(tensorflow::Scope& scope, tensorflow::Input bytes, tensorflow::DataType out_type, bool little_endian) { if (!scope.ok()) return; auto _bytes = ::tensorflow::ops::AsNodeOut(scope, bytes); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DecodeRaw"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DecodeRaw") .Input(_bytes) .Attr("out_type", out_type) .Attr("little_endian", little_endian) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } DrawBoundingBoxes::DrawBoundingBoxes(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input boxes, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("DrawBoundingBoxes"); auto builder = ::tensorflow::NodeBuilder(unique_name, "DrawBoundingBoxes") .Input(_images) .Input(_boxes) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } EncodeJpeg::EncodeJpeg(tensorflow::Scope& scope, tensorflow::Input image, tensorflow::string format, tensorflow::string xmp_metadata, int64_t quality, bool progressive, bool optimize_size, bool chroma_downsampling, tensorflow::string density_unit, int64_t x_density, int64_t y_density) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("EncodeJpeg"); auto builder = ::tensorflow::NodeBuilder(unique_name, "EncodeJpeg") .Input(_image) .Attr("format", format) .Attr("xmp_metadata", xmp_metadata) .Attr("quality", quality) .Attr("progressive", progressive) .Attr("optimize_size", optimize_size) .Attr("chroma_downsampling", chroma_downsampling) .Attr("density_unit", density_unit) .Attr("x_density", x_density) .Attr("y_density", y_density) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } EncodePng::EncodePng(tensorflow::Scope& scope, tensorflow::Input image, int64_t compression) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("EncodePng"); auto builder = ::tensorflow::NodeBuilder(unique_name, "EncodePng") .Input(_image) .Attr("compression", compression) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ExtractGlimpse::ExtractGlimpse(tensorflow::Scope& scope, tensorflow::Input input, tensorflow::Input size, tensorflow::Input offsets, bool centered, bool normalized, bool uniform_noise) { if (!scope.ok()) return; auto _input = ::tensorflow::ops::AsNodeOut(scope, input); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); if (!scope.ok()) return; auto _offsets = ::tensorflow::ops::AsNodeOut(scope, offsets); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ExtractGlimpse"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ExtractGlimpse") .Input(_input) .Input(_size) .Input(_offsets) .Attr("centered", centered) .Attr("normalized", normalized) .Attr("uniform_noise", uniform_noise) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ExtractImagePatches::ExtractImagePatches(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::gtl::ArraySlice<int64_t> ksizes, tensorflow::gtl::ArraySlice<int64_t> strides, tensorflow::gtl::ArraySlice<int64_t> rates, tensorflow::string padding, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ExtractImagePatches"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ExtractImagePatches") .Input(_images) .Attr("ksizes", ksizes) .Attr("strides", strides) .Attr("rates", rates) .Attr("padding", padding) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ExtractJpegShape::ExtractJpegShape(tensorflow::Scope& scope, tensorflow::Input contents, tensorflow::DataType output_type) { if (!scope.ok()) return; auto _contents = ::tensorflow::ops::AsNodeOut(scope, contents); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ExtractJpegShape"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ExtractJpegShape") .Input(_contents) .Attr("output_type", output_type) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } HSVToRGB::HSVToRGB(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("HSVToRGB"); auto builder = ::tensorflow::NodeBuilder(unique_name, "HSVToRGB") .Input(_images) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } NonMaxSuppression::NonMaxSuppression(tensorflow::Scope& scope, tensorflow::Input boxes, tensorflow::Input scores, tensorflow::Input max_output_size, float iou_threshold) { if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _scores = ::tensorflow::ops::AsNodeOut(scope, scores); if (!scope.ok()) return; auto _max_output_size = ::tensorflow::ops::AsNodeOut(scope, max_output_size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("NonMaxSuppression"); auto builder = ::tensorflow::NodeBuilder(unique_name, "NonMaxSuppression") .Input(_boxes) .Input(_scores) .Input(_max_output_size) .Attr("iou_threshold", iou_threshold) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } NonMaxSuppressionV2::NonMaxSuppressionV2(tensorflow::Scope& scope, tensorflow::Input boxes, tensorflow::Input scores, tensorflow::Input max_output_size, tensorflow::Input iou_threshold) { if (!scope.ok()) return; auto _boxes = ::tensorflow::ops::AsNodeOut(scope, boxes); if (!scope.ok()) return; auto _scores = ::tensorflow::ops::AsNodeOut(scope, scores); if (!scope.ok()) return; auto _max_output_size = ::tensorflow::ops::AsNodeOut(scope, max_output_size); if (!scope.ok()) return; auto _iou_threshold = ::tensorflow::ops::AsNodeOut(scope, iou_threshold); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("NonMaxSuppressionV2"); auto builder = ::tensorflow::NodeBuilder(unique_name, "NonMaxSuppressionV2") .Input(_boxes) .Input(_scores) .Input(_max_output_size) .Input(_iou_threshold) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } QuantizedResizeBilinear::QuantizedResizeBilinear(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, tensorflow::Input min, tensorflow::Input max, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); if (!scope.ok()) return; auto _min = ::tensorflow::ops::AsNodeOut(scope, min); if (!scope.ok()) return; auto _max = ::tensorflow::ops::AsNodeOut(scope, max); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("QuantizedResizeBilinear"); auto builder = ::tensorflow::NodeBuilder(unique_name, "QuantizedResizeBilinear") .Input(_images) .Input(_size) .Input(_min) .Input(_max) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } RGBToHSV::RGBToHSV(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::DataType T) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("RGBToHSV"); auto builder = ::tensorflow::NodeBuilder(unique_name, "RGBToHSV") .Input(_images) .Attr("T", T) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } RandomCrop::RandomCrop(tensorflow::Scope& scope, tensorflow::Input image, tensorflow::Input size, tensorflow::DataType T, int64_t seed, int64_t seed2) { if (!scope.ok()) return; auto _image = ::tensorflow::ops::AsNodeOut(scope, image); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("RandomCrop"); auto builder = ::tensorflow::NodeBuilder(unique_name, "RandomCrop") .Input(_image) .Input(_size) .Attr("T", T) .Attr("seed", seed) .Attr("seed2", seed2) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeArea::ResizeArea(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeArea"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeArea") .Input(_images) .Input(_size) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBicubic::ResizeBicubic(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBicubic"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBicubic") .Input(_images) .Input(_size) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBicubicGrad::ResizeBicubicGrad(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input original_image, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _original_image = ::tensorflow::ops::AsNodeOut(scope, original_image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBicubicGrad"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBicubicGrad") .Input(_grads) .Input(_original_image) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBilinear::ResizeBilinear(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBilinear"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBilinear") .Input(_images) .Input(_size) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeBilinearGrad::ResizeBilinearGrad(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input original_image, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _original_image = ::tensorflow::ops::AsNodeOut(scope, original_image); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeBilinearGrad"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeBilinearGrad") .Input(_grads) .Input(_original_image) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeNearestNeighbor::ResizeNearestNeighbor(tensorflow::Scope& scope, tensorflow::Input images, tensorflow::Input size, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _images = ::tensorflow::ops::AsNodeOut(scope, images); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeNearestNeighbor"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeNearestNeighbor") .Input(_images) .Input(_size) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } ResizeNearestNeighborGrad::ResizeNearestNeighborGrad(tensorflow::Scope& scope, tensorflow::Input grads, tensorflow::Input size, tensorflow::DataType T, bool align_corners) { if (!scope.ok()) return; auto _grads = ::tensorflow::ops::AsNodeOut(scope, grads); if (!scope.ok()) return; auto _size = ::tensorflow::ops::AsNodeOut(scope, size); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("ResizeNearestNeighborGrad"); auto builder = ::tensorflow::NodeBuilder(unique_name, "ResizeNearestNeighborGrad") .Input(_grads) .Input(_size) .Attr("T", T) .Attr("align_corners", align_corners) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } SampleDistortedBoundingBox::SampleDistortedBoundingBox(tensorflow::Scope& scope, tensorflow::Input image_size, tensorflow::Input bounding_boxes, tensorflow::DataType T, int64_t seed, int64_t seed2, float min_object_covered, tensorflow::gtl::ArraySlice<float> aspect_ratio_range, tensorflow::gtl::ArraySlice<float> area_range, int64_t max_attempts, bool use_image_if_no_bounding_boxes) { if (!scope.ok()) return; auto _image_size = ::tensorflow::ops::AsNodeOut(scope, image_size); if (!scope.ok()) return; auto _bounding_boxes = ::tensorflow::ops::AsNodeOut(scope, bounding_boxes); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("SampleDistortedBoundingBox"); auto builder = ::tensorflow::NodeBuilder(unique_name, "SampleDistortedBoundingBox") .Input(_image_size) .Input(_bounding_boxes) .Attr("T", T) .Attr("seed", seed) .Attr("seed2", seed2) .Attr("min_object_covered", min_object_covered) .Attr("aspect_ratio_range", aspect_ratio_range) .Attr("area_range", area_range) .Attr("max_attempts", max_attempts) .Attr("use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); } SampleDistortedBoundingBoxV2::SampleDistortedBoundingBoxV2(tensorflow::Scope& scope, tensorflow::Input image_size, tensorflow::Input bounding_boxes, tensorflow::Input min_object_covered, tensorflow::DataType T, int64_t seed, int64_t seed2, tensorflow::gtl::ArraySlice<float> aspect_ratio_range, tensorflow::gtl::ArraySlice<float> area_range, int64_t max_attempts, bool use_image_if_no_bounding_boxes) { if (!scope.ok()) return; auto _image_size = ::tensorflow::ops::AsNodeOut(scope, image_size); if (!scope.ok()) return; auto _bounding_boxes = ::tensorflow::ops::AsNodeOut(scope, bounding_boxes); if (!scope.ok()) return; auto _min_object_covered = ::tensorflow::ops::AsNodeOut(scope, min_object_covered); ::tensorflow::Node *ret; const auto unique_name = scope.GetUniqueNameForOp("SampleDistortedBoundingBoxV2"); auto builder = ::tensorflow::NodeBuilder(unique_name, "SampleDistortedBoundingBoxV2") .Input(_image_size) .Input(_bounding_boxes) .Input(_min_object_covered) .Attr("T", T) .Attr("seed", seed) .Attr("seed2", seed2) .Attr("aspect_ratio_range", aspect_ratio_range) .Attr("area_range", area_range) .Attr("max_attempts", max_attempts) .Attr("use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) ; scope.UpdateBuilder(&builder); scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); if (!scope.ok()) return; scope.UpdateStatus(scope.DoShapeInference(ret)); this->operation = ::tensorflow::Operation(ret); this->output = tensorflow::Output(ret, 0); }
43.104493
106
0.562992
MartinR20
a9b7813b425d9cfc2d027aa6221036a6f67f63e9
4,767
cpp
C++
src/mame/drivers/ymdx100.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/ymdx100.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/ymdx100.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:AJR /******************************************************************************* Skeleton driver for Yamaha DX100 & DX27 FM synthesizers. The main differences between DX100 and DX27 are that DX27 has 61 keys rather than 49, but DX100 is portable and can run on battery power. Their tone generation capabilities are identical. *******************************************************************************/ #include "emu.h" #include "bus/midi/midi.h" #include "cpu/m6800/m6801.h" #include "machine/adc0808.h" #include "machine/clock.h" #include "machine/nvram.h" #include "sound/ymopm.h" #include "video/hd44780.h" #include "emupal.h" #include "screen.h" #include "speaker.h" namespace { class yamaha_dx100_state : public driver_device { public: yamaha_dx100_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_midi_in(true) { } void dx100(machine_config &config); protected: virtual void machine_start() override; private: HD44780_PIXEL_UPDATE(lcd_pixel_update); void palette_init(palette_device &palette); DECLARE_WRITE_LINE_MEMBER(p22_w); void mem_map(address_map &map); required_device<hd6303x_cpu_device> m_maincpu; bool m_midi_in; }; void yamaha_dx100_state::machine_start() { save_item(NAME(m_midi_in)); } HD44780_PIXEL_UPDATE(yamaha_dx100_state::lcd_pixel_update) { if (x < 5 && y < 8 && line < 2 && pos < 16) bitmap.pix(line * 10 + y + 1 + ((y == 7) ? 1 : 0), pos * 6 + x + 1) = state ? 1 : 2; } void yamaha_dx100_state::palette_init(palette_device &palette) { palette.set_pen_color(0, rgb_t(0x00, 0x00, 0x00)); // background palette.set_pen_color(1, rgb_t(0xff, 0xff, 0xff)); // lcd pixel on palette.set_pen_color(2, rgb_t(0x18, 0x18, 0x18)); // lcd pixel off } WRITE_LINE_MEMBER(yamaha_dx100_state::p22_w) { if (state) m_maincpu->m6801_clock_serial(); } void yamaha_dx100_state::mem_map(address_map &map) { map(0x0000, 0x001f).m(m_maincpu, FUNC(hd6303x_cpu_device::hd6301x_io)); map(0x0040, 0x00ff).ram(); // internal RAM map(0x0800, 0x0fff).ram().share("nvram"); map(0x1000, 0x17ff).ram(); map(0x2000, 0x2001).rw("lcdc", FUNC(hd44780_device::read), FUNC(hd44780_device::write)); map(0x2800, 0x2800).r("adc", FUNC(m58990_device::data_r)); map(0x3000, 0x3000).w("adc", FUNC(m58990_device::address_data_start_w)); map(0x3800, 0x3801).rw("ymsnd", FUNC(ym2164_device::read), FUNC(ym2164_device::write)); map(0x8000, 0xffff).rom().region("program", 0); } static INPUT_PORTS_START(dx100) INPUT_PORTS_END void yamaha_dx100_state::dx100(machine_config &config) { HD6303X(config, m_maincpu, 7.15909_MHz_XTAL / 2); // HD6303XP m_maincpu->set_addrmap(AS_PROGRAM, &yamaha_dx100_state::mem_map); m_maincpu->in_p2_cb().set([this]() -> u8 { return m_midi_in ? 0x04 : 0; }); m_maincpu->in_p6_cb().set("adc", FUNC(m58990_device::eoc_r)).lshift(4); m_maincpu->out_ser_tx_cb().set("mdout", FUNC(midi_port_device::write_txd)); NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_0); // TC5518BPL + CR2032T battery m58990_device &adc(M58990(config, "adc", 7.15909_MHz_XTAL / 8)); // M58990P-1 (clocked by E) adc.in_callback<5>().set_constant(0x80); // "CNG RAM BATTERY!" displayed unless value is between 0x70 and 0xCC CLOCK(config, "subclock", 500_kHz_XTAL).signal_handler().set(FUNC(yamaha_dx100_state::p22_w)); MIDI_PORT(config, "mdin", midiin_slot, "midiin").rxd_handler().set([this](int state) { m_midi_in = state; }); MIDI_PORT(config, "mdout", midiout_slot, "midiout"); screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_LCD)); screen.set_refresh_hz(60); screen.set_vblank_time(ATTOSECONDS_IN_USEC(2500)); /* not accurate */ screen.set_screen_update("lcdc", FUNC(hd44780_device::screen_update)); screen.set_size(6*16+1, 10*2+1); screen.set_visarea_full(); screen.set_palette("palette"); PALETTE(config, "palette", FUNC(yamaha_dx100_state::palette_init), 3); hd44780_device &lcdc(HD44780(config, "lcdc", 0)); // HD44780RA00 lcdc.set_lcd_size(2, 16); lcdc.set_pixel_update_cb(FUNC(yamaha_dx100_state::lcd_pixel_update)); SPEAKER(config, "lspeaker").front_left(); SPEAKER(config, "rspeaker").front_right(); ym2164_device &ymsnd(YM2164(config, "ymsnd", 7.15909_MHz_XTAL / 2)); // with YM3014 DAC ymsnd.add_route(0, "lspeaker", 0.60); ymsnd.add_route(1, "rspeaker", 0.60); } ROM_START(dx100) ROM_REGION(0x8000, "program", 0) ROM_LOAD("dx100 v1.1.bin", 0x0000, 0x8000, CRC(c3ed7c86) SHA1(5b003db1bb5c1909907153f6446b63b07f5b41d6)) ROM_END } // anonymous namespace SYST(1985, dx100, 0, 0, dx100, dx100, yamaha_dx100_state, empty_init, "Yamaha", "DX100 Digital Programmable Algorithm Synthesizer", MACHINE_IS_SKELETON)
32.875862
152
0.7103
Robbbert
a9b7dddb9080c4466de6e20a251b538f9ee83caa
2,717
cpp
C++
Public/src/Sandbox/MacOs/BuildXLSandbox/Src/Kauth/TrustedBsdHandler.cpp
blufugen/BuildXL
b7f33c72a3c9a8463fc6d656214a5c5dfccac7ad
[ "MIT" ]
null
null
null
Public/src/Sandbox/MacOs/BuildXLSandbox/Src/Kauth/TrustedBsdHandler.cpp
blufugen/BuildXL
b7f33c72a3c9a8463fc6d656214a5c5dfccac7ad
[ "MIT" ]
null
null
null
Public/src/Sandbox/MacOs/BuildXLSandbox/Src/Kauth/TrustedBsdHandler.cpp
blufugen/BuildXL
b7f33c72a3c9a8463fc6d656214a5c5dfccac7ad
[ "MIT" ]
null
null
null
// // TrustedBsdHandler.cpp // // Copyright © 2018 Microsoft. All rights reserved. // #include "TrustedBsdHandler.hpp" #include "OpNames.hpp" int TrustedBsdHandler::HandleLookup(const char *path) { PolicyResult policyResult = PolicyForPath(path); AccessCheckResult checkResult = policyResult.CheckReadAccess( RequestedReadAccess::Probe, FileReadContext(FileExistence::Nonexistent)); FileOperationContext fOp = FileOperationContext::CreateForRead(OpMacLookup, path); const OSSymbol *cacheKey = OSSymbol::withCString(path); Report(fOp, policyResult, checkResult, 0, cacheKey); OSSafeReleaseNULL(cacheKey); // Never deny lookups return KERN_SUCCESS; } int TrustedBsdHandler::HandleReadlink(vnode_t symlinkVNode) { // get symlink path char path[MAXPATHLEN]; int len = MAXPATHLEN; int err = vn_getpath(symlinkVNode, path, &len); if (err) { log_error("Could not get VNnode path for readlink operation; error code: %#X", err); return KERN_SUCCESS; // don't deny access because of our own error } // check read access PolicyResult policyResult = PolicyForPath(path); AccessCheckResult checkResult = policyResult.CheckExistingFileReadAccess(); FileOperationContext fOp = FileOperationContext::CreateForRead(OpMacReadlink, path); Report(fOp, policyResult, checkResult); if (checkResult.ShouldDenyAccess()) { LogAccessDenied(path, 0, "Operation: Readlink"); return EPERM; } else { return KERN_SUCCESS; } } int TrustedBsdHandler::HandleVNodeCreateEvent(const char *fullPath, const bool isDir, const bool isSymlink) { PolicyResult policyResult = PolicyForPath(fullPath); AccessCheckResult result = CheckCreate(policyResult, isDir, isSymlink); if (result.ShouldDenyAccess()) { LogAccessDenied(fullPath, 0, "Operation: VNodeCreate"); return EPERM; } else { return KERN_SUCCESS; } } AccessCheckResult TrustedBsdHandler::CheckCreate(PolicyResult policyResult, bool isDir, bool isSymlink) { AccessCheckResult checkResult = isSymlink ? policyResult.CheckSymlinkCreationAccess() : isDir ? policyResult.CheckDirectoryAccess(CheckDirectoryCreationAccessEnforcement(GetFamFlags())) : policyResult.CheckWriteAccess(); FileOperationContext fop = ToFileContext(OpMacVNodeCreate, GENERIC_WRITE, CreationDisposition::CreateAlways, policyResult.Path()); Report(fop, policyResult, checkResult); return checkResult; }
31.593023
111
0.67869
blufugen
a9b804d9bfb232dbdb24136e837d2fced7982b89
10,643
cpp
C++
examples/as_game/scriptmgr.cpp
PleXone2019/ProDBG
c7042f32da9e54662c3c575725c4cd24a878a2de
[ "MIT" ]
445
2015-01-04T16:30:56.000Z
2022-03-30T02:27:05.000Z
examples/as_game/scriptmgr.cpp
PleXone2019/ProDBG
c7042f32da9e54662c3c575725c4cd24a878a2de
[ "MIT" ]
305
2015-01-04T09:20:03.000Z
2020-10-01T08:45:45.000Z
examples/as_game/scriptmgr.cpp
PleXone2019/ProDBG
c7042f32da9e54662c3c575725c4cd24a878a2de
[ "MIT" ]
49
2015-02-14T01:43:38.000Z
2022-02-15T17:03:55.000Z
#include "scriptmgr.h" #include "gamemgr.h" #include "gameobj.h" #include <iostream> // cout #include <stdio.h> // fopen, fclose #include <string.h> // strcmp #include <assert.h> #include <add_on/scriptstdstring/scriptstdstring.h> #include <add_on/scriptbuilder/scriptbuilder.h> #include <add_on/weakref/weakref.h> using namespace std; CScriptMgr::CScriptMgr() { engine = 0; hasCompileErrors = false; } CScriptMgr::~CScriptMgr() { for( unsigned int n = 0; n < controllers.size(); n++ ) delete controllers[n]; for( unsigned int n = 0; n < contexts.size(); n++ ) contexts[n]->Release(); if( engine ) engine->Release(); } int CScriptMgr::Init() { int r; engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); // Set the message callback to print the human readable messages that the engine gives in case of errors r = engine->SetMessageCallback(asMETHOD(CScriptMgr, MessageCallback), this, asCALL_THISCALL); assert( r >= 0 ); // Register the string type RegisterStdString(engine); // Register the generic handle type, called 'ref' in the script RegisterScriptHandle(engine); // Register the weak ref template type RegisterScriptWeakRef(engine); // Register the game object. The scripts cannot create these directly, so there is no factory function. r = engine->RegisterObjectType("CGameObj", 0, asOBJ_REF); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("CGameObj", asBEHAVE_ADDREF, "void f()", asMETHOD(CGameObj, AddRef), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("CGameObj", asBEHAVE_RELEASE, "void f()", asMETHOD(CGameObj, Release), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("CGameObj", asBEHAVE_GET_WEAKREF_FLAG, "int &f()", asMETHOD(CGameObj, GetWeakRefFlag), asCALL_THISCALL); assert( r >= 0 ); // The object's position is read-only to the script. The position is updated with the Move method r = engine->RegisterObjectMethod("CGameObj", "int get_x() const", asMETHOD(CGameObj, GetX), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectMethod("CGameObj", "int get_y() const", asMETHOD(CGameObj, GetY), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectMethod("CGameObj", "bool Move(int dx, int dy)", asMETHOD(CGameObj, Move), asCALL_THISCALL); assert( r >= 0 ); // The script can kill the owning object r = engine->RegisterObjectMethod("CGameObj", "void Kill()", asMETHOD(CGameObj, Kill), asCALL_THISCALL); assert( r >= 0 ); // The script can send a message to the other object through this method // Observe the autohandle @+ to tell AngelScript to automatically release the handle after the call // The generic handle type is used to allow the script to pass any object to // the other script without the application having to know anything about it r = engine->RegisterObjectMethod("CGameObj", "void Send(ref msg, const CGameObj @+ to)", asMETHOD(CGameObj, Send), asCALL_THISCALL); assert( r >= 0 ); // The game engine will determine the class that represents the controller // by checking if the class implements the IController interface. No methods // are registered for this interface, as the script shouldn't be required to // implement the methods. This will allow the game engine to avoid calling // methods that doesn't do anything, thus improving performance. r = engine->RegisterInterface("IController"); assert( r >= 0 ); // Register the game manager as a singleton. The script will access it through the global property r = engine->RegisterObjectType("CGameMgr", 0, asOBJ_REF | asOBJ_NOHANDLE); assert( r >= 0 ); // Register the game manager's methods r = engine->RegisterGlobalProperty("CGameMgr game", gameMgr); assert( r >= 0 ); // The script can determine what the user wants to do through the actionStates r = engine->RegisterObjectMethod("CGameMgr", "bool get_actionState(int idx)", asMETHOD(CGameMgr, GetActionState), asCALL_THISCALL); assert( r >= 0 ); // The script can call this method to end the game r = engine->RegisterObjectMethod("CGameMgr", "void EndGame(bool win)", asMETHOD(CGameMgr, EndGame), asCALL_THISCALL); assert( r >= 0 ); // Register a method that will allow the script to find an object by its name. // This returns the object as const handle, as the script should only be // allow to directly modify its owner object. // Observe the @+ that tells AngelScript to automatically increase the refcount r = engine->RegisterObjectMethod("CGameMgr", "const CGameObj @+ FindObjByName(const string &in name)", asMETHOD(CGameMgr, FindGameObjByName), asCALL_THISCALL); assert( r >= 0 ); return 0; } void CScriptMgr::MessageCallback(const asSMessageInfo &msg) { const char *type = "ERR "; if( msg.type == asMSGTYPE_WARNING ) type = "WARN"; else if( msg.type == asMSGTYPE_INFORMATION ) type = "INFO"; cout << msg.section << " (" << msg.row << ", " << msg.col << ") : " << type << " : " << msg.message << endl; if( msg.type == asMSGTYPE_ERROR ) hasCompileErrors = true; } CScriptMgr::SController *CScriptMgr::GetControllerScript(const string &script) { int r; // Find the cached controller for( unsigned int n = 0; n < controllers.size(); n++ ) { if( controllers[n]->module == script ) return controllers[n]; } // No controller, check if the script has already been loaded asIScriptModule *mod = engine->GetModule(script.c_str(), asGM_ONLY_IF_EXISTS); if( mod ) { // We've already attempted loading the script before, but there is no controller return 0; } // Compile the script into the module CScriptBuilder builder; r = builder.StartNewModule(engine, script.c_str()); if( r < 0 ) return 0; // If the script file doesn't exist, then there is no script controller for this type FILE *f; if( (f = fopen((script + ".as").c_str(), "r")) == 0 ) return 0; fclose(f); // Let the builder load the script, and do the necessary pre-processing (include files, etc) r = builder.AddSectionFromFile((script + ".as").c_str()); if( r < 0 ) return 0; r = builder.BuildModule(); if( r < 0 ) return 0; // Cache the functions and methods that will be used SController *ctrl = new SController; controllers.push_back(ctrl); ctrl->module = script; // Find the class that implements the IController interface mod = engine->GetModule(script.c_str(), asGM_ONLY_IF_EXISTS); asIObjectType *type = 0; int tc = mod->GetObjectTypeCount(); for( int n = 0; n < tc; n++ ) { bool found = false; type = mod->GetObjectTypeByIndex(n); int ic = type->GetInterfaceCount(); for( int i = 0; i < ic; i++ ) { if( strcmp(type->GetInterface(i)->GetName(), "IController") == 0 ) { found = true; break; } } if( found == true ) { ctrl->type = type; break; } } if( ctrl->type == 0 ) { cout << "Couldn't find the controller class for the type '" << script << "'" << endl; controllers.pop_back(); delete ctrl; return 0; } // Find the factory function // The game engine will pass in the owning CGameObj to the controller for storage string s = string(type->GetName()) + "@ " + string(type->GetName()) + "(CGameObj @)"; ctrl->factoryFunc = type->GetFactoryByDecl(s.c_str()); if( ctrl->factoryFunc == 0 ) { cout << "Couldn't find the appropriate factory for the type '" << script << "'" << endl; controllers.pop_back(); delete ctrl; return 0; } // Find the optional event handlers ctrl->onThinkMethod = type->GetMethodByDecl("void OnThink()"); ctrl->onMessageMethod = type->GetMethodByDecl("void OnMessage(ref @msg, const CGameObj @sender)"); // Add the cache as user data to the type for quick access type->SetUserData(ctrl); return ctrl; } asIScriptObject *CScriptMgr::CreateController(const string &script, CGameObj *gameObj) { int r; asIScriptObject *obj = 0; SController *ctrl = GetControllerScript(script); if( ctrl == 0 ) return 0; // Create the object using the factory function asIScriptContext *ctx = PrepareContextFromPool(ctrl->factoryFunc); // Pass the object pointer to the script function. With this call the // context will automatically increase the reference count for the object. ctx->SetArgObject(0, gameObj); // Make the call and take care of any errors that may happen r = ExecuteCall(ctx); if( r == asEXECUTION_FINISHED ) { // Get the newly created object obj = *((asIScriptObject**)ctx->GetAddressOfReturnValue()); // Since a reference will be kept to this object // it is necessary to increase the ref count obj->AddRef(); } // Return the context to the pool so it can be reused ReturnContextToPool(ctx); return obj; } void CScriptMgr::CallOnThink(asIScriptObject *object) { // Find the cached onThink method id SController *ctrl = reinterpret_cast<SController*>(object->GetObjectType()->GetUserData()); // Call the method using the shared context if( ctrl->onThinkMethod != 0 ) { asIScriptContext *ctx = PrepareContextFromPool(ctrl->onThinkMethod); ctx->SetObject(object); ExecuteCall(ctx); ReturnContextToPool(ctx); } } void CScriptMgr::CallOnMessage(asIScriptObject *object, CScriptHandle &msg, CGameObj *caller) { // Find the cached onMessage method id SController *ctrl = reinterpret_cast<SController*>(object->GetObjectType()->GetUserData()); // Call the method using the shared context if( ctrl->onMessageMethod != 0 ) { asIScriptContext *ctx = PrepareContextFromPool(ctrl->onMessageMethod); ctx->SetObject(object); ctx->SetArgObject(0, &msg); ctx->SetArgObject(1, caller); ExecuteCall(ctx); ReturnContextToPool(ctx); } } int CScriptMgr::ExecuteCall(asIScriptContext *ctx) { int r = ctx->Execute(); if( r != asEXECUTION_FINISHED ) { if( r == asEXECUTION_EXCEPTION ) { cout << "Exception: " << ctx->GetExceptionString() << endl; cout << "Function: " << ctx->GetExceptionFunction()->GetDeclaration() << endl; cout << "Line: " << ctx->GetExceptionLineNumber() << endl; // It is possible to print more information about the location of the // exception, for example the call stack, values of variables, etc if // that is of interest. } } return r; } asIScriptContext *CScriptMgr::PrepareContextFromPool(asIScriptFunction *func) { asIScriptContext *ctx = 0; if( contexts.size() ) { ctx = *contexts.rbegin(); contexts.pop_back(); } else ctx = engine->CreateContext(); int r = ctx->Prepare(func); assert( r >= 0 ); return ctx; } void CScriptMgr::ReturnContextToPool(asIScriptContext *ctx) { contexts.push_back(ctx); // Unprepare the context to free any objects that might be held // as we don't know when the context will be used again. ctx->Unprepare(); }
32.647239
178
0.703937
PleXone2019
a9b877861437253e1b573acee3a83ae4784a75fb
1,745
hpp
C++
src/org/apache/poi/ss/formula/SheetNameFormatter.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/SheetNameFormatter.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/SheetNameFormatter.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/SheetNameFormatter.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/util/regex/fwd-POI.hpp> #include <org/apache/poi/ss/formula/fwd-POI.hpp> #include <java/lang/Object.hpp> struct default_init_tag; class poi::ss::formula::SheetNameFormatter final : public ::java::lang::Object { public: typedef ::java::lang::Object super; private: static constexpr char16_t DELIMITER { u'\'' }; static ::java::util::regex::Pattern* CELL_REF_PATTERN_; protected: void ctor(); public: static ::java::lang::String* format(::java::lang::String* rawSheetName); static void appendFormat(::java::lang::StringBuffer* out, ::java::lang::String* rawSheetName); static void appendFormat(::java::lang::StringBuffer* out, ::java::lang::String* workbookName, ::java::lang::String* rawSheetName); private: static void appendAndEscape(::java::lang::StringBuffer* sb, ::java::lang::String* rawSheetName); static bool needsDelimiting(::java::lang::String* rawSheetName); static bool nameLooksLikeBooleanLiteral(::java::lang::String* rawSheetName); public: /* package */ static bool isSpecialChar(char16_t ch); static bool cellReferenceIsWithinRange(::java::lang::String* lettersPrefix, ::java::lang::String* numbersSuffix); static bool nameLooksLikePlainCellReference(::java::lang::String* rawSheetName); // Generated private: SheetNameFormatter(); protected: SheetNameFormatter(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static void clinit(); private: static ::java::util::regex::Pattern*& CELL_REF_PATTERN(); virtual ::java::lang::Class* getClass0(); };
30.614035
134
0.714613
pebble2015
a9b8f12283b6c49465c6aaa36c89acd50148f3b0
8,135
cc
C++
wrspice/src/cp/backq.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
wrspice/src/cp/backq.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
wrspice/src/cp/backq.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool * * * *========================================================================* $Id:$ *========================================================================*/ /*************************************************************************** JSPICE3 adaptation of Spice3e2 - Copyright (c) Stephen R. Whiteley 1992 Copyright 1990 Regents of the University of California. All rights reserved. Authors: 1985 Wayne A. Christopher 1992 Stephen R. Whiteley ****************************************************************************/ #include "config.h" #include "cshell.h" #include "miscutil/filestat.h" #include "ginterf/graphics.h" #ifdef WIN32 #include <setjmp.h> #endif // // Do backquote substitution on a word list. // void CshPar::BackQuote(wordlist **list) { if (list == 0) return; wordlist *wlist = *list; for (wordlist *wl = wlist; wl; wl = wl->wl_next) { char *t = wl->wl_word; if (!t) continue; char *s; while ((s = strchr(t, cp_back)) != 0) { char *wbuf = new char[s - wl->wl_word + 1]; strncpy(wbuf, wl->wl_word, s - wl->wl_word); wbuf[s - wl->wl_word] = 0; char *bcmd = lstring::copy(s+1); t = s+1; s = bcmd; bool quoted = false; for (char *tm = wbuf; *tm; tm++) { if (*tm == '"') quoted = !quoted; } while (*s && (*s != cp_back)) { // Get s and t past the next backquote t++; s++; } *s = '\0'; if (*t) t++; // Get past the second ` wordlist *nwl = BackEval(bcmd); delete [] bcmd; if (!nwl || !nwl->wl_word) { delete [] wbuf; wordlist::destroy(wlist); *list = 0; return; } if (quoted && nwl->wl_next) { char *tt = wordlist::flatten(nwl); if (strlen(tt) + strlen(wbuf) + strlen(t) >= BSIZE_SP) { tt[BSIZE_SP - strlen(wbuf) - strlen(t) - 1] = 0; GRpkgIf()->ErrPrintf(ET_WARN, "line too long, truncated.\n"); } wordlist::destroy(nwl->wl_next); nwl->wl_next = 0; delete [] nwl->wl_word; nwl->wl_word = tt; } char *tt = new char[strlen(wbuf) + strlen(nwl->wl_word) + 1]; strcpy(tt, wbuf); strcat(tt, nwl->wl_word); delete [] nwl->wl_word; nwl->wl_word = tt; delete [] wbuf; t = lstring::copy(t); bool upd = (wl == wlist); wl = wl->splice(nwl); if (upd) wlist = nwl; int i = strlen(wl->wl_word); tt = new char[i + strlen(t) + 1]; strcpy(tt, wl->wl_word); strcat(tt, t); delete [] t; delete [] wl->wl_word; wl->wl_word = tt; t = &wl->wl_word[i]; } } *list = wlist; } // Do a popen with the string, and then reset the file pointers so that // we can use the first pass of the parser on the output. // wordlist * CshPar::BackEval(const char *string) { if (!*string) return (0); const char *sbak = string; char *tok = lstring::gettok(&string); if (tok && !strcasecmp(tok, "shell")) { delete [] tok; // This is the original Spice3 implementation. Now, we // prepend the command with "shell" to get here. FILE *proc = popen(string, "r"); if (proc == 0) { GRpkgIf()->ErrPrintf(ET_ERROR, "can't evaluate %s.\n", string); return (0); } FILE *old = cp_input; cp_input = proc; bool intv = cp_flags[CP_INTERACTIVE]; cp_flags[CP_INTERACTIVE] = false; cp_bqflag = true; wordlist *wl = Lexer(0); cp_bqflag = false; cp_input = old; cp_flags[CP_INTERACTIVE] = intv; pclose(proc); return (wl); } else { delete [] tok; string = sbak; // New implementation, use our own shell for evaluation. char *tempfile = filestat::make_temp("sp"); FILE *fp = fopen(tempfile, "w+"); TTY.ioPush(fp); CP.PushControl(); bool intr = cp_flags[CP_INTERACTIVE]; cp_flags[CP_INTERACTIVE] = false; #ifdef WIN32 extern jmp_buf msw_jbf[4]; extern int msw_jbf_sp; bool dopop = false; if (msw_jbf_sp < 3) { msw_jbf_sp++; dopop = true; } if (setjmp(msw_jbf[msw_jbf_sp]) == 0) { EvLoop(string); } if (dopop) msw_jbf_sp--; #else try { EvLoop(string); } catch (int) { } #endif cp_flags[CP_CWAIT] = true; // have to reset this cp_flags[CP_INTERACTIVE] = intr; CP.PopControl(); TTY.ioPop(); fflush(fp); rewind(fp); FILE *tfp = cp_input; cp_input = fp; cp_flags[CP_INTERACTIVE] = false; cp_bqflag = true; wordlist *wl = Lexer(0); cp_bqflag = false; cp_input = tfp; cp_flags[CP_INTERACTIVE] = intr; fclose(fp); unlink(tempfile); delete [] tempfile; return (wl); } }
34.914163
77
0.440688
wrcad
a9bc315f64584fde916e9dae2b253b071fad43d2
69,802
cc
C++
be/src/exec/partitioned_aggregation_node.cc
shengyunyao/incubator-doris
036ef5bcb991658bb5187e81d91a66dfeaeddda3
[ "Apache-2.0" ]
1
2020-04-04T08:45:42.000Z
2020-04-04T08:45:42.000Z
be/src/exec/partitioned_aggregation_node.cc
songenjie/incubator-doris
7f148c188efcefd816ab299aa65526207ea05c8f
[ "Apache-2.0" ]
null
null
null
be/src/exec/partitioned_aggregation_node.cc
songenjie/incubator-doris
7f148c188efcefd816ab299aa65526207ea05c8f
[ "Apache-2.0" ]
1
2020-01-06T08:25:22.000Z
2020-01-06T08:25:22.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "exec/partitioned_aggregation_node.h" #include <math.h> #include <sstream> #include <thrift/protocol/TDebugProtocol.h> #include "codegen/codegen_anyval.h" #include "codegen/llvm_codegen.h" #include "exec/partitioned_hash_table.inline.h" #include "exprs/agg_fn_evaluator.h" #include "exprs/expr.h" #include "exprs/expr_context.h" #include "exprs/slot_ref.h" #include "runtime/buffered_tuple_stream2.inline.h" #include "runtime/descriptors.h" #include "runtime/mem_pool.h" #include "runtime/raw_value.h" #include "runtime/row_batch.h" #include "runtime/runtime_state.h" #include "runtime/tuple.h" #include "runtime/tuple_row.h" #include "udf/udf_internal.h" #include "util/runtime_profile.h" #include "util/stack_util.h" #include "gen_cpp/Exprs_types.h" #include "gen_cpp/PlanNodes_types.h" // using namespace llvm; using std::list; namespace doris { const char* PartitionedAggregationNode::_s_llvm_class_name = "class.doris::PartitionedAggregationNode"; PartitionedAggregationNode::PartitionedAggregationNode( ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs) : ExecNode(pool, tnode, descs), _intermediate_tuple_id(tnode.agg_node.intermediate_tuple_id), _intermediate_tuple_desc(NULL), _output_tuple_id(tnode.agg_node.output_tuple_id), _output_tuple_desc(NULL), _needs_finalize(tnode.agg_node.need_finalize), _needs_serialize(false), _block_mgr_client(NULL), _output_partition(NULL), _process_row_batch_fn(NULL), _build_timer(NULL), _ht_resize_timer(NULL), _get_results_timer(NULL), _num_hash_buckets(NULL), _partitions_created(NULL), // _max_partition_level(NULL), _num_row_repartitioned(NULL), _num_repartitions(NULL), _singleton_output_tuple(NULL), _singleton_output_tuple_returned(true), _partition_pool(new ObjectPool()) { DCHECK_EQ(PARTITION_FANOUT, 1 << NUM_PARTITIONING_BITS); } Status PartitionedAggregationNode::init(const TPlanNode& tnode, RuntimeState* state) { RETURN_IF_ERROR(ExecNode::init(tnode, state)); RETURN_IF_ERROR( Expr::create_expr_trees(_pool, tnode.agg_node.grouping_exprs, &_probe_expr_ctxs)); for (int i = 0; i < tnode.agg_node.aggregate_functions.size(); ++i) { AggFnEvaluator* evaluator = NULL; RETURN_IF_ERROR(AggFnEvaluator::create( _pool, tnode.agg_node.aggregate_functions[i], &evaluator)); _aggregate_evaluators.push_back(evaluator); } return Status::OK(); } Status PartitionedAggregationNode::prepare(RuntimeState* state) { SCOPED_TIMER(_runtime_profile->total_time_counter()); // Create the codegen object before preparing _conjunct_ctxs and _children, so that any // ScalarFnCalls will use codegen. // TODO: this is brittle and hard to reason about, revisit // if (state->codegen_enabled()) { // LlvmCodeGen* codegen; // RETURN_IF_ERROR(state->get_codegen(&codegen)); // } RETURN_IF_ERROR(ExecNode::prepare(state)); _state = state; _mem_pool.reset(new MemPool(mem_tracker())); _agg_fn_pool.reset(new MemPool(expr_mem_tracker())); _build_timer = ADD_TIMER(runtime_profile(), "BuildTime"); _ht_resize_timer = ADD_TIMER(runtime_profile(), "HTResizeTime"); _get_results_timer = ADD_TIMER(runtime_profile(), "GetResultsTime"); _num_hash_buckets = ADD_COUNTER(runtime_profile(), "HashBuckets", TUnit::UNIT); _partitions_created = ADD_COUNTER(runtime_profile(), "PartitionsCreated", TUnit::UNIT); // _max_partition_level = runtime_profile()->AddHighWaterMarkCounter( // "MaxPartitionLevel", TUnit::UNIT); _num_row_repartitioned = ADD_COUNTER( runtime_profile(), "RowsRepartitioned", TUnit::UNIT); _num_repartitions = ADD_COUNTER(runtime_profile(), "NumRepartitions", TUnit::UNIT); _num_spilled_partitions = ADD_COUNTER( runtime_profile(), "SpilledPartitions", TUnit::UNIT); // _largest_partition_percent = runtime_profile()->AddHighWaterMarkCounter( // "LargestPartitionPercent", TUnit::UNIT); _intermediate_tuple_desc = state->desc_tbl().get_tuple_descriptor(_intermediate_tuple_id); _output_tuple_desc = state->desc_tbl().get_tuple_descriptor(_output_tuple_id); DCHECK_EQ(_intermediate_tuple_desc->slots().size(), _output_tuple_desc->slots().size()); RETURN_IF_ERROR( Expr::prepare(_probe_expr_ctxs, state, child(0)->row_desc(), expr_mem_tracker())); // AddExprCtxsToFree(_probe_expr_ctxs); _contains_var_len_grouping_exprs = false; // Construct build exprs from _intermediate_agg_tuple_desc for (int i = 0; i < _probe_expr_ctxs.size(); ++i) { SlotDescriptor* desc = _intermediate_tuple_desc->slots()[i]; DCHECK(desc->type().type == TYPE_NULL || desc->type().type == _probe_expr_ctxs[i]->root()->type().type); // Hack to avoid TYPE_NULL SlotRefs. Expr* expr = desc->type().type != TYPE_NULL ? new SlotRef(desc) : new SlotRef(desc, TYPE_BOOLEAN); state->obj_pool()->add(expr); _build_expr_ctxs.push_back(new ExprContext(expr)); state->obj_pool()->add(_build_expr_ctxs.back()); _contains_var_len_grouping_exprs |= expr->type().is_string_type(); } // Construct a new row desc for preparing the build exprs because neither the child's // nor this node's output row desc may contain the intermediate tuple, e.g., // in a single-node plan with an intermediate tuple different from the output tuple. _intermediate_row_desc.reset(new RowDescriptor(_intermediate_tuple_desc, false)); RETURN_IF_ERROR( Expr::prepare(_build_expr_ctxs, state, *_intermediate_row_desc, expr_mem_tracker())); // AddExprCtxsToFree(_build_expr_ctxs); int j = _probe_expr_ctxs.size(); for (int i = 0; i < _aggregate_evaluators.size(); ++i, ++j) { // Skip non-materialized slots; we don't have evaluators instantiated for those. while (!_intermediate_tuple_desc->slots()[j]->is_materialized()) { DCHECK_LT(j, _intermediate_tuple_desc->slots().size() - 1) << "#eval= " << _aggregate_evaluators.size() << " #probe=" << _probe_expr_ctxs.size(); ++j; } // SlotDescriptor* intermediate_slot_desc = _intermediate_tuple_desc->slots()[j]; SlotDescriptor* output_slot_desc = _output_tuple_desc->slots()[j]; FunctionContext* agg_fn_ctx = NULL; // RETURN_IF_ERROR(_aggregate_evaluators[i]->prepare(state, child(0)->row_desc(), // intermediate_slot_desc, output_slot_desc, _agg_fn_pool.get(), &agg_fn_ctx)); RETURN_IF_ERROR(_aggregate_evaluators[i]->prepare(state, child(0)->row_desc(), _agg_fn_pool.get(), output_slot_desc, output_slot_desc, expr_mem_tracker(), &agg_fn_ctx)); _agg_fn_ctxs.push_back(agg_fn_ctx); state->obj_pool()->add(agg_fn_ctx); _needs_serialize |= _aggregate_evaluators[i]->supports_serialize(); } if (_probe_expr_ctxs.empty()) { // Create single output tuple now; we need to output something // even if our input is empty. _singleton_output_tuple = construct_intermediate_tuple(_agg_fn_ctxs, _mem_pool.get(), NULL, NULL); // Check for failures during AggFnEvaluator::init(). RETURN_IF_ERROR(_state->query_status()); _singleton_output_tuple_returned = false; } else { _ht_ctx.reset(new PartitionedHashTableCtx(_build_expr_ctxs, _probe_expr_ctxs, true, true, state->fragment_hash_seed(), MAX_PARTITION_DEPTH, 1)); RETURN_IF_ERROR(_state->block_mgr2()->register_client( min_required_buffers(), mem_tracker(), state, &_block_mgr_client)); RETURN_IF_ERROR(create_hash_partitions(0)); } // TODO: Is there a need to create the stream here? If memory reservations work we may // be able to create this stream lazily and only whenever we need to spill. if (_needs_serialize && _block_mgr_client != NULL) { _serialize_stream.reset(new BufferedTupleStream2(state, *_intermediate_row_desc, state->block_mgr2(), _block_mgr_client, false /* use_initial_small_buffers */, false /* read_write */)); RETURN_IF_ERROR(_serialize_stream->init(id(), runtime_profile(), false)); DCHECK(_serialize_stream->has_write_block()); } // if (state->codegen_enabled()) { // LlvmCodeGen* codegen; // RETURN_IF_ERROR(state->get_codegen(&codegen)); // Function* codegen_process_row_batch_fn = codegen_process_batch(); // if (codegen_process_row_batch_fn != NULL) { // codegen->AddFunctionToJit(codegen_process_row_batch_fn, // reinterpret_cast<void**>(&_process_row_batch_fn)); // add_runtime_exec_option("Codegen Enabled"); // } // } return Status::OK(); } Status PartitionedAggregationNode::open(RuntimeState* state) { SCOPED_TIMER(_runtime_profile->total_time_counter()); RETURN_IF_ERROR(ExecNode::open(state)); RETURN_IF_ERROR(Expr::open(_probe_expr_ctxs, state)); RETURN_IF_ERROR(Expr::open(_build_expr_ctxs, state)); DCHECK_EQ(_aggregate_evaluators.size(), _agg_fn_ctxs.size()); for (int i = 0; i < _aggregate_evaluators.size(); ++i) { RETURN_IF_ERROR(_aggregate_evaluators[i]->open(state, _agg_fn_ctxs[i])); } // Read all the rows from the child and process them. RETURN_IF_ERROR(_children[0]->open(state)); RowBatch batch(_children[0]->row_desc(), state->batch_size(), mem_tracker()); bool eos = false; do { RETURN_IF_CANCELLED(state); RETURN_IF_ERROR(state->check_query_state("Partitioned aggregation, while getting next from child 0.")); RETURN_IF_ERROR(_children[0]->get_next(state, &batch, &eos)); if (UNLIKELY(VLOG_ROW_IS_ON)) { for (int i = 0; i < batch.num_rows(); ++i) { TupleRow* row = batch.get_row(i); VLOG_ROW << "partition-agg-node input row: " << row->to_string(_children[0]->row_desc()); } } SCOPED_TIMER(_build_timer); if (_process_row_batch_fn != NULL) { RETURN_IF_ERROR(_process_row_batch_fn(this, &batch, _ht_ctx.get())); } else if (_probe_expr_ctxs.empty()) { RETURN_IF_ERROR(process_batch_no_grouping(&batch)); } else { // VLOG_ROW << "partition-agg-node batch: " << batch->to_string(); // There is grouping, so we will do partitioned aggregation. RETURN_IF_ERROR(process_batch<false>(&batch, _ht_ctx.get())); } batch.reset(); } while (!eos); // Unless we are inside a subplan expecting to call open()/get_next() on the child // again, the child can be closed at this point. We have consumed all of the input // from the child and transfered ownership of the resources we need. // if (!IsInSubplan()) { child(0)->close(state); // } // Done consuming child(0)'s input. Move all the partitions in _hash_partitions // to _spilled_partitions/_aggregated_partitions. We'll finish the processing in // get_next(). if (!_probe_expr_ctxs.empty()) { RETURN_IF_ERROR(move_hash_partitions(child(0)->rows_returned())); } return Status::OK(); } Status PartitionedAggregationNode::get_next(RuntimeState* state, RowBatch* row_batch, bool* eos) { SCOPED_TIMER(_runtime_profile->total_time_counter()); RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::GETNEXT)); RETURN_IF_CANCELLED(state); RETURN_IF_ERROR(state->check_query_state("Partitioned aggregation, before evaluating conjuncts.")); if (reached_limit()) { *eos = true; return Status::OK(); } ExprContext** ctxs = &_conjunct_ctxs[0]; int num_ctxs = _conjunct_ctxs.size(); if (_probe_expr_ctxs.empty()) { // There was grouping, so evaluate the conjuncts and return the single result row. // We allow calling get_next() after eos, so don't return this row again. if (!_singleton_output_tuple_returned) { int row_idx = row_batch->add_row(); TupleRow* row = row_batch->get_row(row_idx); Tuple* output_tuple = get_output_tuple( _agg_fn_ctxs, _singleton_output_tuple, row_batch->tuple_data_pool()); row->set_tuple(0, output_tuple); if (ExecNode::eval_conjuncts(ctxs, num_ctxs, row)) { row_batch->commit_last_row(); ++_num_rows_returned; } _singleton_output_tuple_returned = true; } // Keep the current chunk to amortize the memory allocation over a series // of reset()/open()/get_next()* calls. row_batch->tuple_data_pool()->acquire_data(_mem_pool.get(), true); *eos = true; COUNTER_SET(_rows_returned_counter, _num_rows_returned); return Status::OK(); } if (_output_iterator.at_end()) { // Done with this partition, move onto the next one. if (_output_partition != NULL) { _output_partition->close(false); _output_partition = NULL; } if (_aggregated_partitions.empty() && _spilled_partitions.empty()) { // No more partitions, all done. *eos = true; return Status::OK(); } // Process next partition. RETURN_IF_ERROR(next_partition()); DCHECK(_output_partition != NULL); } SCOPED_TIMER(_get_results_timer); int count = 0; const int N = BitUtil::next_power_of_two(state->batch_size()); // Keeping returning rows from the current partition. while (!_output_iterator.at_end() && !row_batch->at_capacity()) { // This loop can go on for a long time if the conjuncts are very selective. Do query // maintenance every N iterations. if ((count++ & (N - 1)) == 0) { RETURN_IF_CANCELLED(state); RETURN_IF_ERROR(state->check_query_state("Partitioned aggregation, while evaluating conjuncts.")); } int row_idx = row_batch->add_row(); TupleRow* row = row_batch->get_row(row_idx); Tuple* intermediate_tuple = _output_iterator.get_tuple(); Tuple* output_tuple = get_output_tuple( _output_partition->agg_fn_ctxs, intermediate_tuple, row_batch->tuple_data_pool()); _output_iterator.next(); row->set_tuple(0, output_tuple); if (ExecNode::eval_conjuncts(ctxs, num_ctxs, row)) { row_batch->commit_last_row(); ++_num_rows_returned; if (reached_limit()) { break; // TODO: remove this check? is this expensive? } } } COUNTER_SET(_rows_returned_counter, _num_rows_returned); *eos = reached_limit(); if (_output_iterator.at_end()) { row_batch->mark_need_to_return(); } return Status::OK(); } void PartitionedAggregationNode::cleanup_hash_tbl( const vector<FunctionContext*>& agg_fn_ctxs, PartitionedHashTable::Iterator it) { if (!_needs_finalize && !_needs_serialize) { return; } // Iterate through the remaining rows in the hash table and call serialize/finalize on // them in order to free any memory allocated by UDAs. if (_needs_finalize) { // finalize() requires a dst tuple but we don't actually need the result, // so allocate a single dummy tuple to avoid accumulating memory. Tuple* dummy_dst = NULL; dummy_dst = Tuple::create(_output_tuple_desc->byte_size(), _mem_pool.get()); while (!it.at_end()) { Tuple* tuple = it.get_tuple(); AggFnEvaluator::finalize(_aggregate_evaluators, agg_fn_ctxs, tuple, dummy_dst); it.next(); } } else { while (!it.at_end()) { Tuple* tuple = it.get_tuple(); AggFnEvaluator::serialize(_aggregate_evaluators, agg_fn_ctxs, tuple); it.next(); } } } Status PartitionedAggregationNode::reset(RuntimeState* state) { if (_probe_expr_ctxs.empty()) { // Re-create the single output tuple for this non-grouping agg. _singleton_output_tuple = construct_intermediate_tuple(_agg_fn_ctxs, _mem_pool.get(), NULL, NULL); // Check for failures during AggFnEvaluator::init(). RETURN_IF_ERROR(_state->query_status()); _singleton_output_tuple_returned = false; } else { // Reset the HT and the partitions for this grouping agg. _ht_ctx->set_level(0); close_partitions(); create_hash_partitions(0); } // return ExecNode::reset(state); return Status::OK(); } Status PartitionedAggregationNode::close(RuntimeState* state) { if (is_closed()) { return Status::OK(); } if (!_singleton_output_tuple_returned) { DCHECK_EQ(_agg_fn_ctxs.size(), _aggregate_evaluators.size()); get_output_tuple(_agg_fn_ctxs, _singleton_output_tuple, _mem_pool.get()); } // Iterate through the remaining rows in the hash table and call serialize/finalize on // them in order to free any memory allocated by UDAs if (_output_partition != NULL) { cleanup_hash_tbl(_output_partition->agg_fn_ctxs, _output_iterator); _output_partition->close(false); } close_partitions(); for (int i = 0; i < _aggregate_evaluators.size(); ++i) { _aggregate_evaluators[i]->close(state); } for (int i = 0; i < _agg_fn_ctxs.size(); ++i) { _agg_fn_ctxs[i]->impl()->close(); } if (_agg_fn_pool.get() != NULL) { _agg_fn_pool->free_all(); } if (_mem_pool.get() != NULL) { _mem_pool->free_all(); } if (_ht_ctx.get() != NULL) { _ht_ctx->close(); } if (_serialize_stream.get() != NULL) { _serialize_stream->close(); } if (_block_mgr_client != NULL) { state->block_mgr2()->clear_reservations(_block_mgr_client); } Expr::close(_probe_expr_ctxs, state); Expr::close(_build_expr_ctxs, state); return ExecNode::close(state); } Status PartitionedAggregationNode::Partition::init_streams() { agg_fn_pool.reset(new MemPool(parent->expr_mem_tracker())); DCHECK_EQ(agg_fn_ctxs.size(), 0); for (int i = 0; i < parent->_agg_fn_ctxs.size(); ++i) { agg_fn_ctxs.push_back(parent->_agg_fn_ctxs[i]->impl()->clone(agg_fn_pool.get())); parent->_partition_pool->add(agg_fn_ctxs[i]); } aggregated_row_stream.reset(new BufferedTupleStream2(parent->_state, *parent->_intermediate_row_desc, parent->_state->block_mgr2(), parent->_block_mgr_client, true /* use_initial_small_buffers */, false /* read_write */)); RETURN_IF_ERROR(aggregated_row_stream->init(parent->id(), parent->runtime_profile(), true)); unaggregated_row_stream.reset(new BufferedTupleStream2(parent->_state, parent->child(0)->row_desc(), parent->_state->block_mgr2(), parent->_block_mgr_client, true /* use_initial_small_buffers */, false /* read_write */)); // This stream is only used to spill, no need to ever have this pinned. RETURN_IF_ERROR(unaggregated_row_stream->init(parent->id(), parent->runtime_profile(), false)); DCHECK(unaggregated_row_stream->has_write_block()); return Status::OK(); } bool PartitionedAggregationNode::Partition::init_hash_table() { DCHECK(hash_tbl.get() == NULL); // We use the upper PARTITION_FANOUT num bits to pick the partition so only the // remaining bits can be used for the hash table. // TODO: we could switch to 64 bit hashes and then we don't need a max size. // It might be reasonable to limit individual hash table size for other reasons // though. Always start with small buffers. // TODO: How many buckets? We currently use a default value, 1024. static const int64_t PAGG_DEFAULT_HASH_TABLE_SZ = 1024; hash_tbl.reset(PartitionedHashTable::create(parent->_state, parent->_block_mgr_client, 1, NULL, 1 << (32 - NUM_PARTITIONING_BITS), PAGG_DEFAULT_HASH_TABLE_SZ)); return hash_tbl->init(); } Status PartitionedAggregationNode::Partition::clean_up() { if (parent->_needs_serialize && aggregated_row_stream->num_rows() != 0) { // We need to do a lot more work in this case. This step effectively does a merge // aggregation in this node. We need to serialize the intermediates, spill the // intermediates and then feed them into the aggregate function's merge step. // This is often used when the intermediate is a string type, meaning the current // (before serialization) in-memory layout is not the on-disk block layout. // The disk layout does not support mutable rows. We need to rewrite the stream // into the on disk format. // TODO: if it happens to not be a string, we could serialize in place. This is // a future optimization since it is very unlikely to have a serialize phase // for those UDAs. DCHECK(parent->_serialize_stream.get() != NULL); DCHECK(!parent->_serialize_stream->is_pinned()); DCHECK(parent->_serialize_stream->has_write_block()); const vector<AggFnEvaluator*>& evaluators = parent->_aggregate_evaluators; // serialize and copy the spilled partition's stream into the new stream. Status status = Status::OK(); bool failed_to_add = false; BufferedTupleStream2* new_stream = parent->_serialize_stream.get(); PartitionedHashTable::Iterator it = hash_tbl->begin(parent->_ht_ctx.get()); while (!it.at_end()) { Tuple* tuple = it.get_tuple(); it.next(); AggFnEvaluator::serialize(evaluators, agg_fn_ctxs, tuple); if (UNLIKELY(!new_stream->add_row(reinterpret_cast<TupleRow*>(&tuple), &status))) { failed_to_add = true; break; } } // Even if we can't add to new_stream, finish up processing this agg stream to make // clean up easier (someone has to finalize this stream and we don't want to remember // where we are). if (failed_to_add) { parent->cleanup_hash_tbl(agg_fn_ctxs, it); hash_tbl->close(); hash_tbl.reset(); aggregated_row_stream->close(); RETURN_IF_ERROR(status); return parent->_state->block_mgr2()->mem_limit_too_low_error(parent->_block_mgr_client, parent->id()); } DCHECK(status.ok()); aggregated_row_stream->close(); aggregated_row_stream.swap(parent->_serialize_stream); // Recreate the serialize_stream (and reserve 1 buffer) now in preparation for // when we need to spill again. We need to have this available before we need // to spill to make sure it is available. This should be acquirable since we just // freed at least one buffer from this partition's (old) aggregated_row_stream. parent->_serialize_stream.reset(new BufferedTupleStream2(parent->_state, *parent->_intermediate_row_desc, parent->_state->block_mgr2(), parent->_block_mgr_client, false /* use_initial_small_buffers */, false /* read_write */)); status = parent->_serialize_stream->init(parent->id(), parent->runtime_profile(), false); if (!status.ok()) { hash_tbl->close(); hash_tbl.reset(); return status; } DCHECK(parent->_serialize_stream->has_write_block()); } return Status::OK(); } Status PartitionedAggregationNode::Partition::spill() { DCHECK(!is_closed); DCHECK(!is_spilled()); RETURN_IF_ERROR(clean_up()); // Free the in-memory result data. for (int i = 0; i < agg_fn_ctxs.size(); ++i) { agg_fn_ctxs[i]->impl()->close(); } if (agg_fn_pool.get() != NULL) { agg_fn_pool->free_all(); agg_fn_pool.reset(); } hash_tbl->close(); hash_tbl.reset(); // Try to switch both streams to IO-sized buffers to avoid allocating small buffers // for spilled partition. bool got_buffer = true; if (aggregated_row_stream->using_small_buffers()) { RETURN_IF_ERROR(aggregated_row_stream->switch_to_io_buffers(&got_buffer)); } // Unpin the stream as soon as possible to increase the changes that the // switch_to_io_buffers() call below will succeed. DCHECK(!got_buffer || aggregated_row_stream->has_write_block()) << aggregated_row_stream->debug_string(); RETURN_IF_ERROR(aggregated_row_stream->unpin_stream(false)); if (got_buffer && unaggregated_row_stream->using_small_buffers()) { RETURN_IF_ERROR(unaggregated_row_stream->switch_to_io_buffers(&got_buffer)); } if (!got_buffer) { // We'll try again to get the buffers when the stream fills up the small buffers. VLOG_QUERY << "Not enough memory to switch to IO-sized buffer for partition " << this << " of agg=" << parent->_id << " agg small buffers=" << aggregated_row_stream->using_small_buffers() << " unagg small buffers=" << unaggregated_row_stream->using_small_buffers(); VLOG_FILE << get_stack_trace(); } COUNTER_UPDATE(parent->_num_spilled_partitions, 1); if (parent->_num_spilled_partitions->value() == 1) { parent->add_runtime_exec_option("Spilled"); } return Status::OK(); } void PartitionedAggregationNode::Partition::close(bool finalize_rows) { if (is_closed) { return; } is_closed = true; if (aggregated_row_stream.get() != NULL) { if (finalize_rows && hash_tbl.get() != NULL) { // We need to walk all the rows and finalize them here so the UDA gets a chance // to cleanup. If the hash table is gone (meaning this was spilled), the rows // should have been finalized/serialized in spill(). parent->cleanup_hash_tbl(agg_fn_ctxs, hash_tbl->begin(parent->_ht_ctx.get())); } aggregated_row_stream->close(); } if (hash_tbl.get() != NULL) { hash_tbl->close(); } if (unaggregated_row_stream.get() != NULL) { unaggregated_row_stream->close(); } for (int i = 0; i < agg_fn_ctxs.size(); ++i) { agg_fn_ctxs[i]->impl()->close(); } if (agg_fn_pool.get() != NULL) { agg_fn_pool->free_all(); } } Tuple* PartitionedAggregationNode::construct_intermediate_tuple( const vector<FunctionContext*>& agg_fn_ctxs, MemPool* pool, BufferedTupleStream2* stream, Status* status) { Tuple* intermediate_tuple = NULL; uint8_t* buffer = NULL; if (pool != NULL) { DCHECK(stream == NULL && status == NULL); intermediate_tuple = Tuple::create(_intermediate_tuple_desc->byte_size(), pool); } else { DCHECK(stream != NULL && status != NULL); // Figure out how big it will be to copy the entire tuple. We need the tuple to end // up in one block in the stream. int size = _intermediate_tuple_desc->byte_size(); if (_contains_var_len_grouping_exprs) { // TODO: This is likely to be too slow. The hash table could maintain this as // it hashes. for (int i = 0; i < _probe_expr_ctxs.size(); ++i) { if (!_probe_expr_ctxs[i]->root()->type().is_string_type()) { continue; } if (_ht_ctx->last_expr_value_null(i)) { continue; } StringValue* sv = reinterpret_cast<StringValue*>(_ht_ctx->last_expr_value(i)); size += sv->len; } } // Now that we know the size of the row, allocate space for it in the stream. buffer = stream->allocate_row(size, status); if (buffer == NULL) { if (!status->ok() || !stream->using_small_buffers()) { return NULL; } // IMPALA-2352: Make a best effort to switch to IO buffers and re-allocate. // If switch_to_io_buffers() fails the caller of this function can try to free // some space, e.g. through spilling, and re-attempt to allocate space for // this row. bool got_buffer = false; *status = stream->switch_to_io_buffers(&got_buffer); if (!status->ok() || !got_buffer) { return NULL; } buffer = stream->allocate_row(size, status); if (buffer == NULL) { return NULL; } } intermediate_tuple = reinterpret_cast<Tuple*>(buffer); // TODO: remove this. we shouldn't need to zero the entire tuple. intermediate_tuple->init(size); buffer += _intermediate_tuple_desc->byte_size(); } // Copy grouping values. vector<SlotDescriptor*>::const_iterator slot_desc = _intermediate_tuple_desc->slots().begin(); for (int i = 0; i < _probe_expr_ctxs.size(); ++i, ++slot_desc) { if (_ht_ctx->last_expr_value_null(i)) { intermediate_tuple->set_null((*slot_desc)->null_indicator_offset()); } else { void* src = _ht_ctx->last_expr_value(i); void* dst = intermediate_tuple->get_slot((*slot_desc)->tuple_offset()); if (stream == NULL) { RawValue::write(src, dst, (*slot_desc)->type(), pool); } else { RawValue::write(src, (*slot_desc)->type(), dst, &buffer); } } } // Initialize aggregate output. for (int i = 0; i < _aggregate_evaluators.size(); ++i, ++slot_desc) { while (!(*slot_desc)->is_materialized()) { ++slot_desc; } AggFnEvaluator* evaluator = _aggregate_evaluators[i]; evaluator->init(agg_fn_ctxs[i], intermediate_tuple); // Codegen specific path for min/max. // To minimize branching on the update_tuple path, initialize the result value // so that update_tuple doesn't have to check if the aggregation // dst slot is null. // TODO: remove when we don't use the irbuilder for codegen here. This optimization // will no longer be necessary when all aggregates are implemented with the UDA // interface. // if ((*slot_desc)->type().type != TYPE_STRING && // (*slot_desc)->type().type != TYPE_VARCHAR && // (*slot_desc)->type().type != TYPE_TIMESTAMP && // (*slot_desc)->type().type != TYPE_CHAR && // (*slot_desc)->type().type != TYPE_DECIMAL) { if (!(*slot_desc)->type().is_string_type() && !(*slot_desc)->type().is_date_type()) { ExprValue default_value; void* default_value_ptr = NULL; switch (evaluator->agg_op()) { case AggFnEvaluator::MIN: default_value_ptr = default_value.set_to_max((*slot_desc)->type()); RawValue::write(default_value_ptr, intermediate_tuple, *slot_desc, NULL); break; case AggFnEvaluator::MAX: default_value_ptr = default_value.set_to_min((*slot_desc)->type()); RawValue::write(default_value_ptr, intermediate_tuple, *slot_desc, NULL); break; default: break; } } } return intermediate_tuple; } void PartitionedAggregationNode::update_tuple(FunctionContext** agg_fn_ctxs, Tuple* tuple, TupleRow* row, bool is_merge) { DCHECK(tuple != NULL || _aggregate_evaluators.empty()); for (int i = 0; i < _aggregate_evaluators.size(); ++i) { if (is_merge) { _aggregate_evaluators[i]->merge(agg_fn_ctxs[i], row->get_tuple(0), tuple); } else { _aggregate_evaluators[i]->add(agg_fn_ctxs[i], row, tuple); } } } Tuple* PartitionedAggregationNode::get_output_tuple( const vector<FunctionContext*>& agg_fn_ctxs, Tuple* tuple, MemPool* pool) { DCHECK(tuple != NULL || _aggregate_evaluators.empty()) << tuple; Tuple* dst = tuple; // if (_needs_finalize && _intermediate_tuple_id != _output_tuple_id) { if (_needs_finalize) { dst = Tuple::create(_output_tuple_desc->byte_size(), pool); } if (_needs_finalize) { AggFnEvaluator::finalize(_aggregate_evaluators, agg_fn_ctxs, tuple, dst); } else { AggFnEvaluator::serialize(_aggregate_evaluators, agg_fn_ctxs, tuple); } // Copy grouping values from tuple to dst. // TODO: Codegen this. if (dst != tuple) { int num_grouping_slots = _probe_expr_ctxs.size(); for (int i = 0; i < num_grouping_slots; ++i) { SlotDescriptor* src_slot_desc = _intermediate_tuple_desc->slots()[i]; SlotDescriptor* dst_slot_desc = _output_tuple_desc->slots()[i]; bool src_slot_null = tuple->is_null(src_slot_desc->null_indicator_offset()); void* src_slot = NULL; if (!src_slot_null) { src_slot = tuple->get_slot(src_slot_desc->tuple_offset()); } RawValue::write(src_slot, dst, dst_slot_desc, NULL); } } return dst; } Status PartitionedAggregationNode::append_spilled_row(BufferedTupleStream2* stream, TupleRow* row) { DCHECK(stream != NULL); DCHECK(!stream->is_pinned()); DCHECK(stream->has_write_block()); if (LIKELY(stream->add_row(row, &_process_batch_status))) { return Status::OK(); } // Adding fails iff either we hit an error or haven't switched to I/O buffers. RETURN_IF_ERROR(_process_batch_status); while (true) { bool got_buffer = false; RETURN_IF_ERROR(stream->switch_to_io_buffers(&got_buffer)); if (got_buffer) { break; } RETURN_IF_ERROR(spill_partition()); } // Adding the row should succeed after the I/O buffer switch. if (stream->add_row(row, &_process_batch_status)) { return Status::OK(); } DCHECK(!_process_batch_status.ok()); return _process_batch_status; } void PartitionedAggregationNode::debug_string(int indentation_level, stringstream* out) const { *out << string(indentation_level * 2, ' '); *out << "PartitionedAggregationNode(" << "intermediate_tuple_id=" << _intermediate_tuple_id << " output_tuple_id=" << _output_tuple_id << " needs_finalize=" << _needs_finalize << " probe_exprs=" << Expr::debug_string(_probe_expr_ctxs) << " agg_exprs=" << AggFnEvaluator::debug_string(_aggregate_evaluators); ExecNode::debug_string(indentation_level, out); *out << ")"; } Status PartitionedAggregationNode::create_hash_partitions(int level) { if (level >= MAX_PARTITION_DEPTH) { stringstream error_msg; error_msg << "Cannot perform aggregation at hash aggregation node with id " << _id << '.' << " The input data was partitioned the maximum number of " << MAX_PARTITION_DEPTH << " times." << " This could mean there is significant skew in the data or the memory limit is" << " set too low."; return _state->set_mem_limit_exceeded(error_msg.str()); } _ht_ctx->set_level(level); DCHECK(_hash_partitions.empty()); for (int i = 0; i < PARTITION_FANOUT; ++i) { Partition* new_partition = new Partition(this, level); DCHECK(new_partition != NULL); _hash_partitions.push_back(_partition_pool->add(new_partition)); RETURN_IF_ERROR(new_partition->init_streams()); } DCHECK_GT(_state->block_mgr2()->num_reserved_buffers_remaining(_block_mgr_client), 0); // Now that all the streams are reserved (meaning we have enough memory to execute // the algorithm), allocate the hash tables. These can fail and we can still continue. for (int i = 0; i < PARTITION_FANOUT; ++i) { if (!_hash_partitions[i]->init_hash_table()) { RETURN_IF_ERROR(_hash_partitions[i]->spill()); } } COUNTER_UPDATE(_partitions_created, PARTITION_FANOUT); // COUNTER_SET(_max_partition_level, level); return Status::OK(); } Status PartitionedAggregationNode::check_and_resize_hash_partitions(int num_rows, PartitionedHashTableCtx* ht_ctx) { for (int i = 0; i < PARTITION_FANOUT; ++i) { Partition* partition = _hash_partitions[i]; while (!partition->is_spilled()) { { SCOPED_TIMER(_ht_resize_timer); if (partition->hash_tbl->check_and_resize(num_rows, ht_ctx)) { break; } } // There was not enough memory for the resize. Spill a partition and retry. RETURN_IF_ERROR(spill_partition()); } } return Status::OK(); } int64_t PartitionedAggregationNode::largest_spilled_partition() const { int64_t max_rows = 0; for (int i = 0; i < _hash_partitions.size(); ++i) { Partition* partition = _hash_partitions[i]; if (partition->is_closed || !partition->is_spilled()) { continue; } int64_t rows = partition->aggregated_row_stream->num_rows() + partition->unaggregated_row_stream->num_rows(); if (rows > max_rows) { max_rows = rows; } } return max_rows; } Status PartitionedAggregationNode::next_partition() { DCHECK(_output_partition == NULL); // Keep looping until we get to a partition that fits in memory. Partition* partition = NULL; while (true) { partition = NULL; // First return partitions that are fully aggregated (and in memory). if (!_aggregated_partitions.empty()) { partition = _aggregated_partitions.front(); DCHECK(!partition->is_spilled()); _aggregated_partitions.pop_front(); break; } if (partition == NULL) { DCHECK(!_spilled_partitions.empty()); DCHECK_EQ(_state->block_mgr2()->num_pinned_buffers(_block_mgr_client), _needs_serialize ? 1 : 0); // TODO: we can probably do better than just picking the first partition. We // can base this on the amount written to disk, etc. partition = _spilled_partitions.front(); DCHECK(partition->is_spilled()); // Create the new hash partitions to repartition into. // TODO: we don't need to repartition here. We are now working on 1 / FANOUT // of the input so it's reasonably likely it can fit. We should look at this // partitions size and just do the aggregation if it fits in memory. RETURN_IF_ERROR(create_hash_partitions(partition->level + 1)); COUNTER_UPDATE(_num_repartitions, 1); // Rows in this partition could have been spilled into two streams, depending // on if it is an aggregated intermediate, or an unaggregated row. // Note: we must process the aggregated rows first to save a hash table lookup // in process_batch(). RETURN_IF_ERROR(process_stream<true>(partition->aggregated_row_stream.get())); RETURN_IF_ERROR(process_stream<false>(partition->unaggregated_row_stream.get())); COUNTER_UPDATE(_num_row_repartitioned, partition->aggregated_row_stream->num_rows()); COUNTER_UPDATE(_num_row_repartitioned, partition->unaggregated_row_stream->num_rows()); partition->close(false); _spilled_partitions.pop_front(); // Done processing this partition. Move the new partitions into // _spilled_partitions/_aggregated_partitions. int64_t num_input_rows = partition->aggregated_row_stream->num_rows() + partition->unaggregated_row_stream->num_rows(); // Check if there was any reduction in the size of partitions after repartitioning. int64_t largest_partition = largest_spilled_partition(); DCHECK_GE(num_input_rows, largest_partition) << "Cannot have a partition with " "more rows than the input"; if (num_input_rows == largest_partition) { // Status status = Status::MemTrackerExceeded(); // status.AddDetail(Substitute("Cannot perform aggregation at node with id $0. " // "Repartitioning did not reduce the size of a spilled partition. " // "Repartitioning level $1. Number of rows $2.", // _id, partition->level + 1, num_input_rows)); // _state->SetMemTrackerExceeded(); stringstream error_msg; error_msg << "Cannot perform aggregation at node with id " << _id << ". " << "Repartitioning did not reduce the size of a spilled partition. " << "Repartitioning level " << partition->level + 1 << ". Number of rows " << num_input_rows << " ."; return Status::MemoryLimitExceeded(error_msg.str()); } RETURN_IF_ERROR(move_hash_partitions(num_input_rows)); } } DCHECK(partition->hash_tbl.get() != NULL); DCHECK(partition->aggregated_row_stream->is_pinned()); _output_partition = partition; _output_iterator = _output_partition->hash_tbl->begin(_ht_ctx.get()); COUNTER_UPDATE(_num_hash_buckets, _output_partition->hash_tbl->num_buckets()); return Status::OK(); } template<bool AGGREGATED_ROWS> Status PartitionedAggregationNode::process_stream(BufferedTupleStream2* input_stream) { if (input_stream->num_rows() > 0) { while (true) { bool got_buffer = false; RETURN_IF_ERROR(input_stream->prepare_for_read(true, &got_buffer)); if (got_buffer) { break; } // Did not have a buffer to read the input stream. Spill and try again. RETURN_IF_ERROR(spill_partition()); } bool eos = false; RowBatch batch(AGGREGATED_ROWS ? *_intermediate_row_desc : _children[0]->row_desc(), _state->batch_size(), mem_tracker()); do { RETURN_IF_ERROR(input_stream->get_next(&batch, &eos)); RETURN_IF_ERROR(process_batch<AGGREGATED_ROWS>(&batch, _ht_ctx.get())); RETURN_IF_ERROR(_state->query_status()); // free_local_allocations(); batch.reset(); } while (!eos); } input_stream->close(); return Status::OK(); } Status PartitionedAggregationNode::spill_partition() { int64_t max_freed_mem = 0; int partition_idx = -1; // Iterate over the partitions and pick the largest partition that is not spilled. for (int i = 0; i < _hash_partitions.size(); ++i) { if (_hash_partitions[i]->is_closed) { continue; } if (_hash_partitions[i]->is_spilled()) { continue; } // TODO: In PHJ the bytes_in_mem() call also calculates the mem used by the // _write_block, why do we ignore it here? int64_t mem = _hash_partitions[i]->aggregated_row_stream->bytes_in_mem(true); mem += _hash_partitions[i]->hash_tbl->byte_size(); mem += _hash_partitions[i]->agg_fn_pool->total_reserved_bytes(); if (mem > max_freed_mem) { max_freed_mem = mem; partition_idx = i; } } if (partition_idx == -1) { // Could not find a partition to spill. This means the mem limit was just too low. return _state->block_mgr2()->mem_limit_too_low_error(_block_mgr_client, id()); } return _hash_partitions[partition_idx]->spill(); } Status PartitionedAggregationNode::move_hash_partitions(int64_t num_input_rows) { DCHECK(!_hash_partitions.empty()); stringstream ss; ss << "PA(node_id=" << id() << ") partitioned(level=" << _hash_partitions[0]->level << ") " << num_input_rows << " rows into:" << std::endl; for (int i = 0; i < _hash_partitions.size(); ++i) { Partition* partition = _hash_partitions[i]; int64_t aggregated_rows = partition->aggregated_row_stream->num_rows(); int64_t unaggregated_rows = partition->unaggregated_row_stream->num_rows(); int64_t total_rows = aggregated_rows + unaggregated_rows; double percent = static_cast<double>(total_rows * 100) / num_input_rows; ss << " " << i << " " << (partition->is_spilled() ? "spilled" : "not spilled") << " (fraction=" << std::fixed << std::setprecision(2) << percent << "%)" << std::endl << " #aggregated rows:" << aggregated_rows << std::endl << " #unaggregated rows: " << unaggregated_rows << std::endl; // TODO: update counters to support doubles. // COUNTER_SET(_largest_partition_percent, static_cast<int64_t>(percent)); if (total_rows == 0) { partition->close(false); } else if (partition->is_spilled()) { DCHECK(partition->hash_tbl.get() == NULL); // We need to unpin all the spilled partitions to make room to allocate new // _hash_partitions when we repartition the spilled partitions. // TODO: we only need to do this when we have memory pressure. This might be // okay though since the block mgr should only write these to disk if there // is memory pressure. RETURN_IF_ERROR(partition->aggregated_row_stream->unpin_stream(true)); RETURN_IF_ERROR(partition->unaggregated_row_stream->unpin_stream(true)); // Push new created partitions at the front. This means a depth first walk // (more finely partitioned partitions are processed first). This allows us // to delete blocks earlier and bottom out the recursion earlier. _spilled_partitions.push_front(partition); } else { _aggregated_partitions.push_back(partition); } } VLOG(2) << ss.str(); _hash_partitions.clear(); return Status::OK(); } void PartitionedAggregationNode::close_partitions() { for (int i = 0; i < _hash_partitions.size(); ++i) { _hash_partitions[i]->close(true); } for (list<Partition*>::iterator it = _aggregated_partitions.begin(); it != _aggregated_partitions.end(); ++it) { (*it)->close(true); } for (list<Partition*>::iterator it = _spilled_partitions.begin(); it != _spilled_partitions.end(); ++it) { (*it)->close(true); } _aggregated_partitions.clear(); _spilled_partitions.clear(); _hash_partitions.clear(); _partition_pool->clear(); } #if 0 // Status PartitionedAggregationNode::QueryMaintenance(RuntimeState* state) { // for (int i = 0; i < _aggregate_evaluators.size(); ++i) { // ExprContext::free_local_allocations(_aggregate_evaluators[i]->input_expr_ctxs()); // } // ExprContext::free_local_allocations(_agg_fn_ctxs); // for (int i = 0; i < _hash_partitions.size(); ++i) { // ExprContext::free_local_allocations(_hash_partitions[i]->agg_fn_ctxs); // } // return ExecNode::QueryMaintenance(state); // } // IR Generation for updating a single aggregation slot. Signature is: // void UpdateSlot(FunctionContext* fn_ctx, AggTuple* agg_tuple, char** row) // // The IR for sum(double_col) is: // define void @UpdateSlot(%"class.doris_udf::FunctionContext"* %fn_ctx, // { i8, double }* %agg_tuple, // %"class.doris::TupleRow"* %row) #20 { // entry: // %src = call { i8, double } @GetSlotRef(%"class.doris::ExprContext"* inttoptr // (i64 128241264 to %"class.doris::ExprContext"*), %"class.doris::TupleRow"* %row) // %0 = extractvalue { i8, double } %src, 0 // %is_null = trunc i8 %0 to i1 // br i1 %is_null, label %ret, label %src_not_null // // src_not_null: ; preds = %entry // %dst_slot_ptr = getelementptr inbounds { i8, double }* %agg_tuple, i32 0, i32 1 // call void @SetNotNull({ i8, double }* %agg_tuple) // %dst_val = load double* %dst_slot_ptr // %val = extractvalue { i8, double } %src, 1 // %1 = fadd double %dst_val, %val // store double %1, double* %dst_slot_ptr // br label %ret // // ret: ; preds = %src_not_null, %entry // ret void // } // // The IR for ndv(double_col) is: // define void @UpdateSlot(%"class.doris_udf::FunctionContext"* %fn_ctx, // { i8, %"struct.doris::StringValue" }* %agg_tuple, // %"class.doris::TupleRow"* %row) #20 { // entry: // %dst_lowered_ptr = alloca { i64, i8* } // %src_lowered_ptr = alloca { i8, double } // %src = call { i8, double } @GetSlotRef(%"class.doris::ExprContext"* inttoptr // (i64 120530832 to %"class.doris::ExprContext"*), %"class.doris::TupleRow"* %row) // %0 = extractvalue { i8, double } %src, 0 // %is_null = trunc i8 %0 to i1 // br i1 %is_null, label %ret, label %src_not_null // // src_not_null: ; preds = %entry // %dst_slot_ptr = getelementptr inbounds // { i8, %"struct.doris::StringValue" }* %agg_tuple, i32 0, i32 1 // call void @SetNotNull({ i8, %"struct.doris::StringValue" }* %agg_tuple) // %dst_val = load %"struct.doris::StringValue"* %dst_slot_ptr // store { i8, double } %src, { i8, double }* %src_lowered_ptr // %src_unlowered_ptr = bitcast { i8, double }* %src_lowered_ptr // to %"struct.doris_udf::DoubleVal"* // %ptr = extractvalue %"struct.doris::StringValue" %dst_val, 0 // %dst_stringval = insertvalue { i64, i8* } zeroinitializer, i8* %ptr, 1 // %len = extractvalue %"struct.doris::StringValue" %dst_val, 1 // %1 = extractvalue { i64, i8* } %dst_stringval, 0 // %2 = zext i32 %len to i64 // %3 = shl i64 %2, 32 // %4 = and i64 %1, 4294967295 // %5 = or i64 %4, %3 // %dst_stringval1 = insertvalue { i64, i8* } %dst_stringval, i64 %5, 0 // store { i64, i8* } %dst_stringval1, { i64, i8* }* %dst_lowered_ptr // %dst_unlowered_ptr = bitcast { i64, i8* }* %dst_lowered_ptr // to %"struct.doris_udf::StringVal"* // call void @HllUpdate(%"class.doris_udf::FunctionContext"* %fn_ctx, // %"struct.doris_udf::DoubleVal"* %src_unlowered_ptr, // %"struct.doris_udf::StringVal"* %dst_unlowered_ptr) // %anyval_result = load { i64, i8* }* %dst_lowered_ptr // %6 = extractvalue { i64, i8* } %anyval_result, 1 // %7 = insertvalue %"struct.doris::StringValue" zeroinitializer, i8* %6, 0 // %8 = extractvalue { i64, i8* } %anyval_result, 0 // %9 = ashr i64 %8, 32 // %10 = trunc i64 %9 to i32 // %11 = insertvalue %"struct.doris::StringValue" %7, i32 %10, 1 // store %"struct.doris::StringValue" %11, %"struct.doris::StringValue"* %dst_slot_ptr // br label %ret // // ret: ; preds = %src_not_null, %entry // ret void // } llvm::Function* PartitionedAggregationNode::codegen_update_slot( AggFnEvaluator* evaluator, SlotDescriptor* slot_desc) { DCHECK(slot_desc->is_materialized()); LlvmCodeGen* codegen = NULL; if (!_state->get_codegen(&codegen).ok()) { return NULL; } DCHECK_EQ(evaluator->input_expr_ctxs().size(), 1); ExprContext* input_expr_ctx = evaluator->input_expr_ctxs()[0]; Expr* input_expr = input_expr_ctx->root(); // TODO: implement timestamp // if (input_expr->type().type == TYPE_TIMESTAMP && // evaluator->agg_op() != AggFnEvaluator::AVG) { // return NULL; // } Function* agg_expr_fn = NULL; Status status = input_expr->get_codegend_compute_fn(_state, &agg_expr_fn); if (!status.ok()) { VLOG_QUERY << "Could not codegen UpdateSlot(): " << status.get_error_msg(); return NULL; } DCHECK(agg_expr_fn != NULL); PointerType* fn_ctx_type = codegen->get_ptr_type(FunctionContextImpl::_s_llvm_functioncontext_name); StructType* tuple_struct = _intermediate_tuple_desc->generate_llvm_struct(codegen); if (tuple_struct == NULL) return NULL; // Could not generate tuple struct PointerType* tuple_ptr_type = PointerType::get(tuple_struct, 0); PointerType* tuple_row_ptr_type = codegen->get_ptr_type(TupleRow::_s_llvm_class_name); // Create UpdateSlot prototype LlvmCodeGen::FnPrototype prototype(codegen, "UpdateSlot", codegen->void_type()); prototype.add_argument(LlvmCodeGen::NamedVariable("fn_ctx", fn_ctx_type)); prototype.add_argument(LlvmCodeGen::NamedVariable("agg_tuple", tuple_ptr_type)); prototype.add_argument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type)); LlvmCodeGen::LlvmBuilder builder(codegen->context()); Value* args[3]; Function* fn = prototype.generate_prototype(&builder, &args[0]); Value* fn_ctx_arg = args[0]; Value* agg_tuple_arg = args[1]; Value* row_arg = args[2]; BasicBlock* src_not_null_block = BasicBlock::create(codegen->context(), "src_not_null", fn); BasicBlock* ret_block = BasicBlock::create(codegen->context(), "ret", fn); // Call expr function to get src slot value Value* expr_ctx = codegen->cast_ptr_to_llvm_ptr( codegen->get_ptr_type(ExprContext::_s_llvm_class_name), input_expr_ctx); Value* agg_expr_fn_args[] = { expr_ctx, row_arg }; CodegenAnyVal src = CodegenAnyVal::create_call_wrapped( codegen, &builder, input_expr->type(), agg_expr_fn, agg_expr_fn_args, "src"); Value* src_is_null = src.get_is_null(); builder.create_cond_br(src_is_null, ret_block, src_not_null_block); // Src slot is not null, update dst_slot builder.set_insert_point(src_not_null_block); Value* dst_ptr = builder.create_struct_gep(agg_tuple_arg, slot_desc->field_idx(), "dst_slot_ptr"); Value* result = NULL; if (slot_desc->is_nullable()) { // Dst is NULL, just update dst slot to src slot and clear null bit Function* clear_null_fn = slot_desc->CodegenUpdateNull(codegen, tuple_struct, false); builder.CreateCall(clear_null_fn, agg_tuple_arg); } // Update the slot Value* dst_value = builder.CreateLoad(dst_ptr, "dst_val"); switch (evaluator->agg_op()) { case AggFnEvaluator::COUNT: if (evaluator->is_merge()) { result = builder.CreateAdd(dst_value, src.GetVal(), "count_sum"); } else { result = builder.CreateAdd(dst_value, codegen->get_int_constant(TYPE_BIGINT, 1), "count_inc"); } break; case AggFnEvaluator::MIN: { Function* min_fn = codegen->CodegenMinMax(slot_desc->type(), true); Value* min_args[] = { dst_value, src.GetVal() }; result = builder.CreateCall(min_fn, min_args, "min_value"); break; } case AggFnEvaluator::MAX: { Function* max_fn = codegen->CodegenMinMax(slot_desc->type(), false); Value* max_args[] = { dst_value, src.GetVal() }; result = builder.CreateCall(max_fn, max_args, "max_value"); break; } case AggFnEvaluator::SUM: if (slot_desc->type().type != TYPE_DECIMAL && slot_desc->type().type != TYPE_DECIMALV2) { if (slot_desc->type().type == TYPE_FLOAT || slot_desc->type().type == TYPE_DOUBLE) { result = builder.CreateFAdd(dst_value, src.GetVal()); } else { result = builder.CreateAdd(dst_value, src.GetVal()); } break; } DCHECK(slot_desc->type().type == TYPE_DECIMAL || slot_desc->type().type == TYPE_DECIMALV2); // Fall through to xcompiled case case AggFnEvaluator::AVG: case AggFnEvaluator::NDV: { // Get xcompiled update/merge function from IR module const string& symbol = evaluator->is_merge() ? evaluator->merge_symbol() : evaluator->update_symbol(); Function* ir_fn = codegen->module()->getFunction(symbol); DCHECK(ir_fn != NULL); // Create pointer to src to pass to ir_fn. We must use the unlowered type. Value* src_lowered_ptr = codegen->CreateEntryBlockAlloca( fn, LlvmCodeGen::NamedVariable("src_lowered_ptr", src.value()->getType())); builder.CreateStore(src.value(), src_lowered_ptr); Type* unlowered_ptr_type = CodegenAnyVal::GetUnloweredPtrType(codegen, input_expr->type()); Value* src_unlowered_ptr = builder.CreateBitCast(src_lowered_ptr, unlowered_ptr_type, "src_unlowered_ptr"); // Create intermediate argument 'dst' from 'dst_value' const ColumnType& dst_type = evaluator->intermediate_type(); CodegenAnyVal dst = CodegenAnyVal::GetNonNullVal( codegen, &builder, dst_type, "dst"); dst.SetFromRawValue(dst_value); // Create pointer to dst to pass to ir_fn. We must use the unlowered type. Value* dst_lowered_ptr = codegen->CreateEntryBlockAlloca( fn, LlvmCodeGen::NamedVariable("dst_lowered_ptr", dst.value()->getType())); builder.CreateStore(dst.value(), dst_lowered_ptr); unlowered_ptr_type = CodegenAnyVal::GetUnloweredPtrType(codegen, dst_type); Value* dst_unlowered_ptr = builder.CreateBitCast(dst_lowered_ptr, unlowered_ptr_type, "dst_unlowered_ptr"); // Call 'ir_fn' builder.CreateCall3(ir_fn, fn_ctx_arg, src_unlowered_ptr, dst_unlowered_ptr); // Convert StringVal intermediate 'dst_arg' back to StringValue Value* anyval_result = builder.CreateLoad(dst_lowered_ptr, "anyval_result"); result = CodegenAnyVal(codegen, &builder, dst_type, anyval_result).ToNativeValue(); break; } default: DCHECK(false) << "bad aggregate operator: " << evaluator->agg_op(); } builder.CreateStore(result, dst_ptr); builder.CreateBr(ret_block); builder.SetInsertPoint(ret_block); builder.CreateRetVoid(); return codegen->FinalizeFunction(fn); } // IR codegen for the update_tuple loop. This loop is query specific and based on the // aggregate functions. The function signature must match the non- codegen'd update_tuple // exactly. // For the query: // select count(*), count(int_col), sum(double_col) the IR looks like: // // ; Function Attrs: alwaysinline // define void @update_tuple(%"class.doris::PartitionedAggregationNode"* %this_ptr, // %"class.doris_udf::FunctionContext"** %agg_fn_ctxs, // %"class.doris::Tuple"* %tuple, // %"class.doris::TupleRow"* %row, // i1 %is_merge) #20 { // entry: // %tuple1 = bitcast %"class.doris::Tuple"* %tuple to { i8, i64, i64, double }* // %src_slot = getelementptr inbounds { i8, i64, i64, double }* %tuple1, i32 0, i32 1 // %count_star_val = load i64* %src_slot // %count_star_inc = add i64 %count_star_val, 1 // store i64 %count_star_inc, i64* %src_slot // %0 = getelementptr %"class.doris_udf::FunctionContext"** %agg_fn_ctxs, i32 1 // %fn_ctx = load %"class.doris_udf::FunctionContext"** %0 // call void @UpdateSlot(%"class.doris_udf::FunctionContext"* %fn_ctx, // { i8, i64, i64, double }* %tuple1, // %"class.doris::TupleRow"* %row) // %1 = getelementptr %"class.doris_udf::FunctionContext"** %agg_fn_ctxs, i32 2 // %fn_ctx2 = load %"class.doris_udf::FunctionContext"** %1 // call void @UpdateSlot5(%"class.doris_udf::FunctionContext"* %fn_ctx2, // { i8, i64, i64, double }* %tuple1, // %"class.doris::TupleRow"* %row) // ret void // } Function* PartitionedAggregationNode::codegen_update_tuple() { LlvmCodeGen* codegen = NULL; if (!_state->get_codegen(&codegen).ok()) { return NULL; } SCOPED_TIMER(codegen->codegen_timer()); int j = _probe_expr_ctxs.size(); for (int i = 0; i < _aggregate_evaluators.size(); ++i, ++j) { // skip non-materialized slots; we don't have evaluators instantiated for those while (!_intermediate_tuple_desc->slots()[j]->is_materialized()) { DCHECK_LT(j, _intermediate_tuple_desc->slots().size() - 1); ++j; } SlotDescriptor* slot_desc = _intermediate_tuple_desc->slots()[j]; AggFnEvaluator* evaluator = _aggregate_evaluators[i]; // Don't codegen things that aren't builtins (for now) if (!evaluator->is_builtin()) { return NULL; } bool supported = true; AggFnEvaluator::AggregationOp op = evaluator->agg_op(); PrimitiveType type = slot_desc->type().type; // Char and timestamp intermediates aren't supported if (type == TYPE_TIMESTAMP || type == TYPE_CHAR) { supported = false; } // Only AVG and NDV support string intermediates if ((type == TYPE_STRING || type == TYPE_VARCHAR) && !(op == AggFnEvaluator::AVG || op == AggFnEvaluator::NDV)) { supported = false; } // Only SUM, AVG, and NDV support decimal intermediates if (type == TYPE_DECIMAL && !(op == AggFnEvaluator::SUM || op == AggFnEvaluator::AVG || op == AggFnEvaluator::NDV)) { supported = false; } if (type == TYPE_DECIMALV2 && !(op == AggFnEvaluator::SUM || op == AggFnEvaluator::AVG || op == AggFnEvaluator::NDV)) { supported = false; } if (!supported) { VLOG_QUERY << "Could not codegen update_tuple because intermediate type " << slot_desc->type() << " is not yet supported for aggregate function \"" << evaluator->fn_name() << "()\""; return NULL; } } if (_intermediate_tuple_desc->generate_llvm_struct(codegen) == NULL) { VLOG_QUERY << "Could not codegen update_tuple because we could" << "not generate a matching llvm struct for the intermediate tuple."; return NULL; } // Get the types to match the update_tuple signature Type* agg_node_type = codegen->get_type(PartitionedAggregationNode::_s_llvm_class_name); Type* fn_ctx_type = codegen->get_type(FunctionContextImpl::_s_llvm_functioncontext_name); Type* tuple_type = codegen->get_type(Tuple::_s_llvm_class_name); Type* tuple_row_type = codegen->get_type(TupleRow::_s_llvm_class_name); PointerType* agg_node_ptr_type = agg_node_type->getPointerTo(); PointerType* fn_ctx_ptr_ptr_type = fn_ctx_type->getPointerTo()->getPointerTo(); PointerType* tuple_ptr_type = tuple_type->getPointerTo(); PointerType* tuple_row_ptr_type = tuple_row_type->getPointerTo(); StructType* tuple_struct = _intermediate_tuple_desc->generate_llvm_struct(codegen); PointerType* tuple_ptr = PointerType::get(tuple_struct, 0); LlvmCodeGen::FnPrototype prototype(codegen, "update_tuple", codegen->void_type()); prototype.add_argument(LlvmCodeGen::NamedVariable("this_ptr", agg_node_ptr_type)); prototype.add_argument(LlvmCodeGen::NamedVariable("agg_fn_ctxs", fn_ctx_ptr_ptr_type)); prototype.add_argument(LlvmCodeGen::NamedVariable("tuple", tuple_ptr_type)); prototype.add_argument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type)); prototype.add_argument(LlvmCodeGen::NamedVariable("is_merge", codegen->boolean_type())); LlvmCodeGen::LlvmBuilder builder(codegen->context()); Value* args[5]; Function* fn = prototype.generate_prototype(&builder, &args[0]); Value* agg_fn_ctxs_arg = args[1]; Value* tuple_arg = args[2]; Value* row_arg = args[3]; // Cast the parameter types to the internal llvm runtime types. // TODO: get rid of this by using right type in function signature tuple_arg = builder.CreateBitCast(tuple_arg, tuple_ptr, "tuple"); // Loop over each expr and generate the IR for that slot. If the expr is not // count(*), generate a helper IR function to update the slot and call that. j = _probe_expr_ctxs.size(); for (int i = 0; i < _aggregate_evaluators.size(); ++i, ++j) { // skip non-materialized slots; we don't have evaluators instantiated for those while (!_intermediate_tuple_desc->slots()[j]->is_materialized()) { DCHECK_LT(j, _intermediate_tuple_desc->slots().size() - 1); ++j; } SlotDescriptor* slot_desc = _intermediate_tuple_desc->slots()[j]; AggFnEvaluator* evaluator = _aggregate_evaluators[i]; if (evaluator->is_count_star()) { // TODO: we should be able to hoist this up to the loop over the batch and just // increment the slot by the number of rows in the batch. int field_idx = slot_desc->field_idx(); Value* const_one = codegen->get_int_constant(TYPE_BIGINT, 1); Value* slot_ptr = builder.create_struct_gep(tuple_arg, field_idx, "src_slot"); Value* slot_loaded = builder.CreateLoad(slot_ptr, "count_star_val"); Value* count_inc = builder.CreateAdd(slot_loaded, const_one, "count_star_inc"); builder.CreateStore(count_inc, slot_ptr); } else { Function* update_slot_fn = codegen_update_slot(evaluator, slot_desc); if (update_slot_fn == NULL) return NULL; Value* fn_ctx_ptr = builder.CreateConstGEP1_32(agg_fn_ctxs_arg, i); Value* fn_ctx = builder.CreateLoad(fn_ctx_ptr, "fn_ctx"); builder.CreateCall3(update_slot_fn, fn_ctx, tuple_arg, row_arg); } } builder.CreateRetVoid(); // codegen_process_batch() does the final optimizations. return codegen->FinalizeFunction(fn); } Function* PartitionedAggregationNode::codegen_process_batch() { LlvmCodeGen* codegen = NULL; if (!_state->get_codegen(&codegen).ok()) { return NULL; } SCOPED_TIMER(codegen->codegen_timer()); Function* update_tuple_fn = codegen_update_tuple(); if (update_tuple_fn == NULL) { return NULL; } // Get the cross compiled update row batch function IRFunction::Type ir_fn = (!_probe_expr_ctxs.empty() ? IRFunction::PART_AGG_NODE_PROCESS_BATCH_FALSE : IRFunction::PART_AGG_NODE_PROCESS_BATCH_NO_GROUPING); Function* process_batch_fn = codegen->get_function(ir_fn); DCHECK(process_batch_fn != NULL); int replaced = 0; if (!_probe_expr_ctxs.empty()) { // Aggregation w/o grouping does not use a hash table. // Codegen for hash // The codegen'd process_batch function is only used in open() with _level = 0, // so don't use murmur hash Function* hash_fn = _ht_ctx->codegen_hash_current_row(_state, /* use murmur */ false); if (hash_fn == NULL) { return NULL; } // Codegen PartitionedHashTable::Equals Function* equals_fn = _ht_ctx->codegen_equals(_state); if (equals_fn == NULL) { return NULL; } // Codegen for evaluating probe rows Function* eval_probe_row_fn = _ht_ctx->codegen_eval_row(_state, false); if (eval_probe_row_fn == NULL) { return NULL; } // Replace call sites process_batch_fn = codegen->replace_call_sites(process_batch_fn, false, eval_probe_row_fn, "EvalProbeRow", &replaced); DCHECK_EQ(replaced, 1); process_batch_fn = codegen->replace_call_sites(process_batch_fn, true, hash_fn, "HashCurrentRow", &replaced); DCHECK_EQ(replaced, 1); process_batch_fn = codegen->replace_call_sites(process_batch_fn, true, equals_fn, "Equals", &replaced); DCHECK_EQ(replaced, 1); } process_batch_fn = codegen->replace_call_sites(process_batch_fn, false, update_tuple_fn, "update_tuple", &replaced); DCHECK_GE(replaced, 1); DCHECK(process_batch_fn != NULL); return codegen->optimize_function_with_exprs(process_batch_fn); } #endif }
44.403308
111
0.636114
shengyunyao
a9bdf9cfefc18b5ef3c2b65a86839bc1d4a4ab51
3,533
hpp
C++
src/AFQMC/Utilities/hdf5_consistency_helper.hpp
Hyeondeok-Shin/qmcpack
2b853b6eaa15a795eee9d92085e74b97bd69abc7
[ "NCSA" ]
null
null
null
src/AFQMC/Utilities/hdf5_consistency_helper.hpp
Hyeondeok-Shin/qmcpack
2b853b6eaa15a795eee9d92085e74b97bd69abc7
[ "NCSA" ]
11
2020-05-09T20:57:21.000Z
2020-06-10T00:00:17.000Z
src/AFQMC/Utilities/hdf5_consistency_helper.hpp
Hyeondeok-Shin/qmcpack
2b853b6eaa15a795eee9d92085e74b97bd69abc7
[ "NCSA" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source // License. See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: // Miguel Morales, moralessilva2@llnl.gov, Lawrence Livermore National Laboratory // // File created by: // Fionn Malone, malone14@llnl.gov, Lawrence Livermore National Laboratory //////////////////////////////////////////////////////////////////////////////// #ifndef HDF5_CONSISTENCY_HELPER_HPP #define HDF5_CONSISTENCY_HELPER_HPP #include <vector> #include "hdf/hdf_multi.h" #include "hdf/hdf_archive.h" #include "AFQMC/config.0.h" namespace qmcplusplus { namespace afqmc { // Helper functions for reading integral data from HDF5 files. // Currently only read one-dimensional integrals into std::vector<ValueType> and two-dimensional // integrals into boost::multi::array<ValueType,2>, so only handle these overloads. /** read data from filespace (name) to buffer (out). * If QMC_COMPLEX = 1 and T = RealType then handle this through copy. * If QMC_COMPLEX = 0 and T = ComplexType then abort with error message. * @return true if successful. false indiciates name not found in dump. */ template<typename T> bool readComplexOrReal(hdf_archive& dump, std::string name, std::vector<T>& out) { std::vector<int> shape; int ndim = 1; // vector if (!dump.getShape<std::vector<T>>(name, shape)) { // name not found in dump. return false; } #ifdef QMC_COMPLEX if (shape.size() == ndim + 1) { // Nothing. dump.readEntry(out, name); return true; } else if (shape.size() == ndim) { // Real integrals. std::vector<RealType> out_real(out.size()); dump.readEntry(out_real, name); std::copy_n(out_real.begin(), out_real.size(), out.begin()); return true; } else { app_log() << " Error reading " << name << " dataspace. Shape mismatch.\n"; APP_ABORT(""); return false; } #else if (shape.size() == ndim + 1) { app_log() << " Error: Found complex integrals with QMC_COMPLEX=0.\n"; APP_ABORT(" Please recompile with QMC_COMPLEX=1 or generate real integrals if appropriate.\n"); return false; } else { dump.readEntry(out, name); return true; } #endif } template<typename T> bool readComplexOrReal(hdf_archive& dump, std::string name, boost::multi::array<T, 2>& out) { std::vector<int> shape; int ndim = 2; // matrix if (!dump.getShape<boost::multi::array<T, 2>>(name, shape)) { // name not found in dump. return false; } #ifdef QMC_COMPLEX if (shape.size() == ndim + 1) { // Nothing. dump.readEntry(out, name); return true; } else if (shape.size() == ndim) { // Real integrals. boost::multi::array<RealType, 2> out_real({shape[0], shape[1]}); dump.readEntry(out_real, name); std::copy_n(out_real.origin(), out_real.num_elements(), out.origin()); return true; } else { app_log() << " Error reading " << name << " dataspace. Shape mismatch.\n"; APP_ABORT(""); return false; } #else if (shape.size() == ndim + 1) { app_log() << " Error: Found complex integrals with QMC_COMPLEX=0.\n"; APP_ABORT(" Please recompile with QMC_COMPLEX=1 or generate real integrals if appropriate.\n"); return false; } else { dump.readEntry(out, name); return true; } #endif } } // namespace afqmc } // namespace qmcplusplus #endif
26.365672
99
0.636003
Hyeondeok-Shin
a9be040ed0bd726478b0faf3fe0c1ef9101ecdc6
14,829
cpp
C++
PostGL/GLVolumeFlowPlot.cpp
EMinsight/FEBioStudio
d3e6485610d19217550fb94cb22180bc4bda45f9
[ "MIT" ]
null
null
null
PostGL/GLVolumeFlowPlot.cpp
EMinsight/FEBioStudio
d3e6485610d19217550fb94cb22180bc4bda45f9
[ "MIT" ]
null
null
null
PostGL/GLVolumeFlowPlot.cpp
EMinsight/FEBioStudio
d3e6485610d19217550fb94cb22180bc4bda45f9
[ "MIT" ]
null
null
null
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2021 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "GLVolumeFlowPlot.h" #include "GLModel.h" #include <GLLib/GLContext.h> using namespace Post; extern int LUT[256][15]; extern int ET_HEX[12][2]; REGISTER_CLASS(GLVolumeFlowPlot, CLASS_PLOT, "volume-flow", 0); GLVolumeFlowPlot::GLVolumeFlowPlot() { SetTypeString("volume-flow"); static int n = 1; char szname[128] = { 0 }; sprintf(szname, "VolumeFlow%d", n++); SetName(szname); AddIntParam(0, "Data field")->SetEnumNames("@data_scalar"); AddIntParam(0, "Color map")->SetEnumNames("@color_map"); AddBoolParam(true, "Smooth color map"); AddIntParam(10, "Range divisions")->SetIntRange(2, 50); AddDoubleParam(0.2, "Opacity scale")->SetFloatRange(0.0, 1.0); AddIntParam(1, "Mesh subdivisions")->SetIntRange(1, MAX_MESH_DIVS); AddBoolParam(false, "Show legend"); AddIntParam(0, "Max Range type")->SetEnumNames("dynamic\0static\0user\0"); AddDoubleParam(0, "User max"); AddIntParam(0, "Min Range type")->SetEnumNames("dynamic\0static\0user\0"); AddDoubleParam(0, "User min"); m_alpha = 0.2f; m_nfield = 0; m_bsmooth = true; m_nDivs = 10; m_meshDivs = 1; m_range.min = m_range.max = 0; m_range.mintype = m_range.maxtype = RANGE_DYNAMIC; GLLegendBar* bar = new GLLegendBar(&m_Col, 0, 0, 120, 500); bar->align(GLW_ALIGN_LEFT | GLW_ALIGN_VCENTER); bar->copy_label(szname); SetLegendBar(bar); UpdateData(false); } bool GLVolumeFlowPlot::UpdateData(bool bsave) { if (bsave) { m_nfield = GetIntValue(DATA_FIELD); m_Col.SetColorMap(GetIntValue(COLOR_MAP)); m_bsmooth = GetBoolValue(SMOOTH_COLOR_MAP); m_nDivs = GetIntValue(RANGE_DIVISIONS); m_alpha = GetFloatValue(OPACITY_SCALE); m_meshDivs = GetIntValue(MESH_DIVISIONS); if (GetLegendBar()) { bool b = GetBoolValue(SHOW_LEGEND); if (b) GetLegendBar()->show(); else GetLegendBar()->hide(); } m_range.maxtype = GetIntValue(MAX_RANGE_TYPE); m_range.mintype = GetIntValue(MIN_RANGE_TYPE); if (m_range.maxtype == RANGE_USER) m_range.max = GetFloatValue(USER_MAX); if (m_range.mintype == RANGE_USER) m_range.min = GetFloatValue(USER_MIN); m_Col.SetSmooth(m_bsmooth); m_Col.SetDivisions(m_nDivs); Update(GetModel()->CurrentTimeIndex(), 0.f, true); } else { SetIntValue(DATA_FIELD, m_nfield); SetIntValue(COLOR_MAP, m_Col.GetColorMap()); SetBoolValue(SMOOTH_COLOR_MAP, m_bsmooth); SetIntValue(RANGE_DIVISIONS, m_nDivs); SetFloatValue(OPACITY_SCALE, m_alpha); SetIntValue(MESH_DIVISIONS, m_meshDivs); if (GetLegendBar()) { SetBoolValue(SHOW_LEGEND, GetLegendBar()->visible()); } SetIntValue(MAX_RANGE_TYPE, m_range.maxtype); SetIntValue(MIN_RANGE_TYPE, m_range.mintype); SetFloatValue(USER_MAX, m_range.max); SetFloatValue(USER_MIN, m_range.min); } return false; } void GLVolumeFlowPlot::Update(int ntime, float dt, bool breset) { UpdateNodalData(ntime, breset); // get the model CGLModel& mdl = *GetModel(); FEPostModel* fem = mdl.GetFEModel(); FEState* state = fem->CurrentState(); // get the current mesh FEMeshBase& mesh = *mdl.GetActiveMesh(); // get the largest dimension BOX box = m_box; double D = box.GetMaxExtent(); // this is the resolution for the largest dimension const int MAX_RES = 128; const int MIN_RES = 8; // set the resolutions based on the box dimensions int nx = (int)(box.Width () / D * MAX_RES); if (nx < MIN_RES) nx = MIN_RES; int ny = (int)(box.Height() / D * MAX_RES); if (ny < MIN_RES) ny = MIN_RES; int nz = (int)(box.Depth () / D * MAX_RES); if (nz < MIN_RES) nz = MIN_RES; // allocate the slices m_slice_X.resize(nx); m_slice_Y.resize(ny); m_slice_Z.resize(nz); // build the #pragma omp parallel default(shared) { #pragma omp for for (int i = 0; i < nx; ++i) { float x = box.x0 + ((float)i)*(box.x1 - box.x0) / (nx - 1.f); Slice& slice = m_slice_X[i]; CreateSlice(slice, vec3f(1, 0, 0), x); } #pragma omp for for (int i = 0; i < ny; ++i) { float y = box.y0 + ((float)i)*(box.y1 - box.y0) / (ny - 1.f); Slice& slice = m_slice_Y[i]; CreateSlice(slice, vec3f(0, 1, 0), y); } #pragma omp for for (int i = 0; i < nz; ++i) { float z = box.z0 + ((float)i)*(box.z1 - box.z0) / (nz - 1.f); Slice& slice = m_slice_Z[i]; CreateSlice(slice, vec3f(0, 0, 1), z); } } } void GLVolumeFlowPlot::UpdateNodalData(int ntime, bool breset) { CGLModel* mdl = GetModel(); FEMeshBase* pm = mdl->GetActiveMesh(); FEPostModel* pfem = mdl->GetFEModel(); int NN = pm->Nodes(); int NS = pfem->GetStates(); // update the box BOX b(pm->Node(0).r, pm->Node(0).r); for (int i = 0; i < NN; ++i) { vec3d& ri = pm->Node(i).r; if (ri.x < b.x0) b.x0 = ri.x; if (ri.x > b.x1) b.x1 = ri.x; if (ri.y < b.y0) b.y0 = ri.y; if (ri.y > b.y1) b.y1 = ri.y; if (ri.z < b.z0) b.z0 = ri.z; if (ri.z > b.z1) b.z1 = ri.z; } m_box = b; if (breset) { m_map.Clear(); m_rng.clear(); m_val.clear(); } if (m_map.States() != pfem->GetStates()) { m_map.Create(NS, NN, 0.f, -1); m_rng.resize(NS); m_val.resize(NN); } if (m_nfield == 0) return; // see if we need to update this state if (breset || (m_map.GetTag(ntime) != m_nfield)) { m_map.SetTag(ntime, m_nfield); vector<float>& val = m_map.State(ntime); NODEDATA nd; for (int i = 0; i<NN; ++i) { pfem->EvaluateNode(i, ntime, m_nfield, nd); val[i] = nd.m_val; } // evaluate the range float fmin, fmax; fmin = fmax = val[0]; for (int i = 0; i<NN; ++i) { if (val[i] < fmin) fmin = val[i]; if (val[i] > fmax) fmax = val[i]; } if (fmin == fmax) fmax++; m_rng[ntime] = vec2f(fmin, fmax); } // copy current nodal values m_val = m_map.State(ntime); // update range float fmin = m_rng[ntime].x; float fmax = m_rng[ntime].y; switch (m_range.mintype) { case 1: if (fmin > m_range.min) fmin = m_range.min; break; case 2: fmin = m_range.min; break; } switch (m_range.maxtype) { case 1: if (fmax < m_range.max) fmax = m_range.max; break; case 2: fmax = m_range.max; break; } m_range.min = fmin; m_range.max = fmax; if (GetLegendBar()) { GetLegendBar()->SetRange(m_range.min, m_range.max); } } void GLVolumeFlowPlot::CreateSlice(Slice& slice, const vec3d& norm, float ref) { slice.clear(); slice.reserve(100); float ev[8]; // element nodal values float ex[8]; // element nodal distances vec3d er[8]; const int HEX_NT[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; const int PEN_NT[8] = { 0, 1, 2, 2, 3, 4, 5, 5 }; const int TET_NT[8] = { 0, 1, 2, 2, 3, 3, 3, 3 }; const int PYR_NT[8] = {0, 1, 2, 3, 4, 4, 4, 4}; const int* nt; // get the mesh CGLModel* mdl = GetModel(); FEPostModel* ps = mdl->GetFEModel(); FEPostMesh* pm = mdl->GetActiveMesh(); vec2f rng; rng.x = m_range.min; rng.y = m_range.max; if (rng.x == rng.y) rng.y++; int ndivs = m_meshDivs; if (ndivs < 1) ndivs = 1; if (ndivs > MAX_MESH_DIVS) ndivs = MAX_MESH_DIVS; vector<double> q; if (ndivs > 1) { int nsize = ndivs * ndivs * ndivs * 8 * 8; q.resize(nsize); double* H = &q[0]; double D = 1.0 / ndivs; for (int i = 0; i < ndivs; ++i) for (int j = 0; j < ndivs; ++j) for (int k = 0; k < ndivs; ++k) { double r0 = -1.0 + 2.0 * (i * D); double r1 = -1.0 + 2.0 * ((i + 1.0) * D); double s0 = -1.0 + 2.0 * (j * D); double s1 = -1.0 + 2.0 * ((j + 1.0) * D); double t0 = -1.0 + 2.0 * (k * D); double t1 = -1.0 + 2.0 * ((k + 1.0) * D); double rn[8] = { r0, r1, r1, r0, r0, r1, r1, r0 }; double sn[8] = { s0, s0, s1, s1, s0, s0, s1, s1 }; double tn[8] = { t0, t0, t0, t0, t1, t1, t1, t1 }; for (int l = 0; l < 8; ++l, H += 8) { H[0] = 0.125 * (1.0 - rn[l]) * (1.0 - sn[l]) * (1.0 - tn[l]); H[1] = 0.125 * (1.0 + rn[l]) * (1.0 - sn[l]) * (1.0 - tn[l]); H[2] = 0.125 * (1.0 + rn[l]) * (1.0 + sn[l]) * (1.0 - tn[l]); H[3] = 0.125 * (1.0 - rn[l]) * (1.0 + sn[l]) * (1.0 - tn[l]); H[4] = 0.125 * (1.0 - rn[l]) * (1.0 - sn[l]) * (1.0 + tn[l]); H[5] = 0.125 * (1.0 + rn[l]) * (1.0 - sn[l]) * (1.0 + tn[l]); H[6] = 0.125 * (1.0 + rn[l]) * (1.0 + sn[l]) * (1.0 + tn[l]); H[7] = 0.125 * (1.0 - rn[l]) * (1.0 + sn[l]) * (1.0 + tn[l]); } } } // loop over all elements for (int iel = 0; iel <pm->Elements(); ++iel) { // render only if the element is visible and // its material is enabled FEElement_& el = pm->ElementRef(iel); FEMaterial* pmat = ps->GetMaterial(el.m_MatID); if (pmat->benable && el.IsVisible() && el.IsSolid()) { switch (el.Type()) { case FE_HEX8: nt = HEX_NT; break; case FE_HEX20: nt = HEX_NT; break; case FE_HEX27: nt = HEX_NT; break; case FE_PENTA6: nt = PEN_NT; break; case FE_PENTA15: nt = PEN_NT; break; case FE_TET4: nt = TET_NT; break; case FE_TET5: nt = TET_NT; break; case FE_PYRA5: nt = PYR_NT; break; case FE_PYRA13: nt = PYR_NT; break; default: assert(false); return; } // get the nodal values for (int k = 0; k<8; ++k) { FENode& node = pm->Node(el.m_node[nt[k]]); float f = m_val[el.m_node[nt[k]]]; f = (f - rng.x) / (rng.y - rng.x); ev[k] = f; er[k] = node.r; ex[k] = node.r*norm; } if (ndivs == 1) { // calculate the case of the element int ncase = 0; for (int k = 0; k<8; ++k) if (ex[k] <= ref) ncase |= (1 << k); // loop over faces int* pf = LUT[ncase]; for (int l = 0; l < 5; l++) { if (*pf == -1) break; // calculate nodal positions vec3d r[3]; double v[3]; for (int k = 0; k < 3; k++) { int n1 = ET_HEX[pf[k]][0]; int n2 = ET_HEX[pf[k]][1]; double w = 0.5; if (ex[n2] != ex[n1]) w = (ref - ex[n1]) / (ex[n2] - ex[n1]); r[k] = er[n1] * (1 - w) + er[n2] * w; v[k] = ev[n1] * (1 - w) + ev[n2] * w; } // render the face Slice::Face face; face.v[0] = v[0]; face.r[0] = r[0]; face.v[1] = v[1]; face.r[1] = r[1]; face.v[2] = v[2]; face.r[2] = r[2]; slice.add(face); pf += 3; } } else { double sv[8]; // element nodal values double sx[8]; // element nodal distances vec3d sr[8]; double* H = &q[0]; int nsize = ndivs * ndivs * ndivs; for (int i = 0; i < nsize; ++i) { for (int l = 0; l < 8; ++l, H += 8) { sv[l] = ev[0] * H[0] + ev[1] * H[1] + ev[2] * H[2] + ev[3] * H[3] + ev[4] * H[4] + ev[5] * H[5] + ev[6] * H[6] + ev[7] * H[7]; sx[l] = ex[0] * H[0] + ex[1] * H[1] + ex[2] * H[2] + ex[3] * H[3] + ex[4] * H[4] + ex[5] * H[5] + ex[6] * H[6] + ex[7] * H[7]; sr[l] = er[0] * H[0] + er[1] * H[1] + er[2] * H[2] + er[3] * H[3] + er[4] * H[4] + er[5] * H[5] + er[6] * H[6] + er[7] * H[7]; } // calculate the case of the element int ncase = 0; for (int k = 0; k < 8; ++k) if (sx[k] <= ref) ncase |= (1 << k); // loop over faces int* pf = LUT[ncase]; for (int l = 0; l < 5; l++) { if (*pf == -1) break; // calculate nodal positions vec3d r[3]; double v[3]; for (int m = 0; m < 3; m++) { int n1 = ET_HEX[pf[m]][0]; int n2 = ET_HEX[pf[m]][1]; double w = 0.5; if (sx[n2] != sx[n1]) w = (ref - sx[n1]) / (sx[n2] - sx[n1]); r[m] = sr[n1] * (1 - w) + sr[n2] * w; v[m] = sv[n1] * (1 - w) + sv[n2] * w; } // render the face Slice::Face face; face.v[0] = v[0]; face.r[0] = r[0]; face.v[1] = v[1]; face.r[1] = r[1]; face.v[2] = v[2]; face.r[2] = r[2]; slice.add(face); pf += 3; } } } } } } void GLVolumeFlowPlot::Render(CGLContext& rc) { glPushAttrib(GL_ENABLE_BIT); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glEnable(GL_TEXTURE_1D); GLTexture1D& tex = m_Col.GetTexture(); tex.MakeCurrent(); vec3d r(0,0,1); quatd q = rc.m_q; q.Inverse().RotateVector(r); double x = fabs(r.x); double y = fabs(r.y); double z = fabs(r.z); if ((x > y) && (x > z)) { RenderSlices(m_slice_X, (r.x > 0 ? 1 : -1)); } if ((y > x) && (y > z)) { RenderSlices(m_slice_Y, (r.y > 0 ? 1 : -1)); } if ((z > y) && (z > x)) { RenderSlices(m_slice_Z, (r.z > 0 ? 1 : -1)); } glPopAttrib(); } void GLVolumeFlowPlot::RenderSlices(std::vector<GLVolumeFlowPlot::Slice>& slice, int step) { // determine the order in which we have to render the slices int n = (int)slice.size(); int n0, n1; if (step == 1) { n0 = 0; n1 = n; } else { n0 = n - 1; n1 = -1; } // get the color map CColorMap& col = m_Col.ColorMap(); // start rendering GLColor c; double a, v; glBegin(GL_TRIANGLES); { for (int i = n0; i != n1; i += step) { Slice& s = slice[i]; int NF = (int)s.m_Face.size(); for (int j = 0; j < NF; ++j) { Slice::Face& face = s.m_Face[j]; v = face.v[0]; a = (v > 0 ? (v < 1 ? v : 1) : 0); c = col.map(v); // glColor4ub(c.r, c.g, c.b, 255 *face.v[0] * m_alpha); glColor4d(1.0, 1.0, 1.0, a * m_alpha); glTexCoord1d(face.v[0]); glVertex3f(face.r[0].x, face.r[0].y, face.r[0].z); v = face.v[1]; a = (v > 0 ? (v < 1 ? v : 1) : 0); c = col.map(face.v[1]); // glColor4ub(c.r, c.g, c.b, 255 *face.v[1] * m_alpha); glColor4d(1.0, 1.0, 1.0, a * m_alpha); glTexCoord1d(face.v[1]); glVertex3f(face.r[1].x, face.r[1].y, face.r[1].z); v = face.v[2]; a = (v > 0 ? (v < 1 ? v : 1) : 0); c = col.map(face.v[2]); // glColor4ub(c.r, c.g, c.b, 255 *face.v[2] * m_alpha); glColor4d(1.0, 1.0, 1.0, a * m_alpha); glTexCoord1d(face.v[2]); glVertex3f(face.r[2].x, face.r[2].y, face.r[2].z); } } } glEnd(); }
26.815552
132
0.576978
EMinsight
a9c0133b9f104104cb5810785435ad255377e0cf
1,284
hpp
C++
include/cpp/reproc/error.hpp
jetm/reproc
8289864d73172fba063078549b6e37369c6ecae7
[ "MIT" ]
1
2020-01-13T12:52:19.000Z
2020-01-13T12:52:19.000Z
include/cpp/reproc/error.hpp
jetm/reproc
8289864d73172fba063078549b6e37369c6ecae7
[ "MIT" ]
null
null
null
include/cpp/reproc/error.hpp
jetm/reproc
8289864d73172fba063078549b6e37369c6ecae7
[ "MIT" ]
null
null
null
/*! \file error.hpp */ #ifndef REPROC_ERROR_HPP #define REPROC_ERROR_HPP #include "export.hpp" #include <system_error> /*! \namespace reproc */ namespace reproc { /*! \see REPROC_ERROR */ // When editing make sure to change the corresponding enum in error.h as well. enum class errc { // reproc errors /*! #REPROC_WAIT_TIMEOUT */ wait_timeout = 1, /*! #REPROC_STREAM_CLOSED */ stream_closed, /*! #REPROC_PARTIAL_WRITE */ partial_write, // system errors /*! #REPROC_NOT_ENOUGH_MEMORY */ not_enough_memory, /*! #REPROC_PIPE_LIMIT_REACHED */ pipe_limit_reached, /*! #REPROC_INTERRUPTED */ interrupted, /*! #REPROC_PROCESS_LIMIT_REACHED */ process_limit_reached, /*! #REPROC_INVALID_UNICODE */ invalid_unicode, /*! #REPROC_PERMISSION_DENIED */ permission_denied, /*! #REPROC_SYMLINK_LOOP */ symlink_loop, /*! #REPROC_FILE_NOT_FOUND */ file_not_found, /*! #REPROC_NAME_TOO_LONG */ name_too_long }; /*! \private */ REPROC_EXPORT const std::error_category &error_category() noexcept; /*! \private */ REPROC_EXPORT std::error_condition make_error_condition(reproc::errc error) noexcept; } // namespace reproc namespace std { template <> struct is_error_condition_enum<reproc::errc> : true_type { }; } // namespace std #endif
19.454545
78
0.713396
jetm
a9c1cbb631d3b337281c74fa3054015f79e45fdc
2,500
cpp
C++
StockCommission/StockCommission.cpp
wof8317/StockCommission
cd1bad666a3f64132d1a10da9ee5b8ea5e19d48e
[ "WTFPL" ]
1
2021-09-16T23:44:04.000Z
2021-09-16T23:44:04.000Z
StockCommission/StockCommission.cpp
wof8317/StockCommission
cd1bad666a3f64132d1a10da9ee5b8ea5e19d48e
[ "WTFPL" ]
null
null
null
StockCommission/StockCommission.cpp
wof8317/StockCommission
cd1bad666a3f64132d1a10da9ee5b8ea5e19d48e
[ "WTFPL" ]
null
null
null
#include <iostream> #include <iomanip> using namespace std; int main() { double stockShares = 200; //Total stock shares double sharePrice = 21.77; //Share Price double brokerPercentage = 2; //Brokerage percentage double totalStockPrice = stockShares * sharePrice; //Total Stock price calculation double brokerCommission = totalStockPrice * (brokerPercentage / 100); //Brokerage commission calculation double grossTotal = totalStockPrice + brokerCommission; //Gross Total cout << "Kathrine bought " << stockShares << " shares of stock at a price of $" << sharePrice << " per share." << endl; cout << "She must pay her stock broker a " << brokerPercentage << " percent commission for the transaction." << endl; cout << "This is how much she has to pay..." << endl; cout << "\n-----------------------------------------" << endl; cout << stockShares << " shares @ $" << sharePrice << endl; cout << "-----------------------------------------" << endl; cout << "Total Stock Price: $" << setw(8) << setprecision(2) << fixed << totalStockPrice << endl; cout << "Broker Commission: $" << setw(8) << setprecision(2) << fixed << brokerCommission << endl; cout << "Gross Total: " << setw(7) << "$" << setw(8) << setprecision(2) << fixed << grossTotal << endl; cout << "\nHow many shares will you be buying? "; cin >> stockShares; cout << "\nWhat is the price per share? $"; cin >> sharePrice; cout << "\nWhat percentage will your broker be paid? (3 or 4 ...) "; cin >> brokerPercentage; /* Had to do this nasty hack below where I created new variables by appending a 1 after totalStockPrice, brokerCommission, and grossTotal to display the accurate calculations instead of repeating the initial calculations. I didn't like to do it, but it works. */ double totalStockPrice1 = stockShares * sharePrice; double brokerCommission1 = totalStockPrice1 * (brokerPercentage / 100); double grossTotal1 = totalStockPrice1 + brokerCommission1; cout << "\n-----------------------------------------" << endl; cout << setprecision(0) << stockShares << " shares @ $" << setprecision(2) << sharePrice << endl; cout << "-----------------------------------------" << endl; cout << "Stock Cost: $" << setw(10) << setprecision(2) << fixed << totalStockPrice1 << endl; cout << "Broker Fee: $" << setw(10) << setprecision(2) << fixed << brokerCommission1 << endl; cout << "Total Cost: $" << setw(10) << setprecision(2) << fixed << grossTotal1 << endl; cout << "\nHave a nice day!"; return 0; }
58.139535
148
0.6288
wof8317
a9c3814409cd06cf64948a035e7e27ed364d05b4
6,199
cpp
C++
streets_utils/streets_api/intersection_client_api/OAIIntersection_info.cpp
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
3
2021-09-04T16:25:47.000Z
2022-03-09T20:24:30.000Z
streets_utils/streets_api/intersection_client_api/OAIIntersection_info.cpp
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
85
2021-07-07T16:58:46.000Z
2022-03-31T15:35:26.000Z
streets_utils/streets_api/intersection_client_api/OAIIntersection_info.cpp
arseniy-sonar/carma-streets
394fc3609d417d92180c6b6c88e57d2edda9f854
[ "Apache-2.0" ]
4
2021-05-20T23:12:03.000Z
2021-09-08T15:33:42.000Z
/** * Intersection Model API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIIntersection_info.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIIntersection_info::OAIIntersection_info(QString json) { this->initializeModel(); this->fromJson(json); } OAIIntersection_info::OAIIntersection_info() { this->initializeModel(); } OAIIntersection_info::~OAIIntersection_info() {} void OAIIntersection_info::initializeModel() { m_id_isSet = false; m_id_isValid = false; m_name_isSet = false; m_name_isValid = false; m_entry_lanelets_isSet = false; m_entry_lanelets_isValid = false; m_link_lanelets_isSet = false; m_link_lanelets_isValid = false; m_departure_lanelets_isSet = false; m_departure_lanelets_isValid = false; } void OAIIntersection_info::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIIntersection_info::fromJsonObject(QJsonObject json) { m_id_isValid = ::OpenAPI::fromJsonValue(id, json[QString("id")]); m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; m_name_isValid = ::OpenAPI::fromJsonValue(name, json[QString("name")]); m_name_isSet = !json[QString("name")].isNull() && m_name_isValid; m_entry_lanelets_isValid = ::OpenAPI::fromJsonValue(entry_lanelets, json[QString("entry_lanelets")]); m_entry_lanelets_isSet = !json[QString("entry_lanelets")].isNull() && m_entry_lanelets_isValid; m_link_lanelets_isValid = ::OpenAPI::fromJsonValue(link_lanelets, json[QString("link_lanelets")]); m_link_lanelets_isSet = !json[QString("link_lanelets")].isNull() && m_link_lanelets_isValid; m_departure_lanelets_isValid = ::OpenAPI::fromJsonValue(departure_lanelets, json[QString("departure_lanelets")]); m_departure_lanelets_isSet = !json[QString("departure_lanelets")].isNull() && m_departure_lanelets_isValid; } QString OAIIntersection_info::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIIntersection_info::asJsonObject() const { QJsonObject obj; if (m_id_isSet) { obj.insert(QString("id"), ::OpenAPI::toJsonValue(id)); } if (m_name_isSet) { obj.insert(QString("name"), ::OpenAPI::toJsonValue(name)); } if (entry_lanelets.size() > 0) { obj.insert(QString("entry_lanelets"), ::OpenAPI::toJsonValue(entry_lanelets)); } if (link_lanelets.size() > 0) { obj.insert(QString("link_lanelets"), ::OpenAPI::toJsonValue(link_lanelets)); } if (departure_lanelets.size() > 0) { obj.insert(QString("departure_lanelets"), ::OpenAPI::toJsonValue(departure_lanelets)); } return obj; } qint32 OAIIntersection_info::getId() const { return id; } void OAIIntersection_info::setId(const qint32 &id) { this->id = id; this->m_id_isSet = true; } bool OAIIntersection_info::is_id_Set() const{ return m_id_isSet; } bool OAIIntersection_info::is_id_Valid() const{ return m_id_isValid; } QString OAIIntersection_info::getName() const { return name; } void OAIIntersection_info::setName(const QString &name) { this->name = name; this->m_name_isSet = true; } bool OAIIntersection_info::is_name_Set() const{ return m_name_isSet; } bool OAIIntersection_info::is_name_Valid() const{ return m_name_isValid; } QList<OAILanelet_info> OAIIntersection_info::getEntryLanelets() const { return entry_lanelets; } void OAIIntersection_info::setEntryLanelets(const QList<OAILanelet_info> &entry_lanelets) { this->entry_lanelets = entry_lanelets; this->m_entry_lanelets_isSet = true; } bool OAIIntersection_info::is_entry_lanelets_Set() const{ return m_entry_lanelets_isSet; } bool OAIIntersection_info::is_entry_lanelets_Valid() const{ return m_entry_lanelets_isValid; } QList<OAILanelet_info> OAIIntersection_info::getLinkLanelets() const { return link_lanelets; } void OAIIntersection_info::setLinkLanelets(const QList<OAILanelet_info> &link_lanelets) { this->link_lanelets = link_lanelets; this->m_link_lanelets_isSet = true; } bool OAIIntersection_info::is_link_lanelets_Set() const{ return m_link_lanelets_isSet; } bool OAIIntersection_info::is_link_lanelets_Valid() const{ return m_link_lanelets_isValid; } QList<OAILanelet_info> OAIIntersection_info::getDepartureLanelets() const { return departure_lanelets; } void OAIIntersection_info::setDepartureLanelets(const QList<OAILanelet_info> &departure_lanelets) { this->departure_lanelets = departure_lanelets; this->m_departure_lanelets_isSet = true; } bool OAIIntersection_info::is_departure_lanelets_Set() const{ return m_departure_lanelets_isSet; } bool OAIIntersection_info::is_departure_lanelets_Valid() const{ return m_departure_lanelets_isValid; } bool OAIIntersection_info::isSet() const { bool isObjectUpdated = false; do { if (m_id_isSet) { isObjectUpdated = true; break; } if (m_name_isSet) { isObjectUpdated = true; break; } if (entry_lanelets.size() > 0) { isObjectUpdated = true; break; } if (link_lanelets.size() > 0) { isObjectUpdated = true; break; } if (departure_lanelets.size() > 0) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIIntersection_info::isValid() const { // only required properties are required for the object to be considered valid return true; } } // namespace OpenAPI
28.049774
117
0.71447
arseniy-sonar
a9c4e7a00217091cbc1972484e70d13ba715c3a8
3,606
cpp
C++
src/qt/qtwebkit/Source/WebKit2/UIProcess/qt/QtPanGestureRecognizer.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2021-02-09T10:24:31.000Z
2021-02-09T10:24:31.000Z
src/qt/qtwebkit/Source/WebKit2/UIProcess/qt/QtPanGestureRecognizer.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebKit2/UIProcess/qt/QtPanGestureRecognizer.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/* * Copyright (C) 2011 Benjamin Poulain <benjamin@webkit.org> * * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "QtPanGestureRecognizer.h" #include "PageViewportControllerClientQt.h" #include "QtWebPageEventHandler.h" namespace WebKit { QtPanGestureRecognizer::QtPanGestureRecognizer(QtWebPageEventHandler* eventHandler) : QtGestureRecognizer(eventHandler) { reset(); } bool QtPanGestureRecognizer::update(const QTouchEvent::TouchPoint& touchPoint, qint64 eventTimestampMillis) { m_lastPosition = touchPoint.pos(); m_lastEventTimestampMillis = eventTimestampMillis; switch (m_state) { case NoGesture: m_state = GestureRecognitionStarted; m_firstScreenPosition = touchPoint.screenPos(); if (viewportController()) viewportController()->cancelScrollAnimation(); return false; case GestureRecognitionStarted: { // To start the gesture, the delta from start in screen coordinates // must be bigger than the trigger threshold. QPointF totalOffsetFromStart(touchPoint.screenPos() - m_firstScreenPosition); if (qAbs(totalOffsetFromStart.x()) < panningInitialTriggerDistanceThreshold && qAbs(totalOffsetFromStart.y()) < panningInitialTriggerDistanceThreshold) return false; m_state = GestureRecognized; if (viewportController()) viewportController()->panGestureStarted(touchPoint.pos(), eventTimestampMillis); return true; } case GestureRecognized: if (viewportController()) viewportController()->panGestureRequestUpdate(touchPoint.pos(), eventTimestampMillis); return true; default: ASSERT_NOT_REACHED(); } return false; } void QtPanGestureRecognizer::finish(const QTouchEvent::TouchPoint& touchPoint, qint64 eventTimestampMillis) { if (m_state == NoGesture) return; if (viewportController()) viewportController()->panGestureEnded(touchPoint.pos(), eventTimestampMillis); reset(); } void QtPanGestureRecognizer::cancel() { if (m_state == NoGesture) return; if (viewportController()) { viewportController()->panGestureEnded(m_lastPosition, m_lastEventTimestampMillis); viewportController()->panGestureCancelled(); } reset(); } } // namespace WebKit
37.5625
159
0.731559
viewdy
a9c55865bdeb54accb31a401f036bce5d36b1ab2
1,172
cc
C++
scann/scann/oss_wrappers/scann_status.cc
DionysisChristopoulos/google-research
7f59ef421beef32ca16c2a7215be74f7eba01a0f
[ "Apache-2.0" ]
23,901
2018-10-04T19:48:53.000Z
2022-03-31T21:27:42.000Z
scann/scann/oss_wrappers/scann_status.cc
davidfitzek/google-research
eb2b142f26e39aac1dcbb768417465ae9d4e5af6
[ "Apache-2.0" ]
891
2018-11-10T06:16:13.000Z
2022-03-31T10:42:34.000Z
scann/scann/oss_wrappers/scann_status.cc
davidfitzek/google-research
eb2b142f26e39aac1dcbb768417465ae9d4e5af6
[ "Apache-2.0" ]
6,047
2018-10-12T06:31:02.000Z
2022-03-31T13:59:28.000Z
// Copyright 2021 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "scann/oss_wrappers/scann_status.h" #include "absl/strings/str_cat.h" namespace research_scann { Status AnnotateStatus(const Status& s, absl::string_view msg) { if (s.ok() || msg.empty()) return s; absl::string_view new_msg = msg; std::string annotated; if (!s.error_message().empty()) { absl::StrAppend(&annotated, s.error_message(), "; ", msg); new_msg = annotated; } return Status(s.code(), new_msg); } StatusBuilder RetCheckFail(absl::string_view msg) { return InternalErrorBuilder() << msg; } } // namespace research_scann
30.842105
75
0.722696
DionysisChristopoulos
a9c682341093b34c121737d721ee2285de10f303
2,503
cpp
C++
lib/vdc/KDTreeRG.cpp
RemiLacroix-IDRIS/VAPOR
33c787b6089ad845f6f989176d839e117fcdb03f
[ "BSD-3-Clause" ]
1
2021-04-13T07:18:55.000Z
2021-04-13T07:18:55.000Z
lib/vdc/KDTreeRG.cpp
RemiLacroix-IDRIS/VAPOR
33c787b6089ad845f6f989176d839e117fcdb03f
[ "BSD-3-Clause" ]
null
null
null
lib/vdc/KDTreeRG.cpp
RemiLacroix-IDRIS/VAPOR
33c787b6089ad845f6f989176d839e117fcdb03f
[ "BSD-3-Clause" ]
1
2021-01-07T03:09:10.000Z
2021-01-07T03:09:10.000Z
#include <iostream> #include <vector> #include "vapor/VAssert.h" #include <cmath> #include <vapor/utils.h> #include <vapor/KDTreeRG.h> #include "kdtree.h" using namespace std; using namespace VAPoR; KDTreeRG::KDTreeRG( const Grid &xg, const Grid &yg ) : _points( xg, yg ), _kdtree(2 /* dimension */, _points, nanoflann::KDTreeSingleIndexAdaptorParams(20 /* max leaf num */)) { _dims = xg.GetDimensions(); _kdtree.buildIndex(); } KDTreeRG::~KDTreeRG() { } void KDTreeRG::Nearest( const vector <float> &coordu, vector <size_t> &coord) const { VAssert( coordu.size() == 2 ); // 3D case isn't supported yet size_t ret_index; float dist_sqr; nanoflann::KNNResultSet<float, size_t> resultSet(1); resultSet.init( &ret_index, &dist_sqr ); bool rt = _kdtree.findNeighbors( resultSet, coordu.data(), nanoflann::SearchParams() ); VAssert( rt ); // De-serialize the linear offset and put it back in vector form coord.clear(); coord = Wasp::VectorizeCoords( ret_index, _dims ); } KDTreeRGSubset::KDTreeRGSubset() { _kdtree = NULL; _min.clear(); _max.clear(); } KDTreeRGSubset::KDTreeRGSubset( const KDTreeRG *kdtreerg, const vector <size_t> &min, const vector <size_t> &max ) { VAssert(min.size() == max.size()); vector <size_t> dims = kdtreerg->GetDimensions(); VAssert(min.size() == dims.size()); for (int i=0; i<dims.size(); i++) { VAssert(min[i] <= max[i]); VAssert(max[i] < dims[i]); } _kdtree = kdtreerg; // shallow copy _min = min; _max = max; } // Returned coordinates are relative to min and max used in constructor // The origin is given by min // void KDTreeRGSubset::Nearest( const vector <float> &coordu, vector <size_t> &coord ) const { VAssert(coordu.size() == _min.size()); coord.clear(); vector <size_t> global_coords; // Find voxel coorindates of nearest point in global mesh // _kdtree->Nearest(coordu, global_coords); // Clamp global coordinates to region defined by _min, and _max // for (int i=0; i<global_coords.size(); i++) { if (global_coords[i] < _min[i]) global_coords[i] = _min[i]; if (global_coords[i] > _max[i]) global_coords[i] = _max[i]; } // Translate global coordinates to ROI coordinates // for (int i=0; i<global_coords.size(); i++) { coord.push_back(global_coords[i] - _min[i]); } }
25.282828
121
0.624451
RemiLacroix-IDRIS
a9c81c266fbf5f9b4acf3d55eb925409b2743e22
1,337
cpp
C++
TAO/DevGuideExamples/Messaging/AMIcallback/MessengerHandler.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/DevGuideExamples/Messaging/AMIcallback/MessengerHandler.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/DevGuideExamples/Messaging/AMIcallback/MessengerHandler.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: MessengerHandler.cpp 85583 2009-06-09 13:47:38Z calabrese_p $ #include "MessengerHandler.h" #include "ace/OS_NS_time.h" #include <iostream> // Implementation skeleton constructor MessengerHandler::MessengerHandler (CORBA::ORB_ptr orb) : time_(0) , orb_(CORBA::ORB::_duplicate(orb)) { } // Implementation skeleton destructor MessengerHandler::~MessengerHandler (void) { } void MessengerHandler::send_message ( CORBA::Boolean ami_return_val, const char * message, CORBA::Long time ) { if (ami_return_val) { time_ = time; time_t t = time_; const ACE_TCHAR * time_str = ACE_OS::ctime(&t); if (time_str != 0) { std::cout << std::endl << "Message sent at " << ACE_TEXT_ALWAYS_CHAR (time_str) << std::endl; } std::cout << "Content of message: " << message << std::endl; } else { std::cerr << "Error: Message was not sent." << std::endl; } // Our simple test just shuts down after sending one message. orb_->shutdown(false); } void MessengerHandler::send_message_excep (Messaging::ExceptionHolder* excep_holder) { // We'll print an error message and shut down the orb try { excep_holder->raise_exception(); } catch(const CORBA::Exception& ex) { std::cerr << "A CORBA Exception was thrown: " << ex << std::endl; } orb_->shutdown(false); }
23.45614
84
0.666417
cflowe
a9cf13ee2272c8935d174539f8fb3bfa94d8e657
5,064
cpp
C++
src/components/src/core/attack/KeyboardMeleeAttackComponentTest.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
null
null
null
src/components/src/core/attack/KeyboardMeleeAttackComponentTest.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
null
null
null
src/components/src/core/attack/KeyboardMeleeAttackComponentTest.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
null
null
null
#include "KeyboardMeleeAttackComponent.h" #include "gtest/gtest.h" #include "AnimatorMock.h" #include "FriendlyFireValidatorMock.h" #include "InputMock.h" #include "RayCastMock.h" #include "RendererPoolMock.h" #include "exceptions/DependentComponentNotFound.h" using namespace ::testing; using namespace components::core; class KeyboardMeleeAttackComponentTest : public Test { public: KeyboardMeleeAttackComponentTest() { componentOwner.addComponent<AnimationComponent>(animator); componentOwner.addComponent<VelocityComponent>(6); componentOwner.addComponent<DirectionComponent>(); componentOwner.addComponent<AnimationComponent>(animator); componentOwner.addComponent<BoxColliderComponent>(size); attackComponent.loadDependentComponents(); componentOwner.loadDependentComponents(); } const utils::Vector2f size{5, 5}; const utils::Vector2f position1{20, 20}; std::shared_ptr<NiceMock<graphics::RendererPoolMock>> rendererPool = std::make_shared<NiceMock<graphics::RendererPoolMock>>(); std::shared_ptr<components::core::SharedContext> sharedContext = std::make_shared<components::core::SharedContext>(rendererPool); ComponentOwner componentOwner{position1, "AttackComponentTest1", sharedContext}; StrictMock<input::InputMock> input; const utils::DeltaTime deltaTime{3}; std::shared_ptr<StrictMock<animations::AnimatorMock>> animator = std::make_shared<StrictMock<animations::AnimatorMock>>(); std::shared_ptr<StrictMock<physics::RayCastMock>> rayCast = std::make_shared<StrictMock<physics::RayCastMock>>(); std::unique_ptr<StrictMock<FriendlyFireValidatorMock>> friendlyFireValidatorInit{ std::make_unique<StrictMock<FriendlyFireValidatorMock>>()}; StrictMock<FriendlyFireValidatorMock>* friendlyFireValidator{friendlyFireValidatorInit.get()}; std::shared_ptr<MeleeAttack> meleeAttack = std::make_shared<MeleeAttack>(&componentOwner, rayCast, std::move(friendlyFireValidatorInit)); KeyboardMeleeAttackComponent attackComponent{&componentOwner, meleeAttack}; physics::RayCastResult rayCastResult{nullptr}; }; TEST_F(KeyboardMeleeAttackComponentTest, loadDependentComponentsWithoutAnimationComponent_shouldThrowDependentComponentNotFound) { ComponentOwner componentOwnerWithoutBoxCollider{position1, "componentOwnerWithoutBoxCollider", sharedContext}; KeyboardMeleeAttackComponent attackComponentWithoutBoxCollider{&componentOwnerWithoutBoxCollider, meleeAttack}; ASSERT_THROW(attackComponentWithoutBoxCollider.loadDependentComponents(), components::core::exceptions::DependentComponentNotFound); } TEST_F(KeyboardMeleeAttackComponentTest, givenSpaceNotPressed_shouldNotCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(false)); attackComponent.update(deltaTime, input); } TEST_F(KeyboardMeleeAttackComponentTest, givenSpacePressedAndAnimationIsAlreadyAttack_shouldNotCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(true)); EXPECT_CALL(*animator, getAnimationType()).WillOnce(Return(animations::AnimationType::Attack)); attackComponent.update(deltaTime, input); } TEST_F( KeyboardMeleeAttackComponentTest, givenSpacePressedAndAnimationIsDifferentThanAttackAndAttackAnimationProgressInLessThan60Percents_shouldSetAnimationToAttackAndNotCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(true)); EXPECT_CALL(*animator, getAnimationType()) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Attack)); EXPECT_CALL(*animator, setAnimation(animations::AnimationType::Attack)); EXPECT_CALL(*animator, getCurrentAnimationProgressInPercents()).WillOnce(Return(58)); attackComponent.update(deltaTime, input); } TEST_F( KeyboardMeleeAttackComponentTest, givenSpacePressedAndAnimationIsDifferentThanAttackAndAttackAnimationProgressInMoreThan60Percents_shouldSetAnimationToAttackAndCallAttackStrategy) { EXPECT_CALL(input, isKeyPressed(input::InputKey::Space)).WillOnce(Return(true)); EXPECT_CALL(*animator, getAnimationType()) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Idle)) .WillOnce(Return(animations::AnimationType::Attack)); EXPECT_CALL(*animator, setAnimation(animations::AnimationType::Attack)); EXPECT_CALL(*animator, getCurrentAnimationProgressInPercents()).WillOnce(Return(63)); EXPECT_CALL(*animator, getAnimationDirection()).WillOnce(Return(animations::AnimationDirection::Left)); EXPECT_CALL(*rayCast, cast(_, _, _, _)).WillOnce(Return(rayCastResult)); attackComponent.update(deltaTime, input); }
45.621622
152
0.7656
walter-strazak
a9d1a70c991d68b9fe3d0aa3d9af89318f5d5957
362
cpp
C++
2022/code chef/CodeChef Starters 24 (Rated for Div-2 & Div-3)/Yet Another Constructive Problem.cpp
Yashdew/Data-structure
ae9cd759f4f62b8b524061c47dd59e30c1b69f5f
[ "MIT" ]
1
2020-09-16T03:57:40.000Z
2020-09-16T03:57:40.000Z
2022/code chef/CodeChef Starters 24 (Rated for Div-2 & Div-3)/Yet Another Constructive Problem.cpp
Yashdew/Data-structure
ae9cd759f4f62b8b524061c47dd59e30c1b69f5f
[ "MIT" ]
null
null
null
2022/code chef/CodeChef Starters 24 (Rated for Div-2 & Div-3)/Yet Another Constructive Problem.cpp
Yashdew/Data-structure
ae9cd759f4f62b8b524061c47dd59e30c1b69f5f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve() { int X; cin>>X; cout<< (X^1); cout<<" "; cout<< (X^2); cout<<" "<<X<<endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int testCases; cin >> testCases; while (testCases--) { solve(); } return 0; }
13.407407
37
0.477901
Yashdew
a9d51610294a58cbd708d5155eaaeac9b21fbad3
2,095
cpp
C++
boost/libs/type_traits/test/add_volatile_test.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
3
2019-06-25T23:20:19.000Z
2021-03-14T19:38:34.000Z
boost/libs/type_traits/test/add_volatile_test.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
1
2018-01-17T10:11:43.000Z
2018-01-17T10:11:43.000Z
boost/libs/type_traits/test/add_volatile_test.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
3
2016-07-26T08:07:09.000Z
2019-06-25T23:20:21.000Z
// (C) Copyright John Maddock 2000. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.tt.org/LICENSE_1_0.txt) #include "test.hpp" #include "check_type.hpp" #ifdef TEST_STD # include <type_traits> #else # include <boost/type_traits/add_volatile.hpp> #endif BOOST_DECL_TRANSFORM_TEST(add_volatile_test_1, ::tt::add_volatile, const, const volatile) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_2, ::tt::add_volatile, volatile, volatile) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_3, ::tt::add_volatile, *, *volatile) BOOST_DECL_TRANSFORM_TEST2(add_volatile_test_4, ::tt::add_volatile, volatile) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_7, ::tt::add_volatile, *volatile, *volatile) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_10, ::tt::add_volatile, const*, const*volatile) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_11, ::tt::add_volatile, volatile*, volatile*volatile) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_5, ::tt::add_volatile, const &, const&) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_6, ::tt::add_volatile, &, &) #ifndef BOOST_NO_RVALUE_REFERENCES BOOST_DECL_TRANSFORM_TEST(add_volatile_test_6a, ::tt::add_volatile, &&, &&) #endif BOOST_DECL_TRANSFORM_TEST(add_volatile_test_8, ::tt::add_volatile, const [2], const volatile [2]) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_9, ::tt::add_volatile, volatile &, volatile&) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_12, ::tt::add_volatile, [2][3], volatile[2][3]) BOOST_DECL_TRANSFORM_TEST(add_volatile_test_13, ::tt::add_volatile, (&)[2], (&)[2]) TT_TEST_BEGIN(add_volatile) add_volatile_test_1(); add_volatile_test_2(); add_volatile_test_3(); add_volatile_test_4(); add_volatile_test_7(); add_volatile_test_10(); add_volatile_test_11(); add_volatile_test_5(); add_volatile_test_6(); add_volatile_test_8(); add_volatile_test_9(); add_volatile_test_12(); add_volatile_test_13(); #ifndef BOOST_NO_RVALUE_REFERENCES add_volatile_test_6a(); #endif TT_TEST_END
34.916667
97
0.785203
randolphwong
a9dc791f2ff6d477391fe1e44f17828fd4c659c6
5,487
cpp
C++
libs/log/example/doc/extension_stat_collector.cpp
HelloSunyi/boost_1_54_0
429fea793612f973d4b7a0e69c5af8156ae2b56e
[ "BSL-1.0" ]
7
2015-03-03T15:45:12.000Z
2021-04-25T03:37:17.000Z
libs/log/example/doc/extension_stat_collector.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
1
2015-09-05T12:23:01.000Z
2015-09-05T12:23:01.000Z
libs/log/example/doc/extension_stat_collector.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
2
2018-06-21T15:08:14.000Z
2021-04-25T03:37:22.000Z
/* * Copyright Andrey Semashev 2007 - 2013. * 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) */ #include <string> #include <fstream> #include <iostream> #include <stdexcept> #include <boost/shared_ptr.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/phoenix.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/sinks/basic_sink_backend.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/attributes/value_visitation.hpp> #include <boost/log/utility/manipulators/add_value.hpp> namespace logging = boost::log; namespace src = boost::log::sources; namespace expr = boost::log::expressions; namespace sinks = boost::log::sinks; namespace keywords = boost::log::keywords; //[ example_extension_stat_collector_definition // The backend collects statistical information about network activity of the application class stat_collector : public sinks::basic_sink_backend< sinks::combine_requirements< sinks::synchronized_feeding, /*< we will have to store internal data, so let's require frontend to synchronize feeding calls to the backend >*/ sinks::flushing /*< also enable flushing support >*/ >::type > { private: // The file to write the collected information to std::ofstream m_csv_file; // Here goes the data collected so far: // Active connections unsigned int m_active_connections; // Sent bytes unsigned int m_sent_bytes; // Received bytes unsigned int m_received_bytes; // The number of collected records since the last write to the file unsigned int m_collected_count; // The time when the collected data has been written to the file last time boost::posix_time::ptime m_last_store_time; public: // The constructor initializes the internal data explicit stat_collector(const char* file_name); // The function consumes the log records that come from the frontend void consume(logging::record_view const& rec); // The function flushes the file void flush(); private: // The function resets statistical accumulators to initial values void reset_accumulators(); // The function writes the collected data to the file void write_data(); }; //] // The constructor initializes the internal data stat_collector::stat_collector(const char* file_name) : m_csv_file(file_name, std::ios::app), m_active_connections(0), m_last_store_time(boost::posix_time::microsec_clock::universal_time()) { reset_accumulators(); if (!m_csv_file.is_open()) throw std::runtime_error("could not open the CSV file"); } //[ example_extension_stat_collector_consume BOOST_LOG_ATTRIBUTE_KEYWORD(sent, "Sent", unsigned int) BOOST_LOG_ATTRIBUTE_KEYWORD(received, "Received", unsigned int) // The function consumes the log records that come from the frontend void stat_collector::consume(logging::record_view const& rec) { // Accumulate statistical readings if (rec.attribute_values().count("Connected")) ++m_active_connections; else if (rec.attribute_values().count("Disconnected")) --m_active_connections; else { namespace phoenix = boost::phoenix; logging::visit(sent, rec, phoenix::ref(m_sent_bytes) += phoenix::placeholders::_1); logging::visit(received, rec, phoenix::ref(m_received_bytes) += phoenix::placeholders::_1); } ++m_collected_count; // Check if it's time to write the accumulated data to the file boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); if (now - m_last_store_time >= boost::posix_time::minutes(1)) { write_data(); m_last_store_time = now; } } // The function writes the collected data to the file void stat_collector::write_data() { m_csv_file << m_active_connections << ',' << m_sent_bytes << ',' << m_received_bytes << std::endl; reset_accumulators(); } // The function resets statistical accumulators to initial values void stat_collector::reset_accumulators() { m_sent_bytes = m_received_bytes = 0; m_collected_count = 0; } //] //[ example_extension_stat_collector_flush // The function flushes the file void stat_collector::flush() { // Store any data that may have been collected since the list write to the file if (m_collected_count > 0) { write_data(); m_last_store_time = boost::posix_time::microsec_clock::universal_time(); } m_csv_file.flush(); } //] // Complete sink type typedef sinks::synchronous_sink< stat_collector > sink_t; void init_logging() { boost::shared_ptr< logging::core > core = logging::core::get(); boost::shared_ptr< stat_collector > backend(new stat_collector("stat.csv")); boost::shared_ptr< sink_t > sink(new sink_t(backend)); core->add_sink(sink); } int main(int, char*[]) { init_logging(); src::logger lg; BOOST_LOG(lg) << logging::add_value("Connected", true); BOOST_LOG(lg) << logging::add_value("Sent", 100u); BOOST_LOG(lg) << logging::add_value("Received", 200u); logging::core::get()->flush(); return 0; }
31.901163
194
0.69692
HelloSunyi
a9ddbab5bf1fb4deca3be377f9454a1f8cf6d1d9
1,483
cpp
C++
TrackAlgTLD/src/tld/VarianceFilter.cpp
RayanWang/CameraTrackingFramework
1ab2f7289cd000a4baa584bca469744a5486610f
[ "MIT" ]
3
2016-11-05T03:31:48.000Z
2016-12-07T05:57:28.000Z
TrackAlgTLD/src/tld/VarianceFilter.cpp
RayanWang/CameraTrackingFramework
1ab2f7289cd000a4baa584bca469744a5486610f
[ "MIT" ]
null
null
null
TrackAlgTLD/src/tld/VarianceFilter.cpp
RayanWang/CameraTrackingFramework
1ab2f7289cd000a4baa584bca469744a5486610f
[ "MIT" ]
3
2018-11-10T17:19:49.000Z
2020-04-11T16:30:26.000Z
#include "VarianceFilter.h" #include "IntegralImage.h" #include "DetectorCascade.h" using namespace cv; namespace tld { VarianceFilter::VarianceFilter() { enabled = true; minVar = 0; integralImg = NULL; integralImg_squared = NULL; } VarianceFilter::~VarianceFilter() { release(); } void VarianceFilter::release() { if(integralImg != NULL) delete integralImg; integralImg = NULL; if(integralImg_squared != NULL) delete integralImg_squared; integralImg_squared = NULL; } float VarianceFilter::calcVariance(int *off) { int *ii1 = integralImg->data; long long *ii2 = integralImg_squared->data; float mX = (ii1[off[3]] - ii1[off[2]] - ii1[off[1]] + ii1[off[0]]) / (float) off[5]; //Sum of Area divided by area float mX2 = (ii2[off[3]] - ii2[off[2]] - ii2[off[1]] + ii2[off[0]]) / (float) off[5]; return mX2 - mX * mX; } void VarianceFilter::nextIteration(const Mat &img) { if(!enabled) return; release(); integralImg = new IntegralImage<int>(img.size()); integralImg->calcIntImg(img); integralImg_squared = new IntegralImage<long long>(img.size()); integralImg_squared->calcIntImg(img, true); } bool VarianceFilter::filter(int i) { if(!enabled) return true; float bboxvar = calcVariance(windowOffsets + TLD_WINDOW_OFFSET_SIZE * i); detectionResult->variances[i] = bboxvar; if(bboxvar < minVar) { return false; } return true; } } /* namespace tld */
19.513158
119
0.656777
RayanWang
a9deb353db8fc5d30f5b4f7b0b1f3a8963dcec3c
1,440
hpp
C++
code/client/src/sdk/ue/sys/math/utils.hpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
16
2021-10-08T17:47:04.000Z
2022-03-28T13:26:37.000Z
code/client/src/sdk/ue/sys/math/utils.hpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2022-01-19T08:11:57.000Z
2022-01-29T19:02:24.000Z
code/client/src/sdk/ue/sys/math/utils.hpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2021-10-09T11:15:08.000Z
2022-01-27T22:42:26.000Z
#pragma once #include <algorithm> #include <chrono> namespace SDK { namespace ue::sys::math { template <class T> T Lerp(const T &from, const T &to, float fAlpha) { return (T)((to - from) * fAlpha + from); } // Find the relative position of Pos between From and To inline const float Unlerp(const double from, const double to, const double pos) { // Avoid dividing by 0 (results in INF values) if (from == to) return 1.0f; return static_cast<float>((pos - from) / (to - from)); } inline const float Unlerp(const std::chrono::high_resolution_clock::time_point &from, const std::chrono::high_resolution_clock::time_point &to, const std::chrono::high_resolution_clock::time_point &pos) { float r = std::chrono::duration<float, std::milli>(to - from).count(); // Avoid dividing by 0 (results in INF values) if (r < std::numeric_limits<float>::epsilon()) return 1.0f; return std::chrono::duration<float, std::milli>(pos - from).count() / r; } // Unlerp avoiding extrapolation inline const float UnlerpClamped(const double from, const double to, const double pos) { return std::clamp(Unlerp(from, to, pos), 0.0f, 1.0f); } }; // namespace ue::sys::math } // namespace SDK
38.918919
151
0.579167
mufty
a9df1b2ab510da473615f0d4e30847f91ecc016a
808
cpp
C++
0628-Maximum Product of Three Numbers/0628-Maximum Product of Three Numbers.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0601-0700/0628-Maximum Product of Three Numbers/0628-Maximum Product of Three Numbers.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0601-0700/0628-Maximum Product of Three Numbers/0628-Maximum Product of Three Numbers.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: int maximumProduct(vector<int>& nums) { int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; int min1 = INT_MAX, min2 = INT_MAX; for (int num : nums) { if (num > max1) { max3 = max2; max2 = max1; max1 = num; } else if (num > max2) { max3 = max2; max2 = num; } else if (num > max3) { max3 = num; } if (num < min1) { min2 = min1; min1 = num; } else if (num < min2) { min2 = num; } } return max(max1 * max2 * max3, max1 * min1 * min2); } };
25.25
59
0.346535
zhuangli1987
a9e1598a57924d76b824131c3f84fe4f6fc8e22e
6,924
inl
C++
Base/PLCore/include/PLCore/Xml/XmlNode.inl
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/include/PLCore/Xml/XmlNode.inl
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/include/PLCore/Xml/XmlNode.inl
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: XmlNode.inl * * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * The meaning of 'value' changes for the specific type of 'XmlNode' */ inline String XmlNode::GetValue() const { return m_sValue; } /** * @brief * Changes the value of the node */ inline void XmlNode::SetValue(const String &sValue) { m_sValue = sValue; } /** * @brief * One step up the DOM */ inline XmlNode *XmlNode::GetParent() { return m_pParent; } inline const XmlNode *XmlNode::GetParent() const { return m_pParent; } /** * @brief * Returns the first child of this node */ inline XmlNode *XmlNode::GetFirstChild() { return m_pFirstChild; } inline const XmlNode *XmlNode::GetFirstChild() const { return m_pFirstChild; } /** * @brief * Returns the last child of this node */ inline XmlNode *XmlNode::GetLastChild() { return m_pLastChild; } inline const XmlNode *XmlNode::GetLastChild() const { return m_pLastChild; } /** * @brief * An alternate way to walk the children of a node */ inline XmlNode *XmlNode::IterateChildren(XmlNode *pPrevious) { return const_cast< XmlNode* >( (const_cast< const XmlNode* >(this))->IterateChildren( pPrevious ) ); } inline const XmlNode *XmlNode::IterateChildren(const XmlNode *pPrevious) const { return pPrevious ? pPrevious->GetNextSibling() : GetFirstChild(); } /** * @brief * This flavor of 'IterateChildren()' searches for children with a particular 'value' */ inline XmlNode *XmlNode::IterateChildren(const String &sValue, XmlNode *pPrevious) { return pPrevious ? pPrevious->GetNextSibling(sValue) : GetFirstChild(sValue); } inline const XmlNode *XmlNode::IterateChildren(const String &sValue, const XmlNode *pPrevious) const { return pPrevious ? pPrevious->GetNextSibling(sValue) : GetFirstChild(sValue); } /** * @brief * Navigate to a sibling node */ inline XmlNode *XmlNode::GetPreviousSibling() { return m_pPreviousSibling; } inline const XmlNode *XmlNode::GetPreviousSibling() const { return m_pPreviousSibling; } /** * @brief * Navigate to a sibling node */ inline XmlNode *XmlNode::GetNextSibling() { return m_pNextSibling; } inline const XmlNode *XmlNode::GetNextSibling() const { return m_pNextSibling; } /** * @brief * Convenience function to get through elements */ inline XmlElement *XmlNode::GetNextSiblingElement() { return const_cast< XmlElement* >( (const_cast< const XmlNode* >(this))->GetNextSiblingElement() ); } /** * @brief * Convenience function to get through elements */ inline XmlElement *XmlNode::GetFirstChildElement() { return const_cast< XmlElement* >( (const_cast< const XmlNode* >(this))->GetFirstChildElement() ); } /** * @brief * Convenience function to get through elements */ inline XmlElement *XmlNode::GetFirstChildElement(const String &sValue) { return const_cast< XmlElement* >( (const_cast< const XmlNode* >(this))->GetFirstChildElement( sValue ) ); } /** * @brief * Query the type (as an enumerated value, above) of this node */ inline XmlNode::ENodeType XmlNode::GetType() const { return m_nType; } /** * @brief * Return a pointer to the document this node lives in */ inline XmlDocument *XmlNode::GetDocument() { return const_cast< XmlDocument* >( (const_cast< const XmlNode* >(this))->GetDocument() ); } /** * @brief * Returns true if this node has no children */ inline bool XmlNode::NoChildren() const { return !m_pFirstChild; } /** * @brief * Cast functions */ inline XmlDocument *XmlNode::ToDocument() { return (m_nType == Document) ? reinterpret_cast<XmlDocument*>(this) : nullptr; } inline const XmlDocument *XmlNode::ToDocument() const { return (m_nType == Document) ? reinterpret_cast<const XmlDocument*>(this) : nullptr; } inline XmlElement *XmlNode::ToElement() { return (m_nType == Element) ? reinterpret_cast<XmlElement*>(this) : nullptr; } inline const XmlElement *XmlNode::ToElement() const { return (m_nType == Element) ? reinterpret_cast<const XmlElement*>(this) : nullptr; } inline XmlComment *XmlNode::ToComment() { return (m_nType == Comment) ? reinterpret_cast<XmlComment*>(this) : nullptr; } inline const XmlComment *XmlNode::ToComment() const { return (m_nType == Comment) ? reinterpret_cast<const XmlComment*>(this) : nullptr; } inline XmlUnknown *XmlNode::ToUnknown() { return (m_nType == Unknown) ? reinterpret_cast<XmlUnknown*>(this) : nullptr; } inline const XmlUnknown *XmlNode::ToUnknown() const { return (m_nType == Unknown) ? reinterpret_cast<const XmlUnknown*>(this) : nullptr; } inline XmlText *XmlNode::ToText() { return (m_nType == Text) ? reinterpret_cast<XmlText*>(this) : nullptr; } inline const XmlText *XmlNode::ToText() const { return (m_nType == Text) ? reinterpret_cast<const XmlText*>(this) : nullptr; } inline XmlDeclaration *XmlNode::ToDeclaration() { return (m_nType == Declaration) ? reinterpret_cast<XmlDeclaration*>(this) : nullptr; } inline const XmlDeclaration *XmlNode::ToDeclaration() const { return (m_nType == Declaration) ? reinterpret_cast<const XmlDeclaration*>(this) : nullptr; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
25.362637
106
0.656557
ktotheoz
a9e198693653c41b6af3f15700fb519cbf552555
5,588
cpp
C++
tests/unit/weightedgraph_test.cpp
hyunsukimsokcho/libdai
52c0b51823724f02c7a268e6af6db72dc3324385
[ "BSD-2-Clause" ]
11
2018-01-31T16:14:28.000Z
2021-06-22T03:45:11.000Z
tests/unit/weightedgraph_test.cpp
flurischt/libDAI
20683a222e2ef307209290f79081fe428d9c5050
[ "BSD-2-Clause" ]
1
2019-05-25T08:20:58.000Z
2020-02-17T10:58:55.000Z
tests/unit/weightedgraph_test.cpp
flurischt/libDAI
20683a222e2ef307209290f79081fe428d9c5050
[ "BSD-2-Clause" ]
3
2018-12-13T11:49:22.000Z
2021-12-31T03:19:26.000Z
/* This file is part of libDAI - http://www.libdai.org/ * * Copyright (c) 2006-2011, The libDAI authors. All rights reserved. * * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <dai/weightedgraph.h> #include <dai/exceptions.h> #include <strstream> #include <vector> using namespace dai; #define BOOST_TEST_MODULE WeighedGraphTest #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( DEdgeTest ) { DEdge a; BOOST_CHECK_EQUAL( a.first, 0 ); BOOST_CHECK_EQUAL( a.second, 0 ); DEdge b( 3, 5 ); BOOST_CHECK_EQUAL( b.first, 3 ); BOOST_CHECK_EQUAL( b.second, 5 ); DEdge c( 5, 3 ); BOOST_CHECK_EQUAL( c.first, 5 ); BOOST_CHECK_EQUAL( c.second, 3 ); DEdge d( c ); DEdge e = c; DEdge f( 5, 4 ); DEdge g( 3, 6 ); BOOST_CHECK( !(a == b) ); BOOST_CHECK( !(a == c) ); BOOST_CHECK( !(b == c) ); BOOST_CHECK( d == c ); BOOST_CHECK( c == d ); BOOST_CHECK( e == c ); BOOST_CHECK( c == e ); BOOST_CHECK( d == e ); BOOST_CHECK( e == d ); BOOST_CHECK( a < b ); BOOST_CHECK( a < c ); BOOST_CHECK( b < c ); BOOST_CHECK( !(c < d) ); BOOST_CHECK( !(b < a) ); BOOST_CHECK( !(c < a) ); BOOST_CHECK( !(c < b) ); BOOST_CHECK( !(d < c) ); BOOST_CHECK( a < f ); BOOST_CHECK( b < f ); BOOST_CHECK( c < f ); BOOST_CHECK( g < f ); BOOST_CHECK( !(f < a) ); BOOST_CHECK( !(f < b) ); BOOST_CHECK( !(f < c) ); BOOST_CHECK( !(f < g) ); BOOST_CHECK( a < g ); BOOST_CHECK( b < g ); BOOST_CHECK( !(c < g) ); BOOST_CHECK( !(g < a) ); BOOST_CHECK( !(g < b) ); BOOST_CHECK( g < c ); std::stringstream ss; ss << c; std::string s; ss >> s; BOOST_CHECK_EQUAL( s, "(5->3)" ); BOOST_CHECK_EQUAL( c.toString(), s ); } BOOST_AUTO_TEST_CASE( UEdgeTest ) { UEdge a; BOOST_CHECK_EQUAL( a.first, 0 ); BOOST_CHECK_EQUAL( a.second, 0 ); UEdge b( 3, 5 ); BOOST_CHECK_EQUAL( b.first, 3 ); BOOST_CHECK_EQUAL( b.second, 5 ); UEdge c( 5, 3 ); BOOST_CHECK_EQUAL( c.first, 5 ); BOOST_CHECK_EQUAL( c.second, 3 ); UEdge d( c ); UEdge e = c; UEdge f( 5, 4 ); UEdge g( 3, 6 ); UEdge h( DEdge( 5, 3 ) ); BOOST_CHECK_EQUAL( h.first, 5 ); BOOST_CHECK_EQUAL( h.second, 3 ); BOOST_CHECK( !(a == b) ); BOOST_CHECK( !(a == c) ); BOOST_CHECK( b == c ); BOOST_CHECK( d == c ); BOOST_CHECK( c == d ); BOOST_CHECK( e == c ); BOOST_CHECK( c == e ); BOOST_CHECK( d == e ); BOOST_CHECK( e == d ); BOOST_CHECK( a < b ); BOOST_CHECK( a < c ); BOOST_CHECK( !(b < c) ); BOOST_CHECK( !(c < d) ); BOOST_CHECK( !(b < a) ); BOOST_CHECK( !(c < a) ); BOOST_CHECK( !(c < b) ); BOOST_CHECK( !(d < c) ); BOOST_CHECK( a < f ); BOOST_CHECK( b < f ); BOOST_CHECK( c < f ); BOOST_CHECK( g < f ); BOOST_CHECK( !(f < a) ); BOOST_CHECK( !(f < b) ); BOOST_CHECK( !(f < c) ); BOOST_CHECK( !(f < g) ); BOOST_CHECK( a < g ); BOOST_CHECK( b < g ); BOOST_CHECK( c < g ); BOOST_CHECK( !(g < a) ); BOOST_CHECK( !(g < b) ); BOOST_CHECK( !(g < c) ); std::stringstream ss; std::string s; ss << c; ss >> s; BOOST_CHECK_EQUAL( s, "{3--5}" ); BOOST_CHECK_EQUAL( c.toString(), s ); ss << b; ss >> s; BOOST_CHECK_EQUAL( s, "{3--5}" ); BOOST_CHECK_EQUAL( b.toString(), s ); } BOOST_AUTO_TEST_CASE( RootedTreeTest ) { typedef UEdge E; std::vector<E> edges; edges.push_back( E( 1, 2 ) ); edges.push_back( E( 2, 3 ) ); edges.push_back( E( 3, 1 ) ); GraphEL G( edges.begin(), edges.end() ); BOOST_CHECK_THROW( RootedTree T( G, 0 ), Exception ); BOOST_CHECK_THROW( RootedTree T( G, 1 ), Exception ); edges.back().second = 4; G = GraphEL( edges.begin(), edges.end() ); RootedTree T; T = RootedTree( G, 1 ); BOOST_CHECK_EQUAL( T.size(), 3 ); BOOST_CHECK_EQUAL( T[0], DEdge( 1, 2 ) ); BOOST_CHECK_EQUAL( T[1], DEdge( 2, 3 ) ); BOOST_CHECK_EQUAL( T[2], DEdge( 3, 4 ) ); edges.push_back( E(5, 6) ); G = GraphEL( edges.begin(), edges.end() ); BOOST_CHECK_THROW( RootedTree T( G, 1 ), Exception ); GraphAL H( 3 ); H.addEdge( 0, 1 ); H.addEdge( 1, 2 ); H.addEdge( 2, 1 ); G = GraphEL( H ); for( GraphEL::const_iterator e = G.begin(); e != G.end(); e++ ) BOOST_CHECK( H.hasEdge( e->first, e->second ) ); } BOOST_AUTO_TEST_CASE( SpanningTreeTest ) { RootedTree T; WeightedGraph<int> G; G[UEdge(0,1)] = 1; G[UEdge(0,2)] = 2; G[UEdge(1,2)] = 3; G[UEdge(1,3)] = 4; G[UEdge(2,3)] = 5; RootedTree TMin; TMin.push_back( DEdge( 0,1 ) ); TMin.push_back( DEdge( 0,2 ) ); TMin.push_back( DEdge( 1,3 ) ); RootedTree TMax; TMax.push_back( DEdge( 0,2 ) ); TMax.push_back( DEdge( 2,3 ) ); TMax.push_back( DEdge( 3,1 ) ); // T = MinSpanningTree( G, true ); // disabled because of bug in boost graph library 1.54 // BOOST_CHECK_EQUAL( T, TMin ); T = MinSpanningTree( G, false ); BOOST_CHECK_EQUAL( T, TMin ); // T = MaxSpanningTree( G, true ); // disabled because of bug in boost graph library 1.54 // BOOST_CHECK_EQUAL( T, TMax ); T = MaxSpanningTree( G, false ); BOOST_CHECK_EQUAL( T, TMax ); WeightedGraph<double> H; H[UEdge(1,2)] = 1; H[UEdge(1,3)] = 2; H[UEdge(2,3)] = 3; H[UEdge(2,4)] = 4; H[UEdge(3,4)] = 5; BOOST_CHECK_THROW( T = MinSpanningTree( H, true ), Exception ); }
25.87037
101
0.549571
hyunsukimsokcho
a9e69fca7b101add965ea2fc385fbff4c246eab5
20,100
cpp
C++
dcgmi/tests/TestDiag.cpp
deepio/DCGM
d10273f18fb3d425da752ab6bb7e07af3d18caec
[ "Apache-2.0" ]
85
2021-02-03T19:58:50.000Z
2022-03-21T08:00:11.000Z
dcgmi/tests/TestDiag.cpp
deepio/DCGM
d10273f18fb3d425da752ab6bb7e07af3d18caec
[ "Apache-2.0" ]
19
2021-03-19T08:13:58.000Z
2022-03-17T02:50:41.000Z
dcgmi/tests/TestDiag.cpp
deepio/DCGM
d10273f18fb3d425da752ab6bb7e07af3d18caec
[ "Apache-2.0" ]
17
2021-02-04T06:47:30.000Z
2022-03-21T22:14:03.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fstream> #include <iostream> #include <stddef.h> #include <string> #include "Diag.h" #include "NvvsJsonStrings.h" #include "PluginStrings.h" #include "TestDiag.h" #include "Topo.h" TestDiag::TestDiag() {} TestDiag::~TestDiag() {} int TestDiag::Run() { int st; int Nfailed = 0; st = TestHelperGetPluginName(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestHelperGetPluginName FAILED with %d.\n", st); } else fprintf(stdout, "TestDiag::TestHelperGetPluginName PASSED.\n"); st = TestHelperJsonAddResult(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestHelperJsonAddResult FAILED with %d.\n", st); } else fprintf(stdout, "TestDiag::TestHelperJsonAddResult PASSED.\n"); st = TestHelperJsonAddBasicTests(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestHelperJsonAddBasicTests FAILED with %d.\n", st); } else fprintf(stdout, "TestDiag::TestHelperJsonAddBasicTests PASSED.\n"); st = TestHelperJsonBuildOutput(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestHelperDisplayAsJson FAILED with %d.\n", st); } else fprintf(stdout, "TestDiag::TestHelperDisplayAsJson PASSED.\n"); st = TestGetFailureResult(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestGetFailureResult FAILED with %d.\n", st); } else fprintf(stdout, "TestDiag::TestGetFailureResult PASSED.\n"); st = TestPopulateGpuList(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestPopulateGpuList FAILED with %d.\n", st); } else fprintf(stdout, "TestDiag::TestPopulateGpuList PASSED.\n"); st = TestHelperGetAffinity(); if (st) { Nfailed++; fprintf(stderr, "TestDiag::TestHelperGetAffinity FAILED with %d.\n", st); } else { fprintf(stdout, "TestDiag::TestHelperGetAffinity PASSED.\n"); } return Nfailed; } int TestDiag::TestPopulateGpuList() { std::vector<unsigned int> gpuVec; dcgmDiagResponse_t diagResult; int ret = 0; Diag d; d.InitializeDiagResponse(diagResult); // Test initial conditions for (unsigned int i = 0; i < DCGM_MAX_NUM_DEVICES; i++) { if (diagResult.perGpuResponses[i].gpuId != DCGM_MAX_NUM_DEVICES) { fprintf(stderr, "Gpu Id wasn't initialized correctly for the %dth position", i); ret = -1; } } if (diagResult.gpuCount != 0) { fprintf(stderr, "Gpu count should be 0 but was %d.\n", diagResult.gpuCount); ret = -1; } if (diagResult.version != dcgmDiagResponse_version) { fprintf(stderr, "Version should be %u but was %u.\n", dcgmDiagResponse_version, diagResult.version); ret = -1; } d.PopulateGpuList(diagResult, gpuVec); if (gpuVec.size() != 0) { fprintf(stderr, "Shouldn't have added gpus to the list from an empty diagResult, but we did.\n"); ret = -1; } // The server code will set the gpuId sometimes on GPUs that haven't run, but when it does // it'll initialize the tests to not have run, so let's set up ours that way for (unsigned int i = 0; i < DCGM_PER_GPU_TEST_COUNT; i++) { diagResult.perGpuResponses[0].results[i].status = DCGM_DIAG_RESULT_NOT_RUN; diagResult.perGpuResponses[1].results[i].status = DCGM_DIAG_RESULT_PASS; } diagResult.perGpuResponses[0].gpuId = 0; diagResult.perGpuResponses[1].gpuId = 1; diagResult.gpuCount = 1; d.PopulateGpuList(diagResult, gpuVec); if (gpuVec.size() != diagResult.gpuCount) { fprintf(stderr, "Expected %u GPUs in the list, but found %u.\n", diagResult.gpuCount, (unsigned)gpuVec.size()); ret = -1; } return ret; } int TestDiag::TestGetFailureResult() { int ret = 0; Diag d; dcgmDiagResponse_t diagResult = {}; diagResult.levelOneTestCount = DCGM_SWTEST_COUNT; dcgmReturn_t drt = d.GetFailureResult(diagResult); if (drt != DCGM_ST_OK) { fprintf(stderr, "Expected a zero initialized diagResult to return success, but got '%s'.\n", errorString(drt)); ret = -1; } diagResult.levelOneResults[DCGM_SWTEST_INFOROM].status = DCGM_DIAG_RESULT_FAIL; drt = d.GetFailureResult(diagResult); if (drt != DCGM_ST_NVVS_ERROR) { ret = -1; fprintf(stderr, "Expected an error when the inforom test returns a failure, but got success.\n"); } // Clear this failure diagResult.levelOneResults[DCGM_SWTEST_INFOROM].status = DCGM_DIAG_RESULT_WARN; drt = d.GetFailureResult(diagResult); if (drt != DCGM_ST_OK) { fprintf( stderr, "Expected a diagResult with only a warning to return success, but got '%s'.\n", errorString(drt)); ret = -1; } diagResult.gpuCount = 1; diagResult.perGpuResponses[3].results[DCGM_PCI_INDEX].status = DCGM_DIAG_RESULT_FAIL; drt = d.GetFailureResult(diagResult); if (drt != DCGM_ST_OK) { fprintf(stderr, "Shouldn't have picked up a failure outside of our gpu count.\n"); ret = -1; } diagResult.gpuCount = 4; drt = d.GetFailureResult(diagResult); if (drt != DCGM_ST_NVVS_ERROR) { ret = -1; fprintf(stderr, "Expected an error when the PCI test returns a failure, but got success.\n"); } return ret; } std::string TestDiag::GetTag() { return std::string("diag"); } int TestDiag::TestHelperGetPluginName() { int ret = 0; Diag d; std::string name = d.HelperGetPluginName(DCGM_MEMORY_INDEX); if (name != "GPU Memory") { fprintf(stderr, "Expected 'GPU Memory' to be the name for test index %d, but got '%s'.\n", static_cast<int>(DCGM_MEMORY_INDEX), name.c_str()); ret = -1; } name = d.HelperGetPluginName(DCGM_DIAGNOSTIC_INDEX); if (name != DIAGNOSTIC_PLUGIN_NAME) { fprintf(stderr, "Expected '%s' to be the name for test index %d, but got '%s'.\n", DIAGNOSTIC_PLUGIN_NAME, static_cast<int>(DCGM_DIAGNOSTIC_INDEX), name.c_str()); ret = -1; } name = d.HelperGetPluginName(DCGM_PCI_INDEX); if (name != PCIE_PLUGIN_NAME) { fprintf(stderr, "Expected '%s' to be the name for test index %d, but got '%s'.\n", PCIE_PLUGIN_NAME, static_cast<int>(DCGM_PCI_INDEX), name.c_str()); ret = -1; } name = d.HelperGetPluginName(DCGM_SM_STRESS_INDEX); if (name != SMSTRESS_PLUGIN_NAME) { fprintf(stderr, "Expected '%s' to be the name for test index %d, but got '%s'.\n", SMSTRESS_PLUGIN_NAME, static_cast<int>(DCGM_SM_STRESS_INDEX), name.c_str()); ret = -1; } name = d.HelperGetPluginName(DCGM_TARGETED_STRESS_INDEX); if (name != TS_PLUGIN_NAME) { fprintf(stderr, "Expected '%s' to be the name for test index %d, but got '%s'.\n", TS_PLUGIN_NAME, static_cast<int>(DCGM_TARGETED_STRESS_INDEX), name.c_str()); ret = -1; } name = d.HelperGetPluginName(DCGM_TARGETED_POWER_INDEX); if (name != TP_PLUGIN_NAME) { fprintf(stderr, "Expected '%s' to be the name for test index %d, but got '%s'.\n", TP_PLUGIN_NAME, static_cast<int>(DCGM_TARGETED_POWER_INDEX), name.c_str()); ret = -1; } name = d.HelperGetPluginName(DCGM_MEMORY_BANDWIDTH_INDEX); if (name != MEMBW_PLUGIN_NAME) { fprintf(stderr, "Expected '%s' to be the name for test index %d, but got '%s'.\n", MEMBW_PLUGIN_NAME, static_cast<int>(DCGM_MEMORY_BANDWIDTH_INDEX), name.c_str()); ret = -1; } return ret; } int TestDiag::TestHelperJsonAddResult() { int ret = 0; Diag d; dcgmDiagResponsePerGpu_v2 gpuResponse = {}; unsigned int testIndex = 0; unsigned int gpuIndex = 0; Json::Value testEntry; size_t i = 0; gpuResponse.results[testIndex].status = DCGM_DIAG_RESULT_NOT_RUN; if (d.HelperJsonAddResult(gpuResponse, testEntry, gpuIndex, testIndex, i) == true) { fprintf(stderr, "Expected a false return for adding a result for an empty test, but got true.\n"); ret = -1; } if (testEntry[NVVS_RESULTS].empty() == false) { fprintf(stderr, "Should not have added a result that didn't run, but we did.\n"); ret = -1; } gpuResponse.results[testIndex].status = DCGM_DIAG_RESULT_PASS; if (d.HelperJsonAddResult(gpuResponse, testEntry, gpuIndex, testIndex, i) == false) { fprintf(stderr, "Expected a true return for adding a result for a passing test, but got false.\n"); ret = -1; } if (testEntry[NVVS_RESULTS].empty() == true) { fprintf(stderr, "Should have added a result for a passing test, but we didn't.\n"); ret = -1; } i++; gpuResponse.results[testIndex].status = DCGM_DIAG_RESULT_FAIL; std::string warning("Stormlight usage of 100 broams exceeded expected usage of 80 broams.\n"); std::string info("Stormlight was used at a rate of 10 broams / second."); snprintf( gpuResponse.results[testIndex].error.msg, sizeof(gpuResponse.results[testIndex].error.msg), warning.c_str()); snprintf(gpuResponse.results[testIndex].info, sizeof(gpuResponse.results[testIndex].info), info.c_str()); if (d.HelperJsonAddResult(gpuResponse, testEntry, gpuIndex, testIndex, i) == false) { fprintf(stderr, "Expected a true return for adding a result for a failing test, but got false.\n"); ret = -1; } if (testEntry[NVVS_RESULTS][1].empty() == true) { fprintf(stderr, "Should have added a result for a failing test, but we didn't.\n"); ret = -1; } else { Json::Value &result = testEntry[NVVS_RESULTS][1]; if (result[NVVS_GPU_IDS].asString() != "0") { fprintf(stderr, "Gpu id should have been '0' but was '%s'.\n", result[NVVS_GPU_IDS].asString().c_str()); ret = -1; } if (result[NVVS_STATUS].asString() != "Fail") { fprintf(stderr, "Expected a status of 'Fail' but was '%s'.\n", result[NVVS_STATUS].asString().c_str()); ret = -1; } if (result[NVVS_WARNINGS].asString() != warning) { fprintf(stderr, "Expected warning to be '%s' but was '%s'.\n", warning.c_str(), result[NVVS_WARNINGS].asString().c_str()); ret = -1; } if (result[NVVS_INFO].asString() != info) { fprintf( stderr, "Expected info to be '%s' but was '%s'.\n", info.c_str(), result[NVVS_INFO].asString().c_str()); ret = -1; } } return ret; } int TestDiag::TestHelperJsonAddBasicTests() { int ret = 0; Diag d; dcgmDiagResponse_t r = {}; Json::Value output; int categoryIndex = 0; r.levelOneTestCount = DCGM_SWTEST_COUNT; for (int i = 0; i < DCGM_SWTEST_COUNT; i++) r.levelOneResults[i].status = DCGM_DIAG_RESULT_PASS; d.HelperJsonAddBasicTests(output, categoryIndex, r); if (output[NVVS_NAME].empty() == true) { fprintf(stderr, "Failed to create the DCGM Diagnostic entry.\n"); return -1; } Json::Value &diag = output[NVVS_NAME]; if (diag[NVVS_HEADERS].empty() == true || diag[NVVS_HEADERS].isArray() == false) { fprintf(stderr, "Failed to create the category array.\n"); return -1; } Json::Value &category = diag[NVVS_HEADERS][0]; if (category[NVVS_HEADER].asString() != "Deployment") { fprintf( stderr, "Category name should be 'Deployment' but is '%s'.\n", category[NVVS_HEADER].asString().c_str()); ret = -1; } if (category[NVVS_TESTS].empty() == true || category[NVVS_TESTS].isArray() == false) { fprintf(stderr, "Failed to create the test array.\n"); return -1; } Json::Value &tests = category[NVVS_TESTS]; if (tests.size() < 10) { fprintf(stderr, "There should be 10 tests in the Deployment category, but there weren't.\n"); ret = -1; } return ret; } int TestDiag::TestHelperJsonTestEntry(Json::Value &testEntry, int gpuIndex, const std::string &status, const std::string &warning) { Json::Value &results = testEntry[NVVS_RESULTS]; if (results.empty() || results.isArray() == false || static_cast<int>(results.size()) <= gpuIndex) { fprintf(stderr, "Test entry json isn't formatted as expected.\n"); return -1; } Json::Value &result = results[gpuIndex]; if (result[NVVS_STATUS].empty() == true) { fprintf(stderr, "Result entry had no status populated.\n"); return -1; } if (result[NVVS_STATUS].asString() != status) { fprintf(stderr, "Test entry had expected status '%s' but found '%s'.\n", status.c_str(), result[NVVS_STATUS].asString().c_str()); return -1; } if (warning.size() > 0 && result[NVVS_WARNINGS].asString() != warning) { fprintf(stderr, "Test entry had expected warning '%s' but found '%s'.\n", warning.c_str(), results[NVVS_WARNINGS].asString().c_str()); return -1; } return 0; } int TestDiag::TestHelperJsonBuildOutput() { int ret = 0; Diag d; dcgmDiagResponse_t r = {}; Json::Value output; std::vector<unsigned int> gpuIndices; const char *warnings[] = { "Voidspren are dangerous.", "Vorin herecy isn't meaningful.", "Hoid is only watching out for Hoid.", "The Unmade can't be held forever.", "The Heralds probably aren't mentally stable.", "Taravangian makes Sadaes look innocent.", "Amaram is a jerk." }; for (int i = 0; i < DCGM_SWTEST_COUNT; i++) r.levelOneResults[i].status = DCGM_DIAG_RESULT_PASS; gpuIndices.push_back(0); gpuIndices.push_back(1); for (int i = 0; i < DCGM_MAX_NUM_DEVICES; i++) { if (i == 0) { for (int j = 0; j < DCGM_PER_GPU_TEST_COUNT; j++) { r.perGpuResponses[i].results[j].status = DCGM_DIAG_RESULT_PASS; } } else if (i == 1) { for (int j = 0; j < DCGM_PER_GPU_TEST_COUNT; j++) { r.perGpuResponses[i].results[j].status = DCGM_DIAG_RESULT_FAIL; snprintf(r.perGpuResponses[i].results[j].error.msg, sizeof(r.perGpuResponses[i].results[j].error.msg), "%s", warnings[j]); } } else { for (int j = 0; j < DCGM_PER_GPU_TEST_COUNT; j++) { r.perGpuResponses[i].results[j].status = DCGM_DIAG_RESULT_NOT_RUN; } } } d.HelperJsonBuildOutput(output, r, gpuIndices); if (output[NVVS_NAME].empty() == true || output[NVVS_NAME][NVVS_HEADERS].empty() == true || output[NVVS_NAME][NVVS_HEADERS].isArray() == false) { fprintf(stderr, "Json isn't structured correctly.\n"); return -1; } Json::Value &headers = output[NVVS_NAME][NVVS_HEADERS]; if (headers.size() != 4) { fprintf(stderr, "Didn't get 4 headers like expected.\n"); return -1; } Json::Value &integration = headers[1]; Json::Value &hardware = headers[2]; Json::Value &stress = headers[3]; if (integration[NVVS_TESTS].empty() == true || integration[NVVS_TESTS].isArray() == false || hardware[NVVS_TESTS].empty() == true || hardware[NVVS_TESTS].isArray() == false || stress[NVVS_TESTS].empty() == true || stress[NVVS_TESTS].isArray() == false) { fprintf(stderr, "Plugin categories should have arrays of tests, but don't.\n"); return -1; } if (TestHelperJsonTestEntry(integration[NVVS_TESTS][0], 0, "Pass", "")) { fprintf(stderr, "Failure with PCIe gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(integration[NVVS_TESTS][0], 1, "Fail", warnings[DCGM_PCI_INDEX])) { fprintf(stderr, "Failure with PCIe gpu 1.\n"); ret = -1; } if (TestHelperJsonTestEntry(hardware[NVVS_TESTS][0], 0, "Pass", "")) { fprintf(stderr, "Failure with GPU Memory gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(hardware[NVVS_TESTS][0], 1, "Fail", warnings[DCGM_MEMORY_INDEX])) { fprintf(stderr, "Failure with GPU Memory gpu 1.\n"); ret = -1; } if (TestHelperJsonTestEntry(hardware[NVVS_TESTS][1], 0, "Pass", "")) { fprintf(stderr, "Failure with Diagnostic gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(hardware[NVVS_TESTS][1], 1, "Fail", warnings[DCGM_DIAGNOSTIC_INDEX])) { fprintf(stderr, "Failure with Diagnostic gpu 1.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][0], 0, "Pass", "")) { fprintf(stderr, "Failure with SM Stress gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][0], 1, "Fail", warnings[DCGM_SM_STRESS_INDEX])) { fprintf(stderr, "Failure with SM Stress gpu 1.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][1], 0, "Pass", "")) { fprintf(stderr, "Failure with Targeted Stress gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][1], 1, "Fail", warnings[DCGM_TARGETED_STRESS_INDEX])) { fprintf(stderr, "Failure with Targeted Stress gpu 1.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][2], 0, "Pass", "")) { fprintf(stderr, "Failure with Targeted Power gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][2], 1, "Fail", warnings[DCGM_TARGETED_POWER_INDEX])) { fprintf(stderr, "Failure with Targeted Power gpu 1.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][3], 0, "Pass", "")) { fprintf(stderr, "Failure with Memory Bandwidth gpu 0.\n"); ret = -1; } if (TestHelperJsonTestEntry(stress[NVVS_TESTS][3], 1, "Fail", warnings[DCGM_MEMORY_BANDWIDTH_INDEX])) { fprintf(stderr, "Failure with Memory Bandwidth gpu 1.\n"); ret = -1; } return ret; }
30.781011
120
0.57791
deepio
a9e78ea74bc4acba6164bd009514a281a592a07b
1,149
cpp
C++
src/_leetcode/leet_989.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_989.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_989.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
/* * ====================== leet_989.cpp ========================== * -- tpr -- * CREATE -- 2020.05.27 * MODIFY -- * ---------------------------------------------------------- * 989. 数组形式的整数加法 */ #include "innLeet.h" #include "TreeNode1.h" namespace leet_989 {//~ std::vector<int> addToArrayForm( std::vector<int>& A, int K ){ int Na = static_cast<int>(A.size()); std::deque<int> que {}; int carry = 0; for( int a=Na-1; a>=0 || K>0; a--, K=K/10 ){ int va = (a>=0) ? A.at(a) : 0; int vk = K%10; int tmp = va + vk + carry; carry = tmp/10; que.push_front( tmp%10 ); } if( carry>0 ){ que.push_front(1); } return std::vector<int>(que.begin(), que.end()); } //=========================================================// void main_(){ std::vector<int> a { 1,2,3,4,5 }; auto ret = addToArrayForm( a, 0 ); cout <<"ret:"<<endl; for( int i : ret ){ cout <<i<<", "; } cout << endl; debug::log( "\n~~~~ leet: 989 :end ~~~~\n" ); } }//~
20.890909
65
0.369887
turesnake
a9e9f922330e0e1e94d484150355aba412b97d56
60
cpp
C++
libconfig/Config.cpp
qiu708/libconfig
24e79f923c96a5210a1dc5603000d90b56b13318
[ "MIT" ]
null
null
null
libconfig/Config.cpp
qiu708/libconfig
24e79f923c96a5210a1dc5603000d90b56b13318
[ "MIT" ]
null
null
null
libconfig/Config.cpp
qiu708/libconfig
24e79f923c96a5210a1dc5603000d90b56b13318
[ "MIT" ]
null
null
null
// // Created by qiu on 2021/12/20. // #include "Config.h"
10
32
0.6
qiu708
a9eb9702fdc558d395e6efbad594284a0e382c88
423
cc
C++
c11/day01/4.1for.cc
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
7
2017-07-16T15:09:26.000Z
2021-09-01T02:13:15.000Z
c11/day01/4.1for.cc
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
null
null
null
c11/day01/4.1for.cc
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
3
2017-09-13T09:54:49.000Z
2019-03-18T01:29:15.000Z
#include<iostream> #include<vector> int main() { for ( int i : { 1, 2, 3, 4, 5, 6 } ) { std::cout<< i <<std::endl; } std::vector<int> v { 1, 2, 3, 4, 5, 6 }; for (auto& elem : v ) { //非只读方式 可以修改原来值 //for ( auto elem : v ) { //拷贝成临时变量 即只读的方式即做任何操作都不会改变原来的值 elem *= 3; } //for (auto elem : v) { //效率低 for (const auto& elem : v ) { // 为什么是const ref 防止调拷贝构造和析构 std::cout<<elem<<" "; } return 0; }
19.227273
61
0.527187
hankai17
a9f538cd9584ce5af910730b2aa11d007ed6dbf8
11,104
cpp
C++
app/hpocommand.cpp
pnrobinson/phenopacketpp
f710b408d86f94b7a0c6c734a1a65890226bc7b6
[ "MIT" ]
1
2019-06-14T17:46:17.000Z
2019-06-14T17:46:17.000Z
app/hpocommand.cpp
pnrobinson/phenopacketpp
f710b408d86f94b7a0c6c734a1a65890226bc7b6
[ "MIT" ]
20
2019-06-18T10:24:20.000Z
2019-11-03T15:35:30.000Z
app/hpocommand.cpp
pnrobinson/phenotools
f710b408d86f94b7a0c6c734a1a65890226bc7b6
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <optional> #include <sstream> #include <fstream> #include "hpocommand.h" #include "../lib/jsonobo.h" #include "../lib/property.h" #define EMPTY_STRING "" using namespace phenotools; using std::string; using std::cout; using std::cerr; using std::stringstream; using std::make_unique; string stringify_date(tm *t) { stringstream ss; ss << t->tm_year + 1900 << "-" << std::right << std::setfill('0') << std::setw(2) << t->tm_mon + 1 << "-" << std::right << std::setfill('0') << std::setw(2) << t->tm_mday; return ss.str(); } HpoCommand::HpoCommand(const string &hp_json_path, bool descriptive_stats, bool quality_control, const string &date, const string &end_date, const string &termid, bool debug) : HpoCommand(hp_json_path, descriptive_stats,quality_control,date,end_date,termid,debug,EMPTY_STRING) { } HpoCommand::HpoCommand(const string &hp_json_path, bool descriptive_stats, bool quality_control, const string &date, const string &end_date, const string &termid, bool debug, const string &outpath): PhenotoolsCommand(hp_json_path), show_descriptive_stats(descriptive_stats), show_quality_control(quality_control), threshold_date_str(date), end_date_str(end_date), debug_(debug), outpath_(outpath) { if (date.empty()) { // the following is the birthday of the HPO this->start_date_ = make_unique<struct tm>(string_to_time("2008-11-01")); } else { this->start_date_ = make_unique<struct tm>(string_to_time(date)); } if (end_date.empty()) { // this means the user did not pass an end date. We set the end date to 42 days after today to include everything // up to and including the present time // current date/time based on current system time_t now = time(0); tm *gmtm = gmtime(&now); this->end_date_ = make_unique<struct tm>(*gmtm); } else { this->end_date_ = make_unique<struct tm>(string_to_time(end_date)); } if (! termid.empty()) { this->tid_ = make_unique<TermId>(TermId::from_string(termid)); } } HpoCommand::HpoCommand(const string &hp_json_path, const string &hpo_term_file, const string &outpath): hpo_termfile_(hpo_term_file), outpath_(outpath), do_term_annotation_(true) { JsonOboParser parser{hp_json_path}; error_list_ = parser.get_errors(); this->ontology_ = parser.get_ontology(); if (! error_list_.empty()) { for (string s : error_list_) { cerr << "[ERROR] " << s << "\n"; } } } void HpoCommand::annotate_termfile() const { std::ifstream file(hpo_termfile_); if (! file.good()) { cerr << "[Could not open " << hpo_termfile_ << " for reading\n"; return; } std::ofstream outfile; outfile.open(outpath_); if (! outfile.good()) { cerr << "[Could not open " << outpath_ << " for writing\n"; return; } string line; while (std::getline(file, line)) { TermId tid = TermId::from_string(line); if (tid.get_value() == "0000118") { // root term, skip continue; } std::optional<Term> term = ontology_->get_term(tid); if (! term) { cerr << "[WARNING] Could not retrieve term for " << tid << "\n"; } else if (term->obsolete()){ continue; } if (term->is_alternative_id(tid)) { continue; } std::set<TermId> ancestors = ontology_->get_ancestors(tid); bool found = false; for (TermId t : ancestors) { auto p = std::find (toplevelCatories_.begin(), toplevelCatories_.end(), t); if (p != toplevelCatories_.end()) { outfile << tid << "\t" << *p << "\n"; found = true; break; } } if (! found) { cout << "[WARN] Not placed in category: " << term->get_label() <<": " << tid << "\n"; } } } void HpoCommand::output_terms_by_category() const { vector<TermId> termids = ontology_->get_current_term_ids(); std::ofstream outfile; unsigned int valid_term_count = 0; outfile.open(outpath_); if (! outfile.good()) { cerr << "[Could not open " << outpath_ << " for writing\n"; return; } for (TermId tid : termids) { std::optional<Term> term = ontology_->get_term(tid); if (! term) { cerr << "[WARNING] Could not retrieve term for " << tid << "\n"; } else if (term->obsolete()){ continue; } valid_term_count++; std::set<TermId> ancestors = ontology_->get_ancestors(tid); bool found = false; for (TermId t : ancestors) { auto p = std::find (toplevelCatories_.begin(), toplevelCatories_.end(), t); if (p != toplevelCatories_.end()) { outfile << tid << "\t" << *p << "\n"; found = true; break; } } if (! found) { cout << "[WARN] Not placed in category: " << term->get_label() <<": " << tid << "\n"; } } cout << "[INFO] Number of valid terms: " << valid_term_count << "\n"; } int HpoCommand::execute() { if (do_term_annotation_) { init_toplevel_categories(); if (hpo_termfile_.empty()) { output_terms_by_category(); } else { annotate_termfile(); } return EXIT_SUCCESS; } if (show_quality_control) { show_qc(); } if (show_descriptive_stats) { show_stats(); } if (debug_) { ontology_->debug_print(); } if (tid_) { if (outpath_.empty()) { output_descendants(std::cout); } else { std::ofstream fout; fout.open(outpath_.c_str(), std::ios::out); if (!fout) { cerr << "error: open file for output failed!\n"; abort(); // in <cstdlib> header } output_descendants(fout); fout.close(); } } return EXIT_SUCCESS; } void HpoCommand::show_qc() { if (error_list_.size() == 0) { cout <<"[INFO] No errors enounted in JSON parse\n"; return; } cout << "[ERRORS]:\n"; for (string e : error_list_) { cout << e << "\n"; } cout << "\n"; } void HpoCommand::show_stats() { ontology_->output_descriptive_statistics(); } void HpoCommand::output_descendants(std::ostream & ost) { vector<TermId> descs = this->ontology_->get_descendant_term_ids(*tid_); std::optional<Term> term = this->ontology_->get_term(*tid_); if (! term) { cerr << "[ERROR] Could not find term for " << *tid_ << "\n"; return; } string label = term->get_label(); int N = descs.size(); int total = 0; int total_newer = 0; ost << "#Subontology: " << *tid_ << " (" << label << ")\n"; // Now print the header ost << "#hpo.id\thpo.label\tcreation.date\tincluded\n"; for (TermId tid : descs) { total++; std::optional<Term> termopt = this->ontology_->get_term(tid); if (! termopt) { cerr << "[ERROR] Could not find term for " << tid << "\n"; continue; } label = termopt->get_label(); tm creation_date = termopt->get_creation_date(); stringstream ss; ss << creation_date.tm_year + 1900 << "-" << creation_date.tm_mon + 1 << "-" << creation_date.tm_mday; bool passes_threshold = in_time_window(creation_date); ost << tid << "\t" << label << "\t" << ss.str() << "\t" << (passes_threshold ? "T" : "F") << "\n"; if (passes_threshold) { total_newer++; } ost << "#Created after " << threshold_date_str << ": " << total_newer << "\n"; ost << "#Total: " << total << "\n"; } } void HpoCommand::count_descendants() { int total = 0; int total_newer = 0; vector<TermId> descs = this->ontology_->get_descendant_term_ids(*tid_); if (start_date_) { for (TermId tid : descs) { total++; std::optional<Term> termopt = this->ontology_->get_term(tid); if (! termopt) { cerr << "[ERROR] Could not find term for " << tid << "\n"; return; } else { cout << tid << ": " << termopt->get_label() << "\n"; } tm creation_date = termopt->get_creation_date(); if (in_time_window(creation_date)) { cout << tid << " was created before: " << (1900 + creation_date.tm_year) << "\n"; } else { cout << tid << " was created after: " << (1900 + creation_date.tm_year) << "\n"; total_newer++; } } cout << " We found " << total << " descendants of " << *tid_ << " including " << total_newer << " new terms\n"; } else { int N = descs.size(); cout << "Term " << *tid_ << " has " << N << " descendants.\n"; } } /** * This function checks whether a date is within the two trheshold dates * A typical use case is to ask whether a term was created between 2015 and 2018. */ bool HpoCommand::in_time_window(tm time) const { if (time.tm_year == start_date_->tm_year) { if (time.tm_mon < start_date_->tm_mon) { return false; } else if (time.tm_mon == start_date_->tm_mon && time.tm_mday < start_date_->tm_mday) { return false; } // if we get here, the years are the same and the month day are not earlier. // so far, ,so good } else if (time.tm_year < start_date_->tm_year) { return false; } // if we get here, that time is equal to or later than start_date_ if (time.tm_year == end_date_->tm_year) { if (time.tm_mon > end_date_->tm_mon) { return false; } else if (time.tm_mon == end_date_->tm_mon && time.tm_mday > end_date_->tm_mday) { return false; } } else if (time.tm_year > end_date_->tm_year) { return false; } return true; } void HpoCommand::print_category(const string &path, const string &outpath) const { std::ifstream file(path); std::string line; while (std::getline(file, line)) { cout << line; } }
29.068063
130
0.521524
pnrobinson
a9f867f9cc8f26e44f516e481f2f1cf203fac7a4
2,915
cpp
C++
WorkScript/Type/FloatType.cpp
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
3
2018-07-23T10:59:00.000Z
2019-04-05T04:57:19.000Z
WorkScript/Type/FloatType.cpp
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
null
null
null
WorkScript/Type/FloatType.cpp
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
1
2019-06-28T05:57:47.000Z
2019-06-28T05:57:47.000Z
#include "Type.h" #include "Function.h" #include "Module.h" #include "Utils.h" #include "FloatType.h" #include "Exception.h" using namespace std; using namespace WorkScript; std::unordered_map<std::wstring, FloatType*> FloatType::types; Finalizer FloatType::staticFinalizer(&FloatType::releaseTypes); FloatType::FloatType(FloatTypeClassification cls, bool isConst, bool isVolatile) noexcept :classification(cls), _const(isConst),_volatile(isVolatile) { } std::wstring WorkScript::FloatType::getName() const noexcept { wstring str; if(this->_const) str += L"const "; if(this->_volatile) str += L"volatile "; switch(this->classification){ case FloatTypeClassification::FLOAT: str += L"float"; break; case FloatTypeClassification::DOUBLE: str += L"double"; break; // case FloatTypeClassification::LONG_DOUBLE: // str += L"long double"; // break; } return str; } std::wstring WorkScript::FloatType::getMangledName() const noexcept { return FloatType::getMangledName(this->classification, this->_const, this->_volatile); } std::wstring FloatType::getMangledName(FloatTypeClassification cls, bool isConst, bool isVolatile) noexcept{ wstring name; if(isConst) name += L"K"; switch(cls){ case FloatTypeClassification::FLOAT: name += L"f"; break; case FloatTypeClassification::DOUBLE: name += L"d"; break; // case FloatTypeClassification::LONG_DOUBLE: // name += L"e"; // break; } return name; } TypeClassification WorkScript::FloatType::getClassification() const noexcept { return TypeClassification::FLOAT; } llvm::Type * WorkScript::FloatType::getLLVMType(GenerateContext *context) const { llvm::LLVMContext &ctx = *context->getLLVMContext(); auto len = this->getLength(); switch (len) { case 32: return llvm::Type::getFloatTy(ctx); case 64: return llvm::Type::getDoubleTy(ctx); default: throw InternalException(L"不支持的浮点类型长度:" + to_wstring(len)); } } bool WorkScript::FloatType::equals(const Type * type) const noexcept { if (type->getClassification() != TypeClassification::FLOAT)return false; auto *target = (const FloatType*)type; if (this->classification != target->classification)return false; return true; } void WorkScript::FloatType::releaseTypes() noexcept { for (auto it : types) { delete it.second; } } FloatType * WorkScript::FloatType::get(FloatTypeClassification cls, bool isConst, bool isVolatile) noexcept { wstring idStr = FloatType::getMangledName(cls, isConst, isVolatile); auto it = types.find(idStr); if (it != types.end()) return it->second; else return (types[idStr] = new FloatType(cls, isConst, isVolatile)); } unsigned FloatType::getLength() const noexcept { switch(this->classification) { case FloatTypeClassification::FLOAT: return 32; case FloatTypeClassification::DOUBLE: return 64; // case FloatTypeClassification::LONG_DOUBLE: // return 80; default: return 0; } }
25.347826
108
0.726244
jingjiajie
a9fa3855607f9553d22d6f2d658479e71e61d5ea
26,353
cpp
C++
src/hotspot/share/ci/ciInstanceKlass.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/ci/ciInstanceKlass.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/ci/ciInstanceKlass.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "ci/ciField.hpp" #include "ci/ciInstance.hpp" #include "ci/ciInstanceKlass.hpp" #include "ci/ciUtilities.inline.hpp" #include "classfile/javaClasses.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmClasses.hpp" #include "memory/allocation.hpp" #include "memory/allocation.inline.hpp" #include "memory/resourceArea.hpp" #include "oops/instanceKlass.inline.hpp" #include "oops/klass.inline.hpp" #include "oops/oop.inline.hpp" #include "oops/fieldStreams.inline.hpp" #include "runtime/fieldDescriptor.inline.hpp" #include "runtime/handles.inline.hpp" #include "runtime/jniHandles.inline.hpp" // ciInstanceKlass // // This class represents a Klass* in the HotSpot virtual machine // whose Klass part in an InstanceKlass. // ------------------------------------------------------------------ // ciInstanceKlass::ciInstanceKlass // // Loaded instance klass. ciInstanceKlass::ciInstanceKlass(Klass* k) : ciKlass(k) { assert(get_Klass()->is_instance_klass(), "wrong type"); assert(get_instanceKlass()->is_loaded(), "must be at least loaded"); InstanceKlass* ik = get_instanceKlass(); AccessFlags access_flags = ik->access_flags(); _flags = ciFlags(access_flags); _has_finalizer = access_flags.has_finalizer(); _has_subklass = flags().is_final() ? subklass_false : subklass_unknown; _init_state = ik->init_state(); _nonstatic_field_size = ik->nonstatic_field_size(); _has_nonstatic_fields = ik->has_nonstatic_fields(); _has_nonstatic_concrete_methods = ik->has_nonstatic_concrete_methods(); _is_hidden = ik->is_hidden(); _is_record = ik->is_record(); _nonstatic_fields = NULL; // initialized lazily by compute_nonstatic_fields: _has_injected_fields = -1; _implementor = NULL; // we will fill these lazily // Ensure that the metadata wrapped by the ciMetadata is kept alive by GC. // This is primarily useful for metadata which is considered as weak roots // by the GC but need to be strong roots if reachable from a current compilation. // InstanceKlass are created for both weak and strong metadata. Ensuring this metadata // alive covers the cases where there are weak roots without performance cost. oop holder = ik->klass_holder(); if (ik->class_loader_data()->has_class_mirror_holder()) { // Though ciInstanceKlass records class loader oop, it's not enough to keep // non-strong hidden classes alive (loader == NULL). Klass holder should // be used instead. It is enough to record a ciObject, since cached elements are never removed // during ciObjectFactory lifetime. ciObjectFactory itself is created for // every compilation and lives for the whole duration of the compilation. assert(holder != NULL, "holder of hidden class is the mirror which is never null"); (void)CURRENT_ENV->get_object(holder); } Thread *thread = Thread::current(); if (ciObjectFactory::is_initialized()) { _loader = JNIHandles::make_local(thread, ik->class_loader()); _protection_domain = JNIHandles::make_local(thread, ik->protection_domain()); _is_shared = false; } else { Handle h_loader(thread, ik->class_loader()); Handle h_protection_domain(thread, ik->protection_domain()); _loader = JNIHandles::make_global(h_loader); _protection_domain = JNIHandles::make_global(h_protection_domain); _is_shared = true; } // Lazy fields get filled in only upon request. _super = NULL; _java_mirror = NULL; if (is_shared()) { if (k != vmClasses::Object_klass()) { super(); } //compute_nonstatic_fields(); // done outside of constructor } _field_cache = NULL; } // Version for unloaded classes: ciInstanceKlass::ciInstanceKlass(ciSymbol* name, jobject loader, jobject protection_domain) : ciKlass(name, T_OBJECT) { assert(name->char_at(0) != JVM_SIGNATURE_ARRAY, "not an instance klass"); _init_state = (InstanceKlass::ClassState)0; _nonstatic_field_size = -1; _has_nonstatic_fields = false; _nonstatic_fields = NULL; _has_injected_fields = -1; _is_hidden = false; _is_record = false; _loader = loader; _protection_domain = protection_domain; _is_shared = false; _super = NULL; _java_mirror = NULL; _field_cache = NULL; } // ------------------------------------------------------------------ // ciInstanceKlass::compute_shared_is_initialized void ciInstanceKlass::compute_shared_init_state() { GUARDED_VM_ENTRY( InstanceKlass* ik = get_instanceKlass(); _init_state = ik->init_state(); ) } // ------------------------------------------------------------------ // ciInstanceKlass::compute_shared_has_subklass bool ciInstanceKlass::compute_shared_has_subklass() { GUARDED_VM_ENTRY( InstanceKlass* ik = get_instanceKlass(); _has_subklass = ik->subklass() != NULL ? subklass_true : subklass_false; return _has_subklass == subklass_true; ) } // ------------------------------------------------------------------ // ciInstanceKlass::loader oop ciInstanceKlass::loader() { ASSERT_IN_VM; return JNIHandles::resolve(_loader); } // ------------------------------------------------------------------ // ciInstanceKlass::loader_handle jobject ciInstanceKlass::loader_handle() { return _loader; } // ------------------------------------------------------------------ // ciInstanceKlass::protection_domain oop ciInstanceKlass::protection_domain() { ASSERT_IN_VM; return JNIHandles::resolve(_protection_domain); } // ------------------------------------------------------------------ // ciInstanceKlass::protection_domain_handle jobject ciInstanceKlass::protection_domain_handle() { return _protection_domain; } // ------------------------------------------------------------------ // ciInstanceKlass::field_cache // // Get the field cache associated with this klass. ciConstantPoolCache* ciInstanceKlass::field_cache() { if (is_shared()) { return NULL; } if (_field_cache == NULL) { assert(!is_java_lang_Object(), "Object has no fields"); Arena* arena = CURRENT_ENV->arena(); _field_cache = new (arena) ciConstantPoolCache(arena, 5); } return _field_cache; } // ------------------------------------------------------------------ // ciInstanceKlass::get_canonical_holder // ciInstanceKlass* ciInstanceKlass::get_canonical_holder(int offset) { #ifdef ASSERT if (!(offset >= 0 && offset < layout_helper())) { tty->print("*** get_canonical_holder(%d) on ", offset); this->print(); tty->print_cr(" ***"); }; assert(offset >= 0 && offset < layout_helper(), "offset must be tame"); #endif if (offset < instanceOopDesc::base_offset_in_bytes()) { // All header offsets belong properly to java/lang/Object. return CURRENT_ENV->Object_klass(); } ciInstanceKlass* self = this; assert(self->is_loaded(), "must be loaded to access field info"); ciField* field = self->get_field_by_offset(offset, false); if (field != NULL) { return field->holder(); } else { for (;;) { assert(self->is_loaded(), "must be loaded to have size"); ciInstanceKlass* super = self->super(); if (super == NULL || super->nof_nonstatic_fields() == 0) { return self; } else { self = super; // return super->get_canonical_holder(offset) } } } } // ------------------------------------------------------------------ // ciInstanceKlass::is_java_lang_Object // // Is this klass java.lang.Object? bool ciInstanceKlass::is_java_lang_Object() const { return equals(CURRENT_ENV->Object_klass()); } // ------------------------------------------------------------------ // ciInstanceKlass::uses_default_loader bool ciInstanceKlass::uses_default_loader() const { // Note: We do not need to resolve the handle or enter the VM // in order to test null-ness. return _loader == NULL; } // ------------------------------------------------------------------ /** * Return basic type of boxed value for box klass or T_OBJECT if not. */ BasicType ciInstanceKlass::box_klass_type() const { if (uses_default_loader() && is_loaded()) { return vmClasses::box_klass_type(get_Klass()); } else { return T_OBJECT; } } /** * Is this boxing klass? */ bool ciInstanceKlass::is_box_klass() const { return is_java_primitive(box_klass_type()); } /** * Is this boxed value offset? */ bool ciInstanceKlass::is_boxed_value_offset(int offset) const { BasicType bt = box_klass_type(); return is_java_primitive(bt) && (offset == java_lang_boxing_object::value_offset(bt)); } static bool is_klass_initialized(Symbol* klass_name) { VM_ENTRY_MARK; InstanceKlass* ik = SystemDictionary::find_instance_klass(klass_name, Handle(), Handle()); return ik != nullptr && ik->is_initialized(); } bool ciInstanceKlass::is_box_cache_valid() const { BasicType box_type = box_klass_type(); if (box_type != T_OBJECT) { switch(box_type) { case T_INT: return is_klass_initialized(java_lang_Integer_IntegerCache::symbol()); case T_CHAR: return is_klass_initialized(java_lang_Character_CharacterCache::symbol()); case T_SHORT: return is_klass_initialized(java_lang_Short_ShortCache::symbol()); case T_BYTE: return is_klass_initialized(java_lang_Byte_ByteCache::symbol()); case T_LONG: return is_klass_initialized(java_lang_Long_LongCache::symbol()); case T_BOOLEAN: case T_FLOAT: case T_DOUBLE: return true; default:; } } return false; } // ------------------------------------------------------------------ // ciInstanceKlass::is_in_package // // Is this klass in the given package? bool ciInstanceKlass::is_in_package(const char* packagename, int len) { // To avoid class loader mischief, this test always rejects application classes. if (!uses_default_loader()) return false; GUARDED_VM_ENTRY( return is_in_package_impl(packagename, len); ) } bool ciInstanceKlass::is_in_package_impl(const char* packagename, int len) { ASSERT_IN_VM; // If packagename contains trailing '/' exclude it from the // prefix-test since we test for it explicitly. if (packagename[len - 1] == '/') len--; if (!name()->starts_with(packagename, len)) return false; // Test if the class name is something like "java/lang". if ((len + 1) > name()->utf8_length()) return false; // Test for trailing '/' if (name()->char_at(len) != '/') return false; // Make sure it's not actually in a subpackage: if (name()->index_of_at(len+1, "/", 1) >= 0) return false; return true; } // ------------------------------------------------------------------ // ciInstanceKlass::print_impl // // Implementation of the print method. void ciInstanceKlass::print_impl(outputStream* st) { ciKlass::print_impl(st); GUARDED_VM_ENTRY(st->print(" loader=" INTPTR_FORMAT, p2i(loader()));) if (is_loaded()) { st->print(" loaded=true initialized=%s finalized=%s subklass=%s size=%d flags=", bool_to_str(is_initialized()), bool_to_str(has_finalizer()), bool_to_str(has_subklass()), layout_helper()); _flags.print_klass_flags(); if (_super) { st->print(" super="); _super->print_name(); } if (_java_mirror) { st->print(" mirror=PRESENT"); } } else { st->print(" loaded=false"); } } // ------------------------------------------------------------------ // ciInstanceKlass::super // // Get the superklass of this klass. ciInstanceKlass* ciInstanceKlass::super() { assert(is_loaded(), "must be loaded"); if (_super == NULL && !is_java_lang_Object()) { GUARDED_VM_ENTRY( Klass* super_klass = get_instanceKlass()->super(); _super = CURRENT_ENV->get_instance_klass(super_klass); ) } return _super; } // ------------------------------------------------------------------ // ciInstanceKlass::java_mirror // // Get the instance of java.lang.Class corresponding to this klass. // Cache it on this->_java_mirror. ciInstance* ciInstanceKlass::java_mirror() { if (is_shared()) { return ciKlass::java_mirror(); } if (_java_mirror == NULL) { _java_mirror = ciKlass::java_mirror(); } return _java_mirror; } // ------------------------------------------------------------------ // ciInstanceKlass::unique_concrete_subklass ciInstanceKlass* ciInstanceKlass::unique_concrete_subklass() { if (!is_loaded()) return NULL; // No change if class is not loaded if (!is_abstract()) return NULL; // Only applies to abstract classes. if (!has_subklass()) return NULL; // Must have at least one subklass. VM_ENTRY_MARK; InstanceKlass* ik = get_instanceKlass(); Klass* up = ik->up_cast_abstract(); assert(up->is_instance_klass(), "must be InstanceKlass"); if (ik == up) { return NULL; } return CURRENT_THREAD_ENV->get_instance_klass(up); } // ------------------------------------------------------------------ // ciInstanceKlass::has_finalizable_subclass bool ciInstanceKlass::has_finalizable_subclass() { if (!is_loaded()) return true; VM_ENTRY_MARK; return Dependencies::find_finalizable_subclass(get_instanceKlass()) != NULL; } // ------------------------------------------------------------------ // ciInstanceKlass::contains_field_offset bool ciInstanceKlass::contains_field_offset(int offset) { VM_ENTRY_MARK; return get_instanceKlass()->contains_field_offset(offset); } // ------------------------------------------------------------------ // ciInstanceKlass::get_field_by_offset ciField* ciInstanceKlass::get_field_by_offset(int field_offset, bool is_static) { if (!is_static) { for (int i = 0, len = nof_nonstatic_fields(); i < len; i++) { ciField* field = _nonstatic_fields->at(i); int field_off = field->offset_in_bytes(); if (field_off == field_offset) return field; if (field_off > field_offset) break; // could do binary search or check bins, but probably not worth it } return NULL; } VM_ENTRY_MARK; InstanceKlass* k = get_instanceKlass(); fieldDescriptor fd; if (!k->find_field_from_offset(field_offset, is_static, &fd)) { return NULL; } ciField* field = new (CURRENT_THREAD_ENV->arena()) ciField(&fd); return field; } // ------------------------------------------------------------------ // ciInstanceKlass::get_field_by_name ciField* ciInstanceKlass::get_field_by_name(ciSymbol* name, ciSymbol* signature, bool is_static) { VM_ENTRY_MARK; InstanceKlass* k = get_instanceKlass(); fieldDescriptor fd; Klass* def = k->find_field(name->get_symbol(), signature->get_symbol(), is_static, &fd); if (def == NULL) { return NULL; } ciField* field = new (CURRENT_THREAD_ENV->arena()) ciField(&fd); return field; } static int sort_field_by_offset(ciField** a, ciField** b) { return (*a)->offset_in_bytes() - (*b)->offset_in_bytes(); // (no worries about 32-bit overflow...) } // ------------------------------------------------------------------ // ciInstanceKlass::compute_nonstatic_fields int ciInstanceKlass::compute_nonstatic_fields() { assert(is_loaded(), "must be loaded"); if (_nonstatic_fields != NULL) return _nonstatic_fields->length(); if (!has_nonstatic_fields()) { Arena* arena = CURRENT_ENV->arena(); _nonstatic_fields = new (arena) GrowableArray<ciField*>(arena, 0, 0, NULL); return 0; } assert(!is_java_lang_Object(), "bootstrap OK"); // Size in bytes of my fields, including inherited fields. int fsize = nonstatic_field_size() * heapOopSize; ciInstanceKlass* super = this->super(); GrowableArray<ciField*>* super_fields = NULL; if (super != NULL && super->has_nonstatic_fields()) { int super_flen = super->nof_nonstatic_fields(); super_fields = super->_nonstatic_fields; assert(super_flen == 0 || super_fields != NULL, "first get nof_fields"); } GrowableArray<ciField*>* fields = NULL; GUARDED_VM_ENTRY({ fields = compute_nonstatic_fields_impl(super_fields); }); if (fields == NULL) { // This can happen if this class (java.lang.Class) has invisible fields. if (super_fields != NULL) { _nonstatic_fields = super_fields; return super_fields->length(); } else { return 0; } } int flen = fields->length(); // Now sort them by offset, ascending. // (In principle, they could mix with superclass fields.) fields->sort(sort_field_by_offset); _nonstatic_fields = fields; return flen; } GrowableArray<ciField*>* ciInstanceKlass::compute_nonstatic_fields_impl(GrowableArray<ciField*>* super_fields) { ASSERT_IN_VM; Arena* arena = CURRENT_ENV->arena(); int flen = 0; GrowableArray<ciField*>* fields = NULL; InstanceKlass* k = get_instanceKlass(); for (JavaFieldStream fs(k); !fs.done(); fs.next()) { if (fs.access_flags().is_static()) continue; flen += 1; } // allocate the array: if (flen == 0) { return NULL; // return nothing if none are locally declared } if (super_fields != NULL) { flen += super_fields->length(); } fields = new (arena) GrowableArray<ciField*>(arena, flen, 0, NULL); if (super_fields != NULL) { fields->appendAll(super_fields); } for (JavaFieldStream fs(k); !fs.done(); fs.next()) { if (fs.access_flags().is_static()) continue; fieldDescriptor& fd = fs.field_descriptor(); ciField* field = new (arena) ciField(&fd); fields->append(field); } assert(fields->length() == flen, "sanity"); return fields; } bool ciInstanceKlass::compute_injected_fields_helper() { ASSERT_IN_VM; InstanceKlass* k = get_instanceKlass(); for (InternalFieldStream fs(k); !fs.done(); fs.next()) { if (fs.access_flags().is_static()) continue; return true; } return false; } void ciInstanceKlass::compute_injected_fields() { assert(is_loaded(), "must be loaded"); int has_injected_fields = 0; if (super() != NULL && super()->has_injected_fields()) { has_injected_fields = 1; } else { GUARDED_VM_ENTRY({ has_injected_fields = compute_injected_fields_helper() ? 1 : 0; }); } // may be concurrently initialized for shared ciInstanceKlass objects assert(_has_injected_fields == -1 || _has_injected_fields == has_injected_fields, "broken concurrent initialization"); _has_injected_fields = has_injected_fields; } bool ciInstanceKlass::has_object_fields() const { GUARDED_VM_ENTRY( return get_instanceKlass()->nonstatic_oop_map_size() > 0; ); } // ------------------------------------------------------------------ // ciInstanceKlass::find_method // // Find a method in this klass. ciMethod* ciInstanceKlass::find_method(ciSymbol* name, ciSymbol* signature) { VM_ENTRY_MARK; InstanceKlass* k = get_instanceKlass(); Symbol* name_sym = name->get_symbol(); Symbol* sig_sym= signature->get_symbol(); Method* m = k->find_method(name_sym, sig_sym); if (m == NULL) return NULL; return CURRENT_THREAD_ENV->get_method(m); } // ------------------------------------------------------------------ // ciInstanceKlass::is_leaf_type bool ciInstanceKlass::is_leaf_type() { assert(is_loaded(), "must be loaded"); if (is_shared()) { return is_final(); // approximately correct } else { return !has_subklass() && (nof_implementors() == 0); } } // ------------------------------------------------------------------ // ciInstanceKlass::implementor // // Report an implementor of this interface. // Note that there are various races here, since my copy // of _nof_implementors might be out of date with respect // to results returned by InstanceKlass::implementor. // This is OK, since any dependencies we decide to assert // will be checked later under the Compile_lock. ciInstanceKlass* ciInstanceKlass::implementor() { ciInstanceKlass* impl = _implementor; if (impl == NULL) { // Go into the VM to fetch the implementor. { VM_ENTRY_MARK; MutexLocker ml(Compile_lock); Klass* k = get_instanceKlass()->implementor(); if (k != NULL) { if (k == get_instanceKlass()) { // More than one implementors. Use 'this' in this case. impl = this; } else { impl = CURRENT_THREAD_ENV->get_instance_klass(k); } } } // Memoize this result. if (!is_shared()) { _implementor = impl; } } return impl; } // Utility class for printing of the contents of the static fields for // use by compilation replay. It only prints out the information that // could be consumed by the compiler, so for primitive types it prints // out the actual value. For Strings it's the actual string value. // For array types it it's first level array size since that's the // only value which statically unchangeable. For all other reference // types it simply prints out the dynamic type. class StaticFinalFieldPrinter : public FieldClosure { outputStream* _out; const char* _holder; public: StaticFinalFieldPrinter(outputStream* out, const char* holder) : _out(out), _holder(holder) { } void do_field(fieldDescriptor* fd) { if (fd->is_final() && !fd->has_initial_value()) { ResourceMark rm; oop mirror = fd->field_holder()->java_mirror(); _out->print("staticfield %s %s %s ", _holder, fd->name()->as_quoted_ascii(), fd->signature()->as_quoted_ascii()); switch (fd->field_type()) { case T_BYTE: _out->print_cr("%d", mirror->byte_field(fd->offset())); break; case T_BOOLEAN: _out->print_cr("%d", mirror->bool_field(fd->offset())); break; case T_SHORT: _out->print_cr("%d", mirror->short_field(fd->offset())); break; case T_CHAR: _out->print_cr("%d", mirror->char_field(fd->offset())); break; case T_INT: _out->print_cr("%d", mirror->int_field(fd->offset())); break; case T_LONG: _out->print_cr(INT64_FORMAT, (int64_t)(mirror->long_field(fd->offset()))); break; case T_FLOAT: { float f = mirror->float_field(fd->offset()); _out->print_cr("%d", *(int*)&f); break; } case T_DOUBLE: { double d = mirror->double_field(fd->offset()); _out->print_cr(INT64_FORMAT, *(int64_t*)&d); break; } case T_ARRAY: // fall-through case T_OBJECT: { oop value = mirror->obj_field_acquire(fd->offset()); if (value == NULL) { _out->print_cr("null"); } else if (value->is_instance()) { assert(fd->field_type() == T_OBJECT, ""); if (value->is_a(vmClasses::String_klass())) { const char* ascii_value = java_lang_String::as_quoted_ascii(value); _out->print("\"%s\"", (ascii_value != NULL) ? ascii_value : ""); } else { const char* klass_name = value->klass()->name()->as_quoted_ascii(); _out->print_cr("%s", klass_name); } } else if (value->is_array()) { typeArrayOop ta = (typeArrayOop)value; _out->print("%d", ta->length()); if (value->is_objArray()) { objArrayOop oa = (objArrayOop)value; const char* klass_name = value->klass()->name()->as_quoted_ascii(); _out->print(" %s", klass_name); } _out->cr(); } else { ShouldNotReachHere(); } break; } default: ShouldNotReachHere(); } } } }; void ciInstanceKlass::dump_replay_data(outputStream* out) { ResourceMark rm; InstanceKlass* ik = get_instanceKlass(); ConstantPool* cp = ik->constants(); // Try to record related loaded classes Klass* sub = ik->subklass(); while (sub != NULL) { if (sub->is_instance_klass() && !sub->is_hidden()) { out->print_cr("instanceKlass %s", sub->name()->as_quoted_ascii()); } sub = sub->next_sibling(); } // Dump out the state of the constant pool tags. During replay the // tags will be validated for things which shouldn't change and // classes will be resolved if the tags indicate that they were // resolved at compile time. out->print("ciInstanceKlass %s %d %d %d", ik->name()->as_quoted_ascii(), is_linked(), is_initialized(), cp->length()); for (int index = 1; index < cp->length(); index++) { out->print(" %d", cp->tags()->at(index)); } out->cr(); if (is_initialized()) { // Dump out the static final fields in case the compilation relies // on their value for correct replay. StaticFinalFieldPrinter sffp(out, ik->name()->as_quoted_ascii()); ik->do_local_static_fields(&sffp); } } #ifdef ASSERT bool ciInstanceKlass::debug_final_field_at(int offset) { GUARDED_VM_ENTRY( InstanceKlass* ik = get_instanceKlass(); fieldDescriptor fd; if (ik->find_field_from_offset(offset, false, &fd)) { return fd.is_final(); } ); return false; } bool ciInstanceKlass::debug_stable_field_at(int offset) { GUARDED_VM_ENTRY( InstanceKlass* ik = get_instanceKlass(); fieldDescriptor fd; if (ik->find_field_from_offset(offset, false, &fd)) { return fd.is_stable(); } ); return false; } #endif
33.316056
120
0.634235
1690296356
a9fb12b3adb18fd085f45d92ae9eb6fb1bbce2a6
2,820
cpp
C++
src/utilities/QrDefinitions.cpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
1
2022-03-13T14:21:23.000Z
2022-03-13T14:21:23.000Z
src/utilities/QrDefinitions.cpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
null
null
null
src/utilities/QrDefinitions.cpp
jce-caba/gtkQRmm
0a6f46bdbbc30195c2ddf993be43d218dbc2c47a
[ "MIT" ]
null
null
null
#include "QrDefinitions.hpp" using namespace GtkQR; QRDataContainer::QRDataContainer() { correction_level = QRErrorCorrectionLevel ::QR_ERROR_CORRECTION_LEVEL_MEDIUM; isMicro=false; enable_UTF8=true; qrversion_number = QR_NO_VERSION; qrversion = QRVersion::QR_VERSION_NULL; mask = QR_NO_MASK; } QRDataContainer::QRDataContainer(const QRDataContainer &other) { copyparameters(const_cast<QRDataContainer &>(other)); copylist(other); } QRDataContainer::QRDataContainer(QRDataContainer &&other) { unsigned short aux = num_modules; copyparameters(other); std::swap(eci_mode,other.eci_mode); other.num_modules =aux; } QRDataContainer& QRDataContainer::operator=(const QRDataContainer &other) { copyparameters(const_cast<QRDataContainer &>(other)); copylist(other); return *this; } QRDataContainer& QRDataContainer::operator=(QRDataContainer &&other) { unsigned short aux = num_modules; copyparameters(other); std::swap(eci_mode,other.eci_mode); other.num_modules =aux; return *this; } void QRDataContainer::copyparameters(QRDataContainer &other) { enable_UTF8= other.enable_UTF8; isMicro= other.isMicro; isMicro= other.isMicro; correction_level= other.correction_level; qrversion= other.qrversion; qrversion_number= other.qrversion_number; num_modules= other.num_modules; mask= other.mask; num_eci_mode= other.num_eci_mode; data_coding= other.data_coding; error= other.error; warning= other.warning; } void QRDataContainer::copylist(const QRDataContainer &other) { eci_mode.clear(); for (std::list<QREciMode>::const_iterator it=other.eci_mode.begin(); it != other.eci_mode.end(); ++it) eci_mode.push_back (*it); } QRDataContainer::~QRDataContainer() { } QRVersion QRDataContainer::getqrversion() { return qrversion; } short QRDataContainer::getqrversion_number() { return qrversion_number; } unsigned short QRDataContainer::getnum_modules() { return num_modules; } unsigned short QRDataContainer::getnum_mask() { return mask; } QREciMode QRDataContainer::geteci_mode(int position) { QREciMode eci=QREciMode::QR_ECI_MODE_ISO_8859_1; int i=0; bool finded=false; std::list<QREciMode>::const_iterator it=eci_mode.begin(); while(it != eci_mode.end() && !finded) { if(i==position) { eci= *it; finded=true; } else { i++; ++it; } } return eci; } unsigned short QRDataContainer::getnum_eci_mode() { return num_eci_mode; } QRData QRDataContainer::getdata_coding() { return data_coding; } std:: string & QRDataContainer::geterror() { return error; } std:: string & QRDataContainer::getwarning() { return warning; }
20.735294
105
0.697163
jce-caba
a9ff6b9a7748e61e7aefed30a0a8c592e913db79
891
cpp
C++
STACK/Reverse a string using stack.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
STACK/Reverse a string using stack.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
1
2021-03-30T14:00:56.000Z
2021-03-30T14:00:56.000Z
STACK/Reverse a string using stack.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
/* Reverse a string using Stack ---------------------------- Easy Accuracy: 54.33% Submissions: 27645 Points: 2 You are given a string S, the task is to reverse the string using stack. Example 1: Input: S="GeeksforGeeks" Output: skeeGrofskeeG Your Task: You don't need to read input or print anything. Y our task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ length of the string ≤ 100 */ ----- CODE ----- //return the address of the string char* reverse(char *S, int len) { //code here stack<char> ans; for(int i=0;S[i]!='\0';i++) { ans.push(S[i]); } int i=0; while(!ans.empty()) { S[i++]=ans.top(); ans.pop(); } return S; }
21.214286
127
0.590348
snanacha
e7001d3cbe9d9c9a755e7c74634c4bccdd3eef33
726
cpp
C++
arm9/source/lz77.cpp
RocketRobz/RocketVideoPlayer
be4a671078dbad2f4e7224418a8ee21e5b0fca86
[ "MIT" ]
20
2019-05-20T16:40:30.000Z
2022-02-21T09:35:41.000Z
arm9/source/lz77.cpp
RocketRobz/RocketVideoPlayer
be4a671078dbad2f4e7224418a8ee21e5b0fca86
[ "MIT" ]
1
2020-11-21T22:54:23.000Z
2020-11-21T23:21:26.000Z
arm9/source/lz77.cpp
RocketRobz/RocketVideoPlayer
be4a671078dbad2f4e7224418a8ee21e5b0fca86
[ "MIT" ]
2
2019-09-02T02:16:32.000Z
2019-09-06T14:01:52.000Z
#include <nds.h> #include "tonccpy.h" #define __itcm __attribute__((section(".itcm"))) void __itcm lzssDecompress(u8* source, u8* destination) { u32 leng = (source[1] | (source[2] << 8) | (source[3] << 16)); int Offs = 4; int dstoffs = 0; while (true) { u8 header = source[Offs++]; for (int i = 0; i < 8; i++) { if ((header & 0x80) == 0) destination[dstoffs++] = source[Offs++]; else { u8 a = source[Offs++]; u8 b = source[Offs++]; int offs = (((a & 0xF) << 8) | b) + 1; int length = (a >> 4) + 3; for (int j = 0; j < length; j++) { destination[dstoffs] = destination[dstoffs - offs]; dstoffs++; } } if (dstoffs >= (int)leng) return; header <<= 1; } } }
21.352941
69
0.528926
RocketRobz
e7049e1031d9b0d372d672491c1106c643fe3fa4
922
cpp
C++
oskar/settings/test/Test_Int.cpp
happyseayou/OSKAR
3fb995ed39deb6b11da12524e8e30f0ca8f9c39b
[ "BSD-3-Clause" ]
46
2015-12-15T14:24:16.000Z
2022-01-24T16:54:49.000Z
oskar/settings/test/Test_Int.cpp
happyseayou/OSKAR
3fb995ed39deb6b11da12524e8e30f0ca8f9c39b
[ "BSD-3-Clause" ]
37
2016-08-04T17:53:03.000Z
2022-03-10T10:22:01.000Z
oskar/settings/test/Test_Int.cpp
happyseayou/OSKAR
3fb995ed39deb6b11da12524e8e30f0ca8f9c39b
[ "BSD-3-Clause" ]
32
2016-05-09T10:30:11.000Z
2022-01-26T07:55:27.000Z
/* * Copyright (c) 2015-2021, The OSKAR Developers. * See the LICENSE file at the top-level directory of this distribution. */ #include <gtest/gtest.h> #include "settings/oskar_settings_types.h" using namespace oskar; TEST(settings_types, Int) { Int i; ASSERT_TRUE(i.set_default("1")); ASSERT_STREQ("1", i.get_default()); ASSERT_STREQ("1", i.get_value()); ASSERT_TRUE(i.is_default()); ASSERT_TRUE(i.set_value("9")); ASSERT_FALSE(i.is_default()); ASSERT_EQ(9, i.value()); ASSERT_EQ(1, i.default_value()); ASSERT_FALSE(i.set_value("2.111")); ASSERT_FALSE(i.set_value("foo")); // Comparison. { Int i1, i2; ASSERT_TRUE(i1.set_value("1")); ASSERT_TRUE(i2.set_value("1")); ASSERT_TRUE(i1 == i2); ASSERT_FALSE(i2 > i1); ASSERT_TRUE(i2.set_value("2")); ASSERT_FALSE(i1 == i2); ASSERT_TRUE(i2 > i1); } }
24.918919
72
0.617137
happyseayou
e70a6facbf9bd6f8f86c7ebac1a7667ba4081c16
4,377
hpp
C++
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/vecidx.hpp
RemiArnaud/The-Forge
70f5f4b544831ea3a51de2ad4a7f341fb1b971c5
[ "Apache-2.0" ]
29
2019-02-17T08:17:41.000Z
2022-03-06T17:46:55.000Z
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/vecidx.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
1
2019-06-11T08:35:32.000Z
2019-06-11T08:35:32.000Z
Common_3/ThirdParty/OpenSource/ModifiedSonyMath/sse/vecidx.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
6
2019-05-06T07:54:58.000Z
2021-09-29T00:25:11.000Z
/* Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. 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 Sony Computer Entertainment Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef VECTORMATH_SSE_VECIDX_HPP #define VECTORMATH_SSE_VECIDX_HPP namespace Vectormath { namespace SSE { // ======================================================== // VecIdx // ======================================================== // Used in setting elements of Vector3, Vector4, Point3, or Quat // with the subscripting operator []. VECTORMATH_ALIGNED_TYPE_PRE class VecIdx { __m128 & ref; int i; public: inline VecIdx(__m128 & vec, int idx) : ref(vec), i(idx) { } // // implicitly casts to float unless VECTORMATH_NO_SCALAR_CAST defined // in which case, implicitly casts to FloatInVec, and one must call // getAsFloat() to convert to float. // #ifdef VECTORMATH_NO_SCALAR_CAST inline operator FloatInVec() const; inline float getAsFloat() const; #else // !VECTORMATH_NO_SCALAR_CAST inline operator float() const; #endif // VECTORMATH_NO_SCALAR_CAST inline float operator = (float scalar); inline FloatInVec operator = (const FloatInVec & scalar); inline FloatInVec operator = (const VecIdx & scalar); inline FloatInVec operator *= (float scalar); inline FloatInVec operator *= (const FloatInVec & scalar); inline FloatInVec operator /= (float scalar); inline FloatInVec operator /= (const FloatInVec & scalar); inline FloatInVec operator += (float scalar); inline FloatInVec operator += (const FloatInVec & scalar); inline FloatInVec operator -= (float scalar); inline FloatInVec operator -= (const FloatInVec & scalar); } VECTORMATH_ALIGNED_TYPE_POST; //========================================= #ConfettiMathExtensionsStart ================================================ // ======================================================== // IVecIdx // ======================================================== // Used in setting elements of IVector3, IVector4 // with the subscripting operator []. VECTORMATH_ALIGNED_TYPE_PRE class IVecIdx { __m128i & ref; int i; public: inline IVecIdx(__m128i & vec, int idx) : ref(vec), i(idx) {} // // implicitly casts to int unless VECTORMATH_NO_SCALAR_CAST defined // #ifdef VECTORMATH_NO_SCALAR_CAST inline int getAsInt() const; #else // !VECTORMATH_NO_SCALAR_CAST inline operator int() const; #endif // VECTORMATH_NO_SCALAR_CAST inline int operator = (int scalar); inline int operator = (const IVecIdx & scalar); inline int operator *= (int scalar); inline int operator /= (int scalar); inline int operator += (int scalar); inline int operator -= (int scalar); } VECTORMATH_ALIGNED_TYPE_POST; //========================================= #ConfettiMathExtensionsEnd ================================================ } // namespace SSE } // namespace Vectormath #endif // VECTORMATH_SSE_VECIDX_HPP
36.475
121
0.673749
RemiArnaud
e70a72bed0953718953972932757a0c3b10e4592
18,816
cpp
C++
software/motion_estimate/vo_estimate/src/fovision/fovision_simple_odometry.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
92
2016-01-14T21:03:50.000Z
2021-12-01T17:57:46.000Z
software/motion_estimate/vo_estimate/src/fovision/fovision_simple_odometry.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
62
2016-01-16T18:08:14.000Z
2016-03-24T15:16:28.000Z
software/motion_estimate/vo_estimate/src/fovision/fovision_simple_odometry.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
41
2016-01-14T21:26:58.000Z
2022-03-28T03:10:39.000Z
// simple test program: // se-simple-vo -L ~/drc-testing-data/state_est/run1_field_camera_snippet.lcmlog -P drc_robot.cfg -p // Just do VO, not do any imu integration, dont correct for any urdf/cfg offsets // Output motion in x forward, z up frame #include <zlib.h> #include <lcm/lcm-cpp.hpp> #include <bot_param/param_client.h> #include <bot_frames/bot_frames.h> #include <bot_frames_cpp/bot_frames_cpp.hpp> #include <lcmtypes/bot_core.hpp> #include <lcmtypes/multisense.hpp> #include <lcmtypes/microstrain.hpp> #include "drcvision/voconfig.hpp" #include "drcvision/vofeatures.hpp" #include "drcvision/voestimator.hpp" #include "fovision.hpp" #include <pronto_utils/pronto_vis.hpp> // visualize pt clds #include <ConciseArgs> /// For Forward Kinematics from body to head: #include "urdf/model.h" #include "kdl/tree.hpp" #include "kdl_parser/kdl_parser.hpp" #include "forward_kinematics/treefksolverposfull_recursive.hpp" #include <model-client/model-client.hpp> #include <path_util/path_util.h> #include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression #include <opencv/cv.h> // for disparity using namespace std; using namespace cv; // for disparity ops struct CommandLineConfig { std::string camera_config; // which block from the cfg to read int fusion_mode; bool feature_analysis; std::string output_extension; bool output_signal; bool vicon_init; // initializae off of vicon std::string input_channel; bool verbose; std::string in_log_fname; std::string param_file; }; class StereoOdom{ public: StereoOdom(boost::shared_ptr<lcm::LCM> &lcm_recv_, boost::shared_ptr<lcm::LCM> &lcm_pub_, const CommandLineConfig& cl_cfg_); ~StereoOdom(){ free (left_buf_); free(right_buf_); } private: const CommandLineConfig cl_cfg_; int image_size_; // just the resolution of the image uint8_t* left_buf_; uint8_t* right_buf_; mutable std::vector<float> disparity_buf_; // Is mutable necessary? uint8_t* rgb_buf_ ; uint8_t* decompress_disparity_buf_; image_io_utils* imgutils_; int64_t utime_cur_; boost::shared_ptr<lcm::LCM> lcm_recv_; boost::shared_ptr<lcm::LCM> lcm_pub_; BotParam* botparam_; BotFrames* botframes_; bot::frames* botframes_cpp_; voconfig::KmclConfiguration* config; // FoVision* vo_; // VoFeatures* features_; int64_t utime_prev_; uint8_t* left_buf_ref_; // copies of the reference images - probably can be extracted from fovis directly int64_t ref_utime_; Eigen::Isometry3d ref_camera_pose_; // [pose of the camera when the reference frames changed bool changed_ref_frames_; VoEstimator* estimator_; void featureAnalysis(); void updateMotion(int64_t utime); void multisenseHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t* msg); void multisenseLDHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t* msg); void multisenseLRHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t* msg); void viconHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg); bool pose_initialized_; Eigen::Isometry3d world_to_camera_; Eigen::Isometry3d world_to_body_; }; StereoOdom::StereoOdom(boost::shared_ptr<lcm::LCM> &lcm_recv_, boost::shared_ptr<lcm::LCM> &lcm_pub_, const CommandLineConfig& cl_cfg_) : lcm_recv_(lcm_recv_), lcm_pub_(lcm_pub_), cl_cfg_(cl_cfg_), utime_cur_(0), utime_prev_(0), ref_utime_(0), changed_ref_frames_(false) { if (cl_cfg_.param_file.empty()) { std::cout << "Get param from LCM\n"; botparam_ = bot_param_get_global(lcm_recv_->getUnderlyingLCM(), 0); } else { std::cout << "Get param from file\n"; botparam_ = bot_param_new_from_file(cl_cfg_.param_file.c_str()); } if (botparam_ == NULL) { exit(1); } botframes_ = bot_frames_get_global(lcm_recv_->getUnderlyingLCM(), botparam_); botframes_cpp_ = new bot::frames(botframes_); // Read config from file: config = new voconfig::KmclConfiguration(botparam_, cl_cfg_.camera_config); boost::shared_ptr<fovis::StereoCalibration> stereo_calibration_; stereo_calibration_ = boost::shared_ptr<fovis::StereoCalibration>(config->load_stereo_calibration()); image_size_ = stereo_calibration_->getWidth() * stereo_calibration_->getHeight(); left_buf_ = (uint8_t*) malloc(3*image_size_); right_buf_ = (uint8_t*) malloc(3*image_size_); left_buf_ref_ = (uint8_t*) malloc(3*image_size_); // used of feature output rgb_buf_ = (uint8_t*) malloc(10*image_size_ * sizeof(uint8_t)); decompress_disparity_buf_ = (uint8_t*) malloc( 4*image_size_*sizeof(uint8_t)); // arbitary size chosen.. vo_ = new FoVision(lcm_pub_ , stereo_calibration_); features_ = new VoFeatures(lcm_pub_, stereo_calibration_->getWidth(), stereo_calibration_->getHeight() ); estimator_ = new VoEstimator(lcm_pub_ , botframes_, cl_cfg_.output_extension ); lcm_recv_->subscribe( cl_cfg_.input_channel,&StereoOdom::multisenseHandler,this); pose_initialized_ = false; if (!cl_cfg_.vicon_init){ std::cout << "Init internal est using default\n"; // Initialise the nominal camera frame with the head pointing horizontally Eigen::Matrix3d M; M << 0, 0, 1, -1, 0, 0, 0, -1, 0; world_to_camera_ = M * Eigen::Isometry3d::Identity(); world_to_camera_.translation().x() = 0; world_to_camera_.translation().y() = 0; world_to_camera_.translation().z() = 1.65; // nominal head height pose_initialized_ = true; }else{ lcm_recv_->subscribe("VICON_BODY|VICON_FRONTPLATE",&StereoOdom::viconHandler,this); } imgutils_ = new image_io_utils( lcm_pub_->getUnderlyingLCM(), stereo_calibration_->getWidth(), 2*stereo_calibration_->getHeight()); // extra space for stereo tasks cout <<"StereoOdom Constructed\n"; } int counter =0; void StereoOdom::featureAnalysis(){ /// Incremental Feature Output: if (counter%5 == 0 ){ features_->setFeatures(vo_->getMatches(), vo_->getNumMatches() , utime_cur_); features_->setCurrentImage(left_buf_); //features_->setCurrentImages(left_buf_, right_buf_); //features_->setCurrentCameraPose( estimator_->getCameraPose() ); features_->setCurrentCameraPose( world_to_camera_ ); features_->doFeatureProcessing(1); // 1 = send the FEATURES_CUR } /// Reference Feature Output: /////////////////////////////////////////////// // Check we changed reference frame last iteration, if so output the set of matching inliers: if (changed_ref_frames_) { if (ref_utime_ > 0){ // skip the first null image if(vo_->getNumMatches() > 200){ // if less than 50 features - dont bother writing // was: if(featuresA.size() > 50){ // if less than 50 features - dont bother writing cout << "ref frame from " << utime_prev_ << " at " << utime_cur_ << " with " <<vo_->getNumMatches()<<" matches\n"; features_->setFeatures(vo_->getMatches(), vo_->getNumMatches() , ref_utime_); features_->setReferenceImage(left_buf_ref_); features_->setReferenceCameraPose( ref_camera_pose_ ); features_->doFeatureProcessing(0); // 0 = send the FEATURES_REF } } changed_ref_frames_=false; } if (vo_->getChangeReferenceFrames()){ // If we change reference frame, note the change for the next iteration. std::cout << "ref frame from " << ref_utime_ << " to " << utime_cur_ << " " << (utime_cur_-ref_utime_)*1E-6 << "sec\n"; ref_utime_ = utime_cur_; // ref_camera_pose_ = estimator_->getCameraPose(); // publish this pose when the ref_camera_pose_ = world_to_camera_; // publish this pose when the // TODO: only copy gray data if its grey std::copy( left_buf_ , left_buf_ + 3*image_size_ , left_buf_ref_); // Keep the image buffer to write with the features: changed_ref_frames_=true; } counter++; } void StereoOdom::updateMotion(int64_t utime){ // Update the camera position in world frame Eigen::Isometry3d delta_camera; Eigen::MatrixXd delta_camera_cov; fovis::MotionEstimateStatusCode delta_status; vo_->getMotion(delta_camera, delta_camera_cov, delta_status ); vo_->fovis_stats(); world_to_camera_ = world_to_camera_ * delta_camera; // Determine the body position in world frame: Eigen::Isometry3d camera_to_body; int status = botframes_cpp_->get_trans_with_utime( botframes_ , "body", "CAMERA_LEFT" , utime, camera_to_body); Eigen::Isometry3d new_world_to_body = world_to_camera_ * camera_to_body; // Find the resultant delta by comparing the body position estimate with its previous Eigen::Isometry3d delta_body = new_world_to_body * ( world_to_body_.inverse() ); if (cl_cfg_.output_signal ){ estimator_->publishPose(utime, "POSE_CAMERA_LEFT_ALT", world_to_camera_, Eigen::Vector3d::Identity(), Eigen::Vector3d::Identity()); estimator_->publishPose(utime, "POSE_BODY", new_world_to_body, Eigen::Vector3d::Identity(), Eigen::Vector3d::Identity()); } // THIS IS NOT THE CORRECT COVARIANCE - ITS THE COVARIANCE IN THE CAMERA FRAME!!!! vo_->send_delta_translation_msg(delta_body, delta_camera_cov, "VO_DELTA_BODY" ); world_to_body_ = new_world_to_body; /* stringstream ss; ss << "Number of Visual Odometry inliers: " << vo_->getNumInliers(); drc::system_status_t status_msg; status_msg.utime = utime_cur_; status_msg.system = 1;// use enums!! status_msg.importance = 0;// use enums!! status_msg.frequency = 1;// use enums!! status_msg.value = ss.str(); lcm_pub_->publish("SYSTEM_STATUS", &status_msg); */ } /// Added for RGB-to-Gray: int pixel_convert_8u_rgb_to_8u_gray (uint8_t *dest, int dstride, int width, int height, const uint8_t *src, int sstride) { int i, j; for (i=0; i<height; i++) { uint8_t *drow = dest + i * dstride; const uint8_t *srow = src + i * sstride; for (j=0; j<width; j++) { drow[j] = 0.2125 * srow[j*3+0] + 0.7154 * srow[j*3+1] + 0.0721 * srow[j*3+2]; } } return 0; } void StereoOdom::multisenseHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t* msg){ if (!pose_initialized_){ return; } utime_prev_ = utime_cur_; utime_cur_ = msg->utime; // Detect the image stream and process accordingly if ( (msg->image_types[0] == bot_core::images_t::LEFT) && (msg->image_types[1] == bot_core::images_t::RIGHT) ) { multisenseLRHandler(rbuf, channel, msg); vo_->doOdometry(left_buf_,right_buf_, msg->utime); }else if( (msg->image_types[0] == bot_core::images_t::LEFT) && (msg->image_types[1] == bot_core::images_t::DISPARITY_ZIPPED) ) { multisenseLDHandler(rbuf, channel, msg); vo_->doOdometry(left_buf_,disparity_buf_.data(), msg->utime ); }else{ std::cout << "StereoOdom::multisenseHandler | image pairings not understood\n"; return; } updateMotion(msg->utime); if(cl_cfg_.feature_analysis) featureAnalysis(); } void StereoOdom::multisenseLDHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t* msg){ int w = msg->images[0].width; int h = msg->images[0].height; if (msg->images[0].pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB ){ rgb_buf_ = (uint8_t*) msg->images[0].data.data(); }else if (msg->images[0].pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY ){ rgb_buf_ = (uint8_t*) msg->images[0].data.data(); }else if (msg->images[0].pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG ){ jpeg_decompress_8u_rgb ( msg->images[0].data.data(), msg->images[0].size, rgb_buf_, w, h, w* 3); pixel_convert_8u_rgb_to_8u_gray( left_buf_, w, w, h, rgb_buf_, w*3); }else{ std::cout << "StereoOdom image type not understood\n"; exit(-1); } // TODO: support other modes (as in the renderer) if (msg->image_types[1] == bot_core::images_t::DISPARITY_ZIPPED) { unsigned long dlen = w*h*2; uncompress(decompress_disparity_buf_ , &dlen, msg->images[1].data.data(), msg->images[1].size); } else{ std::cout << "StereoOdom depth type not understood\n"; exit(-1); } // Convert Carnegie disparity format into floating point disparity. Store in local buffer Mat disparity_orig_temp = Mat::zeros(h,w,CV_16UC1); // h,w disparity_orig_temp.data = (uchar*) decompress_disparity_buf_; // ... is a simple assignment possible? cv::Mat_<float> disparity_orig(h, w); disparity_orig = disparity_orig_temp; disparity_buf_.resize(h * w); cv::Mat_<float> disparity(h, w, &(disparity_buf_[0])); disparity = disparity_orig / 16.0; return; } void StereoOdom::multisenseLRHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t* msg){ int w = msg->images[0].width; int h = msg->images[0].height; if (msg->images[0].pixelformat != msg->images[1].pixelformat){ std::cout << "Pixel formats not identical, not supported\n"; exit(-1); } switch (msg->images[0].pixelformat) { case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY: memcpy(left_buf_, msg->images[0].data.data() , msg->images[0].size); memcpy(right_buf_, msg->images[1].data.data() , msg->images[1].size); break; case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB: // image came in as raw RGB buffer. convert to grayscale: pixel_convert_8u_rgb_to_8u_gray( left_buf_ , w, w, h, msg->images[0].data.data(), w*3); pixel_convert_8u_rgb_to_8u_gray( right_buf_, w, w, h, msg->images[1].data.data(), w*3); break; case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG: // not sure why but the same setting seem to work for both jpeg compressed color (left) and grey (right): jpeg_decompress_8u_gray(msg->images[0].data.data(), msg->images[0].size, left_buf_, w, h, w); jpeg_decompress_8u_gray(msg->images[1].data.data(), msg->images[1].size, right_buf_, w, h, w); break; default: std::cout << "Unrecognized image format\n"; exit(-1); break; } return; } static inline bot_core::pose_t getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime){ bot_core::pose_t pose_msg; pose_msg.utime = utime; pose_msg.pos[0] = pose.translation().x(); pose_msg.pos[1] = pose.translation().y(); pose_msg.pos[2] = pose.translation().z(); Eigen::Quaterniond r_x(pose.rotation()); pose_msg.orientation[0] = r_x.w(); pose_msg.orientation[1] = r_x.x(); pose_msg.orientation[2] = r_x.y(); pose_msg.orientation[3] = r_x.z(); return pose_msg; } void StereoOdom::viconHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg){ if ( cl_cfg_.vicon_init && !pose_initialized_ ){ std::cout << "Init internal est using Vicon\n"; Eigen::Isometry3d worldvicon_to_frontplate_vicon; worldvicon_to_frontplate_vicon.setIdentity(); worldvicon_to_frontplate_vicon.translation() << msg->trans[0], msg->trans[1] , msg->trans[2]; Eigen::Quaterniond quat = Eigen::Quaterniond(msg->quat[0], msg->quat[1], msg->quat[2], msg->quat[3]); worldvicon_to_frontplate_vicon.rotate(quat); // Apply the body to frontplate transform Eigen::Isometry3d frontplate_vicon_to_body_vicon = botframes_cpp_->get_trans_with_utime(botframes_, "body_vicon" , "frontplate_vicon", msg->utime); Eigen::Isometry3d body_to_camera = botframes_cpp_->get_trans_with_utime(botframes_, "CAMERA_LEFT" , "body", msg->utime); Eigen::Isometry3d worldvicon_to_camera = worldvicon_to_frontplate_vicon* frontplate_vicon_to_body_vicon * body_to_camera; bot_core::pose_t pose_msg = getPoseAsBotPose(worldvicon_to_camera, msg->utime); lcm_pub_->publish("POSE_BODY_ALT", &pose_msg ); world_to_camera_ = worldvicon_to_camera; // prev_vicon_utime_ = msg->utime; pose_initialized_ = TRUE; } } int main(int argc, char **argv){ CommandLineConfig cl_cfg; cl_cfg.camera_config = "CAMERA"; cl_cfg.input_channel = "CAMERA"; cl_cfg.output_signal = FALSE; cl_cfg.feature_analysis = FALSE; cl_cfg.vicon_init = FALSE; cl_cfg.fusion_mode = 0; cl_cfg.output_extension = ""; cl_cfg.in_log_fname = ""; std::string param_file = ""; // actual file cl_cfg.param_file = ""; // full path to file ConciseArgs parser(argc, argv, "fovision-odometry"); parser.add(cl_cfg.camera_config, "c", "camera_config", "Camera Config block to use: CAMERA, stereo, stereo_with_letterbox"); parser.add(cl_cfg.output_signal, "p", "output_signal", "Output POSE_BODY and POSE_BODY_ALT signals"); parser.add(cl_cfg.feature_analysis, "f", "feature_analysis", "Publish Feature Analysis Data"); parser.add(cl_cfg.vicon_init, "g", "vicon_init", "Bootstrap internal estimate using VICON_FRONTPLATE"); parser.add(cl_cfg.fusion_mode, "m", "fusion_mode", "0 none, 1 at init, 2 every second, 3 init from gt, then every second"); parser.add(cl_cfg.input_channel, "i", "input_channel", "input_channel - CAMERA or CAMERA_BLACKENED"); parser.add(cl_cfg.output_extension, "o", "output_extension", "Extension to pose channels (e.g. '_VO' "); parser.add(cl_cfg.in_log_fname, "L", "in_log_fname", "Process this log file"); parser.add(param_file, "P", "param_file", "Pull params from this file instead of LCM"); parser.parse(); cout << cl_cfg.fusion_mode << " is fusion_mode\n"; cout << cl_cfg.camera_config << " is camera_config\n"; cl_cfg.param_file = std::string(getConfigPath()) +'/' + std::string(param_file); if (param_file.empty()) { // get param from lcm cl_cfg.param_file = ""; } // bool running_from_log = !cl_cfg.in_log_fname.empty(); boost::shared_ptr<lcm::LCM> lcm_recv; boost::shared_ptr<lcm::LCM> lcm_pub; if (running_from_log) { printf("running from log file: %s\n", cl_cfg.in_log_fname.c_str()); //std::string lcmurl = "file://" + in_log_fname + "?speed=0"; std::stringstream lcmurl; //lcmurl << "file://" << in_log_fname << "?speed=" << processing_rate << "&start_timestamp=" << begin_timestamp; lcmurl << "file://" << cl_cfg.in_log_fname ; lcm_recv = boost::shared_ptr<lcm::LCM>(new lcm::LCM(lcmurl.str())); if (!lcm_recv->good()) { fprintf(stderr, "Error couldn't load log file %s\n", lcmurl.str().c_str()); exit(1); } } else { lcm_recv = boost::shared_ptr<lcm::LCM>(new lcm::LCM); } lcm_pub = boost::shared_ptr<lcm::LCM>(new lcm::LCM); StereoOdom fo= StereoOdom(lcm_recv, lcm_pub, cl_cfg); while(0 == lcm_recv->handle()); }
38.243902
165
0.69425
liangfok
e70a92fb8b8356ece812a1476295215c9640eb30
6,597
cxx
C++
sw/3rd_party/VTK-7.1.0/Filters/SMP/Testing/Cxx/TestSMPContour.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
4
2019-05-30T01:52:12.000Z
2021-09-29T21:12:13.000Z
sw/3rd_party/VTK-7.1.0/Filters/SMP/Testing/Cxx/TestSMPContour.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
null
null
null
sw/3rd_party/VTK-7.1.0/Filters/SMP/Testing/Cxx/TestSMPContour.cxx
esean/stl_voro_fill
c569a4019ff80afbf85482c7193711ea85a7cafb
[ "MIT" ]
2
2019-08-30T23:36:13.000Z
2019-11-08T16:52:01.000Z
/*========================================================================= Program: Visualization Toolkit Module: TestCutter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkNew.h" #include "vtkRTAnalyticSource.h" #include "vtkPolyData.h" #include "vtkDataSetTriangleFilter.h" #include "vtkSMPContourGrid.h" #include "vtkSMPContourGridManyPieces.h" #include "vtkContourGrid.h" #include "vtkContourFilter.h" #include "vtkUnstructuredGrid.h" #include "vtkTimerLog.h" #include "vtkNonMergingPointLocator.h" #include "vtkSMPTools.h" #include "vtkXMLMultiBlockDataWriter.h" #include "vtkCompositeDataSet.h" #include "vtkCompositeDataIterator.h" #include "vtkElevationFilter.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkPointDataToCellData.h" #include "vtkXMLPolyDataWriter.h" #define WRITE_DEBUG 0 const int EXTENT = 30; int TestSMPContour(int, char *[]) { vtkSMPTools::Initialize(2); vtkNew<vtkTimerLog> tl; vtkNew<vtkRTAnalyticSource> imageSource; #if 1 imageSource->SetWholeExtent(-EXTENT, EXTENT, -EXTENT, EXTENT, -EXTENT, EXTENT); #else imageSource->SetWholeExtent(-EXTENT, EXTENT, -EXTENT, EXTENT, 0, 0); #endif vtkNew<vtkElevationFilter> ev; ev->SetInputConnection(imageSource->GetOutputPort()); ev->SetLowPoint(-EXTENT, -EXTENT, -EXTENT); ev->SetHighPoint(EXTENT, EXTENT, EXTENT); vtkNew<vtkDataSetTriangleFilter> tetraFilter; tetraFilter->SetInputConnection(ev->GetOutputPort()); tl->StartTimer(); vtkNew<vtkPointDataToCellData> p2c; p2c->SetInputConnection(tetraFilter->GetOutputPort()); p2c->Update(); tetraFilter->GetOutput()->GetCellData()->ShallowCopy(p2c->GetOutput()->GetCellData()); tl->StopTimer(); cout << "Data generation time: " << tl->GetElapsedTime() << endl; cout << "Contour grid: " << endl; vtkNew<vtkContourGrid> cg; cg->SetInputData(tetraFilter->GetOutput()); cg->SetInputArrayToProcess(0, 0, 0, 0, "RTData"); cg->SetValue(0, 200); cg->SetValue(1, 220); tl->StartTimer(); cg->Update(); tl->StopTimer(); vtkIdType baseNumCells = cg->GetOutput()->GetNumberOfCells(); cout << "Number of cells: " << cg->GetOutput()->GetNumberOfCells() << endl; cout << "NUmber of points: " << cg->GetOutput()->GetNumberOfPoints() << endl; cout << "Time: " << tl->GetElapsedTime() << endl; cout << "Contour filter: " << endl; vtkNew<vtkContourFilter> cf; cf->SetInputData(tetraFilter->GetOutput()); cf->SetInputArrayToProcess(0, 0, 0, 0, "RTData"); cf->SetValue(0, 200); cf->SetValue(1, 220); tl->StartTimer(); cf->Update(); tl->StopTimer(); cout << "Number of cells: " << cf->GetOutput()->GetNumberOfCells() << endl; cout << "Time: " << tl->GetElapsedTime() << endl; cout << "SMP Contour grid: " << endl; vtkNew<vtkSMPContourGrid> cg2; cg2->SetInputData(tetraFilter->GetOutput()); cg2->SetInputArrayToProcess(0, 0, 0, 0, "RTData"); cg2->SetValue(0, 200); cg2->SetValue(1, 220); tl->StartTimer(); cg2->Update(); tl->StopTimer(); cout << "Time: " << tl->GetElapsedTime() << endl; #if WRITE_DEBUG vtkNew<vtkXMLPolyDataWriter> pdwriter; pdwriter->SetInputData(cg2->GetOutput()); pdwriter->SetFileName("contour.vtp"); //pwriter->SetDataModeToAscii(); pdwriter->Write(); #endif if (cg2->GetOutput()->GetNumberOfCells() != baseNumCells) { cout << "Error in vtkSMPContourGrid (MergePieces = true) output." << endl; cout << "Number of cells does not match expected, " << cg2->GetOutput()->GetNumberOfCells() << " vs. " << baseNumCells << endl; return EXIT_FAILURE; } cout << "SMP Contour grid: " << endl; cg2->MergePiecesOff(); tl->StartTimer(); cg2->Update(); tl->StopTimer(); cout << "Time: " << tl->GetElapsedTime() << endl; vtkIdType numCells = 0; vtkCompositeDataSet* cds = vtkCompositeDataSet::SafeDownCast( cg2->GetOutputDataObject(0)); if (cds) { vtkCompositeDataIterator* iter = cds->NewIterator(); iter->InitTraversal(); while (!iter->IsDoneWithTraversal()) { vtkPolyData* pd = vtkPolyData::SafeDownCast( iter->GetCurrentDataObject()); if (pd) { numCells += pd->GetNumberOfCells(); } iter->GoToNextItem(); } iter->Delete(); } if (numCells != baseNumCells) { cout << "Error in vtkSMPContourGrid (MergePieces = false) output." << endl; cout << "Number of cells does not match expected, " << numCells << " vs. " << baseNumCells << endl; return EXIT_FAILURE; } vtkNew<vtkSMPContourGridManyPieces> cg3; cg3->SetInputData(tetraFilter->GetOutput()); cg3->SetInputArrayToProcess(0, 0, 0, 0, "RTData"); cg3->SetValue(0, 200); cg3->SetValue(1, 220); cout << "SMP Contour grid: " << endl; tl->StartTimer(); cg3->Update(); tl->StopTimer(); cout << "Time: " << tl->GetElapsedTime() << endl; numCells = 0; cds = vtkCompositeDataSet::SafeDownCast( cg2->GetOutputDataObject(0)); if (cds) { vtkCompositeDataIterator* iter = cds->NewIterator(); iter->InitTraversal(); while (!iter->IsDoneWithTraversal()) { vtkPolyData* pd = vtkPolyData::SafeDownCast( iter->GetCurrentDataObject()); if (pd) { numCells += pd->GetNumberOfCells(); } iter->GoToNextItem(); } iter->Delete(); } if (numCells != baseNumCells) { cout << "Error in vtkSMPContourGridManyPieces output." << endl; cout << "Number of cells does not match expected, " << numCells << " vs. " << baseNumCells << endl; return EXIT_FAILURE; } #if WRITE_DEBUG vtkNew<vtkXMLMultiBlockDataWriter> writer; writer->SetInputData(cg2->GetOutputDataObject(0)); writer->SetFileName("contour1.vtm"); writer->SetDataModeToAscii(); writer->Write(); vtkNew<vtkXMLMultiBlockDataWriter> writer2; writer2->SetInputData(cg3->GetOutputDataObject(0)); writer2->SetFileName("contour2.vtm"); writer2->SetDataModeToAscii(); writer2->Write(); #endif return EXIT_SUCCESS; }
29.850679
89
0.636805
esean
e70b9ecabb0cc3dc198982df5a473950788726d5
565
cc
C++
src/cymoca/util.cc
jgoppert/cymoca
45a991f56a397a7fea3429eacad6f33dfbf5a6d4
[ "BSD-3-Clause" ]
6
2018-06-24T17:49:33.000Z
2020-06-13T20:43:20.000Z
src/cymoca/util.cc
jgoppert/cymoca
45a991f56a397a7fea3429eacad6f33dfbf5a6d4
[ "BSD-3-Clause" ]
3
2018-07-01T10:15:00.000Z
2018-07-09T21:35:18.000Z
src/cymoca/util.cc
jgoppert/cymoca
45a991f56a397a7fea3429eacad6f33dfbf5a6d4
[ "BSD-3-Clause" ]
1
2018-07-01T10:10:31.000Z
2018-07-01T10:10:31.000Z
// // Created by jgoppert on 3/23/21. // #include "util.h" #ifdef __GNUG__ #include <cxxabi.h> #include <cstdlib> #include <memory> std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning // enable c++11 by passing the flag -std=c++11 to g++ std::unique_ptr<char, void (*)(void*)> res{ abi::__cxa_demangle(name, NULL, NULL, &status), std::free}; return (status == 0) ? res.get() : name; } #else // does nothing if not g++ std::string demangle(const char* name) { return name; } #endif
22.6
77
0.654867
jgoppert
e70c2ef5786889df55c9b27b07c30810347deedd
9,832
cpp
C++
src/vulkan/VulkanContext.cpp
choiip/fui
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
[ "Zlib" ]
null
null
null
src/vulkan/VulkanContext.cpp
choiip/fui
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
[ "Zlib" ]
null
null
null
src/vulkan/VulkanContext.cpp
choiip/fui
dc54b2d29c423a5b257dd7d812e5d5f52a10ba8a
[ "Zlib" ]
null
null
null
#include "vulkan/VulkanContext.hpp" #include "vku.hpp" #define NANOVG_VULKAN_IMPLEMENTATION #include "nanovg_vk.h" #include "core/Log.hpp" #include "core/MathDef.hpp" #include "core/Status.hpp" namespace fui { struct VulkanContext::Private { std::shared_ptr<vk::UniqueInstance> instance; vk::SurfaceKHR surface; std::shared_ptr<vk::su::SwapChainData> swapchain; vk::PhysicalDevice gpu; vk::UniqueDevice device; vk::UniqueCommandPool commandPool; vk::Queue graphicsQueue; vk::Queue presentQueue; vk::UniqueCommandBuffer commandBuffer; vk::UniqueSemaphore presentComplete; vk::UniqueSemaphore renderComplete; vk::UniqueRenderPass renderPass; std::vector<vk::UniqueFramebuffer> framebuffers; uint32_t currentBuffer; vk::Extent2D frameExtent; std::shared_ptr<vk::su::DepthBufferData> depthBuffer; std::shared_ptr<vk::UniqueDebugReportCallbackEXT> debugCallback; }; VulkanContext::VulkanContext(const std::shared_ptr<vk::UniqueInstance>& instance, const std::shared_ptr<vk::UniqueDebugReportCallbackEXT>& debugReportCallback) { _p.reset(new Private); _p->instance = instance; _p->debugCallback = debugReportCallback; auto gpuResult = instance->get().enumeratePhysicalDevices(); if (!gpuResult.empty()) { _p->gpu = gpuResult[0]; } else { LOGE << "vkEnumeratePhysicalDevices failed "; } auto queueFamilyProperties = _p->gpu.getQueueFamilyProperties(); auto graphicsQueueFamilyIndex = vk::su::findGraphicsQueueFamilyIndex(queueFamilyProperties); constexpr float queuePriorities[] = {0.f}; vk::DeviceQueueCreateInfo deviceQueueCreateInfo(vk::DeviceQueueCreateFlags(), graphicsQueueFamilyIndex, 1, queuePriorities); const char* deviceExtensions[] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; constexpr auto deviceExtensionsCount = sizeof(deviceExtensions) / sizeof(deviceExtensions[0]); vk::PhysicalDeviceFeatures deviceFeatures; deviceFeatures.samplerAnisotropy = true; vk::DeviceCreateInfo deviceCreateInfo(vk::DeviceCreateFlags(), 1, &deviceQueueCreateInfo, 0, nullptr, deviceExtensionsCount, deviceExtensions, &deviceFeatures); _p->device = _p->gpu.createDeviceUnique(deviceCreateInfo); _p->graphicsQueue = _p->device->getQueue(graphicsQueueFamilyIndex, 0); auto d = _p->device.get(); /* Create a command pool to allocate our command buffer from */ _p->commandPool = d.createCommandPoolUnique({vk::CommandPoolCreateFlagBits::eResetCommandBuffer, graphicsQueueFamilyIndex}); auto commandBuffers = d.allocateCommandBuffersUnique({_p->commandPool.get(), vk::CommandBufferLevel::ePrimary, 1}); _p->commandBuffer = std::move(commandBuffers[0]); } VulkanContext::~VulkanContext() { _p->device->waitIdle(); nvgDeleteVk(vg()); _p->renderComplete.reset(); _p->presentComplete.reset(); _p->framebuffers.clear(); _p->renderPass.reset(); _p->depthBuffer.reset(); _p->swapchain.reset(); _p->commandBuffer.reset(); _p->commandPool.reset(); _p->device.reset(); _p->instance->get().destroySurfaceKHR(_p->surface, NULL); } vk::PhysicalDevice& VulkanContext::physicalDevice() { return _p->gpu; } vk::Device& VulkanContext::device() { return _p->device.get(); } vk::SurfaceKHR& VulkanContext::surface() { return _p->surface; } vk::Queue& VulkanContext::graphicsQueue() { return _p->graphicsQueue; } vk::Queue& VulkanContext::presentQueue() { return _p->presentQueue; } Status VulkanContext::initSwapchain(const vk::SurfaceKHR& surface, const vk::Extent2D& extent) { auto queueIndices = vk::su::findGraphicsAndPresentQueueFamilyIndex(_p->gpu, surface); auto graphicsQueueFamilyIndex = queueIndices.first; auto presentQueueFamilyIndex = queueIndices.second; _p->graphicsQueue = _p->device->getQueue(graphicsQueueFamilyIndex, 0); _p->presentQueue = _p->device->getQueue(presentQueueFamilyIndex, 0); auto oldSwapChainData = _p->swapchain ? std::move(_p->swapchain->swapChain) : vk::UniqueSwapchainKHR(); _p->surface = surface; _p->frameExtent = extent; _p->swapchain = std::make_shared<vk::su::SwapChainData>( _p->gpu, _p->device, surface, _p->frameExtent, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, oldSwapChainData, graphicsQueueFamilyIndex, presentQueueFamilyIndex); return Status::OK; } Status VulkanContext::initFramebuffer(const vk::Extent2D& extent) { vk::Format depthFormat = vk::su::pickDepthFormat(_p->gpu); auto colorFormat = _p->swapchain->colorFormat; _p->renderPass = vk::su::createRenderPass(_p->device, colorFormat, depthFormat); _p->presentComplete = _p->device->createSemaphoreUnique(vk::SemaphoreCreateInfo()); _p->renderComplete = _p->device->createSemaphoreUnique(vk::SemaphoreCreateInfo()); _p->depthBuffer = std::make_shared<vk::su::DepthBufferData>(_p->gpu, _p->device, depthFormat, extent); vk::su::oneTimeSubmit(_p->commandBuffer, _p->graphicsQueue, [&](vk::UniqueCommandBuffer const& commandBuffer) { vk::su::setImageLayout(commandBuffer, *_p->depthBuffer->image, depthFormat, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal); }); _p->framebuffers = vk::su::createFramebuffers(_p->device, _p->renderPass, _p->swapchain->imageViews, _p->depthBuffer->imageView, extent); return Status::OK; } Status VulkanContext::initVG() { if (_vg != nullptr) { nvgDeleteVk(_vg); } VKNVGCreateInfo createInfo = {0}; createInfo.gpu = _p->gpu; createInfo.device = _p->device.get(); createInfo.queue = _p->graphicsQueue; createInfo.renderPass = _p->renderPass.get(); createInfo.cmdBuffer = _p->commandBuffer.get(); int flag = NVG_ANTIALIAS | NVG_STENCIL_STROKES; #ifdef NDEBUG flag |= NVG_DEBUG; #endif _vg = nvgCreateVk(createInfo, flag); if (_vg == NULL) { LOGE << "Could not init nanovg (Vulkan)."; return Status::UNKNOWN_ERROR; } return Status::OK; } Status VulkanContext::rebuildSwapchain() { auto extent = _p->frameExtent; _p->device->waitIdle(); initSwapchain(_p->surface, extent); vk::Format depthFormat = _p->depthBuffer->format; *(_p->depthBuffer) = vk::su::DepthBufferData(_p->gpu, _p->device, depthFormat, extent); vk::su::oneTimeSubmit(_p->commandBuffer, _p->graphicsQueue, [&](vk::UniqueCommandBuffer const& commandBuffer) { vk::su::setImageLayout(commandBuffer, *_p->depthBuffer->image, depthFormat, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal); }); _p->framebuffers = vk::su::createFramebuffers(_p->device, _p->renderPass, _p->swapchain->imageViews, _p->depthBuffer->imageView, extent); return Status::OK; } auto VulkanContext::setViewport(int x, int y, int width, int height) -> decltype(this) { vk::Viewport viewport = {(float)x, (float)y, (float)width, (float)height, 0.f, 1.f}; vk::Rect2D scissor = {{x, y}, {(uint32_t)width, (uint32_t)height}}; _p->commandBuffer->setViewport(0, 1, &viewport); _p->commandBuffer->setScissor(0, 1, &scissor); return this; } auto VulkanContext::preDraw(const Recti& renderArea, const Color* clearColor, const float* clearDepth, const int* clearStencil) -> decltype(this) { if (renderArea.w != _p->frameExtent.width || renderArea.h != _p->frameExtent.height) { _p->frameExtent = vk::Extent2D(renderArea.w, renderArea.h); rebuildSwapchain(); } auto&& cb = _p->currentBuffer; // Get the index of the next available swapchain image: _p->device->acquireNextImageKHR(_p->swapchain->swapChain.get(), vk::su::FenceTimeout, _p->presentComplete.get(), nullptr, &cb); if (clearColor != nullptr) {} if (clearDepth != nullptr) {} if (clearStencil != nullptr) {} vk::ClearValue clearValues[2]; clearValues[0].color.float32[0] = 0.3f; clearValues[0].color.float32[1] = 0.3f; clearValues[0].color.float32[2] = 0.32f; clearValues[0].color.float32[3] = 1.0f; clearValues[1].depthStencil.depth = 1.0f; clearValues[1].depthStencil.stencil = 0; vk::RenderPassBeginInfo renderPassBeginInfo; renderPassBeginInfo.pNext = NULL; renderPassBeginInfo.renderPass = _p->renderPass.get(); renderPassBeginInfo.framebuffer = _p->framebuffers[cb].get(); renderPassBeginInfo.renderArea.offset.x = renderArea.x; renderPassBeginInfo.renderArea.offset.y = renderArea.y; renderPassBeginInfo.renderArea.extent.width = renderArea.w; renderPassBeginInfo.renderArea.extent.height = renderArea.h; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; _p->commandBuffer->begin(vk::CommandBufferBeginInfo()); _p->commandBuffer->beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline); return setViewport(renderArea.x, renderArea.y, renderArea.w, renderArea.h); } auto VulkanContext::postDraw() -> decltype(this) { auto&& cb = _p->currentBuffer; _p->commandBuffer->endRenderPass(); _p->commandBuffer->end(); vk::PipelineStageFlags pipelineStageFlags = vk::PipelineStageFlagBits::eColorAttachmentOutput; vk::SubmitInfo submitInfo(1, &_p->presentComplete.get(), &pipelineStageFlags, 1, &_p->commandBuffer.get(), 1, &_p->renderComplete.get()); /* Queue the command buffer for execution */ _p->graphicsQueue.submit(submitInfo, nullptr); /* Now present the image in the window */ vk::PresentInfoKHR presentInfo(1, &_p->renderComplete.get(), 1, &_p->swapchain->swapChain.get(), &cb); try { _p->graphicsQueue.presentKHR(presentInfo); _p->graphicsQueue.waitIdle(); } catch (const vk::OutOfDateKHRError&) {} return this; } } // namespace fui
37.96139
117
0.710537
choiip
e70c2f82e1106fd4437a6d6209dacdba5d81c43f
8,463
cc
C++
biosig4octmat-3.2.0/biosig/maybe-missing/regexprep.cc
TianGL/CNN-MI-BCI
788493ffc954df153cd928d84090d9625ff357d4
[ "MIT" ]
41
2018-10-30T07:40:11.000Z
2022-02-25T13:37:40.000Z
biosig4octmat-3.2.0/biosig/maybe-missing/regexprep.cc
TianGL/CNN-SAE-MI-BCI-
788493ffc954df153cd928d84090d9625ff357d4
[ "MIT" ]
2
2018-11-30T17:47:07.000Z
2022-02-22T22:45:17.000Z
biosig4octmat-2.90/biosig/maybe-missing/regexprep.cc
wilkesk/cSPider
89db77e3f534decc37b01d47dff37f576f4725a1
[ "BSD-2-Clause" ]
13
2018-12-18T13:54:01.000Z
2022-03-08T13:03:28.000Z
// This code is public domain. // Author: Paul Kienzle #ifdef HAVE_CONFIG_H # include <config.h> #else # include <octave/config.h> #endif #include "defun-dld.h" #include "error.h" #include "parse.h" #include "quit.h" #include "Cell.h" DEFUN_DLD(regexprep,args,nargout,"\ -*- texinfo -*-\n\ @deftypefn {Function File} @var{string} = regexprep(@var{string}, @var{pat}, @var{repstr}, @var{options})\n\ Replace matches of @var{pat} in @var{string} with @var{repstr}.\n\ \n\ \n\ The replacement can contain @code{$i}, which subsubstitutes\n\ for the ith set of parentheses in the match string. E.g.,\n\ @example\n\ \n\ regexprep(\"Bill Dunn\",'(\\w+) (\\w+)','$2, $1')\n\ \n\ @end example\n\ returns \"Dunn, Bill\"\n\ \n\ @var{options} may be zero or more of\n\ @table @samp\n\ \n\ @item once\n\ Replace only the first occurance of @var{pat} in the result.\n\ \n\ @item warnings\n\ This option is present for compatibility but is ignored.\n\ \n\ @item ignorecase or matchcase\n\ Ignore case for the pattern matching (see @code{regexpi}).\n\ Alternatively, use (?i) or (?-i) in the pattern.\n\ \n\ @item lineanchors and stringanchors\n\ Whether characters ^ and $ match the beginning and ending of lines.\n\ Alternatively, use (?m) or (?-m) in the pattern.\n\ \n\ @item dotexceptnewline and dotall\n\ Whether . matches newlines in the string.\n\ Alternatively, use (?s) or (?-s) in the pattern.\n\ \n\ @item freespacing or literalspacing\n\ Whether whitespace and # comments can be used to make the regular expression more readable.\n\ Alternatively, use (?x) or (?-x) in the pattern.\n\ \n\ @end table\n\ @seealso{regexp,regexpi}\n\ @end deftypefn") { octave_value_list retval; int nargin = args.length(); int nopts = nargin - 3; if (nargin < 3) { print_usage("regexprep"); return retval; } // Make sure we have string,pattern,replacement const std::string buffer = args(0).string_value (); if (error_state) return retval; const std::string pattern = args(1).string_value (); if (error_state) return retval; const std::string replacement = args(2).string_value (); if (error_state) return retval; // Pack options excluding 'tokenize' and various output // reordering strings into regexp arg list octave_value_list regexpargs(nargin-1,octave_value()); regexpargs(0) = args(0); regexpargs(1) = args(1); int len=2; for (int i = 3; i < nargin; i++) { const std::string opt = args(i).string_value(); if (opt != "tokenize" && opt != "start" && opt != "end" && opt != "tokenextents" && opt != "match" && opt != "tokens" && opt != "names" && opt != "warnings") { regexpargs(len++) = args(i); } } regexpargs.resize(len); //std::cout << "Buffer " << buffer << std::endl; //std::cout << "Pattern " << pattern << std::endl; //std::cout << "Replacement " << replacement << std::endl; // Identify replacement tokens; build a vector of group numbers in // the replacement string so that we can quickly calculate the size // of the replacement. int tokens = 0; for (size_t i=1; i < replacement.size(); i++) { if (replacement[i-1]=='$' && isdigit(replacement[i])) { tokens++, i++; } } std::vector<int> token(tokens); int k=0; for (size_t i=1; i < replacement.size(); i++) { if (replacement[i-1]=='$' && isdigit(replacement[i])) { token[k++] = replacement[i]-'0'; i++; } } // Perform replacement std::string rep; if (tokens > 0) { // Call regexp, asking for start, end, and capture start/end octave_value_list regexpret = feval("regexp", regexpargs, 3); if (regexpret(0).is_empty()) { retval(0) = args(0); return retval; } const ColumnVector s(regexpret(0).vector_value()); const ColumnVector e(regexpret(1).vector_value()); const Cell te(regexpret(2).cell_value()); if (error_state) return retval; // Determine replacement length const size_t replen = replacement.size() - 2*tokens; int delta = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; const Matrix pairs(te(i).matrix_value()); size_t pairlen = 0; for (int j=0; j < tokens; j++) { if (token[j] == 0) pairlen += size_t(e(i)-s(i))+1; else if (token[j] <= pairs.rows()) pairlen += size_t(pairs(token[j]-1,1)-pairs(token[j]-1,0))+1; } delta += int(replen + pairlen) - int(e(i)-s(i)+1); } // std::cout << "replacement delta is " << delta << std::endl; // Build replacement string rep.reserve(buffer.size()+delta); size_t from = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; const Matrix pairs(te(i).matrix_value()); rep.append(&buffer[from], size_t(s(i)-1)-from); from = size_t(e(i)-1)+1; for (size_t j=1; j < replacement.size(); j++) { if (replacement[j-1]=='$' && isdigit(replacement[j])) { int k = replacement[j]-'0'; if (k==0) { // replace with entire match rep.append(&buffer[size_t(e(i)-1)], size_t(e(i)-s(i))+1); } else if (k <= pairs.rows()) { // replace with group capture // std::cout << "k=" << k << " [" << pairs(k-1,0) << "," << pairs(k-1,1) << "]" << std::endl; rep.append(&buffer[size_t(pairs(k-1,0)-1)], size_t(pairs(k-1,1)-pairs(k-1,0))+1); } else { // replace with nothing } j++; } else { rep.append(1,replacement[j-1]); if (j == replacement.size()-1) { rep.append(1,replacement[j]); } } } // std::cout << "->" << rep << std::endl; } rep.append(&buffer[from],buffer.size()-from); } else { // Call regexp, asking for start, end octave_value_list regexpret = feval("regexp", regexpargs, 2); if (regexpret(0).is_empty()) { retval(0) = args(0); return retval; } const ColumnVector s(regexpret(0).vector_value()); const ColumnVector e(regexpret(1).vector_value()); if (error_state) return retval; // Determine replacement length const size_t replen = replacement.size(); int delta = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; delta += int(replen) - int(e(i)-s(i)+1); } // std::cout << "replacement delta is " << delta << std::endl; // Build replacement string rep.reserve(buffer.size()+delta); size_t from = 0; for (int i=0; i < s.length(); i++) { OCTAVE_QUIT; rep.append(&buffer[from],size_t(s(i)-1)-from); from = size_t(e(i)-1)+1; rep.append(replacement); // std::cout << "->" << rep << std::endl; } rep.append(&buffer[from],buffer.size()-from); } retval(0) = rep; return retval; } /* %!test # Replace with empty %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; %! t = regexprep(xml,'<[!?][^>]*>',''); %! assert(t,' <tag v="hello">some stuff</tag>') %!test # Replace with non-empty %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; %! t = regexprep(xml,'<[!?][^>]*>','?'); %! assert(t,'? <tag v="hello">some stuff?</tag>') %!test # Check that 'tokenize' is ignored %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>'; %! t = regexprep(xml,'<[!?][^>]*>','','tokenize'); %! assert(t,' <tag v="hello">some stuff</tag>') %!test # Capture replacement %! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_PCRE"))) %! data = "Bob Smith\nDavid Hollerith\nSam Jenkins"; %! result = "Smith, Bob\nHollerith, David\nJenkins, Sam"; %! t = regexprep(data,'(?m)^(\w+)\s+(\w+)$','$2, $1'); %! assert(t,result) %! end # Return the original if no match %!assert(regexprep('hello','world','earth'),'hello') ## Test a general replacement %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_"), "a_b_c_d_e_f_g"); ## Make sure it works at the beginning and end %!assert(regexprep("a[b]c{d}e-f=g", "a", "_"), "_[b]c{d}e-f=g"); %!assert(regexprep("a[b]c{d}e-f=g", "g", "_"), "a[b]c{d}e-f=_"); ## Options %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_", "once"), "a_b]c{d}e-f=g"); %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "ignorecase"), "a_b_c_d_e_f_g"); ## Option combinations %!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "once", "ignorecase"), "a_b]c{d}e-f=g"); */
28.785714
109
0.581827
TianGL
e70c974e0ad39a424c776064f17d7982ee43c141
53,764
cpp
C++
win32/src/win32security_sspi.cpp
huanyin88/Mod-Pywin32-For-Python3.x-DDE
992931aa534357d54aaac34077f0128d3a740e5e
[ "Apache-2.0" ]
3
2020-06-18T16:57:44.000Z
2020-07-21T17:52:06.000Z
win32/src/win32security_sspi.cpp
huanyin88/Mod-Pywin32-For-Python3.x-DDE
992931aa534357d54aaac34077f0128d3a740e5e
[ "Apache-2.0" ]
null
null
null
win32/src/win32security_sspi.cpp
huanyin88/Mod-Pywin32-For-Python3.x-DDE
992931aa534357d54aaac34077f0128d3a740e5e
[ "Apache-2.0" ]
null
null
null
// SSPI objects for the win32security module, by Roger Upole // $Id$ // Currently this file contains only object definitions - the SSPI methods // themselves are defined in win32security.i. In the future this may change. // @doc - This file contains autoduck documentation #include "PyWinTypes.h" #include "structmember.h" #include "PyWinObjects.h" #include "PySecurityObjects.h" #include "win32security_sspi.h" #include "schannel.h" //////////////////////////////////////////////////////////////////////// // // PySecBufferDesc // //////////////////////////////////////////////////////////////////////// Py_ssize_t PySecBufferDesc_sq_length(PyObject *self) { PSecBufferDesc psecbufferdesc = ((PySecBufferDesc *)self)->GetSecBufferDesc(); return psecbufferdesc->cBuffers; } PyObject *PySecBufferDesc_sq_item(PyObject *self, Py_ssize_t i) { PySecBufferDesc *This = (PySecBufferDesc *)self; PSecBufferDesc psecbufferdesc = This->GetSecBufferDesc(); if ((ULONG)i >= psecbufferdesc->cBuffers) { PyErr_SetString(PyExc_IndexError, "Index specified larger than number of allocated buffers"); return NULL; } Py_INCREF(This->obBuffers[i]); return This->obBuffers[i]; } int PySecBufferDesc_sq_ass_item(PyObject *self, Py_ssize_t i, PyObject *ob) { if (ob == NULL) { PyErr_SetString(PyExc_NotImplementedError, "Removing buffers not yet supported"); return -1; } PSecBuffer psecbuffer; PySecBufferDesc *This = (PySecBufferDesc *)self; PSecBufferDesc psecbufferdesc = This->GetSecBufferDesc(); if ((ULONG)i >= psecbufferdesc->cBuffers) { PyErr_Format(PyExc_IndexError, "PySecBufferDesc contains %d buffers", psecbufferdesc->cBuffers); return -1; } if (!PyWinObject_AsSecBuffer(ob, &psecbuffer, FALSE)) return -1; Py_XDECREF(This->obBuffers[i]); Py_INCREF(ob); This->obBuffers[i] = ob; psecbufferdesc->pBuffers[i] = *psecbuffer; return 0; } PySequenceMethods PySecBufferDesc_sequencemethods = { PySecBufferDesc_sq_length, // inquiry sq_length; NULL, // binaryfunc sq_concat; NULL, // intargfunc sq_repeat; PySecBufferDesc_sq_item, // intargfunc sq_item; NULL, // intintargfunc sq_slice; PySecBufferDesc_sq_ass_item, // intobjargproc sq_ass_item;; NULL, // intintobjargproc sq_ass_slice; NULL, // objobjproc sq_contains; NULL, // binaryfunc sq_inplace_concat; NULL // intargfunc sq_inplace_repeat; }; // ??? why isnt append included ??? // @object PySecBufferDesc|Sequence-like object that contains a group of buffers to be used with SSPI functions. // @comm This object is created using win32security.PySecBufferDescType(Version), where Version is an int that // defaults to SECBUFFER_VERSION if not passed in. struct PyMethodDef PySecBufferDesc::methods[] = { {"append", PySecBufferDesc::append, 1}, // @pymeth append|Adds a <o PySecBuffer> to the list of buffers {NULL}}; #define OFF(e) offsetof(PySecBufferDesc, e) struct PyMemberDef PySecBufferDesc::members[] = { {"Version", T_ULONG, OFF(secbufferdesc.ulVersion), 0, "Currently should always be SECBUFFER_VERSION"}, {NULL}}; PyTypeObject PySecBufferDescType = { PYWIN_OBJECT_HEAD "PySecBufferDesc", sizeof(PySecBufferDesc), 0, PySecBufferDesc::deallocFunc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare PySecBufferDesc::tp_repr, // tp_repr 0, // PyNumberMethods *tp_as_number &PySecBufferDesc_sequencemethods, // PySequenceMethods *tp_as_sequence 0, // PyMappingMethods *tp_as_mapping 0, // hashfunc tp_hash 0, // tp_call 0, // tp_str PyObject_GenericGetAttr, // tp_getattro PyObject_GenericSetAttr, // tp_setattro 0, // PyBufferProcs *tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags 0, // tp_doc 0, // traverseproc tp_traverse 0, // tp_clear 0, // richcmpfunc tp_richcompare 0, // tp_weaklistoffset 0, // getiterfunc tp_iter 0, // iternextfunc tp_iternext PySecBufferDesc::methods, PySecBufferDesc::members, 0, // tp_getset; 0, // tp_base; 0, // tp_dict; 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc PySecBufferDesc::tp_new // newfunc tp_new; }; // InitializeSecurityContext can allocate output buffers if flag ISC_REQ_ALLOCATE_MEMORY is set // Untested !!!!!! PySecBufferDesc::PySecBufferDesc(PSecBufferDesc psecbufferdesc) { ob_type = &PySecBufferDescType; secbufferdesc = *psecbufferdesc; secbufferdesc.pBuffers = (PSecBuffer)malloc(psecbufferdesc->cBuffers * sizeof(SecBuffer)); obBuffers = (PyObject **)malloc(psecbufferdesc->cBuffers * sizeof(PyObject *)); if (obBuffers != NULL) for (ULONG i = 0; i < psecbufferdesc->cBuffers; i++) obBuffers[i] = PyWinObject_FromSecBuffer(&psecbufferdesc->pBuffers[i]); _Py_NewReference(this); } PySecBufferDesc::PySecBufferDesc(ULONG ulVersion) { DWORD bufsize; ob_type = &PySecBufferDescType; secbufferdesc.ulVersion = ulVersion; secbufferdesc.cBuffers = 0; max_buffers = 5; bufsize = max_buffers * sizeof(PyObject *); obBuffers = (PyObject **)malloc(bufsize); if (obBuffers == NULL) PyErr_Format(PyExc_MemoryError, "PySecBufferDesc: unable to allocate %d PyObject pointers (%d bytes)", max_buffers, bufsize); else ZeroMemory(obBuffers, bufsize); bufsize = max_buffers * sizeof(SecBuffer); secbufferdesc.pBuffers = (PSecBuffer)malloc(bufsize); if (obBuffers == NULL) PyErr_Format(PyExc_MemoryError, "PySecBufferDesc: unable to allocate %d SecBuffer's (%d bytes)", max_buffers, bufsize); else ZeroMemory(secbufferdesc.pBuffers, bufsize); _Py_NewReference(this); } PySecBufferDesc::~PySecBufferDesc() { if (secbufferdesc.pBuffers != NULL) free(secbufferdesc.pBuffers); for (ULONG buf_ind = 0; buf_ind < secbufferdesc.cBuffers; buf_ind++) Py_XDECREF(obBuffers[buf_ind]); if (obBuffers != NULL) free(obBuffers); } BOOL PySecBufferDesc_Check(PyObject *ob) { if (ob->ob_type != &PySecBufferDescType) { PyErr_SetString(PyExc_TypeError, "Object must be a PySecBufferDesc"); return FALSE; } return TRUE; } void PySecBufferDesc::deallocFunc(PyObject *ob) { delete (PySecBufferDesc *)ob; } PSecBufferDesc PySecBufferDesc::GetSecBufferDesc(void) { return &secbufferdesc; } PyObject *PySecBufferDesc::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwargs) { ULONG ulVersion = SECBUFFER_VERSION; static char *keywords[] = {"Version", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|l:PySecBufferDescType", keywords, &ulVersion)) return NULL; return new PySecBufferDesc(ulVersion); } PyObject * PySecBufferDesc::tp_repr(PyObject * obj) { PSecBufferDesc psecbufferdesc = ((PySecBufferDesc *)obj)->GetSecBufferDesc(); return PyUnicode_FromFormat("PySecBufferDesc(ulVersion: %i | cBuffers: %i | pBuffers: %p)", psecbufferdesc->ulVersion, psecbufferdesc->cBuffers, psecbufferdesc->pBuffers); } BOOL PyWinObject_AsSecBufferDesc(PyObject *ob, PSecBufferDesc *ppSecBufferDesc, BOOL bNoneOk) { if (ob == Py_None) { if (bNoneOk) { *ppSecBufferDesc = NULL; return TRUE; } PyErr_SetString(PyExc_ValueError, "PySecBufferDesc cannot be None in this context"); return FALSE; } if (!PySecBufferDesc_Check(ob)) return FALSE; *ppSecBufferDesc = ((PySecBufferDesc *)ob)->GetSecBufferDesc(); // move any changes made to the individual PySecBuffer objects back into the SecBufferDesc array for (ULONG i = 0; i < (*ppSecBufferDesc)->cBuffers; i++) (*ppSecBufferDesc)->pBuffers[i] = *((PySecBuffer *)((PySecBufferDesc *)ob)->obBuffers[i])->GetSecBuffer(); return TRUE; } // @pymethod |PySecBufferDesc|append|Adds a <o PySecBuffer> to the buffer configuration PyObject *PySecBufferDesc::append(PyObject *self, PyObject *args) { PyObject *ob; PSecBuffer psecbuffer; PSecBuffer pbufsave; PyObject **obbufsave; PySecBufferDesc *This = (PySecBufferDesc *)self; PSecBufferDesc psecbufferdesc = This->GetSecBufferDesc(); if (!PyArg_ParseTuple(args, "O", &ob)) return NULL; // @pyparm |buffer||<o PySecBuffer> object to be attached to the group of buffers if (!PyWinObject_AsSecBuffer(ob, &psecbuffer, FALSE)) return NULL; // make sure consistent internal state can be restored if allocations fail pbufsave = psecbufferdesc->pBuffers; obbufsave = This->obBuffers; psecbufferdesc->cBuffers++; if (psecbufferdesc->cBuffers > This->max_buffers) { psecbufferdesc->pBuffers = (PSecBuffer)realloc(psecbufferdesc->pBuffers, psecbufferdesc->cBuffers * sizeof(SecBuffer)); This->obBuffers = (PyObject **)realloc(This->obBuffers, psecbufferdesc->cBuffers * sizeof(PyObject *)); if ((psecbufferdesc->pBuffers == NULL) || (This->obBuffers == NULL)) { PyErr_SetString(PyExc_MemoryError, "Unable to reallocate interal PySecBufferDesc structures"); psecbufferdesc->cBuffers--; psecbufferdesc->pBuffers = pbufsave; This->obBuffers = obbufsave; return NULL; } This->max_buffers++; } // keep reference to PySecBuffers that contain the actual allocated buffers so they can be kept in sync psecbufferdesc->pBuffers[psecbufferdesc->cBuffers - 1] = *psecbuffer; This->obBuffers[psecbufferdesc->cBuffers - 1] = ob; Py_INCREF(ob); Py_INCREF(Py_None); return Py_None; } // propagate changes back to PySecBuffer objects that constitute the actual allocated buffers void PySecBufferDesc::modify_in_place(void) { for (ULONG i = 0; i < secbufferdesc.cBuffers; i++) *((PySecBuffer *)obBuffers[i])->GetSecBuffer() = secbufferdesc.pBuffers[i]; } // ??? don't actually use this anywhere yet, but some protocols can allocate buffers for you (ISC_REQ_ALLOCATE_MEMORY) // Check for this flag in ContextReq and an output SecBufferDesc with 0 buffers initially and non-zero after API call ? // How to specify different deallocation (FreeContextBuffer) when object is destroyed ? PyObject *PyWinObject_FromSecBufferDesc(PSecBufferDesc pSecBufferDesc) { if (pSecBufferDesc == NULL) { Py_INCREF(Py_None); return Py_None; } return new PySecBufferDesc(pSecBufferDesc); } //////////////////////////////////////////////////////////////////////// // // PySecBuffer // //////////////////////////////////////////////////////////////////////// // @object PySecBuffer|Python object wrapping a SecBuffer structure // Created using win32security.PySecBufferType(type,size) where type is a SECBUFFER_* constant struct PyMethodDef PySecBuffer::methods[] = { {"Clear", PySecBuffer::Clear, 1}, // @pymeth Clear|Resets all members of the structure {NULL}}; #undef OFF #define OFF(e) offsetof(PySecBuffer, e) struct PyMemberDef PySecBuffer::members[] = { // @prop int|BufferType| {"BufferType", T_ULONG, OFF(secbuffer.BufferType), 0, "Type of buffer, one of the SECBUFFER_* constants - can also be combined with SECBUFFER_READONLY"}, // @prop string|Buffer| {"Buffer", T_OBJECT, OFF(obdummy), 0, "Encoded data buffer"}, // @prop int|BufferSize| {"BufferSize", T_ULONG, OFF(secbuffer.cbBuffer), 0, "Current size of data in buffer"}, // @prop int|MaxBufferSize| {"MaxBufferSize", T_ULONG, OFF(maxbufsize), READONLY, "Maximum size of data buffer"}, {NULL}}; PyTypeObject PySecBufferType = { PYWIN_OBJECT_HEAD "PySecBuffer", sizeof(PySecBuffer), 0, PySecBuffer::deallocFunc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare PySecBuffer::tp_repr, // tp_repr 0, // PyNumberMethods *tp_as_number 0, // PySequenceMethods *tp_as_sequence 0, // PyMappingMethods *tp_as_mapping 0, // hashfunc tp_hash 0, // tp_call 0, // tp_str PySecBuffer::getattro, // tp_getattro PySecBuffer::setattro, // tp_setattro 0, // PyBufferProcs *tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags 0, // tp_doc 0, // traverseproc tp_traverse 0, // tp_clear 0, // richcmpfunc tp_richcompare 0, // tp_weaklistoffset 0, // getiterfunc tp_iter 0, // iternextfunc tp_iternext PySecBuffer::methods, PySecBuffer::members, 0, // tp_getset; 0, // tp_base; 0, // tp_dict; 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc PySecBuffer::tp_new // newfunc tp_new; }; PySecBuffer::PySecBuffer(PSecBuffer psecbuffer) { maxbufsize = secbuffer.cbBuffer; ob_type = &PySecBufferType; secbuffer = *psecbuffer; secbuffer.pvBuffer = malloc(psecbuffer->cbBuffer); if (secbuffer.pvBuffer == NULL) PyErr_Format(PyExc_MemoryError, "PySecBuffer::PySecBuffer - cannot allocate buffer of %d bytes", psecbuffer->cbBuffer); else memcpy(secbuffer.pvBuffer, psecbuffer->pvBuffer, psecbuffer->cbBuffer); _Py_NewReference(this); } PySecBuffer::PySecBuffer(ULONG cbBuffer, ULONG BufferType) { obdummy = NULL; maxbufsize = cbBuffer; ob_type = &PySecBufferType; secbuffer.cbBuffer = cbBuffer; secbuffer.BufferType = BufferType; allocBuffer = NULL; if (cbBuffer > 0) { // Stores our allocated memory in a class property so we don't try and free memory that wasn't allocated by us. // Windows could change where pvBuffer points to after a function call and we should only be concerned about // freeing memory that we have allocated ourselves. allocBuffer = malloc(cbBuffer); // Any code that creates instances should check that buffer is not NULL ! if (allocBuffer == NULL) PyErr_Format(PyExc_MemoryError, "PySecBuffer::PySecBuffer - cannot allocate buffer of %d bytes", cbBuffer); else ZeroMemory(allocBuffer, cbBuffer); } secbuffer.pvBuffer = allocBuffer; _Py_NewReference(this); } PySecBuffer::~PySecBuffer() { // We don't check secbuffer.pvBuffer as that could be a pointer set by Windows and not our originally allocated // block of memory. if (allocBuffer != NULL) free(allocBuffer); } BOOL PySecBuffer_Check(PyObject *ob) { if (ob->ob_type != &PySecBufferType) { PyErr_SetString(PyExc_TypeError, "Object must be a PySecBuffer"); return FALSE; } return TRUE; } void PySecBuffer::deallocFunc(PyObject *ob) { delete (PySecBuffer *)ob; } PSecBuffer PySecBuffer::GetSecBuffer(void) { return &secbuffer; } PyObject *PySecBuffer::getattro(PyObject *self, PyObject *obname) { PSecBuffer psecbuffer = ((PySecBuffer *)self)->GetSecBuffer(); char *name = PYWIN_ATTR_CONVERT(obname); if (name == NULL) return NULL; if (strcmp(name, "Buffer") == 0) return PyString_FromStringAndSize((char *)psecbuffer->pvBuffer, psecbuffer->cbBuffer); return PyObject_GenericGetAttr(self, obname); } int PySecBuffer::setattro(PyObject *self, PyObject *obname, PyObject *obvalue) { PySecBuffer *This = (PySecBuffer *)self; char *name; void *value; DWORD valuelen; name = PYWIN_ATTR_CONVERT(obname); if (name == NULL) return -1; if (strcmp(name, "Buffer") == 0) { if (!PyWinObject_AsReadBuffer(obvalue, &value, &valuelen)) return -1; PSecBuffer psecbuffer = This->GetSecBuffer(); if (valuelen > This->maxbufsize) { PyErr_Format(PyExc_ValueError, "Data size (%d) greater than allocated buffer size (%d)", valuelen, This->maxbufsize); return -1; } ZeroMemory(psecbuffer->pvBuffer, This->maxbufsize); memcpy(psecbuffer->pvBuffer, value, valuelen); // buffer length should be size of actual data, allocated size is kept in our own maxbufsize psecbuffer->cbBuffer = valuelen; return 0; } return PyObject_GenericSetAttr(self, obname, obvalue); } PyObject *PySecBuffer::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwargs) { ULONG cbBuffer, BufferType; static char *keywords[] = {"BufferSize", "BufferType", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ll", keywords, &cbBuffer, &BufferType)) return NULL; return new PySecBuffer(cbBuffer, BufferType); } PyObject * PySecBuffer::tp_repr(PyObject * obj) { PSecBuffer psecbuffer = ((PySecBuffer *)obj)->GetSecBuffer(); return PyUnicode_FromFormat("PySecBuffer(cbBuffer: %i | BufferType: %i | pvBuffer: %p)", psecbuffer->cbBuffer, psecbuffer->BufferType, psecbuffer->pvBuffer); } // @pymethod |PySecBuffer|Clear|Resets the buffer to all NULL's, and set the current size to maximum PyObject *PySecBuffer::Clear(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":Clear")) return NULL; PySecBuffer *This = (PySecBuffer *)self; PSecBuffer psecbuffer = This->GetSecBuffer(); psecbuffer->cbBuffer = This->maxbufsize; ZeroMemory(psecbuffer->pvBuffer, psecbuffer->cbBuffer); Py_INCREF(Py_None); return Py_None; } BOOL PyWinObject_AsSecBuffer(PyObject *ob, PSecBuffer *psecbuffer, BOOL bNoneOk) { if (!PySecBuffer_Check(ob)) return FALSE; *psecbuffer = ((PySecBuffer *)ob)->GetSecBuffer(); return TRUE; } PyObject *PyWinObject_FromSecBuffer(PSecBuffer psecbuffer) { return new PySecBuffer(psecbuffer); } //////////////////////////////////////////////////////////////////////// // // PyCtxtHandle // //////////////////////////////////////////////////////////////////////// // @object PyCtxtHandle|Security context handle, as used with sspi functions // @comm Create using win32security.PyCtxtHandleType(). The handle must be initialized by passing it to // <om win32security.InitializeSecurityContext> or <om win32security.AcceptSecurityContext> struct PyMethodDef PyCtxtHandle::methods[] = { {"Detach", PyCtxtHandle::Detach, 1}, // @pymeth Detach|Disassociates object from handle and returns integer value of handle {"CompleteAuthToken", PyCtxtHandle::CompleteAuthToken, 1}, //@pymeth CompleteAuthToken|Completes the authentication token {"QueryContextAttributes", PyCtxtHandle::QueryContextAttributes, 1}, // @pymeth QueryContextAttributes|Retrieves info about a security context {"DeleteSecurityContext", PyCtxtHandle::DeleteSecurityContext, 1}, // @pymeth DeleteSecurityContext|Frees the security context and invalidates the handle {"QuerySecurityContextToken", PyCtxtHandle::QuerySecurityContextToken, 1}, // @pymeth QuerySecurityContextToken|Returns the access token for a security context {"MakeSignature", PyCtxtHandle::MakeSignature, 1}, // @pymeth MakeSignature|Generates a signature for a message {"VerifySignature", PyCtxtHandle::VerifySignature, 1}, // @pymeth VerifySignature|Verifies a signature created using <om PyCtxtHandle.MakeSignature> {"EncryptMessage", PyCtxtHandle::EncryptMessage, 1}, // @pymeth EncryptMessage|Encrypts data with security context's session key {"DecryptMessage", PyCtxtHandle::DecryptMessage, 1}, // @pymeth DecryptMessage|Decrypts data encrypted by <om PyCtxtHandle.EncryptMessage> {"ImpersonateSecurityContext", PyCtxtHandle::ImpersonateSecurityContext, 1}, // @pymeth ImpersonateSecurityContext|Causes a server to act in the security context of an authenticated // client {"RevertSecurityContext", PyCtxtHandle::RevertSecurityContext, 1}, // @pymeth RevertSecurityContext|Stops impersonation of a client initiated by <om // PyCtxtHandle::ImpersonateSecurityContext> {NULL}}; PyTypeObject PyCtxtHandleType = { PYWIN_OBJECT_HEAD "PyCtxtHandle", sizeof(PyCtxtHandle), 0, PyCtxtHandle::deallocFunc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // PyNumberMethods *tp_as_number 0, // PySequenceMethods *tp_as_sequence 0, // PyMappingMethods *tp_as_mapping 0, // hashfunc tp_hash 0, // tp_call 0, // tp_str PyObject_GenericGetAttr, // tp_getattro PyObject_GenericSetAttr, // tp_setattro 0, // PyBufferProcs *tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags 0, // tp_doc 0, // traverseproc tp_traverse 0, // tp_clear 0, // richcmpfunc tp_richcompare 0, // tp_weaklistoffset 0, // getiterfunc tp_iter 0, // iternextfunc tp_iternext PyCtxtHandle::methods, NULL, 0, // tp_getset; 0, // tp_base; 0, // tp_dict; 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc PyCtxtHandle::tp_new // newfunc tp_new; }; PyCtxtHandle::PyCtxtHandle(PCtxtHandle pctxthandle) { ob_type = &PyCtxtHandleType; ctxthandle = *pctxthandle; _Py_NewReference(this); } PyCtxtHandle::PyCtxtHandle(void) { ob_type = &PyCtxtHandleType; SecInvalidateHandle(&ctxthandle); _Py_NewReference(this); } PyCtxtHandle::~PyCtxtHandle() { if (SecIsValidHandle(&ctxthandle)) (*psecurityfunctiontable->DeleteSecurityContext)(&ctxthandle); } BOOL PyCtxtHandle_Check(PyObject *ob) { if (ob->ob_type != &PyCtxtHandleType) { PyErr_SetString(PyExc_TypeError, "Object must be a PyCtxtHandle"); return FALSE; } return TRUE; } void PyCtxtHandle::deallocFunc(PyObject *ob) { delete (PyCtxtHandle *)ob; } PCtxtHandle PyCtxtHandle::GetCtxtHandle(void) { return &ctxthandle; } PyObject *PyCtxtHandle::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwargs) { return new PyCtxtHandle(); } BOOL PyWinObject_AsCtxtHandle(PyObject *ob, PCtxtHandle *pctxthandle, BOOL bNoneOk) { if (ob == Py_None) { if (bNoneOk) { *pctxthandle = NULL; return TRUE; } PyErr_SetString(PyExc_ValueError, "Context handle cannot be NULL"); return FALSE; } if (!PyCtxtHandle_Check(ob)) return FALSE; *pctxthandle = ((PyCtxtHandle *)ob)->GetCtxtHandle(); return TRUE; } PyObject *PyWinObject_FromCtxtHandle(PCtxtHandle pctxthandle) { return new PyCtxtHandle(pctxthandle); } // @pymethod |PyCtxtHandle|MakeSignature|Creates a crytographic hash of a message using session key of the security // context PyObject *PyCtxtHandle::MakeSignature(PyObject *self, PyObject *args) { // @pyparm int|fqop||Flags that indicate quality of protection desired, specific to each security package // @pyparm <o PySecBufferDesc>|Message||Buffer set that includes buffers for input data and output signature // @pyparm int|MessageSeqNo||A sequential number used by some packages to verify that no extraneous messages have // been received // @rdesc Returns None on success, and output buffer in Message will contain the signature // @comm The buffer configuration is dependent on the security package. Usually there is one input buffer of // type SECBUFFER_DATA and an output buffer of type SECBUFFER_TOKEN SECURITY_STATUS err; PyObject *obdesc; PSecBufferDesc psecbufferdesc; ULONG fqop, seq_no; CHECK_SECURITYFUNCTIONTABLE(MakeSignature); if (!PyArg_ParseTuple(args, "lOl:MakeSignature", &fqop, &obdesc, &seq_no)) return NULL; if (!PyWinObject_AsSecBufferDesc(obdesc, &psecbufferdesc, FALSE)) return NULL; PCtxtHandle pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->MakeSignature)(pctxt, fqop, psecbufferdesc, seq_no); Py_END_ALLOW_THREADS if (err < 0) { PyWin_SetAPIError("MakeSignature", err); return NULL; } // copy changes in buffers back to individual PySecBuffer objects ((PySecBufferDesc *)obdesc)->modify_in_place(); Py_INCREF(Py_None); return Py_None; } // @pymethod |PyCtxtHandle|VerifySignature|Verifies a signature created using <om PyCtxtHandle.MakeSignature> PyObject *PyCtxtHandle::VerifySignature(PyObject *self, PyObject *args) { // @pyparm <o PySecBufferDesc>|Message||SecBufferDesc that contains data buffer and signature buffer // @pyparm int|MessageSeqNo||A sequential number used by some packages to verify that no extraneous messages have // been received // @rdesc Returns quality of protection flags used to create signature // @comm The buffer configuration is dependent on the security package. Usually there is a data buffer of type // SECBUFFER_DATA // and a signature buffer of type SECBUFFER_TOKEN SECURITY_STATUS err; PyObject *obdesc; PSecBufferDesc psecbufferdesc; ULONG fqop, seq_no; CHECK_SECURITYFUNCTIONTABLE(VerifySignature); if (!PyArg_ParseTuple(args, "Ol:VerifySignature", &obdesc, &seq_no)) return NULL; if (!PyWinObject_AsSecBufferDesc(obdesc, &psecbufferdesc, FALSE)) return NULL; PCtxtHandle pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); err = (*psecurityfunctiontable->VerifySignature)(pctxt, psecbufferdesc, seq_no, &fqop); if (err == SEC_E_OK) return Py_BuildValue("l", fqop); PyWin_SetAPIError("VerifySignature", err); return NULL; } // @pymethod |PyCtxtHandle|EncryptMessage|Encrypts data with session key of security context PyObject *PyCtxtHandle::EncryptMessage(PyObject *self, PyObject *args) { // @pyparm int|fqop||Flags that indicate quality of protection desired, specific to each security package // @pyparm <o PySecBufferDesc>|Message||<o PySecBufferDesc> that contains data buffer(s) to be encrypted // @pyparm int|MessageSeqNo||A sequential number used by some packages to verify that no extraneous messages have // been received // @rdesc Returns None on success, and buffer(s) will contain encrypted data // @comm The buffer configuration is dependent on the security package. Usually there is one input buffer // of type SECBUFFER_DATA to be encrypted in-place and another empty buffer of type SECBUFFER_PADDING or // SECBUFFER_TOKEN to receive signature or padding data SECURITY_STATUS err; PyObject *obdesc; PSecBufferDesc psecbufferdesc; ULONG fqop, seq_no; CHECK_SECURITYFUNCTIONTABLE(EncryptMessage); if (!PyArg_ParseTuple(args, "lOl:EncryptMessage", &fqop, &obdesc, &seq_no)) return NULL; if (!PyWinObject_AsSecBufferDesc(obdesc, &psecbufferdesc, FALSE)) return NULL; PCtxtHandle pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->EncryptMessage)(pctxt, fqop, psecbufferdesc, seq_no); Py_END_ALLOW_THREADS if (err < 0) { PyWin_SetAPIError("EncryptMessage", err); return NULL; } // copy changes in buffers back to individual PySecBuffer objects ((PySecBufferDesc *)obdesc)->modify_in_place(); Py_INCREF(Py_None); return Py_None; } // @pymethod |PyCtxtHandle|DecryptMessage|Decrypts data produced by <om PyCtxtHandle.EncryptMessage> PyObject *PyCtxtHandle::DecryptMessage(PyObject *self, PyObject *args) { // @pyparm <o PySecBufferDesc>|Message||<o PySecBufferDesc> containing data buffers to be decrypted // @pyparm int|MessageSeqNo||A sequential number used by some packages to verify that no extraneous messages have // been received // @rdesc Returns flags specfic to security package indicating quality of protection // @comm The buffer configuration is dependent on the security package. Usually there is one buffer // of type SECBUFFER_DATA which is modified in place and a second buffer of type SECBUFFER_TOKEN or // SECBUFFER_PADDING containing signature, padding, or other extra data from encryption process that doesn't fit // in first buffer SECURITY_STATUS err; PyObject *obdesc; PSecBufferDesc psecbufferdesc; ULONG fqop, seq_no; CHECK_SECURITYFUNCTIONTABLE(DecryptMessage); if (!PyArg_ParseTuple(args, "Ol:DecryptMessage", &obdesc, &seq_no)) return NULL; if (!PyWinObject_AsSecBufferDesc(obdesc, &psecbufferdesc, FALSE)) return NULL; PCtxtHandle pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->DecryptMessage)(pctxt, psecbufferdesc, seq_no, &fqop); Py_END_ALLOW_THREADS((PySecBufferDesc *)obdesc)->modify_in_place(); if (err == SEC_E_OK) return Py_BuildValue("l", fqop); PyWin_SetAPIError("DecryptMessage", err); return NULL; } // @pymethod long|PyCtxtHandle|Detach|Disassociates object from handle and returns integer value of handle // @comm Use when the security context needs to persist beyond the lifetime of the Python object PyObject *PyCtxtHandle::Detach(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":Detach")) return NULL; PyCtxtHandle *This = (PyCtxtHandle *)self; PCtxtHandle pctxthandle = This->GetCtxtHandle(); PyObject *ret = PyWinObject_FromSecHandle(pctxthandle); if (ret != NULL) SecInvalidateHandle(pctxthandle); return ret; } // @pymethod |PyCtxtHandle|DeleteSecurityContext|Frees the security context and invalidates the handle PyObject *PyCtxtHandle::DeleteSecurityContext(PyObject *self, PyObject *args) { CHECK_SECURITYFUNCTIONTABLE(DeleteSecurityContext); if (!PyArg_ParseTuple(args, ":DeleteSecurityContext")) return NULL; PyCtxtHandle *This = (PyCtxtHandle *)self; PCtxtHandle pctxt = This->GetCtxtHandle(); SECURITY_STATUS err = (*psecurityfunctiontable->DeleteSecurityContext)(pctxt); if (err != SEC_E_OK) { PyWin_SetAPIError("DeleteSecurityContext", err); return NULL; } SecInvalidateHandle(pctxt); Py_INCREF(Py_None); return Py_None; } // @pymethod |PyCtxtHandle|CompleteAuthToken|Completes the authentication token // @comm This method should be invoked on a context handle if the InitializeSecurityContext call that created it // returned SEC_I_COMPLETE_NEEDED or SEC_I_COMPLETE_AND_CONTINUE PyObject *PyCtxtHandle::CompleteAuthToken(PyObject *self, PyObject *args) { PCtxtHandle pctxt; PSecBufferDesc psecbufferdesc; PyObject *obsecbufferdesc; SECURITY_STATUS err; CHECK_SECURITYFUNCTIONTABLE(CompleteAuthToken); // @pyparm <o PySecBufferDesc>|Token||The buffer that contains the token buffer used when the context was // initialized if (!PyArg_ParseTuple(args, "O:CompleteAuthToken", &obsecbufferdesc)) return NULL; if (!PyWinObject_AsSecBufferDesc(obsecbufferdesc, &psecbufferdesc, FALSE)) return NULL; pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->CompleteAuthToken)(pctxt, psecbufferdesc); Py_END_ALLOW_THREADS if (err == SEC_E_OK) { Py_INCREF(Py_None); return Py_None; } PyWin_SetAPIError("CompleteAuthToken", err); return NULL; } // @pymethod |PyCtxtHandle|QueryContextAttributes|Retrieves info about a security context PyObject *PyCtxtHandle::QueryContextAttributes(PyObject *self, PyObject *args) { SECURITY_STATUS err; PCtxtHandle pctxt; BYTE buf[256]; ZeroMemory(&buf, 256); ULONG attr; PyObject *ret = NULL; CHECK_SECURITYFUNCTIONTABLE(QueryContextAttributesW); // @pyparm int|Attribute||SECPKG_ATTR_* constant if (!PyArg_ParseTuple(args, "l:QueryContextAttributes", &attr)) return NULL; pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->QueryContextAttributesW)(pctxt, attr, &buf); Py_END_ALLOW_THREADS if (err != SEC_E_OK) { PyWin_SetAPIError("QueryContextAttributes", err); return NULL; } // @comm Not all attributes are available for every security package // @flagh Attribute|Return type switch (attr) { // @flag SECPKG_ATTR_ACCESS_TOKEN|<o PyHANDLE> - returns a handle to the context's access token case SECPKG_ATTR_ACCESS_TOKEN: ret = PyWinObject_FromHANDLE(((PSecPkgContext_AccessToken)&buf)->AccessToken); break; // @flag SECPKG_ATTR_AUTHORITY|<o PyUnicode> - returns the name of the authenticating entity case SECPKG_ATTR_AUTHORITY: ret = PyWinObject_FromWCHAR(((PSecPkgContext_AuthorityW)&buf)->sAuthorityName); (*psecurityfunctiontable->FreeContextBuffer)(((PSecPkgContext_AuthorityW)&buf)->sAuthorityName); break; // @flag SECPKG_ATTR_CIPHER_STRENGTHS|(int,int) - returns the mininum and maximum cipher strengths allowed case SECPKG_ATTR_CIPHER_STRENGTHS: PSecPkgCred_CipherStrengths cs; cs = (PSecPkgCred_CipherStrengths)&buf; ret = Py_BuildValue("ll", cs->dwMinimumCipherStrength, cs->dwMaximumCipherStrength); break; // @flag SECPKG_ATTR_CONNECTION_INFO|Returns a dictionary of connection info representing a // SecPkgContext_ConnectionInfo struct case SECPKG_ATTR_CONNECTION_INFO: PSecPkgContext_ConnectionInfo ci; ci = (PSecPkgContext_ConnectionInfo)&buf; ret = Py_BuildValue("{s:l,s:l,s:l,s:l,s:l,s:l,s:l}", "Protocol", ci->dwProtocol, "Cipher", ci->aiCipher, "CipherStrength", ci->dwCipherStrength, "Hash", ci->aiHash, "HashStrength", ci->dwHashStrength, "Exch", ci->aiExch, "ExchStrength", ci->dwExchStrength); break; // @flag SECPKG_ATTR_SESSION_KEY|string - returns the session key for the context case SECPKG_ATTR_SESSION_KEY: PSecPkgContext_SessionKey sk; sk = (PSecPkgContext_SessionKey)&buf; ret = PyString_FromStringAndSize((const char *)sk->SessionKey, sk->SessionKeyLength); (*psecurityfunctiontable->FreeContextBuffer)(sk->SessionKey); break; // @flag SECPKG_ATTR_ISSUER_LIST_EX|(int, string) - Returns names of trusted certificate issuers case SECPKG_ATTR_ISSUER_LIST_EX: PSecPkgContext_IssuerListInfoEx li; li = (PSecPkgContext_IssuerListInfoEx)&buf; ret = Py_BuildValue("lN", li->cIssuers, PyString_FromStringAndSize((char *)li->aIssuers->pbData, li->aIssuers->cbData)); (*psecurityfunctiontable->FreeContextBuffer)(li->aIssuers); break; // @flag SECPKG_ATTR_FLAGS|int - returns flags negotiated when context was established case SECPKG_ATTR_FLAGS: ret = PyLong_FromUnsignedLong(((PSecPkgContext_Flags)&buf)->Flags); break; // @flag SECPKG_ATTR_PACKAGE_INFO|dict - returns dictionary containing info for context's security package case SECPKG_ATTR_PACKAGE_INFO: PSecPkgContext_PackageInfoW pi; pi = (PSecPkgContext_PackageInfoW)&buf; ret = PyWinObject_FromSecPkgInfo(pi->PackageInfo); (*psecurityfunctiontable->FreeContextBuffer)(pi->PackageInfo); break; // @flag SECPKG_ATTR_NEGOTIATION_INFO|(int, dict) - returns state of negotiation (SECPKG_NEGOTIATION_COMPLETE, // SECPKG_NEGOTIATION_OPTIMISTIC,SECPKG_NEGOTIATION_IN_PROGRESS) and info for negotiated package case SECPKG_ATTR_NEGOTIATION_INFO: PSecPkgContext_NegotiationInfoW ni; ni = (PSecPkgContext_NegotiationInfoW)&buf; ret = Py_BuildValue("lN", ni->NegotiationState, PyWinObject_FromSecPkgInfo(ni->PackageInfo)); (*psecurityfunctiontable->FreeContextBuffer)(ni->PackageInfo); break; // @flag SECPKG_ATTR_NAMES|<o PyUnicode> - returns the user name for the context case SECPKG_ATTR_NAMES: ret = PyWinObject_FromWCHAR(((PSecPkgContext_NamesW)&buf)->sUserName); (*psecurityfunctiontable->FreeContextBuffer)(((PSecPkgContext_NamesW)&buf)->sUserName); break; // @flag SECPKG_ATTR_SIZES|dict containing buffer sizes to be used with the context case SECPKG_ATTR_SIZES: PSecPkgContext_Sizes sz; sz = (PSecPkgContext_Sizes)&buf; ret = Py_BuildValue("{s:l,s:l,s:l,s:l}", "MaxToken", sz->cbMaxToken, "MaxSignature", sz->cbMaxSignature, "BlockSize", sz->cbBlockSize, "SecurityTrailer", sz->cbSecurityTrailer); break; // @flag SECPKG_ATTR_PASSWORD_EXPIRY|<o PyTime> - returns time password expires case SECPKG_ATTR_PASSWORD_EXPIRY: PSecPkgContext_PasswordExpiry pe; pe = (PSecPkgContext_PasswordExpiry)&buf; ret = PyWinObject_FromTimeStamp(pe->tsPasswordExpires); break; // @flag SECPKG_ATTR_LIFESPAN|(<o PyTime>,<o PyTime>) - returns time period during which context is valid case SECPKG_ATTR_LIFESPAN: PSecPkgContext_Lifespan ls; ls = (PSecPkgContext_Lifespan)&buf; ret = Py_BuildValue("NN", PyWinObject_FromTimeStamp(ls->tsStart), PyWinObject_FromTimeStamp(ls->tsExpiry)); break; // @flag SECPKG_ATTR_NATIVE_NAMES|(<o PyUnicode>,<o PyUnicode>) - returns client and server names case SECPKG_ATTR_NATIVE_NAMES: PSecPkgContext_NativeNamesW nn; nn = (PSecPkgContext_NativeNamesW)&buf; ret = Py_BuildValue("NN", PyWinObject_FromWCHAR(nn->sClientName), PyWinObject_FromWCHAR(nn->sServerName)); (*psecurityfunctiontable->FreeContextBuffer)(nn->sClientName); (*psecurityfunctiontable->FreeContextBuffer)(nn->sServerName); break; // @flag SECPKG_ATTR_TARGET_INFORMATION|string - returns the target for the context case SECPKG_ATTR_TARGET_INFORMATION: PSecPkgContext_TargetInformation ti; ti = (PSecPkgContext_TargetInformation)&buf; ret = PyString_FromStringAndSize((const char *)ti->MarshalledTargetInfo, ti->MarshalledTargetInfoLength); (*psecurityfunctiontable->FreeContextBuffer)(ti->MarshalledTargetInfo); break; // @flag SECPKG_ATTR_STREAM_SIZES|dict (see SecPkgContext_StreamSizes) containing message buffer sizes case SECPKG_ATTR_STREAM_SIZES: PSecPkgContext_StreamSizes ss; ss = (PSecPkgContext_StreamSizes)buf; ret = Py_BuildValue("{s:l,s:l,s:l,s:l,s:l}", "Header", ss->cbHeader, "Trailer", ss->cbTrailer, "MaximumMessage", ss->cbMaximumMessage, "Buffers", ss->cBuffers, "BlockSize", ss->cbBlockSize); break; // @flag SECPKG_ATTR_KEY_INFO|dict (see SecPkgContext_KeyInfo) containing encryption key parameters case SECPKG_ATTR_KEY_INFO: PSecPkgContext_KeyInfo ki; ki = (PSecPkgContext_KeyInfo)&buf; ret = Py_BuildValue("{s:u,s:u,s:l,s:l,s:l}", "SignatureAlgorithmName", ki->sSignatureAlgorithmName, "EncryptAlgorithmName", ki->sEncryptAlgorithmName, "KeySize", ki->KeySize, "SignatureAlgorithm", ki->SignatureAlgorithm, "EncryptAlgorithm", ki->EncryptAlgorithm); (*psecurityfunctiontable->FreeContextBuffer)(ki->sSignatureAlgorithmName); (*psecurityfunctiontable->FreeContextBuffer)(ki->sEncryptAlgorithmName); break; // @flag SECPKG_ATTR_DCE_INFO|not supported yet case SECPKG_ATTR_DCE_INFO: // SecPkgContext_DceInfo // @flag SECPKG_ATTR_LOCAL_CERT_CONTEXT|not supported yet case SECPKG_ATTR_LOCAL_CERT_CONTEXT: // PCCERT_CONTEXT // @flag SECPKG_ATTR_REMOTE_CERT_CONTEXT|not supported yet case SECPKG_ATTR_REMOTE_CERT_CONTEXT: // PCCERT_CONTEXT // @flag SECPKG_ATTR_ROOT_STORE|not supported yet case SECPKG_ATTR_ROOT_STORE: // HCERTCONTEXT // @flag SECPKG_ATTR_SUPPORTED_ALGS|not supported yet case SECPKG_ATTR_SUPPORTED_ALGS: // SecPkgCred_SupportedAlgs // @flag SECPKG_ATTR_SUPPORTED_PROTOCOLS|not supported yet case SECPKG_ATTR_SUPPORTED_PROTOCOLS: // SecPkgCred_SupportedProtocols default: PyErr_SetString(PyExc_NotImplementedError, "Attribute is not supported yet"); } return ret; } // @pymethod <o PyHandle>|PyCtxtHandle|QuerySecurityContextToken|Returns the access token for a security context PyObject *PyCtxtHandle::QuerySecurityContextToken(PyObject *self, PyObject *args) { SECURITY_STATUS err; PCtxtHandle pctxt; HANDLE htoken; CHECK_SECURITYFUNCTIONTABLE(QuerySecurityContextToken); if (!PyArg_ParseTuple(args, ":QuerySecurityContextToken")) return NULL; pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->QuerySecurityContextToken)(pctxt, &htoken); Py_END_ALLOW_THREADS if (err == SEC_E_OK) return PyWinObject_FromHANDLE(htoken); PyWin_SetAPIError("QuerySecurityContextToken", err); return NULL; } // @pymethod |PyCtxtHandle|ImpersonateSecurityContext|Impersonates a client security context PyObject *PyCtxtHandle::ImpersonateSecurityContext(PyObject *self, PyObject *args) { CHECK_SECURITYFUNCTIONTABLE(ImpersonateSecurityContext); PCtxtHandle pctxt; SECURITY_STATUS err; if (!PyArg_ParseTuple(args, ":ImpersonateSecurityContext")) return NULL; pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->ImpersonateSecurityContext)(pctxt); Py_END_ALLOW_THREADS if (err == SEC_E_OK) { Py_INCREF(Py_None); return Py_None; } PyWin_SetAPIError("ImpersonateSecurityContext", err); return NULL; } // @pymethod |PyCtxtHandle|RevertSecurityContext|Stops impersonation of client context (see <om // PyCtxtHandle::ImpersonateSecurityContext>) PyObject *PyCtxtHandle::RevertSecurityContext(PyObject *self, PyObject *args) { CHECK_SECURITYFUNCTIONTABLE(RevertSecurityContext); PCtxtHandle pctxt; SECURITY_STATUS err; if (!PyArg_ParseTuple(args, ":RevertSecurityContext")) return NULL; pctxt = ((PyCtxtHandle *)self)->GetCtxtHandle(); Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->RevertSecurityContext)(pctxt); Py_END_ALLOW_THREADS if (err == SEC_E_OK) { Py_INCREF(Py_None); return Py_None; } PyWin_SetAPIError("RevertSecurityContext", err); return NULL; } //////////////////////////////////////////////////////////////////////// // // PyCredHandle // //////////////////////////////////////////////////////////////////////// PyObject *PyWinObject_FromSecPkgInfo(PSecPkgInfoW psecpkginfo) { return Py_BuildValue("{s:l,s:l,s:l,s:l,s:u,s:u}", "Capabilities", psecpkginfo->fCapabilities, "Version", psecpkginfo->wVersion, "RPCID", psecpkginfo->wRPCID, "MaxToken", psecpkginfo->cbMaxToken, "Name", psecpkginfo->Name, "Comment", psecpkginfo->Comment); } // @object PyCredHandle|Handle to a set of logon credentials, used with sspi authentication functions // @comm This object is usually created using <om win32security.AcquireCredentialsHandle>. // An uninitialized handle can also be created using win32security.PyCredHandleType() struct PyMethodDef PyCredHandle::methods[] = { {"Detach", PyCredHandle::Detach, 1}, // @pymeth Detach|Disassociates object from handle and returns integer value of handle (prevents automatic // freeing of credentials when object is deallocated), {"FreeCredentialsHandle", PyCredHandle::FreeCredentialsHandle, 1}, // @pymeth FreeCredentialsHandle|Releases the credentials handle {"QueryCredentialsAttributes", PyCredHandle::QueryCredentialsAttributes, 1}, // @pymeth QueryCredentialsAttributes|Returns information about the credentials {NULL}}; PyTypeObject PyCredHandleType = { PYWIN_OBJECT_HEAD "PyCredHandle", sizeof(PyCredHandle), 0, PyCredHandle::deallocFunc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // PyNumberMethods *tp_as_number 0, // PySequenceMethods *tp_as_sequence 0, // PyMappingMethods *tp_as_mapping 0, // hashfunc tp_hash 0, // tp_call 0, // tp_str PyObject_GenericGetAttr, // tp_getattro PyObject_GenericSetAttr, // tp_setattro 0, // PyBufferProcs *tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags 0, // tp_doc 0, // traverseproc tp_traverse 0, // tp_clear 0, // richcmpfunc tp_richcompare 0, // tp_weaklistoffset 0, // getiterfunc tp_iter 0, // iternextfunc tp_iternext PyCredHandle::methods, NULL, 0, // tp_getset; 0, // tp_base; 0, // tp_dict; 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc PyCredHandle::tp_new // newfunc tp_new; }; PyCredHandle::PyCredHandle(PCredHandle pcredhandle) { ob_type = &PyCredHandleType; credhandle = *pcredhandle; _Py_NewReference(this); } PyCredHandle::PyCredHandle(void) { ob_type = &PyCredHandleType; SecInvalidateHandle(&credhandle); _Py_NewReference(this); } PyCredHandle::~PyCredHandle() { if (SecIsValidHandle(&credhandle)) (*psecurityfunctiontable->FreeCredentialsHandle)(&credhandle); } BOOL PyCredHandle_Check(PyObject *ob) { if (ob->ob_type != &PyCredHandleType) { PyErr_SetString(PyExc_TypeError, "Object must be a PyCredHandle"); return FALSE; } return TRUE; } void PyCredHandle::deallocFunc(PyObject *ob) { delete (PyCredHandle *)ob; } PCredHandle PyCredHandle::GetCredHandle(void) { return &credhandle; } PyObject *PyCredHandle::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwargs) { return new PyCredHandle(); } BOOL PyWinObject_AsCredHandle(PyObject *ob, PCredHandle *pcredhandle, BOOL bNoneOk) { if (ob == Py_None) { if (bNoneOk) { *pcredhandle = NULL; return TRUE; } PyErr_SetString(PyExc_ValueError, "Credentials handle cannot be NULL"); return FALSE; } if (!PyCredHandle_Check(ob)) return FALSE; *pcredhandle = ((PyCredHandle *)ob)->GetCredHandle(); return TRUE; } PyObject *PyWinObject_FromCredHandle(PCredHandle pcredhandle) { return new PyCredHandle(pcredhandle); } // @pymethod long|PyCredHandle|Detach|Disassociates object from handle and returns integer value of handle, PyObject *PyCredHandle::Detach(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":Detach")) return NULL; PyCredHandle *This = (PyCredHandle *)self; PCredHandle pcredhandle = This->GetCredHandle(); PyObject *ret = PyWinObject_FromSecHandle(pcredhandle); if (ret != NULL) SecInvalidateHandle(pcredhandle); return ret; } // @pymethod |PyCredHandle|FreeCredentialsHandle|Releases the credentials handle and makes object unusable PyObject *PyCredHandle::FreeCredentialsHandle(PyObject *self, PyObject *args) { CHECK_SECURITYFUNCTIONTABLE(FreeCredentialsHandle); if (!PyArg_ParseTuple(args, ":FreeCredentialsHandle")) return NULL; PyCredHandle *This = (PyCredHandle *)self; PCredHandle pcredhandle = This->GetCredHandle(); SECURITY_STATUS err = (*psecurityfunctiontable->FreeCredentialsHandle)(pcredhandle); if (err != SEC_E_OK) { PyWin_SetAPIError("FreeCredentialsHandle", err); return NULL; } SecInvalidateHandle(pcredhandle); Py_INCREF(Py_None); return Py_None; } // @pymethod |PyCredHandle|QueryCredentialsAttributes|Returns information about the credentials // @rdesc Type of returned values is dependent on Attribute PyObject *PyCredHandle::QueryCredentialsAttributes(PyObject *self, PyObject *args) { // @pyparm int|Attribute||SECPKG_* constant specifying which type of information to return // @comm Only SECPKG_CRED_ATTR_NAMES currently supported ULONG attr; SECURITY_STATUS err; PyObject *ret = NULL; BYTE buf[32]; CHECK_SECURITYFUNCTIONTABLE(QueryCredentialsAttributesW); PyCredHandle *This = (PyCredHandle *)self; PCredHandle pcredhandle = This->GetCredHandle(); if (!PyArg_ParseTuple(args, "l:QueryCredentialsAttributes", &attr)) return NULL; Py_BEGIN_ALLOW_THREADS err = (*psecurityfunctiontable->QueryCredentialsAttributesW)(pcredhandle, attr, &buf); Py_END_ALLOW_THREADS if (err != SEC_E_OK) { PyWin_SetAPIError("QueryCredentialsAttributes", err); return NULL; } // @flagh Attribute|Return type switch (attr) { // @flag SECPKG_CRED_ATTR_NAMES|<o PyUnicode> - returns username that credentials represent case SECPKG_CRED_ATTR_NAMES: PSecPkgCredentials_NamesW cn; cn = (PSecPkgCredentials_NamesW)&buf; ret = PyWinObject_FromWCHAR(cn->sUserName); (*psecurityfunctiontable->FreeContextBuffer)(cn->sUserName); break; // @flag SECPKG_ATTR_SUPPORTED_ALGS|Not supported yet case SECPKG_ATTR_SUPPORTED_ALGS: // SecPkgCred_SupportedAlgs: // @flag SECPKG_ATTR_CIPHER_STRENGTHS|Not supported yet case SECPKG_ATTR_CIPHER_STRENGTHS: // SecPkgCred_CipherStrengths: // @flag SECPKG_ATTR_SUPPORTED_PROTOCOLS|Not supported yet case SECPKG_ATTR_SUPPORTED_PROTOCOLS: // SecPkgCred_SupportedProtocols: default: PyErr_SetString(PyExc_NotImplementedError, "Attribute is not supported yet"); } return ret; }
44.728785
120
0.641321
huanyin88
e70defc77324a44a3c116a3d5fe07b70951abb2b
20,149
cpp
C++
dev/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
1
2020-03-24T04:54:22.000Z
2020-03-24T04:54:22.000Z
dev/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
null
null
null
dev/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Search/Filter.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
2
2019-07-09T00:03:08.000Z
2020-03-24T04:54:27.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzCore/Asset/AssetTypeInfoBus.h> #include <AzFramework/StringFunc/StringFunc.h> #include <AzToolsFramework/AssetBrowser/Search/Filter.h> #include <AzToolsFramework/AssetBrowser/AssetBrowserEntry.h> #include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h> #include <AzToolsFramework/AssetBrowser/EBusFindAssetTypeByName.h> namespace AzToolsFramework { namespace AssetBrowser { namespace { bool StringMatch(const QString& searched, const QString& text) { return text.contains(searched, Qt::CaseInsensitive); } //! Intersect operation between two sets which then overwrites result void Intersect(AZStd::vector<const AssetBrowserEntry*>& result, AZStd::vector<const AssetBrowserEntry*>& set) { // inefficient, but sets are tiny so probably not worth the optimization effort AZStd::vector<const AssetBrowserEntry*> intersection; for (auto entry : result) { if (AZStd::find(set.begin(), set.end(), entry) != set.end()) { intersection.push_back(entry); } } result = intersection; } //! Insert an entry if it doesn't already exist void Join(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) { if (AZStd::find(result.begin(), result.end(), entry) == result.end()) { result.push_back(entry); } } //! Join operation between two sets which then overwrites result void Join(AZStd::vector<const AssetBrowserEntry*>& result, AZStd::vector<const AssetBrowserEntry*>& set) { AZStd::vector<const AssetBrowserEntry*> unionResult; for (auto entry : set) { Join(result, entry); } } //! Expand all children recursively and write to result void ExpandDown(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) { Join(result, entry); AZStd::vector<const AssetBrowserEntry*> children; entry->GetChildren<AssetBrowserEntry>(children); for (auto child : children) { ExpandDown(result, child); } } //! Expand all entries that are either parent or child relationship to the entry and write to result void Expand(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) { auto parent = entry->GetParent(); while (parent && parent->GetEntryType() != AssetBrowserEntry::AssetEntryType::Root) { Join(result, parent); parent = parent->GetParent(); } ExpandDown(result, entry); } } ////////////////////////////////////////////////////////////////////////// // AssetBrowserEntryFilter ////////////////////////////////////////////////////////////////////////// AssetBrowserEntryFilter::AssetBrowserEntryFilter() : m_direction(None) { } bool AssetBrowserEntryFilter::Match(const AssetBrowserEntry* entry) const { if (MatchInternal(entry)) { return true; } if (m_direction & Up) { auto parent = entry->GetParent(); while (parent && parent->GetEntryType() != AssetBrowserEntry::AssetEntryType::Root) { if (MatchInternal(parent)) { return true; } parent = parent->GetParent(); } } if (m_direction & Down) { AZStd::vector<const AssetBrowserEntry*> children; entry->GetChildren<AssetBrowserEntry>(children); for (auto child : children) { if (MatchDown(child)) { return true; } } } return false; } void AssetBrowserEntryFilter::Filter(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) const { FilterInternal(result, entry); if (m_direction & Up) { auto parent = entry->GetParent(); while (parent && parent->GetEntryType() != AssetBrowserEntry::AssetEntryType::Root) { FilterInternal(result, parent); parent = parent->GetParent(); } } if (m_direction & Down) { AZStd::vector<const AssetBrowserEntry*> children; entry->GetChildren<AssetBrowserEntry>(children); for (auto child : children) { FilterDown(result, child); } } } QString AssetBrowserEntryFilter::GetName() const { return m_name.isEmpty() ? GetNameInternal() : m_name; } void AssetBrowserEntryFilter::SetName(const QString& name) { m_name = name; } const QString& AssetBrowserEntryFilter::GetTag() const { return m_tag; } void AssetBrowserEntryFilter::SetTag(const QString& tag) { m_tag = tag; } void AssetBrowserEntryFilter::SetFilterPropagation(int direction) { m_direction = direction; } void AssetBrowserEntryFilter::FilterInternal(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) const { if (MatchInternal(entry)) { Join(result, entry); } } bool AssetBrowserEntryFilter::MatchDown(const AssetBrowserEntry* entry) const { if (MatchInternal(entry)) { return true; } AZStd::vector<const AssetBrowserEntry*> children; entry->GetChildren<AssetBrowserEntry>(children); for (auto child : children) { if (MatchDown(child)) { return true; } } return false; } void AssetBrowserEntryFilter::FilterDown(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) const { if (MatchInternal(entry)) { Join(result, entry); } AZStd::vector<const AssetBrowserEntry*> children; entry->GetChildren<AssetBrowserEntry>(children); for (auto child : children) { FilterDown(result, child); } } ////////////////////////////////////////////////////////////////////////// // StringFilter ////////////////////////////////////////////////////////////////////////// StringFilter::StringFilter() : m_filterString("") {} void StringFilter::SetFilterString(const QString& filterString) { m_filterString = filterString; Q_EMIT updatedSignal(); } QString StringFilter::GetNameInternal() const { return m_filterString; } bool StringFilter::MatchInternal(const AssetBrowserEntry* entry) const { // no filter string matches any asset if (m_filterString.isEmpty()) { return true; } // entry's name matches search pattern if (StringMatch(m_filterString, entry->GetDisplayName().c_str())) { return true; } return false; } ////////////////////////////////////////////////////////////////////////// // AssetTypeFilter ////////////////////////////////////////////////////////////////////////// AssetTypeFilter::AssetTypeFilter() : m_assetType(AZ::Data::AssetType::CreateNull()) {} void AssetTypeFilter::SetAssetType(AZ::Data::AssetType assetType) { m_assetType = assetType; Q_EMIT updatedSignal(); } void AssetTypeFilter::SetAssetType(const char* assetTypeName) { EBusFindAssetTypeByName result(assetTypeName); AZ::AssetTypeInfoBus::BroadcastResult(result, &AZ::AssetTypeInfo::GetAssetType); SetAssetType(result.GetAssetType()); } AZ::Data::AssetType AssetTypeFilter::GetAssetType() const { return m_assetType; } QString AssetTypeFilter::GetNameInternal() const { QString name; AZ::AssetTypeInfoBus::EventResult(name, m_assetType, &AZ::AssetTypeInfo::GetAssetTypeDisplayName); return name; } bool AssetTypeFilter::MatchInternal(const AssetBrowserEntry* entry) const { // this filter only works on products. if (entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product) { if (m_assetType.IsNull()) { return true; } if (static_cast<const ProductAssetBrowserEntry*>(entry)->GetAssetType() == m_assetType) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// // AssetGroupFilter ////////////////////////////////////////////////////////////////////////// AssetGroupFilter::AssetGroupFilter() : m_group("All") { } void AssetGroupFilter::SetAssetGroup(const QString& group) { m_group = group; } const QString& AssetGroupFilter::GetAssetTypeGroup() const { return m_group; } QString AssetGroupFilter::GetNameInternal() const { return m_group; } bool AssetGroupFilter::MatchInternal(const AssetBrowserEntry* entry) const { // this filter only works on products. if (entry->GetEntryType() != AssetBrowserEntry::AssetEntryType::Product) { return false; } if (m_group.compare("All", Qt::CaseInsensitive) == 0) { return true; } auto product = static_cast<const ProductAssetBrowserEntry*>(entry); QString group; AZ::AssetTypeInfoBus::EventResult(group, product->GetAssetType(), &AZ::AssetTypeInfo::GetGroup); if (m_group.compare("Other", Qt::CaseInsensitive) == 0 && group.isEmpty()) { return true; } return (m_group.compare(group, Qt::CaseInsensitive) == 0); } ////////////////////////////////////////////////////////////////////////// // EntryTypeFilter ////////////////////////////////////////////////////////////////////////// EntryTypeFilter::EntryTypeFilter() : m_entryType(AssetBrowserEntry::AssetEntryType::Product) {} void EntryTypeFilter::SetEntryType(AssetBrowserEntry::AssetEntryType entryType) { m_entryType = entryType; } AssetBrowserEntry::AssetEntryType EntryTypeFilter::GetEntryType() const { return m_entryType; } QString EntryTypeFilter::GetNameInternal() const { return AssetBrowserEntry::AssetEntryTypeToString(m_entryType); } bool EntryTypeFilter::MatchInternal(const AssetBrowserEntry* entry) const { return entry->GetEntryType() == m_entryType; } ////////////////////////////////////////////////////////////////////////// // CompositeFilter ////////////////////////////////////////////////////////////////////////// CompositeFilter::CompositeFilter(LogicOperatorType logicOperator) : m_logicOperator(logicOperator) , m_emptyResult(true) {} void CompositeFilter::AddFilter(FilterConstType filter) { connect(filter.data(), &AssetBrowserEntryFilter::updatedSignal, this, &AssetBrowserEntryFilter::updatedSignal, Qt::UniqueConnection); m_subFilters.append(filter); Q_EMIT updatedSignal(); } void CompositeFilter::RemoveFilter(FilterConstType filter) { if (m_subFilters.removeAll(filter)) { Q_EMIT updatedSignal(); } } void CompositeFilter::RemoveAllFilters() { m_subFilters.clear(); Q_EMIT updatedSignal(); } void CompositeFilter::SetLogicOperator(LogicOperatorType logicOperator) { m_logicOperator = logicOperator; Q_EMIT updatedSignal(); } const QList<FilterConstType>& CompositeFilter::GetSubFilters() const { return m_subFilters; } void CompositeFilter::SetEmptyResult(bool result) { if (m_emptyResult != result) { m_emptyResult = result; Q_EMIT updatedSignal(); } } QString CompositeFilter::GetNameInternal() const { QString name = ""; for (auto it = m_subFilters.begin(); it != m_subFilters.end(); ++it) { name += (*it)->GetName(); if (AZStd::next(it) != m_subFilters.end()) { name += ", "; } } return name; } bool CompositeFilter::MatchInternal(const AssetBrowserEntry* entry) const { if (m_subFilters.count() == 0) { return m_emptyResult; } // AND if (m_logicOperator == LogicOperatorType::AND) { for (auto filter : m_subFilters) { if (!filter->Match(entry)) { return false; } } return true; } // OR for (auto filter : m_subFilters) { if (filter->Match(entry)) { return true; } } return false; } void CompositeFilter::FilterInternal(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) const { // if no subfilters are present in this composite filter then all relating entries would match if (m_subFilters.isEmpty()) { // only if match on empty filter is success if (m_emptyResult) { Expand(result, entry); } return; } // AND if (m_logicOperator == LogicOperatorType::AND) { AZStd::vector<const AssetBrowserEntry*> andResult; bool firstResult = true; for (auto filter : m_subFilters) { if (firstResult) { firstResult = false; filter->Filter(andResult, entry); } else { AZStd::vector<const AssetBrowserEntry*> set; filter->Filter(set, entry); Intersect(andResult, set); } if (andResult.empty()) { break; } } Join(result, andResult); } // OR else { for (auto filter : m_subFilters) { AZStd::vector<const AssetBrowserEntry*> set; filter->Filter(set, entry); Join(result, set); } } } ////////////////////////////////////////////////////////////////////////// // InverseFilter ////////////////////////////////////////////////////////////////////////// InverseFilter::InverseFilter() {} void InverseFilter::SetFilter(FilterConstType filter) { if (m_filter == filter) { return; } m_filter = filter; Q_EMIT updatedSignal(); } QString InverseFilter::GetNameInternal() const { if (m_filter.isNull()) { QString name = tr("NOT"); } QString name = tr("NOT (%1)").arg(m_filter->GetName()); return name; } bool InverseFilter::MatchInternal(const AssetBrowserEntry* entry) const { if (m_filter.isNull()) { return false; } return !m_filter->Match(entry); } void InverseFilter::FilterInternal(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) const { if (MatchInternal(entry)) { Expand(result, entry); } } ////////////////////////////////////////////////////////////////////////// // CleanerProductsFilter ////////////////////////////////////////////////////////////////////////// CleanerProductsFilter::CleanerProductsFilter() {} QString CleanerProductsFilter::GetNameInternal() const { return QString(); } bool CleanerProductsFilter::MatchInternal(const AssetBrowserEntry* entry) const { auto product = azrtti_cast<const ProductAssetBrowserEntry*>(entry); if (!product) { return true; } auto source = product->GetParent(); if (!source) { return true; } if (source->GetChildCount() != 1) { return true; } AZStd::string assetTypeName; AZ::AssetTypeInfoBus::EventResult(assetTypeName, product->GetAssetType(), &AZ::AssetTypeInfo::GetAssetTypeDisplayName); if (!assetTypeName.empty()) { return true; } return false; } void CleanerProductsFilter::FilterInternal(AZStd::vector<const AssetBrowserEntry*>& result, const AssetBrowserEntry* entry) const { if (MatchInternal(entry)) { Expand(result, entry); } } } // namespace AssetBrowser } // namespace AzToolsFramework #include <AssetBrowser/Search/Filter.moc>
32.762602
145
0.475954
crazyskateface
e714bdb1b5f51ce212a87506c8a3fefea6ceb4ae
1,129
cpp
C++
DOJ/#699.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
DOJ/#699.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
DOJ/#699.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2022 */ #include <algorithm> #include <cstdio> #include <cstring> const int maxn = 1e6 + 10; int n, a[maxn]; class BIT { private: int v[maxn], bound; inline int lowbit(int x) { return x & -x; } public: inline void init(int n) { bound = n; memset(v, 0, sizeof(v)); } inline void add(int pos, int x) { for (int i = pos; i <= bound; i += lowbit(i)) v[i] = std::max(v[i], x); } inline int query(int pos) { int res = 0; for (int i = pos; i > 0; i -= lowbit(i)) res = std::max(res, v[i]); return res; } }tree; inline void solve() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i); tree.init(n); int ans = 0; for (int i = n, cur; i > 0; --i) { cur = tree.query(a[i]) + 1; ans = std::max(ans, cur); tree.add(a[i], cur); } printf("%d\n", ans); } int main() { int t; scanf("%d", &t); while (t--) solve(); return 0; }
16.602941
53
0.457927
Nickel-Angel
e71577990644b7ee9ca979e097096d87022d85f4
4,365
cpp
C++
Examples/PBD/PBDDeformableObject/PBD3DDeformableObject.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
2
2020-08-14T07:21:30.000Z
2021-08-30T09:39:09.000Z
Examples/PBD/PBDDeformableObject/PBD3DDeformableObject.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
null
null
null
Examples/PBD/PBDDeformableObject/PBD3DDeformableObject.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
1
2020-08-14T07:00:31.000Z
2020-08-14T07:00:31.000Z
/*========================================================================= Library: iMSTK Copyright (c) Kitware, Inc. & Center for Modeling, Simulation, & Imaging in Medicine, Rensselaer Polytechnic 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.txt 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 "imstkSimulationManager.h" #include "imstkMeshIO.h" #include "imstkPbdModel.h" #include "imstkPbdObject.h" #include "imstkPbdSolver.h" #include "imstkOneToOneMap.h" #include "imstkAPIUtilities.h" #include "imstkTetraTriangleMap.h" using namespace imstk; /// /// \brief This example demonstrates the soft body simulation /// using Position based dynamics /// int main() { auto simManager = std::make_shared<SimulationManager>(); auto scene = simManager->createNewScene("PBDVolume"); scene->getCamera()->setPosition(0, 2.0, 15.0); //auto surfMesh = std::dynamic_pointer_cast<SurfaceMesh>(MeshIO::read(iMSTK_DATA_ROOT "/asianDragon/asianDragon.obj")); //auto tetMesh = std::dynamic_pointer_cast<TetrahedralMesh>(MeshIO::read(iMSTK_DATA_ROOT "/asianDragon/asianDragon.veg")); auto surfMesh = std::dynamic_pointer_cast<SurfaceMesh>(MeshIO::read(iMSTK_DATA_ROOT "/vibe/3D_New/Stomach/tetra/stomach3/stomach.obj")); auto tetMesh = std::dynamic_pointer_cast<TetrahedralMesh>(MeshIO::read(iMSTK_DATA_ROOT "/vibe/3D_New/Stomach/tetra/stomach3/stomach.tet")); //auto tetMesh = TetrahedralMesh::createTetrahedralMeshCover(surfMesh, 10, 6, 6); auto map = std::make_shared<TetraTriangleMap>(tetMesh, surfMesh); auto material = std::make_shared<RenderMaterial>(); material->setDisplayMode(RenderMaterial::DisplayMode::WIREFRAME_SURFACE); auto surfMeshModel = std::make_shared<VisualModel>(surfMesh); surfMeshModel->setRenderMaterial(material); auto deformableObj = std::make_shared<PbdObject>("DeformableObject"); auto pbdModel = std::make_shared<PbdModel>(); pbdModel->setModelGeometry(tetMesh); // configure model auto pbdParams = std::make_shared<PBDModelConfig>(); // FEM constraint pbdParams->m_YoungModulus = 100.0; pbdParams->m_PoissonRatio = 0.3; pbdParams->m_fixedNodeIds = { 51, 127, 178 }; pbdParams->enableFEMConstraint(PbdConstraint::Type::FEMTet, PbdFEMConstraint::MaterialType::StVK); // Other parameters pbdParams->m_uniformMassValue = 1.0; pbdParams->m_gravity = Vec3d(0, -9.8, 0); pbdParams->m_maxIter = 45; // Set the parameters pbdModel->configure(pbdParams); pbdModel->setDefaultTimeStep(0.02); pbdModel->setTimeStepSizeType(imstk::TimeSteppingType::fixed); deformableObj->setDynamicalModel(pbdModel); deformableObj->addVisualModel(surfMeshModel); deformableObj->setPhysicsGeometry(tetMesh); deformableObj->setPhysicsToVisualMap(map); //assign the computed map deformableObj->setDynamicalModel(pbdModel); auto pbdSolver = std::make_shared<PbdSolver>(); pbdSolver->setPbdObject(deformableObj); scene->addNonlinearSolver(pbdSolver); scene->addSceneObject(deformableObj); // Setup plane auto planeGeom = std::make_shared<Plane>(); planeGeom->setWidth(40); planeGeom->setTranslation(0, -6, 0); auto planeObj = std::make_shared<CollidingObject>("Plane"); planeObj->setVisualGeometry(planeGeom); planeObj->setCollidingGeometry(planeGeom); scene->addSceneObject(planeObj); // Light auto light = std::make_shared<DirectionalLight>("light"); light->setFocalPoint(Vec3d(5, -8, -5)); light->setIntensity(1); scene->addLight(light); simManager->setActiveScene(scene); simManager->getViewer()->setBackgroundColors(Vec3d(0.3285, 0.3285, 0.6525), Vec3d(0.13836, 0.13836, 0.2748), true); simManager->start(SimulationStatus::paused); return 0; }
38.628319
140
0.705155
quantingxie
e71641642715a9a22f578b6d93a04bc9bc1280e4
8,458
cpp
C++
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/EnclaveIdentityParserUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/EnclaveIdentityParserUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
QuoteVerification/QVL/Src/AttestationLibrary/test/UnitTests/EnclaveIdentityParserUT.cpp
fqiu1/SGXDataCenterAttestationPrimitives
19483cca7b924f89ecfdb89e675d34d6a6d4b9dd
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2011-2020 Intel Corporation. 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <SgxEcdsaAttestation/QuoteVerification.h> #include <Verifiers/EnclaveReportVerifier.h> #include <Verifiers/EnclaveIdentityParser.h> #include <numeric> #include <iostream> #include <QuoteGenerator.h> #include <QuoteVerification/Quote.h> #include <EnclaveIdentityGenerator.h> using namespace testing; using namespace ::intel::sgx::qvl; using namespace std; struct EnclaveIdentityParserUT : public Test { EnclaveIdentityParser parser; }; TEST_F(EnclaveIdentityParserUT, shouldReturnStatusOkWhenJsonIsOk) { string json = qeIdentityJsonWithSignature(EnclaveIdentityVectorModel().toJSON()); auto result = parser.parse(json); ASSERT_EQ(STATUS_OK, result->getStatus()); } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectIsWrong) { EnclaveIdentityVectorModel model; model.miscselect = {{1, 1}}; string json = qeIdentityJsonWithSignature(qeIdentityJsonWithSignature(model.toJSON())); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenOptionalFieldIsInvalid) { EnclaveIdentityVectorModel model; string json = qeIdentityJsonWithSignature(model.toJSON()); removeWordFromString("mrenclave", json); removeWordFromString("mrsigner", json); removeWordFromString("isvprodid", json); removeWordFromString("isvsvn", json); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenVerionFieldIsInvalid) { EnclaveIdentityVectorModel model; string json = qeIdentityJsonWithSignature(model.toJSON()); removeWordFromString("version", json); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectHasIncorrectSize) { EnclaveIdentityVectorModel model; model.miscselect= {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectIsNotHexString) { EnclaveIdentityStringModel model; model.miscselect = "xyz00000"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectMaskHasIncorrectSize) { EnclaveIdentityVectorModel model; model.miscselectMask = {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenMiscselectMaskIsNotHexString) { EnclaveIdentityStringModel model; model.miscselectMask = "xyz00000"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesHasIncorrectSize) { EnclaveIdentityVectorModel model; model.attributes = {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesIsNotHexString) { EnclaveIdentityStringModel model; model.attributes = "xyz45678900000000000000123456789"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesMaskHasIncorrectSize) { EnclaveIdentityVectorModel model; model.attributesMask = {{1, 1}}; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenAttributesMaskIsNotHexString) { EnclaveIdentityStringModel model; model.attributesMask = "xyz45678900000000000000123456789"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenIssuedateIsWrong) { EnclaveIdentityStringModel model; model.issueDate = "2018-08-22T10:09:"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityInvalidWhenNextUpdateIsWrong) { EnclaveIdentityStringModel model; model.nextUpdate = "2018-08-22T10:09:"; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_INVALID, ex.getStatus()); } } TEST_F(EnclaveIdentityParserUT, shouldReturnEnclaveIdentityUnsuportedVersionWhenVersionIsWrong) { EnclaveIdentityVectorModel model; model.version = 5; string json = qeIdentityJsonWithSignature(model.toJSON()); try { parser.parse(json); FAIL(); } catch (const ParserException &ex) { EXPECT_EQ(STATUS_SGX_ENCLAVE_IDENTITY_UNSUPPORTED_VERSION, ex.getStatus()); } }
30.868613
101
0.72594
fqiu1
e7188320a896d638c6c7d376cdcebf593b1ff6c9
1,527
cc
C++
tensorflow/core/lib/core/refcount.cc
deepakmuralidharan/tensorflow
f40e41f9c71ef2865f96f3db3cea2909797fe2a3
[ "Apache-2.0" ]
23
2016-02-04T21:08:43.000Z
2022-01-14T13:22:33.000Z
tensorflow/core/lib/core/refcount.cc
deepakmuralidharan/tensorflow
f40e41f9c71ef2865f96f3db3cea2909797fe2a3
[ "Apache-2.0" ]
2
2016-05-31T16:38:55.000Z
2018-12-30T20:17:05.000Z
tensorflow/core/lib/core/refcount.cc
deepakmuralidharan/tensorflow
f40e41f9c71ef2865f96f3db3cea2909797fe2a3
[ "Apache-2.0" ]
20
2016-02-15T17:31:02.000Z
2020-01-12T08:18:48.000Z
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/lib/core/refcount.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace core { RefCounted::RefCounted() : ref_(1) {} RefCounted::~RefCounted() { DCHECK_EQ(ref_.load(), 0); } void RefCounted::Ref() const { DCHECK_GE(ref_.load(), 1); ref_.fetch_add(1, std::memory_order_relaxed); } bool RefCounted::Unref() const { DCHECK_GT(ref_.load(), 0); // If ref_==1, this object is owned only by the caller. Bypass a locked op // in that case. if (ref_.load(std::memory_order_acquire) == 1 || ref_.fetch_sub(1) == 1) { // Make DCHECK in ~RefCounted happy DCHECK((ref_.store(0), true)); delete this; return true; } else { return false; } } bool RefCounted::RefCountIsOne() const { return (ref_.load(std::memory_order_acquire) == 1); } } // namespace core } // namespace tensorflow
29.941176
80
0.681074
deepakmuralidharan
e71aba9f8bab732ff313e39ab5ad7e5b11169912
3,128
cpp
C++
src/core/errfloat.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
21
2016-12-14T09:46:27.000Z
2021-12-28T10:05:04.000Z
src/core/errfloat.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
2
2016-12-02T07:47:14.000Z
2018-01-30T18:11:09.000Z
src/core/errfloat.cpp
zq317157782/raiden
09376a9499f8b86e86c3049b4e654957cb4dc29e
[ "BSD-2-Clause" ]
null
null
null
/* * errfloat.cpp * * Created on: 2016年11月15日 * Author: zhuqian */ #include "errfloat.h" #include "mmath.h" EFloat::EFloat(float v, float err) : _value(v) { Assert(!std::isnan(v)); Assert(!std::isnan(err)); if (err == 0.0f) { _low = _high = v; } else { //这里调用NextFloatUp和NextFloatDown是为了做保守的边界 _low = NextFloatDown(v - err); _high = NextFloatUp(v + err); } #ifdef DEBUG _highPrecisionValue = _value; Check(); #endif } EFloat EFloat::operator+(EFloat f) const { EFloat result; result._value = _value + f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue + f._highPrecisionValue; #endif //这里调用NextFloatUp和NextFloatDown是为了做保守的边界 result._low = NextFloatDown(LowerBound() + f.LowerBound()); result._high = NextFloatUp(UpperBound() + f.UpperBound()); result.Check(); return result; } EFloat EFloat::operator-(EFloat f) const { EFloat result; result._value = _value - f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue - f._highPrecisionValue; #endif //这里调用NextFloatUp和NextFloatDown是为了做保守的边界 result._low = NextFloatDown(LowerBound() - f.UpperBound()); result._high = NextFloatUp(UpperBound() - f.LowerBound()); result.Check(); return result; } EFloat EFloat::operator*(EFloat f) const { EFloat result; result._value = _value * f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue * f._highPrecisionValue; #endif Float all[4] = { LowerBound() * f.LowerBound(), LowerBound() * f.UpperBound(), UpperBound() * f.LowerBound(), UpperBound() * f.UpperBound() }; result._low = NextFloatDown( std::min(std::min(all[0], all[1]), std::min(all[2], all[3]))); result._high = NextFloatUp( std::max(std::max(all[0], all[1]), std::max(all[2], all[3]))); result.Check(); return result; } EFloat EFloat::operator/(EFloat f) const { EFloat result; result._value = _value / f._value; #ifdef DEBUG result._highPrecisionValue = _highPrecisionValue / f._highPrecisionValue; #endif if (f._low < 0.0f && f._high > 0.0f) { //除以0的情况 result._low = -Infinity; result._high = Infinity; } else { Float all[4] = { LowerBound() / f.LowerBound(), LowerBound() / f.UpperBound(), UpperBound() / f.LowerBound(), UpperBound() / f.UpperBound() }; result._low = NextFloatDown( std::min(std::min(all[0], all[1]), std::min(all[2], all[3]))); result._high = NextFloatUp( std::max(std::max(all[0], all[1]), std::max(all[2], all[3]))); } result.Check(); return result; } EFloat EFloat::operator-() const{ EFloat result; result._value=-_value; #ifdef DEBUG result._highPrecisionValue = -_highPrecisionValue; #endif result._low=-_high; result._high=-_low; result.Check(); return result; } bool EFloat::operator==(EFloat f) const{ return _value==f._value; } EFloat::EFloat(const EFloat&f){ _value=f._value; #ifdef DEBUG _highPrecisionValue =f._highPrecisionValue; #endif _low=f._low; _high=f._high; Check(); } EFloat& EFloat::operator=(const EFloat&f){ _value=f._value; #ifdef DEBUG _highPrecisionValue =f._highPrecisionValue; #endif _low=f._low; _high=f._high; Check(); return *this; }
24.061538
74
0.691176
zq317157782
e71c1cc68f3ca93d3f5b0f0f3751f4ddd64da9b8
2,048
hpp
C++
src/utils/argvec.hpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
1
2019-01-27T17:54:45.000Z
2019-01-27T17:54:45.000Z
src/utils/argvec.hpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
src/utils/argvec.hpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
#pragma once #include "glm.hpp" namespace Math{ /* Vector with template specified dimension. * For operations on vectors use glm::vec */ template<typename _ValT, int _D> struct Component { _ValT data[_D]; }; // specializations for named access of the first 3 dimensions template<typename _ValT> struct Component<_ValT, 1> { union{ _ValT x; _ValT data[1]; }; }; template<typename _ValT> struct Component<_ValT, 2> { union{ struct{ _ValT x, y; }; _ValT data[2]; }; }; template<typename _ValT> struct Component<_ValT, 3> { union{ struct{ _ValT x, y, z; }; _ValT data[3]; }; }; //the actual vector class template<typename _ValT, int _D> struct ArgVec : public Component<_ValT, _D> { typedef Component<_ValT, _D> ST; ArgVec() { }; //construct with one arg for every dimension template<bool Enable = true, typename = typename std::enable_if< _D == 1 && Enable >::type> ArgVec(_ValT _x) { ST::x = _x; }; template<bool Enable = true, typename = typename std::enable_if< _D == 2 && Enable >::type> ArgVec(_ValT _x, _ValT _y){ ST::x = _x; ST::y = _y; }; template<bool Enable = true, typename = typename std::enable_if< _D == 3 && Enable >::type> ArgVec(_ValT _x, _ValT _y, _ValT _z){ ST::x = _x; ST::y = _y; ST::z = _z; }; // return value of _ind dimension _ValT operator[](size_t _ind) const { return ST::data[_ind]; } _ValT& operator[](size_t _ind) { return ST::data[_ind]; } template<typename _ValOther> _ValT distance(const ArgVec<_ValOther, _D>& _oth) const { _ValT ret = 0.f; for(int i = 0; i < _D; ++i) ret += (ST::data[i] - (_ValT)_oth[i]) * (ST::data[i] - (_ValT)_oth[i]); return sqrt(ret); } operator glm::vec2() const { return glm::vec2(ST::x, ST::y); } operator float() { return ST::x; } }; template<typename _ValT, int _D> auto operator*(float _lhs, ArgVec<_ValT, _D> _rhs) { for (int i = 0; i < _D; ++i) _rhs[i] *= _lhs; return _rhs; } //some common types typedef ArgVec<float, 2> AVec2; }
21.333333
93
0.625
Thanduriel
e71d768557ac348bb29d36f057abba6652af6877
1,299
cpp
C++
C++/Stack/421 Simplify Path.cpp
MuteMeteor/LintCode
8c73aa71fbd70409b9fc636a13a3fd6c4a387f62
[ "MIT" ]
null
null
null
C++/Stack/421 Simplify Path.cpp
MuteMeteor/LintCode
8c73aa71fbd70409b9fc636a13a3fd6c4a387f62
[ "MIT" ]
null
null
null
C++/Stack/421 Simplify Path.cpp
MuteMeteor/LintCode
8c73aa71fbd70409b9fc636a13a3fd6c4a387f62
[ "MIT" ]
null
null
null
/* Given an absolute path for a file (Unix-style), simplify it. Example "/home/", => "/home" "/a/./b/../../c/", => "/c" Challenge Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". */ class Solution { public: /** * @param path the original path * @return the simplified path */ string simplifyPath(string& path) { // Write your code here vector<string> dirs; auto i = path.begin(); while (i != path.end()) { auto j = find(i, path.end(), '/'); //find first string dir = string(i, j); //not include j if(dir.size() && dir != ".") { if(dir == "..") { if(dirs.size()) dirs.pop_back(); } else { dirs.push_back(dir); } } i = ( j == path.end() ? j : j + 1); //move forward } if(dirs.empty()) return "/"; string res; for(auto dir : dirs) res.append("/" + dir); return res; } };
25.98
100
0.470362
MuteMeteor
e72417f0a9cdfe753b1446becbcedd40d511174c
639
cpp
C++
externals/skia/third_party/externals/angle2/src/tests/deqp_support/angle_deqp_gtest_main.cpp
terrajobst/linux-packaging-skiasharp
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
[ "MIT" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
externals/skia/third_party/externals/angle2/src/tests/deqp_support/angle_deqp_gtest_main.cpp
terrajobst/linux-packaging-skiasharp
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
[ "MIT" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
externals/skia/third_party/externals/angle2/src/tests/deqp_support/angle_deqp_gtest_main.cpp
terrajobst/linux-packaging-skiasharp
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
[ "MIT" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// // Copyright 2015 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // angle_deqp_gtest_main: // Entry point for standalone dEQP tests. #include <gtest/gtest.h> // Defined in angle_deqp_gtest.cpp. Declared here so we don't need to make a header that we import // in Chromium. namespace angle { void InitTestHarness(int *argc, char **argv); } // namespace angle int main(int argc, char **argv) { angle::InitTestHarness(&argc, argv); testing::InitGoogleTest(&argc, argv); int rt = RUN_ALL_TESTS(); return rt; }
25.56
98
0.710485
terrajobst
e7269d982ca2357e03ac7932a0de9d38272a32e2
8,394
cpp
C++
Sources/Elastos/Packages/Apps/Dialer/src/elastos/droid/contacts/common/util/LocalizedNameResolver.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Packages/Apps/Dialer/src/elastos/droid/contacts/common/util/LocalizedNameResolver.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Packages/Apps/Dialer/src/elastos/droid/contacts/common/util/LocalizedNameResolver.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "Elastos.Droid.Accounts.h" #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Utility.h" #include <Elastos.CoreLibrary.External.h> #include "elastos/droid/contacts/common/util/LocalizedNameResolver.h" #include "elastos/droid/utility/Xml.h" #include <elastos/utility/logging/Logger.h> #include "R.h" using Elastos::Droid::Accounts::IAccountManagerHelper; using Elastos::Droid::Accounts::CAccountManagerHelper; using Elastos::Droid::Accounts::IAccountManager; using Elastos::Droid::Accounts::IAuthenticatorDescription; using Elastos::Droid::Content::Pm::IPackageManager; using Elastos::Droid::Content::Pm::IPackageInfo; using Elastos::Droid::Content::Pm::IPackageItemInfo; using Elastos::Droid::Content::Pm::IServiceInfo; using Elastos::Droid::Content::Res::ITypedArray; using Elastos::Droid::Content::Res::IResources; using Elastos::Droid::Content::Res::IXmlResourceParser; using Elastos::Droid::Utility::Xml; using Elastos::Droid::Utility::IAttributeSet; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Contacts { namespace Common { namespace Util { const String LocalizedNameResolver::TAG("LocalizedNameResolver"); const String LocalizedNameResolver::METADATA_CONTACTS("android.provider.CONTACTS_STRUCTURE"); const String LocalizedNameResolver::CONTACTS_DATA_KIND("ContactsDataKind"); ECode LocalizedNameResolver::GetAllContactsName( /* [in] */ IContext* context, /* [in] */ const String& accountType, /* [out] */ String* name) { VALIDATE_NOT_NULL(name) *name = String(NULL); if (context == NULL) { Logger::E("LocalizedNameResolver", "Context must not be null"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (accountType.IsNull()) return NOERROR; *name = ResolveAllContactsName(context, accountType); return NOERROR; } String LocalizedNameResolver::ResolveAllContactsName( /* [in] */ IContext* context, /* [in] */ const String& accountType) { AutoPtr<IAccountManagerHelper> helper; CAccountManagerHelper::AcquireSingleton((IAccountManagerHelper**)&helper); AutoPtr<IAccountManager> am; helper->Get(context, (IAccountManager**)&am); AutoPtr<ArrayOf<IAuthenticatorDescription*> > types; am->GetAuthenticatorTypes((ArrayOf<IAuthenticatorDescription*>**)&types); for (Int32 i = 0; i < types->GetLength(); ++i) { AutoPtr<IAuthenticatorDescription> auth = (*types)[i]; String type; auth->GetType(&type); if (accountType.Equals(type)) { String pkgName; auth->GetPackageName(&pkgName); return ResolveAllContactsNameFromMetaData(context, pkgName); } } return String(NULL); } String LocalizedNameResolver::ResolveAllContactsNameFromMetaData( /* [in] */ IContext* context, /* [in] */ const String& packageName) { AutoPtr<IPackageManager> pm; context->GetPackageManager((IPackageManager**)&pm); // try { AutoPtr<IPackageInfo> pi; pm->GetPackageInfo(packageName, IPackageManager::GET_SERVICES | IPackageManager::GET_META_DATA, (IPackageInfo**)&pi); AutoPtr<ArrayOf<IServiceInfo*> > services; if (pi != NULL && (pi->GetServices((ArrayOf<IServiceInfo*>**)&services), services != NULL)) { for (Int32 i = 0; i < services->GetLength(); ++i) { AutoPtr<IServiceInfo> si = (*services)[i]; AutoPtr<IXmlResourceParser> parser; IPackageItemInfo::Probe(si)->LoadXmlMetaData(pm, METADATA_CONTACTS, (IXmlResourceParser**)&parser); if (parser != NULL) { String str; ECode ec = LoadAllContactsNameFromXml(context, IXmlPullParser::Probe(parser), packageName, &str); if (ec == (ECode)E_NAME_NOT_FOUND_EXCEPTION) { Logger::W(TAG, "Problem loading \"All Contacts\"-name: 0x%08x", ec); break; } return str; } } } // } catch (NameNotFoundException e) { // Log.w(TAG, "Problem loading \"All Contacts\"-name: " + e.toString()); // } return String(NULL); } ECode LocalizedNameResolver::LoadAllContactsNameFromXml( /* [in] */ IContext* context, /* [in] */ IXmlPullParser* parser, /* [in] */ const String& packageName, /* [out] */ String* _name) { VALIDATE_NOT_NULL(_name) *_name = String(NULL); // try { AutoPtr<IAttributeSet> attrs = Xml::AsAttributeSet(parser); Int32 type; while ((parser->Next(&type), type != IXmlPullParser::START_TAG) && type != IXmlPullParser::END_DOCUMENT) { // Drain comments and whitespace } if (type != IXmlPullParser::START_TAG) { Logger::E(TAG, "No start tag found"); return E_ILLEGAL_STATE_EXCEPTION; } Int32 depth; parser->GetDepth(&depth); Int32 depthTemp; while (((parser->Next(&type), type != IXmlPullParser::END_TAG) || (parser->GetDepth(&depthTemp), depthTemp > depth)) && type != IXmlPullParser::END_DOCUMENT) { String name; parser->GetName(&name); if (type == IXmlPullParser::START_TAG && CONTACTS_DATA_KIND.Equals(name)) { AutoPtr<ITypedArray> typedArray; AutoPtr<ArrayOf<Int32> > params = TO_ATTRS_ARRAYOF(Elastos::Droid::Dialer::R::styleable::ContactsDataKind); context->ObtainStyledAttributes(attrs, params, (ITypedArray**)&typedArray); // try { // See if a string has been hardcoded directly into the xml String nonResourceString; typedArray->GetNonResourceString( Elastos::Droid::Dialer::R::styleable::ContactsDataKind_android_allContactsName, &nonResourceString); if (!nonResourceString.IsNull()) { *_name = nonResourceString; typedArray->Recycle(); return NOERROR; } // See if a resource is referenced. We can't rely on getString // to automatically resolve it as the resource lives in a different package Int32 id; typedArray->GetResourceId( Elastos::Droid::Dialer::R::styleable::ContactsDataKind_android_allContactsName, 0, &id); if (id == 0) { typedArray->Recycle(); return NOERROR; } // Resolve the resource Id AutoPtr<IPackageManager> packageManager; context->GetPackageManager((IPackageManager**)&packageManager); AutoPtr<IResources> resources; // try { ECode ec = packageManager->GetResourcesForApplication(packageName, (IResources**)&resources); if (ec == (ECode)E_NAME_NOT_FOUND_EXCEPTION) { typedArray->Recycle(); return NOERROR; } // } catch (NameNotFoundException e) { // return null; // } // try { resources->GetString(id, _name); typedArray->Recycle(); return NOERROR; // } catch (NotFoundException e) { // return null; // } // } finally { // typedArray.recycle(); // } } } return NOERROR; // } catch (XmlPullParserException e) { // throw new IllegalStateException("Problem reading XML", e); // } catch (IOException e) { // throw new IllegalStateException("Problem reading XML", e); // } } } // namespace Util } // namespace Common } // namespace Contacts } // namespace Droid } // namespace Elastos
38.504587
120
0.626519
jingcao80
e7285f475dc936124bd14ec0c0c44ce03387048d
386
cc
C++
poj/1/1969.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
1
2015-04-17T09:54:23.000Z
2015-04-17T09:54:23.000Z
poj/1/1969.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
poj/1/1969.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main() { int term; while (cin >> term) { int a = (1 + sqrt(1 + 8*(term-1))) / 2.0; int b = term - (1+a*(a-1)/2); if (a % 2 == 0) { cout << "TERM " << term << " IS " << b+1 << '/' << a-b << endl; } else { cout << "TERM " << term << " IS " << a-b << '/' << b+1 << endl; } } return 0; }
21.444444
69
0.417098
eagletmt
e72996c8acd1f0e35eaea01887fcdf9e397e6190
2,400
cpp
C++
D#0003-optimizing_cosine_distance_searching_in_a_million_feature-set/code/main.cpp
awesome-archive/CaptainBlackboard
c8ec5f1adf2301724a3a864890df6c0bcb598505
[ "MIT" ]
961
2019-01-30T01:46:26.000Z
2022-03-31T01:09:39.000Z
D#0003-optimizing_cosine_distance_searching_in_a_million_feature-set/code/main.cpp
zhangshaokun999/CaptainBlackboard
f0f6781f55cf24d2bcb28cb65ef124505d411e27
[ "MIT" ]
125
2019-02-20T14:24:17.000Z
2021-04-22T12:33:08.000Z
D#0003-optimizing_cosine_distance_searching_in_a_million_feature-set/code/main.cpp
zhangshaokun999/CaptainBlackboard
f0f6781f55cf24d2bcb28cb65ef124505d411e27
[ "MIT" ]
171
2019-09-30T01:36:18.000Z
2022-03-23T06:37:02.000Z
//main.cpp #include <iostream> #include <malloc.h> #include "timer.h" #include "search_best.h" #define ALGIN (32) // 使用SIMD需要内存对齐,128bit的指令需要16位对齐,256bit的指令需要32位对齐 #define FACENUM (1000*1000) // 底库中存有100万张人脸特征向量 //#define FEATSIZE (512) // 每个人脸特征向量的维度是512维,每一维是一个DType类型的浮点数 //Step 11,用PCA做特征选择,压缩512维到256维 #define FEATSIZE (256) // 每个人脸特征向量的维度是256维,每一维是一个DType类型的浮点数 // Step 4, double-->float(在我的电脑上,sizeof(float)==4,sizeof(double)==8, sizeof(short)==2, sizeof(int)==4 //typedef float DType; // Step 12, float-->unsigned short,定点化 typedef float DType; float calcL(const DType * const pVec, const int len) { float l = 0.0f; for(int i = 0; i < len; i++) { l += pVec[i] * pVec[i]; } return sqrt(l) + FLT_MIN; } int main(int argc, char* argv[]) { // 1.定义当前脸的特征,并初始化 __attribute__((aligned(ALGIN))) DType vectorA[FEATSIZE]; for(int i = 0; i < FEATSIZE; i++) { vectorA[i] = static_cast<DType>(FACENUM/2*FEATSIZE + i) / (FACENUM * FEATSIZE); } // 模归一化 const float l = calcL(vectorA, FEATSIZE); for(int i = 0; i < FEATSIZE; i++) { vectorA[i] /= l; } // 2.定义底库中所有脸的特征向量,并初始化 // 为了使用SIMD优化,使用memalign申请对齐了的内存,牺牲了代码的可移植性 DType* pDB = reinterpret_cast<DType*>(memalign(ALGIN, sizeof(DType)*FACENUM*FEATSIZE)); if(!pDB) { std::cout << "out of memory\n"; return -1; } // 验证内存是否对齐 // printf("vectorA[%p], pDB[%p].\n", vectorA, pDB); for(int i = 0; i < FACENUM; i++) { for(int j = 0; j < FEATSIZE; j++) { pDB[i*FEATSIZE+j] = static_cast<DType>(i*FEATSIZE + j) / (FACENUM * FEATSIZE); } // 模归一化 const float norm = calcL(pDB + i*FEATSIZE, FEATSIZE); for(int j = 0; j < FEATSIZE; j++) { pDB[i*FEATSIZE+j] /= norm; } } // 3.定义计数器并开始计时 Timer t; int best_index = SearchBest(static_cast<DType*>(vectorA), FEATSIZE, pDB, FACENUM*FEATSIZE); // 4.打印结果 std::cout << "Best face index is: " << best_index << std::endl; std::cout << "Find the best face index eat: " << t.elapsed_micro() << "us" << std::endl; std::cout << "PER Cosine_similarity call eat: " << t.elapsed_nano() / FACENUM << "ns" << std::endl; //printf("double[%d], float[%d], short[%d], int[%d].\n", (int)sizeof(double), (int)sizeof(float), (int)sizeof(short), (int)sizeof(int)); // 5.释放分配的内存,防止内存泄露 // memalign分配的内存也可以用free释放 free(pDB); return 0; }
28.915663
138
0.612083
awesome-archive
e729f8341e231d6e07305b516881ce334028c83c
5,431
cpp
C++
src/core/formula.cpp
Jetpie/OpenLinear
c501ab26bd53bcfd781d0aae22bb75392629000f
[ "BSD-2-Clause" ]
3
2015-04-07T12:37:50.000Z
2015-07-02T01:38:30.000Z
src/core/formula.cpp
Jetpie/OpenLinear
c501ab26bd53bcfd781d0aae22bb75392629000f
[ "BSD-2-Clause" ]
null
null
null
src/core/formula.cpp
Jetpie/OpenLinear
c501ab26bd53bcfd781d0aae22bb75392629000f
[ "BSD-2-Clause" ]
null
null
null
// Problem formulations // // Naming Convention: // 1.solver classes are named by all capital letter denote type and a // "Solver" prefix separated by underscore. // 2.some math notation like w^t by x will be denoted as wTx, // which big T means transpose. For the same style, other name // convention can be deduced like wT means transpose of w. It worths // something to mention that big X means matrix and small x means // vector. Hope this is helpful for readers. // // @author: Bingqing Qu // // Copyright (C) 2014-2015 Bingqing Qu <sylar.qu@gmail.com> // // @license: See LICENSE at root directory #include "formula.hpp" namespace oplin{ using std::cout; using std::endl; using std::cerr; Problem::Problem(DatasetPtr dataset, const std::vector<double>& C) : dataset_(dataset) { // use swap trick std::vector<double>(C).swap(C_); regularizer_ = NULL; } void Problem::regularized_gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { if(regularizer_) regularizer_->gradient(w,grad); } void Problem::update_weights(Eigen::Ref<ColVector> new_w, const Eigen::Ref<const ColVector>& w, const Eigen::Ref<const ColVector>& p, const double& alpha) { new_w.noalias() = w + alpha * p; } double L1_Regularizer::loss(const Eigen::Ref<const ColVector>& w) { return w.lpNorm<1>(); } /** * Compute the L1-regularized gradient * * Reference: * Galen Andrew and Jianfeng Gao. 2007. Scalable training of L1-regularized \ * log-linear models. In ICML. * * @param w weights */ void L1_Regularizer::gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { // this is the key part of the well defined pesudo-gradient in // Jianfeng et al's paper for(int i=0; i < grad.rows(); ++i) { if(w(i) == 0) { if(grad(i) < -1 ) ++grad(i); else if(grad(i) > 1) --grad(i); else grad(i) = 0; } else { grad(i) += w(i) > 0? 1 : (-1); } } } double L2_Regularizer::loss(const Eigen::Ref<const ColVector>& w) { return (w.squaredNorm() * 0.5); } void L2_Regularizer::gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { grad.noalias() += w; } /********************************************************************* * Logistic Regression *********************************************************************/ LR_Problem::LR_Problem(DatasetPtr dataset, const std::vector<double>& C) : Problem(dataset, C) { z_ = ColVector(dataset->n_samples, 1); } LR_Problem::~LR_Problem(){} /** * Compute the loss functionn * * @param w weights * */ double LR_Problem::loss(const Eigen::Ref<const ColVector>& w) { double f = regularizer_? regularizer_->loss(w):0; const std::vector<double>& y = dataset_->y; // W^T X z_.noalias() = w.transpose() * (*(dataset_->X)); // std::cout << z_.sum() << std::endl; // loss function : negative log likelihood for(size_t i = 0; i < dataset_->n_samples; ++i) f += C_[i] * log( 1 + exp(-y[i] * z_(i) ) ); return f; } /** * Compute the gradient descent direction * * @param w weights */ void LR_Problem::gradient(const Eigen::Ref<const ColVector>& w, Eigen::Ref<ColVector> grad) { const std::vector<double>& y = dataset_->y; for(size_t i = 0; i < dataset_->n_samples; ++i) { // h_w(y_i,x_i) - sigmoid function z_(i) = 1 / (1+exp(-y[i]*z_(i))); // C * (h_w(y_i,x_i) - 1) * y[i] z_(i) = C_[i]*(z_(i)-1)*y[i]; } // declare noalias here to enforce lazy evaluation for memory saving grad.noalias() = *(dataset_->X) * z_; } /********************************************************************* * L1-Regularized Logistic Regression *********************************************************************/ L1R_LR_Problem::L1R_LR_Problem(DatasetPtr dataset, const std::vector<double>& C) : LR_Problem(dataset, C) { regularizer_ = std::make_shared<L1_Regularizer>(); if(!regularizer_) { cerr << "L1R_LR_Problem::L1R_LR_Problem : Failed to declare regularizer! (" << __FILE__ << ", line " << __LINE__ << ")."<< endl; throw(std::bad_alloc()); } } L1R_LR_Problem::~L1R_LR_Problem(){} void L1R_LR_Problem::update_weights(Eigen::Ref<ColVector> new_w, const Eigen::Ref<const ColVector>& w, const Eigen::Ref<const ColVector>& p, const double& alpha) { new_w.noalias() = w + alpha * p; // prevent moving outside orthants for(size_t i = 0; i < dataset_->dimension; ++i) { // check same sign if(new_w(i) * w(i) < 0 ) new_w(i) = 0.0; } } /********************************************************************* * L2-Regularized Logistic Regression *********************************************************************/ L2R_LR_Problem::L2R_LR_Problem(DatasetPtr dataset, const std::vector<double>& C) : LR_Problem(dataset, C) { regularizer_ = std::make_shared<L2_Regularizer>(); if(!regularizer_) { cerr << "L2R_LR_Problem::L2R_LR_Problem : Failed to declare regularizer! (" << __FILE__ << ", line " << __LINE__ << ")."<< endl; throw(std::bad_alloc()); } } L2R_LR_Problem::~L2R_LR_Problem(){} } // oplin
28.584211
105
0.558829
Jetpie
e72aca89b87268a17a8f791c42d63f1b9d5bbc03
5,650
cpp
C++
cctbx/geometry_restraints/bond_similarity_bpl.cpp
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
155
2016-11-23T12:52:16.000Z
2022-03-31T15:35:44.000Z
cctbx/geometry_restraints/bond_similarity_bpl.cpp
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
590
2016-12-10T11:31:18.000Z
2022-03-30T23:10:09.000Z
cctbx/geometry_restraints/bond_similarity_bpl.cpp
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
115
2016-11-15T08:17:28.000Z
2022-02-09T15:30:14.000Z
#include <cctbx/boost_python/flex_fwd.h> #include <boost/python/def.hpp> #include <boost/python/class.hpp> #include <boost/python/args.hpp> #include <boost/python/return_value_policy.hpp> #include <boost/python/copy_const_reference.hpp> #include <boost/python/return_by_value.hpp> #include <scitbx/array_family/boost_python/shared_wrapper.h> #include <scitbx/array_family/selections.h> #include <scitbx/stl/map_wrapper.h> #include <cctbx/geometry_restraints/bond_similarity.h> namespace cctbx { namespace geometry_restraints { namespace { struct bond_similarity_proxy_wrappers : boost::python::pickle_suite { typedef bond_similarity_proxy w_t; static boost::python::tuple getinitargs(w_t const& self) { return boost::python::make_tuple(self.i_seqs, self.sym_ops, self.weights); } static void wrap() { using namespace boost::python; typedef return_value_policy<return_by_value> rbv; class_<w_t>("bond_similarity_proxy", no_init) .def(init< af::shared<af::tiny<std::size_t, 2> >, af::shared<double> const&>(( arg("i_seqs"), arg("weights")))) .def(init< af::shared<af::tiny<std::size_t, 2> >, af::shared<sgtbx::rt_mx>, af::shared<double> const&>(( arg("i_seqs"), arg("sym_ops"), arg("weights")))) .add_property("i_seqs", make_getter(&w_t::i_seqs, rbv())) .add_property("weights", make_getter(&w_t::weights, rbv())) .add_property("sym_ops", make_getter(&w_t::sym_ops, rbv())) .def_pickle(bond_similarity_proxy_wrappers()) ; { typedef return_internal_reference<> rir; scitbx::af::boost_python::shared_wrapper< bond_similarity_proxy, rir>::wrap( "shared_bond_similarity_proxy"); } } }; struct bond_similarity_wrappers : boost::python::pickle_suite { typedef bond_similarity w_t; static boost::python::tuple getinitargs(w_t const& self) { return boost::python::make_tuple(self.sites_array, self.weights); } static void wrap() { using namespace boost::python; typedef return_value_policy<copy_const_reference> ccr; typedef return_value_policy<return_by_value> rbv; scitbx::af::boost_python::shared_wrapper< af::tiny<scitbx::vec3<double>, 2>, rbv>::wrap( "sites_array"); class_<w_t>("bond_similarity", no_init) .def(init< af::shared<af::tiny<scitbx::vec3<double>, 2> > const&, af::shared<double> const&>(( arg("sites_array"), arg("weights")))) .def(init<uctbx::unit_cell const&, af::const_ref<scitbx::vec3<double> > const&, bond_similarity_proxy const&>( (arg("unit_cell"), arg("sites_cart"), arg("proxy")))) .def(init<af::const_ref<scitbx::vec3<double> > const&, bond_similarity_proxy const&>( (arg("sites_cart"), arg("proxy")))) .add_property("sites_array", make_getter( &w_t::sites_array, rbv())) .add_property("weights", make_getter(&w_t::weights, rbv())) .def("deltas", &w_t::deltas, ccr()) .def("rms_deltas", &w_t::rms_deltas) .def("residual", &w_t::residual) .def("gradients", &w_t::gradients) .def("mean_distance", &w_t::mean_distance) .def_pickle(bond_similarity_wrappers()) ; } }; void wrap_all() { using namespace boost::python; bond_similarity_proxy_wrappers::wrap(); bond_similarity_wrappers::wrap(); def("bond_similarity_deltas_rms", (af::shared<double>(*)( af::const_ref<scitbx::vec3<double> > const&, af::const_ref<bond_similarity_proxy> const&)) bond_similarity_deltas_rms, (arg("sites_cart"), arg("proxies"))); def("bond_similarity_residuals", (af::shared<double>(*)( af::const_ref<scitbx::vec3<double> > const&, af::const_ref<bond_similarity_proxy> const&)) bond_similarity_residuals, (arg("sites_cart"), arg("proxies"))); def("bond_similarity_residual_sum", (double(*)( af::const_ref<scitbx::vec3<double> > const&, af::const_ref<bond_similarity_proxy> const&, af::ref<scitbx::vec3<double> > const&)) bond_similarity_residual_sum, (arg("sites_cart"), arg("proxies"), arg("gradient_array"))); def("bond_similarity_deltas_rms", (af::shared<double>(*)( uctbx::unit_cell const&, af::const_ref<scitbx::vec3<double> > const&, af::const_ref<bond_similarity_proxy> const&)) bond_similarity_deltas_rms, (arg("unit_cell"), arg("sites_cart"), arg("proxies"))); def("bond_similarity_residuals", (af::shared<double>(*)( uctbx::unit_cell const&, af::const_ref<scitbx::vec3<double> > const&, af::const_ref<bond_similarity_proxy> const&)) bond_similarity_residuals, (arg("unit_cell"), arg("sites_cart"), arg("proxies"))); def("bond_similarity_residual_sum", (double(*)( uctbx::unit_cell const&, af::const_ref<scitbx::vec3<double> > const&, af::const_ref<bond_similarity_proxy> const&, af::ref<scitbx::vec3<double> > const&)) bond_similarity_residual_sum, (arg("unit_cell"), arg("sites_cart"), arg("proxies"), arg("gradient_array"))); } } // namespace <anonymous> namespace boost_python { void wrap_bond_similarity() { wrap_all(); } }}} // namespace cctbx::geometry_restraints::boost_python
33.431953
69
0.622124
rimmartin
e72ae859303167117e22f572d0c08297d96afdbf
3,062
cpp
C++
fboss/agent/hw/bcm/tests/QsetCmpTests.cpp
midopooler/fboss
c8d08dd4255e97e5977f53712e7c91a7d045a0cb
[ "BSD-3-Clause" ]
1
2020-03-20T22:47:21.000Z
2020-03-20T22:47:21.000Z
fboss/agent/hw/bcm/tests/QsetCmpTests.cpp
phshaikh/fboss
05e6ed1e9d62bf7db45a770886b1761e046c1722
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/bcm/tests/QsetCmpTests.cpp
phshaikh/fboss
05e6ed1e9d62bf7db45a770886b1761e046c1722
[ "BSD-3-Clause" ]
null
null
null
/* * 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/hw/bcm/tests/BcmTest.h" #include "fboss/agent/hw/bcm/BcmFieldProcessorUtils.h" #include "fboss/agent/platforms/tests/utils/BcmTestPlatform.h" extern "C" { #if (!defined(BCM_VER_MAJOR)) // TODO (skhare) Find OpenNSA method for this #define sal_memset memset #else #include <bcm/field.h> #include <sal/core/libc.h> #endif } DECLARE_int32(acl_gid); DECLARE_int32(ll_mcast_gid); using namespace facebook::fboss::utility; namespace facebook::fboss { TEST_F(BcmTest, QsetCmp) { // Qset comparison with itself ASSERT_TRUE(qsetsEqual( getAclQset(getAsic()->getAsicType()), getAclQset(getAsic()->getAsicType()))); ASSERT_TRUE(qsetsEqual(getLLMcastQset(), getLLMcastQset())); auto aclEffectiveQset = getGroupQset(getUnit(), static_cast<bcm_field_group_t>(FLAGS_acl_gid)); auto llMcastEffectiveQset = getGroupQset( getUnit(), static_cast<bcm_field_group_t>(FLAGS_ll_mcast_gid)); ASSERT_TRUE(qsetsEqual(aclEffectiveQset, aclEffectiveQset)); ASSERT_TRUE(qsetsEqual(llMcastEffectiveQset, llMcastEffectiveQset)); // Qset comparison with another fails ASSERT_FALSE( qsetsEqual(getAclQset(getAsic()->getAsicType()), getLLMcastQset())); // Just doing a Qset cmp on qsets obtained from configured groups fails ASSERT_FALSE( qsetsEqual(getAclQset(getAsic()->getAsicType()), aclEffectiveQset)); ASSERT_FALSE(qsetsEqual(getLLMcastQset(), llMcastEffectiveQset)); // Comparing via FPGroupDesiredQsetCmp succeeds when comparing qsets // of the same group ASSERT_TRUE(FPGroupDesiredQsetCmp( getUnit(), static_cast<bcm_field_group_t>(FLAGS_acl_gid), getAclQset(getAsic()->getAsicType())) .hasDesiredQset()); ASSERT_TRUE(FPGroupDesiredQsetCmp( getUnit(), static_cast<bcm_field_group_t>(FLAGS_ll_mcast_gid), getLLMcastQset()) .hasDesiredQset()); // Comparing via FPGroupDesiredQsetCmp fails when comparing qsets of // different groups ASSERT_FALSE(FPGroupDesiredQsetCmp( getUnit(), static_cast<bcm_field_group_t>(FLAGS_acl_gid), getLLMcastQset()) .hasDesiredQset()); } TEST_F(BcmTest, BcmAddsExtraQuals) { bcm_field_qset_t qset; BCM_FIELD_QSET_INIT(qset); BCM_FIELD_QSET_ADD(qset, bcmFieldQualifySrcIp6); constexpr auto kTmpGrpAndPri = 9999; createFPGroup(getUnit(), qset, kTmpGrpAndPri, kTmpGrpAndPri); auto effectiveQset = getGroupQset(getUnit(), kTmpGrpAndPri); ASSERT_TRUE(BCM_FIELD_QSET_TEST(effectiveQset, bcmFieldQualifyStage)); ASSERT_FALSE(BCM_FIELD_QSET_TEST(qset, bcmFieldQualifyStage)); } } // namespace facebook::fboss
35.195402
79
0.714892
midopooler
e72e0d148ad4d79d9545f1c981711da1b115c2a6
1,215
hpp
C++
GC/VectorProtocol.hpp
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
null
null
null
GC/VectorProtocol.hpp
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
3
2022-02-22T16:14:53.000Z
2022-02-22T16:37:41.000Z
GC/VectorProtocol.hpp
GnarlyMshtep/DORAM
c78f7d516b52046b3105e8b967f048faea6c6fed
[ "BSD-2-Clause" ]
null
null
null
/* * VectorProtocol.cpp * */ #ifndef GC_VECTORPROTOCOL_HPP_ #define GC_VECTORPROTOCOL_HPP_ #include "VectorProtocol.h" namespace GC { template<class T> VectorProtocol<T>::VectorProtocol(Player& P) : part_protocol(P), P(P) { } template<class T> void VectorProtocol<T>::init(Preprocessing<T>& prep, typename T::MAC_Check& MC) { part_protocol.init(prep.get_part(), MC.get_part_MC()); } template<class T> void VectorProtocol<T>::init_mul() { part_protocol.init_mul(); } template<class T> void VectorProtocol<T>::prepare_mul(const T& x, const T& y, int n) { if (n == -1) n = T::default_length; for (int i = 0; i < n; i++) part_protocol.prepare_mul(x.get_reg(i), y.get_reg(i), 1); } template<class T> void VectorProtocol<T>::exchange() { part_protocol.exchange(); } template<class T> T VectorProtocol<T>::finalize_mul(int n) { T res; finalize_mult(res, n); return res; } template<class T> void VectorProtocol<T>::finalize_mult(T& res, int n) { if (n == -1) n = T::default_length; res.resize_regs(n); for (int i = 0; i < n; i++) res.get_reg(i) = part_protocol.finalize_mul(1); } } /* namespace GC */ #endif
17.357143
65
0.640329
GnarlyMshtep
e73058b8cd3a4db02c4a4933d85a04c56cc58f80
6,017
cpp
C++
Online Judges/Toph/J. Smart Feature Phone - 2.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/Toph/J. Smart Feature Phone - 2.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/Toph/J. Smart Feature Phone - 2.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; #define rep(i,p,n) for( i = p; i<n;i++) #define ll long long int #define pb push_back #define VI vector<int> #define VL vector<long long int> #define VD vector<double> #define pi pair<int,int> #define mp(a,b) make_pair(a,b) #define eps 1e-9 #define PI 2.0*acos(0.0) //#define PI acos(-1.0) #define MOD 1000000007 #define INF (1<<28) #define Clear(a,b) memset(a,b,sizeof(a)) //istringstream is() template<class T>inline bool read(T &x) { int c=getchar(); int sgn=1; while(~c&&c<'0'||c>'9') { if(c=='-')sgn=-1; c=getchar(); } for(x=0; ~c&&'0'<=c&&c<='9'; c=getchar())x=x*10+c-'0'; x*=sgn; return ~c; } template <class T> inline T bigmod(T p,T e,T M){ ll ret = 1; for(; e > 0; e >>= 1){ if(e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a,T b){if(b==0)return a;return gcd(b,a%b);} template <class T> inline T modinverse(T a,T M){return bigmod(a,M-2,M);} template<typename T>inline T POW(T B,T P) { if(P==0) return 1; if(P&1) return B*POW(B,P-1); else return SQR(POW(B,P/2)); } template<typename T>inline T Dis(T x1,T y1,T x2, T y2) { return sqrt( SQR(x1-x2) + SQR(y1-y2) ); } template<typename T>inline T Angle(T x1,T y1,T x2, T y2) { return atan( double(y1-y2) / double(x1-x2)); } template<typename T>inline T DIFF(T a,T b) { T d = a-b; if(d<0)return -d; else return d; } template<typename T>inline T ABS(T a) { if(a<0)return -a; else return a; } template<typename T>inline T euclide(T a,T b,T &x,T &y) { if(a<0) { T d=euclide(-a,b,x,y); x=-x; return d; } if(b<0) { T d=euclide(a,-b,x,y); y=-y; return d; } if(b==0) { x=1; y=0; return a; } else { T d=euclide(b,a%b,x,y); T t=x; x=y; y=t-(a/b)*y; return d; } } inline int Set(int N, int pos) { return N= N|(1<<pos); } inline int Reset(int N, int pos) { return N= N & ~(1<<pos); } inline bool check(int N, int pos) { return (bool) (N&(1<<pos)); } /************************************************************************************/ char str[100010]; struct node { char ch; int cnt; }; node arr[30]; bool cmp(node a, node b) { if(a.cnt==b.cnt) return a.ch<b.ch; return a.cnt>b.cnt; } vector<char> res[10]; int main() { //freopen("input.txt","r",stdin); //freopen("out.txt","w",stdout); //ios_base::sync_with_stdio(false); cin.tie(0); int test,i,j,Case,n,m; read(test); rep(Case,1,test+1) { gets(str); int len = strlen(str); for(int i =0 ;i<26;i++) { arr[i].ch = 'a'+i; arr[i].cnt=0; // cout<<arr[i].ch<<endl; } for(int i=0;i<len;i++) { arr[str[i]-'a'].cnt++; } sort(arr,arr+26,cmp); if(arr[0].cnt>=arr[1].cnt && arr[0].cnt!=0) { res[0].push_back(arr[0].ch); } else { for(int i=1;i<3;i++) res[0].push_back(arr[i].ch); for(int i=3;i<6;i++) { res[1].push_back(arr[i].ch); } for(int i=6;i<9;i++) { res[2].push_back(arr[i].ch); } for(int i=9;i<12;i++) { res[3].push_back(arr[i].ch); } for(int i=12;i<15;i++) { res[4].push_back(arr[i].ch); } for(int i=15;i<19;i++) { res[5].push_back(arr[i].ch); } for(int i=19;i<22;i++) { res[6].push_back(arr[i].ch); } for(int i=22;i<26;i++) { res[7].push_back(arr[i].ch); } printf("Case %d:\n",Case); printf("###############\n#....#%c%c%c#%c%c%c.#\n###############\n#%c%c%c.#%c%c%c#%c%c%c.#\n###############\n#%c%c%c%c#%c%c%c#%c%c%c%c#\n###############\n",res[0][0],res[0][1],res[0][2],res[1][0],res[1][1],res[1][2],res[2][0],res[2][1],res[2][2], res[3][0],res[3][1],res[3][2], res[4][0],res[4][1],res[4][2], res[5][0],res[5][1],res[5][2], res[5][3], res[6][0],res[6][1],res[6][2], res[7][0],res[7][1],res[7][2],res[7][3]); continue ; } if(arr[1].cnt>=arr[2].cnt && arr[1].cnt!=0) { res[1].push_back(arr[0].ch); } else { for(int i=1;i<3;i++) res[0].push_back(arr[i].ch); for(int i=3;i<6;i++) { res[1].push_back(arr[i].ch); } for(int i=6;i<9;i++) { res[2].push_back(arr[i].ch); } for(int i=9;i<12;i++) { res[3].push_back(arr[i].ch); } for(int i=12;i<15;i++) { res[4].push_back(arr[i].ch); } for(int i=15;i<19;i++) { res[5].push_back(arr[i].ch); } for(int i=19;i<22;i++) { res[6].push_back(arr[i].ch); } for(int i=22;i<26;i++) { res[7].push_back(arr[i].ch); } printf("Case %d:\n",Case); printf("###############\n#....#%c%c%c#%c%c%c.#\n###############\n#%c%c%c.#%c%c%c#%c%c%c.#\n###############\n#%c%c%c%c#%c%c%c#%c%c%c%c#\n###############\n",res[0][0],res[0][1],res[0][2],res[1][0],res[1][1],res[1][2],res[2][0],res[2][1],res[2][2], res[3][0],res[3][1],res[3][2], res[4][0],res[4][1],res[4][2], res[5][0],res[5][1],res[5][2], res[5][3], res[6][0],res[6][1],res[6][2], res[7][0],res[7][1],res[7][2],res[7][3]); continue ; } } return 0; }
22.040293
430
0.414492
akazad13
e7323fe3658eb1d900cb28be8435b97fc523aad1
325
hxx
C++
src/copy.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
src/copy.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
src/copy.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
#pragma once template <class H, class G> void copy(H& a, const G& x) { for (int u : x.vertices()) a.addVertex(u, x.vertexData(u)); for (int u : x.vertices()) { for (int v : x.edges(u)) a.addEdge(u, v, x.edgeData(u, v)); } } template <class G> auto copy(const G& x) { G a; copy(a, x); return a; }
15.47619
40
0.556923
puzzlef
e7332dc50cb9f2f686f40329593a8f1d5d09c6b5
1,625
cpp
C++
src/main/cpp/subsystems/Turret.cpp
ZairaV4/Rapid-React
7eb2cfee3849ffdc1dec62aa6da986c9ceb6aaac
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Turret.cpp
ZairaV4/Rapid-React
7eb2cfee3849ffdc1dec62aa6da986c9ceb6aaac
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Turret.cpp
ZairaV4/Rapid-React
7eb2cfee3849ffdc1dec62aa6da986c9ceb6aaac
[ "BSD-3-Clause" ]
null
null
null
#include "subsystems/Turret.h" #include "Constants.h" #include "frc/smartdashboard/Smartdashboard.h" #include "networktables/NetworkTable.h" #include "networktables/NetworkTableInstance.h" #include "networktables/NetworkTableEntry.h" #include "networktables/NetworkTableValue.h" #include "wpi/span.h" using namespace frc; using namespace std; Turret::Turret() { anglePID.SetTolerance(0.1); alignPID.SetTolerance(0.1); } void Turret::Periodic() { float turretDeg = (encoder.Get() * 44.4) / 360; limelight = nt::NetworkTableInstance::GetDefault().GetTable("limelight"); bool sensorMode = SmartDashboard::GetBoolean("Sensor Mode", false); bool climbMode = SmartDashboard::GetBoolean("Climb Mode", false); SmartDashboard::PutNumber("Turret Encoder", turretDeg); if (!sensorMode) Move(); else if (sensorMode) Align(); } bool Turret::SetAngle(float angle) { float output; anglePID.SetSetpoint(angle); output = anglePID.Calculate(encoder.Get()); motor.Set(clamp(output, -kTurretSpeed, kTurretSpeed)); return anglePID.AtSetpoint(); } bool Turret::Align() { float output; alignPID.SetSetpoint(0); output = alignPID.Calculate(-limelight->GetNumber("tx", 0.0)); // SI el output es positivo, y no ha llegado a su ángulo máximo a la derecha, // o si el output es negativo y no ha llegado a su ángulo máximo a la izquierda, setear el motor motor.Set(clamp(output, -kTurretSpeed, kTurretSpeed)); return alignPID.AtSetpoint(); } void Turret::Reset() { encoder.Reset(); } void Turret::Move() { motor.Set((-control.GetRawButton(cRightBumper) + control.GetRawButton(cLeftBumper)) * kTurretSpeed); }
22.569444
101
0.738462
ZairaV4
e733c2f5d296bf2d4b307a8439e43962dbe21d64
271
cpp
C++
lang/C++/window-creation-2.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:38.000Z
2018-11-09T22:08:38.000Z
lang/C++/window-creation-2.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/window-creation-2.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
#include <iostream> #include <gtkmm.h> int main( int argc, char* argv[] ) { try { Gtk::Main m( argc, argv ) ; Gtk::Window win ; m.run( win ) ; } catch( std::exception const & exc ) { std::cout << exc.what() << std::endl ; exit( -1 ) ; } exit( 0 ) ; }
12.318182
40
0.531365
ethansaxenian
e73657ba950bf255ff3e10060dde68d9afe78a20
2,189
cpp
C++
Engine/src/Engine/Core/Application.cpp
CodePYJ/Engine
d1d481581eb6373ddf0935f11f62842c0781aafd
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Core/Application.cpp
CodePYJ/Engine
d1d481581eb6373ddf0935f11f62842c0781aafd
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Core/Application.cpp
CodePYJ/Engine
d1d481581eb6373ddf0935f11f62842c0781aafd
[ "Apache-2.0" ]
null
null
null
#include "Application.h" #include "Engine/Renderer/Renderer.h" #include <GLFW/glfw3.h> #include <glad/glad.h> namespace EE { Application* Application::s_app = nullptr; Application::Application() { m_Window = std::unique_ptr<Window>(Window::Create(1600, 900)); m_Window->SetEventCallbackFun(std::bind(&Application::OnEvent, this, std::placeholders::_1)); s_app = this; m_ImGuiLayer = new ImGuiLayer(); PushOverlay(m_ImGuiLayer); } Application::~Application() { } void Application::Run() { while (m_Running) { float time = (float)glfwGetTime(); Timestep timestep = time - m_LastFrameTime; m_LastFrameTime = time; for (Layer* layer : m_layerstack) layer->OnUpdate(timestep); m_ImGuiLayer->Begin(); for (Layer* layer : m_layerstack) layer->OnImGuiRender(); m_ImGuiLayer->End(); OnUpdate(); } } void Application::OnEvent(Event& event) { EventDispatcher dispatcher(event); dispatcher.Dispatch<WindowCloseEvent>(std::bind(&Application::OnWindowClose, this, std::placeholders::_1)); dispatcher.Dispatch<WindowResizeEvent>(std::bind(&Application::OnWindowResize, this, std::placeholders::_1)); if (EventType::WindowClose == event.GetEventType()) OnWindowClose(event); //EE_TRACE(event.ToString()); for (auto it = m_layerstack.end(); it != m_layerstack.begin();) { //EE_TRACE((*(it-1))->GetName()); if (event.Handled) { //EE_TRACE(event.Handled); break; } (*--it)->OnEvent(event); } } void Application::OnUpdate() { glfwPollEvents(); m_Window->OnUpdate(); } void Application::OnWindowClose(Event& e) { m_Running = false; } void Application::OnWindowResize(WindowResizeEvent& e) { if (e.GetWidth() == 0 || e.GetHeight() == 0) m_Minimized = true; m_Minimized = false; Renderer::OnWindowResize(e.GetWidth(), e.GetHeight()); } void Application::PushLayer(Layer* layer) { m_layerstack.PushLayer(layer); } void Application::PopLayer(Layer* layer) { m_layerstack.PopLayer(layer); } void Application::PushOverlay(Layer* layer) { m_layerstack.PushOverlay(layer); } void Application::PopOverlay(Layer* layer) { m_layerstack.PopOverlay(layer); } }
21.048077
111
0.686158
CodePYJ
e73a0aaac98a626500254efdfc57da5c6002f425
3,290
hpp
C++
include/Pyramid.hpp
SudoCpp/Pyramid
97180840f05bab5f76dd183e09e93218579d7a80
[ "BSD-3-Clause" ]
null
null
null
include/Pyramid.hpp
SudoCpp/Pyramid
97180840f05bab5f76dd183e09e93218579d7a80
[ "BSD-3-Clause" ]
null
null
null
include/Pyramid.hpp
SudoCpp/Pyramid
97180840f05bab5f76dd183e09e93218579d7a80
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, SudoCpp All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __PYRAMID_PYRAMID_HPP__ #define __PYRAMID_PYRAMID_HPP__ #include "simplextk.hpp" #include "simplexsdl.hpp" #include "RGBColor.hpp" namespace pyramid { class Window; class Widget; class Pyramid : public simplex::Singleton { static Pyramid* instance; simplex::Array<Window*> windows; int lastWidgetID; static const RGBColor WidgetTextColor; static const RGBColor WidgetForegroundColor; static const int HoverTimer; Widget* lastMouseButtonWidget; Widget* lastMouseHoverWidget; public: const static simplex::string DefaultFontPath; const static RGBColor DefaultBackgroundColor; virtual ~Pyramid(); template <typename WindowType, typename... Args> static WindowType& CreateWindow(Args&&... args); static void StartProgram(); static void RedrawWindows(); static int GetWidgetID(); private: static Pyramid& GetInstance(); Pyramid(); void processWindowEvents(simplex::sdl::WindowEvent& event); void processMouseEvents(simplex::sdl::MouseEvent& event); Widget& getWidgetAtMouse(Window& window, int xPosition, int yPosition); Window& getCurrentWindow(uint32_t windowID); }; #define __class__ "pyramid::Pyramid" template <typename WindowType, typename... Args> WindowType& Pyramid::CreateWindow(Args&&... args) { WindowType* window = new WindowType(std::forward<Args>(args)...); Pyramid& pyramid = GetInstance(); pyramid.windows.add(window); return *window; } #undef __class__ } #endif //__PYRAMID_PYRAMID_HPP__
36.153846
82
0.71307
SudoCpp
e73bc683da3d4d41a3f3b6f29634e01c07905989
1,324
cpp
C++
ParticleEngine/ParticleForceRegistry.cpp
bernhardrieder/Particle-Engine
ea5885f2ee2446426b6ae93ce687802ef922fb29
[ "Unlicense" ]
null
null
null
ParticleEngine/ParticleForceRegistry.cpp
bernhardrieder/Particle-Engine
ea5885f2ee2446426b6ae93ce687802ef922fb29
[ "Unlicense" ]
null
null
null
ParticleEngine/ParticleForceRegistry.cpp
bernhardrieder/Particle-Engine
ea5885f2ee2446426b6ae93ce687802ef922fb29
[ "Unlicense" ]
2
2019-05-09T05:27:18.000Z
2020-02-11T18:04:56.000Z
#include "pch.h" #include "ParticleForceRegistry.h" ParticleForceRegistry::ParticleForceRegistry() { } ParticleForceRegistry::~ParticleForceRegistry() { } void ParticleForceRegistry::Add(Particle* particle, ParticleForceGenerator* forceGenerator) { ParticleForceRegistration registration; registration.Particle = particle; registration.ForceGenerator = forceGenerator; m_registrations.push_back(registration); } void ParticleForceRegistry::Remove(Particle* particle, ParticleForceGenerator* forceGenerator) { for (size_t index = 0; index < m_registrations.size(); ++index) { if (m_registrations[index].Particle == particle && m_registrations[index].ForceGenerator == forceGenerator) { m_registrations.erase(m_registrations.begin() + index); break; } } } void ParticleForceRegistry::Clear() { m_registrations.clear(); } void ParticleForceRegistry::UpdateForces(const float& deltaTime) { removeInactiveParticle(); for (ParticleForceRegistration& i : m_registrations) { i.ForceGenerator->UpdateForce(i.Particle, deltaTime); } } void ParticleForceRegistry::removeInactiveParticle() { for (std::vector<ParticleForceRegistration>::iterator it = m_registrations.begin(); it != m_registrations.end();) { if (!(*it).Particle->IsActive()) it = m_registrations.erase(it); else ++it; } }
22.827586
114
0.761329
bernhardrieder
e73be63b5db357a85cf7f19520727ac5d50dff16
847
cpp
C++
Strings/reverse_words.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Strings/reverse_words.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Strings/reverse_words.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
//leetcode.com/problems/reverse-words-in-a-string/ #include <bits/stdc++.h> using namespace std; class Solution { public: string reverseWords(string s) { string reverse_order_words = ""; int i = 0; int n = s.length(); while (i < n) { while (i < n && s[i] == ' ') { ++i; } if (i >= n) { break; } int j = i + 1; while (j < n && s[j] != ' ') { ++j; } string word = s.substr(i, j - i); if (reverse_order_words == "") { reverse_order_words += word; } else { reverse_order_words = word + " " + reverse_order_words; } i = j + 1; } return reverse_order_words; } };
24.911765
71
0.399055
khushisinha20
e741113c455830abce4a05b912e7c3ad295ea415
1,997
cpp
C++
src/Engine.cpp
Spooky309/Minecrap
bf30839bf4a80bf71340e7cf1af1f952599329de
[ "MIT" ]
1
2020-01-02T23:45:00.000Z
2020-01-02T23:45:00.000Z
src/Engine.cpp
Spooky309/Minecrap
bf30839bf4a80bf71340e7cf1af1f952599329de
[ "MIT" ]
null
null
null
src/Engine.cpp
Spooky309/Minecrap
bf30839bf4a80bf71340e7cf1af1f952599329de
[ "MIT" ]
null
null
null
#include "Engine.h" #include "SpriteElement2D.h" #include "FileSystem.h" #include "FontManager.h" #include "TextElement2D.h" #include <iostream> // PERFORMANCE IMPROVEMENTS TO MAKE: // 1. Broadphase on vs. AABB Tests // 2. Keep a list of active AABBs to avoid needless testing against AABB::alive Engine::Engine() : m_graphics(new Graphics()), m_input(new Input()) {} TextElement2D* text_test; void Engine::Go(const std::vector<std::string> argv) { m_fs = new FileSystem(); m_vitals = new EngineVitals(); m_bdata = new BlockData(); m_graphics->Init(); m_input->Init(m_graphics->GetWindow()); m_fm = new FontManager(); m_tdict = new TextureDictionary(); m_world = new World(16, 256, 16, m_tdict, m_bdata); m_player = new Player(m_world, m_bdata, glm::vec3(10, 130, 10)); text_test = new TextElement2D(glm::vec2(0.0f, 768.0f),glm::vec2(1.0f,1.0f),m_fm->LoadFont("dfont.ttf"),"0.0\n0.0"); text_test->SetText("last second ft (min/max/avg) (ms): 0/0/0\naverage framerate (1s): 0fps"); m_oTime = glfwGetTime(); m_vitals->FrameFinishCallback = [](const float& ft, const float& fr, const float& min, const float& max) { text_test->SetText("last second ft (min/max/avg) (ms): " + std::to_string(min) + "/" + std::to_string(max) + "/" + std::to_string(ft) + "\n" + "average framerate (1s): "+std::to_string(fr) + "fps"); }; while (Tick()); } bool Engine::Tick() { float dTime = (float)(glfwGetTime() - m_oTime); m_oTime = glfwGetTime(); m_vitals->FrameFinished(dTime); if (m_input->GetKeyDown(GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(m_graphics->GetWindow(), true); } m_graphics->Get2DRenderer()->QueueRender(text_test); m_world->RenderWorld(); m_world->UpdateWorld(); m_graphics->Render(); m_player->Update(dTime); m_input->Update(m_graphics->GetWindow()); glfwPollEvents(); if (glfwWindowShouldClose(m_graphics->GetWindow())) return false; return true; }
35.660714
151
0.662494
Spooky309
8d451901383a043d62cdc80e5fb6fda54d59fc55
3,103
cpp
C++
src/config_loader.cpp
oeone/ClashSubGenerator
3188f336a4388ed304c82d2d24b9ef69f21f32d5
[ "MIT" ]
2
2021-12-16T11:20:00.000Z
2021-12-16T11:20:11.000Z
src/config_loader.cpp
oeone/ClashSubGenerator
3188f336a4388ed304c82d2d24b9ef69f21f32d5
[ "MIT" ]
1
2020-08-04T02:09:40.000Z
2020-08-04T02:09:40.000Z
src/config_loader.cpp
oeone/ClashSubGenerator
3188f336a4388ed304c82d2d24b9ef69f21f32d5
[ "MIT" ]
3
2020-08-01T07:06:07.000Z
2021-12-14T12:33:36.000Z
// // Created by Kotarou on 2020/8/7. // #include <fstream> #include <fmt/format.h> #include <yaml-cpp/yaml.h> #include <spdlog/spdlog.h> #include "config_loader.h" #include "uri.h" #include "hash.h" #include "httpclient.h" #include "filesystem.h" #include "exception/invalid_uri_exception.h" std::shared_ptr<ConfigLoader> ConfigLoader::instance() { static const std::shared_ptr<ConfigLoader> instance{new ConfigLoader{}}; return instance; } std::string ConfigLoader::load_raw(std::string_view uri, bool local_only, bool use_cache) { auto uri_result = Uri::Parse(uri); validate_schema(uri_result); // add support of protocol file:// if (uri_result.getSchema() == "file" || local_only) { SPDLOG_DEBUG("Load local file {}", uri); auto path = uri_result.getBody(); try { if (FileSystem::exists(path)) { std::fstream fin(path.data()); return std::string((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()); } } catch (std::exception &e) { throw FileSystemException(fmt::format("Load file {} filed, error: {}", path, e.what())); } throw FileSystemException(fmt::format("File {} doesn't exist", path)); } else { return cache_loader(uri_result, use_cache); } } YAML::Node ConfigLoader::load_yaml(std::string_view uri, bool local_only, bool use_cache) { auto uri_result = Uri::Parse(uri); validate_schema(uri_result); // add support of protocol file:// if (uri_result.getSchema() == "file" || local_only) { SPDLOG_DEBUG("load local yaml file {}", uri_result.getBody()); auto path = uri_result.getBody(); if (FileSystem::exists(path)) { return YAML::LoadFile(path.data()); } throw FileSystemException(fmt::format("File {} doesn't exist", path)); } else { return YAML::Load(cache_loader(uri_result, use_cache)); } } std::string ConfigLoader::cache_loader(const Uri &uri, bool use_cache) { if (use_cache) { const auto sha1_hash = Hash::sha1(uri.getRawUri()); if (cache.find(sha1_hash) == cache.end()) { // download and cache auto content = HttpClient::get(uri); cache.emplace(sha1_hash, content); SPDLOG_DEBUG("Uri {} downloaded and cached", uri.getRawUri()); return content; } else { SPDLOG_DEBUG("Uri {} loaded from cache", uri.getRawUri()); return cache[sha1_hash]; } } else { return HttpClient::get(uri); } } void ConfigLoader::destroy_cache() { auto size = cache.size(); cache.clear(); SPDLOG_DEBUG("{} cached data deleted", size); } void ConfigLoader::validate_schema(const Uri &uri) { constexpr std::string_view valid_schema[] = {"http", "https", "file"}; for (const auto &schema : valid_schema) { if (schema == uri.getSchema()) { return; } } throw InvalidURIException(fmt::format("URI {} doesn't have a valid schema", uri.getRawUri())); }
31.663265
108
0.617145
oeone
8d4753a57f45e5e2681497ef18b41ef86c7aaa30
813
cpp
C++
kernel/posix/string.cpp
mschwartz/amos
345a4f8f52b9805722c10ac4cedb24b480fe2dc7
[ "MIT" ]
4
2020-08-18T00:11:09.000Z
2021-04-05T11:16:32.000Z
kernel/posix/string.cpp
mschwartz/amos
345a4f8f52b9805722c10ac4cedb24b480fe2dc7
[ "MIT" ]
1
2020-08-15T20:39:13.000Z
2020-08-15T20:39:13.000Z
kernel/posix/string.cpp
mschwartz/amos
345a4f8f52b9805722c10ac4cedb24b480fe2dc7
[ "MIT" ]
null
null
null
#include <posix.h> #include <posix/string.h> size_t strlen(char *s) { int count = 0; while (*s++) { count++; } return count; } void strcpy(char *dst, const char *src) { while ((*dst++ = *src++)); } void reverse(char *src) { int l = strlen(src); char work[l+1]; char *dst = work, *end_ptr = &src[l-1]; for (int i=0; i<l; i++) { *dst++ = *end_ptr--; } *dst++ = '\0'; strcpy(src, work); } void memcpy(void *dst, void *src, size_t size) { uint8_t *s = (uint8_t *)src, *d = (uint8_t *)dst; for (size_t i = 0; i < size; i++) { *d++ = *s++; } } void memset(void *dst, uint8_t v, size_t size) { uint8_t *d = (uint8_t *)dst; // size = 4096; // kprint("memset(%x, %d, %d)\n", d, v, 4096); for (size_t i = 0; i < size; i++) { *d++ = v; } }
16.9375
49
0.499385
mschwartz
8d481bc1adad90985207ec3cbeae0668734d7fa6
1,519
cpp
C++
3666 THE MATRIX PROBLEM/main.cpp
sqc1999-oi/HDU
5583755c5b7055e4a7254b2124f67982cc49b72d
[ "MIT" ]
1
2016-07-18T12:05:44.000Z
2016-07-18T12:05:44.000Z
3666 THE MATRIX PROBLEM/main.cpp
sqc1999-oi/HDU
5583755c5b7055e4a7254b2124f67982cc49b72d
[ "MIT" ]
null
null
null
3666 THE MATRIX PROBLEM/main.cpp
sqc1999-oi/HDU
5583755c5b7055e4a7254b2124f67982cc49b72d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stack> #include <cstring> #include <cmath> using namespace std; struct Edge { int To, Next; double Pow; Edge(int to, double pow, int next) : To(to), Pow(pow), Next(next) { } Edge() { } } E[1000001]; int G[1001], cnt, Cnt[1001]; double dis[1001]; bool inq[1001]; void AddEdge(int from, int to, double pow) { E[++cnt] = Edge(to, pow, G[from]); G[from] = cnt; } int a[401][401]; int main() { ios::sync_with_stdio(false); int n, m, l, u; while (cin >> n >> m >> l >> u) { memset(G, 0, sizeof G); cnt = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int w; cin >> w; AddEdge(j + n, i, log(u) - log(w)); AddEdge(i, j + n, log(w) - log(l)); } for (int i = 1; i <= n + m; i++) AddEdge(0, i, 0); memset(dis, 0x3f, sizeof dis); memset(Cnt, 0, sizeof Cnt); memset(inq, 0, sizeof inq); dis[0] = 0; stack<int> q; q.push(0); inq[0] = true; bool flag = true; while (!q.empty()) { int u = q.top(); q.pop(); inq[u] = false; for (int i = G[u]; i != 0; i = E[i].Next) { int &v = E[i].To; double tmp = dis[v]; dis[v] = min(dis[v], dis[u] + E[i].Pow); if (tmp != dis[v] && !inq[v]) { if (++Cnt[v] > n + m + 1) { flag = false; break; } q.push(v); inq[v] = true; } } if (!flag) break; } cout << (flag ? "YES" : "NO") << endl; } }
18.301205
45
0.463463
sqc1999-oi
8d483cf84c2d917421a4f571992670461a8aef81
4,814
cxx
C++
Modules/Video/Filtering/test/itkDecimateFramesVideoFilterTest.cxx
lassoan/ITK
4634cb0490934f055065230e3db64df8f546b72a
[ "Apache-2.0" ]
2
2019-09-15T10:17:06.000Z
2019-09-15T10:19:06.000Z
Modules/Video/Filtering/test/itkDecimateFramesVideoFilterTest.cxx
lassoan/ITK
4634cb0490934f055065230e3db64df8f546b72a
[ "Apache-2.0" ]
null
null
null
Modules/Video/Filtering/test/itkDecimateFramesVideoFilterTest.cxx
lassoan/ITK
4634cb0490934f055065230e3db64df8f546b72a
[ "Apache-2.0" ]
1
2021-09-23T08:33:37.000Z
2021-09-23T08:33:37.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkDecimateFramesVideoFilter.h" #include "itkVideoFileReader.h" #include "itkVideoFileWriter.h" #include "itkFileListVideoIOFactory.h" #include "itkFileListVideoIO.h" #include "itkImageFileReader.h" #include "itkImageRegionConstIterator.h" #include "itkTestingMacros.h" // type alias constexpr unsigned int Dimension = 2; using PixelType = unsigned char; using FrameType = itk::Image<PixelType, Dimension>; using VideoType = itk::VideoStream<FrameType>; using FilterType = itk::DecimateFramesVideoFilter<VideoType>; using ReaderType = itk::VideoFileReader<VideoType>; using WriterType = itk::VideoFileWriter<VideoType>; namespace itk { namespace DecimateFramesVideoFilterTest { /** * Compare two images pixel by pixel */ bool FramesAreEqual(const FrameType * f1, const FrameType * f2) { using IterType = ImageRegionConstIterator<FrameType>; IterType it1(f1, f1->GetLargestPossibleRegion()); IterType it2(f2, f2->GetLargestPossibleRegion()); while (!it1.IsAtEnd()) { if (it1.Get() != it2.Get()) { return false; } ++it1; ++it2; } return true; } } // namespace DecimateFramesVideoFilterTest } // namespace itk /** * Main test */ int itkDecimateFramesVideoFilterTest(int argc, char * argv[]) { ////// // Check Arguments ////// if (argc < 3) { std::cout << "Usage: " << itkNameOfTestExecutableMacro(argv) << " input_file_string output_file_string" << std::endl; return EXIT_FAILURE; } ////// // Set up pipeline ////// // Instantiate reader, writer, and filter ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); FilterType::Pointer filter = FilterType::New(); // Connect the pipeline filter->SetInput(reader->GetOutput()); writer->SetInput(filter->GetOutput()); // Set the filenames on the reader/writer reader->SetFileName(argv[1]); writer->SetFileName(argv[2]); // Keep every 3rd frame filter->SetPreservedFrameSpacing(3); ////// // Run the pipeline ////// // Register FileListIO with the factory -- shouldn't have to do this. Needs fixing itk::ObjectFactoryBase::RegisterFactory(itk::FileListVideoIOFactory::New()); // For the sake of debugging output, just use one thread filter->SetNumberOfWorkUnits(1); // Update the writer to run everything writer->Update(); ////// // Check the results ////// // Get the list of files for input and output std::vector<std::string> inputFiles = itk::FileListVideoIO::SplitFileNames(argv[1]); std::vector<std::string> outputFiles = itk::FileListVideoIO::SplitFileNames(argv[2]); // Set up two readers to read in the frames that should have been written and // compare against those that actually were using FrameReaderType = itk::ImageFileReader<FrameType>; FrameReaderType::Pointer inputFrameReader = FrameReaderType::New(); FrameReaderType::Pointer outputFrameReader = FrameReaderType::New(); // Compare input frame 0 and output frame 0 inputFrameReader->SetFileName(inputFiles[0]); inputFrameReader->Update(); outputFrameReader->SetFileName(outputFiles[0]); outputFrameReader->Update(); if (!itk::DecimateFramesVideoFilterTest::FramesAreEqual(inputFrameReader->GetOutput(), outputFrameReader->GetOutput())) { std::cerr << "Input frame 0 and output frame 0 don't match" << std::endl; return EXIT_FAILURE; } // Compare input frame 3 and output frame 1 inputFrameReader->SetFileName(inputFiles[3]); inputFrameReader->Update(); outputFrameReader->SetFileName(outputFiles[1]); outputFrameReader->Update(); if (!itk::DecimateFramesVideoFilterTest::FramesAreEqual(inputFrameReader->GetOutput(), outputFrameReader->GetOutput())) { std::cerr << "Input frame 3 and output frame 1 don't match" << std::endl; return EXIT_FAILURE; } ////// // Return successfully ////// return EXIT_SUCCESS; }
29.175758
107
0.672829
lassoan
8d4a3845d214351923034701112e23037b6b129f
1,847
cpp
C++
cpp/thread_thread_thread_2.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/thread_thread_thread_2.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/thread_thread_thread_2.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/thread_thread_thread_2.exe ./cpp/thread_thread_thread_2.cpp && (cd ../_build/cpp/;./thread_thread_thread_2.exe) https://en.cppreference.com/w/cpp/thread/thread/thread */ #include <iostream> #include <utility> #include <thread> #include <chrono> void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 1 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } class foo { public: void bar() { for (int i = 0; i < 5; ++i) { std::cout << "Thread 3 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int n = 0; }; class baz { public: void operator()() { for (int i = 0; i < 5; ++i) { std::cout << "Thread 4 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int n = 0; }; int main() { int n = 0; foo f; baz b; std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f std::thread t6(b); // t6 runs baz::operator() on a copy of object b t2.join(); t4.join(); t5.join(); t6.join(); std::cout << "Final value of n is " << n << '\n'; std::cout << "Final value of f.n (foo::n) is " << f.n << '\n'; std::cout << "Final value of b.n (baz::n) is " << b.n << '\n'; }
26.014085
153
0.525176
rpuntaie
8d4a5ff37dbf9d49be0181b68162842065d0664f
2,140
hpp
C++
Sources/SF2Lib/include/SF2Lib/Render/LowPassFilter.hpp
bradhowes/SF2Lib
766c38c9c49e3cf66f4161edc1695e071c345b63
[ "MIT" ]
null
null
null
Sources/SF2Lib/include/SF2Lib/Render/LowPassFilter.hpp
bradhowes/SF2Lib
766c38c9c49e3cf66f4161edc1695e071c345b63
[ "MIT" ]
null
null
null
Sources/SF2Lib/include/SF2Lib/Render/LowPassFilter.hpp
bradhowes/SF2Lib
766c38c9c49e3cf66f4161edc1695e071c345b63
[ "MIT" ]
null
null
null
// Copyright © 2022 Brad Howes. All rights reserved. #pragma once #include <cassert> #include <iostream> #include "SF2Lib/DSP/DSP.hpp" #include "DSPHeaders/Biquad.hpp" namespace SF2::Render { class LowPassFilter { public: using Coefficients = DSPHeaders::Biquad::Coefficients<Float>; inline static Float defaultFrequency = 13500; inline static Float defaultResonance = 0.0; LowPassFilter(Float sampleRate) noexcept : filter_{Coefficients()}, sampleRate_{sampleRate}, lastFrequency_{defaultFrequency}, lastResonance_{defaultResonance} { updateSettings(defaultFrequency, defaultResonance); } /** Update the filter to use the given frequency and resonance settings. @param frequency frequency represented in cents @param resonance resonance in centiBels */ Float transform(Float frequency, Float resonance, Float sample) noexcept { // return sample; if (lastFrequency_ != frequency || lastResonance_ != resonance) { updateSettings(frequency, resonance); // Bounds taken from FluidSynth, where the upper bound serves as an anti-aliasing filter, just below the // Nyquist frequency. frequency = DSP::clamp(DSP::centsToFrequency(frequency), 5.0, 0.45 * sampleRate_); resonance = DSP::centibelsToResonance(resonance); filter_.setCoefficients(Coefficients::LPF2(sampleRate_, frequency, resonance)); } return filter_.transform(sample); } void reset() noexcept { filter_.reset(); } private: void updateSettings(Float frequency, Float resonance) noexcept { lastFrequency_ = frequency; lastResonance_ = resonance; // Bounds taken from FluidSynth, where the upper bound serves as an anti-aliasing filter, just below the // Nyquist frequency. frequency = DSP::clamp(DSP::centsToFrequency(frequency), 5.0, 0.45 * sampleRate_); resonance = DSP::centibelsToResonance(resonance); filter_.setCoefficients(Coefficients::LPF2(sampleRate_, frequency, resonance)); } DSPHeaders::Biquad::Direct<Float> filter_; Float sampleRate_; Float lastFrequency_; Float lastResonance_; }; } // end namespace SF2::Render
29.315068
110
0.732243
bradhowes