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
3a1c6f6e95f6544ea309810f31d4d1da239734b4
1,731
hpp
C++
src/standard/bits/DD_ReferenceCounter.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
1
2018-06-01T03:29:34.000Z
2018-06-01T03:29:34.000Z
src/standard/bits/DD_ReferenceCounter.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
null
null
null
src/standard/bits/DD_ReferenceCounter.hpp
iDingDong/libDDCPP-old
841260fecc84330ff3bfffba7263f5318f0b4655
[ "BSD-3-Clause" ]
null
null
null
// DDCPP/standard/bits/DD_ReferenceCounter.hpp #ifndef DD_REFERENCE_COUNTER_HPP_INCLUDED_ # define DD_REFERENCE_COUNTER_HPP_INCLUDED_ 1 # include "DD_global_definitions.hpp" DD_DETAIL_BEGIN_ struct ReferenceCounter { public: DD_ALIAS(ThisType, ReferenceCounter); public: DD_ALIAS(LengthType, ::DD::LengthType); public: Pair<LengthType> m_reference_count_; public: Pair<LengthType> const& get_reference_count() const DD_NOEXCEPT { return m_reference_count_; } public: LengthType get_strong_reference_count() const DD_NOEXCEPT { return get_reference_count().first; } public: LengthType get_weak_reference_count() const DD_NOEXCEPT { return get_reference_count().second; } public: ValidityType is_unique_strong_reference() const DD_NOEXCEPT { return get_strong_reference_count() == LengthType(1); } public: ValidityType is_unique_weak_reference() const DD_NOEXCEPT { return get_weak_reference_count() == LengthType(1); } public: ValidityType has_strong_reference() const DD_NOEXCEPT { return get_strong_reference_count(); } public: ValidityType has_weak_reference() const DD_NOEXCEPT { return get_weak_reference_count(); } public: ValidityType is_expired() const DD_NOEXCEPT { return !has_strong_reference(); } public: ProcessType strongly_referred() DD_NOEXCEPT { ++m_reference_count_.first; } public: ProcessType weakly_referred() DD_NOEXCEPT { ++m_reference_count_.second; } public: ProcessType strongly_released() DD_NOEXCEPT { --m_reference_count_.first; } public: ProcessType weakly_released() DD_NOEXCEPT { --m_reference_count_.second; } }; DD_DETAIL_END_ DD_BEGIN_ using detail_::ReferenceCounter; DD_END_ #endif
15.184211
66
0.770075
iDingDong
3a1e53ced0e4e6d5677074243e48f637c8336b95
389
cpp
C++
test/CodeGenCXX/address-space-of-this.cpp
matthewelse/clang
b3ac9db345ddce6397784517cd0c41529220ab8c
[ "Apache-2.0" ]
793
2015-12-03T16:45:26.000Z
2022-02-12T20:14:20.000Z
test/CodeGenCXX/address-space-of-this.cpp
matthewelse/clang
b3ac9db345ddce6397784517cd0c41529220ab8c
[ "Apache-2.0" ]
219
2015-12-04T10:14:05.000Z
2019-10-22T18:19:11.000Z
test/CodeGenCXX/address-space-of-this.cpp
matthewelse/clang
b3ac9db345ddce6397784517cd0c41529220ab8c
[ "Apache-2.0" ]
241
2015-12-03T16:51:28.000Z
2021-10-14T00:21:08.000Z
// RUN: %clang_cc1 %s -std=c++14 -triple=spir -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 %s -std=c++17 -triple=spir -emit-llvm -o - | FileCheck %s struct MyType { MyType(int i) : i(i) {} int i; }; //CHECK: call void @_ZN6MyTypeC1Ei(%struct.MyType* addrspacecast (%struct.MyType addrspace(10)* @m to %struct.MyType*), i32 123) MyType __attribute__((address_space(10))) m = 123;
38.9
128
0.663239
matthewelse
3a1faf79a49428b4c07e39ee3b20059689e4b298
992
cpp
C++
Code/online_problems/codechef/BUILDB.cpp
Kevinjadia/Hacktoberfest_DSA_2021
08fe411a5359d4cf27a8004aecce291f1c4015de
[ "MIT" ]
4
2021-10-22T02:44:57.000Z
2021-11-08T12:21:41.000Z
Code/online_problems/codechef/BUILDB.cpp
Kevinjadia/Hacktoberfest_DSA_2021
08fe411a5359d4cf27a8004aecce291f1c4015de
[ "MIT" ]
95
2021-10-21T21:16:28.000Z
2021-11-02T13:32:00.000Z
Code/online_problems/codechef/BUILDB.cpp
Kevinjadia/Hacktoberfest_DSA_2021
08fe411a5359d4cf27a8004aecce291f1c4015de
[ "MIT" ]
24
2021-10-22T02:42:05.000Z
2021-10-31T16:34:36.000Z
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { long long n,r; cin>>n; cin>>r; long long arr1[n],arr2[n]; for(long long i=0;i<n;i++) { cin>>arr1[i]; } for(long long i=0;i<n;i++) { cin>>arr2[i]; } long long tension=arr2[0]; long long temp=0; long long res=arr2[0]; if(n==1) { cout<<arr2[0]<<endl; } else { for(long long i=1;i<n;i++) { temp=arr1[i]-arr1[i-1]; tension=tension-(temp*r); if(tension<0) { tension=0; } //cout<<tension+arr2[i]-rest<<endl; //tension = tension +arr2[i-1]-rest; tension = arr2[i] + tension; res=max(res,tension); } cout<<res<<endl; } } }
18.036364
48
0.372984
Kevinjadia
3a2381a6feef0b1e2ee4cc37c366668b20ff1bd6
2,111
cpp
C++
src/utils/test/lock.std.cpp
acelyc111/rdsn
298769147750167949af800b96d5b9dcdfab0aeb
[ "MIT" ]
149
2017-10-16T03:24:58.000Z
2022-03-25T02:29:13.000Z
src/utils/test/lock.std.cpp
acelyc111/rdsn
298769147750167949af800b96d5b9dcdfab0aeb
[ "MIT" ]
297
2017-10-19T03:23:34.000Z
2022-03-17T08:00:12.000Z
src/utils/test/lock.std.cpp
acelyc111/rdsn
298769147750167949af800b96d5b9dcdfab0aeb
[ "MIT" ]
63
2017-10-19T01:55:27.000Z
2022-03-09T11:09:00.000Z
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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 "utils/lockp.std.h" #include <gtest/gtest.h> using namespace dsn; using namespace dsn::tools; TEST(tools_common, std_lock_provider) { std_lock_provider *lock = new std_lock_provider(nullptr); lock->lock(); EXPECT_TRUE(lock->try_lock()); lock->unlock(); lock->unlock(); std_lock_nr_provider *nr_lock = new std_lock_nr_provider(nullptr); nr_lock->lock(); EXPECT_FALSE(nr_lock->try_lock()); nr_lock->unlock(); std_rwlock_nr_provider *rwlock = new std_rwlock_nr_provider(nullptr); rwlock->lock_read(); rwlock->unlock_read(); rwlock->lock_write(); rwlock->unlock_write(); std_semaphore_provider *sema = new std_semaphore_provider(0, nullptr); std::thread t([](std_semaphore_provider *s) { s->wait(1000000); }, sema); sema->signal(1); t.join(); delete lock; delete nr_lock; delete rwlock; delete sema; }
34.048387
80
0.721459
acelyc111
3a251cf8b33df88740c77ff1a81064a1549e37c1
664
cpp
C++
src/lib/AST/UnaryOperator.cpp
NCTU-Homework/compiler-hw4
343db48644e4a53759a602983aaf3a4030eeb986
[ "MIT" ]
null
null
null
src/lib/AST/UnaryOperator.cpp
NCTU-Homework/compiler-hw4
343db48644e4a53759a602983aaf3a4030eeb986
[ "MIT" ]
null
null
null
src/lib/AST/UnaryOperator.cpp
NCTU-Homework/compiler-hw4
343db48644e4a53759a602983aaf3a4030eeb986
[ "MIT" ]
null
null
null
#include "AST/UnaryOperator.hpp" #include "visitor/AstNodeVisitor.hpp" UnaryOperatorNode::UnaryOperatorNode(const uint32_t line, const uint32_t col, Operator op, ExpressionNode *p_operand) : ExpressionNode{line, col}, op(op), operand(p_operand) {} const char *UnaryOperatorNode::getOpCString() const { return kOpString[static_cast<size_t>(op)]; } void UnaryOperatorNode::accept(AstNodeVisitor &p_visitor) { p_visitor.visit(*this); } void UnaryOperatorNode::visitChildNodes(AstNodeVisitor &p_visitor) { operand->accept(p_visitor); } const Operator& UnaryOperatorNode::getOperator() const { return op; }
28.869565
77
0.71988
NCTU-Homework
3a262951bcbd671103af8e7d98cc382f61e583bd
3,001
cc
C++
garnet/lib/ui/gfx/tests/compositor_unittest.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
null
null
null
garnet/lib/ui/gfx/tests/compositor_unittest.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
garnet/lib/ui/gfx/tests/compositor_unittest.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 <lib/sys/cpp/testing/component_context_provider.h> #include <zircon/syscalls.h> #include "garnet/lib/ui/gfx/tests/vk_session_test.h" #include "gtest/gtest.h" #include "lib/ui/gfx/util/time.h" #include "lib/ui/scenic/cpp/commands.h" #include "src/ui/lib/escher/test/gtest_vulkan.h" namespace scenic_impl { namespace gfx { namespace test { class CompositorTest : public SessionTest { public: CompositorTest() {} void TearDown() override { SessionTest::TearDown(); view_linker_.reset(); resource_linker_.reset(); time_stamper_.reset(); scene_graph_.reset(); } SessionContext CreateSessionContext() override { SessionContext session_context = SessionTest::CreateSessionContext(); FXL_DCHECK(!scene_graph_); FXL_DCHECK(!time_stamper_); FXL_DCHECK(!resource_linker_); FXL_DCHECK(!view_linker_); // Generate scene graph. scene_graph_ = std::make_unique<SceneGraph>(); // Generate other parameters needed for session context. sys::testing::ComponentContextProvider context_provider_; app_context_ = context_provider_.TakeContext(); time_stamper_ = std::make_unique<EventTimestamper>(app_context_.get()); resource_linker_ = std::make_unique<ResourceLinker>(); view_linker_ = std::make_unique<ViewLinker>(); // Apply to the session context; session_context.event_timestamper = time_stamper_.get(); session_context.view_linker = view_linker_.get(); session_context.resource_linker = resource_linker_.get(); // Finally apply scene graph weak pointer. session_context.scene_graph = scene_graph_->GetWeakPtr(); // Return session return session_context; } private: std::unique_ptr<SceneGraph> scene_graph_; // This is saved because it needs to live longer than the EventTimestamper std::unique_ptr<sys::ComponentContext> app_context_; std::unique_ptr<EventTimestamper> time_stamper_; std::unique_ptr<ViewLinker> view_linker_; std::unique_ptr<ResourceLinker> resource_linker_; }; TEST_F(CompositorTest, Validation) { const int CompositorId = 15; std::array<float, 3> preoffsets = {0, 0, 0}; std::array<float, 9> matrix = {0.3, 0.6, 0.1, 0.3, 0.6, 0.1, 0.3, 0.6, 0.1}; std::array<float, 3> postoffsets = {0, 0, 0}; ASSERT_TRUE(Apply(scenic::NewCreateDisplayCompositorCmd(CompositorId))); ASSERT_TRUE(Apply( scenic::NewSetDisplayColorConversionCmdHACK(CompositorId, preoffsets, matrix, postoffsets))); Display* display = display_manager()->default_display(); ASSERT_TRUE(display != nullptr); const ColorTransform& transform = display->color_transform(); ASSERT_TRUE(transform.preoffsets == preoffsets); ASSERT_TRUE(transform.matrix == matrix); ASSERT_TRUE(transform.postoffsets == postoffsets); } } // namespace test } // namespace gfx } // namespace scenic_impl
31.589474
99
0.736421
zhangpf
3a2da50fe195f8d35967c867c7fcb115d765edbf
5,560
hpp
C++
contracts/relay.token/relay.token.hpp
eosforce/FORCEIO
b8dc334db53a66f8913027bc396eee852f6fe770
[ "MIT" ]
10
2019-01-17T11:56:40.000Z
2019-12-23T11:08:13.000Z
contracts/relay.token/relay.token.hpp
eosforce/FORCEIO
b8dc334db53a66f8913027bc396eee852f6fe770
[ "MIT" ]
null
null
null
contracts/relay.token/relay.token.hpp
eosforce/FORCEIO
b8dc334db53a66f8913027bc396eee852f6fe770
[ "MIT" ]
6
2019-04-24T11:16:02.000Z
2020-11-29T05:41:07.000Z
// // Created by fy on 2019-01-29. // #ifndef FORCEIO_CONTRACT_RELAY_TOKEN_HPP #define FORCEIO_CONTRACT_RELAY_TOKEN_HPP #pragma once #include <eosiolib/eosio.hpp> #include "force.relay/force.relay.hpp" #include "sys.match/sys.match.hpp" namespace relay { using namespace eosio; using std::string; struct sys_bridge_addmort { name trade_name; account_name trade_maker; uint64_t type; void parse(const string memo); }; struct sys_bridge_exchange { name trade_name; account_name trade_maker; account_name recv; uint64_t type; void parse(const string memo); }; enum class trade_type:uint64_t { match=1, bridge_addmortgage, bridge_exchange, trade_type_count }; #ifdef BEFORE_ONLINE_TEST static constexpr uint32_t UPDATE_CYCLE = 126; #else static constexpr uint32_t UPDATE_CYCLE = 315; #endif static constexpr uint64_t OTHER_COIN_WEIGHT = 500; #define COIN_REWARD_RECORD_SIZE 360 class token : public eosio::contract { public: using contract::contract; token( account_name self ) : contract(self) {} struct action { account_name from; account_name to; asset quantity; std::string memo; EOSLIB_SERIALIZE(action, (from)(to)(quantity)(memo)) }; /// @abi action void on( name chain, const checksum256 block_id, const force::relay::action& act ); /// @abi action void create( account_name issuer, name chain, account_name side_account, action_name side_action, asset maximum_supply ); /// @abi action void issue( name chain, account_name to, asset quantity, string memo ); /// @abi action void destroy( name chain, account_name from, asset quantity, string memo ); /// @abi action void transfer( account_name from, account_name to, name chain, asset quantity, string memo ); inline asset get_supply( name chain, symbol_name sym )const; /// @abi action void trade( account_name from, account_name to, name chain, asset quantity, trade_type type, string memo); /// @abi action void addreward(name chain,asset supply,int32_t reward_now); /// @abi action void rewardmine(asset quantity); /// @abi action void claim(name chain,asset quantity,account_name receiver); /// @abi action void settlemine(account_name system_account); /// @abi action void activemine(account_name system_account); private: inline static uint128_t get_account_idx(const name& chain, const asset& a) { return (uint128_t(uint64_t(chain)) << 64) + uint128_t(a.symbol.name()); } struct account { uint64_t id; asset balance; name chain; int128_t mineage = 0; // asset.amount * block height uint32_t mineage_update_height = 0; asset reward = asset(0); uint64_t primary_key() const { return id; } uint128_t get_index_i128() const { return get_account_idx(chain, balance); } }; struct account_next_id { uint64_t id; account_name account; uint64_t primary_key() const { return account; } }; struct reward_mine_info { int128_t total_mineage = 0; asset reward_pool = asset(0); int32_t reward_block_num = 0; uint64_t primary_key() const { return reward_block_num; } }; struct currency_stats { asset supply; asset max_supply; account_name issuer; name chain; account_name side_account; action_name side_action; int128_t total_mineage = 0; // asset.amount * block height uint32_t total_mineage_update_height = 0; uint64_t reward_scope; int32_t reward_size = 0; // vector<reward_mine_info> reward_mine; uint64_t primary_key() const { return supply.symbol.name(); } }; struct reward_currency { uint64_t id; name chain; asset supply; bool reward_now = true; //记录是否是立刻进行挖矿的代币 uint64_t primary_key() const { return id; } uint128_t get_index_i128() const { return get_account_idx(chain, supply); } }; typedef multi_index<N(accounts), account, indexed_by< N(bychain), const_mem_fun<account, uint128_t, &account::get_index_i128 >>> accounts; typedef multi_index<N(stat), currency_stats> stats; typedef multi_index<N(accountid), account_next_id> account_next_ids ; typedef multi_index<N(reward), reward_currency, indexed_by< N(bychain), const_mem_fun<reward_currency, uint128_t, &reward_currency::get_index_i128 >>> rewards; typedef multi_index<N(minereward), reward_mine_info> reward_mine ; void sub_balance( account_name owner, name chain, asset value ); void add_balance( account_name owner, name chain, asset value, account_name ram_payer ); void settle_user(account_name owner, name chain, asset value); public: struct transfer_args { account_name from; account_name to; name chain; asset quantity; string memo; }; }; asset token::get_supply( name chain, symbol_name sym )const { stats statstable( _self, chain ); const auto& st = statstable.get( sym ); return st.supply; } }; #endif //FORCEIO_CONTRACT_RELAY_TOKEN_HPP
26.990291
105
0.641187
eosforce
3a2f18573f8ddca071bdb7d440f6ee51806d1205
1,161
hpp
C++
myFileSystem_mem/include/superblock.hpp
Xiang-Pan/HUST_OS_CourseProject
c04a51dd71a30d6f3f1f760c3674ca5fabc29e5f
[ "MIT" ]
4
2020-07-22T15:25:00.000Z
2022-03-27T09:22:31.000Z
myFileSystem_mem/include/superblock.hpp
HoverWings/HUST_OS_CourseProject
c04a51dd71a30d6f3f1f760c3674ca5fabc29e5f
[ "MIT" ]
null
null
null
myFileSystem_mem/include/superblock.hpp
HoverWings/HUST_OS_CourseProject
c04a51dd71a30d6f3f1f760c3674ca5fabc29e5f
[ "MIT" ]
null
null
null
/* FileName: superblock.hpp * Author: Hover * E-Mail: hover@hust.edu.cn * GitHub: HoverWings * Description: superblock */ #ifndef _SUPERBLOCK_H_ #define _SUPERBLOCK_H_ #include "inode.hpp" #include <fstream> #include <list> #include <map> #include <string> #include <vector> #include <cstring> #include "macro.h" #include "assert.h" #include "myfs.hpp" #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> class myFS; class SuperBlock { private: bool inode_bitmap[INODE_NUM]; bool block_bitmap[BLOCK_NUM]; public: // uint node_num; // now inode num // uint direct_blocks; // uint blocks_num; // uint block_size; int q; class myFS* myfs; SuperBlock(); bool write_back_to_disk(); bool read_from_disk(); // template<class Archive> // void serialize(Archive & ar, const unsigned int version) // { // ar& inode_bitmap; // ar& block_bitmap; // } }; #endif
21.109091
67
0.622739
Xiang-Pan
3a2f94c29afe7266af07a00208752fe28f6dbf1a
215
cpp
C++
cplusplus/variadics.cpp
offonrynk/hackerrank
56f389187cab5ee93bac00c2c6ac9cb2ad0a0d58
[ "MIT" ]
null
null
null
cplusplus/variadics.cpp
offonrynk/hackerrank
56f389187cab5ee93bac00c2c6ac9cb2ad0a0d58
[ "MIT" ]
null
null
null
cplusplus/variadics.cpp
offonrynk/hackerrank
56f389187cab5ee93bac00c2c6ac9cb2ad0a0d58
[ "MIT" ]
null
null
null
#include <iostream> template <bool value> int reversed_binary_value() { return value; } template <bool a, bool b, bool... d> int reversed_binary_value() { return (reversed_binary_value<b, d...>() << 1) + a; }
17.916667
64
0.674419
offonrynk
3a316b3f6cf2cb63eef6d56f1e44ef85db01c7d7
5,393
hpp
C++
Dependencies/xerces-c-src_2_8_0/include/xercesc/validators/common/AllContentModel.hpp
neonkingfr/wildogcad
6d9798daa672d3ab293579439f38bb279fa376c7
[ "BSD-3-Clause" ]
11
2016-02-26T23:00:34.000Z
2020-11-12T03:09:45.000Z
proj/vendors/xerces/include/xercesc/validators/common/AllContentModel.hpp
DSRCorporation/asdcplib-as02
018002ccc5d62716514921a14782446e8edc4f3a
[ "OpenSSL" ]
null
null
null
proj/vendors/xerces/include/xercesc/validators/common/AllContentModel.hpp
DSRCorporation/asdcplib-as02
018002ccc5d62716514921a14782446e8edc4f3a
[ "OpenSSL" ]
1
2018-07-10T19:24:28.000Z
2018-07-10T19:24:28.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. */ /* * $Id: AllContentModel.hpp 568078 2007-08-21 11:43:25Z amassari $ */ #if !defined(ALLCONTENTMODEL_HPP) #define ALLCONTENTMODEL_HPP #include <xercesc/framework/XMLContentModel.hpp> #include <xercesc/util/ValueVectorOf.hpp> #include <xercesc/validators/common/ContentLeafNameTypeVector.hpp> XERCES_CPP_NAMESPACE_BEGIN class ContentSpecNode; // // AllContentModel is a derivative of the abstract content model base // class that handles the special case of <all> feature in schema. If a model // is <all>, all non-optional children must appear // // So, all we have to do is to keep an array of the possible children and // validate by just looking up each child being validated by looking it up // in the list, and make sure all non-optional children appear. // class AllContentModel : public XMLContentModel { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- AllContentModel ( ContentSpecNode* const parentContentSpec , const bool isMixed , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); ~AllContentModel(); // ----------------------------------------------------------------------- // Implementation of the ContentModel virtual interface // ----------------------------------------------------------------------- virtual int validateContent ( QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId ) const; virtual int validateContentSpecial ( QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId , GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool ) const; virtual ContentLeafNameTypeVector* getContentLeafNameTypeVector() const ; virtual unsigned int getNextState(const unsigned int currentState, const unsigned int elementIndex) const; virtual void checkUniqueParticleAttribution ( SchemaGrammar* const pGrammar , GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool , XMLValidator* const pValidator , unsigned int* const pContentSpecOrgURI , const XMLCh* pComplexTypeName = 0 ) ; private : // ----------------------------------------------------------------------- // Private helper methods // ----------------------------------------------------------------------- void buildChildList ( ContentSpecNode* const curNode , ValueVectorOf<QName*>& toFill , ValueVectorOf<bool>& toType ); // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- AllContentModel(); AllContentModel(const AllContentModel&); AllContentModel& operator=(const AllContentModel&); // ----------------------------------------------------------------------- // Private data members // // fCount // The count of possible children in the fChildren member. // // fChildren // The list of possible children that we have to accept. This array // is allocated as large as needed in the constructor. // // fChildOptional // The corresponding list of optional state of each child in fChildren // True if the child is optional (i.e. minOccurs = 0). // // fNumRequired // The number of required children in <all> (i.e. minOccurs = 1) // // fIsMixed // AllContentModel with mixed PCDATA. // ----------------------------------------------------------------------- MemoryManager* fMemoryManager; unsigned int fCount; QName** fChildren; bool* fChildOptional; unsigned int fNumRequired; bool fIsMixed; bool fHasOptionalContent; }; inline ContentLeafNameTypeVector* AllContentModel::getContentLeafNameTypeVector() const { return 0; } inline unsigned int AllContentModel::getNextState(const unsigned int, const unsigned int) const { return XMLContentModel::gInvalidTrans; } XERCES_CPP_NAMESPACE_END #endif
34.570513
87
0.575932
neonkingfr
3a35abe378de5385c0ca8d71446f0be43146accb
6,813
cpp
C++
src/loop050.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
4
2016-11-07T12:50:14.000Z
2020-04-30T19:48:05.000Z
src/loop050.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
1
2017-04-17T12:00:16.000Z
2017-04-17T12:00:16.000Z
src/loop050.cpp
TannerRogalsky/Demoloops
13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5
[ "MIT" ]
null
null
null
#include "demoloop.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include "graphics/shader.h" using namespace std; using namespace demoloop; const uint32_t CYCLE_LENGTH = 10; const static std::string shaderCode = R"===( uniform mediump float cycle_ratio; #define DEMOLOOP_M_PI 3.1459 #ifdef VERTEX vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) { return transform_proj * model * vertpos; } #endif #ifdef PIXEL highp vec3 mod289(highp vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } highp vec2 mod289(highp vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } highp vec3 permute(highp vec3 x) { return mod289(((x*34.0)+1.0)*x); } float snoise( vec2 v) { const highp vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) -0.577350269189626, // -1.0 + 2.0 * C.x 0.024390243902439); // 1.0 / 41.0 // First corner highp vec2 i = floor(v + dot(v, C.yy) ); highp vec2 x0 = v - i + dot(i, C.xx); // Other corners highp vec2 i1; //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 //i1.y = 1.0 - i1.x; i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); // x0 = x0 - 0.0 + 0.0 * C.xx ; // x1 = x0 - i1 + 1.0 * C.xx ; // x2 = x0 - 1.0 + 2.0 * C.xx ; highp vec4 x12 = x0.xyxy + C.xxzz; x12.xy -= i1; // Permutations i = mod289(i); // Avoid truncation effects in permutation highp vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) + i.x + vec3(0.0, i1.x, 1.0 )); highp vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); m = m*m ; m = m*m ; // Gradients: 41 points uniformly over a line, mapped onto a diamond. // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) highp vec3 x = 2.0 * fract(p * C.www) - 1.0; highp vec3 h = abs(x) - 0.5; highp vec3 ox = floor(x + 0.5); highp vec3 a0 = x - ox; // Normalise gradients implicitly by scaling m // Approximation of: m *= inversesqrt( a0*a0 + h*h ); m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); // Compute final noise value at P highp vec3 g; g.x = a0.x * x0.x + h.x * x0.y; g.yz = a0.yz * x12.xz + h.yz * x12.yw; return 130.0 * dot(m, g); } float snoise(float x, float y) { return snoise(vec2(x, y)); } float noise(float x, float y, float a, float b) { return snoise(x * a / 256.0, y * b / 256.0); } vec3 mix(float a, vec3 v1, vec3 v2) { return v1 * (1.0 - a) + v2 * a; } float smoothStep(float w, float a, float b) { if (w>=b) return 1.0; if (w<=a) return 0.0; float d = b-a; return (w-a)/d; } vec3 colsca(vec3 c, float s) { return c * s; } vec3 eye(float x, float y, float b) { float rx = 2.0*(x-0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y; float ry = 2.0*(y-0.5); float a = atan(ry, rx); float e = rx*rx + ry*ry; float r = sqrt(e); vec3 fue = vec3(1.0, 1.0, 1.0); vec3 den = vec3(0.3, 0.7, 0.4 + e); // veins // float ven = noise(24 * x, 24 * y, 128, 128); // ven = smoothStep(ven, -0.2, 0.0) - smoothStep(ven, 0.0, 0.2); // ven += x + pow(x, 6) * 10; // fue.r += 0.04 - 0.00*ven; // fue.g += 0.04 - 0.05*ven; // fue.b += 0.04 - 0.05*ven; // circular pattern float noiseOffset = pow(sin(cycle_ratio * DEMOLOOP_M_PI), 2.0) * 1.0; float no = 0.8 + 0.2 * noise(4.0*r + noiseOffset, 32.0*a/DEMOLOOP_M_PI + noiseOffset, 256.0, 256.0); den = colsca(den, no); // iris float irisSize = 0.025 - (1.0 - pow(sin((cycle_ratio) * DEMOLOOP_M_PI), 3.0)) * 0.02; float f2 = smoothStep(e, irisSize, irisSize + 0.01); den = colsca(den, f2); vec3 mixed = mix(smoothStep(e, 0.35, 0.36), den, fue); // ring float ri = smoothStep(e, 0.31, 0.35) - smoothStep(e, 0.35, 0.36); ri = 1.0 - 0.35 * ri; mixed = colsca(mixed, ri); // reflection // float r3 = sqrt(r*r*r); // float re = noise(2.0+4.0*r3*cos(a), 4.0*r3*sin(a), 128.0, 128.0); // re = 0.4 * smoothStep(re, 0.1, 0.5); // mixed += re * (1.0 - mixed); // eye contours mixed=colsca(mixed,0.8+0.15*smoothStep(-b,0.0,0.2)); mixed=colsca(mixed,0.8+0.2*smoothStep(-b,0.0,0.05)); return mixed; } vec3 skin(float x, float y, float b) { float rx = 2.0*(x - 0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y; float ry = 2.0*(y - 0.5); vec3 skinColor = vec3(0.75, 0.69, 0.6); // float cel = 0.95 + 0.05 * noise(64.0*x, 64.0*y, 256.0, 256.0); // skinColor = colsca(skinColor, cel); // skinColor.r += 0.03 * rx; // skinColor.g += 0.03 * ry; // skinColor = colsca(skinColor, y * 0.1 + 0.9); // float bri = noise(128.0 * x, 128.0 * y, 256.0, 256.0); // bri = 0.2 + 0.8 * smoothStep(bri, 0.0, 0.3); // skinColor = mix(bri*0.08*y, skinColor, vec3(1, 1, 1)); // float san = 0.50*noise(16.0*x,16.0*y,256.0,256.0); // san+= 0.25*noise(32.0*x,32.0*y,256.0,256.0); // skinColor.g*=1-0.1*san; // float osc = 0.500*noise(16.0*x,16.0*y,256.0,256.0); // osc+= 0.250*noise(24.0*x,24.0*y,256.0,256.0); // osc+= 0.125*noise(48.0*x,48.0*y,256.0,256.0); // skinColor=colsca(skinColor,0.9+0.1*osc); // skinColor.r+=0.08*x; // skinColor.g+=0.01; // float pecas = noise(32.0*x,32.0*y,256.0,256.0); // pecas=smoothStep(pecas,0.80,0.8001); // skinColor *= 1.0 - 0.16*pecas; float g = smoothStep(1.0 - b, 0.2, 0.7); g -= smoothStep(1.0 - b, 0.8, 1.0) * 3.0; skinColor += g * 0.1; // skinColor = mix(0.14, skinColor, vec3(1.0, 1.0, 1.0)); // skinColor *= 1.23; // skinColor += 0.21; skinColor=colsca(skinColor,(1.0-(b*0.5))); return skinColor; } vec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) { float t = cycle_ratio; float r = 0.0, g = 0.0, b = 0.0; float x = tc.x; float y = tc.y; float rx = 2.0*(x - 0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y; float ry = 2.0*(y - 0.5); // float h = 3.0*sqrt(x*x*x)*(1.0-x); float h = (2.0*(1.0 - pow(sin(cycle_ratio * DEMOLOOP_M_PI), 5.0)) + 1.0)*sqrt(x*x*x)*(1.0-x); float e = abs(ry) - h; float f = smoothStep( e, 0.0, 0.01 ); float eyeX = x + cos(cycle_ratio * DEMOLOOP_M_PI * 2.0) * 0.1 - 0.1; // y += sin(cycle_ratio * DEMOLOOP_M_PI * 2) * 0.1; vec3 skinColor = skin(x, y, e); vec3 eyeColor = eye(eyeX, y, e); return vec4(mix(f, eyeColor, skinColor), 1.0); } #endif )==="; class Loop050 : public Demoloop { public: Loop050() : Demoloop(CYCLE_LENGTH, 150, 150, 150), shader({shaderCode, shaderCode}) { } void Update() { const float cycle_ratio = getCycleRatio(); shader.attach(); shader.sendFloat("cycle_ratio", 1, &cycle_ratio, 1); renderTexture(gl.getDefaultTexture(), 0, 0, width, height); shader.detach(); } private: Shader shader; }; int main(int, char**){ Loop050 test; test.Run(); return 0; }
27.582996
102
0.577866
TannerRogalsky
3a37bdced5e0efee4020441b1398b40eafd176e2
1,797
hpp
C++
src/network/credentials_manager.hpp
Natureshadow/biboumi
b70136b96e579e8d38a30a298f885899cb80514c
[ "Zlib" ]
null
null
null
src/network/credentials_manager.hpp
Natureshadow/biboumi
b70136b96e579e8d38a30a298f885899cb80514c
[ "Zlib" ]
null
null
null
src/network/credentials_manager.hpp
Natureshadow/biboumi
b70136b96e579e8d38a30a298f885899cb80514c
[ "Zlib" ]
null
null
null
#pragma once #include "biboumi.h" #ifdef BOTAN_FOUND #include <botan/credentials_manager.h> #include <botan/certstor.h> #include <botan/tls_client.h> class TCPSocketHandler; /** * If the given cert isn’t valid, based on the given hostname * and fingerprint, then throws the exception if it’s non-empty. * * Must be called after the standard (from Botan) way of * checking the certificate, if we want to also accept certificates based * on a trusted fingerprint. */ void check_tls_certificate(const std::vector<Botan::X509_Certificate>& certs, const std::string& hostname, const std::string& trusted_fingerprint, const std::exception_ptr& exc); class BasicCredentialsManager: public Botan::Credentials_Manager { public: BasicCredentialsManager(const TCPSocketHandler* const socket_handler); BasicCredentialsManager(BasicCredentialsManager&&) = delete; BasicCredentialsManager(const BasicCredentialsManager&) = delete; BasicCredentialsManager& operator=(const BasicCredentialsManager&) = delete; BasicCredentialsManager& operator=(BasicCredentialsManager&&) = delete; std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type, const std::string& context) override final; void set_trusted_fingerprint(const std::string& fingerprint); const std::string& get_trusted_fingerprint() const; private: const TCPSocketHandler* const socket_handler; static bool try_to_open_one_ca_bundle(const std::vector<std::string>& paths); static void load_certs(); static Botan::Certificate_Store_In_Memory certificate_store; static bool certs_loaded; std::string trusted_fingerprint; }; #endif //BOTAN_FOUND
34.557692
116
0.734001
Natureshadow
3a37e87f2c3a5d9b482dfc4d8ee661fabb28abd8
98,005
cc
C++
diplomacy_research/proto/diplomacy_tensorflow/core/profiler/tfprof_options.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
39
2019-09-06T13:42:24.000Z
2022-03-18T18:38:43.000Z
diplomacy_research/proto/diplomacy_tensorflow/core/profiler/tfprof_options.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
9
2019-09-19T22:35:32.000Z
2022-02-24T18:04:57.000Z
diplomacy_research/proto/diplomacy_tensorflow/core/profiler/tfprof_options.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
8
2019-10-16T21:09:14.000Z
2022-02-23T05:20:37.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: diplomacy_tensorflow/core/profiler/tfprof_options.proto #include "diplomacy_tensorflow/core/profiler/tfprof_options.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckerOption; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto namespace diplomacy { namespace tensorflow { namespace tfprof { class OptionsProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<OptionsProto> _instance; } _OptionsProto_default_instance_; class AdvisorOptionsProto_CheckersEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto_CheckersEntry_DoNotUse> _instance; } _AdvisorOptionsProto_CheckersEntry_DoNotUse_default_instance_; class AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> _instance; } _AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse_default_instance_; class AdvisorOptionsProto_CheckerOptionDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto_CheckerOption> _instance; } _AdvisorOptionsProto_CheckerOption_default_instance_; class AdvisorOptionsProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto> _instance; } _AdvisorOptionsProto_default_instance_; } // namespace tfprof } // namespace tensorflow } // namespace diplomacy namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto { static void InitDefaultsOptionsProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_OptionsProto_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::OptionsProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::tfprof::OptionsProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_OptionsProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsOptionsProto}, {}}; static void InitDefaultsAdvisorOptionsProto_CheckersEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckersEntry_DoNotUse_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse(); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAdvisorOptionsProto_CheckersEntry_DoNotUse}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption.base,}}; static void InitDefaultsAdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse(); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse}, {}}; static void InitDefaultsAdvisorOptionsProto_CheckerOption() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckerOption = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAdvisorOptionsProto_CheckerOption}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse.base,}}; static void InitDefaultsAdvisorOptionsProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAdvisorOptionsProto}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_OptionsProto.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto_CheckerOption.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto.base); } ::google::protobuf::Metadata file_level_metadata[5]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, max_depth_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_peak_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_residual_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_output_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_micros_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_accelerator_micros_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_cpu_micros_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_params_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_float_ops_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_occurrence_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, step_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, order_by_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, account_type_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, start_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, trim_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, show_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, hide_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, account_displayed_op_only_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, select_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, output_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, dump_to_file_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, value_), 0, 1, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption, options_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto, checkers_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::diplomacy::tensorflow::tfprof::OptionsProto)}, { 27, 34, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse)}, { 36, 43, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse)}, { 45, -1, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption)}, { 51, -1, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_OptionsProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckersEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "diplomacy_tensorflow/core/profiler/tfprof_options.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n7diplomacy_tensorflow/core/profiler/tfp" "rof_options.proto\022\033diplomacy.tensorflow." "tfprof\"\225\004\n\014OptionsProto\022\021\n\tmax_depth\030\001 \001" "(\003\022\021\n\tmin_bytes\030\002 \001(\003\022\026\n\016min_peak_bytes\030" "\023 \001(\003\022\032\n\022min_residual_bytes\030\024 \001(\003\022\030\n\020min" "_output_bytes\030\025 \001(\003\022\022\n\nmin_micros\030\003 \001(\003\022" "\036\n\026min_accelerator_micros\030\026 \001(\003\022\026\n\016min_c" "pu_micros\030\027 \001(\003\022\022\n\nmin_params\030\004 \001(\003\022\025\n\rm" "in_float_ops\030\005 \001(\003\022\026\n\016min_occurrence\030\021 \001" "(\003\022\014\n\004step\030\022 \001(\003\022\020\n\010order_by\030\007 \001(\t\022\034\n\024ac" "count_type_regexes\030\010 \003(\t\022\032\n\022start_name_r" "egexes\030\t \003(\t\022\031\n\021trim_name_regexes\030\n \003(\t\022" "\031\n\021show_name_regexes\030\013 \003(\t\022\031\n\021hide_name_" "regexes\030\014 \003(\t\022!\n\031account_displayed_op_on" "ly\030\r \001(\010\022\016\n\006select\030\016 \003(\t\022\016\n\006output\030\017 \001(\t" "\022\024\n\014dump_to_file\030\020 \001(\t\"\370\002\n\023AdvisorOption" "sProto\022P\n\010checkers\030\001 \003(\0132>.diplomacy.ten" "sorflow.tfprof.AdvisorOptionsProto.Check" "ersEntry\032o\n\rCheckersEntry\022\013\n\003key\030\001 \001(\t\022M" "\n\005value\030\002 \001(\0132>.diplomacy.tensorflow.tfp" "rof.AdvisorOptionsProto.CheckerOption:\0028" "\001\032\235\001\n\rCheckerOption\022\\\n\007options\030\001 \003(\0132K.d" "iplomacy.tensorflow.tfprof.AdvisorOption" "sProto.CheckerOption.OptionsEntry\032.\n\014Opt" "ionsEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028" "\001b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 1009); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "diplomacy_tensorflow/core/profiler/tfprof_options.proto", &protobuf_RegisterTypes); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto namespace diplomacy { namespace tensorflow { namespace tfprof { // =================================================================== void OptionsProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int OptionsProto::kMaxDepthFieldNumber; const int OptionsProto::kMinBytesFieldNumber; const int OptionsProto::kMinPeakBytesFieldNumber; const int OptionsProto::kMinResidualBytesFieldNumber; const int OptionsProto::kMinOutputBytesFieldNumber; const int OptionsProto::kMinMicrosFieldNumber; const int OptionsProto::kMinAcceleratorMicrosFieldNumber; const int OptionsProto::kMinCpuMicrosFieldNumber; const int OptionsProto::kMinParamsFieldNumber; const int OptionsProto::kMinFloatOpsFieldNumber; const int OptionsProto::kMinOccurrenceFieldNumber; const int OptionsProto::kStepFieldNumber; const int OptionsProto::kOrderByFieldNumber; const int OptionsProto::kAccountTypeRegexesFieldNumber; const int OptionsProto::kStartNameRegexesFieldNumber; const int OptionsProto::kTrimNameRegexesFieldNumber; const int OptionsProto::kShowNameRegexesFieldNumber; const int OptionsProto::kHideNameRegexesFieldNumber; const int OptionsProto::kAccountDisplayedOpOnlyFieldNumber; const int OptionsProto::kSelectFieldNumber; const int OptionsProto::kOutputFieldNumber; const int OptionsProto::kDumpToFileFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 OptionsProto::OptionsProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_OptionsProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.tfprof.OptionsProto) } OptionsProto::OptionsProto(const OptionsProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), account_type_regexes_(from.account_type_regexes_), start_name_regexes_(from.start_name_regexes_), trim_name_regexes_(from.trim_name_regexes_), show_name_regexes_(from.show_name_regexes_), hide_name_regexes_(from.hide_name_regexes_), select_(from.select_) { _internal_metadata_.MergeFrom(from._internal_metadata_); order_by_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.order_by().size() > 0) { order_by_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.order_by_); } output_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.output().size() > 0) { output_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_); } dump_to_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.dump_to_file().size() > 0) { dump_to_file_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.dump_to_file_); } ::memcpy(&max_depth_, &from.max_depth_, static_cast<size_t>(reinterpret_cast<char*>(&account_displayed_op_only_) - reinterpret_cast<char*>(&max_depth_)) + sizeof(account_displayed_op_only_)); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.tfprof.OptionsProto) } void OptionsProto::SharedCtor() { order_by_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dump_to_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&max_depth_, 0, static_cast<size_t>( reinterpret_cast<char*>(&account_displayed_op_only_) - reinterpret_cast<char*>(&max_depth_)) + sizeof(account_displayed_op_only_)); } OptionsProto::~OptionsProto() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.tfprof.OptionsProto) SharedDtor(); } void OptionsProto::SharedDtor() { order_by_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dump_to_file_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void OptionsProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* OptionsProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const OptionsProto& OptionsProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_OptionsProto.base); return *internal_default_instance(); } void OptionsProto::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; account_type_regexes_.Clear(); start_name_regexes_.Clear(); trim_name_regexes_.Clear(); show_name_regexes_.Clear(); hide_name_regexes_.Clear(); select_.Clear(); order_by_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dump_to_file_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&max_depth_, 0, static_cast<size_t>( reinterpret_cast<char*>(&account_displayed_op_only_) - reinterpret_cast<char*>(&max_depth_)) + sizeof(account_displayed_op_only_)); _internal_metadata_.Clear(); } bool OptionsProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.tfprof.OptionsProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 max_depth = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &max_depth_))); } else { goto handle_unusual; } break; } // int64 min_bytes = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_bytes_))); } else { goto handle_unusual; } break; } // int64 min_micros = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_micros_))); } else { goto handle_unusual; } break; } // int64 min_params = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_params_))); } else { goto handle_unusual; } break; } // int64 min_float_ops = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_float_ops_))); } else { goto handle_unusual; } break; } // string order_by = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_order_by())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->order_by().data(), static_cast<int>(this->order_by().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.order_by")); } else { goto handle_unusual; } break; } // repeated string account_type_regexes = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_account_type_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->account_type_regexes(this->account_type_regexes_size() - 1).data(), static_cast<int>(this->account_type_regexes(this->account_type_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.account_type_regexes")); } else { goto handle_unusual; } break; } // repeated string start_name_regexes = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_start_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->start_name_regexes(this->start_name_regexes_size() - 1).data(), static_cast<int>(this->start_name_regexes(this->start_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.start_name_regexes")); } else { goto handle_unusual; } break; } // repeated string trim_name_regexes = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_trim_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->trim_name_regexes(this->trim_name_regexes_size() - 1).data(), static_cast<int>(this->trim_name_regexes(this->trim_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.trim_name_regexes")); } else { goto handle_unusual; } break; } // repeated string show_name_regexes = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_show_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->show_name_regexes(this->show_name_regexes_size() - 1).data(), static_cast<int>(this->show_name_regexes(this->show_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.show_name_regexes")); } else { goto handle_unusual; } break; } // repeated string hide_name_regexes = 12; case 12: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(98u /* 98 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_hide_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->hide_name_regexes(this->hide_name_regexes_size() - 1).data(), static_cast<int>(this->hide_name_regexes(this->hide_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.hide_name_regexes")); } else { goto handle_unusual; } break; } // bool account_displayed_op_only = 13; case 13: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(104u /* 104 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &account_displayed_op_only_))); } else { goto handle_unusual; } break; } // repeated string select = 14; case 14: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(114u /* 114 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_select())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->select(this->select_size() - 1).data(), static_cast<int>(this->select(this->select_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.select")); } else { goto handle_unusual; } break; } // string output = 15; case 15: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_output())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->output().data(), static_cast<int>(this->output().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.output")); } else { goto handle_unusual; } break; } // string dump_to_file = 16; case 16: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(130u /* 130 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_dump_to_file())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dump_to_file().data(), static_cast<int>(this->dump_to_file().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.dump_to_file")); } else { goto handle_unusual; } break; } // int64 min_occurrence = 17; case 17: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(136u /* 136 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_occurrence_))); } else { goto handle_unusual; } break; } // int64 step = 18; case 18: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(144u /* 144 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &step_))); } else { goto handle_unusual; } break; } // int64 min_peak_bytes = 19; case 19: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(152u /* 152 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_peak_bytes_))); } else { goto handle_unusual; } break; } // int64 min_residual_bytes = 20; case 20: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(160u /* 160 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_residual_bytes_))); } else { goto handle_unusual; } break; } // int64 min_output_bytes = 21; case 21: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(168u /* 168 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_output_bytes_))); } else { goto handle_unusual; } break; } // int64 min_accelerator_micros = 22; case 22: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(176u /* 176 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_accelerator_micros_))); } else { goto handle_unusual; } break; } // int64 min_cpu_micros = 23; case 23: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(184u /* 184 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_cpu_micros_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.tfprof.OptionsProto) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.tfprof.OptionsProto) return false; #undef DO_ } void OptionsProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 max_depth = 1; if (this->max_depth() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->max_depth(), output); } // int64 min_bytes = 2; if (this->min_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->min_bytes(), output); } // int64 min_micros = 3; if (this->min_micros() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(3, this->min_micros(), output); } // int64 min_params = 4; if (this->min_params() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->min_params(), output); } // int64 min_float_ops = 5; if (this->min_float_ops() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->min_float_ops(), output); } // string order_by = 7; if (this->order_by().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->order_by().data(), static_cast<int>(this->order_by().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.order_by"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 7, this->order_by(), output); } // repeated string account_type_regexes = 8; for (int i = 0, n = this->account_type_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->account_type_regexes(i).data(), static_cast<int>(this->account_type_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.account_type_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 8, this->account_type_regexes(i), output); } // repeated string start_name_regexes = 9; for (int i = 0, n = this->start_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->start_name_regexes(i).data(), static_cast<int>(this->start_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.start_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 9, this->start_name_regexes(i), output); } // repeated string trim_name_regexes = 10; for (int i = 0, n = this->trim_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->trim_name_regexes(i).data(), static_cast<int>(this->trim_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.trim_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 10, this->trim_name_regexes(i), output); } // repeated string show_name_regexes = 11; for (int i = 0, n = this->show_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->show_name_regexes(i).data(), static_cast<int>(this->show_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.show_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 11, this->show_name_regexes(i), output); } // repeated string hide_name_regexes = 12; for (int i = 0, n = this->hide_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->hide_name_regexes(i).data(), static_cast<int>(this->hide_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.hide_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 12, this->hide_name_regexes(i), output); } // bool account_displayed_op_only = 13; if (this->account_displayed_op_only() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(13, this->account_displayed_op_only(), output); } // repeated string select = 14; for (int i = 0, n = this->select_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->select(i).data(), static_cast<int>(this->select(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.select"); ::google::protobuf::internal::WireFormatLite::WriteString( 14, this->select(i), output); } // string output = 15; if (this->output().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->output().data(), static_cast<int>(this->output().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.output"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 15, this->output(), output); } // string dump_to_file = 16; if (this->dump_to_file().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dump_to_file().data(), static_cast<int>(this->dump_to_file().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.dump_to_file"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 16, this->dump_to_file(), output); } // int64 min_occurrence = 17; if (this->min_occurrence() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(17, this->min_occurrence(), output); } // int64 step = 18; if (this->step() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(18, this->step(), output); } // int64 min_peak_bytes = 19; if (this->min_peak_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(19, this->min_peak_bytes(), output); } // int64 min_residual_bytes = 20; if (this->min_residual_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(20, this->min_residual_bytes(), output); } // int64 min_output_bytes = 21; if (this->min_output_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(21, this->min_output_bytes(), output); } // int64 min_accelerator_micros = 22; if (this->min_accelerator_micros() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(22, this->min_accelerator_micros(), output); } // int64 min_cpu_micros = 23; if (this->min_cpu_micros() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(23, this->min_cpu_micros(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.tfprof.OptionsProto) } ::google::protobuf::uint8* OptionsProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 max_depth = 1; if (this->max_depth() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->max_depth(), target); } // int64 min_bytes = 2; if (this->min_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->min_bytes(), target); } // int64 min_micros = 3; if (this->min_micros() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(3, this->min_micros(), target); } // int64 min_params = 4; if (this->min_params() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->min_params(), target); } // int64 min_float_ops = 5; if (this->min_float_ops() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->min_float_ops(), target); } // string order_by = 7; if (this->order_by().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->order_by().data(), static_cast<int>(this->order_by().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.order_by"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 7, this->order_by(), target); } // repeated string account_type_regexes = 8; for (int i = 0, n = this->account_type_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->account_type_regexes(i).data(), static_cast<int>(this->account_type_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.account_type_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(8, this->account_type_regexes(i), target); } // repeated string start_name_regexes = 9; for (int i = 0, n = this->start_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->start_name_regexes(i).data(), static_cast<int>(this->start_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.start_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(9, this->start_name_regexes(i), target); } // repeated string trim_name_regexes = 10; for (int i = 0, n = this->trim_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->trim_name_regexes(i).data(), static_cast<int>(this->trim_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.trim_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(10, this->trim_name_regexes(i), target); } // repeated string show_name_regexes = 11; for (int i = 0, n = this->show_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->show_name_regexes(i).data(), static_cast<int>(this->show_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.show_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(11, this->show_name_regexes(i), target); } // repeated string hide_name_regexes = 12; for (int i = 0, n = this->hide_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->hide_name_regexes(i).data(), static_cast<int>(this->hide_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.hide_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(12, this->hide_name_regexes(i), target); } // bool account_displayed_op_only = 13; if (this->account_displayed_op_only() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(13, this->account_displayed_op_only(), target); } // repeated string select = 14; for (int i = 0, n = this->select_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->select(i).data(), static_cast<int>(this->select(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.select"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(14, this->select(i), target); } // string output = 15; if (this->output().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->output().data(), static_cast<int>(this->output().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.output"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 15, this->output(), target); } // string dump_to_file = 16; if (this->dump_to_file().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dump_to_file().data(), static_cast<int>(this->dump_to_file().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.dump_to_file"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 16, this->dump_to_file(), target); } // int64 min_occurrence = 17; if (this->min_occurrence() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(17, this->min_occurrence(), target); } // int64 step = 18; if (this->step() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(18, this->step(), target); } // int64 min_peak_bytes = 19; if (this->min_peak_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(19, this->min_peak_bytes(), target); } // int64 min_residual_bytes = 20; if (this->min_residual_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(20, this->min_residual_bytes(), target); } // int64 min_output_bytes = 21; if (this->min_output_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(21, this->min_output_bytes(), target); } // int64 min_accelerator_micros = 22; if (this->min_accelerator_micros() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(22, this->min_accelerator_micros(), target); } // int64 min_cpu_micros = 23; if (this->min_cpu_micros() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(23, this->min_cpu_micros(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.tfprof.OptionsProto) return target; } size_t OptionsProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.tfprof.OptionsProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated string account_type_regexes = 8; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->account_type_regexes_size()); for (int i = 0, n = this->account_type_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->account_type_regexes(i)); } // repeated string start_name_regexes = 9; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->start_name_regexes_size()); for (int i = 0, n = this->start_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->start_name_regexes(i)); } // repeated string trim_name_regexes = 10; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->trim_name_regexes_size()); for (int i = 0, n = this->trim_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->trim_name_regexes(i)); } // repeated string show_name_regexes = 11; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->show_name_regexes_size()); for (int i = 0, n = this->show_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->show_name_regexes(i)); } // repeated string hide_name_regexes = 12; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->hide_name_regexes_size()); for (int i = 0, n = this->hide_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->hide_name_regexes(i)); } // repeated string select = 14; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->select_size()); for (int i = 0, n = this->select_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->select(i)); } // string order_by = 7; if (this->order_by().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->order_by()); } // string output = 15; if (this->output().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->output()); } // string dump_to_file = 16; if (this->dump_to_file().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->dump_to_file()); } // int64 max_depth = 1; if (this->max_depth() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->max_depth()); } // int64 min_bytes = 2; if (this->min_bytes() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_bytes()); } // int64 min_micros = 3; if (this->min_micros() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_micros()); } // int64 min_params = 4; if (this->min_params() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_params()); } // int64 min_float_ops = 5; if (this->min_float_ops() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_float_ops()); } // int64 min_occurrence = 17; if (this->min_occurrence() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_occurrence()); } // int64 step = 18; if (this->step() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->step()); } // int64 min_peak_bytes = 19; if (this->min_peak_bytes() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_peak_bytes()); } // int64 min_residual_bytes = 20; if (this->min_residual_bytes() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_residual_bytes()); } // int64 min_output_bytes = 21; if (this->min_output_bytes() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_output_bytes()); } // int64 min_accelerator_micros = 22; if (this->min_accelerator_micros() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_accelerator_micros()); } // int64 min_cpu_micros = 23; if (this->min_cpu_micros() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_cpu_micros()); } // bool account_displayed_op_only = 13; if (this->account_displayed_op_only() != 0) { total_size += 1 + 1; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void OptionsProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.tfprof.OptionsProto) GOOGLE_DCHECK_NE(&from, this); const OptionsProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const OptionsProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.tfprof.OptionsProto) MergeFrom(*source); } } void OptionsProto::MergeFrom(const OptionsProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.tfprof.OptionsProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; account_type_regexes_.MergeFrom(from.account_type_regexes_); start_name_regexes_.MergeFrom(from.start_name_regexes_); trim_name_regexes_.MergeFrom(from.trim_name_regexes_); show_name_regexes_.MergeFrom(from.show_name_regexes_); hide_name_regexes_.MergeFrom(from.hide_name_regexes_); select_.MergeFrom(from.select_); if (from.order_by().size() > 0) { order_by_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.order_by_); } if (from.output().size() > 0) { output_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_); } if (from.dump_to_file().size() > 0) { dump_to_file_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.dump_to_file_); } if (from.max_depth() != 0) { set_max_depth(from.max_depth()); } if (from.min_bytes() != 0) { set_min_bytes(from.min_bytes()); } if (from.min_micros() != 0) { set_min_micros(from.min_micros()); } if (from.min_params() != 0) { set_min_params(from.min_params()); } if (from.min_float_ops() != 0) { set_min_float_ops(from.min_float_ops()); } if (from.min_occurrence() != 0) { set_min_occurrence(from.min_occurrence()); } if (from.step() != 0) { set_step(from.step()); } if (from.min_peak_bytes() != 0) { set_min_peak_bytes(from.min_peak_bytes()); } if (from.min_residual_bytes() != 0) { set_min_residual_bytes(from.min_residual_bytes()); } if (from.min_output_bytes() != 0) { set_min_output_bytes(from.min_output_bytes()); } if (from.min_accelerator_micros() != 0) { set_min_accelerator_micros(from.min_accelerator_micros()); } if (from.min_cpu_micros() != 0) { set_min_cpu_micros(from.min_cpu_micros()); } if (from.account_displayed_op_only() != 0) { set_account_displayed_op_only(from.account_displayed_op_only()); } } void OptionsProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.tfprof.OptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } void OptionsProto::CopyFrom(const OptionsProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.tfprof.OptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } bool OptionsProto::IsInitialized() const { return true; } void OptionsProto::Swap(OptionsProto* other) { if (other == this) return; InternalSwap(other); } void OptionsProto::InternalSwap(OptionsProto* other) { using std::swap; account_type_regexes_.InternalSwap(CastToBase(&other->account_type_regexes_)); start_name_regexes_.InternalSwap(CastToBase(&other->start_name_regexes_)); trim_name_regexes_.InternalSwap(CastToBase(&other->trim_name_regexes_)); show_name_regexes_.InternalSwap(CastToBase(&other->show_name_regexes_)); hide_name_regexes_.InternalSwap(CastToBase(&other->hide_name_regexes_)); select_.InternalSwap(CastToBase(&other->select_)); order_by_.Swap(&other->order_by_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); output_.Swap(&other->output_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); dump_to_file_.Swap(&other->dump_to_file_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(max_depth_, other->max_depth_); swap(min_bytes_, other->min_bytes_); swap(min_micros_, other->min_micros_); swap(min_params_, other->min_params_); swap(min_float_ops_, other->min_float_ops_); swap(min_occurrence_, other->min_occurrence_); swap(step_, other->step_); swap(min_peak_bytes_, other->min_peak_bytes_); swap(min_residual_bytes_, other->min_residual_bytes_); swap(min_output_bytes_, other->min_output_bytes_); swap(min_accelerator_micros_, other->min_accelerator_micros_); swap(min_cpu_micros_, other->min_cpu_micros_); swap(account_displayed_op_only_, other->account_displayed_op_only_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata OptionsProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== AdvisorOptionsProto_CheckersEntry_DoNotUse::AdvisorOptionsProto_CheckersEntry_DoNotUse() {} AdvisorOptionsProto_CheckersEntry_DoNotUse::AdvisorOptionsProto_CheckersEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void AdvisorOptionsProto_CheckersEntry_DoNotUse::MergeFrom(const AdvisorOptionsProto_CheckersEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata AdvisorOptionsProto_CheckersEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[1]; } void AdvisorOptionsProto_CheckersEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse() {} AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::MergeFrom(const AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[2]; } void AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void AdvisorOptionsProto_CheckerOption::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AdvisorOptionsProto_CheckerOption::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AdvisorOptionsProto_CheckerOption::AdvisorOptionsProto_CheckerOption() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) } AdvisorOptionsProto_CheckerOption::AdvisorOptionsProto_CheckerOption(const AdvisorOptionsProto_CheckerOption& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); options_.MergeFrom(from.options_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) } void AdvisorOptionsProto_CheckerOption::SharedCtor() { } AdvisorOptionsProto_CheckerOption::~AdvisorOptionsProto_CheckerOption() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) SharedDtor(); } void AdvisorOptionsProto_CheckerOption::SharedDtor() { } void AdvisorOptionsProto_CheckerOption::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* AdvisorOptionsProto_CheckerOption::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AdvisorOptionsProto_CheckerOption& AdvisorOptionsProto_CheckerOption::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption.base); return *internal_default_instance(); } void AdvisorOptionsProto_CheckerOption::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; options_.Clear(); _internal_metadata_.Clear(); } bool AdvisorOptionsProto_CheckerOption::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<string, string> options = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&options_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.value")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) return false; #undef DO_ } void AdvisorOptionsProto_CheckerOption::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, string> options = 1; if (!this->options().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.value"); } }; if (output->IsSerializationDeterministic() && this->options().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->options().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(options_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it) { entry.reset(options_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) } ::google::protobuf::uint8* AdvisorOptionsProto_CheckerOption::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, string> options = 1; if (!this->options().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.value"); } }; if (deterministic && this->options().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->options().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(options_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it) { entry.reset(options_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) return target; } size_t AdvisorOptionsProto_CheckerOption::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, string> options = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->options_size()); { ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it) { entry.reset(options_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AdvisorOptionsProto_CheckerOption::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) GOOGLE_DCHECK_NE(&from, this); const AdvisorOptionsProto_CheckerOption* source = ::google::protobuf::internal::DynamicCastToGenerated<const AdvisorOptionsProto_CheckerOption>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) MergeFrom(*source); } } void AdvisorOptionsProto_CheckerOption::MergeFrom(const AdvisorOptionsProto_CheckerOption& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; options_.MergeFrom(from.options_); } void AdvisorOptionsProto_CheckerOption::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) if (&from == this) return; Clear(); MergeFrom(from); } void AdvisorOptionsProto_CheckerOption::CopyFrom(const AdvisorOptionsProto_CheckerOption& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) if (&from == this) return; Clear(); MergeFrom(from); } bool AdvisorOptionsProto_CheckerOption::IsInitialized() const { return true; } void AdvisorOptionsProto_CheckerOption::Swap(AdvisorOptionsProto_CheckerOption* other) { if (other == this) return; InternalSwap(other); } void AdvisorOptionsProto_CheckerOption::InternalSwap(AdvisorOptionsProto_CheckerOption* other) { using std::swap; options_.Swap(&other->options_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata AdvisorOptionsProto_CheckerOption::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void AdvisorOptionsProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AdvisorOptionsProto::kCheckersFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AdvisorOptionsProto::AdvisorOptionsProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) } AdvisorOptionsProto::AdvisorOptionsProto(const AdvisorOptionsProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); checkers_.MergeFrom(from.checkers_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) } void AdvisorOptionsProto::SharedCtor() { } AdvisorOptionsProto::~AdvisorOptionsProto() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) SharedDtor(); } void AdvisorOptionsProto::SharedDtor() { } void AdvisorOptionsProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* AdvisorOptionsProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AdvisorOptionsProto& AdvisorOptionsProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto.base); return *internal_default_instance(); } void AdvisorOptionsProto::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; checkers_.Clear(); _internal_metadata_.Clear(); } bool AdvisorOptionsProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { AdvisorOptionsProto_CheckersEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< AdvisorOptionsProto_CheckersEntry_DoNotUse, ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 >, ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption > > parser(&checkers_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckersEntry.key")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) return false; #undef DO_ } void AdvisorOptionsProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; if (!this->checkers().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckersEntry.key"); } }; if (output->IsSerializationDeterministic() && this->checkers().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->checkers().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(checkers_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it) { entry.reset(checkers_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) } ::google::protobuf::uint8* AdvisorOptionsProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; if (!this->checkers().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckersEntry.key"); } }; if (deterministic && this->checkers().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->checkers().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(checkers_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it) { entry.reset(checkers_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) return target; } size_t AdvisorOptionsProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->checkers_size()); { ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it) { entry.reset(checkers_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AdvisorOptionsProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) GOOGLE_DCHECK_NE(&from, this); const AdvisorOptionsProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const AdvisorOptionsProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) MergeFrom(*source); } } void AdvisorOptionsProto::MergeFrom(const AdvisorOptionsProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; checkers_.MergeFrom(from.checkers_); } void AdvisorOptionsProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } void AdvisorOptionsProto::CopyFrom(const AdvisorOptionsProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } bool AdvisorOptionsProto::IsInitialized() const { return true; } void AdvisorOptionsProto::Swap(AdvisorOptionsProto* other) { if (other == this) return; InternalSwap(other); } void AdvisorOptionsProto::InternalSwap(AdvisorOptionsProto* other) { using std::swap; checkers_.Swap(&other->checkers_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata AdvisorOptionsProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace tfprof } // namespace tensorflow } // namespace diplomacy namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::OptionsProto* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::OptionsProto >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::OptionsProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
45.711287
269
0.711984
wwongkamjan
3a39cfdc9dfa49dd4df7d185703759de58d8f167
3,845
cpp
C++
firmware/uvc_controller/mbed-os/drivers/source/PwmOut.cpp
davewhiiite/uvc
fd45223097eed5a824294db975b3c74aa5f5cc8f
[ "MIT" ]
1
2021-06-12T14:54:07.000Z
2021-06-12T14:54:07.000Z
firmware/uvc_controller/mbed-os/drivers/source/PwmOut.cpp
davewhiiite/uvc
fd45223097eed5a824294db975b3c74aa5f5cc8f
[ "MIT" ]
null
null
null
firmware/uvc_controller/mbed-os/drivers/source/PwmOut.cpp
davewhiiite/uvc
fd45223097eed5a824294db975b3c74aa5f5cc8f
[ "MIT" ]
null
null
null
/* mbed Microcontroller Library * Copyright (c) 2006-2019 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * 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 "drivers/PwmOut.h" #if DEVICE_PWMOUT #include "platform/mbed_critical.h" #include "platform/mbed_power_mgmt.h" #include "platform/mbed_assert.h" namespace mbed { PwmOut::PwmOut(PinName pin) : _pin(pin), _deep_sleep_locked(false), _initialized(false), _duty_cycle(0) { PwmOut::init(); } PwmOut::PwmOut(const PinMap &pinmap) : _deep_sleep_locked(false) { core_util_critical_section_enter(); pwmout_init_direct(&_pwm, &pinmap); core_util_critical_section_exit(); } PwmOut::~PwmOut() { PwmOut::deinit(); } void PwmOut::write(float value) { core_util_critical_section_enter(); pwmout_write(&_pwm, value); core_util_critical_section_exit(); } float PwmOut::read() { core_util_critical_section_enter(); float val = pwmout_read(&_pwm); core_util_critical_section_exit(); return val; } void PwmOut::period(float seconds) { core_util_critical_section_enter(); pwmout_period(&_pwm, seconds); core_util_critical_section_exit(); } void PwmOut::period_ms(int ms) { core_util_critical_section_enter(); pwmout_period_ms(&_pwm, ms); core_util_critical_section_exit(); } void PwmOut::period_us(int us) { core_util_critical_section_enter(); pwmout_period_us(&_pwm, us); core_util_critical_section_exit(); } void PwmOut::pulsewidth(float seconds) { core_util_critical_section_enter(); pwmout_pulsewidth(&_pwm, seconds); core_util_critical_section_exit(); } void PwmOut::pulsewidth_ms(int ms) { core_util_critical_section_enter(); pwmout_pulsewidth_ms(&_pwm, ms); core_util_critical_section_exit(); } void PwmOut::pulsewidth_us(int us) { core_util_critical_section_enter(); pwmout_pulsewidth_us(&_pwm, us); core_util_critical_section_exit(); } void PwmOut::suspend() { core_util_critical_section_enter(); if (_initialized) { _duty_cycle = PwmOut::read(); PwmOut::deinit(); } core_util_critical_section_exit(); } void PwmOut::resume() { core_util_critical_section_enter(); if (!_initialized) { PwmOut::init(); PwmOut::write(_duty_cycle); } core_util_critical_section_exit(); } void PwmOut::lock_deep_sleep() { if (_deep_sleep_locked == false) { sleep_manager_lock_deep_sleep(); _deep_sleep_locked = true; } } void PwmOut::unlock_deep_sleep() { if (_deep_sleep_locked == true) { sleep_manager_unlock_deep_sleep(); _deep_sleep_locked = false; } } void PwmOut::init() { core_util_critical_section_enter(); if (!_initialized) { pwmout_init(&_pwm, _pin); lock_deep_sleep(); _initialized = true; } core_util_critical_section_exit(); } void PwmOut::deinit() { core_util_critical_section_enter(); if (_initialized) { pwmout_free(&_pwm); unlock_deep_sleep(); _initialized = false; } core_util_critical_section_exit(); } } // namespace mbed #endif // #if DEVICE_PWMOUT
22.354651
76
0.669961
davewhiiite
3a3b6b6d891e5a1c5f550069227dd999325afc22
6,457
cpp
C++
SCTK/src/asclite/test/alignment_test.cpp
IIP-Sogang/Audio-Visual-Speech-Recognition
bd03be91135acbc6162b83092d462b7fe71dd007
[ "MIT" ]
113
2018-11-20T06:00:39.000Z
2022-03-29T06:01:55.000Z
SCTK/src/asclite/test/alignment_test.cpp
IIP-Sogang/Audio-Visual-Speech-Recognition
bd03be91135acbc6162b83092d462b7fe71dd007
[ "MIT" ]
28
2017-09-11T16:20:26.000Z
2022-02-13T14:16:33.000Z
SCTK/src/asclite/test/alignment_test.cpp
IIP-Sogang/Audio-Visual-Speech-Recognition
bd03be91135acbc6162b83092d462b7fe71dd007
[ "MIT" ]
42
2017-09-06T14:47:09.000Z
2022-03-04T19:41:21.000Z
/* * ASCLITE * Author: Jerome Ajot, Jon Fiscus, Nicolas Radde, Chris Laprun * * This software was developed at the National Institute of Standards and Technology by * employees of the Federal Government in the course of their official duties. Pursuant * to title 17 Section 105 of the United States Code this software is not subject to * copyright protection and is in the public domain. ASCLITE is an experimental system. * NIST assumes no responsibility whatsoever for its use by other parties, and makes no * guarantees, expressed or implied, about its quality, reliability, or any other * characteristic. We would appreciate acknowledgement if the software is used. * * THIS SOFTWARE IS PROVIDED "AS IS." With regard to this software, NIST MAKES NO EXPRESS * OR IMPLIED WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING MERCHANTABILITY, * OR FITNESS FOR A PARTICULAR PURPOSE. */ #include "alignment_test.h" #include "graphalignedsegment.h" #include "alignedspeech.h" AlignmentTest::AlignmentTest() { bench = new StdBenchmark(); } AlignmentTest::~AlignmentTest() { //delete bench; } void AlignmentTest::TestAll() { cout << "Testing insertions..." << endl; TestInsertions(); cout << "OK!" << endl; cout << "Testing deletions..." << endl; TestDeletions(); cout << "OK!" << endl; } void AlignmentTest::TestInsertions() { Alignment* ali; SegmentsGroup* sg; std::size_t testIndex = 2; // simple insertion, one segment ali = GetAlignmentFor(testIndex, &sg); Segment* ref = sg->GetReference(0)[0]; Segment* hyp = sg->GetHypothesis(0)[0]; vector< Token* > refs = ref->ToTopologicalOrderedStruct(); vector< Token* > hyps = hyp->ToTopologicalOrderedStruct(); cout << "Single Insertion tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); Speech* refSpeech = ref->GetParentSpeech(); AlignedSpeech* asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); AlignedSegment* asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); TokenAlignment* ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == refs[0]); assert(ta->GetTokenFor("hyp") == hyps[0]); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[1]); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == refs[1]); assert(ta->GetTokenFor("hyp") == hyps[2]); cout << " OK." << endl; testIndex = 4; // only insertion, one segment ali = GetAlignmentFor(testIndex, &sg); ref = sg->GetReference(0)[0]; hyp = sg->GetHypothesis(0)[0]; refs = ref->ToTopologicalOrderedStruct(); hyps = hyp->ToTopologicalOrderedStruct(); cout << "Only Insertion tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); refSpeech = ref->GetParentSpeech(); asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[0]); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[1]); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[2]); cout << " OK." << endl; delete ali; delete sg; } void AlignmentTest::TestDeletions() { Alignment* ali; SegmentsGroup* sg; std::size_t testIndex = 3; // simple deletion, one segment ali = GetAlignmentFor(testIndex, &sg); Segment* ref = sg->GetReference(0)[0]; Segment* hyp = sg->GetHypothesis(0)[0]; vector< Token* > refs = ref->ToTopologicalOrderedStruct(); vector< Token* > hyps = hyp->ToTopologicalOrderedStruct(); cout << "Single Deletion tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); Speech* refSpeech = ref->GetParentSpeech(); AlignedSpeech* asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); AlignedSegment* asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); TokenAlignment* ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == refs[0]); assert(ta->GetTokenFor("hyp") == hyps[0]); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == refs[1]); assert(ta->GetTokenFor("hyp") == NULL); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == refs[2]); assert(ta->GetTokenFor("hyp") == hyps[1]); cout << " OK." << endl; testIndex = 5; // only deletions, one segment ali = GetAlignmentFor(testIndex, &sg); ref = sg->GetReference(0)[0]; hyp = sg->GetHypothesis(0)[0]; refs = ref->ToTopologicalOrderedStruct(); hyps = hyp->ToTopologicalOrderedStruct(); cout << "Only Deletions tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); refSpeech = ref->GetParentSpeech(); asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == refs[0]); assert(ta->GetTokenFor("hyp") == NULL); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == refs[1]); assert(ta->GetTokenFor("hyp") == NULL); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == refs[2]); assert(ta->GetTokenFor("hyp") == NULL); cout << " OK." << endl; delete ali; delete sg; } Alignment* AlignmentTest::GetAlignmentFor(std::size_t testIndex, SegmentsGroup** sg) { Alignment* ali = NULL; GraphAlignedSegment* gas = bench->GetResult(testIndex); *sg = bench->GetTest(testIndex); ali = new Alignment(); ali->AddSystem("", "hyp"); ali->AddGraphAlignedSegment(gas, "hyp", *sg); return ali; }
33.630208
90
0.690878
IIP-Sogang
3a3c00a2e9e748161f51c2fe809691f2da6fc39f
1,140
cpp
C++
TAO/orbsvcs/performance-tests/RTEvent/lib/RTEC_Initializer.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/performance-tests/RTEvent/lib/RTEC_Initializer.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/performance-tests/RTEvent/lib/RTEC_Initializer.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
/** * @file RTEC_Initializer.cpp * * $Id: RTEC_Initializer.cpp 91675 2010-09-08 19:09:19Z johnnyw $ * * @author Carlos O'Ryan <coryan@uci.edu> */ #include "RTEC_Initializer.h" #include "RTCORBA_Setup.h" #include "orbsvcs/Event/EC_Event_Channel.h" #include "orbsvcs/Event/EC_Default_Factory.h" #include "orbsvcs/Event/EC_RTCORBA_Factory.h" #include "ace/Dynamic_Service.h" TAO_EC_Event_Channel * RTEC_Initializer::create (PortableServer::POA_ptr consumer_poa, PortableServer::POA_ptr supplier_poa, RTCORBA_Setup * rtcorba_setup) { TAO_EC_Event_Channel_Attributes attr (consumer_poa, supplier_poa); if (rtcorba_setup == 0) { return new TAO_EC_Event_Channel (attr); } TAO_EC_Factory *body = ACE_Dynamic_Service<TAO_EC_Factory>::instance ("EC_Factory"); auto_ptr<TAO_EC_Factory> factory ( new TAO_EC_RTCORBA_Factory (body, rtcorba_setup->lanes ())); TAO_EC_Event_Channel *ec = new TAO_EC_Event_Channel (attr, factory.get (), 1); factory.release (); return ec; }
26.511628
65
0.659649
cflowe
3a3c737e177e79caa3dd9fb3ffa71b10e4190155
1,583
hpp
C++
EFI/CLOVER/kexts/Other/Lilu_v1.4.3-Debug.kext/Contents/Resources/Headers/kern_policy.hpp
zhujinle/Lenovo-yoga-c930-hackintosh
679ec3efe7e63b102e5a2ad7a3f5a1cd48a949ca
[ "MIT" ]
56
2019-11-07T01:57:38.000Z
2021-06-07T21:09:52.000Z
EFI/CLOVER/kexts/Other/Lilu_v1.4.3-Debug.kext/Contents/Resources/Headers/kern_policy.hpp
zhujinle/Lenovo-yoga-c930-hackintosh
679ec3efe7e63b102e5a2ad7a3f5a1cd48a949ca
[ "MIT" ]
10
2020-07-27T01:59:55.000Z
2021-03-02T02:17:04.000Z
EFI/CLOVER/kexts/Other/Lilu_v1.4.3-Debug.kext/Contents/Resources/Headers/kern_policy.hpp
zhujinle/Lenovo-yoga-c930-hackintosh
679ec3efe7e63b102e5a2ad7a3f5a1cd48a949ca
[ "MIT" ]
11
2020-07-10T07:03:08.000Z
2021-05-14T06:44:19.000Z
// // kern_policy.hpp // Lilu // // Copyright © 2016-2017 vit9696. All rights reserved. // #ifndef kern_policy_hpp #define kern_policy_hpp #include <Headers/kern_config.hpp> #include <sys/types.h> #include <sys/proc.h> #include <Library/security/mac_framework.h> #include <Library/security/mac_policy.h> #include <Headers/kern_util.hpp> class Policy { /** * TrustedBSD Policy handle */ mac_policy_handle_t policyHandle {0}; /** * TrustedBSD policy configuration */ mac_policy_conf policyConf; public: /** * May be used at TrustedBSD policy initialisation * * @param conf policy configuration */ static void dummyPolicyInitBSD(mac_policy_conf *conf) { DBGLOG("policy", "init bsd"); } /** * Compile-time policy constructor * * @param name policy name literal * @param descr policy description literal * @param ops policy functions */ constexpr Policy(const char *name, const char *descr, struct mac_policy_ops *ops) : policyConf{ .mpc_name = name, .mpc_fullname = descr, .mpc_labelnames = nullptr, .mpc_labelname_count = 0, .mpc_ops = ops, // Our policies are loaded very early and are static. We cannot unload them. .mpc_loadtime_flags = 0 /*MPC_LOADTIME_FLAG_UNLOADOK*/, .mpc_field_off = nullptr, .mpc_runtime_flags = 0 } { } /** * Registers TrustedBSD policy * * @return true on success */ EXPORT bool registerPolicy(); /** * Unregisters TrustedBSD policy if allowed * * @return true on success */ EXPORT bool unregisterPolicy(); }; #endif /* kern_policy_hpp */
21.106667
96
0.689829
zhujinle
3a3e2f2b818c38b1c01f390ef641f9e3b0f0b91b
1,066
cpp
C++
Cplusplus_Study/array_vector.cpp
SuperBruceJia/paper-reading
ccfa34706fd525b1c47ec2476896efbd020c7210
[ "MIT" ]
11
2020-11-13T02:47:56.000Z
2022-03-25T06:13:06.000Z
Cplusplus_Study/array_vector.cpp
SuperBruceJia/paper-reading
ccfa34706fd525b1c47ec2476896efbd020c7210
[ "MIT" ]
null
null
null
Cplusplus_Study/array_vector.cpp
SuperBruceJia/paper-reading
ccfa34706fd525b1c47ec2476896efbd020c7210
[ "MIT" ]
2
2021-10-10T13:42:20.000Z
2021-12-14T09:59:23.000Z
#include <iostream> using namespace std; int main(int argc, char *argv[]) { char vowels [] {'a', 'e','i', 'w', 'r'}; cout << "The first vowels is " << vowels[0] << endl; cout << "The last vowels is " << vowels[4] << endl; double hi_temps [] {90.1, 89.7, 77.5, 81.6}; cout << "The first high temperature is " << hi_temps[0] << endl; hi_temps[0] = 100.7; for (int i=0; i<=3; i++) cout << hi_temps[i] << endl; int test_score [] {}; cout << "Input 5 test scores: " << endl; cin >> test_score[0]; cin >> test_score[1]; cin >> test_score[2]; cin >> test_score[3]; cin >> test_score[4]; cout << "First score at index 0 is " << test_score[0] << endl; cout << "Second score at index 1 is " << test_score[1] << endl; cout << "Third score at index 2 is " << test_score[2] << endl; cout << "Fourth score at index 3 is " << test_score[3] << endl; cout << "Fifth score at index 4 is " << test_score[4] << endl; cout << test_score << endl; return 0; }
29.611111
68
0.532833
SuperBruceJia
3a4020e072bbf5b9b13187ab9910d8a19da1ed8d
13,603
cc
C++
cc/resources/picture_pile_impl.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
cc/resources/picture_pile_impl.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
cc/resources/picture_pile_impl.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <limits> #include "base/debug/trace_event.h" #include "cc/base/region.h" #include "cc/debug/benchmark_instrumentation.h" #include "cc/debug/debug_colors.h" #include "cc/resources/picture_pile_impl.h" #include "skia/ext/analysis_canvas.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSize.h" #include "ui/gfx/rect_conversions.h" #include "ui/gfx/size_conversions.h" #include "ui/gfx/skia_util.h" namespace cc { PicturePileImpl::ClonesForDrawing::ClonesForDrawing( const PicturePileImpl* pile, int num_threads) { for (int i = 0; i < num_threads; i++) { scoped_refptr<PicturePileImpl> clone = PicturePileImpl::CreateCloneForDrawing(pile, i); clones_.push_back(clone); } } PicturePileImpl::ClonesForDrawing::~ClonesForDrawing() { } scoped_refptr<PicturePileImpl> PicturePileImpl::Create() { return make_scoped_refptr(new PicturePileImpl); } scoped_refptr<PicturePileImpl> PicturePileImpl::CreateFromOther( const PicturePileBase* other) { return make_scoped_refptr(new PicturePileImpl(other)); } scoped_refptr<PicturePileImpl> PicturePileImpl::CreateCloneForDrawing( const PicturePileImpl* other, unsigned thread_index) { return make_scoped_refptr(new PicturePileImpl(other, thread_index)); } PicturePileImpl::PicturePileImpl() : clones_for_drawing_(ClonesForDrawing(this, 0)) { } PicturePileImpl::PicturePileImpl(const PicturePileBase* other) : PicturePileBase(other), clones_for_drawing_(ClonesForDrawing(this, num_raster_threads())) { } PicturePileImpl::PicturePileImpl( const PicturePileImpl* other, unsigned thread_index) : PicturePileBase(other, thread_index), clones_for_drawing_(ClonesForDrawing(this, 0)) { } PicturePileImpl::~PicturePileImpl() { } PicturePileImpl* PicturePileImpl::GetCloneForDrawingOnThread( unsigned thread_index) const { CHECK_GT(clones_for_drawing_.clones_.size(), thread_index); return clones_for_drawing_.clones_[thread_index].get(); } void PicturePileImpl::RasterDirect( SkCanvas* canvas, gfx::Rect canvas_rect, float contents_scale, RasterStats* raster_stats) { RasterCommon(canvas, NULL, canvas_rect, contents_scale, raster_stats); } void PicturePileImpl::RasterForAnalysis( skia::AnalysisCanvas* canvas, gfx::Rect canvas_rect, float contents_scale) { RasterCommon(canvas, canvas, canvas_rect, contents_scale, NULL); } void PicturePileImpl::RasterToBitmap( SkCanvas* canvas, gfx::Rect canvas_rect, float contents_scale, RasterStats* raster_stats) { #ifndef NDEBUG // Any non-painted areas will be left in this color. canvas->clear(DebugColors::NonPaintedFillColor()); #endif // NDEBUG // If this picture has opaque contents, it is guaranteeing that it will // draw an opaque rect the size of the layer. If it is not, then we must // clear this canvas ourselves. if (!contents_opaque_) { // Clearing is about ~4x faster than drawing a rect even if the content // isn't covering a majority of the canvas. canvas->clear(SK_ColorTRANSPARENT); } else { // Even if it is opaque, on any rasterizations that touch the edge of the // layer, we also need to raster the background color underneath the last // texel (since the recording won't cover it) and outside the last texel // (due to linear filtering when using this texture). gfx::SizeF total_content_size = gfx::ScaleSize(tiling_.total_size(), contents_scale); gfx::Rect content_rect(gfx::ToCeiledSize(total_content_size)); gfx::Rect deflated_content_rect = content_rect; content_rect.Intersect(canvas_rect); // The final texel of content may only be partially covered by a // rasterization; this rect represents the content rect that is fully // covered by content. deflated_content_rect.Inset(0, 0, 1, 1); deflated_content_rect.Intersect(canvas_rect); if (!deflated_content_rect.Contains(canvas_rect)) { // Drawing at most 2 x 2 x (canvas width + canvas height) texels is 2-3X // faster than clearing, so special case this. canvas->save(); gfx::Rect inflated_content_rect = content_rect; inflated_content_rect.Inset(0, 0, -1, -1); canvas->clipRect(gfx::RectToSkRect(inflated_content_rect), SkRegion::kReplace_Op); canvas->clipRect(gfx::RectToSkRect(deflated_content_rect), SkRegion::kDifference_Op); canvas->drawColor(background_color_, SkXfermode::kSrc_Mode); canvas->restore(); } } RasterCommon(canvas, NULL, canvas_rect, contents_scale, raster_stats); } void PicturePileImpl::RasterCommon( SkCanvas* canvas, SkDrawPictureCallback* callback, gfx::Rect canvas_rect, float contents_scale, RasterStats* raster_stats) { DCHECK(contents_scale >= min_contents_scale_); canvas->translate(-canvas_rect.x(), -canvas_rect.y()); gfx::SizeF total_content_size = gfx::ScaleSize(tiling_.total_size(), contents_scale); gfx::Rect total_content_rect(gfx::ToCeiledSize(total_content_size)); gfx::Rect content_rect = total_content_rect; content_rect.Intersect(canvas_rect); // Rasterize the collection of relevant picture piles. gfx::Rect layer_rect = gfx::ScaleToEnclosingRect( content_rect, 1.f / contents_scale); canvas->clipRect(gfx::RectToSkRect(content_rect), SkRegion::kIntersect_Op); Region unclipped(content_rect); if (raster_stats) { raster_stats->total_pixels_rasterized = 0; raster_stats->total_rasterize_time = base::TimeDelta::FromSeconds(0); raster_stats->best_rasterize_time = base::TimeDelta::FromSeconds(0); } for (TilingData::Iterator tile_iter(&tiling_, layer_rect); tile_iter; ++tile_iter) { PictureListMap::iterator map_iter = picture_list_map_.find(tile_iter.index()); if (map_iter == picture_list_map_.end()) continue; PictureList& pic_list= map_iter->second; if (pic_list.empty()) continue; // Raster through the picture list top down, using clips to make sure that // pictures on top are not overdrawn by pictures on the bottom. for (PictureList::reverse_iterator i = pic_list.rbegin(); i != pic_list.rend(); ++i) { // This is intentionally *enclosed* rect, so that the clip is aligned on // integral post-scale content pixels and does not extend past the edges // of the picture's layer rect. The min_contents_scale enforces that // enough buffer pixels have been added such that the enclosed rect // encompasses all invalidated pixels at any larger scale level. gfx::Rect content_clip = gfx::ScaleToEnclosedRect( (*i)->LayerRect(), contents_scale); DCHECK(!content_clip.IsEmpty()) << "Layer rect: " << (*i)->LayerRect().ToString() << "Contents scale: " << contents_scale; content_clip.Intersect(canvas_rect); if (!unclipped.Intersects(content_clip)) continue; base::TimeDelta total_duration = base::TimeDelta::FromInternalValue(0); base::TimeDelta best_duration = base::TimeDelta::FromInternalValue(std::numeric_limits<int64>::max()); int repeat_count = std::max(1, slow_down_raster_scale_factor_for_debug_); TRACE_EVENT0(benchmark_instrumentation::kCategory, benchmark_instrumentation::kRasterLoop); for (int j = 0; j < repeat_count; ++j) { base::TimeTicks start_time; if (raster_stats) start_time = base::TimeTicks::HighResNow(); (*i)->Raster(canvas, callback, content_clip, contents_scale); if (raster_stats) { base::TimeDelta duration = base::TimeTicks::HighResNow() - start_time; total_duration += duration; best_duration = std::min(best_duration, duration); } } if (raster_stats) { raster_stats->total_pixels_rasterized += repeat_count * content_clip.width() * content_clip.height(); raster_stats->total_rasterize_time += total_duration; raster_stats->best_rasterize_time += best_duration; } if (show_debug_picture_borders_) { gfx::Rect border = gfx::ScaleToEnclosedRect( (*i)->LayerRect(), contents_scale); border.Inset(0, 0, 1, 1); SkPaint picture_border_paint; picture_border_paint.setColor(DebugColors::PictureBorderColor()); canvas->drawLine(border.x(), border.y(), border.right(), border.y(), picture_border_paint); canvas->drawLine(border.right(), border.y(), border.right(), border.bottom(), picture_border_paint); canvas->drawLine(border.right(), border.bottom(), border.x(), border.bottom(), picture_border_paint); canvas->drawLine(border.x(), border.bottom(), border.x(), border.y(), picture_border_paint); } // Don't allow pictures underneath to draw where this picture did. canvas->clipRect( gfx::RectToSkRect(content_clip), SkRegion::kDifference_Op); unclipped.Subtract(content_clip); } } #ifndef NDEBUG // Fill the remaining clip with debug color. This allows us to // distinguish between non painted areas and problems with missing // pictures. SkPaint paint; paint.setColor(DebugColors::MissingPictureFillColor()); paint.setXfermodeMode(SkXfermode::kSrc_Mode); canvas->drawPaint(paint); #endif // NDEBUG // We should always paint some part of |content_rect|. DCHECK(!unclipped.Contains(content_rect)); } skia::RefPtr<SkPicture> PicturePileImpl::GetFlattenedPicture() { TRACE_EVENT0("cc", "PicturePileImpl::GetFlattenedPicture"); gfx::Rect layer_rect(tiling_.total_size()); skia::RefPtr<SkPicture> picture = skia::AdoptRef(new SkPicture); if (layer_rect.IsEmpty()) return picture; SkCanvas* canvas = picture->beginRecording( layer_rect.width(), layer_rect.height(), SkPicture::kUsePathBoundsForClip_RecordingFlag); RasterToBitmap(canvas, layer_rect, 1.0, NULL); picture->endRecording(); return picture; } void PicturePileImpl::AnalyzeInRect(gfx::Rect content_rect, float contents_scale, PicturePileImpl::Analysis* analysis) { DCHECK(analysis); TRACE_EVENT0("cc", "PicturePileImpl::AnalyzeInRect"); gfx::Rect layer_rect = gfx::ScaleToEnclosingRect( content_rect, 1.0f / contents_scale); layer_rect.Intersect(gfx::Rect(tiling_.total_size())); SkBitmap empty_bitmap; empty_bitmap.setConfig(SkBitmap::kNo_Config, layer_rect.width(), layer_rect.height()); skia::AnalysisDevice device(empty_bitmap); skia::AnalysisCanvas canvas(&device); RasterForAnalysis(&canvas, layer_rect, 1.0f); analysis->is_solid_color = canvas.GetColorIfSolid(&analysis->solid_color); analysis->has_text = canvas.HasText(); } PicturePileImpl::Analysis::Analysis() : is_solid_color(false), has_text(false) { } PicturePileImpl::Analysis::~Analysis() { } PicturePileImpl::PixelRefIterator::PixelRefIterator( gfx::Rect content_rect, float contents_scale, const PicturePileImpl* picture_pile) : picture_pile_(picture_pile), layer_rect_(gfx::ScaleToEnclosingRect( content_rect, 1.f / contents_scale)), tile_iterator_(&picture_pile_->tiling_, layer_rect_), picture_list_(NULL) { // Early out if there isn't a single tile. if (!tile_iterator_) return; if (AdvanceToTileWithPictures()) AdvanceToPictureWithPixelRefs(); } PicturePileImpl::PixelRefIterator::~PixelRefIterator() { } PicturePileImpl::PixelRefIterator& PicturePileImpl::PixelRefIterator::operator++() { ++pixel_ref_iterator_; if (pixel_ref_iterator_) return *this; ++picture_list_iterator_; AdvanceToPictureWithPixelRefs(); return *this; } bool PicturePileImpl::PixelRefIterator::AdvanceToTileWithPictures() { for (; tile_iterator_; ++tile_iterator_) { PictureListMap::const_iterator map_iterator = picture_pile_->picture_list_map_.find(tile_iterator_.index()); if (map_iterator != picture_pile_->picture_list_map_.end()) { picture_list_ = &map_iterator->second; picture_list_iterator_ = picture_list_->begin(); return true; } } return false; } void PicturePileImpl::PixelRefIterator::AdvanceToPictureWithPixelRefs() { DCHECK(tile_iterator_); do { for (; picture_list_iterator_ != picture_list_->end(); ++picture_list_iterator_) { pixel_ref_iterator_ = Picture::PixelRefIterator(layer_rect_, picture_list_iterator_->get()); if (pixel_ref_iterator_) return; } ++tile_iterator_; } while (AdvanceToTileWithPictures()); } void PicturePileImpl::DidBeginTracing() { gfx::Rect layer_rect(tiling_.total_size()); for (PictureListMap::iterator pli = picture_list_map_.begin(); pli != picture_list_map_.end(); pli++) { PictureList& picture_list = (*pli).second; for (PictureList::iterator picture = picture_list.begin(); picture != picture_list.end(); picture++) { (*picture)->EmitTraceSnapshot(); } } } } // namespace cc
34.613232
80
0.694553
kurli
3a44c033ac66b7f048f5ccfb7eb6185314beadf3
1,180
cpp
C++
csci515/src/practice/Rectangle.cpp
atreyasinha/school
356458e7e281b9e0458830600f97afc2c4a47088
[ "MIT" ]
null
null
null
csci515/src/practice/Rectangle.cpp
atreyasinha/school
356458e7e281b9e0458830600f97afc2c4a47088
[ "MIT" ]
null
null
null
csci515/src/practice/Rectangle.cpp
atreyasinha/school
356458e7e281b9e0458830600f97afc2c4a47088
[ "MIT" ]
null
null
null
// updated Thu Apr 25 21:55:03 PDT 2019 #include <cassert> #include <GL/gl.h> #include "Rectangle.h" Rectangle::Rectangle(double red, double green, double blue) : Game_object(red, green, blue, RECTANGLE) { Register("rotation", 0.0); } /* virtual */ void Rectangle::build_display_list() { assert(m_display_list); glNewList(m_display_list, GL_COMPILE); glMatrixMode(GL_MODELVIEW); glPushMatrix(); if (attribute<double>("rotation") != 0) { double center_x = attribute<int>("x") + object_width/2.0; double center_y = attribute<int>("y") + object_height/2.0; glTranslated(center_x, center_y, 0); glRotated(attribute<double>("rotation"), 0, 0, 1); glTranslated(-center_x, -center_y, 0); } glColor3f(attribute<double>("red"), attribute<double>("green"), attribute<double>("blue")); glBegin(GL_QUADS); glVertex2i(attribute<int>("x"), attribute<int>("y")); glVertex2i(attribute<int>("x") + object_width, attribute<int>("y")); glVertex2i(attribute<int>("x") + object_width, attribute<int>("y") + object_height); glVertex2i(attribute<int>("x"), attribute<int>("y") + object_height); glEnd(); glPopMatrix(); glEndList(); }
30.25641
93
0.676271
atreyasinha
3a459516d778f606b423ddee514d5605a0ac6096
15,475
cxx
C++
Source/ImageTools/ResampleVolumesToBeIsotropic/source/ResampleVolumesToBeIsotropic.cxx
SCIInstitute/ShapeWorks-Prep
7a3cb1eadf84c93e85874d9da230bb5eebb09bf3
[ "MIT" ]
null
null
null
Source/ImageTools/ResampleVolumesToBeIsotropic/source/ResampleVolumesToBeIsotropic.cxx
SCIInstitute/ShapeWorks-Prep
7a3cb1eadf84c93e85874d9da230bb5eebb09bf3
[ "MIT" ]
1
2020-08-04T22:37:34.000Z
2020-08-05T06:17:43.000Z
Source/ImageTools/ResampleVolumesToBeIsotropic/source/ResampleVolumesToBeIsotropic.cxx
SCIInstitute/ShapeWorks-Prep
7a3cb1eadf84c93e85874d9da230bb5eebb09bf3
[ "MIT" ]
null
null
null
#include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkIdentityTransform.h" #include "itkAntiAliasBinaryImageFilter.h" #include "itkImageRegionIterator.h" #include "itkChangeInformationImageFilter.h" #include "string.h" #include "itkBSplineInterpolateImageFunction.h" #include "OptionParser.h" optparse::OptionParser buildParser() { const std::string usage = "%prog [OPTION]"; const std::string version = "%prog 0.1"; const std::string desc = "A command line tool that resamples given mri/binary volumes to have isotropic voxel spacing...."; //const std::string epilog = "note: --numthreads 0 means use system default (usually max number supported).\n"; const std::string epilog = ""; optparse::OptionParser parser = optparse::OptionParser() .usage(usage) .version(version) .description(desc) .epilog(epilog); parser.add_option("--inFilename").action("store").type("string").set_default("").help("The filename of the input image to be resampled."); parser.add_option("--outFilename").action("store").type("string").set_default("").help("The filename of the output resampled image."); parser.add_option("--isBinaryImage").action("store").type("bool").set_default(false).help("A flag to treat the input image as a binary image (specialized resampling pipeline) [default disabled]."); parser.add_option("--isoSpacing").action("store").type("float").set_default("").help("The isotropic spacing in all dimensions."); parser.add_option("--sizeX").action("store").type("int").set_default(0).help("Image size in x-direction (optional, if set to 0, the size is autmatically estimated from the input image)."); parser.add_option("--sizeY").action("store").type("int").set_default(0).help("Image size in y-direction (optional, if set to 0, the size is autmatically estimated from the input image)."); parser.add_option("--sizeZ").action("store").type("int").set_default(0).help("Image size in z-direction (optional, if set to 0, the size is autmatically estimated from the input image)."); parser.add_option("--isCenterImageOn").action("store").type("bool").set_default(false).help("A flag to center the image, i.e. change the origin in the image header to the physcial coordinates of the first voxel (lower left corner) [default disabled]."); return parser; } //this has been added for image region iteration as the image was not updated even after set template<typename TImage> void DeepCopy(typename TImage::Pointer input, typename TImage::Pointer output) { output->SetRegions(input->GetLargestPossibleRegion()); output->Allocate(); itk::ImageRegionConstIterator<TImage> inputIterator(input, input->GetLargestPossibleRegion()); itk::ImageRegionIterator<TImage> outputIterator(output, output->GetLargestPossibleRegion()); while(!inputIterator.IsAtEnd()) { outputIterator.Set(inputIterator.Get()); ++inputIterator; ++outputIterator; } } int main( int argc, char * argv[] ) { optparse::OptionParser parser = buildParser(); optparse::Values & options = parser.parse_args(argc,argv); std::vector<std::string> args = parser.args(); if(argc < 4) { parser.print_help(); return EXIT_FAILURE; } std::string inFilename = (std::string) options.get("inFilename"); std::string outFilename = (std::string) options.get("outFilename"); int sizeX = (int) options.get("sizeX"); int sizeY = (int) options.get("sizeY"); int sizeZ = (int) options.get("sizeZ"); float isoSpacing = (float) options.get("isoSpacing"); bool isBinaryImage = (bool) options.get("isBinaryImage"); bool isCenterImageOn = (bool) options.get("isCenterImageOn"); if(isBinaryImage==true) { typedef float InputPixelType; typedef float InternalPixelType; typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inFilename ); InputImageType::ConstPointer inputImage = reader->GetOutput(); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught!" << std::endl; std::cerr << excep << std::endl; } typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ResampleImageFilter<InternalImageType, OutputImageType > ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); typedef itk::IdentityTransform< double, Dimension > TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); resampler->SetTransform( transform ); //typedef itk::LinearInterpolateImageFunction<InternalImageType, double > InterpolatorType; typedef itk::BSplineInterpolateImageFunction<InternalImageType, double, double> InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetSplineOrder(3); resampler->SetInterpolator( interpolator ); //this is to overcome padding that was occuring after resampling step due to enlargement of size as per input resampler->SetDefaultPixelValue( -1); OutputImageType::SpacingType spacing; spacing[0] = isoSpacing; spacing[1] = isoSpacing; spacing[2] = isoSpacing; resampler->SetOutputSpacing( spacing ); resampler->SetOutputOrigin( inputImage->GetOrigin() ); resampler->SetOutputDirection( inputImage->GetDirection() ); InputImageType::SizeType outputSize; InputImageType::SizeType inputSize =inputImage->GetLargestPossibleRegion().GetSize(); typedef InputImageType::SizeType::SizeValueType SizeValueType; const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing(); if(sizeX == 0 || sizeY == 0 || sizeZ == 0){ sizeX = std::ceil(inputSize[0] * inputSpacing[0] / isoSpacing); sizeY = std::ceil(inputSize[1] * inputSpacing[1] / isoSpacing); sizeZ = std::ceil((inputSize[2] - 1 ) * inputSpacing[2] / isoSpacing); } outputSize[0] = static_cast<SizeValueType>( sizeX ); outputSize[1] = static_cast<SizeValueType>( sizeY ); outputSize[2] = static_cast<SizeValueType>( sizeZ ); std::cout<<"InputFileName:"<<inFilename<<std::endl; std::cout<<"InputSize:"<<inputSize[0]<<" "<<inputSize[1]<<" "<<inputSize[2]<<std::endl; std::cout<<"OutputSize:"<<outputSize[0]<<" "<<outputSize[1]<<" "<<outputSize[2]<<std::endl; std::cout<<"InputSpacing:"<<inputSpacing[0]<<" "<<inputSpacing[1]<<" "<<inputSpacing[2]<<std::endl; std::cout<<"OutputSpacing:"<<isoSpacing<<std::endl; resampler->SetSize( outputSize); /*Anti aliasing for binary images*/ typedef itk::AntiAliasBinaryImageFilter< InternalImageType, InternalImageType > FilterType; FilterType::Pointer antialiasFilter = FilterType::New(); antialiasFilter->SetInput( reader->GetOutput() ); antialiasFilter->SetMaximumRMSError( 0.01); antialiasFilter->SetNumberOfIterations( 50 ); antialiasFilter->Update(); /*resampling the binary image*/ resampler->SetInput( antialiasFilter->GetOutput() ); resampler->Update(); OutputImageType::Pointer resampledImage = resampler->GetOutput(); OutputImageType::Pointer outputImage = OutputImageType::New(); DeepCopy<OutputImageType>(resampledImage, outputImage); outputImage->SetSpacing( spacing ); outputImage->SetOrigin( inputImage->GetOrigin() ); itk::ImageRegionIterator<OutputImageType> imageIterator(resampledImage, resampledImage->GetLargestPossibleRegion()); itk::ImageRegionIterator<OutputImageType> outIterator(outputImage, outputImage->GetLargestPossibleRegion()); /*thresholding for binary images*/ while(!imageIterator.IsAtEnd()) { OutputPixelType val = imageIterator.Get(); if(val>=0) outIterator.Set((OutputPixelType)1); else outIterator.Set((OutputPixelType)0); ++imageIterator; ++outIterator; } typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outFilename ); // center volume if indicated (i.e. move (0,0,0) to the center of the bounding box) typedef itk::ChangeInformationImageFilter< OutputImageType > ImageInfoFilterType; ImageInfoFilterType::Pointer infoFilter = ImageInfoFilterType::New(); if(isCenterImageOn == true) { std::cout << "CENTER IS ON ... " << std::endl; // itk assumes center to be at pixel(0,0,0) - lower left corner so if we explicitly modify // the origin to the region center, any subsequent processing will force the origin to be at the corner and moves the image region accordingly infoFilter->SetInput(outputImage); //infoFilter->SetOutputOrigin( origin ); //infoFilter->ChangeOriginOn(); infoFilter->CenterImageOn(); infoFilter->Update(); writer->SetInput( infoFilter->GetOutput() ); } else writer->SetInput(outputImage); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } return EXIT_SUCCESS; } //for MRI images else { // typedef unsigned short InputPixelType; // typedef unsigned short InternalPixelType; // typedef unsigned short OutputPixelType; typedef float InputPixelType; typedef float InternalPixelType; typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inFilename ); InputImageType::ConstPointer inputImage = reader->GetOutput(); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught!" << std::endl; std::cerr << excep << std::endl; } typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ResampleImageFilter<InternalImageType, OutputImageType > ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); typedef itk::IdentityTransform< double, Dimension > TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); resampler->SetTransform( transform ); typedef itk::LinearInterpolateImageFunction<InternalImageType, double > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); resampler->SetInterpolator( interpolator ); //this is to overcome padding that was occuring after resampling step due to enlargement of size as per input resampler->SetDefaultPixelValue( 0 ); OutputImageType::SpacingType spacing; spacing[0] = isoSpacing; spacing[1] = isoSpacing; spacing[2] = isoSpacing; resampler->SetOutputSpacing( spacing ); resampler->SetOutputOrigin( inputImage->GetOrigin() ); resampler->SetOutputDirection( inputImage->GetDirection() ); InputImageType::SizeType outputSize; InputImageType::SizeType inputSize =inputImage->GetLargestPossibleRegion().GetSize(); typedef InputImageType::SizeType::SizeValueType SizeValueType; const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing(); if(sizeX == 0 || sizeY == 0 || sizeZ == 0){ sizeX = std::ceil(inputSize[0] * inputSpacing[0] / isoSpacing); sizeY = std::ceil(inputSize[1] * inputSpacing[1] / isoSpacing); sizeZ = std::ceil((inputSize[2] - 1 ) * inputSpacing[2] / isoSpacing); } outputSize[0] = static_cast<SizeValueType>( sizeX ); outputSize[1] = static_cast<SizeValueType>( sizeY ); outputSize[2] = static_cast<SizeValueType>( sizeZ ); std::cout<<"InputFileName:"<<inFilename<<std::endl; std::cout<<"InputSize:"<<inputSize[0]<<" "<<inputSize[1]<<" "<<inputSize[2]<<std::endl; std::cout<<"OutputSize:"<<outputSize[0]<<" "<<outputSize[1]<<" "<<outputSize[2]<<std::endl; std::cout<<"InputSpacing:"<<inputSpacing[0]<<" "<<inputSpacing[1]<<" "<<inputSpacing[2]<<std::endl; std::cout<<"OutputSpacing:"<<isoSpacing<<std::endl; resampler->SetSize( outputSize); /*resampling the non binary images*/ resampler->SetInput(reader->GetOutput() ); resampler->Update(); OutputImageType::Pointer resampledImage = resampler->GetOutput(); OutputImageType::Pointer outputImage = resampler->GetOutput(); outputImage->SetSpacing( spacing ); outputImage->SetOrigin( inputImage->GetOrigin() ); typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outFilename ); // center volume if indicated (i.e. move (0,0,0) to the center of the bounding box) typedef itk::ChangeInformationImageFilter< OutputImageType > ImageInfoFilterType; ImageInfoFilterType::Pointer infoFilter = ImageInfoFilterType::New(); if(isCenterImageOn) { std::cout << "CENTER IS ON ... " << std::endl; // itk assumes center to be at pixel(0,0,0) - lower left corner so if we explicitly modify // the origin to the region center, any subsequent processing will force the origin to be at the corner and moves the image region accordingly infoFilter->SetInput(outputImage); //infoFilter->SetOutputOrigin( origin ); //infoFilter->ChangeOriginOn(); infoFilter->CenterImageOn(); infoFilter->Update(); writer->SetInput( infoFilter->GetOutput() ); } else writer->SetInput(resampler->GetOutput()); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } return EXIT_SUCCESS; } }
42.166213
257
0.644911
SCIInstitute
3a4c78ac435cd30a3fef99b13b1afeeb82e2d4e0
15,981
cpp
C++
software/controller/lib/hal/i2c.cpp
RespiraWorks/Ventilator
2b431b96d988a5d88cc60525470277757c2b88f4
[ "Apache-2.0" ]
47
2020-07-05T03:06:25.000Z
2022-03-14T16:59:24.000Z
software/controller/lib/hal/i2c.cpp
RespiraWorks/Ventilator
2b431b96d988a5d88cc60525470277757c2b88f4
[ "Apache-2.0" ]
545
2020-07-01T22:25:42.000Z
2022-03-31T04:07:28.000Z
software/controller/lib/hal/i2c.cpp
RespiraWorks/Ventilator
2b431b96d988a5d88cc60525470277757c2b88f4
[ "Apache-2.0" ]
19
2020-07-16T18:48:28.000Z
2022-02-09T10:20:21.000Z
/* Copyright 2020, RespiraWorks 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 file contains code to setup, send and receive data on the I²C channel // See header file for implementation philosophy. // //////////////////////////////////////////////////////////////////// #include "i2c.h" #include <cstring> #include "clocks.h" #include "gpio.h" #if defined(BARE_STM32) I2C::STM32Channel i2c1; #else I2C::Channel i2c1; #endif // BARE_STM32 namespace I2C { // Reference abbreviations ([RM], [PCB], etc) are defined in hal/README.md void initialize() { // Enable I2C1 and DMA2 peripheral clocks (we use DMA2 to send/receive data) enable_peripheral_clock(PeripheralID::I2C1); enable_peripheral_clock(PeripheralID::DMA2); // The following pins are used as i2c1 bus on the rev-1 PCB (see [PCB]): // Set Pin Function to I²C, [DS] Table 17 (pg 77) GPIO::alternate_function(GPIO::Port::B, /*pin =*/8, GPIO::AlternativeFuncion::AF4); // I2C1_SCL GPIO::alternate_function(GPIO::Port::B, /*pin =*/9, GPIO::AlternativeFuncion::AF4); // I2C1_SDA // Set output speed to Fast GPIO::output_speed(GPIO::Port::B, 8, GPIO::OutSpeed::Fast); GPIO::output_speed(GPIO::Port::B, 9, GPIO::OutSpeed::Fast); // Set open drain mode GPIO::output_type(GPIO::Port::B, 8, GPIO::OutType::OpenDrain); GPIO::output_type(GPIO::Port::B, 9, GPIO::OutType::OpenDrain); // Set Pull Up resistors GPIO::pull_up(GPIO::Port::B, 8); GPIO::pull_up(GPIO::Port::B, 9); Interrupts::singleton().EnableInterrupt(InterruptVector::I2c1Event, IntPriority::Low); Interrupts::singleton().EnableInterrupt(InterruptVector::I2c1Error, IntPriority::Low); Interrupts::singleton().EnableInterrupt(InterruptVector::Dma2Channel6, IntPriority::Low); Interrupts::singleton().EnableInterrupt(InterruptVector::Dma2Channel7, IntPriority::Low); // init i2c1 #if defined(BARE_STM32) i2c1.Init(I2C1Base, DMA::Base::DMA2, I2C::Speed::Fast); #endif } bool Channel::SendRequest(const Request &request) { *(request.processed) = false; // We need to ensure thread safety as this function might be // called from a timer interrupt as well as the main loop. // Also, because our ISR change the transfer_in_progress_ member variable. BlockInterrupts block; // Queue the request if possible: check that there is room in the index // buffer if (buffer_.IsFull()) { return false; } // Add the current queue_ index into the buffer if (buffer_.Put(ind_queue_)) { queue_[ind_queue_] = request; } else { return false; } // In case of a write request, copy data to our write buffer if (request.direction == ExchangeDirection::Write) { if (!CopyDataToWriteBuffer(request.data, request.size)) { return false; } // update the request's data pointer to the write buffer instead of the // caller's scope variable queue_[ind_queue_].data = &write_buffer_[write_buffer_index_]; // update the write buffer index write_buffer_index_ += request.size; } // increment ind_queue_, which is the index at which the next request will // be put in the queue, with wrapping around the queue. if (++ind_queue_ >= QueueLength) { ind_queue_ = 0; } if (!transfer_in_progress_) { StartTransfer(); } // if a transfer is already in progress, this request will be initiated by // the interrupt handlers, our work is done! return true; } bool Channel::CopyDataToWriteBuffer(const void *data, const uint16_t size) { // This protected function is only called from an already thread safe // function, but leaning on the safe side here, I am disabling interrupts // for this one anyway, in case someone changes the design of the I²C class. BlockInterrupts block; // Check if the empty space at the end of the buffer is big enough to // store all of the data if (write_buffer_index_ + size > WriteBufferSize) { // It isn't ==> Check if the empty space at the beginning of the buffer // is big enough to store all of the data instead if (size >= write_buffer_start_) { // There is no contiguous space left in buffer that is big enough, // we can't safely send this Write request. return false; } // We can write at the beginning of the buffer, need to remember that we // wrap at that index in order to properly wrap when updating // write_buffer_start_ when the (previous) transfer will end. wrapping_index_ = write_buffer_index_; write_buffer_index_ = 0; } memcpy(&write_buffer_[write_buffer_index_], data, size); return true; } void Channel::StartTransfer() { transfer_in_progress_ = true; // In DMA mode, a single request can lead to several transfers, when it is // longer than 255 bytes. Therefore we need to check whether this call is a // continuation of a long request or a new request. // Also in case of transfer error, we may need to re-send the last request if (remaining_size_ == 0) { // Ensure thread safety BlockInterrupts block; // This indicates the last request has been successfully sent, hence we // will send the next request in the queue. std::optional<uint8_t> index = buffer_.Get(); if (index == std::nullopt) { // no request in the queue transfer_in_progress_ = false; return; } last_request_ = queue_[*index]; next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; error_retry_ = MaxRetries; } SetupI2CTransfer(); } // Method called by interrupt handler when dma is disabled. This method // transfers data to/from the tx/rx registers from/to *request.data void Channel::TransferByte() { if (remaining_size_ == 0) { // this shouldn't happen, but just to be safe, we stop here. return; } if (last_request_.direction == ExchangeDirection::Read) { ReceiveByte(); } else { SendByte(); } if (--remaining_size_ > 0) { // increment next_data_ pointer only in case we are still expecting more // data to prevent unwarranted memory access next_data_ += sizeof(uint8_t); }; } void Channel::EndTransfer() { // Ensure thread safety BlockInterrupts block; *last_request_.processed = true; if (last_request_.direction == ExchangeDirection::Write) { // free the part of the write buffer that was dedicated to this request write_buffer_start_ += last_request_.size; if (write_buffer_start_ >= wrapping_index_) { // We don't allow data in the same request to wrap around, so we // must detect that the next write data actually starts at index 0 // to properly free the end of the buffer as well write_buffer_start_ = 0; } } transfer_in_progress_ = false; } void Channel::I2CEventHandler() { if (!transfer_in_progress_) { return; } // resend the request in case the slave NACK'd our request if (NackDetected()) { // clear the nack ClearNack(); // the slave is non-responsive --> start the request anew next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; StartTransfer(); } // When we are using DMA, NACK is the only I²C event we are dealing with if (dma_enable_) { return; } if (NextByteNeeded()) { // carry on with the current transfer TransferByte(); } if (TransferReload()) { // To continue a request that is longer than 255 bits, all we need to do // is write a non-zero transfer size, and set the reload byte // accordingly (see [RM] p1151 (Write request) and 1155 (Read request)) WriteTransferSize(); } if (TransferComplete()) { // Send stop condition StopTransfer(); // Clean necessary states EndTransfer(); // And start the next one (if any) StartTransfer(); } } void Channel::I2CErrorHandler() { // I²C error --> clear all error flags (except those that are SMBus only) ClearErrors(); // and restart the request up to error_retry_ times if (--error_retry_ > 0) { next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; } else { // skip this request and go to next one; remaining_size_ = 0; } StartTransfer(); } void STM32Channel::Init(I2CReg *i2c, DMA::Base dma, Speed speed) { i2c_ = i2c; dma_ = dma; // Disable I²C peripheral i2c_->control_reg1.enable = 0; // Set I²C speed using timing values from [RM] table 182 i2c_->timing.full_reg = static_cast<uint32_t>(speed); // Setup DMA channels // if (dma != nullptr) { SetupDMAChannels(dma); // } // enable I²C peripheral i2c_->control_reg1.enable = 1; // configure I²C interrupts i2c_->control_reg1.nack_interrupts = 1; i2c_->control_reg1.error_interrupts = 1; // in DMA mode, we do not treat the transfer-specific ones if (!dma_enable_) { i2c_->control_reg1.rx_interrupts = 1; i2c_->control_reg1.tx_interrupts = 1; i2c_->control_reg1.tx_complete_interrupts = 1; } else { i2c_->control_reg1.rx_interrupts = 0; i2c_->control_reg1.tx_interrupts = 0; i2c_->control_reg1.tx_complete_interrupts = 0; } } void STM32Channel::SetupI2CTransfer() { // set transfer-specific registers per [RM] p1149 to 1158 i2c_->control2.slave_addr_7b = last_request_.slave_address & 0x7f; i2c_->control2.transfer_direction = static_cast<bool>(last_request_.direction); if (dma_enable_) { SetupDMATransfer(); } WriteTransferSize(); i2c_->control2.start = 1; } // Write the remaining size to the appropriate register with reload logic void STM32Channel::WriteTransferSize() { if (remaining_size_ <= 255) { i2c_->control2.n_bytes = static_cast<uint8_t>(remaining_size_); i2c_->control2.reload = 0; } else { i2c_->control2.n_bytes = 255; // Transfer reload is not currently supported by our HAL in DMA mode, // we will treat a reload as a new transfer. In effect this means we // will have to reissue the I²C header and start condition. // It also means that any request that has a (functional) header inside // its data and is longer than 255 bytes may not be processed correctly // by the I²C slave, as it will be split (this is referred to as a // Restart condition rather than Reload) if (!dma_enable_) { i2c_->control2.reload = 1; } else { i2c_->control2.reload = 0; } } } // DMA functions are only meaningful in BARE_STM32 void STM32Channel::SetupDMAChannels(const DMA::Base dma) { // DMA mapping for I²C (see [RM] p299) static struct { DMA::Base dma_base; volatile void *i2c_base; DMA::Channel tx_channel_id; DMA::Channel rx_channel_id; uint8_t request_number; } DmaMap[] = { {DMA::Base::DMA1, I2C1Base, DMA::Channel::Chan6, DMA::Channel::Chan7, 3}, {DMA::Base::DMA1, I2C2Base, DMA::Channel::Chan4, DMA::Channel::Chan5, 3}, {DMA::Base::DMA1, I2C3Base, DMA::Channel::Chan2, DMA::Channel::Chan3, 3}, {DMA::Base::DMA2, I2C1Base, DMA::Channel::Chan7, DMA::Channel::Chan6, 5}, {DMA::Base::DMA2, I2C4Base, DMA::Channel::Chan2, DMA::Channel::Chan1, 0}, }; for (auto &map : DmaMap) { if (dma == map.dma_base && i2c_ == map.i2c_base) { auto *dma_register = DMA::get_register(dma); dma_ = dma; tx_channel_ = &dma_register->channel[static_cast<uint8_t>(map.tx_channel_id)]; rx_channel_ = &dma_register->channel[static_cast<uint8_t>(map.rx_channel_id)]; // Tell the STM32 that those two DMA channels are used for I2C DMA::SelectChannel(dma, map.rx_channel_id, map.request_number); DMA::SelectChannel(dma, map.tx_channel_id, map.request_number); // configure both DMA channels to handle I²C transfers ConfigureDMAChannel(rx_channel_, ExchangeDirection::Read); ConfigureDMAChannel(tx_channel_, ExchangeDirection::Write); dma_enable_ = true; i2c_->control_reg1.dma_rx = 1; i2c_->control_reg1.dma_tx = 1; break; } } } void I2C::STM32Channel::ConfigureDMAChannel(volatile DmaReg::ChannelRegs *channel, ExchangeDirection direction) { channel->config.priority = 0b01; // medium priority channel->config.tx_error_interrupt = 1; // interrupt on error channel->config.half_tx_interrupt = 0; // no half-transfer interrupt channel->config.tx_complete_interrupt = 1; // interrupt on DMA complete channel->config.mem2mem = 0; // memory-to-memory mode disabled channel->config.memory_size = static_cast<uint8_t>(DMA::TransferSize::Byte); channel->config.peripheral_size = static_cast<uint8_t>(DMA::TransferSize::Byte); channel->config.memory_increment = 1; // increment dest address channel->config.peripheral_increment = 0; // don't increment source address channel->config.circular = 0; if (direction == ExchangeDirection::Read) { channel->config.direction = static_cast<uint8_t>(DMA::ChannelDir::PeripheralToMemory); channel->peripheral_address = &(i2c_->rx_data); } else { channel->config.direction = static_cast<uint8_t>(DMA::ChannelDir::MemoryToPeripheral); channel->peripheral_address = &(i2c_->tx_data); } } void STM32Channel::SetupDMATransfer() { if (!dma_enable_) { return; } // to be on the safe size, disable both channels in case they weren't // (likely when this is called as a "retry after error") rx_channel_->config.enable = 0; tx_channel_->config.enable = 0; volatile DmaReg::ChannelRegs *channel{nullptr}; if (last_request_.direction == ExchangeDirection::Read) { channel = rx_channel_; } else { channel = tx_channel_; } channel->memory_address = next_data_; if (remaining_size_ <= 255) { channel->count = remaining_size_; } else { channel->count = 255; } // when using DMA, we need to use autoend, otherwise the STOP condition // which we issue at the end of the DMA transfer (which means the last byte // has been written to the register) may arrive before the last byte is // actually written on the line. Tests with both DMA and I2C interrupts // enabled to send Stop at the end of the I2C transfer were inconclusive. i2c_->control2.autoend = 1; channel->config.enable = 1; } void STM32Channel::DMAIntHandler(DMA::Channel chan) { if (!dma_enable_ || !transfer_in_progress_) return; auto *dma_register = DMA::get_register(dma_); dma_register->channel[static_cast<uint8_t>(chan)].config.enable = 0; if (DMA::IntStatus(dma_, chan, DMA::Interrupt::TransferComplete)) { if (remaining_size_ > 255) { // decrement remaining size by 255 (the size of the DMA transfer) remaining_size_ = static_cast<uint16_t>(remaining_size_ - 255); next_data_ += 255 * sizeof(uint8_t); } else { remaining_size_ = 0; EndTransfer(); } } else if (DMA::IntStatus(dma_, chan, DMA::Interrupt::TransferError)) { // we are dealing with an error --> reset transfer (up to MaxRetries // times) if (--error_retry_ > 0) { next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; } else { // skip this request and go to next request; remaining_size_ = 0; } } // clear all interrupts and (re-)start the current or next transfer DMA::ClearInt(dma_, chan, DMA::Interrupt::Global); StartTransfer(); } } // namespace I2C
34.969365
91
0.686315
RespiraWorks
3a4e2c0d89ad2020520c1ba26d2a9d85000f0b7d
309
cpp
C++
tools/pathanalyzer/tests/independent_ite.cpp
Trass3r/pharos
adeb128aca418696d03889daadc33c1f17ceff90
[ "RSA-MD" ]
3
2015-07-15T08:43:56.000Z
2021-02-28T17:53:52.000Z
tools/pathanalyzer/tests/independent_ite.cpp
sei-ccohen/pharos
78d08494a5c0bffff3789cae7acc538303b1926c
[ "RSA-MD" ]
null
null
null
tools/pathanalyzer/tests/independent_ite.cpp
sei-ccohen/pharos
78d08494a5c0bffff3789cae7acc538303b1926c
[ "RSA-MD" ]
null
null
null
// Copyright 2019 Carnegie Mellon University. See LICENSE file for terms. #include "test.hpp" int main() { path_start(); int n=INT_RAND, k=INT_RAND, j=INT_RAND; int x=0; if ( n == 0 ) { x++; } if (k == 0) { x++; } if (j == 0) { x++; } if (x == 3) { path_goal(); } }
12.875
74
0.495146
Trass3r
3a521542ae98bdc5e7ffce1afcd79026d128886c
7,124
cpp
C++
src/condor_utils/hibernator.tools.cpp
zhangzhehust/htcondor
e07510d62161f38fa2483b299196ef9a7b9f7941
[ "Apache-2.0" ]
1
2017-02-13T01:25:34.000Z
2017-02-13T01:25:34.000Z
src/condor_utils/hibernator.tools.cpp
zhangzhehust/htcondor
e07510d62161f38fa2483b299196ef9a7b9f7941
[ "Apache-2.0" ]
1
2021-04-06T04:19:40.000Z
2021-04-06T04:19:40.000Z
src/condor_utils/hibernator.tools.cpp
zhangzhehust/htcondor
e07510d62161f38fa2483b299196ef9a7b9f7941
[ "Apache-2.0" ]
2
2016-05-24T17:12:13.000Z
2017-02-13T01:25:35.000Z
/*************************************************************** * * Copyright (C) 1990-2008, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /*************************************************************** * Headers ***************************************************************/ #include "condor_common.h" #include "condor_config.h" #include "condor_uid.h" #include "hibernator.tools.h" #include "path_utils.h" #include "../condor_daemon_core.V6/condor_daemon_core.h" /*************************************************************** * UserDefinedToolsHibernator class ***************************************************************/ UserDefinedToolsHibernator::UserDefinedToolsHibernator () throw () : HibernatorBase (), m_keyword ( "HIBERNATE" ), m_reaper_id ( -1 ) { for ( unsigned i = 0; i <= 10; ++i ) { m_tool_paths[i] = NULL; } configure (); } UserDefinedToolsHibernator::UserDefinedToolsHibernator ( const MyString &keyword ) throw () : HibernatorBase (), m_keyword ( keyword ), m_reaper_id ( -1 ) { for ( unsigned i = 0; i <= 10; ++i ) { m_tool_paths[i] = NULL; } configure (); } UserDefinedToolsHibernator::~UserDefinedToolsHibernator () throw () { for ( unsigned i = 1; i <= 10; ++i ) { if ( NULL != m_tool_paths[i] ) { free ( m_tool_paths[i] ); m_tool_paths[i] = NULL; } } if ( -1 != m_reaper_id ) { daemonCore->Cancel_Reaper ( m_reaper_id ); } } const char* UserDefinedToolsHibernator::getMethod ( void ) const { return "user defined tools"; } /** We define a 'C' style Reaper for use in configure() to eliminate the problem of a cast being made between different pointer to member representations (because of multiple inheritance--C++ Reapers require the object to be of type Service); If we used a C++ style Reaper the compiler may generate incorrect code. */ int UserDefinedToolsHibernator::userDefinedToolsHibernatorReaper ( int pid, int ) { /** Make sure the hibernator didn't leak any processes */ daemonCore->Kill_Family ( pid ); return TRUE; } void UserDefinedToolsHibernator::configure () { MyString name, error; unsigned states = HibernatorBase::NONE; const char *description = NULL; char *arguments = NULL; HibernatorBase::SLEEP_STATE state = HibernatorBase::NONE; bool ok = false; /** There are no tools for S0, or "NONE" */ m_tool_paths[0] = NULL; /** Pull the paths for the rest of the sleep states from the configuration file */ for ( unsigned i = 1; i <= 10; ++i ) { /** Clean out the old path information */ if ( NULL != m_tool_paths[i] ) { free ( m_tool_paths[i] ); m_tool_paths[i] = NULL; } /** Convert the current index to the sleep state equivalent */ state = HibernatorBase::intToSleepState ( i ); if ( HibernatorBase::NONE == state ) { continue; } /** Convert the sleep state to a human consumable description */ description = HibernatorBase::sleepStateToString ( state ); if ( NULL == description ) { continue; } dprintf ( D_FULLDEBUG, "UserDefinedToolsHibernator: state = %d, desc = %s\n", state, "S1" ); /** Build the tool look-up parameter for the tool's path */ name.formatstr ( "%s_USER_%s_TOOL", "HIBERNATE", "S1" ); /** Grab the user defined executable path */ m_tool_paths[i] = validateExecutablePath ( name.Value () ); if ( NULL != m_tool_paths[i] ) { /** Make the path the first argument to Create_Process */ m_tool_args[i].AppendArg ( m_tool_paths[i] ); /** Build the tool look-up parameter for the tool's argument list */ name.formatstr ( "%s_USER_%s_ARGS", m_keyword.Value(), description ); /** Grab the command's arguments */ arguments = param ( name.Value () ); if ( NULL != arguments ) { /** Parse the command-line arguments */ ok = m_tool_args[i].AppendArgsV1WackedOrV2Quoted ( arguments, &error ); if ( !ok ) { dprintf ( D_FULLDEBUG, "UserDefinedToolsHibernator::configure: failed " "to parse the tool arguments defined in the " "configuration file: %s\n", error.Value() ); } /** Dump the param'd value */ free ( arguments ); } /** Tally the supported state */ states |= state; } else { dprintf ( D_FULLDEBUG, "UserDefinedToolsHibernator::configure: the executable " "(%s) defined in the configuration file is invalid.\n", m_tool_paths[i] ); } } /** Now set the supported states */ setStates ( states ); /** Finally, register the reaper that will clean up after the user defined tool and its children */ m_reaper_id = daemonCore->Register_Reaper ( "UserDefinedToolsHibernator Reaper", (ReaperHandlercpp) &UserDefinedToolsHibernator::userDefinedToolsHibernatorReaper, "UserDefinedToolsHibernator Reaper", NULL ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterState ( HibernatorBase::SLEEP_STATE state ) const { /** Make sure a tool for this sleep state has been defined */ unsigned index = sleepStateToInt ( state ); if ( NULL == m_tool_paths[index] ) { dprintf ( D_FULLDEBUG, "Hibernator::%s tool not configured.\n", HibernatorBase::sleepStateToString ( state ) ); return HibernatorBase::NONE; } /** Tell DaemonCore to register the process family so we can safely kill everything from the reaper */ FamilyInfo fi; fi.max_snapshot_interval = param_integer ( "PID_SNAPSHOT_INTERVAL", 15 ); /** Run the user tool */ int pid = daemonCore->Create_Process ( m_tool_paths[index], m_tool_args[index], PRIV_CONDOR_FINAL, m_reaper_id, FALSE, FALSE, NULL, NULL, &fi ); if ( FALSE == pid ) { dprintf ( D_ALWAYS, "UserDefinedToolsHibernator::enterState: Create_Process() " "failed\n" ); return HibernatorBase::NONE; } return state; } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStateStandBy ( bool /*force*/ ) const { return enterState ( HibernatorBase::S1 ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStateSuspend ( bool /*force*/ ) const { return enterState ( HibernatorBase::S3 ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStateHibernate ( bool /*force*/ ) const { return enterState ( HibernatorBase::S4 ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStatePowerOff ( bool /*force*/ ) const { return enterState ( HibernatorBase::S5 ); }
25.905455
92
0.643739
zhangzhehust
3a52b2a578ca59420a71cd1263fc45435d0b181a
1,263
cpp
C++
erts/emulator/asmjit/arm/a64builder.cpp
williamthome/otp
c4f24d6718ac56c431f0fccf240c5b15482792ed
[ "Apache-2.0" ]
null
null
null
erts/emulator/asmjit/arm/a64builder.cpp
williamthome/otp
c4f24d6718ac56c431f0fccf240c5b15482792ed
[ "Apache-2.0" ]
null
null
null
erts/emulator/asmjit/arm/a64builder.cpp
williamthome/otp
c4f24d6718ac56c431f0fccf240c5b15482792ed
[ "Apache-2.0" ]
2
2015-10-18T22:36:46.000Z
2022-01-26T14:01:57.000Z
// This file is part of AsmJit project <https://asmjit.com> // // See asmjit.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #include "../core/api-build_p.h" #if !defined(ASMJIT_NO_AARCH64) && !defined(ASMJIT_NO_BUILDER) #include "../arm/a64assembler.h" #include "../arm/a64builder.h" #include "../arm/a64emithelper_p.h" ASMJIT_BEGIN_SUB_NAMESPACE(a64) // a64::Builder - Construction & Destruction // ========================================= Builder::Builder(CodeHolder* code) noexcept : BaseBuilder() { _archMask = uint64_t(1) << uint32_t(Arch::kAArch64); assignEmitterFuncs(this); if (code) code->attach(this); } Builder::~Builder() noexcept {} // a64::Builder - Events // ===================== Error Builder::onAttach(CodeHolder* code) noexcept { return Base::onAttach(code); } Error Builder::onDetach(CodeHolder* code) noexcept { return Base::onDetach(code); } // a64::Builder - Finalize // ======================= Error Builder::finalize() { ASMJIT_PROPAGATE(runPasses()); Assembler a(_code); a.addEncodingOptions(encodingOptions()); a.addDiagnosticOptions(diagnosticOptions()); return serializeTo(&a); } ASMJIT_END_SUB_NAMESPACE #endif // !ASMJIT_NO_AARCH64 && !ASMJIT_NO_BUILDER
24.288462
67
0.673001
williamthome
3a52b7904a03a77438d098f06844a64022241da5
4,465
cc
C++
src/bin/convert-ali.cc
jxzhanggg/kaldi-trunk
03fbab26e5714a990e1b6dee9475d4a282a42ccc
[ "Apache-2.0" ]
319
2016-10-24T23:08:04.000Z
2022-03-08T02:36:51.000Z
src/bin/convert-ali.cc
jxzhanggg/kaldi-trunk
03fbab26e5714a990e1b6dee9475d4a282a42ccc
[ "Apache-2.0" ]
18
2017-01-12T12:08:07.000Z
2020-06-18T07:37:20.000Z
src/bin/convert-ali.cc
jxzhanggg/kaldi-trunk
03fbab26e5714a990e1b6dee9475d4a282a42ccc
[ "Apache-2.0" ]
87
2016-10-25T04:39:48.000Z
2021-12-24T07:47:31.000Z
// bin/convert-ali.cc // Copyright 2009-2011 Microsoft Corporation // 2013 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "gmm/am-diag-gmm.h" #include "hmm/transition-model.h" #include "hmm/hmm-utils.h" #include "hmm/tree-accu.h" // for ReadPhoneMap int main(int argc, char *argv[]) { using namespace kaldi; typedef kaldi::int32 int32; try { const char *usage = "Convert alignments from one decision-tree/model to another\n" "Usage: convert-ali [options] <old-model> <new-model> <new-tree> " "<old-alignments-rspecifier> <new-alignments-wspecifier>\n" "e.g.: \n" " convert-ali old/final.mdl new/0.mdl new/tree ark:old/ali.1 ark:new/ali.1\n"; int32 frame_subsampling_factor = 1; bool reorder = true; std::string phone_map_rxfilename; ParseOptions po(usage); po.Register("phone-map", &phone_map_rxfilename, "File name containing old->new phone mapping (each line is: " "old-integer-id new-integer-id)"); po.Register("reorder", &reorder, "True if you want the converted alignments to be 'reordered' " "versus the way they appear in the HmmTopology object"); po.Register("frame-subsampling-factor", &frame_subsampling_factor, "Can be used in converting alignments to reduced frame rates."); po.Read(argc, argv); if (po.NumArgs() != 5) { po.PrintUsage(); exit(1); } std::string old_model_filename = po.GetArg(1); std::string new_model_filename = po.GetArg(2); std::string new_tree_filename = po.GetArg(3); std::string old_alignments_rspecifier = po.GetArg(4); std::string new_alignments_wspecifier = po.GetArg(5); std::vector<int32> phone_map; if (phone_map_rxfilename != "") { // read phone map. ReadPhoneMap(phone_map_rxfilename, &phone_map); } SequentialInt32VectorReader alignment_reader(old_alignments_rspecifier); Int32VectorWriter alignment_writer(new_alignments_wspecifier); TransitionModel old_trans_model; ReadKaldiObject(old_model_filename, &old_trans_model); TransitionModel new_trans_model; ReadKaldiObject(new_model_filename, &new_trans_model); if (!(old_trans_model.GetTopo() == new_trans_model.GetTopo())) KALDI_WARN << "Toplogies of models are not equal: " << "conversion may not be correct or may fail."; ContextDependency new_ctx_dep; // the tree. ReadKaldiObject(new_tree_filename, &new_ctx_dep); int num_success = 0, num_fail = 0; for (; !alignment_reader.Done(); alignment_reader.Next()) { std::string key = alignment_reader.Key(); const std::vector<int32> &old_alignment = alignment_reader.Value(); std::vector<int32> new_alignment; if (ConvertAlignment(old_trans_model, new_trans_model, new_ctx_dep, old_alignment, frame_subsampling_factor, reorder, (phone_map_rxfilename != "" ? &phone_map : NULL), &new_alignment)) { alignment_writer.Write(key, new_alignment); num_success++; } else { KALDI_WARN << "Could not convert alignment for key " << key <<" (possibly truncated alignment?)"; num_fail++; } } KALDI_LOG << "Succeeded converting alignments for " << num_success << " files, failed for " << num_fail; if (num_success != 0) return 0; else return 1; } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
36.300813
86
0.644345
jxzhanggg
3a53f1275b70afb6575f74ab168e6b3406d7aff7
7,629
cpp
C++
NxS Info Tool Source/nxstabpages.cpp
saivert/winamp-plugins
5dae16e80bb63e3de258b4279c444bf2434de564
[ "MIT" ]
3
2019-06-14T12:03:23.000Z
2022-02-12T18:15:38.000Z
NxS Info Tool Source/nxstabpages.cpp
saivert/winamp-plugins
5dae16e80bb63e3de258b4279c444bf2434de564
[ "MIT" ]
null
null
null
NxS Info Tool Source/nxstabpages.cpp
saivert/winamp-plugins
5dae16e80bb63e3de258b4279c444bf2434de564
[ "MIT" ]
null
null
null
/* NxS Tabpages - written by Saivert */ //#include "StdAfx.h" #include "nxstabpages.h" NxS_TabPages::~NxS_TabPages() { Clear(); } HWND NxS_TabPages::SetTabCtrl(HWND NewTabCtrl) { HWND tmp; tmp = m_hwTab; if (IsWindow(NewTabCtrl)) { if (GetCount()>0) TabCtrl_DeleteAllItems(m_hwTab); m_hwTab = NewTabCtrl; if (GetCount()>0) TabCtrl_DeleteAllItems(m_hwTab); TabCtrl_SetItemExtra(m_hwTab, NXSTABPAGES_TABITEMSIZE); } return tmp; } bool NxS_TabPages::DelPage(int index) { TABITEM item; if (TabCtrl_GetItem(m_hwTab, index, &item)) { if (item.dlghandle) { NMHDR hdr; hdr.code = PSN_RESET; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) return false; } DestroyWindow(item.dlghandle); } TabCtrl_DeleteItem(m_hwTab, index); return true; } return false; } bool NxS_TabPages::GetPage(int index, TABITEM &tp) { return TabCtrl_GetItem(m_hwTab, index, &tp)>0; } NxS_TabPages::TABITEM& NxS_TabPages::Pages(int index) { TabCtrl_GetItem(m_hwTab, index, &m_tptemp); return m_tptemp; } bool NxS_TabPages::SendApply() { bool res=true; TABITEM item; //First we check if the active page wants to loose activation if (m_curwnd) { NMHDR hdr; hdr.code = PSN_KILLACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT)) return false; } } //If the active page said OK, we send a PSN_APPLY notification message to //all the pages. Any one of the pages can return PSNRET_INVALID_NOCHANGEPAGE //to make SendApply() return false. This is a clue to keep the host dialog open. for (int i=0; i<GetCount(); i++) { if (TabCtrl_GetItem(m_hwTab, i, &item)) { if (item.dlghandle) { NMHDR hdr; hdr.code = PSN_APPLY; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (PSNRET_INVALID_NOCHANGEPAGE==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) res=false; } } } } return res; } bool NxS_TabPages::Clear(void) { int i; while ((i = GetCount()) > 0) { if (!DelPage(i-1)) return false; } m_curwnd=NULL; //There's no longer an active dialog now... return true; } bool NxS_TabPages::HandleNotifications(WPARAM wParam, LPARAM lParam) { int idTabCtl = (int) LOWORD(wParam); LPNMHDR lpnmhdr = (LPNMHDR) lParam; if (lpnmhdr->hwndFrom == m_hwTab) { if (lpnmhdr->code == TCN_SELCHANGING) { NMHDR hdr; hdr.code = PSN_KILLACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT)) return true; } } if (lpnmhdr->code == TCN_SELCHANGE) { return SelectPage(GetSelPage()); } } if (lpnmhdr->code == TTN_NEEDTEXT) { LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT) lParam; TABITEM item; //Make sure it's our tab control's tooltip calling in... if (lpnmhdr->hwndFrom != TabCtrl_GetToolTips(m_hwTab)) return false; TabCtrl_GetItem(m_hwTab, lpttt->hdr.idFrom, &item); lpttt->hinst = IS_INTRESOURCE(item.tip)?m_hinst:NULL; lpttt->lpszText = item.tip; } return false; } int NxS_TabPages::AddPage(char* lpszTitle, char* lpszDlgRes, DLGPROC lpfnDlgProc, char* lpszTip) { TABITEM i; if (!lpszDlgRes) return 0; if (IS_INTRESOURCE(lpszDlgRes)) i.dialog = lpszDlgRes; else i.SetDlgRes(lpszDlgRes); if (IS_INTRESOURCE(lpszTip)) i.tip = lpszTip; else i.SetTip(lpszTip); if (!lpszTitle) { int len; HWND hwTemp; hwTemp = CreateDialog(m_hinst,(LPCTSTR)lpszDlgRes, GetDesktopWindow(), lpfnDlgProc); len = GetWindowTextLength(hwTemp)+1; i.title = new char[len]; GetWindowText(hwTemp, i.title, len); DestroyWindow(hwTemp); } else i.SetTitle(lpszTitle); i.dlgproc = lpfnDlgProc; i.dlghandle = NULL; //Dialog not created yet... i.itemhdr.mask = TCIF_TEXT|TCIF_PARAM; i.itemhdr.pszText = i.title; return TabCtrl_InsertItem(m_hwTab, GetCount(), &i); } bool NxS_TabPages::SelectPage(int index) { HWND hwndDlg; TABITEM item; hwndDlg = GetParent(m_hwTab); if (index >= 0) { if (m_curwnd) { NMHDR hdr; hdr.code = PSN_KILLACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT)) return false; } ShowWindow(m_curwnd, SW_HIDE); } if (!TabCtrl_GetItem(m_hwTab, index, &item)) return false; if (NULL==item.dlghandle) { item.SetDlgHandle( CreateDialogParam(m_hinst, item.dialog, hwndDlg, item.dlgproc, LPARAM(&item)) ); SetWindowLong(item.dlghandle, GWL_STYLE, WS_CHILD); SetWindowLong(item.dlghandle, GWL_EXSTYLE, WS_EX_CONTROLPARENT); SetParent(item.dlghandle, hwndDlg); EnableThemeDlgTexture(item.dlghandle, m_UseDlgTexture?ETDT_ENABLETAB:ETDT_DISABLE); //Update item.dlghandle (application data item) TabCtrl_SetItem(m_hwTab, index, &item); } { NMHDR hdr; hdr.code = PSN_SETACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (0==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) return false; } } if (m_curwnd=item.dlghandle) { RECT r; GetWindowRect(m_hwTab,&r); TabCtrl_AdjustRect(m_hwTab, FALSE, &r); MapWindowPoints(HWND_DESKTOP, hwndDlg, LPPOINT(&r), 2); //Make right & bottom be the width & height r.right -= r.left; r.bottom -= r.top; SetWindowPos(item.dlghandle, 0, r.left, r.top, r.right, r.bottom, SWP_NOACTIVATE|SWP_NOZORDER); ShowWindow(item.dlghandle,SW_SHOWNA); } TabCtrl_SetCurSel(m_hwTab, index); } return true; } void NxS_TabPages::AdjustPageSize(void) { RECT r; GetWindowRect(m_hwTab,&r); TabCtrl_AdjustRect(m_hwTab, FALSE, &r); MapWindowPoints(HWND_DESKTOP, GetParent(m_hwTab), LPPOINT(&r), 2); //Make right & bottom be the width & height r.right -= r.left; r.bottom -= r.top; SetWindowPos(m_curwnd, 0, r.left, r.top, r.right, r.bottom, SWP_NOACTIVATE|SWP_NOZORDER); } bool NxS_TabPages::SetUseThemedDlgTexture(bool use) { bool prev=m_UseDlgTexture; // If there are already some pages added, // change the state for these pages' dialogs. if (int count=GetCount()) { for (int i=0;i<count;i++) { if (HWND hwndDlg=Pages(i).dlghandle) EnableThemeDlgTexture(hwndDlg, use?ETDT_ENABLETAB:ETDT_DISABLE); } } return prev; } // A wrapper for the "EnableThemeDialogTexture" function located in // UXTHEME.DLL. When you call this with the handle of a dialog, the // dialog's background get a texture that matches the current theme. // This only works on a Windows XP machine. HRESULT NxS_TabPages::EnableThemeDlgTexture(HWND hwnd, DWORD flags) { typedef HRESULT (WINAPI * ENABLETHEMEDIALOGTEXTURE)(HWND, DWORD); ENABLETHEMEDIALOGTEXTURE pfnETDT; HINSTANCE hDll; HRESULT res=-1; if (NULL != (hDll = LoadLibrary(TEXT("uxtheme.dll")))) { if (NULL != (pfnETDT = (ENABLETHEMEDIALOGTEXTURE)GetProcAddress(hDll, "EnableThemeDialogTexture"))) { res = pfnETDT(hwnd, ETDT_ENABLETAB); } FreeLibrary(hDll); } return res; } //#EOF
23.048338
102
0.661555
saivert
3a5770ed7e9e6ae6bd585b7832f2b8c092249fa0
2,525
hpp
C++
src/lib/optimizer/strategy/abstract_rule.hpp
mrcl-tst/hyrise
eec50b39de9f530b0a1732ceb5822b7222f3fe17
[ "MIT" ]
583
2015-01-10T00:55:32.000Z
2022-03-25T12:24:30.000Z
src/lib/optimizer/strategy/abstract_rule.hpp
mrcl-tst/hyrise
eec50b39de9f530b0a1732ceb5822b7222f3fe17
[ "MIT" ]
1,573
2015-01-07T15:47:22.000Z
2022-03-31T11:48:03.000Z
src/lib/optimizer/strategy/abstract_rule.hpp
mrcl-tst/hyrise
eec50b39de9f530b0a1732ceb5822b7222f3fe17
[ "MIT" ]
145
2015-03-09T16:26:07.000Z
2022-02-15T12:53:23.000Z
#pragma once #include <memory> #include <string> #include <unordered_set> #include <vector> namespace opossum { class AbstractCardinalityEstimator; class AbstractCostEstimator; class AbstractLQPNode; class LogicalPlanRootNode; class LQPSubqueryExpression; class AbstractRule { public: virtual ~AbstractRule() = default; /** * This function applies the concrete Optimizer Rule to an LQP. * The default implementation * (1) optimizes the root LQP * (2) optimizes all (nested) subquery LQPs of the optimized root LQP, one-by-one. * * IMPORTANT NOTES ON OPTIMIZING SUBQUERY LQPS: * * Multiple Expressions in different nodes might reference the same LQP. Most commonly this will be the case * for a ProjectionNode computing a subquery and a subsequent PredicateNode filtering based on it. * We do not WANT to optimize the LQP twice (optimization takes time after all) and we CANNOT optimize it * twice, since, e.g., a non-deterministic rule, could produce two different LQPs while optimizing and then the * SubqueryExpression in the PredicateNode couldn't be resolved to a column anymore. There are more subtle * ways LQPs might break in this scenario, and frankly, this is one of the weak links in the expression system... * * ...long story short: * !!! * EACH UNIQUE SUB-LQP IS ONLY OPTIMIZED ONCE, EVEN IF IT OCCURS IN DIFFERENT NODES/EXPRESSIONS. * !!! * * Rules can define their own strategy of optimizing subquery LQPs by overriding this function. See, for example, the * StoredTableColumnAlignmentRule. */ virtual void apply_to_plan(const std::shared_ptr<LogicalPlanRootNode>& lqp_root) const; virtual std::string name() const = 0; std::shared_ptr<AbstractCostEstimator> cost_estimator; protected: /** * This function applies the concrete rule to the given plan, but not to its subquery plans. * * DO NOT CALL THIS FUNCTION RECURSIVELY! * The reason for this can be found in diamond LQPs: When using "trivial" recursion, we would go down both on the * left and the right side of the diamond. On both sides, we would reach the bottom of the diamond. From there, we * would look at each node twice. visit_lqp prevents this by tracking which nodes have already been visited and * avoiding visiting a node twice. */ virtual void _apply_to_plan_without_subqueries(const std::shared_ptr<AbstractLQPNode>& lqp_root) const = 0; }; } // namespace opossum
40.079365
120
0.726733
mrcl-tst
3a5ac902c963d1d7d4d5174d9dc0c7e5ea6c8491
122
hxx
C++
src/Providers/UNIXProviders/SwapSpaceCheck/UNIX_SwapSpaceCheck_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/SwapSpaceCheck/UNIX_SwapSpaceCheck_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/SwapSpaceCheck/UNIX_SwapSpaceCheck_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_AIX #ifndef __UNIX_SWAPSPACECHECK_PRIVATE_H #define __UNIX_SWAPSPACECHECK_PRIVATE_H #endif #endif
10.166667
39
0.844262
brunolauze
3a5acce5b031d3cae5934147f13a40e54db48860
1,504
cpp
C++
Source/modio/Private/BlueprintCallbackProxies/CallbackProxy_GetAllModFiles.cpp
rproepp/UE4Plugin
fea28dd683bce081a57f3346c74c3fee26e76ace
[ "MIT" ]
12
2021-03-26T07:49:10.000Z
2022-03-30T10:24:24.000Z
Source/modio/Private/BlueprintCallbackProxies/CallbackProxy_GetAllModFiles.cpp
colorstheforce/modio-ue4
374241e232269398465cd659b41488933ba42a39
[ "MIT" ]
2
2021-07-15T16:15:33.000Z
2021-11-14T09:18:17.000Z
Source/modio/Private/BlueprintCallbackProxies/CallbackProxy_GetAllModFiles.cpp
colorstheforce/modio-ue4
374241e232269398465cd659b41488933ba42a39
[ "MIT" ]
2
2021-06-11T21:45:56.000Z
2022-03-18T06:30:00.000Z
// Copyright 2020 modio. All Rights Reserved. // Released under MIT. #include "BlueprintCallbackProxies/CallbackProxy_GetAllModFiles.h" #include "ModioSubsystem.h" #include "Engine/Engine.h" UCallbackProxy_GetAllModfiles::UCallbackProxy_GetAllModfiles(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } UCallbackProxy_GetAllModfiles* UCallbackProxy_GetAllModfiles::GetAllModfiles(UObject* WorldContext, int32 ModId) { UCallbackProxy_GetAllModfiles* Proxy = NewObject<UCallbackProxy_GetAllModfiles>(); Proxy->SetFlags(RF_StrongRefOnFrame); Proxy->ModId = ModId; Proxy->WorldContextObject = WorldContext; return Proxy; } void UCallbackProxy_GetAllModfiles::Activate() { UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); FModioSubsystemPtr Modio = FModioSubsystem::Get(World); if (Modio.IsValid()) { Modio->GetAllModfiles(this->ModId, FModioModfileArrayDelegate::CreateUObject(this, &UCallbackProxy_GetAllModfiles::OnGetAllModfilesDelegate)); } else { // @todonow: Make something more pretty than this FModioResponse Response; TArray<FModioModfile> Mods; OnFailure.Broadcast(Response, Mods); } } void UCallbackProxy_GetAllModfiles::OnGetAllModfilesDelegate(FModioResponse Response, const TArray<FModioModfile>& Modfiles) { if (Response.Code >= 200 && Response.Code < 300) { OnSuccess.Broadcast(Response, Modfiles); } else { OnFailure.Broadcast(Response, Modfiles); } }
30.08
143
0.791888
rproepp
3a5d42c70bcd6b24b4896625c41a4ff2801ebcd3
2,414
hpp
C++
include/VFSPP/core.hpp
asarium/vfspp
854af7fdef8b8f72629c81fae5f2404b572d490d
[ "MIT" ]
5
2015-03-27T02:40:12.000Z
2018-12-11T02:58:04.000Z
include/VFSPP/core.hpp
asarium/vfspp
854af7fdef8b8f72629c81fae5f2404b572d490d
[ "MIT" ]
null
null
null
include/VFSPP/core.hpp
asarium/vfspp
854af7fdef8b8f72629c81fae5f2404b572d490d
[ "MIT" ]
2
2016-08-22T09:42:59.000Z
2020-07-04T20:18:59.000Z
#pragma once #include <string> #include <vector> #include <boost/smart_ptr.hpp> #include <boost/algorithm/string.hpp> #include "vfspp_compiler_detection.h" #include "vfspp_export.h" namespace vfspp { class IFileSystemEntry; typedef std::string string_type; typedef boost::shared_ptr<IFileSystemEntry> FileEntryPointer; const char DirectorySeparatorChar = '/'; const char * const DirectorySeparatorStr = "/"; enum EntryType { UNKNOWN, DIRECTORY, FILE }; enum Operations { OP_READ = 1 << 0, OP_WRITE = 1 << 1, OP_DELETE = 1 << 2, OP_CREATE = 1 << 3 }; class VFSPP_EXPORT InvalidOperationException : public std::exception { public: InvalidOperationException(const string_type& message = "Invalid operation!") throw() : msg(message) {} virtual ~InvalidOperationException() throw() {} const char* what() const throw() VFSPP_OVERRIDE { return msg.c_str(); } private: string_type msg; }; class VFSPP_EXPORT FileSystemException : public std::exception { public: FileSystemException(const string_type& message = "Invalid operation!") throw() : msg(message) {} virtual ~FileSystemException() throw() {} const char* what() const throw() VFSPP_OVERRIDE { return msg.c_str(); } private: string_type msg; }; class VFSPP_EXPORT IFileSystemEntry { public: enum OpenMode { MODE_READ = 1 << 0, MODE_WRITE = 1 << 1, MODE_MEMORY_MAPPED = 1 << 2, }; protected: string_type path; public: IFileSystemEntry(const string_type& pathIn); virtual ~IFileSystemEntry() {} bool isRoot() const { return path.size() == 0; } const string_type& getPath() const { return path; } virtual FileEntryPointer getChild(const string_type& path) = 0; virtual size_t numChildren() = 0; virtual void listChildren(std::vector<FileEntryPointer>& outVector) = 0; virtual boost::shared_ptr<std::streambuf> open(int mode = MODE_READ) = 0; virtual EntryType getType() const = 0; virtual bool deleteChild(const string_type& name) = 0; virtual FileEntryPointer createEntry(EntryType type, const string_type& name) = 0; virtual void rename(const string_type& newPath) = 0; virtual time_t lastWriteTime() = 0; }; class VFSPP_EXPORT IFileSystem { public: virtual ~IFileSystem() {} virtual IFileSystemEntry* getRootEntry() = 0; virtual int supportedOperations() const = 0; virtual string_type getName() const = 0; }; }
20.116667
101
0.707125
asarium
3a5d555a8ef076a4c95005f21f6902e022895a1f
19,398
cc
C++
chrome/browser/ash/login/app_mode/kiosk_launch_controller_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/browser/ash/login/app_mode/kiosk_launch_controller_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/browser/ash/login/app_mode/kiosk_launch_controller_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 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 "base/strings/strcat.h" #include "chrome/browser/ash/app_mode/kiosk_app_manager.h" #include "chrome/browser/ash/app_mode/kiosk_app_types.h" #include "chrome/browser/ash/app_mode/web_app/mock_web_kiosk_app_launcher.h" #include "chrome/browser/ash/login/app_mode/kiosk_launch_controller.h" #include "chrome/browser/ash/login/test/kiosk_test_helpers.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/external_provider_impl.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/fake_app_launch_splash_screen_handler.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "components/account_id/account_id.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/policy_constants.h" #include "components/session_manager/core/session_manager.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/browser_test.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/pref_names.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { using ::testing::_; const char kExtensionId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const char kExtensionName[] = "extension_name"; const char kInvalidExtensionId[] = "invalid_id"; const char kInvalidExtensionName[] = "invalid_name"; // URL of Chrome Web. const char kExtensionUpdateUrl[] = "https://clients2.google.com/service/update2/crx"; class KioskLaunchControllerTest : public InProcessBrowserTest, public ::testing::WithParamInterface<KioskAppType> { public: using AppState = KioskLaunchController::AppState; using NetworkUIState = KioskLaunchController::NetworkUIState; KioskLaunchControllerTest() = default; KioskLaunchControllerTest(const KioskLaunchControllerTest&) = delete; KioskLaunchControllerTest& operator=(const KioskLaunchControllerTest&) = delete; void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); auto app_launcher = std::make_unique<MockWebKioskAppLauncher>(); view_ = std::make_unique<FakeAppLaunchSplashScreenHandler>(); app_launcher_ = app_launcher.get(); disable_wait_timer_and_login_operations_for_testing_ = KioskLaunchController::DisableWaitTimerAndLoginOperationsForTesting(); controller_ = KioskLaunchController::CreateForTesting( view_.get(), std::move(app_launcher)); switch (GetParam()) { case KioskAppType::kArcApp: kiosk_app_id_ = KioskAppId::ForArcApp(EmptyAccountId()); break; case KioskAppType::kChromeApp: kiosk_app_id_ = KioskAppId::ForChromeApp(std::string()); KioskAppManager::Get()->AddAppForTest(std::string(), EmptyAccountId(), GURL(), std::string()); break; case KioskAppType::kWebApp: kiosk_app_id_ = KioskAppId::ForWebApp(EmptyAccountId()); break; } } KioskLaunchController* controller() { return controller_.get(); } KioskAppLauncher::Delegate* launch_controls() { return static_cast<KioskAppLauncher::Delegate*>(controller_.get()); } KioskProfileLoader::Delegate* profile_controls() { return static_cast<KioskProfileLoader::Delegate*>(controller_.get()); } AppLaunchSplashScreenView::Delegate* view_controls() { return static_cast<AppLaunchSplashScreenView::Delegate*>(controller_.get()); } MockWebKioskAppLauncher* launcher() { return app_launcher_; } void ExpectState(AppState app_state, NetworkUIState network_state) { EXPECT_EQ(app_state, controller_->app_state_); EXPECT_EQ(network_state, controller_->network_ui_state_); } void ExpectViewState(AppLaunchSplashScreenView::AppLaunchState launch_state) { EXPECT_EQ(launch_state, view_->GetAppLaunchState()); } void FireSplashScreenTimer() { controller_->OnTimerFire(); } void SetOnline(bool online) { view_->SetNetworkReady(online); static_cast<AppLaunchSplashScreenView::Delegate*>(controller_.get()) ->OnNetworkStateChanged(online); } Profile* profile() { return browser()->profile(); } FakeAppLaunchSplashScreenHandler* view() { return view_.get(); } KioskAppId kiosk_app_id() { return kiosk_app_id_; } private: ScopedCanConfigureNetwork can_configure_network_for_testing_{true, false}; std::unique_ptr<base::AutoReset<bool>> disable_wait_timer_and_login_operations_for_testing_; std::unique_ptr<FakeAppLaunchSplashScreenHandler> view_; MockWebKioskAppLauncher* app_launcher_; // owned by `controller_`. std::unique_ptr<KioskLaunchController> controller_; KioskAppId kiosk_app_id_; }; IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, RegularFlow) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, AlreadyInstalled) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, ConfigureNetworkBeforeProfile) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); // User presses the hotkey. view_controls()->OnNetworkConfigRequested(); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNeedToShow); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kShowingNetworkConfigureUI); // WebKioskAppLauncher::Initialize call is synchronous, we have to call the // response now. launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigFinished(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingProfile); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); launch_controls()->OnAppPrepared(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); // Skipping INSTALLED state since there splash screen timer is stopped when // network configure ui was shown. launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, ConfigureNetworkDuringInstallation) { SetOnline(false); controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); // User presses the hotkey, current installation is canceled. EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigRequested(); // Launcher restart causes network to be requested again. launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigFinished(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingProfile); launch_controls()->OnAppInstalling(); ExpectState(AppState::kInstallingApp, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, ConnectionLostDuringInstallation) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); ExpectState(AppState::kInstallingApp, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); SetOnline(false); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kShowing); // view state? EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigFinished(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingProfile); launch_controls()->OnAppInstalling(); ExpectState(AppState::kInstallingApp, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } INSTANTIATE_TEST_SUITE_P(All, KioskLaunchControllerTest, testing::Values(KioskAppType::kArcApp, KioskAppType::kChromeApp, KioskAppType::kWebApp)); class KioskLaunchControllerWithExtensionTest : public KioskLaunchControllerTest { public: void SetupForceList(const std::string& extension_id) { std::unique_ptr<base::Value> dict = extensions::DictionaryBuilder() .Set(extension_id, extensions::DictionaryBuilder() .Set(extensions::ExternalProviderImpl::kExternalUpdateUrl, kExtensionUpdateUrl) .Build()) .Build(); ProfileManager::GetPrimaryUserProfile()->GetPrefs()->Set( extensions::pref_names::kInstallForceList, std::move(*dict)); base::Value list(base::Value::Type::LIST); list.Append(base::StrCat({extension_id, ";", kExtensionUpdateUrl})); policy::PolicyMap map; map.Set(policy::key::kExtensionInstallForcelist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, std::move(list), nullptr); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get( ProfileManager::GetPrimaryUserProfile()); extensions::TestExtensionRegistryObserver install_observer(registry); policy_provider_.UpdateChromePolicy(map); base::RunLoop().RunUntilIdle(); } void PreRunTestOnMainThread() override { SetupForceList(kExtensionId); InProcessBrowserTest::PreRunTestOnMainThread(); } extensions::ForceInstalledTracker* force_installed_tracker() { return extensions::ExtensionSystem::Get(profile()) ->extension_service() ->force_installed_tracker(); } void RunUntilAppPrepared() { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); } void SetExtensionLoaded(const std::string& extension_id, const std::string& extension_name) { auto ext = extensions::ExtensionBuilder(extension_name) .SetID(extension_id) .Build(); force_installed_tracker()->OnExtensionLoaded(profile(), ext.get()); } void SetExtensionReady(const std::string& extension_id, const std::string& extension_name) { auto ext = extensions::ExtensionBuilder(extension_name) .SetID(extension_id) .Build(); force_installed_tracker()->OnExtensionReady(profile(), ext.get()); } policy::MockConfigurationPolicyProvider policy_provider_; }; IN_PROC_BROWSER_TEST_P(KioskLaunchControllerWithExtensionTest, ExtensionLoadedBeforeAppPrepared) { SetExtensionReady(kExtensionId, kExtensionName); RunUntilAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerWithExtensionTest, ExtensionLoadedAfterAppPrepared) { RunUntilAppPrepared(); ExpectState(AppState::kInstallingExtensions, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingExtension); SetExtensionReady(kExtensionId, kExtensionName); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } INSTANTIATE_TEST_SUITE_P(All, KioskLaunchControllerWithExtensionTest, testing::Values(KioskAppType::kArcApp, KioskAppType::kChromeApp, KioskAppType::kWebApp)); class KioskLaunchControllerWithInvalidExtensionTest : public KioskLaunchControllerWithExtensionTest { public: void SetUpInProcessBrowserTestFixture() override { base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs"); EXPECT_CALL(policy_provider_, IsInitializationComplete(_)) .WillRepeatedly(testing::Return(true)); EXPECT_CALL(policy_provider_, IsFirstPolicyLoadComplete(_)) .WillRepeatedly(testing::Return(true)); policy::BrowserPolicyConnector::SetPolicyProviderForTesting( &policy_provider_); } void PreRunTestOnMainThread() override { SetupForceList(kInvalidExtensionId); InProcessBrowserTest::PreRunTestOnMainThread(); } }; IN_PROC_BROWSER_TEST_P(KioskLaunchControllerWithInvalidExtensionTest, InvalidExtensionInstallForceListPolicy) { SetExtensionLoaded(kInvalidExtensionId, kInvalidExtensionName); RunUntilAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); EXPECT_EQ(view()->GetErrorMessageType(), KioskAppLaunchError::Error::kExtensionsPolicyInvalid); } INSTANTIATE_TEST_SUITE_P(All, KioskLaunchControllerWithInvalidExtensionTest, testing::Values(KioskAppType::kArcApp, KioskAppType::kChromeApp, KioskAppType::kWebApp)); } // namespace ash
40.4125
89
0.74982
DamieFC
3a5e0b8fbebf28c8fb4082643cda8428bc575d82
744
cpp
C++
books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_3-MOVING_TO_MODERN_C++/item_15-use_constexpr_whenever_possible/case_5-constexpr_c++11/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_3-MOVING_TO_MODERN_C++/item_15-use_constexpr_whenever_possible/case_5-constexpr_c++11/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_3-MOVING_TO_MODERN_C++/item_15-use_constexpr_whenever_possible/case_5-constexpr_c++11/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
class Point { public: constexpr Point(double xVal = 0, double yVal = 0) noexcept : x(xVal), y(yVal) { } constexpr double xValue() const noexcept { return x; } constexpr double yValue() const noexcept { return y; } void setX(double newX) noexcept { x = newX; } void setY(double newY) noexcept { y = newY; } private: double x, y; }; constexpr Point midpoint(const Point& p1, const Point& p2) noexcept { return { (p1.xValue() + p2.xValue()) / 2, (p2.yValue() + p2.yValue()) / 2 }; } int main() { constexpr Point p1(9.4, 27.7); constexpr Point p2(28.8, 5.3); constexpr auto mid = midpoint(p1, p2); return 0; }
25.655172
70
0.547043
ordinary-developer
3a5e9c5955d341271c7599f69957846aac11979a
6,847
hpp
C++
include/cube.hpp
xyproto/spheremover
174b6ec84472e03cad240376e433dc65da522f83
[ "MIT" ]
2
2020-12-13T20:45:37.000Z
2020-12-14T07:56:15.000Z
include/cube.hpp
xyproto/spheremover
174b6ec84472e03cad240376e433dc65da522f83
[ "MIT" ]
null
null
null
include/cube.hpp
xyproto/spheremover
174b6ec84472e03cad240376e433dc65da522f83
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <iomanip> #include <limits> #include <sstream> #include <string> #include <vector> #include "points.hpp" #include "vec3.hpp" using namespace std::string_literals; // Cube has a position, a width (x), a height (y) and a depth (z) class Cube { protected: const Vec3 m_pos; // center position of the cube const double m_whd[3]; // width, height and depth public: Cube(double _x, double _y, double _z, double _w, double _h, double _d) : m_pos { _x, _y, _z } , m_whd { _w, _h, _d } { } Cube(double _x, double _y, double _z, double _whd) // same width, height and depth : m_pos { _x, _y, _z } , m_whd { _whd, _whd, _whd } { } Cube(const Vec3 _pos, double _w, double _h, double _d) : m_pos { _pos } , m_whd { _w, _h, _d } { } Cube(const Vec3 _pos, double _whd) // same width, height and depth : m_pos { _pos } , m_whd { _whd, _whd, _whd } { } const std::string str() const; double x() const; double y() const; double z() const; double w() const; double h() const; double d() const; const Vec3 pos() const; const Vec3 normal(const Vec3 p) const; const Vec3 p0() const; const Vec3 p1() const; const Vec3 p2() const; const Vec3 p3() const; const Vec3 p4() const; const Vec3 p5() const; const Vec3 p6() const; const Vec3 p7() const; const Points points() const; }; // str returns a string representation of the cube // The string function returns a constant string ("const std::string"), // and does not modify anything ("const"). inline const std::string Cube::str() const { std::stringstream ss; ss << "cube: ("s << m_pos << ", "s << m_whd[0] << ", "s << m_whd[1] << ", "s << m_whd[2] << ")"s; return ss.str(); } // Implement support for the << operator, by calling the Vec3 str method inline std::ostream& operator<<(std::ostream& os, const Cube& s) { os << s.str(); return os; } double Cube::x() const { return m_pos.x(); } double Cube::y() const { return m_pos.y(); } double Cube::z() const { return m_pos.z(); } double Cube::w() const { return m_whd[0]; } double Cube::h() const { return m_whd[1]; } double Cube::d() const { return m_whd[2]; } const Vec3 Cube::pos() const { return m_pos; } // m_pos is the center position // rv is the "radius offset // left bottom front point of the cube (-, -, -) const Vec3 Cube::p0() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { -r0, -r1, -r2 }; } // right bottom front point of the cube (+, -, -) const Vec3 Cube::p1() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { r0, -r1, -r2 }; } // right bottom back point of the cube (+, -, +) const Vec3 Cube::p2() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { r0, -r1, r2 }; } // left bottom back point of the cube (-, -, +) const Vec3 Cube::p3() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { -r0, -r1, r2 }; } // left top front point of the cube (-, +, -) const Vec3 Cube::p4() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { -r0, r1, -r2 }; } // right top front point of the cube (+, +, -) const Vec3 Cube::p5() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { r0, r1, -r2 }; } // right top back point of the cube (+, +, +) const Vec3 Cube::p6() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; return m_pos + Vec3 { r0, r1, r2 }; } // left top back point of the cube (-, +, +) const Vec3 Cube::p7() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; return m_pos + Vec3 { -r0, r1, r2 }; } // points returns a vector of ordered points for this cube const Points Cube::points() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; return Points { std::move(m_pos + Vec3 { -r0, -r1, -r2 }), std::move(m_pos + Vec3 { r0, -r1, -r2 }), std::move(m_pos + Vec3 { r0, -r1, r2 }), std::move(m_pos + Vec3 { -r0, -r1, r2 }), std::move(m_pos + Vec3 { -r0, r1, -r2 }), std::move(m_pos + Vec3 { r0, r1, -r2 }), std::move(m_pos + Vec3 { r0, r1, r2 }), std::move(m_pos + Vec3 { -r0, r1, r2 }), }; } // Get the normal sticking out from the cube at the point p on the surface of the cube const Vec3 Cube::normal(const Vec3 p) const { // BAH. None of the plans work. This function is a work in progress. // 1. Find the closest three points on the cube. // 2. Treat those three points as a face and find the normal from that. // 3. ::intify that normal to get a cube normal. Points xs = this->points(); // TODO: This can be made faster by passing in a distance_squared cache pointer to // each *_closest_* function call. size_t smallest_ai = index_closest(xs, p); size_t smallest_bi = index_closest_except(xs, p, std::vector<size_t> { smallest_ai }); size_t smallest_ci = index_closest_except(xs, p, std::vector<size_t> { smallest_ai, smallest_bi }); size_t smallest_di = index_closest_except( xs, p, std::vector<size_t> { smallest_ai, smallest_bi, smallest_ci }); // Okay, now create vectors that are from the center of the cube to these 3 closest points const Vec3 av = xs[smallest_ai] - m_pos; const Vec3 bv = xs[smallest_bi] - m_pos; const Vec3 cv = xs[smallest_ci] - m_pos; const Vec3 dv = xs[smallest_di] - m_pos; // Average the vectors const Vec3 average_closest = (av + bv + cv + dv) / 4; // Just return the clostest vertex, from the center and to that one, // then normalize and intify. // return av.normalize().intify(); // Normalize the average const Vec3 average_closest_normalized = average_closest.normalize(); // Intify the averaged normal to get a normal that points straight out return average_closest_normalized.intify(); }
26.642023
94
0.595735
xyproto
3a6076681f32c7e0ff074420433601df4c840244
1,215
cpp
C++
src/core/Processor.cpp
ASxa86/azule
9bf89dfc5a80f296b02edd3ac608d9a90e4ea26b
[ "MIT" ]
1
2018-10-19T18:00:19.000Z
2018-10-19T18:00:19.000Z
src/core/Processor.cpp
ASxa86/azule
9bf89dfc5a80f296b02edd3ac608d9a90e4ea26b
[ "MIT" ]
7
2019-06-13T00:48:55.000Z
2020-05-05T00:18:42.000Z
src/core/Processor.cpp
ASxa86/AGE
9bf89dfc5a80f296b02edd3ac608d9a90e4ea26b
[ "MIT" ]
null
null
null
#include <azule/core/Processor.h> #include <azule/utilities/PimplImpl.h> using namespace azule; class Processor::Impl { public: std::vector<std::function<void(std::chrono::microseconds)>> fixedFunctions; std::vector<std::function<void(std::chrono::microseconds)>> variableFunctions; std::vector<std::function<void(std::chrono::microseconds)>> renderFunctions; }; Processor::Processor() { } Processor::~Processor() { } void Processor::fixed(std::chrono::microseconds x) { for(const auto& f : this->pimpl->fixedFunctions) { f(x); } } void Processor::variable(std::chrono::microseconds x) { for(const auto& f : this->pimpl->variableFunctions) { f(x); } } void Processor::render(std::chrono::microseconds x) { for(const auto& f : this->pimpl->renderFunctions) { f(x); } } void Processor::addFixedFunction(const std::function<void(std::chrono::microseconds)>& x) { this->pimpl->fixedFunctions.push_back(x); } void Processor::addVariableFunction(const std::function<void(std::chrono::microseconds)>& x) { this->pimpl->variableFunctions.push_back(x); } void Processor::addRenderFunction(const std::function<void(std::chrono::microseconds)>& x) { this->pimpl->renderFunctions.push_back(x); }
20.25
92
0.723457
ASxa86
3a611f0e25da9757510cd0d85febd4c131a8df8c
3,793
cc
C++
src/baldr/compression_utils.cc
mixvit/valhalla
65d56caf85103f267452e7b79e49ec66a9bf480e
[ "MIT" ]
1
2020-01-12T21:14:45.000Z
2020-01-12T21:14:45.000Z
src/baldr/compression_utils.cc
Bolaxax/valhalla
f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb
[ "MIT" ]
3
2020-08-24T18:48:12.000Z
2021-01-05T21:18:44.000Z
src/baldr/compression_utils.cc
Bolaxax/valhalla
f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb
[ "MIT" ]
1
2021-01-24T16:46:01.000Z
2021-01-24T16:46:01.000Z
#include "baldr/compression_utils.h" namespace valhalla { namespace baldr { /* Deflates data with gzip or zlib wrapper * @param src_func function which modifies the stream to read more input * @param dst_func function which modifies the stream to write more output * @param level what compression level to use * @param gzip whether or not to write a gzip header instead of a zlib one * @return returns true if the stream was successfully inflated, false otherwise */ bool deflate(const std::function<int(z_stream&)>& src_func, const std::function<void(z_stream&)>& dst_func, int level, bool gzip) { // initialize the stream // add 16 to window bits for gzip header instead of zlib header, 9 is max speed z_stream stream{}; if (deflateInit2(&stream, level, Z_DEFLATED, gzip ? 15 + 16 : 15, 9, Z_DEFAULT_STRATEGY) != Z_OK) return false; int flush = Z_NO_FLUSH; int code = Z_OK; do { // if we need more src material try { if (stream.avail_in == 0) flush = src_func(stream); } catch (...) { deflateEnd(&stream); return false; } do { // if we need more space in the dst try { if (stream.avail_out == 0) dst_func(stream); } catch (...) { deflateEnd(&stream); return false; } // only one fatal error to worry about code = deflate(&stream, flush); if (code == Z_STREAM_ERROR) { deflateEnd(&stream); return false; } // only stop when we've got nothing more to put in the dst buffer } while (stream.avail_out == 0); // only stop when we signaled that we have no more input } while (flush != Z_FINISH); // hand back the final buffer dst_func(stream); // if we got here we expected to finish but weren't thats not good deflateEnd(&stream); return true; } /* Inflates gzip or zlib wrapped deflated data * @param src_func function which modifies the stream to read more input * @param dst_func function which modifies the stream to write more output * @return returns true if the stream was successfully inflated, false otherwise */ bool inflate(const std::function<void(z_stream&)>& src_func, const std::function<int(z_stream&)>& dst_func) { // initialize the stream // MAX_WBITS is the max size of the window and should be 15, this will work with headerless // defalted streams to work with gzip add 16, to work with both gzip and libz add 32 z_stream stream{}; if (inflateInit2(&stream, MAX_WBITS + 32) != Z_OK) return false; int flush = Z_NO_FLUSH; int code = Z_OK; do { // if we need more src material try { if (stream.avail_in == 0) src_func(stream); if (stream.avail_in == 0) throw; } catch (...) { inflateEnd(&stream); return false; } do { // if we need more space in the dst try { if (stream.avail_out == 0) flush = dst_func(stream); } catch (...) { inflateEnd(&stream); return false; } // several fatal errors to worry about code = inflate(&stream, flush); switch (code) { case Z_STREAM_ERROR: case Z_NEED_DICT: case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&stream); return false; } // only stop when we've got nothing more to put in the dst buffer } while (stream.avail_out == 0); // only stop when we reached the end of the stream } while (code != Z_STREAM_END); // hand back the final buffer dst_func(stream); // if we got here we expected to finish but weren't thats not good inflateEnd(&stream); return true; } } // namespace baldr } // namespace valhalla
30.344
99
0.627472
mixvit
3a61736a725e8c08f3f43de560bde183998f7e7d
9,905
cpp
C++
src/utils2d/axisalignedboundingbox2d.cpp
AlessandroParrotta/parrlib
d1679ee8a7cff7d14b2d93e898ed58fecff13159
[ "MIT" ]
2
2020-05-08T20:27:14.000Z
2021-01-21T10:28:19.000Z
src/utils2d/axisalignedboundingbox2d.cpp
AlessandroParrotta/parrlib
d1679ee8a7cff7d14b2d93e898ed58fecff13159
[ "MIT" ]
null
null
null
src/utils2d/axisalignedboundingbox2d.cpp
AlessandroParrotta/parrlib
d1679ee8a7cff7d14b2d93e898ed58fecff13159
[ "MIT" ]
1
2020-05-08T20:27:16.000Z
2020-05-08T20:27:16.000Z
#include <parrlib/utils2d/AxisAlignedBoundingBox2D.h> #include <iostream> #include <parrlib/Matrix3f.h> #include <parrlib/otherutil.h> #include <parrlib/stringutils.h> AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(){} //AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(float v) { vmax = v; vmin = v; } AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 v) : vmin(v), vmax(v) {} AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 min, vec2 max) : vmin(min), vmax(max) { align(); } AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 min, vec2 max, bool doalign) : vmin(min), vmax(max), doalign(doalign) { align(); } bool AxisAlignedBoundingBox2D::intersects(AxisAlignedBoundingBox2D const& bb) const { return vmin.x < bb.maxx() && vmax.x > bb.minx() && vmin.y < bb.maxy() && vmax.y > bb.miny(); } void AxisAlignedBoundingBox2D::rescale(vec2 const& v) { if (v.x < vmin.x) vmin.x = v.x; else if (v.x > vmax.x) vmax.x = v.x; if (v.y < vmin.y) vmin.y = v.y; else if (v.y > vmax.y) vmax.y = v.y; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::rescaled(vec2 const& v) const { aabb2 bb = *this; bb.rescale(v); return bb; } void AxisAlignedBoundingBox2D::narrow(AxisAlignedBoundingBox2D const& bb) { if (vmin.x < bb.fmin().x) vmin.x = bb.fmin().x; if (vmin.y < bb.fmin().y) vmin.y = bb.fmin().y; if (vmax.x > bb.fmax().x) vmax.x = bb.fmax().x; if (vmax.y > bb.fmax().y) vmax.y = bb.fmax().y; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::narrowed(AxisAlignedBoundingBox2D const& bb) const { aabb2 tbb = *this; tbb.narrow(bb); return tbb; } void AxisAlignedBoundingBox2D::fit(AxisAlignedBoundingBox2D const& bb) { *this = fitted(bb); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fitted(AxisAlignedBoundingBox2D const& bb) { vec2 p = bb.size() / size(); float scale = outl::minfabs(p.x, p.y); return (centered() * scale + bb.center()); } bool AxisAlignedBoundingBox2D::inside(AxisAlignedBoundingBox2D const& bb) const { return vmin.x >= bb.minx() && vmin.y >= bb.miny() && vmax.x <= bb.maxx() && vmax.y <= bb.maxy(); } bool AxisAlignedBoundingBox2D::pointInside(vec2 const& v) const { return v.x >= vmin.x && v.x <= vmax.x && v.y >= vmin.y && v.y <= vmax.y; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+(vec2 const& v) const { return aabb2(vmin + v, vmax + v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-(vec2 const& v) const { return aabb2(vmin - v, vmax - v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*(vec2 const& v) const { return aabb2(vmin * v, vmax * v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/(vec2 const& v) const { return aabb2(vmin / v, vmax / v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin + bb.fmin(), vmax + bb.fmax()); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin - bb.fmin(), vmax - bb.fmax()); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin * bb.fmin(), vmax * bb.fmax()); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin / bb.fmin(), vmax / bb.fmax()); } AxisAlignedBoundingBox2D operator+ (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v + bb.fmin(), v + bb.fmax() }; } AxisAlignedBoundingBox2D operator- (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v - bb.fmin(), v - bb.fmax() }; } AxisAlignedBoundingBox2D operator* (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v * bb.fmin(), v * bb.fmax() }; } AxisAlignedBoundingBox2D operator/ (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v / bb.fmin(), v / bb.fmax() }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+=(vec2 const& v) { vmin += v; vmax += v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-=(vec2 const& v) { vmin -= v; vmax -= v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*=(vec2 const& v) { vmin *= v; vmax *= v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/=(vec2 const& v) { vmin /= v; vmax /= v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+=(AxisAlignedBoundingBox2D const& bb) { vmin += bb.fmin(); vmax += bb.fmax(); return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-=(AxisAlignedBoundingBox2D const& bb) { vmin -= bb.fmin(); vmax -= bb.fmax(); return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*=(AxisAlignedBoundingBox2D const& bb) { vmin *= bb.fmin(); vmax *= bb.fmax(); return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/=(AxisAlignedBoundingBox2D const& bb) { vmin /= bb.fmin(); vmax /= bb.fmax(); return *this; } bool AxisAlignedBoundingBox2D::operator==(float f) const { return vmin == f && vmax == f; } bool AxisAlignedBoundingBox2D::operator!=(float f) const { return vmin != f && vmax != f; } bool AxisAlignedBoundingBox2D::operator==(AxisAlignedBoundingBox2D const& f) const { return vmin == f.fmin() && vmax == f.fmax(); } bool AxisAlignedBoundingBox2D::operator!=(AxisAlignedBoundingBox2D const& f) const { return vmin != f.fmin() && vmax != f.fmax(); } void AxisAlignedBoundingBox2D::align() { if (!doalign) return; if (vmin.x > vmax.x) std::swap(vmin.x, vmax.x); if (vmin.y > vmax.y) std::swap(vmin.y, vmax.y); } void AxisAlignedBoundingBox2D::fmaxr(vec2 max) { this->vmax = max; align(); } vec2 AxisAlignedBoundingBox2D::fmax() const { return vmax; } void AxisAlignedBoundingBox2D::fminr(vec2 min) { this->vmin = min; align(); } vec2 AxisAlignedBoundingBox2D::fmin() const { return vmin; } vec2 AxisAlignedBoundingBox2D::center() const { return (vmin + vmax) / 2.f; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::centered() const { return *this - center(); } float AxisAlignedBoundingBox2D::minx() const { return vmin.x; } float AxisAlignedBoundingBox2D::miny() const { return vmin.y; } float AxisAlignedBoundingBox2D::maxx() const { return vmax.x; } float AxisAlignedBoundingBox2D::maxy() const { return vmax.y; } void AxisAlignedBoundingBox2D::maxxr(float f) { vmax.x = f; } void AxisAlignedBoundingBox2D::maxyr(float f) { vmax.y = f; } void AxisAlignedBoundingBox2D::minxr(float f) { vmin.x = f; } void AxisAlignedBoundingBox2D::minyr(float f) { vmin.y = f; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::maxx(float f) const { return aabb2{ vmin, {f, vmax.y} }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::maxy(float f) const { return aabb2{ vmin, {vmax.x, f} }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::minx(float f) const { return aabb2{ { f, vmin.y }, vmax }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::miny(float f) const { return aabb2{ { vmin.x, f }, vmax }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fmax(vec2 vmax) const { return aabb2{ vmin, vmax }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fmin(vec2 vmin) const { return aabb2{ vmin, vmax }; } vec2 AxisAlignedBoundingBox2D::get(int i) const { switch (i) { case 0: return {vmin.x, vmin.y}; case 1: return {vmin.x, vmax.y}; case 2: return {vmax.x, vmax.y}; case 3: return {vmax.x, vmin.y}; } return 0.f; } float AxisAlignedBoundingBox2D::getSingle(int i) const { return i == 0 ? vmin.x : i == 1 ? vmin.y : i == 2 ? vmax.x : i == 3 ? vmax.y : 0.f; } vec2 AxisAlignedBoundingBox2D::operator[](int const& i) const { return get(i); } std::array<vec2, 4> AxisAlignedBoundingBox2D::toVerts() const { return { get(0), get(1), get(2), get(3) }; } vec2 AxisAlignedBoundingBox2D::edgeCenter(int i) const { return ((*this)[i] + (*this)[(i+1)%4])/2.f; } vec2 AxisAlignedBoundingBox2D::size() const { return vmax - vmin; } float AxisAlignedBoundingBox2D::sizex() const { return vmax.x - vmin.x; } float AxisAlignedBoundingBox2D::sizey() const { return vmax.y - vmin.y; } void AxisAlignedBoundingBox2D::scale(vec2 const& scale) { *this = scaled(scale); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::scaled(vec2 const& scale) const { return centered()*scale + center(); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::movedIn(vec2 const& delta) const { return { vmin + delta, vmax - delta }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::movedOut(vec2 const& delta) const { return { vmin - delta, vmax + delta }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::forcedIn(AxisAlignedBoundingBox2D const& bb) const{ if (inside(bb)) return *this; //just return if it's already inside if (size() > bb.size()) return bb; aabb2 resbb = *this; if (sizex() > bb.sizex()) resbb = resbb.scaled(vec2(bb.sizex()/sizex() , 1.f)); if (sizey() > bb.sizey()) resbb = resbb.scaled(vec2(1.f, bb.sizey()/sizey())); //translate along x axis if necessary bool xtrasl = false; if (resbb.minx() < bb.minx()) { resbb += vec2x(bb.minx() - resbb.minx()); xtrasl = true; } if (!xtrasl && resbb.maxx() > bb.maxx()) { resbb += vec2x(bb.maxx() - resbb.maxx()); xtrasl = true; } bool ytrasl = false; if (resbb.miny() < bb.fmin().y) { resbb += vec2y(bb.miny() - resbb.miny()); ytrasl = true; } if (!ytrasl && resbb.maxy() > bb.maxy()) { resbb += vec2y(bb.maxy() - resbb.maxy()); ytrasl = true; } return resbb; } std::string AxisAlignedBoundingBox2D::toString() const { std::stringstream ss; ss << "(" << vmin << ", " << vmax << ")"; return ss.str(); } std::ostream& operator<<(std::ostream& os, AxisAlignedBoundingBox2D const& bb) { return os << bb.toString(); } std::wostream& operator<<(std::wostream& os, AxisAlignedBoundingBox2D const& bb) { return os << stru::towstr(bb.toString()); } AxisAlignedBoundingBox2D aabb2s(vec2 const& size) { return { -size/2.f, size/2.f }; }
52.407407
156
0.713074
AlessandroParrotta
3a61efccacd3085e4acf1b2c007aa4dd998acc73
1,982
cpp
C++
src/game.cpp
kvbc/space_shooter
6e9e689d23c5b8570fb791ace938eab09d1b477b
[ "MIT" ]
1
2022-03-14T09:35:11.000Z
2022-03-14T09:35:11.000Z
src/game.cpp
kvbc/space_shooter
6e9e689d23c5b8570fb791ace938eab09d1b477b
[ "MIT" ]
null
null
null
src/game.cpp
kvbc/space_shooter
6e9e689d23c5b8570fb791ace938eab09d1b477b
[ "MIT" ]
null
null
null
#include <windows.h> #include <thread> #include "game.h" #include "particles.h" #include "math.h" #define pressed(c) GetAsyncKeyState(c) void Game::update() { Option BSIZE_X = value(m_op[OP_BSIZE_X]); Option BSIZE_Y = value(m_op[OP_BSIZE_Y]); Option PSPEED = value(m_op[OP_PSPEED]); if(m_plr.health() > 0) { m_plr.display_healthbar(m_board, {1, BSIZE_Y - 1}, PLAYER_HBARS); m_plr.display_health(m_board, {1 + PLAYER_HBARS, BSIZE_Y - 1}); if(m_enemies.size() > 0) for(int i = 0; i < m_enemies.size(); i++) { Entity &enemy = m_enemies[i]; if(enemy.health() > 0) { int _rand = rand(); std::thread([&]() { enemy.display(m_board); if(m_frame % 20 == 0) enemy.move({1, 0}); else if(m_frame % 10 == 0) enemy.move({-1, 0}); if(m_frame % (_rand % ENEMY_FIRERATE + 1) == 0) enemy.fire(m_board, DBULLET); }).detach(); } else m_enemies.m_data.erase(m_enemies.begin() + i); } else { m_board.clear(true); Sprite YouWon = {{{ SPRITE_YOUWON }}, m_op}; YouWon.write(m_board, { (BSIZE_X - YOUWON_SIZE_X) / 2, (BSIZE_Y - YOUWON_SIZE_Y) / 2}); m_board.display(); throw 0; } } else { m_board.clear(true); Sprite GameOver = {{{ SPRITE_GAMEOVER }}, m_op}; GameOver.write(m_board, { (BSIZE_X - GAMEOVER_SIZE_X) / 2, (BSIZE_Y - GAMEOVER_SIZE_Y) / 2}); m_board.display(); throw 0; } m_plr.display(m_board); for(Particle *particle : m_particles) particle->update(this); m_board.display(this); if ( pressed(VK_LEFT) || pressed('a') || pressed('A') ) m_plr.move({-PSPEED, 0}); else if ( pressed(VK_RIGHT) || pressed('d') || pressed('D') ) m_plr.move({PSPEED, 0}); if ( (pressed(VK_UP) || pressed('w') || pressed('W') || pressed(' ')) && m_frame % PLAYER_FIRERATE == 0 ) m_plr.fire(m_board, UBULLET); m_board.clear(); m_frame++; }
22.781609
96
0.573663
kvbc
3a68688cd7a6ef9505f3322babca5e768d9c8691
3,377
cpp
C++
src/PBN.cpp
lanctot/dds
06c1b31795ca2db2f268ea81a1029b03c8c37872
[ "Apache-2.0" ]
93
2015-01-23T01:56:02.000Z
2022-02-21T22:56:41.000Z
src/PBN.cpp
lanctot/dds
06c1b31795ca2db2f268ea81a1029b03c8c37872
[ "Apache-2.0" ]
57
2015-01-15T15:01:01.000Z
2021-06-25T08:36:19.000Z
src/PBN.cpp
online-bridge-hackathon/libdds
19db9cf99bee85074884f628cdd5a5faf79bc766
[ "Apache-2.0" ]
76
2015-04-11T10:22:47.000Z
2022-03-29T09:51:03.000Z
/* DDS, a bridge double dummy solver. Copyright (C) 2006-2014 by Bo Haglund / 2014-2018 by Bo Haglund & Soren Hein. See LICENSE and README. */ #include "dds.h" #include "PBN.h" int IsCard(const char cardChar); int ConvertFromPBN( char const * dealBuff, unsigned int remainCards[DDS_HANDS][DDS_SUITS]) { for (int h = 0; h < DDS_HANDS; h++) for (int s = 0; s < DDS_SUITS; s++) remainCards[h][s] = 0; int bp = 0; while (((dealBuff[bp] != 'W') && (dealBuff[bp] != 'N') && (dealBuff[bp] != 'E') && (dealBuff[bp] != 'S') && (dealBuff[bp] != 'w') && (dealBuff[bp] != 'n') && (dealBuff[bp] != 'e') && (dealBuff[bp] != 's')) && (bp < 3)) bp++; if (bp >= 3) return 0; int first; if ((dealBuff[bp] == 'N') || (dealBuff[bp] == 'n')) first = 0; else if ((dealBuff[bp] == 'E') || (dealBuff[bp] == 'e')) first = 1; else if ((dealBuff[bp] == 'S') || (dealBuff[bp] == 's')) first = 2; else first = 3; bp++; bp++; int handRelFirst = 0; int suitInHand = 0; int card, hand; while ((bp < 80) && (dealBuff[bp] != '\0')) { card = IsCard(dealBuff[bp]); if (card) { switch (first) { case 0: hand = handRelFirst; break; case 1: if (handRelFirst == 0) hand = 1; else if (handRelFirst == 3) hand = 0; else hand = handRelFirst + 1; break; case 2: if (handRelFirst == 0) hand = 2; else if (handRelFirst == 1) hand = 3; else hand = handRelFirst - 2; break; default: if (handRelFirst == 0) hand = 3; else hand = handRelFirst - 1; } remainCards[hand][suitInHand] |= static_cast<unsigned>((bitMapRank[card] << 2)); } else if (dealBuff[bp] == '.') suitInHand++; else if (dealBuff[bp] == ' ') { handRelFirst++; suitInHand = 0; } bp++; } return RETURN_NO_FAULT; } int IsCard(const char cardChar) { switch (cardChar) { case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'T': case 't': return 10; case 'J': case 'j': return 11; case 'Q': case 'q': return 12; case 'K': case 'k': return 13; case 'A': case 'a': return 14; default: return 0; } } int ConvertPlayFromPBN( const playTracePBN& playPBN, playTraceBin& playBin) { const int n = playPBN.number; if (n < 0 || n > 52) return RETURN_PLAY_FAULT; playBin.number = n; for (int i = 0; i < 2 * n; i += 2) { char suit = playPBN.cards[i]; int s; if (suit == 's' || suit == 'S') s = 0; else if (suit == 'h' || suit == 'H') s = 1; else if (suit == 'd' || suit == 'D') s = 2; else if (suit == 'c' || suit == 'C') s = 3; else return RETURN_PLAY_FAULT; playBin.suit[i >> 1] = s; int rank = IsCard(playPBN.cards[i+1]); if (rank == 0) return RETURN_PLAY_FAULT; playBin.rank[i >> 1] = rank; } return RETURN_NO_FAULT; }
18.761111
70
0.472017
lanctot
3a6b6c6d2c0446026e2c2790687e55e92977cdb7
25,928
cc
C++
src/clustering/administration/auth/permissions_artificial_table_backend.cc
zadcha/rethinkdb
bb4f5cc28242dc1e29e9a46a8a931ec54420070c
[ "Apache-2.0" ]
21,684
2015-01-01T03:42:20.000Z
2022-03-30T13:32:44.000Z
src/clustering/administration/auth/permissions_artificial_table_backend.cc
RethonkDB/rethonkdb
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
[ "Apache-2.0" ]
4,067
2015-01-01T00:04:51.000Z
2022-03-30T13:42:56.000Z
src/clustering/administration/auth/permissions_artificial_table_backend.cc
RethonkDB/rethonkdb
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
[ "Apache-2.0" ]
1,901
2015-01-01T21:05:59.000Z
2022-03-21T08:14:25.000Z
// iopyright 2010-2015 RethinkDB, all rights reserved. #include "clustering/administration/auth/permissions_artificial_table_backend.hpp" #include "errors.hpp" #include <boost/algorithm/string/join.hpp> #include "clustering/administration/artificial_reql_cluster_interface.hpp" #include "clustering/administration/auth/username.hpp" #include "clustering/administration/datum_adapter.hpp" #include "clustering/administration/tables/name_resolver.hpp" namespace auth { permissions_artificial_table_backend_t::permissions_artificial_table_backend_t( rdb_context_t *rdb_context, lifetime_t<name_resolver_t const &> name_resolver, std::shared_ptr<semilattice_readwrite_view_t<auth_semilattice_metadata_t>> auth_semilattice_view, std::shared_ptr<semilattice_read_view_t<cluster_semilattice_metadata_t>> cluster_semilattice_view, admin_identifier_format_t identifier_format) : base_artificial_table_backend_t( name_string_t::guarantee_valid("permissions"), rdb_context, name_resolver, auth_semilattice_view, cluster_semilattice_view), m_name_resolver(name_resolver), m_identifier_format(identifier_format) { } bool permissions_artificial_table_backend_t::read_all_rows_as_vector( UNUSED auth::user_context_t const &user_context, UNUSED signal_t *interruptor, std::vector<ql::datum_t> *rows_out, UNUSED admin_err_t *error_out) { rows_out->clear(); on_thread_t on_thread(home_thread()); cluster_semilattice_metadata_t cluster_metadata = m_name_resolver.get_cluster_metadata(); // The "admin" user is faked here { ql::datum_t row; if (global_to_datum( username_t("admin"), permissions_t(tribool::True, tribool::True, tribool::True, tribool::True), &row)) { rows_out->push_back(std::move(row)); } } { ql::datum_t row; if (database_to_datum( username_t("admin"), artificial_reql_cluster_interface_t::database_id, permissions_t(tribool::True, tribool::True, tribool::True), cluster_metadata, &row)) { rows_out->push_back(std::move(row)); } } auth_semilattice_metadata_t auth_metadata = m_auth_semilattice_view->get(); for (auto const &user : auth_metadata.m_users) { if (user.first.is_admin() || !static_cast<bool>(user.second.get_ref())) { // The "admin" user is faked above and not displayed from the metadata. continue; } ql::datum_t username = convert_string_to_datum(user.first.to_string()); { ql::datum_t row; if (global_to_datum( user.first, user.second.get_ref()->get_global_permissions(), &row)) { rows_out->push_back(std::move(row)); } } for (auto const &database : user.second.get_ref()->get_database_permissions()) { ql::datum_t row; if (database_to_datum( user.first, database.first, database.second, cluster_metadata, &row)) { rows_out->push_back(std::move(row)); } } for (auto const &table : user.second.get_ref()->get_table_permissions()) { // `table_to_datum` will look up the database ql::datum_t row; if (table_to_datum( user.first, r_nullopt, table.first, table.second, cluster_metadata, &row)) { rows_out->push_back(std::move(row)); } } } return true; } bool permissions_artificial_table_backend_t::read_row( UNUSED auth::user_context_t const &user_context, ql::datum_t primary_key, UNUSED signal_t *interruptor, ql::datum_t *row_out, UNUSED admin_err_t *error_out) { *row_out = ql::datum_t(); on_thread_t on_thread(home_thread()); cluster_semilattice_metadata_t cluster_metadata = m_name_resolver.get_cluster_metadata(); username_t username; database_id_t database_id; namespace_id_t table_id; uint8_t array_size = parse_primary_key( primary_key, cluster_metadata, &username, &database_id, &table_id); if (array_size == 0) { return true; } if (username.is_admin()) { switch (array_size) { case 1: global_to_datum( username, permissions_t(tribool::True, tribool::True, tribool::True, tribool::True), row_out); break; case 2: if (database_id == artificial_reql_cluster_interface_t::database_id) { database_to_datum( username, database_id, permissions_t(tribool::True, tribool::True, tribool::True), cluster_metadata, row_out); } break; } return true; } auth_semilattice_metadata_t auth_metadata = m_auth_semilattice_view->get(); auto user = auth_metadata.m_users.find(username); if (user == auth_metadata.m_users.end() || !static_cast<bool>(user->second.get_ref())) { return true; } // Note these functions will only set `row_out` on success. switch (array_size) { case 1: global_to_datum( username, user->second.get_ref()->get_global_permissions(), row_out); break; case 2: database_to_datum( username, database_id, user->second.get_ref()->get_database_permissions(database_id), cluster_metadata, row_out); break; case 3: table_to_datum( username, make_optional(database_id), table_id, user->second.get_ref()->get_table_permissions(table_id), cluster_metadata, row_out); break; } return true; } bool permissions_artificial_table_backend_t::write_row( UNUSED auth::user_context_t const &user_context, ql::datum_t primary_key, bool pkey_was_autogenerated, ql::datum_t *new_value_inout, UNUSED signal_t *interruptor, admin_err_t *error_out) { on_thread_t on_thread(home_thread()); if (pkey_was_autogenerated) { *error_out = admin_err_t{ "You must specify a primary key.", query_state_t::FAILED}; return false; } cluster_semilattice_metadata_t cluster_metadata = m_cluster_semilattice_view->get(); username_t username_primary; database_id_t database_id_primary; namespace_id_t table_id_primary; uint8_t array_size = parse_primary_key( primary_key, cluster_metadata, &username_primary, &database_id_primary, &table_id_primary, error_out); if (array_size == 0) { return false; } if (username_primary.is_admin()) { *error_out = admin_err_t{ "The permissions of the user `" + username_primary.to_string() + "` can't be modified.", query_state_t::FAILED}; return false; } auth_semilattice_metadata_t auth_metadata = m_auth_semilattice_view->get(); auto user = auth_metadata.m_users.find(username_primary); if (user == auth_metadata.m_users.end() || !static_cast<bool>(user->second.get_ref())) { *error_out = admin_err_t{ "No user named `" + username_primary.to_string() + "`.", query_state_t::FAILED}; return false; } if (new_value_inout->has()) { std::set<std::string> keys; for (size_t i = 0; i < new_value_inout->obj_size(); ++i) { keys.insert(new_value_inout->get_pair(i).first.to_std()); } keys.erase("id"); ql::datum_t username = new_value_inout->get_field("user", ql::NOTHROW); if (username.has()) { keys.erase("user"); if (username_t(username.as_str().to_std()) != username_primary) { *error_out = admin_err_t{ "The key `user` does not match the primary key.", query_state_t::FAILED}; return false; } } if (array_size > 1) { ql::datum_t database = new_value_inout->get_field("database", ql::NOTHROW); if (database.has()) { keys.erase("database"); switch (m_identifier_format) { case admin_identifier_format_t::name: { name_string_t database_name; if (!convert_name_from_datum( database, "database name", &database_name, error_out)) { return false; } if (m_name_resolver.database_id_to_name( database_id_primary, cluster_metadata ).get() != database_name) { *error_out = admin_err_t{ "The key `database` does not match the primary key.", query_state_t::FAILED}; return false; } } break; case admin_identifier_format_t::uuid: { database_id_t database_id_secondary; if (!convert_uuid_from_datum( database, &database_id_secondary, error_out)) { return false; } if (database_id_primary != database_id_secondary) { *error_out = admin_err_t{ "The key `database` does not match the primary key.", query_state_t::FAILED}; return false; } } break; } } } if (array_size > 2) { ql::datum_t table = new_value_inout->get_field("table", ql::NOTHROW); if (table.has()) { keys.erase("table"); switch (m_identifier_format) { case admin_identifier_format_t::name: { name_string_t table_name; if (!convert_name_from_datum( table, "table name", &table_name, error_out)) { return false; } optional<table_basic_config_t> table_basic_config = m_name_resolver.table_id_to_basic_config( table_id_primary, make_optional(database_id_primary)); if (!static_cast<bool>(table_basic_config) || table_basic_config->name != table_name) { *error_out = admin_err_t{ "The key `table` does not match the primary key.", query_state_t::FAILED}; return false; } } break; case admin_identifier_format_t::uuid: { namespace_id_t table_id_secondary; if (!convert_uuid_from_datum( table, &table_id_secondary, error_out)) { return false; } if (table_id_primary != table_id_secondary) { *error_out = admin_err_t{ "The key `table` does not match the primary key.", query_state_t::FAILED}; return false; } } break; } } } bool is_indeterminate = false; ql::datum_t permissions = new_value_inout->get_field("permissions", ql::NOTHROW); if (permissions.has()) { keys.erase("permissions"); try { switch (array_size) { case 1: user->second.apply_write( [&](optional<auth::user_t> *inner_user) { auto &permissions_ref = inner_user->get().get_global_permissions(); permissions_ref.merge(permissions); is_indeterminate = permissions_ref.is_indeterminate(); }); break; case 2: user->second.apply_write( [&](optional<auth::user_t> *inner_user) { auto &permissions_ref = inner_user->get().get_database_permissions( database_id_primary); permissions_ref.merge(permissions); is_indeterminate = permissions_ref.is_indeterminate(); }); break; case 3: user->second.apply_write( [&](optional<auth::user_t> *inner_user) { auto &permissions_ref = inner_user->get().get_table_permissions( table_id_primary); permissions_ref.merge(permissions); is_indeterminate = permissions_ref.is_indeterminate(); }); break; } } catch (admin_op_exc_t const &admin_op_exc) { *error_out = admin_op_exc.to_admin_err(); return false; } } else { *error_out = admin_err_t{ "Expected a field `permissions`.", query_state_t::FAILED}; return false; } if (!keys.empty()) { *error_out = admin_err_t{ "Unexpected key(s) `" + boost::algorithm::join(keys, "`, `") + "`.", query_state_t::FAILED}; return false; } // Updating the permissions to indeterminate is considered equal to a deletion if (is_indeterminate) { *new_value_inout = ql::datum_t(); } } else { switch (array_size) { case 1: user->second.apply_write([](optional<auth::user_t> *inner_user) { inner_user->get().set_global_permissions( permissions_t( tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate)); }); break; case 2: user->second.apply_write([&](optional<auth::user_t> *inner_user) { inner_user->get().set_database_permissions( database_id_primary, permissions_t( tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate)); }); break; case 3: user->second.apply_write([&](optional<auth::user_t> *inner_user) { inner_user->get().set_table_permissions( table_id_primary, permissions_t( tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate)); }); break; } } m_auth_semilattice_view->join(auth_metadata); return true; } uint8_t permissions_artificial_table_backend_t::parse_primary_key( ql::datum_t const &primary_key, cluster_semilattice_metadata_t const &cluster_metadata, username_t *username_out, database_id_t *database_id_out, namespace_id_t *table_id_out, admin_err_t *admin_err_out) { if (primary_key.get_type() != ql::datum_t::R_ARRAY || primary_key.arr_size() < 1 || primary_key.arr_size() > 3) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected an array of one to three items in the primary key, got " + primary_key.print() + ".", query_state_t::FAILED}; } return 0; } ql::datum_t username = primary_key.get(0, ql::NOTHROW); if (username.get_type() != ql::datum_t::R_STR) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected a string as the username, got " + username.print() + ".", query_state_t::FAILED}; } return 0; } *username_out = username_t(username.as_str().to_std()); if (primary_key.arr_size() > 1) { ql::datum_t database = primary_key.get(1, ql::NOTHROW); if (database.get_type() != ql::datum_t::R_STR || !str_to_uuid(database.as_str().to_std(), database_id_out)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected a UUID as the database, got " + database.print() + ".", query_state_t::FAILED}; } return 0; } optional<name_string_t> database_name = m_name_resolver.database_id_to_name(*database_id_out, cluster_metadata); if (!static_cast<bool>(database_name)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ strprintf( "No database with UUID `%s` exists.", uuid_to_str(*database_id_out).c_str()), query_state_t::FAILED}; } return 0; } } if (primary_key.arr_size() > 2) { ql::datum_t table = primary_key.get(2, ql::NOTHROW); if (table.get_type() != ql::datum_t::R_STR || !str_to_uuid(table.as_str().to_std(), table_id_out)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected a UUID as the table, got " + table.print() + ".", query_state_t::FAILED}; } return 0; } optional<table_basic_config_t> table_basic_config = m_name_resolver.table_id_to_basic_config(*table_id_out); if (!static_cast<bool>(table_basic_config)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ strprintf( "No table with UUID `%s` exists.", uuid_to_str(*table_id_out).c_str()), query_state_t::FAILED}; } return 0; } if (table_basic_config->database != *database_id_out) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ strprintf( "No table with UUID `%s` exists.", uuid_to_str(*table_id_out).c_str()), query_state_t::FAILED}; } return 0; } } return primary_key.arr_size(); } bool permissions_artificial_table_backend_t::global_to_datum( username_t const &username, permissions_t const &permissions, ql::datum_t *datum_out) { ql::datum_t permissions_datum = permissions.to_datum(); if (permissions_datum.get_type() != ql::datum_t::R_NULL) { ql::datum_object_builder_t builder; ql::datum_array_builder_t id_builder(ql::configured_limits_t::unlimited); id_builder.add(convert_string_to_datum(username.to_string())); builder.overwrite("id", std::move(id_builder).to_datum()); builder.overwrite("permissions", std::move(permissions_datum)); builder.overwrite("user", convert_string_to_datum(username.to_string())); *datum_out = std::move(builder).to_datum(); return true; } return false; } bool permissions_artificial_table_backend_t::database_to_datum( username_t const &username, database_id_t const &database_id, permissions_t const &permissions, cluster_semilattice_metadata_t const &cluster_metadata, ql::datum_t *datum_out) { ql::datum_t permissions_datum = permissions.to_datum(); if (permissions_datum.get_type() != ql::datum_t::R_NULL) { ql::datum_object_builder_t builder; ql::datum_array_builder_t id_builder(ql::configured_limits_t::unlimited); id_builder.add(convert_string_to_datum(username.to_string())); id_builder.add(convert_uuid_to_datum(database_id)); ql::datum_t database_name_or_uuid; switch (m_identifier_format) { case admin_identifier_format_t::name: { optional<name_string_t> database_name = m_name_resolver.database_id_to_name( database_id, cluster_metadata); database_name_or_uuid = ql::datum_t(database_name.value_or( name_string_t::guarantee_valid("__deleted_database__")).str()); } break; case admin_identifier_format_t::uuid: database_name_or_uuid = ql::datum_t(uuid_to_str(database_id)); break; } builder.overwrite("database", std::move(database_name_or_uuid)); builder.overwrite("id", std::move(id_builder).to_datum()); builder.overwrite("permissions", std::move(permissions_datum)); builder.overwrite("user", convert_string_to_datum(username.to_string())); *datum_out = std::move(builder).to_datum(); return true; } return false; } bool permissions_artificial_table_backend_t::table_to_datum( username_t const &username, optional<database_id_t> const &database_id, namespace_id_t const &table_id, permissions_t const &permissions, cluster_semilattice_metadata_t const &cluster_metadata, ql::datum_t *datum_out) { optional<table_basic_config_t> table_basic_config = m_name_resolver.table_id_to_basic_config(table_id, database_id); if (!static_cast<bool>(table_basic_config)) { return false; } ql::datum_t permissions_datum = permissions.to_datum(); if (permissions_datum.get_type() != ql::datum_t::R_NULL) { ql::datum_object_builder_t builder; ql::datum_array_builder_t id_builder(ql::configured_limits_t::unlimited); id_builder.add(convert_string_to_datum(username.to_string())); id_builder.add(convert_uuid_to_datum(table_basic_config->database)); id_builder.add(convert_uuid_to_datum(table_id)); ql::datum_t database_name_or_uuid; ql::datum_t table_name_or_uuid; switch (m_identifier_format) { case admin_identifier_format_t::name: { optional<name_string_t> database_name = m_name_resolver.database_id_to_name( table_basic_config->database, cluster_metadata); database_name_or_uuid = ql::datum_t(database_name.value_or( name_string_t::guarantee_valid("__deleted_database__")).str()); table_name_or_uuid = ql::datum_t(table_basic_config->name.str()); } break; case admin_identifier_format_t::uuid: database_name_or_uuid = ql::datum_t(uuid_to_str(table_basic_config->database)); table_name_or_uuid = ql::datum_t(uuid_to_str(table_id)); break; } builder.overwrite("database", std::move(database_name_or_uuid)); builder.overwrite("id", std::move(id_builder).to_datum()); builder.overwrite("permissions", std::move(permissions_datum)); builder.overwrite("table", std::move(table_name_or_uuid)); builder.overwrite("user", convert_string_to_datum(username.to_string())); *datum_out = std::move(builder).to_datum(); return true; } return false; } } // namespace auth
38.073421
94
0.523295
zadcha
3a6c3309915e86f8f0e6a5f15317d7c7aea24d23
3,336
cpp
C++
src/logger_asynchronous.cpp
babidev/logging
f53db4cbdd5ed831dad0b673752d4bef7629eb98
[ "BSD-3-Clause" ]
null
null
null
src/logger_asynchronous.cpp
babidev/logging
f53db4cbdd5ed831dad0b673752d4bef7629eb98
[ "BSD-3-Clause" ]
null
null
null
src/logger_asynchronous.cpp
babidev/logging
f53db4cbdd5ed831dad0b673752d4bef7629eb98
[ "BSD-3-Clause" ]
null
null
null
#include "logging/logger_asynchronous.h" #include <chrono> #include "logging/manager.h" namespace logging { logger_asynchronous::logger_asynchronous() : state_{static_cast<unsigned>(state::off)} { start(); } logger_asynchronous::~logger_asynchronous() { stop(); } void logger_asynchronous::start() { unsigned state = state_.load(std::memory_order_acquire); if (state == static_cast<unsigned>(state::working) || state == static_cast<unsigned>(state::starting)) { return; } while (state == static_cast<unsigned>(state::stopping)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); state = state_.load(std::memory_order_acquire); } if (state == static_cast<unsigned>(state::off)) { if (state_.compare_exchange_strong( state, static_cast<unsigned>(state::starting), std::memory_order_release, std::memory_order_relaxed)) { worker_ = std::move(std::thread{[this](){ work(); }}); while(state_.load(std::memory_order_acquire) != static_cast<unsigned>(state::working)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); } } } } void logger_asynchronous::stop() { unsigned state = state_.load(std::memory_order_acquire); if (state == static_cast<unsigned>(state::off) || state == static_cast<unsigned>(state::stopping)) { return; } while (state == static_cast<unsigned>(state::starting)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); state = state_.load(std::memory_order_acquire); } if (state == static_cast<unsigned>(state::working)) { if (state_.compare_exchange_strong( state, static_cast<unsigned>(state::stopping), std::memory_order_release, std::memory_order_relaxed)) { write_condition_.notify_one(); while(state_.load(std::memory_order_acquire) != static_cast<unsigned>(state::off)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); } if (worker_.joinable()) { worker_.join(); } } } } void logger_asynchronous::dispatch(const logging::record& record) { auto state = state_.load(std::memory_order_acquire); if (state == static_cast<unsigned>(state::off) || state == static_cast<unsigned>(state::stopping)) { return; } { std::unique_lock<std::mutex> lock(mutex_); records_.emplace(record); } write_condition_.notify_one(); } void logger_asynchronous::work() { state_.store(static_cast<unsigned>(state::working), std::memory_order_release); bool is_records_queue_empty{true}; while(state_.load(std::memory_order_acquire) != static_cast<unsigned>(state::stopping) || is_records_queue_empty == false) { std::queue<logging::record> buffer; std::unique_lock<std::mutex> lock(mutex_); if (records_.empty()) { write_condition_.wait(lock); } std::swap(records_, buffer); lock.unlock(); while(!buffer.empty()) { auto item = buffer.front(); if (auto sink{manager::instance().find_sink(item.sink_name)}) { if (sink->check_level(item.level)) { sink->write(item); } } buffer.pop(); } lock.lock(); is_records_queue_empty = records_.empty(); } state_.store(static_cast<unsigned>(state::off), std::memory_order_release); } }
29.263158
81
0.66247
babidev
3a6f1f3377a6124cde08d55a6491c55741a1e3ee
45,547
cpp
C++
Source/JavaScriptCore/runtime/ObjectConstructor.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/JavaScriptCore/runtime/ObjectConstructor.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/JavaScriptCore/runtime/ObjectConstructor.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) * Copyright (C) 2008-2019 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "config.h" #include "ObjectConstructor.h" #include "BuiltinNames.h" #include "JSArray.h" #include "JSCInlines.h" #include "JSImmutableButterfly.h" #include "PropertyDescriptor.h" #include "PropertyNameArray.h" #include "Symbol.h" namespace JSC { EncodedJSValue JSC_HOST_CALL objectConstructorAssign(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorValues(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorGetPrototypeOf(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorSetPrototypeOf(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyNames(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperty(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperties(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorCreate(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorSeal(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorFreeze(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorPreventExtensions(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorIsSealed(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorIsFrozen(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorIsExtensible(JSGlobalObject*, CallFrame*); } #include "ObjectConstructor.lut.h" namespace JSC { STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(ObjectConstructor); const ClassInfo ObjectConstructor::s_info = { "Function", &InternalFunction::s_info, &objectConstructorTable, nullptr, CREATE_METHOD_TABLE(ObjectConstructor) }; /* Source for ObjectConstructor.lut.h @begin objectConstructorTable getPrototypeOf objectConstructorGetPrototypeOf DontEnum|Function 1 ObjectGetPrototypeOfIntrinsic setPrototypeOf objectConstructorSetPrototypeOf DontEnum|Function 2 getOwnPropertyDescriptor objectConstructorGetOwnPropertyDescriptor DontEnum|Function 2 getOwnPropertyDescriptors objectConstructorGetOwnPropertyDescriptors DontEnum|Function 1 getOwnPropertyNames objectConstructorGetOwnPropertyNames DontEnum|Function 1 getOwnPropertySymbols objectConstructorGetOwnPropertySymbols DontEnum|Function 1 keys objectConstructorKeys DontEnum|Function 1 ObjectKeysIntrinsic defineProperty objectConstructorDefineProperty DontEnum|Function 3 defineProperties objectConstructorDefineProperties DontEnum|Function 2 create objectConstructorCreate DontEnum|Function 2 ObjectCreateIntrinsic seal objectConstructorSeal DontEnum|Function 1 freeze objectConstructorFreeze DontEnum|Function 1 preventExtensions objectConstructorPreventExtensions DontEnum|Function 1 isSealed objectConstructorIsSealed DontEnum|Function 1 isFrozen objectConstructorIsFrozen DontEnum|Function 1 isExtensible objectConstructorIsExtensible DontEnum|Function 1 is objectConstructorIs DontEnum|Function 2 ObjectIsIntrinsic assign objectConstructorAssign DontEnum|Function 2 values objectConstructorValues DontEnum|Function 1 entries JSBuiltin DontEnum|Function 1 fromEntries JSBuiltin DontEnum|Function 1 @end */ static EncodedJSValue JSC_HOST_CALL callObjectConstructor(JSGlobalObject*, CallFrame*); static EncodedJSValue JSC_HOST_CALL constructWithObjectConstructor(JSGlobalObject*, CallFrame*); ObjectConstructor::ObjectConstructor(VM& vm, Structure* structure) : InternalFunction(vm, structure, callObjectConstructor, constructWithObjectConstructor) { } void ObjectConstructor::finishCreation(VM& vm, JSGlobalObject* globalObject, ObjectPrototype* objectPrototype) { Base::finishCreation(vm, vm.propertyNames->Object.string(), NameAdditionMode::WithoutStructureTransition); putDirectWithoutTransition(vm, vm.propertyNames->prototype, objectPrototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().createPrivateName(), objectConstructorCreate, static_cast<unsigned>(PropertyAttribute::DontEnum), 2); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().definePropertyPrivateName(), objectConstructorDefineProperty, static_cast<unsigned>(PropertyAttribute::DontEnum), 3); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().getPrototypeOfPrivateName(), objectConstructorGetPrototypeOf, static_cast<unsigned>(PropertyAttribute::DontEnum), 1); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().getOwnPropertyNamesPrivateName(), objectConstructorGetOwnPropertyNames, static_cast<unsigned>(PropertyAttribute::DontEnum), 1); } // ES 19.1.1.1 Object([value]) static ALWAYS_INLINE JSObject* constructObjectWithNewTarget(JSGlobalObject* globalObject, CallFrame* callFrame, JSValue newTarget) { VM& vm = globalObject->vm(); ObjectConstructor* objectConstructor = jsCast<ObjectConstructor*>(callFrame->jsCallee()); auto scope = DECLARE_THROW_SCOPE(vm); // We need to check newTarget condition in this caller side instead of InternalFunction::createSubclassStructure side. // Since if we found this condition is met, we should not fall into the type conversion in the step 3. // 1. If NewTarget is neither undefined nor the active function, then if (newTarget && newTarget != objectConstructor) { // a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%ObjectPrototype%"). Structure* baseStructure = getFunctionRealm(vm, asObject(newTarget))->objectStructureForObjectConstructor(); Structure* objectStructure = InternalFunction::createSubclassStructure(globalObject, asObject(newTarget), baseStructure); RETURN_IF_EXCEPTION(scope, nullptr); return constructEmptyObject(vm, objectStructure); } // 2. If value is null, undefined or not supplied, return ObjectCreate(%ObjectPrototype%). JSValue argument = callFrame->argument(0); if (argument.isUndefinedOrNull()) return constructEmptyObject(vm, globalObject->objectStructureForObjectConstructor()); // 3. Return ToObject(value). RELEASE_AND_RETURN(scope, argument.toObject(globalObject)); } static EncodedJSValue JSC_HOST_CALL constructWithObjectConstructor(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(constructObjectWithNewTarget(globalObject, callFrame, callFrame->newTarget())); } static EncodedJSValue JSC_HOST_CALL callObjectConstructor(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(constructObjectWithNewTarget(globalObject, callFrame, JSValue())); } EncodedJSValue JSC_HOST_CALL objectConstructorGetPrototypeOf(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(callFrame->argument(0).getPrototype(globalObject)); } EncodedJSValue JSC_HOST_CALL objectConstructorSetPrototypeOf(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue objectValue = callFrame->argument(0); if (objectValue.isUndefinedOrNull()) return throwVMTypeError(globalObject, scope, "Cannot set prototype of undefined or null"_s); JSValue protoValue = callFrame->argument(1); if (!protoValue.isObject() && !protoValue.isNull()) return throwVMTypeError(globalObject, scope, "Prototype value can only be an object or null"_s); JSObject* object = objectValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); bool shouldThrowIfCantSet = true; bool didSetPrototype = object->setPrototype(vm, globalObject, protoValue, shouldThrowIfCantSet); EXCEPTION_ASSERT_UNUSED(didSetPrototype, scope.exception() || didSetPrototype); return JSValue::encode(objectValue); } JSValue objectConstructorGetOwnPropertyDescriptor(JSGlobalObject* globalObject, JSObject* object, const Identifier& propertyName) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyDescriptor descriptor; if (!object->getOwnPropertyDescriptor(globalObject, propertyName, descriptor)) RELEASE_AND_RETURN(scope, jsUndefined()); RETURN_IF_EXCEPTION(scope, { }); JSObject* result = constructObjectFromPropertyDescriptor(globalObject, descriptor); scope.assertNoException(); ASSERT(result); return result; } JSValue objectConstructorGetOwnPropertyDescriptors(JSGlobalObject* globalObject, JSObject* object) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyNameArray properties(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); JSObject* descriptors = constructEmptyObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); for (auto& propertyName : properties) { PropertyDescriptor descriptor; bool didGetDescriptor = object->getOwnPropertyDescriptor(globalObject, propertyName, descriptor); RETURN_IF_EXCEPTION(scope, { }); if (!didGetDescriptor) continue; JSObject* fromDescriptor = constructObjectFromPropertyDescriptor(globalObject, descriptor); scope.assertNoException(); ASSERT(fromDescriptor); PutPropertySlot slot(descriptors); descriptors->putOwnDataPropertyMayBeIndex(globalObject, propertyName, fromDescriptor, slot); scope.assertNoException(); } return descriptors; } EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyDescriptor(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); auto propertyName = callFrame->argument(1).toPropertyKey(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(objectConstructorGetOwnPropertyDescriptor(globalObject, object, propertyName))); } EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyDescriptors(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(objectConstructorGetOwnPropertyDescriptors(globalObject, object))); } // FIXME: Use the enumeration cache. EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyNames(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(ownPropertyKeys(globalObject, object, PropertyNameMode::Strings, DontEnumPropertiesMode::Include))); } // FIXME: Use the enumeration cache. EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertySymbols(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(ownPropertyKeys(globalObject, object, PropertyNameMode::Symbols, DontEnumPropertiesMode::Include))); } EncodedJSValue JSC_HOST_CALL objectConstructorKeys(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(ownPropertyKeys(globalObject, object, PropertyNameMode::Strings, DontEnumPropertiesMode::Exclude))); } EncodedJSValue JSC_HOST_CALL objectConstructorAssign(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue targetValue = callFrame->argument(0); if (targetValue.isUndefinedOrNull()) return throwVMTypeError(globalObject, scope, "Object.assign requires that input parameter not be null or undefined"_s); JSObject* target = targetValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); // FIXME: Extend this for non JSFinalObject. For example, we would like to use this fast path for function objects too. // https://bugs.webkit.org/show_bug.cgi?id=185358 bool targetCanPerformFastPut = jsDynamicCast<JSFinalObject*>(vm, target) && target->canPerformFastPutInlineExcludingProto(vm); Vector<RefPtr<UniquedStringImpl>, 8> properties; MarkedArgumentBuffer values; unsigned argsCount = callFrame->argumentCount(); for (unsigned i = 1; i < argsCount; ++i) { JSValue sourceValue = callFrame->uncheckedArgument(i); if (sourceValue.isUndefinedOrNull()) continue; JSObject* source = sourceValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); if (targetCanPerformFastPut) { if (!source->staticPropertiesReified(vm)) { source->reifyAllStaticProperties(globalObject); RETURN_IF_EXCEPTION(scope, { }); } auto canPerformFastPropertyEnumerationForObjectAssign = [] (Structure* structure) { if (structure->typeInfo().overridesGetOwnPropertySlot()) return false; if (structure->typeInfo().overridesAnyFormOfGetPropertyNames()) return false; // FIXME: Indexed properties can be handled. // https://bugs.webkit.org/show_bug.cgi?id=185358 if (hasIndexedProperties(structure->indexingType())) return false; if (structure->hasGetterSetterProperties()) return false; if (structure->hasReadOnlyOrGetterSetterPropertiesExcludingProto()) return false; if (structure->hasCustomGetterSetterProperties()) return false; if (structure->isUncacheableDictionary()) return false; // Cannot perform fast [[Put]] to |target| if the property names of the |source| contain "__proto__". if (structure->hasUnderscoreProtoPropertyExcludingOriginalProto()) return false; return true; }; if (canPerformFastPropertyEnumerationForObjectAssign(source->structure(vm))) { // |source| Structure does not have any getters. And target can perform fast put. // So enumerating properties and putting properties are non observable. // FIXME: It doesn't seem like we should have to do this in two phases, but // we're running into crashes where it appears that source is transitioning // under us, and even ends up in a state where it has a null butterfly. My // leading hypothesis here is that we fire some value replacement watchpoint // that ends up transitioning the structure underneath us. // https://bugs.webkit.org/show_bug.cgi?id=187837 // Do not clear since Vector::clear shrinks the backing store. properties.resize(0); values.clear(); source->structure(vm)->forEachProperty(vm, [&] (const PropertyMapEntry& entry) -> bool { if (entry.attributes & PropertyAttribute::DontEnum) return true; PropertyName propertyName(entry.key); if (propertyName.isPrivateName()) return true; properties.append(entry.key); values.appendWithCrashOnOverflow(source->getDirect(entry.offset)); return true; }); for (size_t i = 0; i < properties.size(); ++i) { // FIXME: We could put properties in a batching manner to accelerate Object.assign more. // https://bugs.webkit.org/show_bug.cgi?id=185358 PutPropertySlot putPropertySlot(target, true); target->putOwnDataProperty(vm, properties[i].get(), values.at(i), putPropertySlot); } continue; } } // [[GetOwnPropertyNames]], [[Get]] etc. could modify target object and invalidate this assumption. // For example, [[Get]] of source object could configure setter to target object. So disable the fast path. targetCanPerformFastPut = false; PropertyNameArray properties(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); source->methodTable(vm)->getOwnPropertyNames(source, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); auto assign = [&] (PropertyName propertyName) { PropertySlot slot(source, PropertySlot::InternalMethodType::GetOwnProperty); bool hasProperty = source->methodTable(vm)->getOwnPropertySlot(source, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, void()); if (!hasProperty) return; if (slot.attributes() & PropertyAttribute::DontEnum) return; JSValue value; if (LIKELY(!slot.isTaintedByOpaqueObject())) value = slot.getValue(globalObject, propertyName); else value = source->get(globalObject, propertyName); RETURN_IF_EXCEPTION(scope, void()); PutPropertySlot putPropertySlot(target, true); target->putInline(globalObject, propertyName, value, putPropertySlot); }; // First loop is for strings. Second loop is for symbols to keep standardized order requirement in the spec. // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys bool foundSymbol = false; unsigned numProperties = properties.size(); for (unsigned j = 0; j < numProperties; j++) { const auto& propertyName = properties[j]; if (propertyName.isSymbol()) { foundSymbol = true; continue; } assign(propertyName); RETURN_IF_EXCEPTION(scope, { }); } if (foundSymbol) { for (unsigned j = 0; j < numProperties; j++) { const auto& propertyName = properties[j]; if (propertyName.isSymbol()) { ASSERT(!propertyName.isPrivateName()); assign(propertyName); RETURN_IF_EXCEPTION(scope, { }); } } } } return JSValue::encode(target); } EncodedJSValue JSC_HOST_CALL objectConstructorValues(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue targetValue = callFrame->argument(0); if (targetValue.isUndefinedOrNull()) return throwVMTypeError(globalObject, scope, "Object.values requires that input parameter not be null or undefined"_s); JSObject* target = targetValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); JSArray* values = constructEmptyArray(globalObject, nullptr); RETURN_IF_EXCEPTION(scope, { }); PropertyNameArray properties(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude); target->methodTable(vm)->getOwnPropertyNames(target, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); unsigned index = 0; auto addValue = [&] (PropertyName propertyName) { PropertySlot slot(target, PropertySlot::InternalMethodType::GetOwnProperty); bool hasProperty = target->methodTable(vm)->getOwnPropertySlot(target, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, void()); if (!hasProperty) return; if (slot.attributes() & PropertyAttribute::DontEnum) return; JSValue value; if (LIKELY(!slot.isTaintedByOpaqueObject())) value = slot.getValue(globalObject, propertyName); else value = target->get(globalObject, propertyName); RETURN_IF_EXCEPTION(scope, void()); values->putDirectIndex(globalObject, index++, value); }; for (unsigned i = 0, numProperties = properties.size(); i < numProperties; i++) { const auto& propertyName = properties[i]; if (propertyName.isSymbol()) continue; addValue(propertyName); RETURN_IF_EXCEPTION(scope, { }); } return JSValue::encode(values); } // ES6 6.2.4.5 ToPropertyDescriptor // https://tc39.github.io/ecma262/#sec-topropertydescriptor bool toPropertyDescriptor(JSGlobalObject* globalObject, JSValue in, PropertyDescriptor& desc) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!in.isObject()) { throwTypeError(globalObject, scope, "Property description must be an object."_s); return false; } JSObject* description = asObject(in); bool hasProperty = description->hasProperty(globalObject, vm.propertyNames->enumerable); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->enumerable); RETURN_IF_EXCEPTION(scope, false); desc.setEnumerable(value.toBoolean(globalObject)); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->configurable); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->configurable); RETURN_IF_EXCEPTION(scope, false); desc.setConfigurable(value.toBoolean(globalObject)); } else RETURN_IF_EXCEPTION(scope, false); JSValue value; hasProperty = description->hasProperty(globalObject, vm.propertyNames->value); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->value); RETURN_IF_EXCEPTION(scope, false); desc.setValue(value); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->writable); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->writable); RETURN_IF_EXCEPTION(scope, false); desc.setWritable(value.toBoolean(globalObject)); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->get); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue get = description->get(globalObject, vm.propertyNames->get); RETURN_IF_EXCEPTION(scope, false); if (!get.isUndefined() && !get.isCallable(vm)) { throwTypeError(globalObject, scope, "Getter must be a function."_s); return false; } desc.setGetter(get); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->set); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue set = description->get(globalObject, vm.propertyNames->set); RETURN_IF_EXCEPTION(scope, false); if (!set.isUndefined() && !set.isCallable(vm)) { throwTypeError(globalObject, scope, "Setter must be a function."_s); return false; } desc.setSetter(set); } else RETURN_IF_EXCEPTION(scope, false); if (!desc.isAccessorDescriptor()) return true; if (desc.value()) { throwTypeError(globalObject, scope, "Invalid property. 'value' present on property with getter or setter."_s); return false; } if (desc.writablePresent()) { throwTypeError(globalObject, scope, "Invalid property. 'writable' present on property with getter or setter."_s); return false; } return true; } EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperty(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!callFrame->argument(0).isObject()) return throwVMTypeError(globalObject, scope, "Properties can only be defined on Objects."_s); JSObject* obj = asObject(callFrame->argument(0)); auto propertyName = callFrame->argument(1).toPropertyKey(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); PropertyDescriptor descriptor; auto success = toPropertyDescriptor(globalObject, callFrame->argument(2), descriptor); EXCEPTION_ASSERT(!scope.exception() == success); if (!success) return JSValue::encode(jsNull()); ASSERT((descriptor.attributes() & PropertyAttribute::Accessor) || (!descriptor.isAccessorDescriptor())); scope.assertNoException(); obj->methodTable(vm)->defineOwnProperty(obj, globalObject, propertyName, descriptor, true); RELEASE_AND_RETURN(scope, JSValue::encode(obj)); } static JSValue defineProperties(JSGlobalObject* globalObject, JSObject* object, JSObject* properties) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyNameArray propertyNames(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); asObject(properties)->methodTable(vm)->getOwnPropertyNames(asObject(properties), globalObject, propertyNames, EnumerationMode(DontEnumPropertiesMode::Exclude)); RETURN_IF_EXCEPTION(scope, { }); size_t numProperties = propertyNames.size(); Vector<PropertyDescriptor> descriptors; MarkedArgumentBuffer markBuffer; #define RETURN_IF_EXCEPTION_CLEARING_OVERFLOW(value) do { \ if (scope.exception()) { \ markBuffer.overflowCheckNotNeeded(); \ return value; \ } \ } while (false) for (size_t i = 0; i < numProperties; i++) { JSValue prop = properties->get(globalObject, propertyNames[i]); RETURN_IF_EXCEPTION_CLEARING_OVERFLOW({ }); PropertyDescriptor descriptor; toPropertyDescriptor(globalObject, prop, descriptor); RETURN_IF_EXCEPTION_CLEARING_OVERFLOW({ }); descriptors.append(descriptor); // Ensure we mark all the values that we're accumulating if (descriptor.isDataDescriptor() && descriptor.value()) markBuffer.append(descriptor.value()); if (descriptor.isAccessorDescriptor()) { if (descriptor.getter()) markBuffer.append(descriptor.getter()); if (descriptor.setter()) markBuffer.append(descriptor.setter()); } } RELEASE_ASSERT(!markBuffer.hasOverflowed()); #undef RETURN_IF_EXCEPTION_CLEARING_OVERFLOW for (size_t i = 0; i < numProperties; i++) { auto& propertyName = propertyNames[i]; ASSERT(!propertyName.isPrivateName()); object->methodTable(vm)->defineOwnProperty(object, globalObject, propertyName, descriptors[i], true); RETURN_IF_EXCEPTION(scope, { }); } return object; } EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperties(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!callFrame->argument(0).isObject()) return throwVMTypeError(globalObject, scope, "Properties can only be defined on Objects."_s); JSObject* targetObj = asObject(callFrame->argument(0)); JSObject* props = callFrame->argument(1).toObject(globalObject); EXCEPTION_ASSERT(!!scope.exception() == !props); if (UNLIKELY(!props)) return encodedJSValue(); RELEASE_AND_RETURN(scope, JSValue::encode(defineProperties(globalObject, targetObj, props))); } EncodedJSValue JSC_HOST_CALL objectConstructorCreate(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue proto = callFrame->argument(0); if (!proto.isObject() && !proto.isNull()) return throwVMTypeError(globalObject, scope, "Object prototype may only be an Object or null."_s); JSObject* newObject = proto.isObject() ? constructEmptyObject(globalObject, asObject(proto)) : constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure()); if (callFrame->argument(1).isUndefined()) return JSValue::encode(newObject); JSObject* properties = callFrame->uncheckedArgument(1).toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); RELEASE_AND_RETURN(scope, JSValue::encode(defineProperties(globalObject, newObject, properties))); } enum class IntegrityLevel { Sealed, Frozen }; template<IntegrityLevel level> bool setIntegrityLevel(JSGlobalObject* globalObject, VM& vm, JSObject* object) { // See https://tc39.github.io/ecma262/#sec-setintegritylevel. auto scope = DECLARE_THROW_SCOPE(vm); bool success = object->methodTable(vm)->preventExtensions(object, globalObject); RETURN_IF_EXCEPTION(scope, false); if (UNLIKELY(!success)) return false; PropertyNameArray properties(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, false); PropertyNameArray::const_iterator end = properties.end(); for (PropertyNameArray::const_iterator iter = properties.begin(); iter != end; ++iter) { auto& propertyName = *iter; ASSERT(!propertyName.isPrivateName()); PropertyDescriptor desc; if (level == IntegrityLevel::Sealed) desc.setConfigurable(false); else { bool hasPropertyDescriptor = object->getOwnPropertyDescriptor(globalObject, propertyName, desc); RETURN_IF_EXCEPTION(scope, false); if (!hasPropertyDescriptor) continue; if (desc.isDataDescriptor()) desc.setWritable(false); desc.setConfigurable(false); } object->methodTable(vm)->defineOwnProperty(object, globalObject, propertyName, desc, true); RETURN_IF_EXCEPTION(scope, false); } return true; } template<IntegrityLevel level> bool testIntegrityLevel(JSGlobalObject* globalObject, VM& vm, JSObject* object) { auto scope = DECLARE_THROW_SCOPE(vm); // 1. Assert: Type(O) is Object. // 2. Assert: level is either "sealed" or "frozen". // 3. Let status be ?IsExtensible(O). bool status = object->isExtensible(globalObject); RETURN_IF_EXCEPTION(scope, { }); // 4. If status is true, return false. if (status) return false; // 6. Let keys be ? O.[[OwnPropertyKeys]](). PropertyNameArray keys(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, keys, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); // 7. For each element k of keys, do PropertyNameArray::const_iterator end = keys.end(); for (PropertyNameArray::const_iterator iter = keys.begin(); iter != end; ++iter) { auto& propertyName = *iter; ASSERT(!propertyName.isPrivateName()); // a. Let currentDesc be ? O.[[GetOwnProperty]](k) PropertyDescriptor desc; bool didGetDescriptor = object->getOwnPropertyDescriptor(globalObject, propertyName, desc); RETURN_IF_EXCEPTION(scope, { }); // b. If currentDesc is not undefined, then if (!didGetDescriptor) continue; // i. If currentDesc.[[Configurable]] is true, return false. if (desc.configurable()) return false; // ii. If level is "frozen" and IsDataDescriptor(currentDesc) is true, then // 1. If currentDesc.[[Writable]] is true, return false. if (level == IntegrityLevel::Frozen && desc.isDataDescriptor() && desc.writable()) return false; } return true; } JSObject* objectConstructorSeal(JSGlobalObject* globalObject, JSObject* object) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) { object->seal(vm); return object; } bool success = setIntegrityLevel<IntegrityLevel::Sealed>(globalObject, vm, object); RETURN_IF_EXCEPTION(scope, nullptr); if (UNLIKELY(!success)) { throwTypeError(globalObject, scope, "Unable to prevent extension in Object.seal"_s); return nullptr; } return object; } EncodedJSValue JSC_HOST_CALL objectConstructorSeal(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 1. If Type(O) is not Object, return O. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(obj); RELEASE_AND_RETURN(scope, JSValue::encode(objectConstructorSeal(globalObject, asObject(obj)))); } JSObject* objectConstructorFreeze(JSGlobalObject* globalObject, JSObject* object) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) { object->freeze(vm); return object; } bool success = setIntegrityLevel<IntegrityLevel::Frozen>(globalObject, vm, object); RETURN_IF_EXCEPTION(scope, nullptr); if (UNLIKELY(!success)) { throwTypeError(globalObject, scope, "Unable to prevent extension in Object.freeze"_s); return nullptr; } return object; } EncodedJSValue JSC_HOST_CALL objectConstructorFreeze(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 1. If Type(O) is not Object, return O. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(obj); JSObject* result = objectConstructorFreeze(globalObject, asObject(obj)); RETURN_IF_EXCEPTION(scope, encodedJSValue()); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL objectConstructorPreventExtensions(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue argument = callFrame->argument(0); if (!argument.isObject()) return JSValue::encode(argument); JSObject* object = asObject(argument); bool status = object->methodTable(vm)->preventExtensions(object, globalObject); RETURN_IF_EXCEPTION(scope, { }); if (UNLIKELY(!status)) return throwVMTypeError(globalObject, scope, "Unable to prevent extension in Object.preventExtensions"_s); return JSValue::encode(object); } EncodedJSValue JSC_HOST_CALL objectConstructorIsSealed(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); // 1. If Type(O) is not Object, return true. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(jsBoolean(true)); JSObject* object = asObject(obj); // Quick check for final objects. if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) return JSValue::encode(jsBoolean(object->isSealed(vm))); // 2. Return ? TestIntegrityLevel(O, "sealed"). return JSValue::encode(jsBoolean(testIntegrityLevel<IntegrityLevel::Sealed>(globalObject, vm, object))); } EncodedJSValue JSC_HOST_CALL objectConstructorIsFrozen(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); // 1. If Type(O) is not Object, return true. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(jsBoolean(true)); JSObject* object = asObject(obj); // Quick check for final objects. if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) return JSValue::encode(jsBoolean(object->isFrozen(vm))); // 2. Return ? TestIntegrityLevel(O, "frozen"). return JSValue::encode(jsBoolean(testIntegrityLevel<IntegrityLevel::Frozen>(globalObject, vm, object))); } EncodedJSValue JSC_HOST_CALL objectConstructorIsExtensible(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(jsBoolean(false)); JSObject* object = asObject(obj); bool isExtensible = object->isExtensible(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); return JSValue::encode(jsBoolean(isExtensible)); } EncodedJSValue JSC_HOST_CALL objectConstructorIs(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(jsBoolean(sameValue(globalObject, callFrame->argument(0), callFrame->argument(1)))); } JSArray* ownPropertyKeys(JSGlobalObject* globalObject, JSObject* object, PropertyNameMode propertyNameMode, DontEnumPropertiesMode dontEnumPropertiesMode) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); bool isObjectKeys = propertyNameMode == PropertyNameMode::Strings && dontEnumPropertiesMode == DontEnumPropertiesMode::Exclude; // We attempt to look up own property keys cache in Object.keys case. if (isObjectKeys) { if (LIKELY(!globalObject->isHavingABadTime())) { if (auto* immutableButterfly = object->structure(vm)->cachedOwnKeys()) { Structure* arrayStructure = globalObject->originalArrayStructureForIndexingType(immutableButterfly->indexingMode()); return JSArray::createWithButterfly(vm, nullptr, arrayStructure, immutableButterfly->toButterfly()); } } } PropertyNameArray properties(vm, propertyNameMode, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, properties, EnumerationMode(dontEnumPropertiesMode)); RETURN_IF_EXCEPTION(scope, nullptr); if (propertyNameMode != PropertyNameMode::StringsAndSymbols) { ASSERT(propertyNameMode == PropertyNameMode::Strings || propertyNameMode == PropertyNameMode::Symbols); if (properties.size() < MIN_SPARSE_ARRAY_INDEX) { if (LIKELY(!globalObject->isHavingABadTime())) { if (isObjectKeys) { Structure* structure = object->structure(vm); if (structure->canCacheOwnKeys()) { auto* cachedButterfly = structure->cachedOwnKeysIgnoringSentinel(); if (cachedButterfly == StructureRareData::cachedOwnKeysSentinel()) { size_t numProperties = properties.size(); auto* newButterfly = JSImmutableButterfly::create(vm, CopyOnWriteArrayWithContiguous, numProperties); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; ASSERT(!identifier.isSymbol()); newButterfly->setIndex(vm, i, jsOwnedString(vm, identifier.string())); } structure->setCachedOwnKeys(vm, newButterfly); Structure* arrayStructure = globalObject->originalArrayStructureForIndexingType(newButterfly->indexingMode()); return JSArray::createWithButterfly(vm, nullptr, arrayStructure, newButterfly->toButterfly()); } if (cachedButterfly == nullptr) structure->setCachedOwnKeys(vm, StructureRareData::cachedOwnKeysSentinel()); } } size_t numProperties = properties.size(); JSArray* keys = JSArray::create(vm, globalObject->originalArrayStructureForIndexingType(ArrayWithContiguous), numProperties); WriteBarrier<Unknown>* buffer = keys->butterfly()->contiguous().data(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; if (propertyNameMode == PropertyNameMode::Strings) { ASSERT(!identifier.isSymbol()); buffer[i].set(vm, keys, jsOwnedString(vm, identifier.string())); } else { ASSERT(identifier.isSymbol()); buffer[i].set(vm, keys, Symbol::create(vm, static_cast<SymbolImpl&>(*identifier.impl()))); } } return keys; } } } JSArray* keys = constructEmptyArray(globalObject, nullptr); RETURN_IF_EXCEPTION(scope, nullptr); unsigned index = 0; auto pushDirect = [&] (JSGlobalObject* globalObject, JSArray* array, JSValue value) { array->putDirectIndex(globalObject, index++, value); }; switch (propertyNameMode) { case PropertyNameMode::Strings: { size_t numProperties = properties.size(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; ASSERT(!identifier.isSymbol()); pushDirect(globalObject, keys, jsOwnedString(vm, identifier.string())); RETURN_IF_EXCEPTION(scope, nullptr); } break; } case PropertyNameMode::Symbols: { size_t numProperties = properties.size(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; ASSERT(identifier.isSymbol()); ASSERT(!identifier.isPrivateName()); pushDirect(globalObject, keys, Symbol::create(vm, static_cast<SymbolImpl&>(*identifier.impl()))); RETURN_IF_EXCEPTION(scope, nullptr); } break; } case PropertyNameMode::StringsAndSymbols: { Vector<Identifier, 16> propertySymbols; size_t numProperties = properties.size(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; if (identifier.isSymbol()) { ASSERT(!identifier.isPrivateName()); propertySymbols.append(identifier); continue; } pushDirect(globalObject, keys, jsOwnedString(vm, identifier.string())); RETURN_IF_EXCEPTION(scope, nullptr); } // To ensure the order defined in the spec (9.1.12), we append symbols at the last elements of keys. for (const auto& identifier : propertySymbols) { pushDirect(globalObject, keys, Symbol::create(vm, static_cast<SymbolImpl&>(*identifier.impl()))); RETURN_IF_EXCEPTION(scope, nullptr); } break; } } return keys; } } // namespace JSC
44.873892
203
0.687092
jacadcaps
3a6ff74e04828bc6bcb690735b7aec220f1e3a1b
29,800
cpp
C++
SOURCES/graphics/bspbuild/mgif.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/graphics/bspbuild/mgif.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/graphics/bspbuild/mgif.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include <mgapiall.h> #include <stdlib.h> #include <string.h> #include <windows.h> #include <stddef.h> #include <math.h> static int lasterr = 0; static void Normalize (double *xp, double *yp, double *zp) { // normalize double x = *xp, y = *yp, z = *zp; double mag = sqrt(x*x + y*y + z*z); x /= mag; y /= mag; z /= mag; *xp = x; *yp = y; *zp = z; } static void freenode (mgrec *db) { if (db->next) freenode (db->next); if (db->child) freenode (db->child); free (db); } inline void exch_char (char *a, char *b) { *a ^= *b; *b ^= *a; *a ^= *b; } inline short swap_short (short num) { short data = num; char *cnum = (char *) &data; exch_char (&cnum[1], &cnum[0]); return data; } inline int swap_int (int num) { int data = num; char *cnum = (char *) &data; exch_char (&cnum[3], &cnum[0]); exch_char (&cnum[2], &cnum[1]); return data; } inline float swap_float (float num) { float data = num; char *cnum = (char *) &data; exch_char (&cnum[3], &cnum[0]); exch_char (&cnum[2], &cnum[1]); return data; } inline double swap_double (double num) { double data = num; char *cnum = (char *) &data; exch_char (&cnum[7], &cnum[0]); exch_char (&cnum[6], &cnum[1]); exch_char (&cnum[5], &cnum[2]); exch_char (&cnum[4], &cnum[3]); return data; } struct { FltTypes type; const char *name; } FltNames[] = { #define MKENT(x) { x, #x } MKENT(fltHeader), MKENT(fltGroup), MKENT(fltIcoord), MKENT(fltVU), MKENT(fltVV), MKENT(fltVertex), MKENT(fltPolyMaterial), MKENT(fltDiffuse), MKENT(fltMatAlpha), MKENT(fltPolygon), MKENT(fltBsp), MKENT(fltSwitch), MKENT(fltDof), MKENT(fltLightPoint), MKENT(fltPolyTransparency), MKENT(fltGcLightMode), MKENT(fltPolyTexture), MKENT(fltMatrix), MKENT(fltVColor), MKENT(fltLpDirectionalityType), MKENT(fltLpBackColor), MKENT(fltPolyMgTemplate), MKENT(fltPolyLineStyle), MKENT(fltPolyDrawType), MKENT(fltDPlaneA), MKENT(fltDPlaneB), MKENT(fltDPlaneC), MKENT(fltDPlaneD), MKENT(fltDofPutAnchorX), MKENT(fltDofPutAnchorY), MKENT(fltDofPutAnchorZ), MKENT(fltDofPutAlignX), MKENT(fltDofPutAlignY), MKENT(fltDofPutAlignZ), MKENT(fltDofPutTrackX), MKENT(fltDofPutTrackY), MKENT(fltDofPutTrackZ), MKENT(fltDofMaxX), MKENT(fltDofMinX), MKENT(fltXref), MKENT(fltLodSwitchIn), MKENT(fltXrefFilename), MKENT(fltLod) }; static const int FltSize = sizeof(FltNames) / sizeof(FltNames[0]); static int mgIgnoreRec (OpCode type) { #if 1 return 0; #else switch (type) { case OPCODE_POLYGON: case OPCODE_BINARY_SEPARATING_PLANE: case OPCODE_SWITCH_BEAD: case OPCODE_DEGREE_OF_FREEDOM: case OPCODE_LIGHT_SOURCE_RECORD: case OPCODE_LEVEL_OF_DETAIL: case OPCODE_VERTEX_LIST: case OPCODE_COLOR_TABLE: case OPCODE_HEADER: case OPCODE_TEXT_COMMENT: case OPCODE_TEXTURE_REFERENCE_RECORD: case OPCODE_VERTEX_PALETTE: case OPCODE_VERTEX_WITH_NORMAL: case OPCODE_VERTEX_WITH_NORMAL_AND_UV: case OPCODE_VERTEX_WITH_UV: case OPCODE_MATERIAL_TABLE: case OPCODE_PUSH_LEVEL: case OPCODE_POP_LEVEL: case OPCODE_MATERIAL_PALETTE: case OPCODE_VERTEX_COORDINATE: return 0; default: return 1; } #endif } static int mgIsAncillary (OpCode type) { switch (type) { case OPCODE_TEXT_COMMENT: case OPCODE_LONG_IDENTIFIER: case OPCODE_REPLICATE_CODE: case OPCODE_ROAD_ZONE: case OPCODE_TRANSFORMATION_MATRIX: case OPCODE_VECTOR: case OPCODE_BOUNDING_BOX: case OPCODE_CAT_DATA: case OPCODE_EXTENSION: case OPCODE_VERTEX_COORDINATE: case OPCODE_VERTEX_WITH_NORMAL: case OPCODE_VERTEX_WITH_NORMAL_AND_UV: case OPCODE_VERTEX_WITH_UV: return 1; default: return 0; } } static int mgIsPalette (OpCode type) { switch (type) { case OPCODE_VERTEX_PALETTE: case OPCODE_COLOR_TABLE: case OPCODE_COLOR_NAME_PALETTE: case OPCODE_MATERIAL_PALETTE: case OPCODE_TEXTURE_REFERENCE_RECORD: case OPCODE_EYEPOINT_AND_TRACKPLANE_POSITION: case OPCODE_LINKAGE_RECORD: case OPCODE_SOUND_PALETTE: case OPCODE_LIGHT_SOURCE_PALETTE: case OPCODE_LINE_STYLE_RECORD: case OPCODE_TEXTURE_MAPPING_PALETTE: case OPCODE_MATERIAL_TABLE: return 1; default: return 0; } } const char *FindFltName (FltTypes f) { for (int i = 0; i < FltSize; i++) { if (FltNames[i].type == f) return FltNames[i].name; } return 0; } static int mgGetColorInd (mgrec *rec, int ind, int *rgb) { mgrec *pbase = rec; while (pbase -> parent) { pbase = pbase -> parent; } while (pbase && pbase -> type != OPCODE_COLOR_TABLE) { pbase = mgGetNext (pbase); } if (pbase == NULL) return MG_FALSE; if (rec->vrsn > 1500) { if ((unsigned)ind > (pbase -> len - offsetof(struct aflt_ColorRecord, rgb))/4) return MG_FALSE; struct aflt_ColorRecord *cr; cr = (struct aflt_ColorRecord *)pbase->data; *rgb = swap_int(cr -> rgb[ind]); return MG_TRUE; } else { if ((unsigned)ind > (pbase -> len - offsetof(struct flt_ColorRecord, rgb))/4) return MG_FALSE; struct flt_ColorRecord *cr; cr = (struct flt_ColorRecord *)pbase->data; *rgb = swap_int(cr -> rgb[ind]); return MG_TRUE; } } void mgInit (int type, void *param) { } char *mgGetName (mgrec *rec) { mgrec *p; for (p = rec->next; p && mgIsAncillary(p->type); p = p -> next) { if (p->type == OPCODE_LONG_IDENTIFIER) { char *comm = (char *)malloc (p->len - 4 + 1); memcpy (comm, p->data+4, p->len - 4); comm[p->len - 4] = '\0'; return comm; } } char *comm = (char *)malloc (8); memcpy (comm, rec->data+4, 8); return comm; } char * mgRec2Filename (mgrec *rec) { char *comm = (char *)malloc (9); strcpy (comm, "filename"); return comm; } mgrec *mgGetChild (mgrec *rec) { if (rec -> child) return rec->child; mgrec *p; for (p = rec->next; p && (mgIsAncillary(p->type) || mgIsPalette(p->type)); p = p->next) if (p->child) return p->child; return 0; } mgrec *mgGetParent (mgrec *rec) { return rec -> parent; } void mgExit () { } mgrec *mgGetNext (mgrec *rec) { mgrec *p; for (p = rec->next; p && (mgIsAncillary(p->type) || mgIsPalette(p->type)); p = p->next) continue; return p; } int mgIsCode (mgrec *rec, FltTypes type) { char buf[1024]; switch (type) { case fltPolygon: return rec->type == OPCODE_POLYGON; case fltBsp: return rec->type == OPCODE_BINARY_SEPARATING_PLANE; case fltSwitch: return rec->type == OPCODE_SWITCH_BEAD; case fltDof: return rec->type == OPCODE_DEGREE_OF_FREEDOM; case fltLightPoint: return rec->type == OPCODE_LIGHT_SOURCE_RECORD; case fltLod: return rec->type == OPCODE_LEVEL_OF_DETAIL; case fltVertex: return rec->type == OPCODE_VERTEX_LIST; default: sprintf (buf, "Unknown FltType %d %s\n", type, FindFltName(type)); OutputDebugString(buf); break; } return MG_FALSE; } void mgGetLastError (char *err, int size) { sprintf (err, "Error number %d", lasterr); } void mgFree (char *data) { free (data); } char *mgGetComment (mgrec *record) { while (record && record -> type != OPCODE_TEXT_COMMENT) { record = record -> next; } if (record) { char *comm = (char *)malloc (record -> len - 4); memcpy (comm, record -> data, record -> len - 4); return comm; } return 0; } int mgGetFirstTexture (mgrec *record, int *texind, char *texname) { return MG_FALSE; while (record && record -> type != OPCODE_TEXTURE_REFERENCE_RECORD) { record = record -> next; } if (record) { #if 0 if (record->vrsn > 1500) { OutputDebugString ("Version 1500 textures not supported yet\n"); return MG_FALSE; } #endif struct flt_TexturePatternRecord *tr = (struct flt_TexturePatternRecord *)record -> data; *texind = swap_int(tr -> patternIndex); strcpy (texname, tr -> filename); return MG_TRUE; } return MG_FALSE; } int mgGetNextTexture (mgrec *record, int *texind, char *texname) { if (record->vrsn > 1500) { OutputDebugString ("Version 1500 textures not supported yet\n"); return MG_FALSE; } while (record && record -> type != OPCODE_TEXTURE_REFERENCE_RECORD) { record = record -> next; } if (record == NULL) return MG_FALSE; while (record && record -> type == OPCODE_TEXTURE_REFERENCE_RECORD) { struct flt_TexturePatternRecord *tr = (struct flt_TexturePatternRecord *)record -> data; int ind = swap_int(tr -> patternIndex); if (ind > *texind) { *texind = ind; strcpy (texname, tr -> filename); return MG_TRUE; } record = record->next; } return MG_FALSE; } static mgrec *GetVertex (mgrec *rec, int n) { while (rec -> parent) rec = rec->parent; while (rec && rec -> type != OPCODE_VERTEX_PALETTE) rec = rec->next; if (rec == 0) return 0; int voff = rec->len; rec = rec->next; for (int i = 0; rec && voff < n; i++) { if (voff == n) return rec; voff += rec -> len; rec = rec->next; } return rec; } static int mgGetVertexNormal (mgrec *rec, double *i, double *j, double *k) { if (rec -> type != OPCODE_VERTEX_LIST) { OutputDebugString("GetVertexNormal not a vertex list\n"); return MG_FALSE; } int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { OutputDebugString("GetVertexNormal no vertex list\n"); return MG_FALSE; } switch (vr -> type) { case OPCODE_VERTEX_WITH_NORMAL: { struct flt_VertexCoordinateNormal *vn = (struct flt_VertexCoordinateNormal *)vr->data; *i = swap_float (vn->nx); *j = swap_float (vn->ny); *k = swap_float (vn->nz); return MG_TRUE; } case OPCODE_VERTEX_WITH_NORMAL_AND_UV: { struct flt_VertexCoordinateTextureNormal *vn = (struct flt_VertexCoordinateTextureNormal *)vr->data; *i = swap_float (vn->nx); *j = swap_float (vn->ny); *k = swap_float (vn->nz); return MG_TRUE; } default: return MG_FALSE; } } int mgGetVtxNormal (mgrec *rec, float *i, float *j, float *k) { double i1, j1, k1; if (mgGetVertexNormal (rec, &i1, &j1, &k1) == MG_TRUE) { *i = (float)i1; *j = (float)j1; *k = (float)k1; return MG_TRUE; } return MG_FALSE; } int mgGetVtxColorRGB (mgrec *rec, short *r, short *g, short *b) { if (rec -> type != OPCODE_VERTEX_LIST) { OutputDebugString("mgGetVtxColorRGB not a vertex list\n"); } int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { char buf[1024]; sprintf (buf, "No vertex reference found for %d\n", *vtx); OutputDebugString (buf); return MG_FALSE; } struct flt_VertexCoordinate *vc = (struct flt_VertexCoordinate *)vr->data; int pc= swap_short(vc -> vertexColor); int colind = pc >> 7; int colint = pc & 0x7f; int rgb; if (mgGetColorInd (rec, colind, &rgb) != MG_TRUE) return MG_FALSE; *r = (rgb & 0xff) * colint / 127; *g = ((rgb>>8) & 0xff) * colint / 127; *b = ((rgb>>16) & 0xff) * colint / 127; return MG_TRUE; } int mgGetIcoord (mgrec *rec, FltTypes type, double *x, double *y, double *z) { if (type != fltIcoord) { OutputDebugString("Not fltIcoord\n"); return MG_FALSE; } if (rec -> type == OPCODE_VERTEX_LIST) { int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { char buf[1024]; sprintf (buf, "No vertex reference found for %d\n", *vtx); OutputDebugString (buf); return MG_FALSE; } struct flt_VertexCoordinate *vc = (struct flt_VertexCoordinate *)vr->data; *x = swap_double (vc -> x); *y = swap_double (vc -> y); *z = swap_double (vc -> z); return MG_TRUE; } return MG_FALSE; } static int mgVtxFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_VERTEX_LIST) return MG_FALSE; int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { char buf[1024]; sprintf (buf, "No vertex reference found for %d\n", *vtx); OutputDebugString (buf); return MG_FALSE; } switch (type) { case fltVU: { if (vr -> type == OPCODE_VERTEX_WITH_NORMAL_AND_UV) { struct flt_VertexCoordinateTextureNormal *vt = (struct flt_VertexCoordinateTextureNormal *) vr -> data; *(float *)ptr = swap_float(vt -> u); break; } else if (vr -> type = OPCODE_VERTEX_WITH_UV) { struct flt_VertexCoordinateTexture *vt = (struct flt_VertexCoordinateTexture *) vr -> data; *(float *)ptr = swap_float(vt -> u); break; } else return MG_FALSE; } break; case fltVV: { if (vr -> type == OPCODE_VERTEX_WITH_NORMAL_AND_UV) { struct flt_VertexCoordinateTextureNormal *vt = (struct flt_VertexCoordinateTextureNormal *) vr -> data; *(float *)ptr = swap_float(vt -> v); break; } else if (vr -> type = OPCODE_VERTEX_WITH_UV) { struct flt_VertexCoordinateTexture *vt = (struct flt_VertexCoordinateTexture *) vr -> data; *(float *)ptr = swap_float(vt -> v); break; } else return MG_FALSE; } break; default: return MG_FALSE; } return MG_TRUE; } static int mgBspFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_BINARY_SEPARATING_PLANE) return 0; struct aflt_BinarySeparatingPlane *bsp = (struct aflt_BinarySeparatingPlane *)rec -> data; switch (type) { case fltDPlaneA: *(double *)ptr = swap_double(bsp->a); break; case fltDPlaneB: *(double *)ptr = swap_double(bsp->b); break; case fltDPlaneC: *(double *)ptr = swap_double(bsp->c); break; case fltDPlaneD: *(double *)ptr = swap_double(bsp->d); break; default: OutputDebugString ("Unknown BSP\n"); break; } return 1; } static int mgPolyFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_POLYGON) return 0; if (rec -> vrsn > 1500) { struct aflt_PolygonRecord *pr = (struct aflt_PolygonRecord *)rec->data; switch (type) { case fltPolyMaterial: { *(short *)ptr = swap_short(pr->materialCode); break; } case fltPolyTransparency: { *(short*)ptr = swap_short (pr->transparency); break; } case fltPolyMgTemplate: { *(char *)ptr = pr->templateTransparency; break; } case fltGcLightMode: { *(char *)ptr = pr->lightMode; break; } case fltPolyTexture: { *(short*)ptr = swap_short (pr->textureNo); break; } case fltPolyLineStyle: { *(char *)ptr = pr->linestyle; break; } case fltPolyDrawType: { *(char *)ptr = pr->howToDraw; break; } default: OutputDebugString ("Unknown poly attr\n"); break; } } else { struct flt_PolygonRecord *pr = (struct flt_PolygonRecord *)rec->data; switch (type) { case fltPolyMaterial: { *(short *)ptr = swap_short(pr->materialCode); break; } case fltPolyTransparency: { *(short*)ptr = swap_short (pr->transparency); break; } case fltPolyMgTemplate: { *(char *)ptr = pr->templateTransparency; break; } case fltGcLightMode: { *(char *)ptr = pr->lightMode; break; } case fltPolyTexture: { *(short*)ptr = swap_short (pr->textureNo); break; } case fltPolyLineStyle: { *(char *)ptr = pr->linestyle; break; } case fltPolyDrawType: { *(char *)ptr = pr->howToDraw; break; } default: OutputDebugString ("Unknown poly attr\n"); break; } } return 1; } static int mgDofFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_DEGREE_OF_FREEDOM) return 0; if (rec -> vrsn > 1500) { struct aflt_DegreeOfFreedomRecord *dof = (struct aflt_DegreeOfFreedomRecord *)rec->data; switch (type) { case fltDofPutAnchorX: { *(double *)ptr = swap_double(dof->originx); break; } case fltDofPutAnchorY: { *(double *)ptr = swap_double(dof->originy); break; } case fltDofPutAnchorZ: { *(double *)ptr = swap_double(dof->originz); break; } case fltDofPutAlignX: { *(double *)ptr = swap_double(dof->pointxaxis_x); break; } case fltDofPutAlignY: { *(double *)ptr = swap_double(dof->pointxaxis_y); break; } case fltDofPutAlignZ: { *(double *)ptr = swap_double(dof->pointxaxis_z); break; } case fltDofPutTrackX: { *(double *)ptr = swap_double(dof->pointxyplane_x); break; } case fltDofPutTrackY: { *(double *)ptr = swap_double(dof->pointxyplane_y); break; } case fltDofPutTrackZ: { *(double *)ptr = swap_double(dof->pointxyplane_z); break; } case fltDofMaxX: { *(double *)ptr = swap_double(dof->maxx); break; } case fltDofMinX: { *(double *)ptr = swap_double(dof->minx); break; } default: OutputDebugString ("Unknown DOF attr\n"); break; } } else { struct flt_DegreeOfFreedomRecord *dof = (struct flt_DegreeOfFreedomRecord *)rec->data; switch (type) { case fltDofPutAnchorX: { *(double *)ptr = swap_double(dof->originx); break; } case fltDofPutAnchorY: { *(double *)ptr = swap_double(dof->originy); break; } case fltDofPutAnchorZ: { *(double *)ptr = swap_double(dof->originz); break; } case fltDofPutAlignX: { *(double *)ptr = swap_double(dof->pointxaxis_x); break; } case fltDofPutAlignY: { *(double *)ptr = swap_double(dof->pointxaxis_y); break; } case fltDofPutAlignZ: { *(double *)ptr = swap_double(dof->pointxaxis_z); break; } case fltDofPutTrackX: { *(double *)ptr = swap_double(dof->pointxyplane_x); break; } case fltDofPutTrackY: { *(double *)ptr = swap_double(dof->pointxyplane_y); break; } case fltDofPutTrackZ: { *(double *)ptr = swap_double(dof->pointxyplane_z); break; } case fltDofMaxX: { *(double *)ptr = swap_double(dof->maxx); break; } case fltDofMinX: { *(double *)ptr = swap_double(dof->minx); break; } default: OutputDebugString ("Unknown DOF attr\n"); break; } } return 1; } static int mgMatFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec->vrsn > 1500) { OutputDebugString ("mgMatFetch doesn't support 1500\n"); return MG_FALSE; } if (rec -> type != OPCODE_MATERIAL_TABLE) return MG_FALSE; struct flt_MaterialTable *mt = (struct flt_MaterialTable *)rec -> data; switch (type) { case fltMatAlpha: *(float *)ptr = swap_float (mt -> alpha); break; default: return MG_FALSE; } return MG_TRUE; } int mgGetAttList (mgrec *rec, ...) { va_list ap; FltTypes type; int count = 0; va_start(ap, rec); while ((type = va_arg(ap, FltTypes)) != 0) { switch (type) { case fltVU: case fltVV: { float *fp = va_arg (ap, float *); if (mgVtxFetch (rec, type, fp)) count ++; } break; case fltDPlaneA: case fltDPlaneB: case fltDPlaneC: case fltDPlaneD: { double *dp = va_arg(ap, double *); if (mgBspFetch (rec, type, dp)) count ++; } break; case fltPolyMaterial: { short *mind = va_arg(ap, short *); if (mgPolyFetch(rec, type, mind)) count ++; } break; case fltPolyTransparency: { short *tp = va_arg(ap, short *); if (mgPolyFetch(rec, type, tp)) count ++; } break; case fltPolyMgTemplate: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltGcLightMode: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltPolyTexture: { short *cp = va_arg(ap, short *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltPolyLineStyle: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltPolyDrawType: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltMatAlpha: { float *fp = va_arg (ap, float *); if (mgMatFetch (rec, type, fp)) count ++; } break; case fltDofPutAnchorX: case fltDofPutAnchorY: case fltDofPutAnchorZ: case fltDofPutAlignX: case fltDofPutAlignY: case fltDofPutAlignZ: case fltDofPutTrackX: case fltDofPutTrackY: case fltDofPutTrackZ: case fltDofMaxX: case fltDofMinX: { double *dp = va_arg(ap, double *); if (mgDofFetch (rec, type, dp)) count ++; } break; default: { char buf[1024]; sprintf (buf, "Unsupported attr type %d %s\n", type, FindFltName(type)); OutputDebugString(buf); va_arg (ap, char *); // best guess } break; } } va_end (ap); return count; } static short getshort (FILE *fp) { int c1 = getc(fp); int c2 = getc(fp); return (c1 << 8) | c2; } static mgrec *mgReadSequence (FILE *fp, mgrec *prnt, int vrsn); static mgrec *mgReadRecord (FILE *fp, mgrec *prnt, int vrsn) { mgrec *rec = NULL; while (rec == NULL) { short type = getshort(fp); if (feof(fp)) return 0; rec = (mgrec *)calloc (1, sizeof *rec); rec->type = (OpCode)type; rec->len = getshort(fp); rec->data = (char *) calloc (1, rec -> len); rec->vrsn = vrsn; rec->parent = prnt; memcpy (rec->data, &rec->type, 2); memcpy (rec->data+2, &rec->len, 2); fread (rec -> data + 4, rec -> len - 4, 1, fp); if (mgIgnoreRec (rec->type)) { free (rec->data); free (rec); rec = NULL; } else if (rec->type == OPCODE_PUSH_LEVEL) { rec -> child = mgReadSequence(fp, prnt, vrsn); } else if (rec -> type == OPCODE_VERTEX_LIST) { // recode this as a sequence mgrec *last = rec; char *data = rec -> data; struct flt_VertexList *vl = (struct flt_VertexList *)data; rec -> data = (char *)malloc(sizeof (int)); *(int*)rec -> data = swap_int(vl->offset[0]); for (int i = 1; i < (rec->len - 4) / 4; i++) { last->next = (mgrec *)calloc (1, sizeof *rec); last = last->next; last -> type = rec -> type; last -> len = rec -> len; last -> parent = prnt; last -> vrsn = vrsn; last -> data = (char *)malloc(sizeof(int)); *(int*)last -> data = swap_int(vl->offset[i]); } free (data); } } return rec; } static mgrec *mgReadSequence (FILE *fp, mgrec *prnt, int vrsn) { mgrec *base = 0; mgrec *cur = base; mgrec *np; int pcount = 0; while (np = mgReadRecord (fp, base, vrsn)) { if (np -> type == OPCODE_PUSH_LEVEL) { pcount ++; if (cur == NULL) { cur = np -> child; if (base == NULL) base = cur; } else { cur-> child = np -> child; } np -> child = NULL; freenode (np); if (cur) { for (np = cur -> child; np; np = np -> next) { np -> parent = base; } } } else if (np -> type == OPCODE_POP_LEVEL) { freenode (np); pcount --; if (pcount <= 0) break; } else { if (base == 0) { cur = base = np; } else cur->next = np; np ->parent = prnt; while (cur -> next) { cur->parent = prnt; cur = cur->next; } } } return base; } mgrec *mgOpenDb (char *filename) { FILE *fp = fopen(filename, "rb"); if (fp == NULL) return NULL; mgrec *base = mgReadRecord (fp, 0, 0); if (base->type != OPCODE_HEADER) { return NULL; } struct flt_HeaderRecord *fh = (struct flt_HeaderRecord *)base->data; printf ("Version %d, db version %d\n", swap_int(fh->formatRev), swap_int(fh->DBRev)); base -> next = mgReadSequence (fp, 0, swap_int(fh->formatRev)); fclose (fp); if (base->type != OPCODE_HEADER) { return NULL; } return base; } void mgCloseDb (mgrec *db) { // freenode (db); } mgrec *mgGetMaterial (mgrec *db, int matind) { if (db -> vrsn > 1500) { OutputDebugString ("mgGetMaterial doesn't support 1500\n"); return MG_FALSE; } mgrec *pbase = db; while (pbase -> parent) { pbase = pbase -> parent; } while (pbase && pbase -> type != OPCODE_MATERIAL_TABLE) { pbase = pbase -> next; } if (pbase == NULL) return 0; if (pbase -> child) { for (mgrec *cp = pbase -> child; cp; cp = cp -> next) { if (cp -> xdata == matind) return cp; } } flt_MaterialRecord *fmr = (flt_MaterialRecord *)pbase->data; if (matind < 0 || matind > 64) return 0; mgrec *mr = (mgrec *) calloc (1, sizeof *mr); mr -> type = OPCODE_MATERIAL_TABLE; mr -> parent = pbase; mr -> xdata = matind; mr -> next = pbase -> child; pbase->child = mr; mr -> data = (char *)calloc (1, sizeof (flt_MaterialTable)); memcpy (mr -> data, &fmr -> mat[matind], sizeof (flt_MaterialTable)); return mr; } static int mgFind15Material (mgrec *db, int matind, short *r, short *g, short *b) { mgrec *pbase = db; while (pbase -> parent) { pbase = pbase -> parent; } while (pbase && pbase -> type != OPCODE_MATERIAL_PALETTE) { pbase = pbase -> next; } if (pbase == NULL) return 0; while (pbase->type == OPCODE_MATERIAL_PALETTE) { aflt_MaterialRecord *matrec = (aflt_MaterialRecord *)pbase->data; if (swap_int(matrec->materialIndex) == matind) { *r = (short)(255.0f * swap_float(matrec->diffuseRed)); *g = (short)(255.0f * swap_float(matrec->diffuseGreen)); *b = (short)(255.0f * swap_float(matrec->diffuseBlue)); return MG_TRUE; } pbase = pbase->next; } return MG_FALSE; } static int mgFind14Material (mgrec *db, int matind, short *r, short *g, short *b) { mgrec *pbase = mgGetMaterial(db, matind); if (pbase == NULL) return MG_FALSE; flt_MaterialTable *matrec = (flt_MaterialTable *)pbase->data; *r = (short)(255.0f * swap_float(matrec->diffuseRed)); *g = (short)(255.0f * swap_float(matrec->diffuseGreen)); *b = (short)(255.0f * swap_float(matrec->diffuseBlue)); return MG_TRUE; } int mgGetPolyColorRGB (mgrec *rec, short *r, short *g, short *b) { if (rec -> type != OPCODE_POLYGON) return MG_FALSE; int colindex; int colintens; if (strncmp (rec->data + 4, "f45", 3) == 0 || strncmp (rec->data + 4, "f42", 3) == 0) { *r =0; *g = 255; *b = 0; return MG_TRUE; } if (rec->vrsn > 1500) { struct aflt_PolygonRecord *pr; pr = (struct aflt_PolygonRecord *)rec->data; int mc = swap_short(pr->materialCode); if (mc != -1) { return mgFind15Material (rec, mc, r, g, b); } else { int pc = swap_short (pr->primaryColor); colindex = pc >> 7; colintens = pc & 0x7f; } } else { struct flt_PolygonRecord *pr; pr = (struct flt_PolygonRecord *)rec->data; int mc = swap_short(pr->materialCode); if (mc != -1) { return mgFind14Material (rec, mc, r, g, b); } unsigned short pc = swap_short (pr->primaryColor); colindex = pc >> 7; colintens = pc & 0x7f; } int rgb; if (mgGetColorInd (rec, colindex, &rgb) != MG_TRUE) return MG_FALSE; *r = (rgb & 0xff) * colintens / 127; *g = ((rgb>>8) & 0xff) * colintens / 127; *b = ((rgb>>16) & 0xff) * colintens / 127; return MG_TRUE; } static int mgGetFaceFromVertexNormal (mgrec *vert, double *i, double *j, double *k) { double i1, j1, k1; double nx = 0.0, ny = 0.0, nz = 0.0; int count = 0; while (vert) { if (mgGetVertexNormal(vert, &i1, &j1, &k1) != MG_TRUE) return MG_FALSE; nx += i1; ny += j1; nz += k1; count ++; vert = mgGetNext (vert); } nx /= count; ny /= count; nz /= count; Normalize (&nx, &ny, &nz); *i = nx; *j = ny; *k = nz; return MG_TRUE; } int mgGetPolyNormal(mgrec *rec, double *i, double *j, double *k) { mgrec *child = mgGetChild (rec); if (child == 0 || child -> type != OPCODE_VERTEX_LIST) { OutputDebugString ("No child with vertex\n"); return MG_FALSE; } if (mgGetFaceFromVertexNormal (child, i, j, k) == MG_TRUE) return MG_TRUE; // otherwise compute it ourself. OutputDebugString ("Got to calculate our own normal\n"); double x1, y1, z1; if (mgGetIcoord (child, fltIcoord, &x1, &y1, &z1) == MG_FALSE) { OutputDebugString ("No vertex 1\n"); return MG_FALSE; } double x2, y2, z2; child = child -> next; if (mgGetIcoord (child, fltIcoord, &x2, &y2, &z2) == MG_FALSE) { OutputDebugString ("No vertex 2\n"); return MG_FALSE; } double x3, y3, z3; child = child -> next; if (mgGetIcoord (child, fltIcoord, &x3, &y3, &z3) == MG_FALSE) { OutputDebugString ("No vertex 3\n"); return MG_FALSE; } // 2 - 1 = u x1 = x2 - x1; y1 = y2 - y1; z1 = z2 - z1; // 3 - 2 = v x2 = x3 - x2; y2 = y3 - y2; z2 = z3 - z2; // u cross v x3 = y1 * z2 + z1 * y2; y3 = z1 * x2 + x1 * z2; z3 = x1 * y2 + y1 * x2; Normalize (&x3, &y3, &z3); *i = x3; *j = y3; *k = z3; return MG_TRUE; } int mgGetMatrix (mgrec *rec, FltTypes type, mgmatrix *mat) { OutputDebugString("mgGetmatrix not implemented\n"); return MG_FALSE; } int mgGetNormColor (mgrec *rec, FltTypes type, float *r, float *g, float *b) { if (rec->vrsn > 1500) { OutputDebugString ("mgGetNormColor not supported in 1500\n"); return MG_FALSE; } if (rec -> type != OPCODE_MATERIAL_TABLE) return MG_FALSE; struct flt_MaterialTable *mt = (struct flt_MaterialTable *)rec -> data; switch (type) { case fltDiffuse: *r = swap_float(mt->diffuseRed); *g = swap_float(mt->diffuseGreen); *b = swap_float(mt->diffuseBlue); break; default: OutputDebugString ("Unknown type for GetNormColor\n"); return MG_FALSE; } return MG_TRUE; } int mgIndex2RGB (mgrec *rec, int colind, float intensity, short *r, short *g, short *b) { OutputDebugString("mgIndex2RGB not implemented\n"); return MG_FALSE; } void mgSetMessagesEnabled (int, int) { }
22.887865
105
0.61255
IsraelyFlightSimulator
3a703e47399996e93a085ff59daccde6fa8c585e
459
hpp
C++
net/include/HttpHeaderConnection.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
27
2019-04-27T00:51:22.000Z
2022-03-30T04:05:44.000Z
net/include/HttpHeaderConnection.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
9
2020-05-03T12:17:50.000Z
2021-10-15T02:18:47.000Z
net/include/HttpHeaderConnection.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
1
2019-04-16T01:45:36.000Z
2019-04-16T01:45:36.000Z
#ifndef __OBOTCHA_HTTP_HEADER_CONNECTION_HPP__ #define __OBOTCHA_HTTP_HEADER_CONNECTION_HPP__ #include "Object.hpp" #include "StrongPointer.hpp" #include "String.hpp" #include "ArrayList.hpp" namespace obotcha { DECLARE_CLASS(HttpHeaderConnection) { public: _HttpHeaderConnection(); _HttpHeaderConnection(String); void import(String); void set(String); String get(); String toString(); private: String type; }; } #endif
14.34375
46
0.738562
wangsun1983
3a734b81f8873d428f3eb78e2aee8bc25cbd315d
2,026
hpp
C++
src/xf86drmMode.hpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
128
2015-01-07T19:47:09.000Z
2022-01-22T19:42:14.000Z
src/xf86drmMode.hpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
null
null
null
src/xf86drmMode.hpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
24
2015-01-07T19:47:10.000Z
2022-01-25T17:42:37.000Z
/* xf86drmMode.h uses the following license: * Copyright (c) 2007-2008 Tungsten Graphics, Inc., Cedar Park, Texas. * Copyright (c) 2007-2008 Dave Airlie <airlied@linux.ie> * Copyright (c) 2007-2008 Jakob Bornecrantz <wallbraker@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "stack.hpp" #include "convert/char.hpp" #include <drm/drm_mode.h> #include <xf86drmMode.h> LUA_METATABLE_NAMED(drm_clip_rect); LUA_METATABLE_NAMED(_drmModeConnector); LUA_METATABLE_NAMED(drmModeConnection); LUA_METATABLE_NAMED(_drmModeEncoder); LUA_METATABLE_NAMED(_drmModeObjectProperties); LUA_METATABLE_NAMED(_drmModePlane); LUA_METATABLE_NAMED(_drmModeProperty); LUA_METATABLE_NAMED(_drmModePropertyBlob); LUA_METATABLE_NAMED(_drmModePlaneRes); LUA_METATABLE_NAMED(drmModeSubPixel); LUA_METATABLE_NAMED(_drmModeModeInfo); LUA_METATABLE_NAMED(_drmModeRes); LUA_METATABLE_NAMED(_drmModeFB); LUA_METATABLE_NAMED(_drmModeCrtc); extern "C" int luaopen_xf86drmMode(lua_State* const state);
38.226415
79
0.794176
dafrito
3a749fb516e9de87ac9e1fc40f6eaf6e47a18659
3,256
cpp
C++
Mesh.cpp
miky-kr5/OGL4-Instanced-Perf
c1db44ceb5f9be720c9f75e254275f5a9457309b
[ "BSD-2-Clause" ]
null
null
null
Mesh.cpp
miky-kr5/OGL4-Instanced-Perf
c1db44ceb5f9be720c9f75e254275f5a9457309b
[ "BSD-2-Clause" ]
null
null
null
Mesh.cpp
miky-kr5/OGL4-Instanced-Perf
c1db44ceb5f9be720c9f75e254275f5a9457309b
[ "BSD-2-Clause" ]
null
null
null
#include "Mesh.h" Mesh::Mesh() { } Mesh::~Mesh() { Vertexs.clear(); Normals.clear(); Uvs.clear(); Objects.clear(); } void Mesh::setName(std::string name){ Name = name; } std::string* Mesh::getName(){ return &Name; } void Mesh::AddVertex(float x, float y, float z) { glm::vec3 vertex(x, y, z); Vertexs.push_back(vertex); } void Mesh::AddNormal(float x, float y, float z) { glm::vec3 normal(x, y, z); Normals.push_back(normal); } void Mesh::AddUv(float u, float v) { glm::vec2 uv(u, v); Uvs.push_back(uv); } void Mesh::AddMaterialGroup(MaterialGroup newMG) { Objects.push_back(newMG); } MaterialGroup* Mesh::getLastMaterialGroup() { return &Objects.back(); } unsigned long Mesh::getVertexsSize() { return Vertexs.size(); } unsigned long Mesh::getNormalsize() { return Normals.size(); } unsigned long Mesh::getUvsSize() { return Uvs.size(); } void Mesh::Print() { printf("Object Name: %s\n -Number of Vertex: %d\n -Number of Normals: %d\n -Number of Uvs: %d\n-Number of Materials Groups: %d\n", Name.c_str(), Vertexs.size(), Normals.size(), Uvs.size(), Objects.size()); for (int i = 0; i < Objects.size(); i++) Objects[i].Print(); } void Mesh::GenBuffers() { int size = Objects.size(); sizeFaces = 0; for (int i = 0; i < size; i++) { int numTriangle = Objects[i].getTriangles()->size() / 3; Objects[i].setOffsetandCount(sizeFaces, numTriangle); sizeFaces += numTriangle; } float* BufferData = new float [sizeFaces * (3+3+2)]; int cont = 0; for (int i = 0; i < size; i++) { std::vector<unsigned int>* faces = Objects[i].getTriangles(); int sizeFace = faces->size(); for (int j = 0; j < sizeFace; j += 3, cont += 8) { BufferData[cont] = Vertexs[(*faces)[j]].x; BufferData[cont + 1] = Vertexs[(*faces)[j]].y; BufferData[cont + 2] = Vertexs[(*faces)[j]].z; BufferData[cont + 3] = Normals[(*faces)[j + 1]].x; BufferData[cont + 4] = Normals[(*faces)[j + 1]].y; BufferData[cont + 5] = Normals[(*faces)[j + 1]].z; BufferData[cont + 6] = Uvs[(*faces)[j + 2]].x; BufferData[cont + 7] = Uvs[(*faces)[j + 2]].y; } } glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, (sizeFaces * 8) * sizeof(float), BufferData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(sizeof(float) * 3)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(sizeof(float) * 6)); delete BufferData; glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Mesh::render(GLuint MaterialAmbientID, GLuint MaterialDiffuseID, GLuint MaterialSpecularID, GLuint ShinninesID) { glBindVertexArray(VertexArrayID); unsigned int size = Objects.size(); for (int i = 0; i < size; i++) Objects[i].render(MaterialAmbientID, MaterialDiffuseID, MaterialSpecularID, ShinninesID); }
23.092199
210
0.636364
miky-kr5
b9198bf3a63ba8bacd1b900e3415c97b43e10b6c
667
hpp
C++
library/cgp/containers/buffer_stack/buffer_stack.hpp
drohmer/CGP
3e7651649320d0bff19394ecd9546e872802c3e7
[ "MIT" ]
null
null
null
library/cgp/containers/buffer_stack/buffer_stack.hpp
drohmer/CGP
3e7651649320d0bff19394ecd9546e872802c3e7
[ "MIT" ]
2
2022-03-03T16:34:03.000Z
2022-03-20T13:08:56.000Z
library/cgp/containers/buffer_stack/buffer_stack.hpp
drohmer/CGP
3e7651649320d0bff19394ecd9546e872802c3e7
[ "MIT" ]
null
null
null
#pragma once namespace cgp { /** Base class for small fixed-size vectors (vec3, mat3, etc.). * buffer_stack structure is a generic fixed-size vector, essentially equivalent to a std::array. * In addition to std::array syntax, buffer_stack provides extra convenient functions (similar to buffer) for numerical vectors +, -, *, / as well as strict bounds checking. */ // template <typename T, int N> struct buffer_stack; } #include "implementation/buffer_stack.hpp" #include "implementation/buffer_stack2.hpp" #include "implementation/buffer_stack3.hpp" #include "implementation/buffer_stack4.hpp" #include "special_types/special_types.hpp"
33.35
177
0.746627
drohmer
b91a0929fd33b9d9782b9e9cf0f184828ac08702
4,342
cpp
C++
solved-topcoder/Solved/CatsOnTheLineDiv2.cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2019-03-31T05:47:30.000Z
2019-03-31T05:47:30.000Z
solved-topcoder/Solved/CatsOnTheLineDiv2.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
solved-topcoder/Solved/CatsOnTheLineDiv2.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
/** * @author : Maruf Tuhin * @School : CUET CSE 11 * @Topcoder : the_redback * @CodeForces : the_redback * @UVA : the_redback * @link : http://www.fb.com/maruf.2hin */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long llu; #define ft first #define sd second #define mp make_pair #define pb(x) push_back(x) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define mem(a,b) memset(a,b,sizeof(a)) #define meminf(a) memset(a,126,sizeof(a)) #define inf 1e7 #define eps 1e-9 #define mod 1000000007 #define NN 10100 #define z 4000 //cout << setfill('0') << setw(3) << a << endl; //cout << fixed << setprecision(20) << a << endl; struct D { int pos,cnt; }a[60]; bool flag[NN]; bool comp(D aa,D bb) { return aa.pos<bb.pos; } struct CatsOnTheLineDiv2 { string getAnswer(vector <int> position, vector <int> count, int time) { string ret; int n=count.size(); int i,j,k,l; for(i=0;i<count.size();i++) { a[i].pos=position[i]; a[i].cnt=count[i]; } sort(a,a+n,comp); mem(flag,0); int low=-inf; int high=inf; for(i=0;i<n;i++) { low=a[i].pos-time+z; high=a[i].pos+time+z; int cnt=0; while(low<=high && cnt<a[i].cnt) { if(flag[low]==0) { cnt++; flag[low]=1; } low++; } if(cnt<a[i].cnt) return "Impossible"; } return "Possible"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {7}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "Possible"; verify_case(0, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {8}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; string Arg3 = "Impossible"; verify_case(1, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {0, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; string Arg3 = "Impossible"; verify_case(2, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {5, 0, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2, 3, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; string Arg3 = "Impossible"; verify_case(3, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_4() { int Arr0[] = {5, 1, -10, 7, 12, 2, 10, 20}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 4, 2, 7, 1, 4, 3, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; string Arg3 = "Possible"; verify_case(4, Arg3, getAnswer(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CatsOnTheLineDiv2 ___test; ___test.run_test(-1); int gbase; cin>>gbase; // erase this line if you are not using dev-cpp! :) return 0; } // END CUT HERE
38.767857
329
0.544219
Maruf-Tuhin
b91cd44ed44c1025090cacadecbf00e4dc36bf25
924
cpp
C++
src/reconstruct.cpp
ckpwinters/StereoTracking
f7e2c52c0c4481303560a1d03603a9d4971e8103
[ "BSD-2-Clause" ]
null
null
null
src/reconstruct.cpp
ckpwinters/StereoTracking
f7e2c52c0c4481303560a1d03603a9d4971e8103
[ "BSD-2-Clause" ]
null
null
null
src/reconstruct.cpp
ckpwinters/StereoTracking
f7e2c52c0c4481303560a1d03603a9d4971e8103
[ "BSD-2-Clause" ]
null
null
null
// // Created by lab on 16-12-27. // #include "reconstruct.h" namespace tracker{ void Triangulate::Reconstruct3d(vector<Point2f> &matched_L, vector<Point2f> &matched_R, vector<Point3f> &coord_3d) { size_t num_points=matched_L.size(); //double pixel_size=4.65e-3; //Z=b*f/d float d,Z,Y,X; //cout<<"debug info.."<<endl; for(size_t i=0;i<num_points;i++) { //* Transform them into the same world coordinate. d=matched_L[i].x-matched_R[i].x; Z=baseline*f/(d*pixel_size); Y=pixel_size*Z*(matched_L[i].y-this->camera_matrix.at<float>(1,2))/f; X=pixel_size*Z*(matched_L[i].x-this->camera_matrix.at<float>(0,2))/f; //cout<<"X["<<i<<"]:"<<X<<endl; //* Cartesian coordinate system.(0,0,0) is right at perspective point coord_3d.push_back(Point3d(X,-Y,-Z)); } } }
31.862069
120
0.568182
ckpwinters
b91db10327c3d0428aae74a5859d9e53fa213c76
1,898
cpp
C++
src/persistence/assetdb.cpp
nondejus/WaykiChain
dddd2b882f380e416b3069155bb3431fd5627258
[ "MIT" ]
1
2020-02-27T00:29:05.000Z
2020-02-27T00:29:05.000Z
src/persistence/assetdb.cpp
nondejus/WaykiChain
dddd2b882f380e416b3069155bb3431fd5627258
[ "MIT" ]
null
null
null
src/persistence/assetdb.cpp
nondejus/WaykiChain
dddd2b882f380e416b3069155bb3431fd5627258
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2017-2019 The WaykiChain Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assetdb.h" #include "commons/uint256.h" #include "commons/util/util.h" #include <stdint.h> using namespace std; bool CAssetDBCache::GetAsset(const TokenSymbol &tokenSymbol, CAsset &asset) { return assetCache.GetData(tokenSymbol, asset); } bool CAssetDBCache::HaveAsset(const TokenSymbol &tokenSymbol) { return assetCache.HaveData(tokenSymbol); } bool CAssetDBCache::SaveAsset(const CAsset &asset) { return assetCache.SetData(asset.symbol, asset); } bool CAssetDBCache::ExistAssetSymbol(const TokenSymbol &tokenSymbol) { return assetCache.HaveData(tokenSymbol); } shared_ptr<string> CAssetDBCache::CheckTransferCoinSymbol(const TokenSymbol &symbol) { size_t coinSymbolSize = symbol.size(); if (coinSymbolSize == 0 || coinSymbolSize > MAX_TOKEN_SYMBOL_LEN) { return make_shared<string>("empty or too long"); } if ((coinSymbolSize < MIN_ASSET_SYMBOL_LEN && !kCoinTypeSet.count(symbol)) || (coinSymbolSize >= MIN_ASSET_SYMBOL_LEN && !HaveAsset(symbol))) return make_shared<string>("unsupported symbol"); return nullptr; } bool CAssetDBCache::AddAssetTradingPair(const CAssetTradingPair &assetTradingPair) { return assetTradingPairCache.SetData(assetTradingPair, 1); } bool CAssetDBCache::EraseAssetTradingPair(const CAssetTradingPair &assetTradingPair) { return assetTradingPairCache.EraseData(assetTradingPair); } bool CAssetDBCache::ExistAssetTradingPair(const CAssetTradingPair &assetTradingPair) { return assetTradingPairCache.HaveData(assetTradingPair); } bool CAssetDBCache::Flush() { assetCache.Flush(); assetTradingPairCache.Flush(); return true; }
33.298246
86
0.763435
nondejus
b91ed1f420de1fbaef1d34e93f766b5a45b22d93
2,411
cc
C++
tests/json-test.cc
kikairoya/black_circle
f3d8b90c9ddc76561d6ddc5e29e5e8fc8d3318c6
[ "BSL-1.0" ]
1
2016-06-20T21:16:36.000Z
2016-06-20T21:16:36.000Z
tests/json-test.cc
kikairoya/black_circle
f3d8b90c9ddc76561d6ddc5e29e5e8fc8d3318c6
[ "BSL-1.0" ]
null
null
null
tests/json-test.cc
kikairoya/black_circle
f3d8b90c9ddc76561d6ddc5e29e5e8fc8d3318c6
[ "BSL-1.0" ]
null
null
null
#include <common.hpp> #include "json_parser.hpp" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> using namespace circle; template <typename T> inline T clone(const T &v) { return v; } template <typename T> struct object_type { typedef T type; }; template <> struct object_type<int> { typedef circle::int64_t type; }; template <> struct object_type<unsigned> { typedef circle::int64_t type; }; template <> struct object_type<char *> { typedef string type; }; template <> struct object_type<const char *> { typedef string type; }; template <size_t N> struct object_type<char [N]> { typedef string type; }; template <size_t N> struct object_type<const char [N]> { typedef string type; }; struct insert_object_t { insert_object_t(json::json_object_map &obj, string &jstr): obj(obj), jstr(jstr), n() { } template <typename T> void operator()(const T &val, const string &vstr) { const string key = "val" + boost::lexical_cast<string>(++n); obj[key] = static_cast<typename object_type<T>::type>(val); jstr.insert(jstr.length()-1, ",\""+key+"\":"+vstr); } json::json_object_map &obj; string &jstr; unsigned n; }; BOOST_AUTO_TEST_CASE(json_parse_test) { BOOST_CHECK(json::parse_json("[]") == json::json_object_value(json::json_array_type())); json::json_object_value obj((json::json_object_map())); json::json_object_map &om = boost::get<json::json_object_map>(obj); BOOST_CHECK(json::parse_json("{}") == obj); string jstr = "{\"null\":null}"; insert_object_t ins(om, jstr); om["null"] = json::null_t(); BOOST_CHECK(json::parse_json(jstr) == obj); ins(10, "10"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(10., "10."); BOOST_CHECK(json::parse_json(jstr) == obj); ins("str", "\"str\""); BOOST_CHECK(json::parse_json(jstr) == obj); ins("", "\"\""); BOOST_CHECK(json::parse_json(jstr) == obj); ins(true, "true"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(false, "false"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(0, "0"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(clone(obj), clone(jstr)); BOOST_CHECK(json::parse_json(jstr) == obj); ins(-5, "-5"); ins(-3., "-3."); ins("3.3", "\"3.3\""); ins("null", "\"null\""); BOOST_CHECK(json::parse_json(jstr) == obj); ins(clone(obj), clone(jstr)); BOOST_CHECK(json::parse_json(jstr) == obj); }
34.942029
90
0.657818
kikairoya
b921915b91c5b1e551985d52111e130b85ffaf2d
781
cpp
C++
3.7.0/lldb-3.7.0.src/test/functionalities/data-formatter/rdar-10887661/main.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
3
2016-02-10T14:18:40.000Z
2018-02-05T03:15:56.000Z
3.7.0/lldb-3.7.0.src/test/functionalities/data-formatter/rdar-10887661/main.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
1
2016-02-10T15:40:03.000Z
2016-02-10T15:40:03.000Z
3.7.0/lldb-3.7.0.src/test/functionalities/data-formatter/rdar-10887661/main.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
null
null
null
struct foo { int a; int b; int c; int d; int e; int f; int g; int h; int i; int j; int k; int l; int m; int n; int o; int p; int q; int r; foo(int X) : a(X), b(X+1), c(X+3), d(X+5), e(X+7), f(X+9), g(X+11), h(X+13), i(X+15), j(X+17), k(X+19), l(X+21), m(X+23), n(X+25), o(X+27), p(X+29), q(X+31), r(X+33) {} }; struct wrapint { int x; wrapint(int X) : x(X) {} }; int main() { foo f00_1(0); foo *f00_ptr = new foo(12); f00_1.a++; // Set break point at this line. wrapint test_cast('A' + 256*'B' + 256*256*'C'+ 256*256*256*'D'); return 0; }
12.596774
47
0.372599
androm3da
b9234d0993e65bdc8336c96fb359568a72186ab2
4,024
hpp
C++
third_party/omr/jitbuilder/apigen/extras/cpp/Macros.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/jitbuilder/apigen/extras/cpp/Macros.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/jitbuilder/apigen/extras/cpp/Macros.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2018, 2018 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #ifndef CPP_BINDING_RUNTIME_INCL #define CPP_BINDING_RUNTIME_INCL #define TOSTR(x) #x #define LINETOSTR(x) TOSTR(x) #define ARG_SETUP(baretype, ptrImpl, byVarArg, parmArg) \ TR::baretype *ptrImpl = NULL; \ TR::baretype **byVarArg = NULL; \ if (parmArg) \ { \ byVarArg = &ptrImpl; \ if (*parmArg) \ ptrImpl = reinterpret_cast<TR::baretype *>((*parmArg)->_impl); \ } #define ARG_RETURN(baretype, ptrImpl, parmArg) \ if (parmArg) \ { \ GET_CLIENT_OBJECT(clientObj, baretype, ptrImpl); \ *parmArg = clientObj; \ } #define ARRAY_ARG_SETUP(baretype, arraySize, arrayImpl, parmArg) \ TR::baretype **arrayImpl = new TR::baretype *[arraySize]; \ for (uint32_t i=0;i < arraySize;i++) \ { \ if (parmArg[i] != NULL) \ arrayImpl[i] = reinterpret_cast<TR::baretype *>((parmArg[i])->_impl); \ else \ arrayImpl[i] = NULL; \ } #define ARRAY_ARG_RETURN(baretype, arraySize, arrayImpl, parmArg) \ for (uint32_t i=0;i < arraySize;i++) \ { \ if (arrayImpl[i] != NULL) \ { \ GET_CLIENT_OBJECT(clientObj, baretype, arrayImpl[i]) \ parmArg[i] = clientObj; \ } \ else \ parmArg[i] = NULL; \ } // This macro defines clientObj in the scope where macro is used #define GET_CLIENT_OBJECT(clientObj, baretype, implObj) \ baretype *clientObj = NULL; \ if (implObj != NULL) \ { \ clientObj = reinterpret_cast<baretype *>(implObj->client()); \ } #endif // defined(CPP_BINDING_RUNTIME_INCL)
51.589744
135
0.430666
xiacijie
b9239bd6aab5a02618bd9690189e4f56dfd69d09
2,456
cpp
C++
Receiver/DailyDataEntry.cpp
Engin-Boot/visit-case-s1b3
60e9ca88fa3f388d769f56e7346a1e9e971b4c91
[ "MIT" ]
null
null
null
Receiver/DailyDataEntry.cpp
Engin-Boot/visit-case-s1b3
60e9ca88fa3f388d769f56e7346a1e9e971b4c91
[ "MIT" ]
null
null
null
Receiver/DailyDataEntry.cpp
Engin-Boot/visit-case-s1b3
60e9ca88fa3f388d769f56e7346a1e9e971b4c91
[ "MIT" ]
null
null
null
#include "DailyDataEntry.h" //splits the input string by spaces //returns a vector of words vector<string> splitStringBySpaces(string str) { //declaration of empty vector //will contain words vector<string> singleDayEntry; //initialized new word string word = ""; //traverse input string for (unsigned int i_char = 0; i_char < str.length(); i_char++) { if (str[i_char] != ' ') { //adding characters to the word word = word + str[i_char]; } else { //pushing single word of input string into vector singleDayEntry.push_back(word); //initialized next new word word = ""; } } //pushing single word of input string into vector singleDayEntry.push_back(word); //return vector of words return singleDayEntry; } //default constructor DailyDataEntry::DailyDataEntry() {} //parameterized constructor //initialize data member DailyDataEntry::DailyDataEntry(const string &date, int day, int numberOfEntries) : date(date), day(day), numberOfEntries(numberOfEntries) {} //getter for date std::string DailyDataEntry::getDate() { return date; } //getter for day int DailyDataEntry::getDay() { return day; } //getter for numberOfEntries int DailyDataEntry::getNumberOfEntries() { return numberOfEntries; } //return a vector of DailyDataEntry object type //vector has all the data needed for calculating aggregates vector<DailyDataEntry> DailyDataEntry::getDailyDataEntryFromSender(const vector<vector<string>> &senderData) { //check for input if (senderData.empty()) throw runtime_error("No Input"); //number of input strings unsigned int n = senderData.size(); //declare vector of DailtDataEntry type vector<DailyDataEntry> monthlyEntryData; //traverse each vector of string for (unsigned int i_singleDayEntry = 0; i_singleDayEntry < n; i_singleDayEntry++) { //create a DailyDataEntry object having date day numberOfEntries DailyDataEntry data(senderData.at(i_singleDayEntry).at(0), stoi(senderData.at(i_singleDayEntry).at(1)), stoi(senderData.at(i_singleDayEntry).at(2))); //write single day data (DailyDataEntry object) into vector monthlyEntryData.push_back(data); } //return vector having all sender data return monthlyEntryData; }
29.238095
108
0.670195
Engin-Boot
b9243933db9eeb3db42009eb0243dccc3fc203f0
10,105
cpp
C++
Source/Samples/41_DatabaseDemo/DatabaseDemo.cpp
ArnisLielturks/GameOff2017-WildDimension
16d5cd0a0a7c8c520bee974f008ba719e37c996f
[ "MIT" ]
3
2017-09-18T02:18:49.000Z
2021-04-10T00:17:15.000Z
Source/Samples/41_DatabaseDemo/DatabaseDemo.cpp
ArnisLielturks/GameOff2017-WildDimension
16d5cd0a0a7c8c520bee974f008ba719e37c996f
[ "MIT" ]
1
2017-09-18T06:05:25.000Z
2017-09-18T06:05:25.000Z
Source/Samples/41_DatabaseDemo/DatabaseDemo.cpp
pengfei666/Urho3D
80658b06596e17e89278dde8e9a6cbe9375c7cee
[ "MIT" ]
null
null
null
// // Copyright (c) 2008-2017 the Urho3D project. // // 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 <Urho3D/Core/CoreEvents.h> #include <Urho3D/Core/ProcessUtils.h> #include <Urho3D/Database/Database.h> #include <Urho3D/Database/DatabaseEvents.h> #include <Urho3D/Engine/Console.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Engine/EngineEvents.h> #include <Urho3D/Input/Input.h> #include <Urho3D/IO/Log.h> #include <Urho3D/UI/Button.h> #include "DatabaseDemo.h" // Expands to this example's entry-point URHO3D_DEFINE_APPLICATION_MAIN(DatabaseDemo) DatabaseDemo::DatabaseDemo(Context* context) : Sample(context), connection_(nullptr), row_(0), maxRows_(50) { } DatabaseDemo::~DatabaseDemo() { // Although the managed database connection will be disconnected by Database subsystem automatically in its destructor, // it is a good practice for a class to balance the number of connect() and disconnect() calls. GetSubsystem<Database>()->Disconnect(connection_); connection_ = nullptr; } void DatabaseDemo::Start() { // Execute base class startup Sample::Start(); // Subscribe to console commands and the frame update SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(DatabaseDemo, HandleConsoleCommand)); SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(DatabaseDemo, HandleUpdate)); // Subscribe key down event SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(DatabaseDemo, HandleEscKeyDown)); // Hide logo to make room for the console SetLogoVisible(false); // Show the console by default, make it large. Console will show the text edit field when there is at least one // subscriber for the console command event Console* console = GetSubsystem<Console>(); console->SetNumRows((unsigned)(GetSubsystem<Graphics>()->GetHeight() / 16)); console->SetNumBufferedRows(2 * console->GetNumRows()); console->SetCommandInterpreter(GetTypeName()); console->SetVisible(true); console->GetCloseButton()->SetVisible(false); // Show OS mouse cursor GetSubsystem<Input>()->SetMouseVisible(true); // Set the mouse mode to use in the sample Sample::InitMouseMode(MM_FREE); // Open the operating system console window (for stdin / stdout) if not open yet OpenConsoleWindow(); // In general, the connection string is really the only thing that need to be changed when switching underlying database API // and that when using ODBC API then the connection string must refer to an already installed ODBC driver // Although it has not been tested yet but the ODBC API should be able to interface with any vendor provided ODBC drivers // In this particular demo, however, when using ODBC API then the SQLite-ODBC driver need to be installed // The SQLite-ODBC driver can be built from source downloaded from http://www.ch-werner.de/sqliteodbc/ // You can try to install other ODBC driver and modify the connection string below to match your ODBC driver // Both DSN and DSN-less connection string should work // The ODBC API, i.e. URHO3D_DATABASE_ODBC build option, is only available for native (including RPI) platforms // and it is designed for development of game server connecting to ODBC-compliant databases in mind // This demo will always work when using SQLite API as the SQLite database engine is embedded inside Urho3D game engine // and this is also the case when targeting Web platform // We could have used #ifdef to init the connection string during compile time, but below shows how it is done during runtime // The "URHO3D_DATABASE_ODBC" compiler define is set when URHO3D_DATABASE_ODBC build option is enabled // Connect to a temporary in-memory SQLite database connection_ = GetSubsystem<Database>()->Connect(Database::GetAPI() == DBAPI_ODBC ? "Driver=SQLite3;Database=:memory:" : "file://"); // Subscribe to database cursor event to loop through query resultset SubscribeToEvent(E_DBCURSOR, URHO3D_HANDLER(DatabaseDemo, HandleDbCursor)); // Show instruction Print("This demo connects to temporary in-memory database.\n" "All the tables and their data will be lost after exiting the demo.\n" "Enter a valid SQL statement in the console input and press Enter to execute.\n" "Enter 'get/set maxrows [number]' to get/set the maximum rows to be printed out.\n" "Enter 'get/set connstr [string]' to get/set the database connection string and establish a new connection to it.\n" "Enter 'quit' or 'exit' to exit the demo.\n" "For example:\n "); HandleInput("create table tbl1(col1 varchar(10), col2 smallint)"); HandleInput("insert into tbl1 values('Hello', 10)"); HandleInput("insert into tbl1 values('World', 20)"); HandleInput("select * from tbl1"); } void DatabaseDemo::HandleConsoleCommand(StringHash eventType, VariantMap& eventData) { using namespace ConsoleCommand; if (eventData[P_ID].GetString() == GetTypeName()) HandleInput(eventData[P_COMMAND].GetString()); } void DatabaseDemo::HandleUpdate(StringHash eventType, VariantMap& eventData) { // Check if there is input from stdin String input = GetConsoleInput(); if (input.Length()) HandleInput(input); } void DatabaseDemo::HandleEscKeyDown(StringHash eventType, VariantMap& eventData) { // Unlike the other samples, exiting the engine when ESC is pressed instead of just closing the console if (eventData[KeyDown::P_KEY].GetInt() == KEY_ESCAPE) engine_->Exit(); } void DatabaseDemo::HandleDbCursor(StringHash eventType, VariantMap& eventData) { using namespace DbCursor; // In a real application the P_SQL can be used to do the logic branching in a shared event handler // However, this is not required in this sample demo unsigned numCols = eventData[P_NUMCOLS].GetUInt(); const VariantVector& colValues = eventData[P_COLVALUES].GetVariantVector(); const Vector<String>& colHeaders = eventData[P_COLHEADERS].GetStringVector(); // In this sample demo we just use db cursor to dump each row immediately so we can filter out the row to conserve memory // In a real application this can be used to perform the client-side filtering logic eventData[P_FILTER] = true; // In this sample demo we abort the further cursor movement when maximum rows being dumped has been reached eventData[P_ABORT] = ++row_ >= maxRows_; for (unsigned i = 0; i < numCols; ++i) Print(ToString("Row #%d: %s = %s", row_, colHeaders[i].CString(), colValues[i].ToString().CString())); } void DatabaseDemo::HandleInput(const String& input) { // Echo input string to stdout Print(input); row_ = 0; if (input == "quit" || input == "exit") engine_->Exit(); else if (input.StartsWith("set") || input.StartsWith("get")) { // We expect a key/value pair for 'set' command Vector<String> tokens = input.Substring(3).Split(' '); String setting = tokens.Size() ? tokens[0] : ""; if (input.StartsWith("set") && tokens.Size() > 1) { if (setting == "maxrows") maxRows_ = Max(ToUInt(tokens[1]), 1U); else if (setting == "connstr") { String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1)); Database* database = GetSubsystem<Database>(); DbConnection* newConnection = database->Connect(newConnectionString); if (newConnection) { database->Disconnect(connection_); connection_ = newConnection; } } } if (tokens.Size()) { if (setting == "maxrows") Print(ToString("maximum rows is set to %d", maxRows_)); else if (setting == "connstr") Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString())); else Print(ToString("Unrecognized setting: %s", setting.CString())); } else Print("Missing setting paramater. Recognized settings are: maxrows, connstr"); } else { // In this sample demo we use the dbCursor event to loop through each row as it is being fetched // Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object, // unless the dbCursor event handler has instructed to filter out the fetched row from the final result DbResult result = connection_->Execute(input, true); // Number of affected rows is only meaningful for DML statements like insert/update/delete if (result.GetNumAffectedRows() != -1) Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows())); } Print(" "); } void DatabaseDemo::Print(const String& output) { // Logging appears both in the engine console and stdout URHO3D_LOGRAW(output + "\n"); }
44.911111
129
0.696388
ArnisLielturks
b9276fe0778cf75a47bed12cbb39206cb2df35d4
2,662
cpp
C++
third_party/WebKit/Source/core/css/cssom/CSSLengthValue.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/core/css/cssom/CSSLengthValue.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/css/cssom/CSSLengthValue.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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 "core/css/cssom/CSSLengthValue.h" #include "bindings/core/v8/ExceptionState.h" #include "core/css/CSSPrimitiveValue.h" #include "core/css/cssom/CSSCalcDictionary.h" #include "core/css/cssom/CSSCalcLength.h" #include "core/css/cssom/CSSSimpleLength.h" #include "wtf/HashMap.h" namespace blink { CSSPrimitiveValue::UnitType CSSLengthValue::unitFromName(const String& name) { if (equalIgnoringASCIICase(name, "percent") || name == "%") return CSSPrimitiveValue::UnitType::Percentage; return CSSPrimitiveValue::stringToUnitType(name); } CSSLengthValue* CSSLengthValue::from(const String& cssText, ExceptionState& exceptionState) { // TODO: Implement return nullptr; } CSSLengthValue* CSSLengthValue::from(double value, const String& type, ExceptionState&) { return CSSSimpleLength::create(value, unitFromName(type)); } CSSLengthValue* CSSLengthValue::from(const CSSCalcDictionary& dictionary, ExceptionState& exceptionState) { return CSSCalcLength::create(dictionary, exceptionState); } CSSLengthValue* CSSLengthValue::add(const CSSLengthValue* other, ExceptionState& exceptionState) { if (type() == other->type() || type() == CalcLengthType) return addInternal(other, exceptionState); CSSCalcLength* result = CSSCalcLength::create(this, exceptionState); return result->add(other, exceptionState); } CSSLengthValue* CSSLengthValue::subtract(const CSSLengthValue* other, ExceptionState& exceptionState) { if (type() == other->type() || type() == CalcLengthType) return subtractInternal(other, exceptionState); CSSCalcLength* result = CSSCalcLength::create(this, exceptionState); return result->subtract(other, exceptionState); } CSSLengthValue* CSSLengthValue::multiply(double x, ExceptionState& exceptionState) { return multiplyInternal(x, exceptionState); } CSSLengthValue* CSSLengthValue::divide(double x, ExceptionState& exceptionState) { return divideInternal(x, exceptionState); } CSSLengthValue* CSSLengthValue::addInternal(const CSSLengthValue*, ExceptionState&) { NOTREACHED(); return nullptr; } CSSLengthValue* CSSLengthValue::subtractInternal(const CSSLengthValue*, ExceptionState&) { NOTREACHED(); return nullptr; } CSSLengthValue* CSSLengthValue::multiplyInternal(double, ExceptionState&) { NOTREACHED(); return nullptr; } CSSLengthValue* CSSLengthValue::divideInternal(double, ExceptionState&) { NOTREACHED(); return nullptr; } } // namespace blink
28.934783
105
0.755071
Wzzzx
b92a97394e9a2d6911e2afd3285f946db277388b
3,101
cpp
C++
src/ADBSCEditDLL/test/misc-regex/CppRegex.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
9
2019-05-20T12:06:36.000Z
2022-03-24T19:11:06.000Z
src/ADBSCEditDLL/test/misc-regex/CppRegex.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
null
null
null
src/ADBSCEditDLL/test/misc-regex/CppRegex.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
3
2020-07-06T04:51:33.000Z
2021-07-26T20:08:02.000Z
/* MIT License Android remote Viewer, GUI ADB tools Android Viewer developed to view and control your android device from a PC. ADB exchange Android Viewer, support scale view, input tap from mouse, input swipe from keyboard, save/copy screenshot, etc.. Copyright (c) 2016-2019 PS GitHub: https://github.com/ClnViewer/ADB-Android-Viewer GitHub: https://github.com/ClnViewer/ADB-Android-Viewer/ADBSCEditDLL/ADBSCEdit 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, sub license, 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 <string> #include <iostream> #include <regex> #include <filesystem> #include "../../../ADBViewer/src/version.h" namespace fs = std::filesystem; const char *str[] = { "class.function()", "class:function()", "function()", " -- 373 | 14 | LOAD \"The table the script received has:\n\"", " -- 6 | 16 | GET [LuaObject]", " -- 67 | 18 | GET", " HYPERLINK \"THELP_APP\"Hot keys help\r" // "^\s+(HYPERLINK)\s+\"(\w+)\"(.*)\r$" }; int main(int32_t argc, char *argv[]) { if (argc < 3) { fs::path l_exec{ argv[0] }; std::cout << " * version: " << AVIEW_FULLVERSION_STRING << " - " << __DATE__ << std::endl; std::cout << " * using : " << l_exec.filename().generic_string().c_str() << " <0-6> <ECMAScript regex>" << std::endl; std::cout << std::endl << " ! Bad arguments.." << std::endl; return 0; } try { int32_t idx = std::stoi(argv[1]); idx = ((idx > 6) ? 6 : idx); std::string s(str[idx]); std::string r(argv[2]); const std::regex re( r.c_str(), std::regex::ECMAScript ); std::smatch m; bool b = regex_search(s, m, re); std::cout << "\n\tSearch: " << s.c_str() << std::endl; uint32_t cnt = 1U; for (auto & x : m) std::cout << "\t" << cnt++ << ": " << x <<"\n"; std::cout << "\n\tFound: " << b << " - " << m.size() << std::endl; } catch (std::exception const & ex) { std::cout << "\n\tException: " << ex.what() << std::endl; } return 0; }
34.076923
126
0.618188
ClnViewer
b92e03fdb156047b17616f50b4781434b52ec305
1,120
cpp
C++
Week-1/Day-07-wordPattern.cpp
utkarshavardhana/september-leetcoding-challenge
4e188ea914eea331ab3b032571640c82048e136d
[ "MIT" ]
null
null
null
Week-1/Day-07-wordPattern.cpp
utkarshavardhana/september-leetcoding-challenge
4e188ea914eea331ab3b032571640c82048e136d
[ "MIT" ]
null
null
null
Week-1/Day-07-wordPattern.cpp
utkarshavardhana/september-leetcoding-challenge
4e188ea914eea331ab3b032571640c82048e136d
[ "MIT" ]
null
null
null
class Solution { public: bool wordPattern(string pattern, string str) { vector<string> words = split(str, ' '); map<char, string> table; if (pattern.size() != words.size()) { return false; } for (auto i = 0; i < pattern.size(); ++ i) { auto c = pattern[i]; auto iter = table.find(c); if (iter == table.end()) { for (auto item : table) { if (item.second == words[i]) { return false; } } table.insert(make_pair(c, words[i])); } else { if (iter->second != words[i]) { return false; } } } return true; } vector<string> split(const std::string& str, char delim) { vector<string> words; stringstream ss; ss.str(str); string item; while (getline(ss, item, delim)) { words.push_back(item); } return std::move(words); } };
28.717949
60
0.415179
utkarshavardhana
b92edfa72761efd2e0b504500bb865be9cbbdc31
29,858
hpp
C++
src/axom/core/Array.hpp
LLNL/axom
5f72c784afe953767e773b2fe7df428d006ee113
[ "BSD-3-Clause" ]
86
2019-04-12T20:39:37.000Z
2022-01-28T17:06:08.000Z
src/axom/core/Array.hpp
LLNL/axom
5f72c784afe953767e773b2fe7df428d006ee113
[ "BSD-3-Clause" ]
597
2019-04-25T22:36:16.000Z
2022-03-31T20:21:54.000Z
src/axom/core/Array.hpp
LLNL/axom
5f72c784afe953767e773b2fe7df428d006ee113
[ "BSD-3-Clause" ]
21
2019-06-27T15:53:08.000Z
2021-09-30T20:17:41.000Z
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #ifndef AXOM_ARRAY_HPP_ #define AXOM_ARRAY_HPP_ #include "axom/config.hpp" // for compile-time defines #include "axom/core/Macros.hpp" // for axom macros #include "axom/core/memory_management.hpp" // for memory allocation functions #include "axom/core/utilities/Utilities.hpp" // for processAbort() #include "axom/core/Types.hpp" // for IndexType definition #include "axom/core/ArrayBase.hpp" #include "axom/core/ArrayIteratorBase.hpp" // C/C++ includes #include <algorithm> // for std::transform #include <iostream> // for std::cerr and std::ostream namespace axom { // TODO: Add this as a non-type template parameter to Array/View // The intent is that there will also be a "Dynamic" or "Polymorphic" // resource type // enum MemoryResourceType // { // Host, // Device, // Unified, // Pinned, // Constant, // File, // NoOp, // Shared, // Unknown // }; // Forward declare the templated classes and operator function(s) template <typename T, int DIM> class Array; /*! * \class Array * * \brief Provides a generic multidimensional array container. * * The Array class provides a generic multidimensional array * container with dynamic reallocation and insertion. The dimensionality * of the array must be known at compile time but the extents in each dimension * are dynamic and can be changed at runtime. Array elements are stored * contiguously. * * \note For a multi-component array container, where each element * is a tuple of 1 or more components, Axom provides the MCArray alias, which * corresponds to Array<T, 2>. * * The Array class mirrors std::vector, with future support for GPUs * in-development. The class's multidimensional array functionality roughly mirrors the multidimensional array support provided by numpy's ndarray. * * \see https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html * * This class is meant to be a drop-in replacement for std::vector. * However, it differs in its memory management and construction semantics. * Specifically, we do not require axom::Array to initialize/construct * its memory at allocation time and we use axom's memory_management * and allocator ID abstractions rather than std::allocator. * * Array always retains exclusive ownership of its data and is responsible for * freeing its memory. * * \see ArrayView for non-owning views of one- or multi-dimensional data * Depending on which constructor is used, the Array object can have two * different underlying storage types: * * \tparam T the type of the values to hold. * \tparam DIM The dimension of the array. * * \pre T must be CopyAssignable and Erasable * \see https://en.cppreference.com/w/cpp/named_req * */ template <typename T, int DIM = 1> class Array : public ArrayBase<T, DIM, Array<T, DIM>> { public: static constexpr double DEFAULT_RESIZE_RATIO = 2.0; static constexpr IndexType MIN_DEFAULT_CAPACITY = 32; using value_type = T; using ArrayIterator = ArrayIteratorBase<Array<T, DIM>>; public: /// \name Native Storage Array Constructors /// @{ /*! * \brief Default constructor. Constructs an Array instance with no elements * and default allocator ID. * */ Array(); /*! * \brief Constructs a 1D Array instance with the given number of elements. * * \param [in] num_elements the number of elements the Array holds. * \param [in] capacity the number of elements to allocate space for. * \param [in] allocator_id the ID of the allocator to use (optional) * * \note If no capacity or capacity less than num_elements is specified * then it will default to at least num_elements * DEFAULT_RESIZE_RATIO. * \note a capacity is specified for the number of elements to store in the * array and does not correspond to the actual bytesize. * \note The option to select a capacity is only available for 1-dimensional Arrays * * \pre num_elements >= 0 * * \post capacity() >= size() * \post size() == num_elements * \post getResizeRatio() == DEFAULT_RESIZE_RATIO */ template <IndexType SFINAE = DIM, typename std::enable_if<SFINAE == 1>::type* = nullptr> Array(IndexType num_elements, IndexType capacity = 0, int allocator_id = axom::getDefaultAllocatorID()); /*! * \brief Generic constructor for an Array of arbitrary dimension * * \param [in] args The parameter pack containing the "shape" of the Array * \see https://numpy.org/doc/stable/reference/generated/numpy.empty.html#numpy.empty * * \pre sizeof...(Args) == DIM * * \post capacity() >= size() * \post size() == num_elements * \post getResizeRatio() == DEFAULT_RESIZE_RATIO */ template <typename... Args> Array(Args... args); /*! * \brief Copy constructor for an Array instance * * \param [in] allocator_id the ID of the allocator to use (optional) */ Array(const Array& other, int allocator_id = axom::getDefaultAllocatorID()); /*! * \brief Move constructor for an Array instance */ Array(Array&& other); /// @} /// \name Array copy and move operators /// @{ /*! * \brief Copy assignment operator for Array * * \note The data will be allocated using the allocator ID of the * copy-assigned Array, not the argument Array. * * \pre T must be TriviallyCopyable */ Array& operator=(const Array& other) { if(this != &other) { m_resize_ratio = other.m_resize_ratio; initialize(other.size(), other.capacity()); axom::copy(m_data, other.data(), m_num_elements * sizeof(T)); } return *this; } /*! * \brief Move assignment operator for Array */ Array& operator=(Array&& other) { if(this != &other) { if(m_data != nullptr) { axom::deallocate(m_data); } m_data = other.m_data; m_num_elements = other.m_num_elements; m_capacity = other.m_capacity; m_resize_ratio = other.m_resize_ratio; m_allocator_id = other.m_allocator_id; other.m_data = nullptr; other.m_num_elements = 0; other.m_capacity = 0; other.m_resize_ratio = DEFAULT_RESIZE_RATIO; other.m_allocator_id = INVALID_ALLOCATOR_ID; } return *this; } /// @} /*! * Destructor. Frees the associated buffer. */ virtual ~Array(); /// \name Array element access operators /// @{ // TODO: Implement View class for the case where sizeof...(Args) < DIM (i.e., where the indexing results in a nonscalar) /*! * \brief Return a pointer to the array of data. */ /// @{ inline T* data() { return m_data; } inline const T* data() const { return m_data; } /// @} /// @} /// \name Array methods to modify the data. /// @{ /*! * \brief Set all the values of the array. * * \param [in] value the value to set to. */ void fill(const T& value); /*! * \brief Modify the values of existing elements. * * \param [in] elements the new elements to write. * \param [in] n the number of elements to write. * \param [in] pos the position at which to begin writing. * * \note It's assumed that elements is of length n. * \note The size is unchanged by calls to set. * * \pre pos + n <= m_num_elements. */ void set(const T* elements, IndexType n, IndexType pos); /*! * \brief Clears the contents of the array * * \post size of Array is 0 * \post capacity is unchanged */ void clear(); /*! * \brief Insert an element into the array at the given position. * * \param [in] pos the position at which to insert. * \param [in] value the element value to insert. * * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by 1. * */ template <IndexType SFINAE = DIM, typename std::enable_if<SFINAE == 1>::type* = nullptr> void insert(IndexType pos, const T& value); /*! * \brief Insert an element into the array at the value before pos. * * \param [in] pos the ArrayIterator before which value will be inserted. * \param [in] value the element value to insert. * * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by 1. * * \return ArrayIterator to inserted value */ template <IndexType SFINAE = DIM, typename std::enable_if<SFINAE == 1>::type* = nullptr> ArrayIterator insert(ArrayIterator pos, const T& value); /*! * \brief Insert elements into the array at the given position. * * \param [in] pos the position at which to begin the insertion. * \param [in] n the number of elements to insert. * \param [in] values the element values to insert. * * \note It's assumed that elements is of length n. * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by n. * * \pre pos <= m_num_elements. */ void insert(IndexType pos, IndexType n, const T* values); /*! * \brief Insert elements into the array at the value before pos. * * \param [in] pos the ArrayIterator before which value will be inserted. * \param [in] n the number of elements to insert. * \param [in] values the element values to insert. * * \note It's assumed that elements is of length n. * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by n. * * \pre pos <= end() * * \return ArrayIterator to first element inserted (pos if n == 0) */ template <IndexType SFINAE = DIM, typename std::enable_if<SFINAE == 1>::type* = nullptr> ArrayIterator insert(ArrayIterator pos, IndexType n, const T* values); /*! * \brief Insert n copies of element into the array at the given position. * * \param [in] pos the position at which to begin the insertion. * \param [in] n the number of elements to insert. * \param [in] value the element value to insert. * * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by n. * \note This method is used to create space for elements in the middle of * the array. * * \pre pos <= m_num_elements. */ template <IndexType SFINAE = DIM, typename std::enable_if<SFINAE == 1>::type* = nullptr> void insert(IndexType pos, IndexType n, const T& value); /*! * \brief Insert n copies of element into the array at the value before pos. * * \param [in] pos the ArrayIterator before which value will be inserted. * \param [in] n the number of elements to insert. * \param [in] value the element value to insert. * * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by n. * \note This method is used to create space for elements in the middle of * the array. * * \pre pos <= end() * * \return ArrayIterator to first element inserted (pos if n == 0) */ template <IndexType SFINAE = DIM, typename std::enable_if<SFINAE == 1>::type* = nullptr> ArrayIterator insert(ArrayIterator pos, IndexType n, const T& value); // Make the overload "visible" using ArrayBase<T, DIM, Array<T, DIM>>::insert; /*! * \brief Appends an Array to the end of the calling object * * \param [in] other The Array to append * \tparam OtherArrayType The underlying type of the other array * * \note Reallocation is done if the new size will exceed the capacity. */ template <typename OtherArrayType> void append(const ArrayBase<T, DIM, OtherArrayType>& other) { ArrayBase<T, DIM, Array<T, DIM>>::insert(size(), other); } /*! * \brief Erases an element from the Array * * \param [in] pos the ArrayIterator to the element in the Array * * \return An ArrayIterator following the last element removed. */ ArrayIterator erase(ArrayIterator pos); /*! * \brief Erases elements in the range [first, last) from the Array * * \param [in] first the ArrayIterator to the beginning of the range. * \param [in] last the ArrayIterator to end of range. * * \return An ArrayIterator following the last element removed. */ ArrayIterator erase(ArrayIterator first, ArrayIterator last); /*! * \brief Inserts new element into Array at the given position. * * \param [in] pos the position to insert element at. * \param [in] args the arguments to forward to constructor of the element. * * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by 1. * * \pre T must be MoveAssignable */ template <typename... Args> void emplace(IndexType pos, Args&&... args); /*! * \brief Inserts new element into Array before pos. * * \param [in] pos the ArrayIterator to insert element before. * \param [in] args the arguments to forward to constructor of the element. * * \note Reallocation is done if the new size will exceed the capacity. * \note The size increases by 1. * * \pre T must be MoveAssignable * * \return An ArrayIterator to the emplaced element. */ template <typename... Args> ArrayIterator emplace(ArrayIterator pos, Args&&... args); /// @} /// \name Array methods to query and set attributes /// @{ /*! * \brief Return the number of elements allocated for the data array. */ IndexType capacity() const { return m_capacity; } /*! * \brief Increase the capacity. Does nothing if the new capacity is less * than the current capacity. * * \param [in] capacity the new number of elements to allocate. */ void reserve(IndexType capacity) { if(capacity > m_capacity) { setCapacity(capacity); } } /*! * \brief Returns an ArrayIterator to the first element of the Array */ ArrayIterator begin() { assert(m_data != nullptr); return ArrayIterator(0, this); } /*! * \brief Returns an ArrayIterator to the element following the last * element of the Array. */ ArrayIterator end() { assert(m_data != nullptr); return ArrayIterator(size(), this); } /*! * \brief Shrink the capacity to be equal to the size. */ void shrink() { setCapacity(m_num_elements); } /*! * \brief Returns true iff the Array stores no elements. * * \note If the Array is empty the capacity can still be greater than zero. */ bool empty() const { return m_num_elements == 0; } /*! * \brief Return the number of elements stored in the data array. */ inline IndexType size() const { return m_num_elements; } /*! * \brief Update the number of elements stored in the data array. * * \note Reallocation is done if the new size will exceed the capacity. */ template <typename... Args> void resize(Args... args); /*! * \brief Exchanges the contents of this Array with the other. */ void swap(Array<T, DIM>& other); /*! * \brief Get the ratio by which the capacity increases upon dynamic resize. */ double getResizeRatio() const { return m_resize_ratio; } /*! * \brief Set the ratio by which the capacity increases upon dynamic resize. * * \param [in] ratio the new resize ratio. */ void setResizeRatio(double ratio) { m_resize_ratio = ratio; } /*! * \brief Get the ID for the umpire allocator */ int getAllocatorID() const { return m_allocator_id; } /// @} protected: /*! * \brief Initialize an Array instance with the given number of elements. * * \param [in] num_elements the number of elements the Array holds. * \param [in] capacity the number of elements to allocate space for. * * \note If no capacity or capacity less than num_elements is specified * then it will default to at least num_elements * DEFAULT_RESIZE_RATIO. * \note a capacity is specified for the number of elements to store in the * array and does not correspond to the actual bytesize. * * \pre num_elements >= 0 * * \post capacity() >= size() * \post size() == num_elements * \post getResizeRatio() == DEFAULT_RESIZE_RATIO */ void initialize(IndexType num_elements, IndexType capacity); /*! * \brief Make space for a subsequent insertion into the array. * * \param [in] n the number of elements to insert. * \param [in] pos the position at which to begin the insertion. * * \return a pointer to the beginning of the insertion space. * * \note Reallocation is done if the new size will exceed the capacity. */ T* reserveForInsert(IndexType n, IndexType pos); /*! * \brief Update the number of elements. * * \param [in] new_num_elements the new number of elements. */ virtual void updateNumElements(IndexType new_num_elements); /*! * \brief Set the number of elements allocated for the data array. * * \param [in] capacity the new number of elements to allocate. */ virtual void setCapacity(IndexType new_capacity); /*! * \brief Reallocates the data array when the size exceeds the capacity. * * \param [in] new_num_elements the number of elements which exceeds the * current capacity. */ virtual void dynamicRealloc(IndexType new_num_elements); T* m_data = nullptr; /// \brief The full number of elements in the array /// i.e., 3 for a 1D Array of size 3, 9 for a 3x3 2D array, etc IndexType m_num_elements = 0; IndexType m_capacity = 0; double m_resize_ratio = DEFAULT_RESIZE_RATIO; int m_allocator_id; }; /// \brief Helper alias for multi-component arrays template <typename T> using MCArray = Array<T, 2>; //------------------------------------------------------------------------------ // Array IMPLEMENTATION //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ template <typename T, int DIM> Array<T, DIM>::Array() : m_allocator_id(axom::getDefaultAllocatorID()) { } template <typename T, int DIM> template <typename... Args> Array<T, DIM>::Array(Args... args) : ArrayBase<T, DIM, Array<T, DIM>>(args...) , m_allocator_id(axom::getDefaultAllocatorID()) { static_assert(sizeof...(Args) == DIM, "Array size must match number of dimensions"); // Intel hits internal compiler error when casting as part of function call const IndexType tmp_args[] = {args...}; assert(detail::allNonNegative(tmp_args)); initialize(detail::packProduct(tmp_args), 0); } //------------------------------------------------------------------------------ template <typename T, int DIM> template <IndexType SFINAE, typename std::enable_if<SFINAE == 1>::type*> Array<T, DIM>::Array(IndexType num_elements, IndexType capacity, int allocator_id) : m_allocator_id(allocator_id) { initialize(num_elements, capacity); } //------------------------------------------------------------------------------ template <typename T, int DIM> Array<T, DIM>::Array(const Array& other, int allocator_id) : ArrayBase<T, DIM, Array<T, DIM>>( static_cast<const ArrayBase<T, DIM, Array<T, DIM>>&>(other)) , m_allocator_id(allocator_id) { initialize(other.size(), other.capacity()); axom::copy(m_data, other.data(), m_num_elements * sizeof(T)); } //------------------------------------------------------------------------------ template <typename T, int DIM> Array<T, DIM>::Array(Array&& other) : ArrayBase<T, DIM, Array<T, DIM>>( static_cast<ArrayBase<T, DIM, Array<T, DIM>>&&>(std::move(other))) , m_resize_ratio(0.0) , m_allocator_id(axom::getDefaultAllocatorID()) { m_data = other.m_data; m_num_elements = other.m_num_elements; m_capacity = other.m_capacity; m_resize_ratio = other.m_resize_ratio; m_allocator_id = other.m_allocator_id; other.m_data = nullptr; other.m_capacity = 0; other.m_resize_ratio = DEFAULT_RESIZE_RATIO; other.m_allocator_id = INVALID_ALLOCATOR_ID; } //------------------------------------------------------------------------------ template <typename T, int DIM> Array<T, DIM>::~Array() { if(m_data != nullptr) { axom::deallocate(m_data); } m_data = nullptr; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::fill(const T& value) { for(IndexType i = 0; i < m_num_elements; i++) { m_data[i] = value; } } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::set(const T* elements, IndexType n, IndexType pos) { assert(elements != nullptr); assert(pos >= 0); assert(pos + n <= m_num_elements); for(IndexType i = 0; i < n; ++i) { m_data[pos + i] = elements[i]; } } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::clear() { // This most likely needs to be a call to erase() instead. for(IndexType i = 0; i < m_num_elements; ++i) { m_data[i].~T(); } updateNumElements(0); } //------------------------------------------------------------------------------ template <typename T, int DIM> template <IndexType SFINAE, typename std::enable_if<SFINAE == 1>::type*> inline void Array<T, DIM>::insert(IndexType pos, const T& value) { reserveForInsert(1, pos); m_data[pos] = value; } //------------------------------------------------------------------------------ template <typename T, int DIM> template <IndexType SFINAE, typename std::enable_if<SFINAE == 1>::type*> inline typename Array<T, DIM>::ArrayIterator Array<T, DIM>::insert( Array<T, DIM>::ArrayIterator pos, const T& value) { assert(pos >= begin() && pos <= end()); insert(pos - begin(), value); return pos; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::insert(IndexType pos, IndexType n, const T* values) { assert(values != nullptr); reserveForInsert(n, pos); for(IndexType i = 0; i < n; ++i) { m_data[pos + i] = values[i]; } } //------------------------------------------------------------------------------ template <typename T, int DIM> template <IndexType SFINAE, typename std::enable_if<SFINAE == 1>::type*> inline typename Array<T, DIM>::ArrayIterator Array<T, DIM>::insert( Array<T, DIM>::ArrayIterator pos, IndexType n, const T* values) { assert(pos >= begin() && pos <= end()); insert(pos - begin(), n, values); return pos; } //------------------------------------------------------------------------------ template <typename T, int DIM> template <IndexType SFINAE, typename std::enable_if<SFINAE == 1>::type*> inline void Array<T, DIM>::insert(IndexType pos, IndexType n, const T& value) { reserveForInsert(n, pos); for(IndexType i = 0; i < n; ++i) { m_data[pos + i] = value; } } //------------------------------------------------------------------------------ template <typename T, int DIM> template <IndexType SFINAE, typename std::enable_if<SFINAE == 1>::type*> inline typename Array<T, DIM>::ArrayIterator Array<T, DIM>::insert( Array<T, DIM>::ArrayIterator pos, IndexType n, const T& value) { assert(pos >= begin() && pos <= end()); insert(pos - begin(), n, value); return pos; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline typename Array<T, DIM>::ArrayIterator Array<T, DIM>::erase( Array<T, DIM>::ArrayIterator pos) { assert(pos >= begin() && pos < end()); int counter = 0; while(pos < end() - 1) { *pos = *(pos + 1); pos += 1; counter += 1; } (*pos).~T(); updateNumElements(m_num_elements - 1); return pos - counter; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline typename Array<T, DIM>::ArrayIterator Array<T, DIM>::erase( Array<T, DIM>::ArrayIterator first, Array<T, DIM>::ArrayIterator last) { assert(first >= begin() && first < end()); assert(last >= first && last <= end()); // Empty range, return last if(first == last) { return last; } int count = 0; // Erase [first,last) elements while(first < last) { (*first).~T(); first++; count++; } first -= count; int shifted = 0; // Shift [last, end) elements over while(last < end()) { *first = *last; first++; last++; shifted++; } updateNumElements(m_num_elements - count); return first - shifted; } //------------------------------------------------------------------------------ template <typename T, int DIM> template <typename... Args> inline void Array<T, DIM>::emplace(IndexType pos, Args&&... args) { reserveForInsert(1, pos); m_data[pos] = std::move(T(std::forward<Args>(args)...)); } //------------------------------------------------------------------------------ template <typename T, int DIM> template <typename... Args> inline typename Array<T, DIM>::ArrayIterator Array<T, DIM>::emplace( Array<T, DIM>::ArrayIterator pos, Args&&... args) { assert(pos >= begin() && pos <= end()); emplace(pos - begin(), args...); return pos; } //------------------------------------------------------------------------------ template <typename T, int DIM> template <typename... Args> inline void Array<T, DIM>::resize(Args... args) { static_assert(sizeof...(Args) == DIM, "Array size must match number of dimensions"); // Intel hits internal compiler error when casting as part of function call const IndexType tmp_args[] = {args...}; assert(detail::allNonNegative(tmp_args)); const auto new_num_elements = detail::packProduct(tmp_args); static_cast<ArrayBase<T, DIM, Array<T, DIM>>&>(*this) = ArrayBase<T, DIM, Array<T, DIM>> {static_cast<IndexType>(args)...}; if(new_num_elements > m_capacity) { dynamicRealloc(new_num_elements); } updateNumElements(new_num_elements); } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::swap(Array<T, DIM>& other) { ArrayBase<T, DIM, Array<T, DIM>>::swap(other); T* temp_data = m_data; IndexType temp_num_elements = m_num_elements; IndexType temp_capacity = m_capacity; double temp_resize_ratio = m_resize_ratio; m_data = other.m_data; m_num_elements = other.m_num_elements; m_capacity = other.m_capacity; m_resize_ratio = other.m_resize_ratio; other.m_data = temp_data; other.m_num_elements = temp_num_elements; other.m_capacity = temp_capacity; other.m_resize_ratio = temp_resize_ratio; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::initialize(IndexType num_elements, IndexType capacity) { assert(num_elements >= 0); if(capacity < 0 || num_elements > capacity) { capacity = 0; } if(capacity == 0) { capacity = (num_elements > MIN_DEFAULT_CAPACITY) ? num_elements : MIN_DEFAULT_CAPACITY; } setCapacity(capacity); updateNumElements(num_elements); // quick checks assert(m_data != nullptr); assert(m_num_elements >= 0); assert(m_capacity >= m_num_elements); } //------------------------------------------------------------------------------ template <typename T, int DIM> inline T* Array<T, DIM>::reserveForInsert(IndexType n, IndexType pos) { assert(n >= 0); assert(pos >= 0); assert(pos <= m_num_elements); if(n == 0) { return m_data + pos; } IndexType new_size = m_num_elements + n; if(new_size > m_capacity) { dynamicRealloc(new_size); } T* const insert_pos = m_data + pos; T* cur_pos = m_data + m_num_elements - 1; for(; cur_pos >= insert_pos; --cur_pos) { *(cur_pos + n) = *cur_pos; } updateNumElements(new_size); return insert_pos; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::updateNumElements(IndexType new_num_elements) { assert(new_num_elements >= 0); assert(new_num_elements <= m_capacity); m_num_elements = new_num_elements; } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::setCapacity(IndexType new_capacity) { assert(new_capacity >= 0); if(new_capacity < m_num_elements) { updateNumElements(new_capacity); } m_data = axom::reallocate<T>(m_data, new_capacity, m_allocator_id); m_capacity = new_capacity; assert(m_data != nullptr || m_capacity <= 0); } //------------------------------------------------------------------------------ template <typename T, int DIM> inline void Array<T, DIM>::dynamicRealloc(IndexType new_num_elements) { assert(m_resize_ratio >= 1.0); IndexType new_capacity = new_num_elements * m_resize_ratio + 0.5; const IndexType block_size = this->blockSize(); const IndexType remainder = new_capacity % block_size; if(remainder != 0) { new_capacity += block_size - remainder; } if(m_resize_ratio < 1.0) { std::cerr << "ERROR: resize ratio must be greater than 1.0.\n"; std::cerr << "Set a valid resize ratio via calling setResizeRatio() with " << "an appropriate value.\n"; utilities::processAbort(); } m_data = axom::reallocate<T>(m_data, new_capacity, m_allocator_id); m_capacity = new_capacity; assert(m_data != nullptr || m_capacity <= 0); } } /* namespace axom */ #endif /* AXOM_ARRAY_HPP_ */
29.67992
122
0.61893
LLNL
b930423655c18483adef98ba4c8b335c5e77704f
580
hpp
C++
obsoleted/old/lib-obsolete/int/libled/row-help.hpp
cppcoder123/led-server
8ebac31e1241bb203d2cedfd644fe52619007cd6
[ "MIT" ]
1
2021-12-23T13:50:53.000Z
2021-12-23T13:50:53.000Z
obsoleted/old/lib-obsolete/int/libled/row-help.hpp
cppcoder123/led-server
8ebac31e1241bb203d2cedfd644fe52619007cd6
[ "MIT" ]
null
null
null
obsoleted/old/lib-obsolete/int/libled/row-help.hpp
cppcoder123/led-server
8ebac31e1241bb203d2cedfd644fe52619007cd6
[ "MIT" ]
null
null
null
// // // #ifndef LIBLED_ROW_HELP_HPP #define LIBLED_ROW_HELP_HPP namespace libled { namespace row { template <typename info_t> struct help_t { static std::size_t size (const info_t &info) {return info.size ();} // static bool test (const info_t &info, std::size_t index) {return info.test (index);} }; // template <> // struct help_t<bool> // { // static std::size_t size () {return 1;} // static bool test (bool info, std::size_t) {return info;} // }; } // namespace row } // namespace libled #endif
18.125
73
0.593103
cppcoder123
b93286ebc358d3e9d754fdc12fa0bef1c26ebba6
2,830
cpp
C++
dataset/util.cpp
g5t/scipp
d819c930a5e438fd65e42e2e4e737743b8d39d37
[ "BSD-3-Clause" ]
null
null
null
dataset/util.cpp
g5t/scipp
d819c930a5e438fd65e42e2e4e737743b8d39d37
[ "BSD-3-Clause" ]
null
null
null
dataset/util.cpp
g5t/scipp
d819c930a5e438fd65e42e2e4e737743b8d39d37
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2021 Scipp contributors (https://github.com/scipp) /// @file /// @author Matthew Andrew #include "scipp/dataset/util.h" #include "scipp/variable/arithmetic.h" #include "scipp/variable/misc_operations.h" #include "scipp/variable/reduction.h" #include "scipp/variable/util.h" #include "scipp/variable/variable_concept.h" using namespace scipp::variable; namespace scipp { namespace { template <class T> scipp::index size_of_bins(const Variable &view, const SizeofTag tag) { const auto &[indices, dim, buffer] = view.constituents<T>(); double scale = 1; if (tag == SizeofTag::ViewOnly) { const auto &[begin, end] = unzip(indices); const auto sizes = sum(end - begin).template value<scipp::index>(); // avoid division by zero scale = sizes == 0 ? 0.0 : sizes / static_cast<double>(buffer.dims()[dim]); } return size_of(indices, tag) + size_of(buffer, tag) * scale; } } // namespace scipp::index size_of(const Variable &view, const SizeofTag tag) { if (view.dtype() == dtype<bucket<Variable>>) { return size_of_bins<Variable>(view, tag); } if (view.dtype() == dtype<bucket<DataArray>>) { return size_of_bins<DataArray>(view, tag); } if (view.dtype() == dtype<bucket<Dataset>>) { return size_of_bins<Dataset>(view, tag); } const auto value_size = view.data().dtype_size(); const auto variance_scale = view.hasVariances() ? 2 : 1; const auto data_size = tag == SizeofTag::Underlying ? view.data().size() : view.dims().volume(); return data_size * value_size * variance_scale; } /// Return the size in memory of a DataArray object. The aligned coord is /// optional because for a DataArray owned by a dataset aligned coords are /// assumed to be owned by the dataset as they can apply to multiple arrays. scipp::index size_of(const DataArray &dataarray, const SizeofTag tag, bool include_aligned_coords) { scipp::index size = 0; size += size_of(dataarray.data(), tag); for (const auto &coord : dataarray.attrs()) { size += size_of(coord.second, tag); } for (const auto &mask : dataarray.masks()) { size += size_of(mask.second, tag); } if (include_aligned_coords) { for (const auto &coord : dataarray.coords()) { size += size_of(coord.second, tag); } } return size; } scipp::index size_of(const Dataset &dataset, const SizeofTag tag) { scipp::index size = 0; for (const auto &data : dataset) { size += size_of(data, tag, false); } for (const auto &coord : dataset.coords()) { size += size_of(coord.second, tag); } return size; } DataArray astype(const DataArray &var, const DType type) { return DataArray(astype(var.data(), type), var.coords(), var.masks(), var.attrs(), var.name()); } } // namespace scipp
32.906977
79
0.673145
g5t
b939490ef770fd0da9b17425b32989fc2cb77e00
3,893
cpp
C++
Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.gen.cpp
Maskside/DriftGame
a518574f3ba4256da0cc948b9f147b4d3aaa3b5c
[ "MIT" ]
null
null
null
Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.gen.cpp
Maskside/DriftGame
a518574f3ba4256da0cc948b9f147b4d3aaa3b5c
[ "MIT" ]
null
null
null
Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.gen.cpp
Maskside/DriftGame
a518574f3ba4256da0cc948b9f147b4d3aaa3b5c
[ "MIT" ]
null
null
null
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedExternalUILibrary.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedFriendsGameInstance.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedFriendsInterface.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedFriendsLibrary.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedIdentityLibrary.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedSessions.init.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedSessionsLibrary.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedVoiceLibrary.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\BlueprintDataDefinitions.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\CancelFindSessionsCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\CreateSessionCallbackProxyAdvanced.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\EndSessionCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\FindFriendSessionCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\FindSessionsCallbackProxyAdvanced.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\GetFriendsCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\GetRecentPlayersCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\GetUserPrivilegeCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\LoginUserCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\LogoutUserCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\SendFriendInviteCallbackProxy.gen.cpp" #include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\UpdateSessionCallbackProxyAdvanced.gen.cpp"
169.26087
187
0.875417
Maskside
b939e4890a22c103baa98b3c9a5bbad84f68573e
1,043
cpp
C++
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/ace/QoS/QoS_Manager.cpp
549654033/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
2
2020-05-20T05:16:34.000Z
2020-05-20T05:19:19.000Z
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/ace/QoS/QoS_Manager.cpp
jimxie2012/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
null
null
null
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/ace/QoS/QoS_Manager.cpp
jimxie2012/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
4
2020-05-20T01:50:16.000Z
2021-08-29T13:48:25.000Z
// QoS_Manager.cpp // $Id: QoS_Manager.cpp 80826 2008-03-04 14:51:23Z wotte $ #include "QoS_Manager.h" #include "ace/Log_Msg.h" ACE_RCSID(ace, QoS_Manager, "$Id: QoS_Manager.cpp 80826 2008-03-04 14:51:23Z wotte $") ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_ALLOC_HOOK_DEFINE(ACE_QOS_MANAGER) ACE_QoS_Manager::ACE_QoS_Manager (void) {} ACE_QoS_Manager::~ACE_QoS_Manager (void) {} // Adds the given session to the list of session objects joined by // this socket. int ACE_QoS_Manager::join_qos_session (ACE_QoS_Session *qos_session) { if (this->qos_session_set ().insert (qos_session) != 0) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Error in adding a new session to the ") ACE_TEXT ("socket session set\n")), -1); return 0; } // Returns the QoS session set for this socket. ACE_Unbounded_Set <ACE_QoS_Session *> ACE_QoS_Manager::qos_session_set (void) { return this->qos_session_set_; } ACE_END_VERSIONED_NAMESPACE_DECL
24.833333
87
0.67977
549654033
b93a3df716967c4f026d647429903fe4cecadbdd
1,797
hpp
C++
include/am/succinct/rsdic/EnumCoder.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/am/succinct/rsdic/EnumCoder.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/am/succinct/rsdic/EnumCoder.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
/* * Copyright (c) 2012 Daisuke Okanohara * * 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 authors nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. */ #ifndef RSDIC_ENUM_CODER_HPP_ #define RSDIC_ENUM_CODER_HPP_ #include <types.h> NS_IZENELIB_AM_BEGIN namespace succinct { namespace rsdic { class EnumCoder { public: static uint64_t Encode(uint64_t val, size_t rank_sb); static uint64_t Decode(uint64_t code, size_t rank_sb); static bool GetBit(uint64_t code, size_t rank_sb, size_t pos); static bool GetBit(uint64_t code, size_t rank_sb, size_t pos, size_t& rank); static size_t Rank(uint64_t code, size_t rank_sb, size_t pos); static size_t Select(uint64_t code, size_t rank_sb, size_t num, bool bit); static inline uint8_t Len(size_t rank_sb) { return kEnumCodeLength_[rank_sb]; } private: static size_t Select0Enum_(uint64_t code, size_t rank_sb, size_t num); static size_t Select1Enum_(uint64_t code, size_t rank_sb, size_t num); static const uint8_t kEnumCodeLength_[65]; static const uint64_t kCombinationTable64_[33][64]; }; } } NS_IZENELIB_AM_END #endif // RSDIC_ENUM_CODER_HPP_
28.983871
80
0.742348
izenecloud
b93d6971337ab178a943d239ab8ff80d31c47884
1,807
cpp
C++
lib/indicator/DbgCliCmdIndSet.cpp
dniklaus/arduino-serial-test
a5efa33111321d8663d5291461e4244af491a6b5
[ "MIT" ]
1
2021-01-07T12:59:18.000Z
2021-01-07T12:59:18.000Z
lib/indicator/DbgCliCmdIndSet.cpp
dniklaus/arduino-serial-test
a5efa33111321d8663d5291461e4244af491a6b5
[ "MIT" ]
1
2018-04-19T12:29:36.000Z
2018-04-19T12:29:36.000Z
lib/indicator/DbgCliCmdIndSet.cpp
dniklaus/arduino-serial-test
a5efa33111321d8663d5291461e4244af491a6b5
[ "MIT" ]
1
2017-08-18T18:30:14.000Z
2017-08-18T18:30:14.000Z
/* * DbgCliCmdLedSet.cpp * * Created on: 01.11.2019 * Author: nid */ #include "DbgCliCmdIndSet.h" #include <string.h> #include <DbgCliNode.h> #include <DbgCliTopic.h> #include <DbgCliCommand.h> #include <DbgTracePort.h> #include <DbgTraceContext.h> #include <DbgTraceOut.h> #include <DbgPrintConsole.h> #include <DbgTraceLevel.h> #include "Indicator.h" DbgCliCmd_IndSet::DbgCliCmd_IndSet(Indicator& indicator) : DbgCli_Command(indicator.dbgCliTopic(), "set", "Set indicator state") , m_trPort(new DbgTrace_Port(this->getParentNode()->getNodeName(), DbgTrace_Level::notice)) , m_indicator(indicator) { } DbgCliCmd_IndSet::~DbgCliCmd_IndSet() { delete m_trPort; m_trPort = 0; } void DbgCliCmd_IndSet::printUsage() { TR_PRINTF(m_trPort, DbgTrace_Level::alert, "%s", getHelpText()); TR_PRINTF(m_trPort, DbgTrace_Level::alert, "Usage: %s %s %s [blink|on|off].", DbgCli_Node::RootNode()->getNodeName(), this->getParentNode()->getNodeName(),this->getNodeName()); } void DbgCliCmd_IndSet::printReport() { TR_PRINTF(m_trPort, DbgTrace_Level::alert, "%s : %s", getHelpText(), Indicator::getLedStateText(m_indicator.getLedState())); } void DbgCliCmd_IndSet::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { if (argc - idxToFirstArgToHandle == 0) { printReport(); } else { if (strncmp(args[idxToFirstArgToHandle], "on", strlen("on")) == 0) { m_indicator.set(); printReport(); } else if (strncmp(args[idxToFirstArgToHandle], "off", strlen("off")) == 0) { m_indicator.clear(); printReport(); } else if (strncmp(args[idxToFirstArgToHandle], "blink", strlen("blink")) == 0) { m_indicator.blink(); printReport(); } else { printUsage(); } } }
24.418919
126
0.674045
dniklaus
b93da383c7f40f496c522dd3e40fa5dfb27828cf
8,350
cc
C++
mist/usb_device_event_notifier.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
mist/usb_device_event_notifier.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
mist/usb_device_event_notifier.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright (c) 2013 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 "mist/usb_device_event_notifier.h" #include <limits> #include <base/logging.h> #include <base/strings/string_number_conversions.h> #include <base/strings/stringprintf.h> #include "mist/event_dispatcher.h" #include "mist/udev.h" #include "mist/udev_device.h" #include "mist/udev_enumerate.h" #include "mist/udev_monitor.h" #include "mist/usb_device_event_observer.h" using base::MessageLoopForIO; using base::StringPrintf; using std::string; using std::unique_ptr; namespace mist { namespace { const char kAttributeBusNumber[] = "busnum"; const char kAttributeDeviceAddress[] = "devnum"; const char kAttributeIdProduct[] = "idProduct"; const char kAttributeIdVendor[] = "idVendor"; } // namespace UsbDeviceEventNotifier::UsbDeviceEventNotifier(EventDispatcher* dispatcher, Udev* udev) : dispatcher_(dispatcher), udev_(udev), udev_monitor_file_descriptor_(UdevMonitor::kInvalidFileDescriptor) { CHECK(dispatcher_); CHECK(udev_); } UsbDeviceEventNotifier::~UsbDeviceEventNotifier() { if (udev_monitor_file_descriptor_ != UdevMonitor::kInvalidFileDescriptor) { dispatcher_->StopWatchingFileDescriptor(udev_monitor_file_descriptor_); udev_monitor_file_descriptor_ = UdevMonitor::kInvalidFileDescriptor; } } bool UsbDeviceEventNotifier::Initialize() { udev_monitor_.reset(udev_->CreateMonitorFromNetlink("udev")); if (!udev_monitor_) { LOG(ERROR) << "Could not create udev monitor."; return false; } if (!udev_monitor_->FilterAddMatchSubsystemDeviceType("usb", "usb_device")) { LOG(ERROR) << "Could not add udev monitor filter."; return false; } if (!udev_monitor_->EnableReceiving()) { LOG(ERROR) << "Could not enable udev monitoring."; return false; } udev_monitor_file_descriptor_ = udev_monitor_->GetFileDescriptor(); if (udev_monitor_file_descriptor_ == UdevMonitor::kInvalidFileDescriptor) { LOG(ERROR) << "Could not get udev monitor file descriptor."; return false; } if (!dispatcher_->StartWatchingFileDescriptor( udev_monitor_file_descriptor_, MessageLoopForIO::WATCH_READ, this)) { LOG(ERROR) << "Could not watch udev monitor file descriptor."; return false; } return true; } bool UsbDeviceEventNotifier::ScanExistingDevices() { unique_ptr<UdevEnumerate> enumerate(udev_->CreateEnumerate()); if (!enumerate || !enumerate->AddMatchSubsystem("usb") || !enumerate->AddMatchProperty("DEVTYPE", "usb_device") || !enumerate->ScanDevices()) { LOG(ERROR) << "Could not enumerate USB devices on the system."; return false; } for (unique_ptr<UdevListEntry> list_entry(enumerate->GetListEntry()); list_entry; list_entry.reset(list_entry->GetNext())) { string sys_path = ConvertNullToEmptyString(list_entry->GetName()); unique_ptr<UdevDevice> device( udev_->CreateDeviceFromSysPath(sys_path.c_str())); if (!device) continue; uint8_t bus_number; uint8_t device_address; uint16_t vendor_id; uint16_t product_id; if (!GetDeviceAttributes(device.get(), &bus_number, &device_address, &vendor_id, &product_id)) continue; for (UsbDeviceEventObserver& observer : observer_list_) { observer.OnUsbDeviceAdded(sys_path, bus_number, device_address, vendor_id, product_id); } } return true; } void UsbDeviceEventNotifier::AddObserver(UsbDeviceEventObserver* observer) { CHECK(observer); observer_list_.AddObserver(observer); } void UsbDeviceEventNotifier::RemoveObserver(UsbDeviceEventObserver* observer) { CHECK(observer); observer_list_.RemoveObserver(observer); } void UsbDeviceEventNotifier::OnFileCanReadWithoutBlocking(int file_descriptor) { VLOG(3) << StringPrintf("File descriptor %d available for read.", file_descriptor); unique_ptr<UdevDevice> device(udev_monitor_->ReceiveDevice()); if (!device) { LOG(WARNING) << "Ignore device event with no associated udev device."; return; } VLOG(1) << StringPrintf( "udev (SysPath=%s, " "Node=%s, " "Subsystem=%s, " "DevType=%s, " "Action=%s, " "BusNumber=%s, " "DeviceAddress=%s, " "VendorId=%s, " "ProductId=%s)", device->GetSysPath(), device->GetDeviceNode(), device->GetSubsystem(), device->GetDeviceType(), device->GetAction(), device->GetSysAttributeValue(kAttributeBusNumber), device->GetSysAttributeValue(kAttributeDeviceAddress), device->GetSysAttributeValue(kAttributeIdVendor), device->GetSysAttributeValue(kAttributeIdProduct)); string sys_path = ConvertNullToEmptyString(device->GetSysPath()); if (sys_path.empty()) { LOG(WARNING) << "Ignore device event with no device sysfs path."; return; } string action = ConvertNullToEmptyString(device->GetAction()); if (action == "add") { uint8_t bus_number; uint8_t device_address; uint16_t vendor_id; uint16_t product_id; if (!GetDeviceAttributes(device.get(), &bus_number, &device_address, &vendor_id, &product_id)) { LOG(WARNING) << "Ignore device event of unidentifiable device."; return; } for (UsbDeviceEventObserver& observer : observer_list_) { observer.OnUsbDeviceAdded(sys_path, bus_number, device_address, vendor_id, product_id); } return; } if (action == "remove") { for (UsbDeviceEventObserver& observer : observer_list_) observer.OnUsbDeviceRemoved(sys_path); } } void UsbDeviceEventNotifier::OnFileCanWriteWithoutBlocking( int file_descriptor) { NOTREACHED(); } // static std::string UsbDeviceEventNotifier::ConvertNullToEmptyString(const char* str) { return str ? str : string(); } // static bool UsbDeviceEventNotifier::ConvertHexStringToUint16(const string& str, uint16_t* value) { int temp_value = -1; if (str.size() != 4 || !base::HexStringToInt(str, &temp_value) || temp_value < 0 || temp_value > std::numeric_limits<uint16_t>::max()) { return false; } *value = static_cast<uint16_t>(temp_value); return true; } // static bool UsbDeviceEventNotifier::ConvertStringToUint8(const string& str, uint8_t* value) { unsigned temp_value = 0; if (!base::StringToUint(str, &temp_value) || temp_value > std::numeric_limits<uint8_t>::max()) { return false; } *value = static_cast<uint8_t>(temp_value); return true; } // static bool UsbDeviceEventNotifier::GetDeviceAttributes(const UdevDevice* device, uint8_t* bus_number, uint8_t* device_address, uint16_t* vendor_id, uint16_t* product_id) { string bus_number_string = ConvertNullToEmptyString( device->GetSysAttributeValue(kAttributeBusNumber)); if (!ConvertStringToUint8(bus_number_string, bus_number)) { LOG(WARNING) << "Invalid USB bus number '" << bus_number_string << "'."; return false; } string device_address_string = ConvertNullToEmptyString( device->GetSysAttributeValue(kAttributeDeviceAddress)); if (!ConvertStringToUint8(device_address_string, device_address)) { LOG(WARNING) << "Invalid USB device address '" << device_address_string << "'."; return false; } string vendor_id_string = ConvertNullToEmptyString( device->GetSysAttributeValue(kAttributeIdVendor)); if (!ConvertHexStringToUint16(vendor_id_string, vendor_id)) { LOG(WARNING) << "Invalid USB vendor ID '" << vendor_id_string << "'."; return false; } string product_id_string = ConvertNullToEmptyString( device->GetSysAttributeValue(kAttributeIdProduct)); if (!ConvertHexStringToUint16(product_id_string, product_id)) { LOG(WARNING) << "Invalid USB product ID '" << product_id_string << "'."; return false; } return true; } } // namespace mist
31.749049
80
0.676886
emersion
b93dd4bab3baaf82c57d23bcaed261571a3ba52f
4,531
cpp
C++
sdk/QtComponents/vuMeter.cpp
InfiniteInteractive/LimitlessSDK
cb71dde14d8c59cbf8a1ece765989c5787fffefa
[ "MIT" ]
3
2017-05-13T20:36:03.000Z
2021-07-16T17:23:01.000Z
sdk/QtComponents/vuMeter.cpp
InfiniteInteractive/LimitlessSDK
cb71dde14d8c59cbf8a1ece765989c5787fffefa
[ "MIT" ]
null
null
null
sdk/QtComponents/vuMeter.cpp
InfiniteInteractive/LimitlessSDK
cb71dde14d8c59cbf8a1ece765989c5787fffefa
[ "MIT" ]
2
2016-08-04T00:16:50.000Z
2017-09-07T14:50:03.000Z
#include "VuMeter.h" #include <QtGui/QPainter> namespace Limitless { VuMeter::VuMeter(QWidget *parent): QWidget(parent) { m_backgroundColor=QColor(0, 0, 0); m_cellColor=QColor(80, 80, 80); m_highColor=Qt::red; m_color=Qt::yellow; m_lowColor=Qt::green; m_maxiumValue=1.0f; m_minimumValue=0.0f; m_value=0.0f; m_cells=40; m_vertical=true; } QSize VuMeter::minimumSizeHint() const { QSize size; if(m_vertical) { size.setHeight(m_cells*4+1); size.setWidth(6); } else { size.setWidth(m_cells*4+1); size.setHeight(6); } return size; } QSize VuMeter::sizeHint() const { QSize size; if(m_vertical) { size.setHeight(m_cells*4+3); size.setWidth(8); } else { size.setWidth(m_cells*4+3); size.setHeight(8); } return size; } void VuMeter::setVertical(bool value) { m_vertical=value; if(value) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); } else { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); } setMinimumSize(minimumSizeHint()); } void VuMeter::setValue(float value) { m_value=value; update(); } void VuMeter::paintEvent(QPaintEvent *event) { if(m_vertical) paintVertical(); else paintHorizontal(); } void VuMeter::paintVertical() { QPainter painter(this); QRect rect=painter.window(); painter.setRenderHint(QPainter::Antialiasing); int cellSpacers=m_cells+1; int height=rect.height()-cellSpacers; //need minum 1 pixel space between blocks int cellHeight=height/m_cells; int extra=(rect.height()-(cellHeight*m_cells)-cellSpacers)/2; painter.setBrush(m_backgroundColor); painter.drawRect(rect); int cellIndex=ceil(m_value*m_cells); int colorIndex=ceil(0.70*m_cells); int highColorIndex=ceil(0.90*m_cells); if(cellIndex < 0) cellIndex=0; else if(cellIndex > m_cells) cellIndex=m_cells; QRect cellRect(rect.x()+1, rect.height()-cellHeight-extra-1, rect.width()-2, cellHeight); QColor currentColor=m_lowColor; int changeIndex=colorIndex; painter.setBrush(m_lowColor); for(size_t i=0; i<cellIndex; ++i) { if(i>=changeIndex) { if(changeIndex==colorIndex) { painter.setBrush(m_color); changeIndex=highColorIndex; } else if(changeIndex==highColorIndex) { painter.setBrush(m_highColor); changeIndex=m_cells; } } painter.drawRect(cellRect); cellRect.setBottom(cellRect.y()-1); cellRect.setTop(cellRect.y()-cellHeight-1); } painter.setBrush(m_cellColor); for(size_t i=cellIndex; i<m_cells; ++i) { painter.drawRect(cellRect); cellRect.setBottom(cellRect.y()-1); cellRect.setTop(cellRect.y()-cellHeight-1); } } void VuMeter::paintHorizontal() { QPainter painter(this); QRect rect=painter.window(); painter.setRenderHint(QPainter::Antialiasing); int cellSpacers=m_cells+1; int width=rect.width()-cellSpacers; //need minum 1 pixel space between blocks int cellWidth=width/m_cells; int extra=(rect.width()-(cellWidth*m_cells)-cellSpacers)/2; painter.setBrush(m_backgroundColor); painter.drawRect(rect); int cellIndex=ceil(m_value*m_cells); int colorIndex=ceil(0.5*m_cells); int highColorIndex=ceil(0.75*m_cells); if(cellIndex < 0) cellIndex=0; else if(cellIndex > m_cells) cellIndex=m_cells; QRect cellRect(rect.left(), rect.y()+1, cellWidth, rect.height()-2); QColor currentColor=m_lowColor; int changeIndex=colorIndex; painter.setBrush(m_lowColor); for(size_t i=0; i<cellIndex; ++i) { if(i>=changeIndex) { if(changeIndex==colorIndex) { painter.setBrush(m_color); changeIndex=highColorIndex; } else if(changeIndex==highColorIndex) { painter.setBrush(m_highColor); changeIndex=m_cells; } } painter.drawRect(cellRect); cellRect.translate(cellWidth+1, 0); } painter.setBrush(m_cellColor); for(size_t i=cellIndex; i<m_cells; ++i) { painter.drawRect(cellRect); cellRect.translate(cellWidth+1, 0); } } }//namespace Limitless
21.783654
93
0.621055
InfiniteInteractive
b93e09783a7aecc460f08528362c1569b0c592ce
3,298
cpp
C++
PhysXChips_Dlg/PhysXRigidDynamic_Dlg.cpp
snaxgameengine/PhysXForSnaX
aa18d93a30e6cfe11b0258af3733b65de0adf832
[ "BSD-3-Clause" ]
3
2021-04-27T08:52:40.000Z
2021-05-19T18:05:40.000Z
PhysXChips_Dlg/PhysXRigidDynamic_Dlg.cpp
snaxgameengine/PhysXForSnaX
aa18d93a30e6cfe11b0258af3733b65de0adf832
[ "BSD-3-Clause" ]
null
null
null
PhysXChips_Dlg/PhysXRigidDynamic_Dlg.cpp
snaxgameengine/PhysXForSnaX
aa18d93a30e6cfe11b0258af3733b65de0adf832
[ "BSD-3-Clause" ]
null
null
null
// Copyright(c) 2013-2019, mCODE A/S // 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 holders 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 HOLDERS 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 "pch.h" #include "PhysXRigidDynamic_Dlg.h" using namespace m3d; DIALOGDESC_DEF(PhysXRigidDynamic_Dlg, PHYSXRIGIDDYNAMIC_GUID); void PhysXRigidDynamic_Dlg::Init() { AddCheckBox(L"Kinematic", GetChip()->IsKinematic() ? RCheckState::Checked : RCheckState::Unchecked, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetKinematic(v.ToUInt() == RCheckState::Checked); }); AddDoubleSpinBox(L"Linear Damping", GetChip()->GetLinearDamping(), 0, FLT_MAX, 0.1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetLinearDamping(v.ToFloat()); }); AddDoubleSpinBox(L"Angular Damping", GetChip()->GetAngularDamping(), 0, FLT_MAX, 0.1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetAngularDamping(v.ToFloat()); }); AddDoubleSpinBox(L"Max Angular Velocity", GetChip()->GetMaxAngularVelocity(), 0.0001, FLT_MAX, 0.1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetMaxAngularVelocity(v.ToFloat()); }); AddDoubleSpinBox(L"Sleep Threshold", GetChip()->GetSleepThreshold(), 0.0001, FLT_MAX, 0.1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetSleepThreshold(v.ToFloat()); }); unsigned p, v; GetChip()->GetMinSolverIterations(p, v); AddSpinBox(1, L"Minimum Position Iterations", p, 1, 255, 1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetMinSolverIterations(v.ToInt(), GetValueFromWidget(2).ToInt()); }); AddSpinBox(2, L"Minimum Velocity Iterations", v, 1, 255, 1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetMinSolverIterations(GetValueFromWidget(1).ToInt(), v.ToInt()); }); AddDoubleSpinBox(L"Contact Report Threshold", GetChip()->GetContactReportThreshold(), 0.0001, FLT_MAX, 0.1, [this](Id id, RVariant v) { SetDirty(); GetChip()->SetContactReportThreshold(v.ToFloat()); }); }
64.666667
205
0.739539
snaxgameengine
b941eea895579899b81da4a62b21b2bba3738ed8
49
hpp
C++
src/boost_log_sinks_attribute_mapping.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_log_sinks_attribute_mapping.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_log_sinks_attribute_mapping.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/log/sinks/attribute_mapping.hpp>
24.5
48
0.816327
miathedev
b945d9ff37db95580ed7705f6c44baa8a20130cc
13,072
cc
C++
src/modular/benchmarks/story_benchmark.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
null
null
null
src/modular/benchmarks/story_benchmark.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
src/modular/benchmarks/story_benchmark.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 <fuchsia/modular/cpp/fidl.h> #include <fuchsia/sys/cpp/fidl.h> #include <lib/fidl/cpp/binding.h> #include <lib/fsl/vmo/strings.h> #include <lib/modular_test_harness/cpp/fake_component.h> #include <lib/modular_test_harness/cpp/fake_module.h> #include <lib/modular_test_harness/cpp/test_harness_fixture.h> #include <src/lib/fxl/logging.h> #include <src/lib/fxl/macros.h> #include <src/lib/fxl/strings/string_number_conversions.h> #include <trace/event.h> #include <memory> #include <utility> #include "peridot/lib/testing/session_shell_impl.h" #include "src/modular/benchmarks/tracing_waiter.h" namespace { // Number of stories to create in the Loop test. const int kStoryCount = 5; // Number of times each module sets its link value. const int kLinkSetCount = 100; class TestStoryWatcher : fuchsia::modular::StoryWatcher { public: TestStoryWatcher() : binding_(this) {} ~TestStoryWatcher() override = default; // Registers itself as a watcher on the given story. Only one story at a time // can be watched. void Watch(fuchsia::modular::StoryController* const story_controller) { story_controller->Watch(binding_.NewBinding()); } // Deregisters itself from the watched story. void Reset() { binding_.Unbind(); } // Sets a callback that will be called once the story is running. void OnStoryRunning(fit::function<void()> on_running) { on_running_ = std::move(on_running); } private: // |fuchsia::modular::StoryWatcher| void OnStateChange(fuchsia::modular::StoryState state) override { FXL_LOG(INFO) << "TestStoryWatcher.OnStateChange(): " << fidl::ToUnderlying(state); if (state != fuchsia::modular::StoryState::RUNNING) { return; } on_running_(); } // |fuchsia::modular::StoryWatcher| void OnModuleAdded(fuchsia::modular::ModuleData /*module_data*/) override {} // |fuchsia::modular::StoryWatcher| void OnModuleFocused(std::vector<std::string> /*module_path*/) override {} fit::function<void()> on_running_; fidl::Binding<fuchsia::modular::StoryWatcher> binding_; }; // A simple link watcher implementation that invokes a callback when // it sees the watched link change. class TestLinkWatcher : fuchsia::modular::LinkWatcher { public: TestLinkWatcher() : binding_(this) {} ~TestLinkWatcher() override = default; // Registers itself as a watcher on the given link. Only one story at a time // can be watched. void Watch(fuchsia::modular::Link* const link) { link->WatchAll(binding_.NewBinding()); } // Deregisters itself from the watched story. void Reset() { binding_.Unbind(); } // Sets the function that is called when the link changes. void OnNotify(fit::function<void(fidl::StringPtr)> callback) { on_notify_ = std::move(callback); } private: // |fuchsia::modular::LinkWatcher| void Notify(fuchsia::mem::Buffer value) override { std::string json; FXL_CHECK(fsl::StringFromVmo(value, &json)); on_notify_(std::move(json)); } fidl::Binding<fuchsia::modular::LinkWatcher> binding_; fit::function<void(fidl::StringPtr)> on_notify_{[](fidl::StringPtr) {}}; FXL_DISALLOW_COPY_AND_ASSIGN(TestLinkWatcher); }; // A basic fake session shell component: gives access to services // available to session shells in their environment, as well as an // implementation of fuchsia::modular::SessionShell built for tests. class TestSessionShell : public modular::testing::FakeComponent { public: fuchsia::modular::StoryProvider* story_provider() { return story_provider_.get(); } fuchsia::modular::SessionShellContext* session_shell_context() { return session_shell_context_.get(); } private: // |modular::testing::FakeComponent| void OnCreate(fuchsia::sys::StartupInfo startup_info) override { component_context()->svc()->Connect(session_shell_context_.NewRequest()); session_shell_context_->GetStoryProvider(story_provider_.NewRequest()); component_context()->outgoing()->AddPublicService( session_shell_impl_.GetHandler()); } modular::testing::SessionShellImpl session_shell_impl_; fuchsia::modular::SessionShellContextPtr session_shell_context_; fuchsia::modular::StoryProviderPtr story_provider_; }; // This module repeatedly updates its root link a number of times and then // just sits there until it's terminated. class TestModule : public modular::testing::FakeModule, fuchsia::modular::LinkWatcher { public: TestModule() : link_watcher_binding_(this) {} private: // |modular::testing::FakeComponent| void OnCreate(fuchsia::sys::StartupInfo startup_info) override { modular::testing::FakeModule::OnCreate(std::move(startup_info)); FXL_LOG(INFO) << "TestModule.OnCreate()"; module_context()->GetLink(nullptr, link_.NewRequest()); // Will call Notify() with current value. link_->WatchAll(link_watcher_binding_.NewBinding()); } // |fuchsia::modular::LinkWatcher| void Notify(fuchsia::mem::Buffer content) override { std::string json; FXL_CHECK(fsl::StringFromVmo(content, &json)); FXL_LOG(INFO) << "TestModule.Notify(): " << json; // First invocation is from WatchAll(); next from Set(). if (count_ == -1) { count_ = 0; Set(); return; } // Corresponding TRACE_ASYNC_BEGIN() is in Set(). TRACE_ASYNC_END("benchmark", "link/set", count_); ++count_; if (count_ <= kLinkSetCount) { Set(); } } void Set() { FXL_LOG(INFO) << "TestModule.Set(): " << count_; // Corresponding TRACE_ASYNC_END() is in Notify(). TRACE_ASYNC_BEGIN("benchmark", "link/set", count_); // Corresponding TRACE_FLOW_END() is in the session shell. TRACE_FLOW_BEGIN("benchmark", "link/trans", count_); fsl::SizedVmo vmo; FXL_CHECK(fsl::VmoFromString(std::to_string(count_), &vmo)); link_->Set(nullptr, std::move(vmo).ToTransport()); } // The number of times the root link has been set. int count_{-1}; fuchsia::modular::LinkPtr link_; fidl::Binding<fuchsia::modular::LinkWatcher> link_watcher_binding_; }; // Measures timing the machinery available to a session shell implementation. class StoryBenchmarkTest : public modular::testing::TestHarnessFixture { public: // Name of the module created in CreateStory(). const std::string kModName = "mod"; // Prefix of the name of each story created. const std::string kStoryNamePrefix = "story-"; // Initializes and starts the modular test harness. void InitSession() { modular::testing::TestHarnessBuilder builder; link_watcher_ = std::make_unique<TestLinkWatcher>(); story_watcher_ = std::make_unique<TestStoryWatcher>(); session_shell_ = std::make_unique<TestSessionShell>(); builder.InterceptSessionShell( session_shell_->GetOnCreateHandler(), {.sandbox_services = {"fuchsia.modular.SessionShellContext", "fuchsia.modular.PuppetMaster"}}); // Listen for the module that is created in CreateStory(). module_ = std::make_unique<TestModule>(); module_url_ = modular::testing::GenerateFakeUrl(); builder.InterceptComponent( module_->GetOnCreateHandler(), {.url = module_url_, .sandbox_services = module_->GetSandboxServices()}); TRACE_ASYNC_BEGIN("benchmark", "session/start", 0); builder.BuildAndRun(test_harness()); // Wait for our session shell to start. RunLoopUntil([&] { bool is_running = session_shell_->is_running(); if (is_running) { TRACE_ASYNC_END("benchmark", "session/start", 0); } return is_running; }); // Connect to the PuppetMaster service also provided to the session shell. fuchsia::modular::testing::ModularService modular_service; modular_service.set_puppet_master(puppet_master_.NewRequest()); test_harness()->ConnectToModularService(std::move(modular_service)); } void CreateStory(std::string story_name) { FXL_LOG(INFO) << "CreateStory()"; TRACE_ASYNC_BEGIN("benchmark", "story/create", 0); story_name_ = story_name; puppet_master_->ControlStory(story_name_, story_puppet_master_.NewRequest()); fuchsia::modular::AddMod add_mod; add_mod.mod_name_transitional = kModName; add_mod.intent.handler = module_url_; add_mod.intent.action = "action"; std::vector<fuchsia::modular::StoryCommand> commands(1); commands.at(0).set_add_mod(std::move(add_mod)); story_puppet_master_->Enqueue(std::move(commands)); bool is_created{false}; story_puppet_master_->Execute([&](fuchsia::modular::ExecuteResult result) { TRACE_ASYNC_END("benchmark", "story/create", 0); is_created = true; }); // Wait for the story to be created. RunLoopUntil([&] { return is_created; }); session_shell_->story_provider()->GetController( story_name_, story_controller_.NewRequest()); } void StoryInfo() { FXL_LOG(INFO) << "StoryInfo()"; TRACE_ASYNC_BEGIN("benchmark", "story/info", 0); bool got_story_info{false}; story_controller_->GetInfo([&](fuchsia::modular::StoryInfo story_info, fuchsia::modular::StoryState state) { TRACE_ASYNC_END("benchmark", "story/info", 0); got_story_info = true; }); // Wait for the story info to be returned. RunLoopUntil([&] { return got_story_info; }); } void StartStory() { FXL_LOG(INFO) << "StartStory()"; TRACE_ASYNC_BEGIN("benchmark", "story/start", 0); bool is_started{false}; story_watcher_->OnStoryRunning([&] { TRACE_ASYNC_END("benchmark", "story/start", 0); is_started = true; }); story_watcher_->Watch(story_controller_.get()); story_controller_->RequestStart(); // Wait for the story to start. RunLoopUntil([&] { return is_started; }); } void WatchLink() { FXL_LOG(INFO) << "WatchLink()"; std::vector<std::string> module_path = {kModName}; fuchsia::modular::LinkPath link_path{.module_path = std::move(module_path), .link_name = nullptr}; story_controller_->GetLink(std::move(link_path), link_.NewRequest()); link_watcher_->Watch(link_.get()); link_watcher_->OnNotify([&](fidl::StringPtr json) { FXL_LOG(INFO) << "WatchLink(): " << json; // Ignore empty links which have the JSON string value "null". if (json == "null") { return; } link_value_ = fxl::StringToNumber<int>(json.get()); // Corresponding TRACE_FLOW_BEGIN() is in the module. TRACE_FLOW_END("benchmark", "link/trans", link_value_); }); } void StopStory() { FXL_LOG(INFO) << "StopStory()"; TRACE_ASYNC_BEGIN("benchmark", "story/stop", 0); bool is_stopped{false}; story_controller_->Stop([&] { TRACE_ASYNC_END("benchmark", "story/stop", 0); is_stopped = true; }); // Wait for the story to stop. RunLoopUntil([&] { return is_stopped; }); } void Reset() { FXL_LOG(INFO) << "Reset()"; link_watcher_->Reset(); story_watcher_->Reset(); story_controller_.Unbind(); story_puppet_master_.Unbind(); story_name_.clear(); } void Logout() { FXL_LOG(INFO) << "Logout()"; TRACE_ASYNC_BEGIN("benchmark", "user/logout", 0); session_shell_->session_shell_context()->Logout(); TRACE_ASYNC_END("benchmark", "user/logout", 0); } // The name of the story created by CreateStory(). std::string story_name_; // Component URL of the |module_| intercepted in InitSession(). std::string module_url_; // The last link value that |link_watcher_| has observed. int link_value_{0}; std::unique_ptr<TestStoryWatcher> story_watcher_; std::unique_ptr<TestSessionShell> session_shell_; std::unique_ptr<TestModule> module_; std::unique_ptr<TestLinkWatcher> link_watcher_; fuchsia::modular::StoryControllerPtr story_controller_; fuchsia::modular::PuppetMasterPtr puppet_master_; fuchsia::modular::StoryPuppetMasterPtr story_puppet_master_; fuchsia::modular::LinkPtr link_; modular::TracingWaiter tracing_waiter_; }; TEST_F(StoryBenchmarkTest, Loop) { // Wait for the tracing service to be ready to use. bool is_tracing_started{false}; tracing_waiter_.WaitForTracing([&] { is_tracing_started = true; }); RunLoopUntil([&] { return is_tracing_started; }); InitSession(); for (int i = 1; i <= kStoryCount; i++) { auto story_name = std::string(kStoryNamePrefix) + std::to_string(i); FXL_LOG(INFO) << "Creating story \"" << story_name << "\" (" << i << " of " << kStoryCount << ")"; CreateStory(story_name); StoryInfo(); WatchLink(); StartStory(); // Wait for the module to set the link value |kLinkSetCount| times. RunLoopUntil([&] { return link_value_ == kLinkSetCount; }); StopStory(); Reset(); } Logout(); } } // namespace
31.272727
79
0.685052
zhangpf
b947d0b549363508cae2e17e7ff9f5eddb259fe5
7,810
cpp
C++
FEBioSource2.9/FEBioMech/FE2DFiberNeoHookean.cpp
wzaylor/FEBio_MCLS
f1052733c31196544fb0921aa55ffa5167a25f98
[ "Intel" ]
1
2021-08-24T08:37:21.000Z
2021-08-24T08:37:21.000Z
FEBioSource2.9/FEBioMech/FE2DFiberNeoHookean.cpp
wzaylor/FEBio_MCLS
f1052733c31196544fb0921aa55ffa5167a25f98
[ "Intel" ]
null
null
null
FEBioSource2.9/FEBioMech/FE2DFiberNeoHookean.cpp
wzaylor/FEBio_MCLS
f1052733c31196544fb0921aa55ffa5167a25f98
[ "Intel" ]
1
2021-03-15T08:22:06.000Z
2021-03-15T08:22:06.000Z
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2019 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 "FE2DFiberNeoHookean.h" // define the material parameters BEGIN_PARAMETER_LIST(FE2DFiberNeoHookean, FEElasticMaterial) ADD_PARAMETER2(m_E, FE_PARAM_DOUBLE, FE_RANGE_GREATER(0.0), "E"); ADD_PARAMETER2(m_v, FE_PARAM_DOUBLE, FE_RANGE_RIGHT_OPEN(-1.0, 0.5), "v"); ADD_PARAMETERV(m_a, FE_PARAM_DOUBLE, 2, "a"); ADD_PARAMETER(m_ac, FE_PARAM_DOUBLE, "active_contraction"); END_PARAMETER_LIST(); double FE2DFiberNeoHookean::m_cth[FE2DFiberNeoHookean::NSTEPS]; double FE2DFiberNeoHookean::m_sth[FE2DFiberNeoHookean::NSTEPS]; ////////////////////////////////////////////////////////////////////// // FE2DFiberNeoHookean ////////////////////////////////////////////////////////////////////// FE2DFiberNeoHookean::FE2DFiberNeoHookean(FEModel* pfem) : FEElasticMaterial(pfem) { static bool bfirst = true; if (bfirst) { double ph; const double PI = 4.0*atan(1.0); for (int n=0; n<NSTEPS; ++n) { ph = 2.0*PI*n / (double) NSTEPS; m_cth[n] = cos(ph); m_sth[n] = sin(ph); } bfirst = false; } m_ac = 0; m_a[0] = m_a[1] = 0; } mat3ds FE2DFiberNeoHookean::Stress(FEMaterialPoint& mp) { FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); mat3d &F = pt.m_F; double detF = pt.m_J; double detFi = 1.0/detF; double lndetF = log(detF); // calculate left Cauchy-Green tensor // (we commented out the matrix components we do not need) double b[3][3]; b[0][0] = F[0][0]*F[0][0]+F[0][1]*F[0][1]+F[0][2]*F[0][2]; b[0][1] = F[0][0]*F[1][0]+F[0][1]*F[1][1]+F[0][2]*F[1][2]; b[0][2] = F[0][0]*F[2][0]+F[0][1]*F[2][1]+F[0][2]*F[2][2]; // b[1][0] = F[1][0]*F[0][0]+F[1][1]*F[0][1]+F[1][2]*F[0][2]; b[1][1] = F[1][0]*F[1][0]+F[1][1]*F[1][1]+F[1][2]*F[1][2]; b[1][2] = F[1][0]*F[2][0]+F[1][1]*F[2][1]+F[1][2]*F[2][2]; // b[2][0] = F[2][0]*F[0][0]+F[2][1]*F[0][1]+F[2][2]*F[0][2]; // b[2][1] = F[2][0]*F[1][0]+F[2][1]*F[1][1]+F[2][2]*F[1][2]; b[2][2] = F[2][0]*F[2][0]+F[2][1]*F[2][1]+F[2][2]*F[2][2]; // lame parameters double lam = m_v*m_E/((1+m_v)*(1-2*m_v)); double mu = 0.5*m_E/(1+m_v); // calculate stress mat3ds s; // --- M A T R I X C O N T R I B U T I O N --- s.xx() = (mu*(b[0][0] - 1) + lam*lndetF)*detFi; s.yy() = (mu*(b[1][1] - 1) + lam*lndetF)*detFi; s.zz() = (mu*(b[2][2] - 1) + lam*lndetF)*detFi; s.xy() = mu*b[0][1]*detFi; s.yz() = mu*b[1][2]*detFi; s.xz() = mu*b[0][2]*detFi; // --- F I B E R C O N T R I B U T I O N --- // NOTE: we have only implemented the active contraction model for this material // There is no passive fiber stress. if (m_ac > 0) { const double PI = 4.0*atan(1.0); double wa = 1.0 / (double) NSTEPS; vec3d a0, a, v; double at; for (int n=0; n<NSTEPS; ++n) { // calculate the local material fiber vector v.x = m_cth[n]; v.y = m_sth[n]; v.z = 0; // calculate the global material fiber vector a0 = pt.m_Q*v; // calculate the global spatial fiber vector a.x = F[0][0]*a0.x + F[0][1]*a0.y + F[0][2]*a0.z; a.y = F[1][0]*a0.x + F[1][1]*a0.y + F[1][2]*a0.z; a.z = F[2][0]*a0.x + F[2][1]*a0.y + F[2][2]*a0.z; // normalize material axis and store fiber stretch a.unit(); // add active contraction stuff at = wa*m_ac *sqrt((m_a[0]*v.x)*(m_a[0]*v.x) + (m_a[1]*v.y)*(m_a[1]*v.y)); s.xx() += at*a.x*a.x; s.yy() += at*a.y*a.y; s.zz() += at*a.z*a.z; s.xy() += at*a.x*a.y; s.yz() += at*a.y*a.z; s.xz() += at*a.x*a.z; } } return s; } tens4ds FE2DFiberNeoHookean::Tangent(FEMaterialPoint& mp) { FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); // deformation gradient mat3d &F = pt.m_F; double detF = pt.m_J; // lame parameters double lam = m_v*m_E/((1+m_v)*(1-2*m_v)); double mu = 0.5*m_E/(1+m_v); double lam1 = lam / detF; double mu1 = (mu - lam*log(detF)) / detF; // --- M A T R I X C O N T R I B U T I O N --- double D[6][6] = {0}; D[0][0] = lam1+2.*mu1; D[0][1] = lam1 ; D[0][2] = lam1 ; D[1][0] = lam1 ; D[1][1] = lam1+2.*mu1; D[1][2] = lam1 ; D[2][0] = lam1 ; D[2][1] = lam1 ; D[2][2] = lam1+2.*mu1; D[3][3] = mu1; D[4][4] = mu1; D[5][5] = mu1; // --- F I B E R C O N T R I B U T I O N --- // NOTE: I commented the fiber stiffness out since I think it will lead to // a nonsymmetric D matrix and I can't deal with that yet. Besides, most // problems seem to be running just fine without this contribution. /* if (m_ac) { // Next, we add the fiber contribution. Since the fibers lie // randomly perpendicular to the transverse axis, we need // to integrate over that plane const double PI = 4.0*atan(1.0); double lam, at, In; vec3d a0, a, v; double wa = 1.0 / (double) NSTEPS; for (int n=0; n<NSTEPS; ++n) { // calculate the local material fiber vector v.x = m_cth[n]; v.y = m_sth[n]; v.z = 0; // calculate the global material fiber vector a0 = pt.Q*v; // calculate the global spatial fiber vector a.x = F[0][0]*a0.x + F[0][1]*a0.y + F[0][2]*a0.z; a.y = F[1][0]*a0.x + F[1][1]*a0.y + F[1][2]*a0.z; a.z = F[2][0]*a0.x + F[2][1]*a0.y + F[2][2]*a0.z; // normalize material axis and store fiber stretch lam = a.unit(); // add active contraction stuff at = wa*m_ac *sqrt((m_a[0]*v.x)*(m_a[0]*v.x) + (m_a[1]*v.y)*(m_a[1]*v.y)); In = lam*lam; D[0][0] += at*(a.x*a.x - 2.0*a.x*a.x*a.x*a.x); // c(0,0,0,0) D[0][1] += at*(a.x*a.x - 2.0*a.x*a.x*a.y*a.y); // c(0,0,1,1) D[0][2] += at*(a.x*a.x - 2.0*a.x*a.x*a.z*a.z); // c(0,0,2,2) D[0][3] -= at*(2.0*a.x*a.x*a.x*a.y); // c(0,0,0,1) D[0][4] -= at*(2.0*a.x*a.x*a.y*a.z); // c(0,0,1,2) D[0][5] -= at*(2.0*a.x*a.x*a.x*a.z); // c(0,0,0,2) D[1][1] += at*(a.y*a.y - 2.0*a.y*a.y*a.y*a.y); // c(1,1,1,1) D[1][2] += at*(a.y*a.y - 2.0*a.y*a.y*a.z*a.z); // c(1,1,2,2) D[1][3] -= at*(2.0*a.y*a.y*a.x*a.y); // c(1,1,0,1) D[1][4] -= at*(2.0*a.y*a.y*a.y*a.z); // c(1,1,1,2) D[1][5] -= at*(2.0*a.y*a.y*a.x*a.z); // c(1,1,0,2) D[2][2] += at*(a.z*a.z - 2.0*a.z*a.z*a.z*a.z); // c(2,2,2,2) D[2][3] -= at*(2.0*a.z*a.z*a.x*a.y); // c(2,2,0,1) D[2][4] -= at*(2.0*a.z*a.z*a.y*a.z); // c(2,2,1,2) D[2][5] -= at*(2.0*a.z*a.z*a.x*a.z); // c(2,2,0,2) D[3][3] -= at*(2.0*a.x*a.y*a.x*a.y); // c(0,1,0,1) D[3][4] -= at*(2.0*a.x*a.y*a.y*a.z); // c(0,1,1,2) D[3][5] -= at*(2.0*a.x*a.y*a.x*a.z); // c(0,1,0,2) D[4][4] -= at*(2.0*a.y*a.z*a.y*a.z); // c(1,2,1,2) D[4][5] -= at*(2.0*a.y*a.z*a.x*a.z); // c(1,2,0,2) D[5][5] -= at*(2.0*a.x*a.z*a.x*a.z); // c(0,2,0,2) } } */ return tens4ds(D); }
32.406639
82
0.565685
wzaylor
b94a33adf78d2b21e61582137ee61764ca00c42b
7,906
cpp
C++
ruby/input/joypad/directinput.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ruby/input/joypad/directinput.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ruby/input/joypad/directinput.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once auto CALLBACK DirectInput_EnumJoypadsCallback(const DIDEVICEINSTANCE* instance, void* p) -> BOOL; auto CALLBACK DirectInput_EnumJoypadAxesCallback(const DIDEVICEOBJECTINSTANCE* instance, void* p) -> BOOL; auto CALLBACK DirectInput_EnumJoypadEffectsCallback(const DIDEVICEOBJECTINSTANCE* instance, void* p) -> BOOL; struct InputJoypadDirectInput { Input& input; InputJoypadDirectInput(Input& input) : input(input) {} struct Joypad { shared_pointer<HID::Joypad> hid{new HID::Joypad}; LPDIRECTINPUTDEVICE8 device = nullptr; LPDIRECTINPUTEFFECT effect = nullptr; u32 pathID = 0; u16 vendorID = 0; u16 productID = 0; bool isXInputDevice = false; }; vector<Joypad> joypads; uintptr handle = 0; LPDIRECTINPUT8 context = nullptr; LPDIRECTINPUTDEVICE8 device = nullptr; bool xinputAvailable = false; u32 effects = 0; auto assign(shared_pointer<HID::Joypad> hid, u32 groupID, u32 inputID, s16 value) -> void { auto& group = hid->group(groupID); if(group.input(inputID).value() == value) return; input.doChange(hid, groupID, inputID, group.input(inputID).value(), value); group.input(inputID).setValue(value); } auto poll(vector<shared_pointer<HID::Device>>& devices) -> void { for(auto& jp : joypads) { if(FAILED(jp.device->Poll())) jp.device->Acquire(); DIJOYSTATE2 state; if(FAILED(jp.device->GetDeviceState(sizeof(DIJOYSTATE2), &state))) continue; for(u32 n : range(4)) { assign(jp.hid, HID::Joypad::GroupID::Axis, 0, state.lX); assign(jp.hid, HID::Joypad::GroupID::Axis, 1, state.lY); assign(jp.hid, HID::Joypad::GroupID::Axis, 2, state.lZ); assign(jp.hid, HID::Joypad::GroupID::Axis, 3, state.lRx); assign(jp.hid, HID::Joypad::GroupID::Axis, 4, state.lRy); assign(jp.hid, HID::Joypad::GroupID::Axis, 5, state.lRz); u32 pov = state.rgdwPOV[n]; s16 xaxis = 0; s16 yaxis = 0; if(pov < 36000) { if(pov >= 31500 || pov <= 4500) yaxis = -32767; if(pov >= 4500 && pov <= 13500) xaxis = +32767; if(pov >= 13500 && pov <= 22500) yaxis = +32767; if(pov >= 22500 && pov <= 31500) xaxis = -32767; } assign(jp.hid, HID::Joypad::GroupID::Hat, n * 2 + 0, xaxis); assign(jp.hid, HID::Joypad::GroupID::Hat, n * 2 + 1, yaxis); } for(u32 n : range(128)) { assign(jp.hid, HID::Joypad::GroupID::Button, n, (bool)state.rgbButtons[n]); } devices.append(jp.hid); } } auto rumble(u64 id, bool enable) -> bool { for(auto& jp : joypads) { if(jp.hid->id() != id) continue; if(jp.effect == nullptr) continue; if(enable) jp.effect->Start(1, 0); else jp.effect->Stop(); return true; } return false; } auto initialize(uintptr handle, LPDIRECTINPUT8 context, bool xinputAvailable) -> bool { if(!handle) return false; this->handle = handle; this->context = context; this->xinputAvailable = xinputAvailable; context->EnumDevices(DI8DEVCLASS_GAMECTRL, DirectInput_EnumJoypadsCallback, (void*)this, DIEDFL_ATTACHEDONLY); return true; } auto terminate() -> void { for(auto& jp : joypads) { jp.device->Unacquire(); if(jp.effect) jp.effect->Release(); jp.device->Release(); } joypads.reset(); context = nullptr; } auto initJoypad(const DIDEVICEINSTANCE* instance) -> bool { Joypad jp; jp.vendorID = instance->guidProduct.Data1 >> 0; jp.productID = instance->guidProduct.Data1 >> 16; jp.isXInputDevice = false; if(auto device = rawinput.find(jp.vendorID, jp.productID)) { jp.isXInputDevice = device().isXInputDevice; } //Microsoft has intentionally imposed artificial restrictions on XInput devices when used with DirectInput //a) the two triggers are merged into a single axis, making uniquely distinguishing them impossible //b) rumble support is not exposed //thus, it's always preferred to let the XInput driver handle these joypads //but if the driver is not available (XInput 1.3 does not ship with stock Windows XP), fall back on DirectInput if(jp.isXInputDevice && xinputAvailable) return DIENUM_CONTINUE; if(FAILED(context->CreateDevice(instance->guidInstance, &device, 0))) return DIENUM_CONTINUE; jp.device = device; device->SetDataFormat(&c_dfDIJoystick2); device->SetCooperativeLevel((HWND)handle, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND); effects = 0; device->EnumObjects(DirectInput_EnumJoypadAxesCallback, (void*)this, DIDFT_ABSAXIS); device->EnumObjects(DirectInput_EnumJoypadEffectsCallback, (void*)this, DIDFT_FFACTUATOR); jp.hid->setRumble(effects > 0); DIPROPGUIDANDPATH property; memset(&property, 0, sizeof(DIPROPGUIDANDPATH)); property.diph.dwSize = sizeof(DIPROPGUIDANDPATH); property.diph.dwHeaderSize = sizeof(DIPROPHEADER); property.diph.dwObj = 0; property.diph.dwHow = DIPH_DEVICE; device->GetProperty(DIPROP_GUIDANDPATH, &property.diph); string devicePath = (const char*)utf8_t(property.wszPath); jp.pathID = Hash::CRC32(devicePath).value(); jp.hid->setVendorID(jp.vendorID); jp.hid->setProductID(jp.productID); jp.hid->setPathID(jp.pathID); if(jp.hid->rumble()) { //disable auto-centering spring for rumble support DIPROPDWORD property; memset(&property, 0, sizeof(DIPROPDWORD)); property.diph.dwSize = sizeof(DIPROPDWORD); property.diph.dwHeaderSize = sizeof(DIPROPHEADER); property.diph.dwObj = 0; property.diph.dwHow = DIPH_DEVICE; property.dwData = false; device->SetProperty(DIPROP_AUTOCENTER, &property.diph); DWORD dwAxes[2] = {(DWORD)DIJOFS_X, (DWORD)DIJOFS_Y}; LONG lDirection[2] = {0, 0}; DICONSTANTFORCE force; force.lMagnitude = DI_FFNOMINALMAX; //full force DIEFFECT effect; memset(&effect, 0, sizeof(DIEFFECT)); effect.dwSize = sizeof(DIEFFECT); effect.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; effect.dwDuration = INFINITE; effect.dwSamplePeriod = 0; effect.dwGain = DI_FFNOMINALMAX; effect.dwTriggerButton = DIEB_NOTRIGGER; effect.dwTriggerRepeatInterval = 0; effect.cAxes = 2; effect.rgdwAxes = dwAxes; effect.rglDirection = lDirection; effect.lpEnvelope = 0; effect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE); effect.lpvTypeSpecificParams = &force; effect.dwStartDelay = 0; device->CreateEffect(GUID_ConstantForce, &effect, &jp.effect, NULL); } for(auto n : range(6)) jp.hid->axes().append(n); for(auto n : range(8)) jp.hid->hats().append(n); for(auto n : range(128)) jp.hid->buttons().append(n); joypads.append(jp); return DIENUM_CONTINUE; } auto initAxis(const DIDEVICEOBJECTINSTANCE* instance) -> bool { DIPROPRANGE range; memset(&range, 0, sizeof(DIPROPRANGE)); range.diph.dwSize = sizeof(DIPROPRANGE); range.diph.dwHeaderSize = sizeof(DIPROPHEADER); range.diph.dwHow = DIPH_BYID; range.diph.dwObj = instance->dwType; range.lMin = -32768; range.lMax = +32767; device->SetProperty(DIPROP_RANGE, &range.diph); return DIENUM_CONTINUE; } auto initEffect(const DIDEVICEOBJECTINSTANCE* instance) -> bool { effects++; return DIENUM_CONTINUE; } }; auto CALLBACK DirectInput_EnumJoypadsCallback(const DIDEVICEINSTANCE* instance, void* p) -> BOOL { return ((InputJoypadDirectInput*)p)->initJoypad(instance); } auto CALLBACK DirectInput_EnumJoypadAxesCallback(const DIDEVICEOBJECTINSTANCE* instance, void* p) -> BOOL { return ((InputJoypadDirectInput*)p)->initAxis(instance); } auto CALLBACK DirectInput_EnumJoypadEffectsCallback(const DIDEVICEOBJECTINSTANCE* instance, void* p) -> BOOL { return ((InputJoypadDirectInput*)p)->initEffect(instance); }
36.266055
115
0.676069
CasualPokePlayer
b94af4968211cb6419b66b0e2a6075d15181bac4
7,645
hpp
C++
drivers/usb/hcds/ehci/src/ehci.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
1
2020-07-29T12:13:14.000Z
2020-07-29T12:13:14.000Z
drivers/usb/hcds/ehci/src/ehci.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
null
null
null
drivers/usb/hcds/ehci/src/ehci.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
null
null
null
#include <queue> #include <arch/mem_space.hpp> #include <async/recurring-event.hpp> #include <async/mutex.hpp> #include <async/result.hpp> #include <helix/memory.hpp> #include "spec.hpp" struct Controller; struct DeviceState; struct ConfigurationState; struct InterfaceState; struct EndpointState; // TODO: This could be moved to a "USB core" driver. struct Enumerator { Enumerator(Controller *controller); // Called by the USB hub driver once a device connects to a port. void connectPort(int port); // Called by the USB hub driver once a device completes reset. void enablePort(int port); private: enum class State { null, resetting, probing }; async::detached _reset(); async::detached _probe(); Controller *_controller; State _state; int _activePort; async::mutex _addressMutex; }; // ---------------------------------------------------------------- // Controller. // ---------------------------------------------------------------- struct Controller : std::enable_shared_from_this<Controller> { Controller(protocols::hw::Device hw_device, helix::Mapping mapping, helix::UniqueDescriptor mmio, helix::UniqueIrq irq); async::detached initialize(); async::result<void> probeDevice(); async::detached handleIrqs(); // ------------------------------------------------------------------------ // Schedule classes. // ------------------------------------------------------------------------ struct AsyncItem : boost::intrusive::list_base_hook<> { }; struct Transaction : AsyncItem { explicit Transaction(arch::dma_array<TransferDescriptor> transfers, size_t size) : transfers{std::move(transfers)}, fullSize{size}, numComplete{0}, lostSize{0} { } arch::dma_array<TransferDescriptor> transfers; size_t fullSize; size_t numComplete; size_t lostSize; // Size lost in short packets. async::promise<frg::expected<UsbError, size_t>> promise; async::promise<frg::expected<UsbError>> voidPromise; }; struct QueueEntity : AsyncItem { QueueEntity(arch::dma_object<QueueHead> the_head, int address, int pipe, PipeType type, size_t packet_size); bool getReclaim(); void setReclaim(bool reclaim); void setAddress(int address); arch::dma_object<QueueHead> head; boost::intrusive::list<Transaction> transactions; }; // ------------------------------------------------------------------------ // Device management. // ------------------------------------------------------------------------ struct EndpointSlot { size_t maxPacketSize; QueueEntity *queueEntity; }; struct DeviceSlot { EndpointSlot controlStates[16]; EndpointSlot outStates[16]; EndpointSlot inStates[16]; }; std::queue<int> _addressStack; DeviceSlot _activeDevices[128]; public: async::result<frg::expected<UsbError, std::string>> configurationDescriptor(int address); async::result<frg::expected<UsbError>> useConfiguration(int address, int configuration); async::result<frg::expected<UsbError>> useInterface(int address, int interface, int alternative); // ------------------------------------------------------------------------ // Transfer functions. // ------------------------------------------------------------------------ static Transaction *_buildControl(XferFlags dir, arch::dma_object_view<SetupPacket> setup, arch::dma_buffer_view buffer, size_t max_packet_size); static Transaction *_buildInterruptOrBulk(XferFlags dir, arch::dma_buffer_view buffer, size_t max_packet_size, bool lazy_notification); async::result<frg::expected<UsbError>> transfer(int address, int pipe, ControlTransfer info); async::result<frg::expected<UsbError, size_t>> transfer(int address, PipeType type, int pipe, InterruptTransfer info); async::result<frg::expected<UsbError, size_t>> transfer(int address, PipeType type, int pipe, BulkTransfer info); private: async::result<frg::expected<UsbError>> _directTransfer(ControlTransfer info, QueueEntity *queue, size_t max_packet_size); // ------------------------------------------------------------------------ // Schedule management. // ------------------------------------------------------------------------ void _linkAsync(QueueEntity *entity); void _linkTransaction(QueueEntity *queue, Transaction *transaction); void _progressSchedule(); void _progressQueue(QueueEntity *entity); boost::intrusive::list<QueueEntity> _asyncSchedule; arch::dma_object<QueueHead> _asyncQh; // ---------------------------------------------------------------------------- // Port management. // ---------------------------------------------------------------------------- void _checkPorts(); public: async::detached resetPort(int number); // ---------------------------------------------------------------------------- // Debugging functions. // ---------------------------------------------------------------------------- private: void _dump(Transaction *transaction); void _dump(QueueEntity *entity); private: protocols::hw::Device _hwDevice; helix::Mapping _mapping; helix::UniqueDescriptor _mmio; helix::UniqueIrq _irq; arch::mem_space _space; arch::mem_space _operational; int _numPorts; Enumerator _enumerator; }; // ---------------------------------------------------------------------------- // DeviceState // ---------------------------------------------------------------------------- struct DeviceState final : DeviceData { explicit DeviceState(std::shared_ptr<Controller> controller, int device); arch::dma_pool *setupPool() override; arch::dma_pool *bufferPool() override; async::result<frg::expected<UsbError, std::string>> configurationDescriptor() override; async::result<frg::expected<UsbError, Configuration>> useConfiguration(int number) override; async::result<frg::expected<UsbError>> transfer(ControlTransfer info) override; private: std::shared_ptr<Controller> _controller; int _device; }; // ---------------------------------------------------------------------------- // ConfigurationState // ---------------------------------------------------------------------------- struct ConfigurationState final : ConfigurationData { explicit ConfigurationState(std::shared_ptr<Controller> controller, int device, int configuration); async::result<frg::expected<UsbError, Interface>> useInterface(int number, int alternative) override; private: std::shared_ptr<Controller> _controller; int _device; int _configuration; }; // ---------------------------------------------------------------------------- // InterfaceState // ---------------------------------------------------------------------------- struct InterfaceState final : InterfaceData { explicit InterfaceState(std::shared_ptr<Controller> controller, int device, int configuration); async::result<frg::expected<UsbError, Endpoint>> getEndpoint(PipeType type, int number) override; private: std::shared_ptr<Controller> _controller; int _device; int _interface; }; // ---------------------------------------------------------------------------- // EndpointState // ---------------------------------------------------------------------------- struct EndpointState final : EndpointData { explicit EndpointState(std::shared_ptr<Controller> controller, int device, PipeType type, int endpoint); async::result<frg::expected<UsbError>> transfer(ControlTransfer info) override; async::result<frg::expected<UsbError, size_t>> transfer(InterruptTransfer info) override; async::result<frg::expected<UsbError, size_t>> transfer(BulkTransfer info) override; private: std::shared_ptr<Controller> _controller; int _device; PipeType _type; int _endpoint; };
29.980392
93
0.591629
kITerE
b94b32da02b41b69030f9732bb465d25ecf4f8ee
5,259
cpp
C++
src/wcx_plugin.cpp
remittor/paxz.wcx
8c10a4673c4e613383f7c61041e4116007ba032d
[ "MIT" ]
9
2019-11-27T09:41:03.000Z
2022-02-19T13:32:57.000Z
src/wcx_plugin.cpp
remittor/paxz.wcx
8c10a4673c4e613383f7c61041e4116007ba032d
[ "MIT" ]
null
null
null
src/wcx_plugin.cpp
remittor/paxz.wcx
8c10a4673c4e613383f7c61041e4116007ba032d
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "wcx_plugin.h" #include "winuser.h" #include "res\resource.h" namespace wcx { plugin::plugin() { m_module = NULL; m_main_thread_id = 0; m_ProcessDataProcW = NULL; m_packer_count = 0; m_testmode = false; m_inited = false; } plugin::~plugin() { destroy(); } int plugin::init(HMODULE lib_addr, DWORD thread_id) { m_module = lib_addr; m_main_thread_id = thread_id; m_inited = true; m_inicfg.init(lib_addr); m_clist.init(m_main_thread_id, m_inicfg); return 0; } int plugin::destroy() { m_arclist.clear(); m_plist.clear(); m_clist.clear(); return 0; } // ========================================================================================= int plugin::show_cfg_dialog(HWND parentWnd, HINSTANCE dllInstance) { m_inicfg.set_cache_size(m_clist.get_cache_size()); m_inicfg.show_cfg_dialog(dllInstance, parentWnd); return 0; } wcx::cfg plugin::get_cfg() { wcx::cfg cfg; m_inicfg.copy(cfg); return cfg; } // ========================================================================================= int plugin::check_file(LPCWSTR filename) { wcx::arcfile arcfile; int hr = arcfile.init(filename, imType); if (hr == 0) { return (arcfile.get_type() == atUnknown) ? E_BAD_ARCHIVE : 0; } return hr; } int plugin::open_file(LPWSTR arcName, int openMode, wcx::archive ** pArc) { int hr = E_BAD_ARCHIVE; wcx::arcfile arcfile; wcx::cache * cache = NULL; wcx::archive * arc = NULL; wcx::cfg cfg; m_clist.delete_zombies(); DWORD tid = GetCurrentThreadId(); WLOGi(L"%S(%d): [0x%X] \"%s\" ", __func__, openMode, tid, arcName); arc = new wcx::archive(); FIN_IF(!arc, 0x30001000 | E_NO_MEMORY); hr = arcfile.init(arcName, imName | imAttr | imType); FIN_IF(hr, hr); hr = m_clist.get_cache(arcfile, true, &cache); FIN_IF(hr, hr); m_inicfg.copy(cfg); hr = arc->init(cfg, arcName, openMode, tid, cache); FIN_IF(hr, 0x30012000 | E_BAD_ARCHIVE); bool xb = m_arclist.add(arc); FIN_IF(!xb, 0x30014000 | E_NO_MEMORY); cache->read_lock(); *pArc = arc; arc = NULL; hr = 0; fin: LOGe_IF(hr, "%s: ERROR = 0x%X ", __func__, hr); if (arc) delete arc; return hr & 0xFF; } int plugin::close_file(wcx::archive * arc) { wcx::cache * cache = arc->get_cache(); if (cache) { cache->read_unlock(); } if (!m_arclist.del(arc)) { delete arc; } return 0; } // ========================================================================================= int plugin::pack_files(LPCWSTR PackedFile, LPCWSTR SubPath, LPCWSTR SrcPath, LPCWSTR AddList, int Flags) { int hr = E_BAD_ARCHIVE; size_t AddListSize = 0; wcx::arcfile arcfile; wcx::packer * packer = NULL; wcx::cfg cfg; InterlockedIncrement(&m_packer_count); DWORD tid = GetCurrentThreadId(); if (m_testmode) { for (LPWSTR s = (LPWSTR)AddList; *s; s++) { if (*s == L'\1') *s = 0; } } for (LPCWSTR fn = AddList; fn[0]; fn += wcslen(fn) + 1) { AddListSize++; FIN_IF(AddListSize >= UINT_MAX, 0x300100 | E_TOO_MANY_FILES); } WLOGd(L"%S(%d): [0x%X] PackedFile = \"%s\" SrcPath = \"%s\" <%Id> ", __func__, Flags, tid, PackedFile, SrcPath, AddListSize); //WLOGd(L" SubPath= \"%s\" AddList = \"%s\" SrcPath = \"%s\" ", SubPath, AddList, SrcPath); FIN_IF(AddList[0] == 0, 0x300200 | E_NO_FILES); FIN_IF(!m_ProcessDataProcW, 0x300400 |E_NO_FILES); if (tid == m_main_thread_id) { UINT uType = MB_OK | MB_ICONERROR | MB_SYSTEMMODAL; int btn = MessageBoxW(NULL, L"Please, update Total Commander!!!", L"CRITICAL ERROR", uType); FIN(0x302200 | E_NO_FILES); } hr = arcfile.init(PackedFile, imName); FIN_IF(hr, 0x302300 | E_EOPEN); DWORD attr = GetFileAttributesW(arcfile.get_fullname()); if (attr != INVALID_FILE_ATTRIBUTES) { if (attr & FILE_ATTRIBUTE_DIRECTORY) { WLOGe(L"%S: ERROR: can't replace directory!!! ", __func__); FIN(0x302400 | E_ECREATE); } WLOGw(L"%S: WARN: archive editing not supported!!! ", __func__); FIN(0x302500 | E_ECREATE); arcfile.clear(); hr = arcfile.init(PackedFile, imName | imAttr | imType); FIN_IF(hr, 0x302600 | E_EOPEN); // TODO: parse archive } m_inicfg.copy(cfg); wcx::packer::type ctype = wcx::packer::ctZstd; // create PAXZ on default LPCWSTR p = wcsrchr(PackedFile, L'.'); if (p) { if (_wcsicmp(p, L".pax") == 0) { ctype = wcx::packer::ctUnknown; cfg.set_uncompress_mode(); // without packing } if (_wcsicmp(p, L".lz4") == 0) { ctype = wcx::packer::ctLz4; } } packer = new wcx::packer(ctype, cfg, Flags, tid, m_ProcessDataProcW); FIN_IF(!packer, 0x303200 | E_NO_MEMORY); packer->set_AddListSize(AddListSize); packer->set_arcfile(arcfile); bool xb = m_plist.add(packer); FIN_IF(!xb, 0x303300 | E_NO_MEMORY); hr = packer->pack_files(SubPath, SrcPath, AddList); fin: if (packer) { if (!m_plist.del(packer)) { delete packer; } } LOGe_IF(hr, "%s: ERROR = 0x%X ", __func__, hr); InterlockedDecrement(&m_packer_count); return hr & 0xFF; } void plugin::destroy_all_packers() { //if (!m_plist.is_empty()) { // TerminateThread for all packers! (exclude m_main_thread_id) //} } } /* namespace */
24.123853
127
0.60715
remittor
b94beb1635e95f0f2a53b68cbe6e653381df716f
37,992
cpp
C++
projects/biogears/libBiogears/src/cdm/engine/PhysiologyEngineDynamicStabilization.cpp
faaizT/core
488b357deece8dd4f7be318eefb49f6330be8239
[ "Apache-2.0" ]
1
2020-10-23T18:23:00.000Z
2020-10-23T18:23:00.000Z
projects/biogears/libBiogears/src/cdm/engine/PhysiologyEngineDynamicStabilization.cpp
faaizT/core
488b357deece8dd4f7be318eefb49f6330be8239
[ "Apache-2.0" ]
5
2020-12-23T00:19:32.000Z
2020-12-29T20:53:58.000Z
projects/biogears/libBiogears/src/cdm/engine/PhysiologyEngineDynamicStabilization.cpp
vybhavramachandran/biogears-vybhav
7271c12b85a324a4f1494e0ce15942dc25bc4931
[ "Apache-2.0" ]
null
null
null
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************************/ #include <biogears/cdm/engine/PhysiologyEngineDynamicStabilization.h> //Standad Includes #include <cmath> //Project Includes #include <biogears/cdm/Serializer.h> #include <biogears/cdm/engine/PhysiologyEngine.h> #include <biogears/cdm/engine/PhysiologyEngineTrack.h> #include <biogears/cdm/properties/SEScalarTime.h> #include <biogears/cdm/scenario/SECondition.h> #include <biogears/cdm/scenario/requests/SEDataRequestManager.h> #include <biogears/cdm/substance/SESubstance.h> #include <biogears/cdm/system/SESystem.h> #include <biogears/cdm/utils/GeneralMath.h> #include <biogears/cdm/utils/TimingProfile.h> #include <biogears/engine/BioGearsPhysiologyEngine.h> namespace biogears { bool PhysiologyEngineDynamicStabilization::StabilizeRestingState(PhysiologyEngine& engine) { Info("Converging to a steady state"); return Stabilize(engine, GetRestingCriteria()); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::StabilizeFeedbackState(PhysiologyEngine& engine) { if (!HasFeedbackCriteria()) return true; Info("Converging feedback to a steady state"); return Stabilize(engine, GetFeedbackCriteria()); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::StabilizeConditions(PhysiologyEngine& engine, const std::vector<const SECondition*>& conditions) { if (conditions.empty()) return true; // Grab the criteria based on the conditions we have PhysiologyEngineDynamicStabilizationCriteria* sc; m_ActiveConditions.clear(); for (auto c : conditions) { sc = GetConditionCriteria(c->GetName()); if (sc == nullptr) { Error("Engine does not support Condition"); return false; } else m_ActiveConditions.push_back(sc); } if (m_ActiveConditions.size() == 1) { Info("Converging provided condition to a steady state"); return Stabilize(engine, *m_ActiveConditions[0]); } else { if (!Merge()) { Error("Unable to merge conditions"); return false; } Info("Converging provided conditions to a steady state"); return Stabilize(engine, m_MergedConditions); } } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::Stabilize(PhysiologyEngine& engine, const PhysiologyEngineDynamicStabilizationCriteria& criteria) { const std::vector<PropertyConvergence*>& properties = criteria.GetPropertyConvergence(); if (properties.empty()) return true; //nothing to do here... m_Cancelled = false; std::stringstream ss; TimingProfile profiler; if (m_LogProgress) { profiler.Start("Total"); profiler.Start("Status"); } // Execute System initialization time PhysiologyEngineTrack* tracker = engine.GetEngineTrack(); bool hasOptionalProperties = false; // Grab all the convergence properties for (PropertyConvergence* pc : properties) { if (pc->IsOptional()) { hasOptionalProperties = true; } if (tracker) { tracker->ConnectRequest(pc->GetDataRequest(), pc->GetDataRequestScalar()); } if (!pc->GetDataRequestScalar().HasScalar()) { ss << "Cannot find convergence property " << pc->GetDataRequest().GetName(); throw CommonDataModelException(ss.str()); } } ss.precision(3); double statusTime_s = 0; // Current time of this status cycle double statusStep_s = 10; //How long did it take to simulate this much time double stablizationTime_s = 0; double dT_s = engine.GetTimeStep(TimeUnit::s); PhysiologyEngineDynamicStabilizer stabilizer(dT_s, criteria); while (!(stabilizer.HasConverged() && stabilizer.HasConvergedOptional())) { if (m_Cancelled) break; if (stabilizer.HasExceededTime()) break; engine.AdvanceModelTime(); stablizationTime_s += dT_s; m_currentTime_s += dT_s; if (m_LogProgress) { statusTime_s += dT_s; if (statusTime_s > statusStep_s) { statusTime_s = 0; ss << "Converging System... it took " << profiler.GetElapsedTime_s("Status") << "s to simulate the past " << statusStep_s << "s" << std::flush; profiler.Reset("Status"); Info(ss); } } stabilizer.Converge(); } double covTime_s = criteria.GetConvergenceTime(TimeUnit::s); if (stabilizer.HasExceededTime()) { Error("Could not converge to provided criteria"); for (PropertyConvergence* pc : properties) { if (stablizationTime_s - pc->GetLastErrorTime_s() < covTime_s) { m_ss << stablizationTime_s << "s - " << pc->GetDataRequest().GetName() << " is not converging, last error time was " << pc->GetLastErrorTime_s() << "s setting a target value of " << pc->GetCurrentTarget() << " and the current value is " << pc->GetDataRequestScalar().GetValue(); Error(m_ss); } /* else { m_ss << stablizationTime_s << "s - " << pc->GetDataRequest().GetName() << " is converging, last error time was " << pc->GetLastErrorTime_s() << "s"; Info(m_ss); }*/ } return false; } else if (m_LogProgress) { ss << "Convergence took " << profiler.GetElapsedTime_s("Total") << "s to simulate " << stablizationTime_s << "s to get engine to a steady state"; Info(ss); if (hasOptionalProperties && !stabilizer.HasConvergedOptional()) { ss << "Could not converge optional properties"; Warning(ss); for (PropertyConvergence* pc : properties) { if (stablizationTime_s - pc->GetLastErrorTime_s() < covTime_s) { m_ss << stablizationTime_s << "s - " << pc->GetDataRequest().GetName() << " is not converging, last error time was " << pc->GetLastErrorTime_s() << "s setting a target value of " << pc->GetCurrentTarget() << " and the current value is " << pc->GetDataRequestScalar().GetValue(); Error(m_ss); } } } } // Save off how long it took us to stabilize GetStabilizationDuration().SetValue(stablizationTime_s, TimeUnit::s); return true; } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilizer::PhysiologyEngineDynamicStabilizer(double timeStep_s, const PhysiologyEngineDynamicStabilizationCriteria& criteria) : Loggable(criteria.GetLogger()) , m_properties(criteria.GetPropertyConvergence()) { m_dT_s = timeStep_s; m_totTime_s = 0; m_passTime_s = 0; m_optsPassTime_s = 0; m_covTime_s = criteria.GetConvergenceTime(TimeUnit::s); m_minTime_s = criteria.GetMinimumReactionTime(TimeUnit::s); m_maxTime_s = criteria.GetMaximumAllowedStabilizationTime(TimeUnit::s) + m_minTime_s; // We will run for at least minTime, THEN to the max time, so maxTime_s is the sum of both m_converged = false; m_convergedOptional = false; m_exceededTime = false; m_hasOptionalProperties = false; for (PropertyConvergence* pc : m_properties) { if (pc->IsOptional()) { m_hasOptionalProperties = true; break; } } if (!m_hasOptionalProperties) m_convergedOptional = true; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilizer::Converge() { bool passedTimeStep = false; bool passedTimeStepOptions = false; m_totTime_s += m_dT_s; if (m_totTime_s < m_minTime_s) return; // Wait for it std::stringstream ss; passedTimeStep = true; passedTimeStepOptions = true; for (PropertyConvergence* pc : m_properties) { bool b = pc->Test(m_totTime_s); if (pc->IsOptional()) { passedTimeStepOptions &= b; } else { passedTimeStep &= b; } } if (passedTimeStep) m_passTime_s += m_dT_s; else m_passTime_s = 0; if (passedTimeStepOptions) m_optsPassTime_s += m_dT_s; else m_optsPassTime_s = 0; if (!m_converged && m_passTime_s >= m_covTime_s) { // We have converged m_converged = true; if (m_hasOptionalProperties) Warning("We have passed required convergence criteria, attempting to converge optional properties from multiple conditions."); } if (m_converged && m_optsPassTime_s >= m_covTime_s) { // We have converged optional props m_convergedOptional = true; Warning("We have passed required and optional convergence criteria."); } if (m_totTime_s > m_maxTime_s) { m_converged = false; m_convergedOptional = false; m_exceededTime = true; } } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::Merge() { // Get a std::hash<std::string>()("foo"); for each Property convergence Data Request // Don't forget to add hashes of compartments and substance names! if applicable // Put it in a map<hash#,vector<PropertyConvergence*>> // After this loop, go through the map and remove any // entries where the vector length is < activeConditions.size() // We only want convergence objects if ALL active conditions have them // From there find the PropertyConvergence with the largest %diff // Add that pointer to the m_MergedConditions (will need new friend method as that method should not be public) Info("Merging Conditions"); m_MergedConditions.Clear(); m_MergedConditions.SetName("MergedCondition"); // May want to include what conditions we are combining in the name? double time_s; double maxConv_s = 0; double maxMinStabilize_s = 0; double maxMaxStabilize_s = 0; const std::vector<PropertyConvergence*>* vCondPConv; std::map<std::string, std::vector<PropertyConvergence*>*> cMap; for (const PhysiologyEngineDynamicStabilizationCriteria* c : m_ActiveConditions) { m_ss << "Analyzing " << c->GetName(); Info(m_ss); vCondPConv = &c->GetPropertyConvergence(); for (PropertyConvergence* pConv : *vCondPConv) { auto cMapItr = cMap.find(pConv->GetDataRequest().GetName()); if (cMapItr != cMap.end()) cMapItr->second->push_back(pConv); else { std::vector<PropertyConvergence*>* vec = new std::vector<PropertyConvergence*>(); vec->push_back(pConv); cMap[pConv->GetDataRequest().GetName()] = vec; } } time_s = c->GetConvergenceTime(TimeUnit::s); if (time_s > maxConv_s) maxConv_s = time_s; time_s = c->GetMinimumReactionTime(TimeUnit::s); if (time_s > maxMinStabilize_s) maxMinStabilize_s = time_s; time_s = c->GetMaximumAllowedStabilizationTime(TimeUnit::s); if (time_s > maxMaxStabilize_s) maxMaxStabilize_s = time_s; } double tmpError; PropertyConvergence* pConv; for (auto i = cMap.begin(); i != cMap.end(); i++) { // Let's find the Convergence that has the largest % difference double pErr = 0; for (auto j = i->second->begin(); j != i->second->end(); j++) { tmpError = (*j)->GetPercentError(); if (tmpError > pErr) { pErr = tmpError; pConv = (*j); } } if (i->second->size() == m_ActiveConditions.size()) { m_ss << "Merged Convergance for property " << pConv->GetDataRequest().GetName() << " using " << pConv->GetPercentError() << "% error"; Info(m_ss); } else { pConv->SetOptional(true); m_ss << "Not all conditions contain " << i->first << " in convergence criteria. Making convergence on this property optional."; Warning(m_ss); } m_MergedConditions.m_PropertyConvergence.push_back(pConv); } DELETE_MAP_SECOND(cMap); // Clean up our Map m_MergedConditions.GetConvergenceTime().SetValue(maxConv_s, TimeUnit::s); m_ss << "Merged Convergence Time : " << m_MergedConditions.GetConvergenceTime(); Info(m_ss); m_MergedConditions.GetMinimumReactionTime().SetValue(maxMinStabilize_s, TimeUnit::s); m_ss << "Merged Minimum Reaction Time : " << m_MergedConditions.GetMinimumReactionTime(); Info(m_ss); m_MergedConditions.GetMaximumAllowedStabilizationTime().SetValue(maxMaxStabilize_s, TimeUnit::s); m_ss << "Merged Maximum Allowed Stabilization Time : " << m_MergedConditions.GetMaximumAllowedStabilizationTime(); Info(m_ss); return true; } //----------------------------------------------------------------------------- // This basically tests the current property with the target property and if they are in a window of acceptance bool PropertyConvergence::Test(double time_s) { double v = !m_DataRequestScalar.HasUnit() ? m_DataRequestScalar.GetValue() : m_DataRequestScalar.GetValue(m_DataRequestScalar.GetUnit()->GetString()); if (std::isnan(m_Target)) { m_Target = v; return false; // Initially target will be NaN until it is pulled for the first time } m_LastError = GeneralMath::PercentTolerance(m_Target, v); if (m_LastError < m_Error) { return true; } m_ss << time_s << "s - Resetting the target for " << GetDataRequest().GetName() << " to " << v << ", the last target value was " << m_Target; Info(m_ss); // Not converging, so this is now our target property m_Target = v; m_LastErrorTime_s = time_s; return false; } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilization::PhysiologyEngineDynamicStabilization(Logger* logger) : PhysiologyEngineStabilization(logger) , m_RestingCriteria(logger) , m_MergedConditions(logger) { m_FeedbackCriteria = nullptr; m_RestingCriteria.SetName("Resting"); } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilization::~PhysiologyEngineDynamicStabilization() { Clear(); } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilization::Clear() { PhysiologyEngineStabilization::Clear(); m_MergedConditions.m_PropertyConvergence.clear(); // \todo Make copies of stabilization criteria m_MergedConditions.Clear(); m_ActiveConditions.clear(); m_RestingCriteria.Clear(); SAFE_DELETE(m_FeedbackCriteria); DELETE_VECTOR(m_ConditionCriteria); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::Load(const CDM::PhysiologyEngineDynamicStabilizationData& in) { PhysiologyEngineStabilization::Load(in); GetRestingCriteria().Load(in.RestingStabilizationCriteria()); if (in.FeedbackStabilizationCriteria().present()) GetFeedbackCriteria().Load(in.FeedbackStabilizationCriteria().get()); for (auto cData : in.ConditionStabilization()) { PhysiologyEngineDynamicStabilizationCriteria* c = new PhysiologyEngineDynamicStabilizationCriteria(GetLogger()); c->Load(cData.Criteria()); c->SetName(cData.Name()); AddConditionCriteria(*c); } return true; } //----------------------------------------------------------------------------- CDM::PhysiologyEngineDynamicStabilizationData* PhysiologyEngineDynamicStabilization::Unload() const { CDM::PhysiologyEngineDynamicStabilizationData* data(new CDM::PhysiologyEngineDynamicStabilizationData()); Unload(*data); return data; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilization::Unload(CDM::PhysiologyEngineDynamicStabilizationData& data) const { PhysiologyEngineStabilization::Unload(data); data.RestingStabilizationCriteria(std::unique_ptr<CDM::PhysiologyEngineDynamicStabilizationCriteriaData>(GetRestingCriteria().Unload())); if (HasFeedbackCriteria()) data.FeedbackStabilizationCriteria(std::unique_ptr<CDM::PhysiologyEngineDynamicStabilizationCriteriaData>(GetFeedbackCriteria()->Unload())); for (auto& c : m_ConditionCriteria) { std::unique_ptr<CDM::PhysiologyEngineDynamicConditionStabilizationData> csData(new CDM::PhysiologyEngineDynamicConditionStabilizationData()); csData->Criteria(std::unique_ptr<CDM::PhysiologyEngineDynamicStabilizationCriteriaData>(c->Unload())); csData->Name(c->GetName()); data.ConditionStabilization().push_back(*csData); } } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::Load(const char* file) { return Load(std::string { file }); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::Load(const std::string& file) { CDM::PhysiologyEngineDynamicStabilizationData* pData; std::unique_ptr<CDM::ObjectData> data; data = Serializer::ReadFile(file, GetLogger()); pData = dynamic_cast<CDM::PhysiologyEngineDynamicStabilizationData*>(data.get()); if (pData == nullptr) { std::stringstream ss; ss << "Unable to read stabilization file : " << file << std::endl; Info(ss); return false; } return Load(*pData); } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilizationCriteria& PhysiologyEngineDynamicStabilization::GetRestingCriteria() { return m_RestingCriteria; } //----------------------------------------------------------------------------- const PhysiologyEngineDynamicStabilizationCriteria& PhysiologyEngineDynamicStabilization::GetRestingCriteria() const { return m_RestingCriteria; } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilization::HasFeedbackCriteria() const { return m_FeedbackCriteria != nullptr; } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilizationCriteria& PhysiologyEngineDynamicStabilization::GetFeedbackCriteria() { if (m_FeedbackCriteria == nullptr) { m_FeedbackCriteria = new PhysiologyEngineDynamicStabilizationCriteria(GetLogger()); m_FeedbackCriteria->SetName("Feedback"); } return *m_FeedbackCriteria; } //----------------------------------------------------------------------------- const PhysiologyEngineDynamicStabilizationCriteria* PhysiologyEngineDynamicStabilization::GetFeedbackCriteria() const { return m_FeedbackCriteria == nullptr ? nullptr : m_FeedbackCriteria; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilization::RemoveConditionCriteria(const char* name) { RemoveConditionCriteria(std::string { name }); } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilization::RemoveConditionCriteria(const std::string& name) { for (auto itr = m_ConditionCriteria.begin(); itr != m_ConditionCriteria.end(); itr++) { if ((*itr)->GetName() == name) { m_ConditionCriteria.erase(itr); return; } } } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilizationCriteria* PhysiologyEngineDynamicStabilization::GetConditionCriteria(const char* name) const { return GetConditionCriteria(std::string { name }); } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilizationCriteria* PhysiologyEngineDynamicStabilization::GetConditionCriteria(const std::string& name) const { for (auto c : m_ConditionCriteria) { if (c->GetName() == name) return c; } return nullptr; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilization::AddConditionCriteria(PhysiologyEngineDynamicStabilizationCriteria& criteria) { for (auto c : m_ConditionCriteria) { if (c->GetName() == criteria.GetName()) return; } m_ConditionCriteria.push_back(&criteria); } //----------------------------------------------------------------------------- const std::vector<PhysiologyEngineDynamicStabilizationCriteria*>& PhysiologyEngineDynamicStabilization::GetConditionCriteria() const { return m_ConditionCriteria; } //----------------------------------------------------------------------------- ////////////////////////////////////////////////// // PhysiologyEngineDynamicStabilizationCriteria // ////////////////////////////////////////////////// PhysiologyEngineDynamicStabilizationCriteria::PhysiologyEngineDynamicStabilizationCriteria(Logger* logger) : Loggable(logger) , m_DataRequestMgr(logger) { m_ConvergenceTime = nullptr; m_MinimumReactionTime = nullptr; m_MaximumAllowedStabilizationTime = nullptr; } //----------------------------------------------------------------------------- PhysiologyEngineDynamicStabilizationCriteria::~PhysiologyEngineDynamicStabilizationCriteria() { Clear(); } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilizationCriteria::Clear() { SAFE_DELETE(m_ConvergenceTime); SAFE_DELETE(m_MinimumReactionTime); SAFE_DELETE(m_MaximumAllowedStabilizationTime); DELETE_VECTOR(m_PropertyConvergence); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilizationCriteria::Load(const CDM::PhysiologyEngineDynamicStabilizationCriteriaData& in) { Clear(); GetConvergenceTime().Load(in.ConvergenceTime()); GetMinimumReactionTime().Load(in.MinimumReactionTime()); GetMaximumAllowedStabilizationTime().Load(in.MaximumAllowedStabilizationTime()); for (auto pcData : in.PropertyConvergence()) CreateSystemPropertyConvergence(pcData.PercentDifference(), pcData.Name()); return true; } //----------------------------------------------------------------------------- CDM::PhysiologyEngineDynamicStabilizationCriteriaData* PhysiologyEngineDynamicStabilizationCriteria::Unload() const { CDM::PhysiologyEngineDynamicStabilizationCriteriaData* data(new CDM::PhysiologyEngineDynamicStabilizationCriteriaData()); Unload(*data); return data; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilizationCriteria::Unload(CDM::PhysiologyEngineDynamicStabilizationCriteriaData& data) const { data.ConvergenceTime(std::unique_ptr<CDM::ScalarTimeData>(m_ConvergenceTime->Unload())); data.MinimumReactionTime(std::unique_ptr<CDM::ScalarTimeData>(m_MinimumReactionTime->Unload())); data.MaximumAllowedStabilizationTime(std::unique_ptr<CDM::ScalarTimeData>(m_MaximumAllowedStabilizationTime->Unload())); for (auto pc : m_PropertyConvergence) { std::unique_ptr<CDM::PhysiologyEngineDynamicStabilizationCriteriaPropertyData> pcData(new CDM::PhysiologyEngineDynamicStabilizationCriteriaPropertyData()); pcData->Name(pc->GetDataRequest().GetName()); pcData->PercentDifference(pc->m_Target); data.PropertyConvergence().push_back(*pcData.get()); } } //----------------------------------------------------------------------------- std::string PhysiologyEngineDynamicStabilizationCriteria::GetName() const { return m_Name; } //----------------------------------------------------------------------------- const char* PhysiologyEngineDynamicStabilizationCriteria::GetName_cStr() const { return m_Name.c_str(); } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilizationCriteria::SetName(const char* name) { m_Name = name; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilizationCriteria::SetName(const std::string& name) { m_Name = name; } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilizationCriteria::HasName() const { return m_Name.empty() ? false : true; } //----------------------------------------------------------------------------- void PhysiologyEngineDynamicStabilizationCriteria::InvalidateName() { m_Name = ""; } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilizationCriteria::HasConvergenceTime() const { return m_ConvergenceTime == nullptr ? false : m_ConvergenceTime->IsValid(); } //----------------------------------------------------------------------------- SEScalarTime& PhysiologyEngineDynamicStabilizationCriteria::GetConvergenceTime() { if (m_ConvergenceTime == nullptr) m_ConvergenceTime = new SEScalarTime(); return *m_ConvergenceTime; } //----------------------------------------------------------------------------- double PhysiologyEngineDynamicStabilizationCriteria::GetConvergenceTime(const TimeUnit& unit) const { if (m_ConvergenceTime == nullptr) return SEScalar::dNaN(); return m_ConvergenceTime->GetValue(unit); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilizationCriteria::HasMinimumReactionTime() const { return m_MinimumReactionTime == nullptr ? false : m_MinimumReactionTime->IsValid(); } //----------------------------------------------------------------------------- SEScalarTime& PhysiologyEngineDynamicStabilizationCriteria::GetMinimumReactionTime() { if (m_MinimumReactionTime == nullptr) m_MinimumReactionTime = new SEScalarTime(); return *m_MinimumReactionTime; } //----------------------------------------------------------------------------- double PhysiologyEngineDynamicStabilizationCriteria::GetMinimumReactionTime(const TimeUnit& unit) const { if (m_MinimumReactionTime == nullptr) return SEScalar::dNaN(); return m_MinimumReactionTime->GetValue(unit); } //----------------------------------------------------------------------------- bool PhysiologyEngineDynamicStabilizationCriteria::HasMaximumAllowedStabilizationTime() const { return m_MaximumAllowedStabilizationTime == nullptr ? false : m_MaximumAllowedStabilizationTime->IsValid(); } //----------------------------------------------------------------------------- SEScalarTime& PhysiologyEngineDynamicStabilizationCriteria::GetMaximumAllowedStabilizationTime() { if (m_MaximumAllowedStabilizationTime == nullptr) m_MaximumAllowedStabilizationTime = new SEScalarTime(); return *m_MaximumAllowedStabilizationTime; } //----------------------------------------------------------------------------- double PhysiologyEngineDynamicStabilizationCriteria::GetMaximumAllowedStabilizationTime(const TimeUnit& unit) const { if (m_MaximumAllowedStabilizationTime == nullptr) return SEScalar::dNaN(); return m_MaximumAllowedStabilizationTime->GetValue(unit); } //----------------------------------------------------------------------------- /// \brief /// Sets convergence critera for a specific properter. /// /// \param percentError - The acceptable percent difference window that the specified property /// must stay within for a specified amount of time for convergence to happen /// /// \param name - The name of the property to converge /// /// \details /// Mulitple convergence property criteria can be specified. All properties must converge for the // specified convergence time. Percent Difference is calculated as such : Math.abs(difference / average) * 100.0 //-------------------------------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateSystemPropertyConvergence(double percentError, const char* name) { return CreateSystemPropertyConvergence(percentError, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateSystemPropertyConvergence(double percentError, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name.c_str()) return *pc; } PropertyConvergence* p = new PropertyConvergence(m_DataRequestMgr.CreatePhysiologyDataRequest(), GetLogger()); p->m_DataRequest.SetName(name); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- /// \brief /// Sets convergence critera for a specific properter. /// /// \param percentError - The acceptable percent difference window that the specified property /// must stay within for a specified amount of time for convergence to happen /// /// \param cmpt - The name of the compartment /// /// \details /// Mulitple convergence property criteria can be specified. All properties must converge for the // specified convergence time. Percent Difference is calculated as such : Math.abs(difference / average) * 100.0 //-------------------------------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateGasCompartmentPropertyConvergence(double percentError, const char* cmpt, const char* name) { return CreateGasCompartmentPropertyConvergence(percentError, std::string { cmpt }, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateGasCompartmentPropertyConvergence(double percentError, const std::string& cmpt, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name) return *pc; } SEGasCompartmentDataRequest& dr = m_DataRequestMgr.CreateGasCompartmentDataRequest(); dr.SetCompartment(cmpt); dr.SetName(name); PropertyConvergence* p = new PropertyConvergence(dr, GetLogger()); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateGasCompartmentPropertyConvergence(double percentError, const char* cmpt, SESubstance& substance, const char* name) { return CreateGasCompartmentPropertyConvergence(percentError, std::string { cmpt }, substance, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateGasCompartmentPropertyConvergence(double percentError, const std::string& cmpt, SESubstance& substance, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name.c_str()) return *pc; } SEGasCompartmentDataRequest& dr = m_DataRequestMgr.CreateGasCompartmentDataRequest(); dr.SetCompartment(cmpt); dr.SetName(name); dr.SetSubstance(&substance); PropertyConvergence* p = new PropertyConvergence(dr, GetLogger()); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateLiquidCompartmentPropertyConvergence(double percentError, const char* cmpt, const char* name) { return CreateLiquidCompartmentPropertyConvergence(percentError, std::string { cmpt }, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateLiquidCompartmentPropertyConvergence(double percentError, const std::string& cmpt, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name.c_str()) return *pc; } SELiquidCompartmentDataRequest& dr = m_DataRequestMgr.CreateLiquidCompartmentDataRequest(); dr.SetCompartment(cmpt); dr.SetName(name); PropertyConvergence* p = new PropertyConvergence(dr, GetLogger()); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateLiquidCompartmentPropertyConvergence(double percentError, const char* cmpt, SESubstance& substance, const char* name) { return CreateLiquidCompartmentPropertyConvergence(percentError, std::string { cmpt }, substance, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateLiquidCompartmentPropertyConvergence(double percentError, const std::string& cmpt, SESubstance& substance, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name) return *pc; } SELiquidCompartmentDataRequest& dr = m_DataRequestMgr.CreateLiquidCompartmentDataRequest(); dr.SetCompartment(cmpt); dr.SetName(name); dr.SetSubstance(&substance); PropertyConvergence* p = new PropertyConvergence(dr, GetLogger()); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateThermalCompartmentPropertyConvergence(double percentError, const char* cmpt, const char* name) { return CreateThermalCompartmentPropertyConvergence(percentError, std::string { cmpt }, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateThermalCompartmentPropertyConvergence(double percentError, const std::string& cmpt, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name) return *pc; } SEThermalCompartmentDataRequest& dr = m_DataRequestMgr.CreateThermalCompartmentDataRequest(); dr.SetCompartment(cmpt); dr.SetName(name); PropertyConvergence* p = new PropertyConvergence(dr, GetLogger()); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateTissueCompartmentPropertyConvergence(double percentError, const char* cmpt, const char* name) { return CreateTissueCompartmentPropertyConvergence(percentError, std::string { cmpt }, std::string { name }); } //----------------------------------------------------------------------------- PropertyConvergence& PhysiologyEngineDynamicStabilizationCriteria::CreateTissueCompartmentPropertyConvergence(double percentError, const std::string& cmpt, const std::string& name) { for (PropertyConvergence* pc : m_PropertyConvergence) { if (pc->m_DataRequest.GetName() == name) return *pc; } SETissueCompartmentDataRequest& dr = m_DataRequestMgr.CreateTissueCompartmentDataRequest(); dr.SetCompartment(cmpt); dr.SetName(name); PropertyConvergence* p = new PropertyConvergence(dr, GetLogger()); p->m_Error = percentError; m_PropertyConvergence.push_back(p); return *p; } //----------------------------------------------------------------------------- const std::vector<PropertyConvergence*>& PhysiologyEngineDynamicStabilizationCriteria::GetPropertyConvergence() const { return m_PropertyConvergence; } //----------------------------------------------------------------------------- ///////////////////////// // PropertyConvergence // ///////////////////////// PropertyConvergence::PropertyConvergence(SEDataRequest& dr, Logger* logger) : Loggable(logger) , m_DataRequest(dr) , m_DataRequestScalar(logger) { m_Error = 0; m_Target = 0; m_LastError = 0; m_LastErrorTime_s = 0; m_Optional = false; m_LastError = SEScalar::dNaN(); m_Target = SEScalar::dNaN(); } //----------------------------------------------------------------------------- PropertyConvergence::~PropertyConvergence() { } //----------------------------------------------------------------------------- void PropertyConvergence::TrackScalar(const SEScalar& s) { m_DataRequestScalar.SetScalar(&s, m_DataRequest); } //----------------------------------------------------------------------------- double PropertyConvergence::GetPercentError() const { return m_Error; } //----------------------------------------------------------------------------- double PropertyConvergence::GetLastPercentError() const { return m_LastError; } //----------------------------------------------------------------------------- double PropertyConvergence::GetLastErrorTime_s() const { return m_LastErrorTime_s; } //----------------------------------------------------------------------------- double PropertyConvergence::GetCurrentTarget() const { return m_Target; } //----------------------------------------------------------------------------- SEDataRequest& PropertyConvergence::GetDataRequest() const { return m_DataRequest; } //----------------------------------------------------------------------------- SEDataRequestScalar& PropertyConvergence::GetDataRequestScalar() { return m_DataRequestScalar; } //----------------------------------------------------------------------------- bool PropertyConvergence::IsOptional() const { return m_Optional; } //----------------------------------------------------------------------------- void PropertyConvergence::SetOptional(bool b) { m_Optional = b; } //----------------------------------------------------------------------------- }
43.369863
288
0.628053
faaizT
b94d28d5edd1ff76f25a1ebe8dcccdadaa510f5b
87,176
hpp
C++
TakistanRoleplay/Config_Spyglass.hpp
hdvertgaming/TakistanRoleplay
56ba5bf9f9d67d6cab20cecf0681c663b2f5d731
[ "Apache-2.0" ]
null
null
null
TakistanRoleplay/Config_Spyglass.hpp
hdvertgaming/TakistanRoleplay
56ba5bf9f9d67d6cab20cecf0681c663b2f5d731
[ "Apache-2.0" ]
null
null
null
TakistanRoleplay/Config_Spyglass.hpp
hdvertgaming/TakistanRoleplay
56ba5bf9f9d67d6cab20cecf0681c663b2f5d731
[ "Apache-2.0" ]
null
null
null
class SpyGlass { civSlotNumber = 75; copSlotNumber = 19; medSlotNumber = 4; /* Internal functions, sort by what they are. Please note any functions you add need the functions named defined and the functions meta name which is the functions name + _meta i.e: "life_fnc_mycoolfunction","life_fnc_mycoolfunction_meta" */ BIS_Functions[] = {"bis_fnc_shownotification_counter","bis_fnc_shownotification_process","bis_fnc_missionhandlers_reloads","bis_fnc_feedback_deltadamage","bis_fnc_selectrespawntemplates_args","bis_fnc_dbvalueindex","bis_fnc_overviewterrain","bis_fnc_dotproduct","bis_fnc_vrcourselaunchers3","bis_fnc_moduleprojectile","bis_fnc_initmodules_ordnance","bis_fnc_setunitinsignia","bis_fnc_getunitinsignia","bis_fnc_getrespawninventories","bis_fnc_dbsymbolclass","bis_fnc_dbvaluelist","bis_fnc_assignplayerrole","bis_fnc_boundingboxmarker","bis_fnc_magnitude","bis_fnc_unitvector","bis_fnc_skirmishtrigger","bis_fnc_initmodules_audio","bis_fnc_sortalphabetically","bis_fnc_inv","bis_fnc_modulecuratoraddpoints","bis_fnc_setmissionstatusslot","bis_fnc_prepareao","bis_fnc_disableloading","bis_fnc_taskhint","bis_fnc_missilelaunchpositionfix","bis_fnc_help","bis_fnc_inanglesector","bis_fnc_curatorobjectregisteredtable","bis_fnc_initrespawnbackpack","bis_fnc_paramviewdistance","bis_fnc_modulepunishment","bis_fnc_localize","bis_fnc_displaycolorget","bis_fnc_dbimportconfig","bis_fnc_vectordiff","bis_fnc_moduleweather","bis_fnc_moduleobjectivesector","bis_fnc_ambientflyby","bis_fnc_onplayerconnected","bis_fnc_feedbackinit","bis_fnc_unitcapture","bis_fnc_arrayunshift","bis_fnc_spawncrew","bis_fnc_playendmusic","bis_fnc_moduleeffectsfire","bis_fnc_modulecreatediaryrecord","bis_fnc_loadfunctions","bis_fnc_missiontaskslocal","bis_fnc_validateparametersoo","bis_fnc_establishingshot","bis_fnc_texttiles","bis_fnc_getvirtualmagazinecargo","bis_fnc_target","bis_fnc_listcuratorplayers","bis_fnc_setfog","bis_fnc_initmodules_intel","bis_fnc_error","bis_fnc_getcfgdatapool","bis_fnc_isinsidearea","bis_fnc_kbmenu","bis_fnc_setidentity","bis_fnc_displayclouds","bis_fnc_configextremes","bis_fnc_orbatconfigpreview","bis_fnc_helicoptercanfly","bis_fnc_curatorobjectregistered","bis_fnc_ffvupdate","bis_fnc_initmodules_animals","bis_fnc_allsynchronizedobjects","bis_fnc_initplayable","bis_fnc_tasksetdestination","bis_fnc_diagjiralink","bis_fnc_exportfunctionstowiki","bis_fnc_modulefdcpout","bis_fnc_paramweather","bis_fnc_taskattack","bis_fnc_bleedtickets","bis_fnc_overviewauthor","bis_fnc_dbimportxml","bis_fnc_diagmacrosauthor","bis_fnc_respawncounter","bis_fnc_vrcoursecommandingactions1","bis_fnc_showcuratorfeedbackmessage","bis_fnc_moduleslingload","bis_fnc_diagknowntargets","bis_fnc_quotations","bis_fnc_configpath","bis_fnc_taskcompleted","bis_fnc_diagaarrecord","bis_fnc_scenegetobjects","bis_fnc_vrcoursecommandingactions2","bis_fnc_moduleai","bis_fnc_modulemissionname","bis_fnc_modulettcpin","bis_fnc_ftlmanager","bis_fnc_randomindex","bis_fnc_vrcoursecommandingactions3","bis_fnc_curatorrespawn","bis_fnc_curatorautomaticpositions","bis_fnc_moduletracers","bis_fnc_subclasses","bis_fnc_removesupportlink","bis_fnc_splitstring","bis_fnc_unpackstaticweapon","bis_fnc_radialred","bis_fnc_vrfadein","bis_fnc_livefeedmoduleinit","bis_fnc_initmodules_multiplayer","bis_fnc_execvm","bis_fnc_relposobject","bis_fnc_terraingradangle","bis_fnc_shakegauges","bis_fnc_scenegetpositionbyangle","bis_fnc_objectsgrabber","bis_fnc_curatorobjectplaced","bis_fnc_livefeed","bis_fnc_respawnnone","bis_fnc_moduleunits","bis_fnc_animtype","bis_fnc_sandstorm","bis_fnc_nearestposition","bis_fnc_selectcrew","bis_fnc_modulechat","bis_fnc_modulecuratoraddaddons","bis_fnc_moduleobjectiveracefinish","bis_fnc_feedback_fatiguecc","bis_fnc_ordinalnumber","bis_fnc_dbclassid","bis_fnc_registercuratorobject","bis_fnc_vrcoursehelislingload1","bis_fnc_modulecombatgetin","bis_fnc_modulerating","bis_fnc_moduleskiptime","bis_fnc_feedback_fatigueradialblur","bis_fnc_taskdescription","bis_fnc_moduletaskcreate","bis_fnc_moduleammo","bis_fnc_effectkilledairdestructionstage2","bis_fnc_instructorfigure","bis_fnc_livefeedsetsource","bis_fnc_addtopairs","bis_fnc_credits","bis_fnc_buildingpositions","bis_fnc_getrespawnmarkers","bis_fnc_posdegtoutm","bis_fnc_addvirtualbackpackcargo","bis_fnc_moveaction","bis_fnc_modulemptypesectorcontrol","bis_fnc_damagepulsing","bis_fnc_taskcurrent","bis_fnc_diagmissionpositions","bis_fnc_findnestedelement","bis_fnc_vrcoursetargetdesignation1","bis_fnc_monthdays","bis_fnc_helicopterseatmove","bis_fnc_mp","bis_fnc_invslotsempty","bis_fnc_commsmenutogglevisibility","bis_fnc_vrcoursetargetdesignation2","bis_fnc_moduleskill","bis_fnc_diagaarrecord_fsm","bis_fnc_respawnendmission","bis_fnc_selectrespawntemplate","bis_fnc_ambientblacklistadd","bis_fnc_livefeedeffects","bis_fnc_vrcoursetargetdesignation3","bis_fnc_iscuratoreditable","bis_fnc_curatorchallengegetinvehicle","bis_fnc_neutralizeunit","bis_fnc_moduleanimals","bis_fnc_dbisclass","bis_fnc_kbisspeaking","bis_fnc_arraypushstack","bis_fnc_invstring","bis_fnc_effectfiredartillery","bis_fnc_iscampaign","bis_fnc_changesupportradiochannel","bis_fnc_boundingboxcorner","bis_fnc_modulezoneprotection","bis_fnc_initmodules_objectives","bis_fnc_limitsupport","bis_fnc_trimstring","bis_fnc_dbclasslist","bis_fnc_diagknownastarget","bis_fnc_createobjectoo","bis_fnc_kmlimport","bis_fnc_randomint","bis_fnc_diagpreviewvehiclecrew","bis_fnc_crewcount","bis_fnc_dbvalueset","bis_fnc_conditionalselect","bis_fnc_scenesetanimationsforgroup","bis_fnc_setobjecttexture","bis_fnc_modulecuratorsetcostsdefault","bis_fnc_modulecountdown","bis_fnc_respawninstant","bis_fnc_teamcolor","bis_fnc_deletetask","bis_fnc_swapvars","bis_fnc_setcuratorattributes","bis_fnc_keycode","bis_fnc_animviewer","bis_fnc_objecttype","bis_fnc_gcinit","bis_fnc_removevirtualitemcargo","bis_fnc_moduledooropen","bis_fnc_removecommmenuitem","bis_fnc_orbatsetgroupparams","bis_fnc_rankparams","bis_fnc_initrespawn","bis_fnc_randompostrigger","bis_fnc_vrcoursecommandingmovement1","bis_fnc_livefeedmodulesettarget","bis_fnc_modulebootcampstage","bis_fnc_moduleobjectivemove","bis_fnc_typetext","bis_fnc_fatigueeffect","bis_fnc_countdown","bis_fnc_customgps","bis_fnc_getlinedist","bis_fnc_taskpatrol","bis_fnc_vrcoursecommandingmovement2","bis_fnc_moduletasksetdescription","bis_fnc_livefeedmoduleeffects","bis_fnc_moduledamage","bis_fnc_paramdaytime","bis_fnc_guigridtoprofile","bis_fnc_curatorobjectedited","bis_fnc_moduleeffectsshells","bis_fnc_animalsitespawn","bis_fnc_modulesfx","bis_fnc_guieffecttiles","bis_fnc_sideid","bis_fnc_moduletimetrial","bis_fnc_unitplayfiring","bis_fnc_setdate","bis_fnc_kbtell","bis_fnc_exportcfgvehicles","bis_fnc_incapacitatedeffect","bis_fnc_selectrandom","bis_fnc_vectoradd","bis_fnc_spawngroup","bis_fnc_removedestroyedcuratoreditableobjects","bis_fnc_modulevolume","bis_fnc_startloadingscreen_ids","bis_fnc_uniqueclasses","bis_fnc_getcfgdataobject","bis_fnc_scenesetbehaviour","bis_fnc_vectorfromxtoy","bis_fnc_vrcourseplaceables1","bis_fnc_modulearsenal","bis_fnc_modulecuratorsetobjectcost","bis_fnc_modulecuratorsetcoefs","bis_fnc_romannumeral","bis_fnc_diagloop","bis_fnc_diagradio","bis_fnc_overviewmission","bis_fnc_numberdigits","bis_fnc_vrcourseplaceables2","bis_fnc_moduleobjectiveracestart","bis_fnc_initmodules_no_category","bis_fnc_errormsg","bis_fnc_consolidatearray","bis_fnc_taskchildren","bis_fnc_addrespawninventory","bis_fnc_customgpsvideo","bis_fnc_returnvehicleturrets","bis_fnc_vrcourseplaceables3","bis_fnc_moduleposter","bis_fnc_initmodules_groupmodifiers","bis_fnc_initmodules_chemlights","bis_fnc_rsclayer_list","bis_fnc_startloadingscreen","bis_fnc_effectplankton","bis_fnc_paramrespawntickets","bis_fnc_modulecuratorsetcostsvehicleclass","bis_fnc_effectfiredlongsmoke","bis_fnc_setrank","bis_fnc_distance2dsqr","bis_fnc_zzrotate","bis_fnc_sceneintruderdetector","bis_fnc_curatorchallengefireweapon","bis_fnc_isloading","bis_fnc_overviewtimetrial","bis_fnc_earthquake","bis_fnc_texturemarker","bis_fnc_arrayfinddeep","bis_fnc_setcuratorvisionmodes","bis_fnc_locweaponinfo","bis_fnc_disablesaving","bis_fnc_singlemissionconfig","bis_fnc_setnestedelement","bis_fnc_taskdefend","bis_fnc_vrcoursecommandingbehaviour1","bis_fnc_initmodules_training","bis_fnc_movein","bis_fnc_scriptedmove","bis_fnc_maxdiffarray","bis_fnc_arsenal","bis_fnc_vrcoursecommandingbehaviour2","bis_fnc_modulepostprocess","bis_fnc_moduleobjectivegetin","bis_fnc_packstaticweapon","bis_fnc_addstackedeventhandler","bis_fnc_ambientanim","bis_fnc_diagkey","bis_fnc_respawntimepenalty","bis_fnc_modulemodules","bis_fnc_jukebox","bis_fnc_modulettcptrigger","bis_fnc_showmissionstatus","bis_fnc_missiontimeleft","bis_fnc_loadclass","bis_fnc_vrcoursecommandingbehaviour3","bis_fnc_playsound","bis_fnc_diagconfig","bis_fnc_addsupportlink","bis_fnc_diagmissionweapons","bis_fnc_addweapon","bis_fnc_helicoptergethitpoints","bis_fnc_removevirtualmagazinecargo","bis_fnc_animatetaskwaypoint","bis_fnc_modulerespawnvehicle","bis_fnc_moduleremotecontrol","bis_fnc_filterstring","bis_fnc_movetorespawnposition","bis_fnc_progressloadingscreen","bis_fnc_markercreate","bis_fnc_classweapon","bis_fnc_scenemiscstuff","bis_fnc_getvirtualitemcargo","bis_fnc_removevirtualweaponcargo","bis_fnc_moduletimemultiplier","bis_fnc_guieditor","bis_fnc_dbsymbolvalue","bis_fnc_dbclasscheck","bis_fnc_flameseffect","bis_fnc_completedcuratorchallengescount","bis_fnc_moduleendmission","bis_fnc_modulerespawntickets","bis_fnc_moduleexecute","bis_fnc_displayname","bis_fnc_respawnmanager","bis_fnc_returnparents","bis_fnc_isinfrontof","bis_fnc_initcuratorattribute","bis_fnc_getcfgdataarray","bis_fnc_functionsdebug","bis_fnc_playvideo","bis_fnc_addvirtualweaponcargo","bis_fnc_getvirtualbackpackcargo","bis_fnc_isforcedcuratorinterface","bis_fnc_moduleobjectivetarget","bis_fnc_animalbehaviour","bis_fnc_camera","bis_fnc_diagwiki","bis_fnc_blackin","bis_fnc_returnnestedelement","bis_fnc_arithmeticmean","bis_fnc_showcuratorattributes","bis_fnc_initmodules_strategicmap","bis_fnc_dbvaluecheck","bis_fnc_respawnspectator","bis_fnc_camfollow","bis_fnc_orbatremovegroupoverlay","bis_fnc_diagvehicleicons","bis_fnc_nearestnum","bis_fnc_respawnmenuspectator","bis_fnc_modulesound","bis_fnc_wppatrol","bis_fnc_dbvalueremove","bis_fnc_instring","bis_fnc_taskcreate","bis_fnc_guimessage","bis_fnc_vrcourseheliadvanced1","bis_fnc_tridenthandledamage","bis_fnc_feedbackmain","bis_fnc_spawnobjects","bis_fnc_typetext2","bis_fnc_posutmtodeg","bis_fnc_curatorchallengeilluminate","bis_fnc_vrcourseheliadvanced2","bis_fnc_modulecuratoraddcameraarea","bis_fnc_ambientplanes","bis_fnc_strategicmapopen","bis_fnc_hudlimits","bis_fnc_scenesetobjects","bis_fnc_vrcourseheliadvanced3","bis_fnc_arrayshuffle","bis_fnc_boundingboxdimensions","bis_fnc_tracebullets","bis_fnc_exportcuratorcosttable","bis_fnc_vrcourseheliadvanced4","bis_fnc_tridentexecute","bis_fnc_modulerespawnposition","bis_fnc_weaponcomponents","bis_fnc_texturevehicleicon","bis_fnc_variablespaceremove","bis_fnc_curatorpinged","bis_fnc_vrcourseheliadvanced5","bis_fnc_init","bis_fnc_feedback_burningtimer","bis_fnc_loop","bis_fnc_displayresize","bis_fnc_cutdecimals","bis_fnc_miscanim","bis_fnc_vrcourseheliadvanced6","bis_fnc_initmodules_effects","bis_fnc_credits_movie","bis_fnc_moduleeffectsemittercreator","bis_fnc_modulemptypedefense","bis_fnc_markwaypoints","bis_fnc_trackmissiontime","bis_fnc_paramguerfriendly","bis_fnc_diarymaps","bis_fnc_sidename","bis_fnc_noflyzonesexport","bis_fnc_keypointsexportfromkml","bis_fnc_flies","bis_fnc_relpos","bis_fnc_managecuratoraddons","bis_fnc_initmodules_smokeshells","bis_fnc_initmodules_flares","bis_fnc_shownotification","bis_fnc_modulefiringdrill","bis_fnc_displaymission","bis_fnc_initdisplay","bis_fnc_kbsentence","bis_fnc_moduleinit","bis_fnc_initdisplays","bis_fnc_diaganim","bis_fnc_supplydrop","bis_fnc_curatorattributes","bis_fnc_isunitvirtual","bis_fnc_getcfgisclass","bis_fnc_helicopterdamage","bis_fnc_randompos","bis_fnc_secondstostring","bis_fnc_parsenumber","bis_fnc_saymessage","bis_fnc_vrcourseheliweapons1","bis_fnc_removescriptedeventhandler","bis_fnc_tasksetdescription","bis_fnc_enemytargets","bis_fnc_openfieldmanual","bis_fnc_triggertomarker","bis_fnc_paramin","bis_fnc_respawntickets","bis_fnc_modulefdstatsclear","bis_fnc_keypointsexport","bis_fnc_playername","bis_fnc_dynamictext","bis_fnc_arraypush","bis_fnc_version","bis_fnc_removecuratoricon","bis_fnc_vrcourseheliweapons2","bis_fnc_modulefuel","bis_fnc_diagaar","bis_fnc_exportcfgmagazines","bis_fnc_getidc","bis_fnc_initmultiplayer","bis_fnc_nearesthelipad","bis_fnc_vrcourseheliweapons3","bis_fnc_modulesimulationmanager","bis_fnc_feedback_damageblur","bis_fnc_getidd","bis_fnc_settopairs","bis_fnc_wpartillery","bis_fnc_briefinginit","bis_fnc_addclassoo","bis_fnc_orbatanimate","bis_fnc_param","bis_fnc_scriptedwaypointtype","bis_fnc_position","bis_fnc_curatorchallengefindintel","bis_fnc_vrcourseheliweapons4","bis_fnc_modulemode","bis_fnc_modulespawnaioptions","bis_fnc_feedback_damagecc","bis_fnc_tasksetstate","bis_fnc_taskvar","bis_fnc_gc","bis_fnc_configviewer","bis_fnc_classmagazine","bis_fnc_getcfgdatabool","bis_fnc_blackout","bis_fnc_dbisvalue","bis_fnc_titlecard","bis_fnc_friendlysides","bis_fnc_crows","bis_fnc_unitcapturesimple","bis_fnc_addevidence","bis_fnc_objectsmapper","bis_fnc_getcfgdata","bis_fnc_tasksunit","bis_fnc_relscaleddist","bis_fnc_effectfiredhelirocket","bis_fnc_noflyzone","bis_fnc_counter","bis_fnc_radiosetplaylist","bis_fnc_returnconfigentry","bis_fnc_wpland","bis_fnc_missionflow","bis_fnc_refreshcommmenu","bis_fnc_missionhandlers","bis_fnc_getparamvalue","bis_fnc_helicopterseat","bis_fnc_locations","bis_fnc_absspeed","bis_fnc_addcuratorchallenge","bis_fnc_modulecuratorsetattributes","bis_fnc_settask","bis_fnc_displayloading","bis_fnc_ondiarychanged","bis_fnc_ambienthelicopters","bis_fnc_moduletriggers","bis_fnc_genericsentence","bis_fnc_savegame","bis_fnc_greatestnum","bis_fnc_scenecreatescenetrigger","bis_fnc_scenecheckweapons","bis_fnc_estimatedtimeleft","bis_fnc_sortby","bis_fnc_removestackedeventhandler","bis_fnc_postogrid","bis_fnc_tridentsetrelationship","bis_fnc_modulestrategicmaporbat","bis_fnc_modulecuratorseteditingareatype","bis_fnc_initmodules_objectmodifiers","bis_fnc_effectkilledsecondaries","bis_fnc_kbtopicconfig","bis_fnc_modulettcpout","bis_fnc_preload","bis_fnc_roundnum","bis_fnc_vrfadeout","bis_fnc_curatorattachobject","bis_fnc_moduleeffectssmoke","bis_fnc_endloadingscreen","bis_fnc_modulettcpclear","bis_fnc_music","bis_fnc_linearconversion","bis_fnc_magnitudesqr","bis_fnc_vrtimer","bis_fnc_drawcuratorlocations","bis_fnc_indicatebleeding","bis_fnc_effectfiredflares","bis_fnc_dbconfigpath","bis_fnc_rsclayer","bis_fnc_playersidefaction","bis_fnc_removeindex","bis_fnc_selectdiarysubject","bis_fnc_livefeedmodulesetsource","bis_fnc_guigrid","bis_fnc_briefinganimate","bis_fnc_sidecolor","bis_fnc_3dcredits","bis_fnc_setovercast","bis_fnc_modulestrategicmapmission","bis_fnc_effectfired","bis_fnc_nearestroad","bis_fnc_singlemissionkeys","bis_fnc_modulebleedtickets","bis_fnc_radialredout","bis_fnc_colorrgbatotexture","bis_fnc_threat","bis_fnc_commsmenutoggleavailability","bis_fnc_addcuratorareafromtrigger","bis_fnc_curatorvisionmodes","bis_fnc_curatorhint","bis_fnc_moduleeffectsbubbles","bis_fnc_execfsm","bis_fnc_diaghit","bis_fnc_fadeeffect","bis_fnc_exportinventory","bis_fnc_modulesavegame","bis_fnc_initmodules_respawn","bis_fnc_feedback_fatiguepp","bis_fnc_preload_server","bis_fnc_colorrgbatohtml","bis_fnc_ctrlfittotextheight","bis_fnc_codeperformance","bis_fnc_enemysides","bis_fnc_convertunits","bis_fnc_mpexec","bis_fnc_setpitchbank","bis_fnc_drawcuratordeaths","bis_fnc_guieffecttiles_ppchromaberration","bis_fnc_toupperdisplaytexts","bis_fnc_endmission","bis_fnc_sceneareaclearance","bis_fnc_initvirtualunit","bis_fnc_modulespawnai","bis_fnc_phoneticalword","bis_fnc_respawnconfirm","bis_fnc_taskparent","bis_fnc_findinpairs","bis_fnc_basicbackpack","bis_fnc_arraycompare","bis_fnc_sortnum","bis_fnc_addvirtualitemcargo","bis_fnc_endmissionserver","bis_fnc_initmodules_firingdrills","bis_fnc_feedback_damageradialblur","bis_fnc_isinzoom","bis_fnc_dbprint","bis_fnc_addcommmenuitem","bis_fnc_dirindicator","bis_fnc_selectrandomweighted","bis_fnc_respawnrounds","bis_fnc_synchronizedobjects","bis_fnc_kbcanspeak","bis_fnc_groupvehicles","bis_fnc_dbvalueid","bis_fnc_ambientanimcombat","bis_fnc_functionpath","bis_fnc_missionconversations","bis_fnc_orbatsetgroupfade","bis_fnc_curatorwaypointplaced","bis_fnc_curatorsaymessage","bis_fnc_curatorchallengedestroyvehicle","bis_fnc_getservervariable","bis_fnc_modulemine","bis_fnc_createlogrecord","bis_fnc_runlater","bis_fnc_enemydetected","bis_fnc_arraypop","bis_fnc_scenegetparticipants","bis_fnc_scenecreatesoundentities","bis_fnc_modulecreateprojectile","bis_fnc_loadinventory","bis_fnc_wpsuppress","bis_fnc_displaycontrols","bis_fnc_dbvaluereturn","bis_fnc_removerespawnposition","bis_fnc_scenerotate","bis_fnc_modulecuratoraddeditingareaplayers","bis_fnc_onload","bis_fnc_dirto","bis_fnc_mirrorcuratorsettings","bis_fnc_locationdescription","bis_fnc_tridentgetrelationship","bis_fnc_importimagelinks","bis_fnc_showunitinfo","bis_fnc_guinewsfeed","bis_fnc_feedback_testhelper","bis_fnc_cinemaborder","bis_fnc_diagbulletcam","bis_fnc_shutdown","bis_fnc_executestackedeventhandler","bis_fnc_showmarkers","bis_fnc_curatorautomatic","bis_fnc_respawngroup","bis_fnc_credits_movieconfig","bis_fnc_ctrlsetscale","bis_fnc_invslottype","bis_fnc_togglecuratorvisionmode","bis_fnc_modulelightning","bis_fnc_initmodules_environment","bis_fnc_feedback_allowdeathscreen","bis_fnc_vrspawneffect","bis_fnc_exportcfggroups","bis_fnc_initmodules_supports","bis_fnc_modulettcptriggerbehind","bis_fnc_pip","bis_fnc_effectkilled","bis_fnc_markertotrigger","bis_fnc_spawnenemy","bis_fnc_invcodetoarray","bis_fnc_commsmenucreate","bis_fnc_addvirtualmagazinecargo","bis_fnc_addcuratoricon","bis_fnc_didjip","bis_fnc_moduleunlockarea","bis_fnc_modulecas","bis_fnc_cameraold","bis_fnc_colorconfigtorgba","bis_fnc_setrespawndelay","bis_fnc_setobjectrotation","bis_fnc_getcfgsubclasses","bis_fnc_setrespawninventory","bis_fnc_iscurator","bis_fnc_modulegroupid","bis_fnc_dbclassremove","bis_fnc_advhintcredits","bis_fnc_rounddir","bis_fnc_numbertext","bis_fnc_moduletrident","bis_fnc_showrespawnmenu","bis_fnc_halo","bis_fnc_intrigger","bis_fnc_vreffectkilled","bis_fnc_shakecuratorcamera","bis_fnc_managecuratorchallenges","bis_fnc_formatcuratorchallengeobjects","bis_fnc_modulemptypegroundsupport","bis_fnc_initmodules_modes","bis_fnc_feedback_blue","bis_fnc_respawnmenuinventory","bis_fnc_invremove","bis_fnc_showtime","bis_fnc_modulemptypegamemaster","bis_fnc_initmodules_missionflow","bis_fnc_unitaddon","bis_fnc_diaryhints","bis_fnc_setidcstreamfriendly","bis_fnc_initparams","bis_fnc_removerespawninventory","bis_fnc_modulefriendlyfire","bis_fnc_moduleobjectiveracecp","bis_fnc_respawnbase","bis_fnc_getfrompairs","bis_fnc_interpolateweather","bis_fnc_unitcapturefiring","bis_fnc_vrdrawborder","bis_fnc_activateaddons","bis_fnc_modulegenericradio","bis_fnc_modulestrategicmapopen","bis_fnc_missiontasks","bis_fnc_fixdate","bis_fnc_diagkeytest","bis_fnc_updateplayerarray","bis_fnc_diagmacrosnamesound","bis_fnc_halt","bis_fnc_healtheffects","bis_fnc_helicoptertype","bis_fnc_effectfiredrocket","bis_fnc_missionrespawntype","bis_fnc_isleapyear","bis_fnc_setppeffecttemplate","bis_fnc_spotter","bis_fnc_getfactions","bis_fnc_removevirtualbackpackcargo","bis_fnc_modulecuratoraddeditableobjects","bis_fnc_modulecuratoraddicon","bis_fnc_mapsize","bis_fnc_diagpreview","bis_fnc_diagmacrosverify","bis_fnc_modulefdfademarker","bis_fnc_posdegtoworld","bis_fnc_respect","bis_fnc_moduleunlockobject","bis_fnc_modulecuratorsetcamera","bis_fnc_guihint","bis_fnc_diagmacros","bis_fnc_livefeedterminate","bis_fnc_wprelax","bis_fnc_healing","bis_fnc_overviewdifficulty","bis_fnc_getunitbyuid","bis_fnc_logformat","bis_fnc_ambientpostprocess","bis_fnc_fps","bis_fnc_vrcoursehelibasics1","bis_fnc_tridentclient","bis_fnc_modulestrategicmapimage","bis_fnc_diagmacrosmapsize","bis_fnc_removeallscriptedeventhandlers","bis_fnc_addscore","bis_fnc_livefeedsettarget","bis_fnc_markerpath","bis_fnc_rotatevector2d","bis_fnc_vrcourseballistics1","bis_fnc_vrcoursehelibasics2","bis_fnc_modulemptypeseize","bis_fnc_orbataddgroupoverlay","bis_fnc_respawnseagull","bis_fnc_taskstate","bis_fnc_vectormultiply","bis_fnc_vrcourseballistics2","bis_fnc_forcecuratorinterface","bis_fnc_vrcoursehelibasics3","bis_fnc_effectfiredsmokelauncher_boat","bis_fnc_kbcreatedummy","bis_fnc_infotext","bis_fnc_vrcourseballistics3","bis_fnc_dbclassset","bis_fnc_isbuildingenterable","bis_fnc_orbatgetgroupparams","bis_fnc_objectheight","bis_fnc_recompile","bis_fnc_invslots","bis_fnc_colorrgbtohtml","bis_fnc_randomnum","bis_fnc_vrcourseballistics4","bis_fnc_drawao","bis_fnc_initmodules_events","bis_fnc_returnchildren","bis_fnc_sidetype","bis_fnc_unitplay","bis_fnc_arrayinsert","bis_fnc_areequal","bis_fnc_crossproduct","bis_fnc_feedback_fatigueblur","bis_fnc_initmodules","bis_fnc_gridtopos","bis_fnc_addscriptedeventhandler","bis_fnc_returngroupcomposition","bis_fnc_moduleshowhide","bis_fnc_moduleobjective","bis_fnc_deletevehiclecrew","bis_fnc_callscriptedeventhandler","bis_fnc_weaponaddon","bis_fnc_spawn","bis_fnc_execremote","bis_fnc_findextreme","bis_fnc_geometricmean","bis_fnc_transportservice","bis_fnc_modulehealth","bis_fnc_preload_init","bis_fnc_genericsentenceinit","bis_fnc_missionconversationslocal","bis_fnc_taskdestination","bis_fnc_call","bis_fnc_diagfindmissingauthors","bis_fnc_respawnmenuposition","bis_fnc_advhint","bis_fnc_exportcfgpatches","bis_fnc_exportgroupformations","bis_fnc_paramcountdown","bis_fnc_radiosetchannel","bis_fnc_modulecuratoraddeditingarea","bis_fnc_mp_packet","bis_fnc_objectvar","bis_fnc_tasksetcurrent","bis_fnc_findoverwatch","bis_fnc_effectfiredsmokelauncher","bis_fnc_respawnwave","bis_fnc_settasklocal","bis_fnc_ambientblacklist","bis_fnc_curatorchallengespawnlightning","bis_fnc_destroycity","bis_fnc_arrayshift","bis_fnc_invadd","bis_fnc_supplydropservice","bis_fnc_variablespaceadd","bis_fnc_deleteinventory","bis_fnc_modulesector","bis_fnc_modulestrategicmapinit","bis_fnc_modulediary","bis_fnc_initmodules_sites","bis_fnc_kbpriority","bis_fnc_forceend","bis_fnc_vehicleroles","bis_fnc_moduledate","bis_fnc_missionflow_fsm","bis_fnc_taskexists","bis_fnc_loadentry","bis_fnc_credits_moviesupport","bis_fnc_bloodeffect","bis_fnc_aligntabs","bis_fnc_log","bis_fnc_vrdrawgrid","bis_fnc_drawrespawnpositions","bis_fnc_modulezonerestriction","bis_fnc_modulespawnaipoint","bis_fnc_modulecuratorsetcostsside","bis_fnc_modulecovermap","bis_fnc_removefrompairs","bis_fnc_orbattooltip","bis_fnc_strategicmapmousebuttonclick","bis_fnc_modulehandle","bis_fnc_effectkilledairdestruction","bis_fnc_setheight","bis_fnc_removenestedelement","bis_fnc_spawnvehicle","bis_fnc_vrcoursecommandingvehicles1","bis_fnc_feedbackmain_fsm","bis_fnc_feedback_allowpp","bis_fnc_findsafepos","bis_fnc_isposblacklisted","bis_fnc_taskhandler","bis_fnc_getvirtualweaponcargo","bis_fnc_vrcoursecommandingvehicles2","bis_fnc_modulespawnaisectortactic","bis_fnc_moduleobjectivefind","bis_fnc_diagpreviewcycle","bis_fnc_advhintcall","bis_fnc_respawnside","bis_fnc_modulefdcpin","bis_fnc_subselect","bis_fnc_scenesetposformation","bis_fnc_vrcoursecommandingvehicles3","bis_fnc_playmusic","bis_fnc_modulehint","bis_fnc_modulecurator","bis_fnc_setcuratorcamera","bis_fnc_modulefdskeetdestruction","bis_fnc_objectside","bis_fnc_modulerank","bis_fnc_modulemptypegroundsupportbase","bis_fnc_strategicmapanimate","bis_fnc_ambientanimgetparams","bis_fnc_enablesaving","bis_fnc_displaycolorset","bis_fnc_drawcuratorrespawnmarkers","bis_fnc_setservervariable","bis_fnc_initmodules_curator","bis_fnc_ambientboats","bis_fnc_modulefdcpclear","bis_fnc_relativedirto","bis_fnc_listplayers","bis_fnc_modulepositioning","bis_fnc_modulerespawninventory","bis_fnc_kbtelllocal","bis_fnc_titletext","bis_fnc_groupindicator","bis_fnc_dirteffect","bis_fnc_onend","bis_fnc_islocalized","bis_fnc_singlemissionname","bis_fnc_radiosettrack","bis_fnc_baseweapon","bis_fnc_moduletasksetdestination","bis_fnc_getrespawnpositions","bis_fnc_basictask","bis_fnc_moduleradiochannelcreate","bis_fnc_dbclassindex","bis_fnc_modulettstatsclear","bis_fnc_exportcfghints","bis_fnc_diagkeylayout","bis_fnc_orbatopen","bis_fnc_ctrltextheight","bis_fnc_exportmaptobitxt","bis_fnc_isdemo","bis_fnc_distance2d","bis_fnc_timetostring","bis_fnc_finishcuratorchallenge","bis_fnc_moduleeffectsplankton","bis_fnc_modulehq","bis_fnc_feedback_damagepp","bis_fnc_guibackground","bis_fnc_getturrets","bis_fnc_functionmeta","bis_fnc_taskreal","bis_fnc_cargoturretindex","bis_fnc_dbclassreturn","bis_fnc_createmenu","bis_fnc_lowestnum","bis_fnc_saveinventory","bis_fnc_initintelobject","bis_fnc_damagechanged","bis_fnc_effectfiredrifle","bis_fnc_kbskip","bis_fnc_noflyzonescreate","bis_fnc_worldarea","bis_fnc_aan","bis_fnc_boundingcircle","bis_fnc_addrespawnposition","bis_fnc_arefriendly","bis_fnc_exportcfgweapons","bis_fnc_getpitchbank","bis_fnc_vrcourselaunchers1","bis_fnc_drawminefields","bis_fnc_moduletasksetstate","bis_fnc_advhintarg","bis_fnc_itemtype","bis_fnc_initexpo","bis_fnc_markerparams","bis_fnc_unitplaysimple","bis_fnc_vrspawnselector","bis_fnc_vrcourselaunchers2"}; BIS_UI_Functions[] = {"bis_fnc_guimessage_meta","bis_fnc_guimessage_status_meta","bis_fnc_registercuratorobject_meta","bis_fnc_curatorautomatic_meta","bis_fnc_isloading_meta","bis_fnc_animalsitespawn_meta","bis_fnc_dbclassid_meta","bis_fnc_ambientplanes_meta","bis_fnc_invremove_meta","bis_fnc_fixdate_meta","bis_fnc_vrcourseheliweapons3_meta","bis_fnc_cargoturretindex_meta","bis_fnc_execvm_meta","bis_fnc_convertunits_meta","bis_fnc_magnitude_meta","bis_fnc_infotext_meta","bis_fnc_modulesector_meta","bis_fnc_skirmishtrigger_meta","bis_fnc_spawngroup_meta","bis_fnc_isinsidearea_meta","bis_fnc_deletetask_meta","bis_fnc_version_meta","bis_fnc_getrespawnmarkers_meta","bis_fnc_diagwiki_meta","bis_fnc_geometricmean_meta","bis_fnc_radiosetplaylist_meta","bis_fnc_advhintcredits_meta","bis_fnc_vrtimer_meta","bis_fnc_subclasses_meta","bis_fnc_exportinventory_meta","bis_fnc_destroycity_meta","bis_fnc_arrayshuffle_meta","bis_fnc_moduleslingload_meta","bis_fnc_fps_meta","bis_fnc_moduletriggers_meta","bis_fnc_tracebullets_meta","bis_fnc_moduleunlockobject_meta","bis_fnc_respawnmanager_meta","bis_fnc_titletext_meta","bis_fnc_getlinedist_meta","bis_fnc_vreffectkilled_meta","bis_fnc_shutdown_meta","bis_fnc_moduleweather_meta","bis_fnc_modulegenericradio_meta","bis_fnc_respawngroup_meta","bis_fnc_numberdigits_meta","bis_fnc_dbvalueindex_meta","bis_fnc_kmlimport_meta","bis_fnc_weaponaddon_meta","bis_fnc_drawcuratordeaths_meta","bis_fnc_blackout_meta","bis_fnc_interpolateweather_meta","bis_fnc_respect_meta","bis_fnc_displayname_meta","bis_fnc_moduleobjectivegetin_meta","bis_fnc_modulespawnai_meta","bis_fnc_playersidefaction_meta","bis_fnc_wpsuppress_meta","bis_fnc_texturemarker_meta","bis_fnc_customgpsvideo_meta","bis_fnc_taskattack_meta","bis_fnc_singlemissionconfig_meta","bis_fnc_modulesfx_meta","bis_fnc_moduleradiochannelcreate_meta","bis_fnc_vrcourseheliadvanced1_meta","bis_fnc_scriptedmove_meta","bis_fnc_dirteffect_meta","bis_fnc_respawnmenuposition_meta","bis_fnc_effectfiredflares_meta","bis_fnc_modulecuratorsetattributes_meta","bis_fnc_enemytargets_meta","bis_fnc_spawnenemy_meta","bis_fnc_scenesetanimationsforgroup_meta","bis_fnc_addrespawninventory_meta","bis_fnc_modulecuratoraddaddons_meta","bis_fnc_respawnwave_meta","bis_fnc_rankparams_meta","bis_fnc_initdisplays_meta","bis_fnc_noflyzonesexport_meta","bis_fnc_scriptedwaypointtype_meta","bis_fnc_findinpairs_meta","bis_fnc_vrcoursecommandingvehicles1_meta","bis_fnc_addvirtualitemcargo_meta","bis_fnc_removecommmenuitem_meta","bis_fnc_returnconfigentry_meta","bis_fnc_modulespawnaipoint_meta","bis_fnc_boundingboxcorner_meta","bis_fnc_setrespawndelay_meta","bis_fnc_removesupportlink_meta","bis_fnc_basicbackpack_meta","bis_fnc_getservervariable_meta","bis_fnc_diagloop_meta","bis_fnc_iscuratoreditable_meta","bis_fnc_getturrets_meta","bis_fnc_curatorchallengedestroyvehicle_meta","bis_fnc_tasksetdescription_meta","bis_fnc_selectdiarysubject_meta","bis_fnc_modulepostprocess_meta","bis_fnc_helicoptertype_meta","bis_fnc_kbcreatedummy_meta","bis_fnc_getpitchbank_meta","bis_fnc_strategicmapanimate_meta","bis_fnc_orbatremovegroupoverlay_meta","bis_fnc_getvirtualbackpackcargo_meta","bis_fnc_modulerespawnvehicle_meta","bis_fnc_drawrespawnpositions_meta","bis_fnc_unitplay_meta","bis_fnc_monthdays_meta","bis_fnc_dbvalueid_meta","bis_fnc_enemysides_meta","bis_fnc_isinzoom_meta","bis_fnc_ambientanimcombat_meta","bis_fnc_typetext_meta","bis_fnc_refreshcommmenu_meta","bis_fnc_modulefiringdrill_meta","bis_fnc_moduleeffectsshells_meta","bis_fnc_moduleobjectiveracefinish_meta","bis_fnc_getvirtualmagazinecargo_meta","bis_fnc_endmissionserver_meta","bis_fnc_setdate_meta","bis_fnc_errormsg_meta","bis_fnc_helicopterseatmove_meta","bis_fnc_arrayunshift_meta","bis_fnc_diagpreviewvehiclecrew_meta","bis_fnc_dbimportxml_meta","bis_fnc_sortnum_meta","bis_fnc_vrcourseheliweapons4_meta","bis_fnc_boundingcircle_meta","bis_fnc_effectfiredrocket_meta","bis_fnc_music_meta","bis_fnc_addclassoo_meta","bis_fnc_curatorchallengefireweapon_meta","bis_fnc_codeperformance_meta","bis_fnc_commsmenucreate_meta","bis_fnc_numbertext_meta","bis_fnc_tridentgetrelationship_meta","bis_fnc_curatorattachobject_meta","bis_fnc_modulecuratoraddeditableobjects_meta","bis_fnc_damagepulsing_meta","bis_fnc_getvirtualweaponcargo_meta","bis_fnc_addvirtualweaponcargo_meta","bis_fnc_moduleammo_meta","bis_fnc_miscanim_meta","bis_fnc_modulecuratorsetcoefs_meta","bis_fnc_singlemissionkeys_meta","bis_fnc_playmusic_meta","bis_fnc_respawnbase_meta","bis_fnc_taskhint_meta","bis_fnc_invslots_meta","bis_fnc_configpath_meta","bis_fnc_deletevehiclecrew_meta","bis_fnc_modulefdcpclear_meta","bis_fnc_instructorfigure_meta","bis_fnc_spawnvehicle_meta","bis_fnc_dbprint_meta","bis_fnc_validateparametersoo_meta","bis_fnc_modulecuratorseteditingareatype_meta","bis_fnc_prepareao_meta","bis_fnc_filterstring_meta","bis_fnc_hudlimits_meta","bis_fnc_arraypop_meta","bis_fnc_radialred_meta","bis_fnc_loadentry_meta","bis_fnc_vrcourseplaceables1_meta","bis_fnc_vrdrawborder_meta","bis_fnc_islocalized_meta","bis_fnc_modulecuratorsetcostsdefault_meta","bis_fnc_arefriendly_meta","bis_fnc_displaycolorset_meta","bis_fnc_kbsentence_meta","bis_fnc_arsenal_meta","bis_fnc_fadeeffect_meta","bis_fnc_settopairs_meta","bis_fnc_initmultiplayer_meta","bis_fnc_modulegroupid_meta","bis_fnc_modulebootcampstage_meta","bis_fnc_instring_meta","bis_fnc_moduleobjectivetarget_meta","bis_fnc_paramweather_meta","bis_fnc_customgps_meta","bis_fnc_effectkilled_meta","bis_fnc_vrcourseballistics1_meta","bis_fnc_enemydetected_meta","bis_fnc_locationdescription_meta","bis_fnc_vrcourseheliadvanced2_meta","bis_fnc_moduletaskcreate_meta","bis_fnc_moduletasksetdestination_meta","bis_fnc_orbatanimate_meta","bis_fnc_getunitinsignia_meta","bis_fnc_getrespawnpositions_meta","bis_fnc_ftlmanager_meta","bis_fnc_forcecuratorinterface_meta","bis_fnc_countdown_meta","bis_fnc_modulemine_meta","bis_fnc_managecuratorchallenges_meta","bis_fnc_invslottype_meta","bis_fnc_colorrgbatohtml_meta","bis_fnc_objectsgrabber_meta","bis_fnc_arrayinsert_meta","bis_fnc_swapvars_meta","bis_fnc_basictask_meta","bis_fnc_randomint_meta","bis_fnc_objectvar_meta","bis_fnc_modulebleedtickets_meta","bis_fnc_supplydropservice_meta","bis_fnc_modulehint_meta","bis_fnc_mp_meta","bis_fnc_ctrlsetscale_meta","bis_fnc_removefrompairs_meta","bis_fnc_vrcoursecommandingvehicles2_meta","bis_fnc_showtime_meta","bis_fnc_formatcuratorchallengeobjects_meta","bis_fnc_diagknownastarget_meta","bis_fnc_dbisvalue_meta","bis_fnc_moduledate_meta","bis_fnc_modulemissionname_meta","bis_fnc_unitaddon_meta","bis_fnc_halt_meta","bis_fnc_unitvector_meta","bis_fnc_dotproduct_meta","bis_fnc_livefeedmodulesettarget_meta","bis_fnc_groupindicator_meta","bis_fnc_titlecard_meta","bis_fnc_scenegetobjects_meta","bis_fnc_moduletrident_meta","bis_fnc_bleedtickets_meta","bis_fnc_setmissionstatusslot_meta","bis_fnc_modulehandle_meta","bis_fnc_vrspawnselector_meta","bis_fnc_modulevolume_meta","bis_fnc_moduleeffectsfire_meta","bis_fnc_addcuratoricon_meta","bis_fnc_playername_meta","bis_fnc_iscurator_meta","bis_fnc_savegame_meta","bis_fnc_cutdecimals_meta","bis_fnc_diagpreview_meta","bis_fnc_exportcfgmagazines_meta","bis_fnc_returnchildren_meta","bis_fnc_setrespawninventory_meta","bis_fnc_modulerating_meta","bis_fnc_modulemptypeseize_meta","bis_fnc_respawnspectator_meta","bis_fnc_taskchildren_meta","bis_fnc_feedbackinit_meta","bis_fnc_modulecreatediaryrecord_meta","bis_fnc_estimatedtimeleft_meta","bis_fnc_taskcreate_meta","bis_fnc_call_meta","bis_fnc_camera_meta","bis_fnc_boundingboxdimensions_meta","bis_fnc_3dcredits_meta","bis_fnc_timetostring_meta","bis_fnc_exportcuratorcosttable_meta","bis_fnc_configviewer_meta","bis_fnc_vectormultiply_meta","bis_fnc_nearesthelipad_meta","bis_fnc_findoverwatch_meta","bis_fnc_help_meta","bis_fnc_diagjiralink_meta","bis_fnc_missionhandlers_meta","bis_fnc_vrcoursecommandingbehaviour1_meta","bis_fnc_selectrandom_meta","bis_fnc_areequal_meta","bis_fnc_vectoradd_meta","bis_fnc_moduleeffectssmoke_meta","bis_fnc_diagmacrosnamesound_meta","bis_fnc_lowestnum_meta","bis_fnc_moduleanimals_meta","bis_fnc_invslotsempty_meta","bis_fnc_groupvehicles_meta","bis_fnc_kbmenu_meta","bis_fnc_dbsymbolvalue_meta","bis_fnc_modulecuratorsetcamera_meta","bis_fnc_moduleobjective_meta","bis_fnc_tridentsetrelationship_meta","bis_fnc_tridenthandledamage_meta","bis_fnc_setovercast_meta","bis_fnc_incapacitatedeffect_meta","bis_fnc_kbtell_meta","bis_fnc_sideid_meta","bis_fnc_guieffecttiles_meta","bis_fnc_teamcolor_meta","bis_fnc_modulelightning_meta","bis_fnc_wpartillery_meta","bis_fnc_kbtopicconfig_meta","bis_fnc_strategicmapopen_meta","bis_fnc_target_meta","bis_fnc_modulestrategicmapimage_meta","bis_fnc_curatorchallengefindintel_meta","bis_fnc_position_meta","bis_functions_listpreinit","bis_fnc_diagmacros_meta","bis_fnc_objectheight_meta","bis_fnc_jukebox_meta","bis_fnc_paramguerfriendly_meta","bis_fnc_initplayable_meta","bis_fnc_diaghit_meta","bis_fnc_initrespawn_meta","bis_fnc_taskhandler_meta","bis_fnc_rotatevector2d_meta","bis_fnc_vrcourseplaceables2_meta","bis_fnc_dbclasscheck_meta","bis_fnc_curatorsaymessage_meta","bis_fnc_managecuratoraddons_meta","bis_fnc_addstackedeventhandler_meta","bis_fnc_livefeedterminate_meta","bis_fnc_radialredout_meta","bis_fnc_nearestposition_meta","bis_fnc_mirrorcuratorsettings_meta","bis_fnc_sidetype_meta","bis_fnc_modulecuratorsetcostsside_meta","bis_fnc_exportcfgvehicles_meta","bis_fnc_vrcourseballistics2_meta","bis_fnc_markwaypoints_meta","bis_fnc_nearestnum_meta","bis_fnc_romannumeral_meta","bis_fnc_paramin_meta","bis_fnc_vrcourseheliadvanced3_meta","bis_fnc_friendlysides_meta","bis_fnc_setunitinsignia_meta","bis_fnc_diagmacrosauthor_meta","bis_fnc_ambientblacklistadd_meta","bis_fnc_execfsm_meta","bis_fnc_removestackedeventhandler_meta","bis_fnc_modulezonerestriction_meta","bis_fnc_vrcoursetargetdesignation1_meta","bis_fnc_trimstring_meta","bis_fnc_scenecheckweapons_meta","bis_fnc_boundingboxmarker_meta","bis_fnc_drawcuratorrespawnmarkers_meta","bis_fnc_effectfiredsmokelauncher_boat_meta","bis_fnc_vrcoursecommandingvehicles3_meta","bis_fnc_scenegetparticipants_meta","bis_fnc_functionpath_meta","bis_fnc_modulesimulationmanager_meta","bis_fnc_supplydrop_meta","bis_fnc_setfog_meta","bis_fnc_guinewsfeed_meta","bis_fnc_updateplayerarray_meta","bis_fnc_guieditor_meta","bis_fnc_taskparent_meta","bis_fnc_createlogrecord_meta","bis_fnc_guigridtoprofile_meta","bis_fnc_dirto_meta","bis_fnc_spawnobjects_meta","bis_fnc_orbatsetgroupparams_meta","bis_fnc_runlater_meta","bis_fnc_assignplayerrole_meta","bis_fnc_trackmissiontime_meta","bis_fnc_moveaction_meta","bis_fnc_objecttype_meta","bis_fnc_missionrespawntype_meta","bis_fnc_orbattooltip_meta","bis_fnc_scenecreatescenetrigger_meta","bis_fnc_initintelobject_meta","bis_fnc_displayclouds_meta","bis_fnc_credits_movieconfig_meta","bis_fnc_saveinventory_meta","bis_fnc_ctrltextheight_meta","bis_fnc_scenerotate_meta","bis_fnc_orbatopen_meta","bis_fnc_vrcourselaunchers1_meta","bis_fnc_genericsentence_meta","bis_fnc_fatigueeffect_meta","bis_fnc_livefeedmodulesetsource_meta","bis_fnc_vrcoursecommandingbehaviour2_meta","bis_fnc_variablespaceadd_meta","bis_fnc_findsafepos_meta","bis_fnc_getidc_meta","bis_fnc_overviewtimetrial_meta","bis_fnc_sortby_meta","bis_fnc_setidcstreamfriendly_meta","bis_fnc_animalbehaviour_meta","bis_fnc_getparamvalue_meta","bis_fnc_enablesaving_meta","bis_fnc_addcuratorchallenge_meta","bis_fnc_modulemptypegamemaster_meta","bis_fnc_removerespawnposition_meta","bis_functions_list","bis_fnc_vrcoursecommandingmovement1_meta","bis_fnc_spotter_meta","bis_fnc_setcuratorcamera_meta","bis_fnc_blackin_meta","bis_fnc_paramdaytime_meta","bis_fnc_diarymaps_meta","bis_fnc_initparams_meta","bis_fnc_playvideo_meta","bis_fnc_sceneareaclearance_meta","bis_fnc_findnestedelement_meta","bis_fnc_scenesetposformation_meta","bis_fnc_moduleunlockarea_meta","bis_fnc_setcuratorvisionmodes_meta","bis_fnc_secondstostring_meta","bis_fnc_scenesetobjects_meta","bis_fnc_effectkilledairdestruction_meta","bis_fnc_getfactions_meta","bis_fnc_orbatsetgroupfade_meta","bis_fnc_modulefdfademarker_meta","bis_fnc_playendmusic_meta","bis_fnc_modulettcpclear_meta","bis_fnc_livefeedsettarget_meta","bis_fnc_vrcourseplaceables3_meta","bis_fnc_consolidatearray_meta","bis_fnc_startloadingscreen_meta","bis_fnc_diagknowntargets_meta","bis_fnc_addevidence_meta","bis_fnc_tasksunit_meta","bis_fnc_modulettstatsclear_meta","bis_fnc_tridentexecute_meta","bis_fnc_moduledamage_meta","bis_fnc_curatorrespawn_meta","bis_fnc_vectordiff_meta","bis_fnc_moduletimetrial_meta","bis_fnc_feedbackmain_meta","bis_fnc_arraypush_meta","bis_fnc_moduleshowhide_meta","bis_fnc_locweaponinfo_meta","bis_fnc_moduleunits_meta","bis_fnc_curatorwaypointplaced_meta","bis_fnc_vrcourseballistics3_meta","bis_fnc_modulespawnaisectortactic_meta","bis_fnc_moduletasksetdescription_meta","bis_fnc_rounddir_meta","bis_fnc_crewcount_meta","bis_fnc_classweapon_meta","bis_fnc_vrcourseheliadvanced4_meta","bis_fnc_vrcoursehelibasics1_meta","bis_fnc_moduleeffectsemittercreator_meta","bis_fnc_getrespawninventories_meta","bis_fnc_crossproduct_meta","bis_fnc_overviewterrain_meta","bis_fnc_credits_movie_meta","bis_fnc_getunitbyuid_meta","bis_fnc_removecuratoricon_meta","bis_fnc_paramviewdistance_meta","bis_fnc_locations_meta","bis_fnc_modulesound_meta","bis_fnc_loadclass_meta","bis_fnc_unitcapturesimple_meta","bis_fnc_modulettcpin_meta","bis_fnc_vrcoursetargetdesignation2_meta","bis_fnc_animatetaskwaypoint_meta","bis_fnc_vehicleroles_meta","bis_fnc_showcuratorattributes_meta","bis_fnc_missiontaskslocal_meta","bis_fnc_conditionalselect_meta","bis_fnc_callscriptedeventhandler_meta","bis_fnc_dbclassindex_meta","bis_fnc_respawntimepenalty_meta","bis_fnc_getcfgdatabool_meta","bis_fnc_invcodetoarray_meta","bis_fnc_vectorfromxtoy_meta","bis_fnc_diagradio_meta","bis_fnc_preload_meta","bis_fnc_cameraold_meta","bis_fnc_texttiles_meta","bis_fnc_changesupportradiochannel_meta","bis_fnc_executestackedeventhandler_meta","bis_mainmenu_isplayexpanded","bis_fnc_modulerespawntickets_meta","bis_fnc_effectfiredhelirocket_meta","bis_fnc_addscore_meta","bis_fnc_flies_meta","bis_fnc_vrcoursecommandingactions1_meta","bis_fnc_modulecovermap_meta","bis_fnc_scenesetbehaviour_meta","bis_fnc_displaycolorget_meta","bis_fnc_taskstate_meta","bis_fnc_addtopairs_meta","bis_fnc_getvirtualitemcargo_meta","bis_functions_listpostinit","bis_fnc_missionconversations_meta","bis_fnc_unitplayfiring_meta","bis_fnc_radiosetchannel_meta","bis_fnc_dynamictext_meta","bis_fnc_distance2d_meta","bis_fnc_moduleeffectsplankton_meta","bis_fnc_respawnrounds_meta","bis_fnc_moduleposter_meta","bis_fnc_isposblacklisted_meta","bis_fnc_unpackstaticweapon_meta","bis_fnc_onload_meta","bis_fnc_tasksetcurrent_meta","bis_fnc_aligntabs_meta","bis_fnc_moduleeffectsbubbles_meta","bis_fnc_objectside_meta","bis_fnc_diagkeylayout_meta","bis_fnc_modulepositioning_meta","bis_fnc_respawnmenuspectator_meta","bis_fnc_taskdefend_meta","bis_fnc_addcommmenuitem_meta","bis_fnc_vrcourselaunchers2_meta","bis_fnc_drawao_meta","bis_fnc_worldarea_meta","bis_fnc_overviewmission_meta","bis_fnc_vrcoursecommandingbehaviour3_meta","bis_fnc_modulecuratorsetcostsvehicleclass_meta","bis_fnc_loop_meta","bis_fnc_modulesavegame_meta","bis_fnc_cinemaborder_meta","bis_fnc_onplayerconnected_meta","bis_fnc_getidd_meta","bis_fnc_diagmissionweapons_meta","bis_fnc_shakegauges_meta","bis_fnc_moduleobjectivefind_meta","bis_fnc_vrcoursecommandingmovement2_meta","bis_fnc_respawnmenuinventory_meta","bis_fnc_removeindex_meta","bis_fnc_effectfiredsmokelauncher_meta","bis_fnc_helicoptergethitpoints_meta","bis_fnc_moduleexecute_meta","bis_fnc_diagkey_meta","bis_fnc_exportcfgweapons_meta","bis_fnc_arrayfinddeep_meta","bis_fnc_modulestrategicmapinit_meta","bis_fnc_diaryhints_meta","bis_fnc_exportgroupformations_meta","bis_fnc_getcfgdataobject_meta","bis_fnc_texturevehicleicon_meta","bis_fnc_modulecreateprojectile_meta","bis_fnc_initmodules_meta","bis_fnc_modulefdstatsclear_meta","bis_fnc_ondiarychanged_meta","bis_fnc_ffvupdate_meta","bis_fnc_moduleobjectivesector_meta","bis_fnc_inv_meta","bis_fnc_log_meta","bis_mainmenu_isoptionsexpanded","bis_displayinterrupt_isoptionsexpanded","bis_fnc_keypointsexportfromkml_meta","bis_fnc_localize_meta","bis_fnc_endloadingscreen_meta","bis_fnc_vrfadeout_meta","bis_fnc_classmagazine_meta","bis_fnc_halo_meta","bis_fnc_kbtelllocal_meta","bis_fnc_initdisplay_meta","bis_fnc_vrcourseballistics4_meta","bis_fnc_showmarkers_meta","bis_fnc_togglecuratorvisionmode_meta","bis_fnc_randompos_meta","bis_fnc_mpexec_meta","bis_fnc_vrcourseheliadvanced5_meta","bis_fnc_vrcoursehelibasics2_meta","bis_fnc_keycode_meta","bis_fnc_guimessage_meta","bis_fnc_colorrgbtohtml_meta","bis_fnc_isforcedcuratorinterface_meta","bis_fnc_exportcfgpatches_meta","bis_fnc_randomindex_meta","bis_fnc_modulefdcpin_meta","bis_fnc_showcuratorfeedbackmessage_meta","bis_fnc_respawnconfirm_meta","bis_fnc_ctrlfittotextheight_meta","bis_fnc_credits_meta","bis_fnc_radiosettrack_meta","bis_fnc_modulecombatgetin_meta","bis_fnc_arithmeticmean_meta","bis_fnc_counter_meta","bis_fnc_vrcoursetargetdesignation3_meta","bis_fnc_livefeedsetsource_meta","bis_fnc_setservervariable_meta","bis_fnc_subselect_meta","bis_fnc_posdegtoutm_meta","bis_fnc_flameseffect_meta","bis_fnc_setidentity_meta","bis_fnc_removenestedelement_meta","bis_fnc_dbclassremove_meta","bis_fnc_dbimportconfig_meta","bis_fnc_dbvalueset_meta","bis_fnc_noflyzone_meta","bis_fnc_sortalphabetically_meta","bis_fnc_getcfgsubclasses_meta","bis_fnc_unitcapture_meta","bis_fnc_saymessage_meta","bis_fnc_modulepunishment_meta","bis_fnc_selectrandomweighted_meta","bis_fnc_playsound_meta","bis_fnc_didjip_meta","bis_fnc_kbisspeaking_meta","bis_fnc_setobjecttexture_meta","bis_fnc_modulestrategicmapmission_meta","bis_fnc_livefeedmoduleeffects_meta","bis_fnc_dbvalueremove_meta","bis_fnc_effectfiredrifle_meta","bis_fnc_isunitvirtual_meta","bis_fnc_vrcoursecommandingactions2_meta","bis_fnc_scenecreatesoundentities_meta","bis_fnc_moduletasksetstate_meta","bis_fnc_deleteinventory_meta","bis_fnc_diagmacrosverify_meta","bis_fnc_diagbulletcam_meta","bis_fnc_error_meta","bis_fnc_modulecuratoraddeditingareaplayers_meta","bis_fnc_displayloading_meta","bis_fnc_tasksetstate_meta","bis_fnc_setppeffecttemplate_meta","bis_fnc_exportcfghints_meta","bis_fnc_gcinit_meta","bis_fnc_paramrespawntickets_meta","bis_fnc_randomnum_meta","bis_fnc_dbisclass_meta","bis_fnc_initexpo_meta","bis_fnc_modulemptypegroundsupportbase_meta","bis_fnc_invadd_meta","bis_fnc_taskcurrent_meta","bis_fnc_getfrompairs_meta","bis_fnc_vrcourselaunchers3_meta","bis_fnc_diagaar_meta","bis_fnc_livefeed_meta","bis_fnc_modulecuratorsetobjectcost_meta","bis_fnc_effectkilledairdestructionstage2_meta","bis_fnc_importimagelinks_meta","bis_fnc_setheight_meta","bis_fnc_disablesaving_meta","bis_fnc_setnestedelement_meta","bis_fnc_showunitinfo_meta","bis_fnc_limitsupport_meta","bis_fnc_disableloading_meta","bis_fnc_randompostrigger_meta","bis_fnc_moduletimemultiplier_meta","bis_fnc_inanglesector_meta","bis_fnc_initdisplays_prestart","bis_fnc_markerpath_meta","bis_fnc_missilelaunchpositionfix_meta","bis_fnc_briefinginit_meta","bis_fnc_modulefuel_meta","bis_fnc_removevirtualweaponcargo_meta","bis_fnc_relposobject_meta","bis_fnc_curatorautomaticpositions_meta","bis_fnc_orbataddgroupoverlay_meta","bis_fnc_pip_meta","bis_fnc_showmissionstatus_meta","bis_fnc_ambientboats_meta","bis_fnc_addrespawnposition_meta","bis_fnc_modulecuratoraddicon_meta","bis_fnc_moduleendmission_meta","bis_fnc_modulemptypedefense_meta","bis_fnc_modulecurator_meta","bis_fnc_genericsentenceinit_meta","bis_fnc_modulecuratoraddpoints_meta","bis_fnc_itemtype_meta","bis_fnc_threat_meta","bis_fnc_modulespawnaioptions_meta","bis_fnc_dbsymbolclass_meta","bis_fnc_curatorchallengeilluminate_meta","bis_fnc_moduleinit_meta","bis_fnc_setrank_meta","bis_fnc_weaponcomponents_meta","bis_fnc_livefeedmoduleinit_meta","bis_fnc_vrcoursehelislingload1_meta","bis_fnc_dirindicator_meta","bis_fnc_vrcourseheliadvanced6_meta","bis_fnc_vrcoursehelibasics3_meta","bis_fnc_modulecuratoraddeditingarea_meta","bis_fnc_singlemissionname_meta","bis_fnc_openfieldmanual_meta","bis_mainmenu_islearnexpanded","bis_fnc_credits_moviesupport_meta","bis_fnc_curatorobjectregistered_meta","bis_fnc_maxdiffarray_meta","bis_fnc_activateaddons_meta","bis_fnc_guieffecttiles_alpha","bis_fnc_returnnestedelement_meta","bis_fnc_relscaleddist_meta","bis_fnc_listcuratorplayers_meta","bis_fnc_moduleskill_meta","bis_fnc_diagfindmissingauthors_meta","bis_fnc_terraingradangle_meta","bis_fnc_linearconversion_meta","bis_fnc_dbclassset_meta","bis_fnc_ambienthelicopters_meta","bis_fnc_missionflow_meta","bis_fnc_colorrgbatotexture_meta","bis_fnc_configextremes_meta","bis_fnc_commsmenutogglevisibility_meta","bis_fnc_diagvehicleicons_meta","bis_fnc_completedcuratorchallengescount_meta","bis_fnc_settasklocal_meta","bis_fnc_helicoptercanfly_meta","bis_fnc_taskdestination_meta","bis_fnc_sidecolor_meta","bis_fnc_crows_meta","bis_fnc_earthquake_meta","bis_fnc_guibackground_meta","bis_fnc_guihint_meta","bis_fnc_dbclassreturn_meta","bis_fnc_rsclayer_meta","bis_fnc_indicatebleeding_meta","bis_fnc_healtheffects_meta","bis_fnc_execremote_meta","bis_fnc_vrcoursecommandingactions3_meta","bis_fnc_effectfiredartillery_meta","bis_fnc_transportservice_meta","bis_fnc_endmission_meta","bis_fnc_uniqueclasses_meta","bis_fnc_progressloadingscreen_meta","bis_fnc_modulemptypesectorcontrol_meta","bis_fnc_dbvaluereturn_meta","bis_fnc_ambientblacklist_meta","bis_fnc_diagmissionpositions_meta","bis_fnc_advhint_hinthandlers","bis_fnc_vrcourseheliweapons1_meta","bis_fnc_noflyzonescreate_meta","bis_fnc_buildingpositions_meta","bis_fnc_exportcfggroups_meta","bis_shownchat","bis_fnc_displayresize_meta","bis_fnc_orbatconfigpreview_meta","bis_fnc_objectsmapper_meta","bis_fnc_moduletracers_meta","bis_fnc_loadinventory_meta","bis_fnc_diagaarrecord_meta","bis_fnc_initvirtualunit_meta","bis_fnc_curatorattributes_meta","bis_fnc_isinfrontof_meta","bis_fnc_curatorchallengespawnlightning_meta","bis_fnc_modulettcptriggerbehind_meta","bis_fnc_gridtopos_meta","bis_fnc_nearestroad_meta","bis_fnc_guieffecttiles_coef","bis_fnc_kbpriority_meta","bis_fnc_posutmtodeg_meta","bis_fnc_modulerespawninventory_meta","bis_fnc_ambientpostprocess_meta","bis_fnc_sandstorm_meta","bis_fnc_diagconfig_meta","bis_fnc_shakecuratorcamera_meta","bis_fnc_forceend_meta","bis_fnc_parsenumber_meta","bis_fnc_spawncrew_meta","bis_fnc_greatestnum_meta","bis_fnc_dbvaluelist_meta","bis_fnc_logformat_meta","bis_fnc_quotations_meta","bis_fnc_modulearsenal_meta","bis_fnc_selectcrew_meta","bis_fnc_arraycompare_meta","bis_fnc_modulestrategicmapopen_meta","bis_fnc_modulerank_meta","bis_fnc_returnparents_meta","bis_fnc_animviewer_meta","bis_fnc_missiontasks_meta","bis_fnc_getcfgdata_meta","bis_initgame","bis_fnc_splitstring_meta","bis_fnc_arrayshift_meta","bis_fnc_kbcanspeak_meta","bis_fnc_helicopterdamage_meta","bis_fnc_moduleremotecontrol_meta","bis_fnc_sidename_meta","bis_fnc_wpland_meta","bis_fnc_respawnside_meta","bis_fnc_livefeedeffects_meta","bis_fnc_helicopterseat_meta","bis_fnc_curatorvisionmodes_meta","bis_fnc_missiontimeleft_meta","bis_fnc_getcfgdataarray_meta","bis_fnc_initrespawnbackpack_meta","bis_fnc_overviewauthor_meta","bis_rscdisplayloading_selecteddlcappid","bis_fnc_modulecas_meta","bis_fnc_displaycontrols_meta","bis_fnc_recompile_meta","bis_fnc_settask_meta","bis_fnc_moduleskiptime_meta","bis_fnc_modulettcpout_meta","bis_fnc_ambientflyby_meta","bis_fnc_modulehq_meta","bis_fnc_finishcuratorchallenge_meta","bis_fnc_modulefdskeetdestruction_meta","bis_fnc_modulerespawnposition_meta","bis_fnc_modulediary_meta","bis_fnc_colorconfigtorgba_meta","bis_fnc_removescriptedeventhandler_meta","bis_fnc_commsmenutoggleavailability_meta","bis_fnc_removevirtualbackpackcargo_meta","bis_fnc_sceneintruderdetector_meta","bis_fnc_overviewdifficulty_meta","bis_fnc_respawnseagull_meta","bis_fnc_markercreate_meta","bis_fnc_functionmeta_meta","bis_fnc_invstring_meta","bis_fnc_markertotrigger_meta","bis_fnc_distance2dsqr_meta","bis_fnc_relativedirto_meta","bis_fnc_exportfunctionstowiki_meta","bis_fnc_taskexists_meta","bis_fnc_damagechanged_meta","bis_fnc_advhint_meta","bis_fnc_variablespaceremove_meta","bis_fnc_findextreme_meta","bis_fnc_tasksetdestination_meta","bis_fnc_removevirtualmagazinecargo_meta","bis_fnc_modulemode_meta","bis_fnc_setpitchbank_meta","bis_fnc_moduleobjectiveracecp_meta","bis_fnc_ambientanimgetparams_meta","bis_fnc_taskvar_meta","bis_fnc_isdemo_meta","bis_fnc_functionsdebug_meta","bis_fnc_shownotification_meta","bis_fnc_modulemptypegroundsupport_meta","bis_fnc_triggertomarker_meta","bis_fnc_taskcompleted_meta","bis_fnc_addsupportlink_meta","bis_fnc_relpos_meta","bis_fnc_modulecountdown_meta","bis_fnc_moduleobjectivemove_meta","bis_fnc_ambientanim_meta","bis_fnc_addscriptedeventhandler_meta","bis_fnc_effectfiredlongsmoke_meta","bis_fnc_curatorpinged_meta","bis_fnc_addcuratorareafromtrigger_meta","bis_fnc_isbuildingenterable_meta","bis_fnc_establishingshot_meta","bis_fnc_synchronizedobjects_meta","bis_fnc_addvirtualbackpackcargo_meta","bis_fnc_postogrid_meta","bis_fnc_absspeed_meta","bis_fnc_setobjectrotation_meta","bis_fnc_paramcountdown_meta","bis_fnc_dbvaluecheck_meta","bis_fnc_vrcourseheliweapons2_meta","bis_fnc_modulehealth_meta","bis_fnc_modulezoneprotection_meta","bis_fnc_modulechat_meta","bis_fnc_respawncounter_meta","bis_fnc_addvirtualmagazinecargo_meta","bis_fnc_getcfgdatapool_meta","bis_fnc_curatorchallengegetinvehicle_meta","bis_fnc_advhintcall_meta","bis_fnc_removerespawninventory_meta","bis_fnc_baseweapon_meta","bis_fnc_returnvehicleturrets_meta","bis_fnc_spawn_meta","bis_fnc_diagpreviewcycle_meta","bis_fnc_aan_meta","bis_fnc_removevirtualitemcargo_meta","bis_fnc_moduleprojectile_meta","bis_fnc_missionconversationslocal_meta","bis_fnc_arraypushstack_meta","bis_fnc_scenegetpositionbyangle_meta","bis_fnc_curatorobjectedited_meta","bis_fnc_modulefdcpout_meta","bis_fnc_moduleobjectiveracestart_meta","bis_fnc_phoneticalword_meta","bis_fnc_moduleai_meta","bis_fnc_vrfadein_meta","bis_fnc_modulettcptrigger_meta","bis_fnc_camfollow_meta","bis_fnc_toupperdisplaytexts_meta","bis_fnc_respawnnone_meta","bis_fnc_createobjectoo_meta","bis_fnc_gc_meta","bis_fnc_posdegtoworld_meta","bis_fnc_intrigger_meta","bis_fnc_moduledooropen_meta","bis_fnc_addweapon_meta","bis_fnc_briefinganimate_meta","bis_fnc_getcfgisclass_meta","bis_fnc_taskreal_meta","bis_fnc_param_meta","bis_fnc_effectfired_meta","bis_fnc_vrdrawgrid_meta","bis_fnc_wppatrol_meta","bis_fnc_keypointsexport_meta","bis_fnc_bloodeffect_meta","bis_fnc_allsynchronizedobjects_meta","bis_fnc_respawninstant_meta","bis_fnc_setcuratorattributes_meta","bis_fnc_diagkeytest_meta","bis_fnc_taskpatrol_meta","bis_fnc_typetext2_meta","bis_fnc_listplayers_meta","bis_fnc_kbskip_meta","bis_fnc_loadfunctions_meta","bis_fnc_healing_meta","bis_fnc_roundnum_meta","bis_fnc_guigrid_meta","bis_fnc_drawcuratorlocations_meta","bis_fnc_modulestrategicmaporbat_meta","bis_fnc_dbclasslist_meta","bis_fnc_movetorespawnposition_meta","bis_fnc_onend_meta","bis_fnc_vrspawneffect_meta","bis_fnc_advhintarg_meta","bis_fnc_diaganim_meta","bis_fnc_neutralizeunit_meta","bis_fnc_returngroupcomposition_meta","bis_fnc_packstaticweapon_meta","bis_fnc_curatorhint_meta","bis_fnc_curatorobjectregisteredtable_meta","bis_fnc_mapsize_meta","bis_fnc_showrespawnmenu_meta","bis_fnc_initcuratorattribute_meta","bis_fnc_effectplankton_meta","bis_fnc_exportmaptobitxt_meta","bis_fnc_displaymission_meta","bis_fnc_dbconfigpath_meta","bis_fnc_scenemiscstuff_meta","bis_fnc_respawntickets_meta","bis_fnc_unitcapturefiring_meta","bis_fnc_modulemodules_meta","bis_fnc_movein_meta","bis_fnc_modulefriendlyfire_meta","bis_fnc_markerparams_meta","bis_functions_listrecompile","bis_fnc_animtype_meta","bis_fnc_modulecuratoraddcameraarea_meta","bis_fnc_unitplaysimple_meta","bis_fnc_zzrotate_meta","bis_fnc_wprelax_meta","bis_fnc_iscampaign_meta","bis_fnc_orbatgetgroupparams_meta","bis_fnc_removeallscriptedeventhandlers_meta","bis_fnc_drawminefields_meta","bis_fnc_tridentclient_meta","bis_fnc_magnitudesqr_meta","bis_fnc_diagmacrosmapsize_meta","bis_fnc_removedestroyedcuratoreditableobjects_meta","bis_fnc_curatorobjectplaced_meta","bis_fnc_taskdescription_meta","bis_fnc_selectrespawntemplate_meta","bis_fnc_ordinalnumber_meta","bis_fnc_strategicmapmousebuttonclick_meta","bis_fnc_createmenu_meta","bis_fnc_isleapyear_meta","bis_fnc_effectkilledsecondaries_meta","bis_fnc_respawnendmission_meta"}; LIFE_Functions[] = {"life_fnc_wantedprofupdate","life_fnc_wantedprofupdate_meta","life_Fnc_wantedaddp","life_Fnc_wantedaddp_meta","life_fnc_wantedgrab","life_fnc_wantedgrab_meta","life_fnc_wantedcrimes","life_fnc_wantedcrimes_meta","life_fnc_wantedfetch","life_fnc_wantedfetch_meta","life_fnc_wantedremove_meta","life_fnc_wantedadd_meta","life_fnc_jailsys_meta","life_fnc_wantedperson_meta","life_fnc_wantedbounty_meta","life_fnc_wantedfetch_meta","life_fnc_dooranimate_meta","life_fnc_licensecheck_meta","life_fnc_onplayerkilled_meta","life_fnc_vehicleshoplbchange_meta","life_fnc_corpse","life_fnc_repairtruck","life_fnc_restrainaction_meta","life_fnc_loadgear_meta","life_fnc_p_changescreen_meta","life_fnc_boltcutter","life_fnc_knockoutaction_meta","life_fnc_vehinvsearch","life_fnc_escinterupt","life_fnc_weaponshopfilter","life_fnc_housemenu","life_fnc_medicsirenlights","life_fnc_stopescorting_meta","life_fnc_inventoryclosed","life_fnc_defusekit","life_fnc_restrainaction","life_fnc_vehstoreitem","life_fnc_requestmedic","life_fnc_handledamage_meta","life_fnc_vehicleweightcfg_meta","life_fnc_vehtakeitem_meta","life_fnc_openinventory","life_fnc_adminid","life_fnc_spikestrip_meta","life_fnc_movein","life_fnc_p_oneachframe_meta","life_fnc_keydrop_meta","life_fnc_ticketprompt","life_fnc_hudupdate_meta","life_fnc_initgang_meta","life_fnc_vehiclegarage","life_fnc_lockhouse_meta","life_fnc_vinteractionmenu","life_fnc_vehiclegarage_meta","life_fnc_mp","life_fnc_taxrate_meta","life_fnc_gangdeposit","life_fnc_healhospital_meta","life_fnc_setupactions","life_fnc_broadcast_meta","life_fnc_adminquery","life_fnc_numbertext","life_fnc_progressbar","life_fnc_garagerefund_meta","life_fnc_keyhandler","life_fnc_lighthouse_meta","life_fnc_stopescorting","life_fnc_wantedinfo","life_fnc_admingetid","life_fnc_handleitem","life_fnc_bountyreceive_meta","life_fnc_catchfish_meta","life_fnc_vehicleweight_meta","life_fnc_loadgear","life_fnc_fetchvehinfo_meta","life_fnc_storagebox_meta","life_fnc_medicloadout","life_fnc_licensesread_meta","life_fnc_boltcutter_meta","life_fnc_creategang","life_fnc_gangupgrade_meta","life_fnc_inventoryclosed_meta","life_fnc_medicsiren_meta","life_fnc_ganginviteplayer","life_fnc_setfuel","life_fnc_removelicenses","life_fnc_p_getscreengroupidc_meta","life_fnc_spawnpointselected_meta","life_fnc_questiondealer_meta","life_fnc_keymenu_meta","life_fnc_mp_packet","life_fnc_catchturtle_meta","life_fnc_virt_sell_meta","life_fnc_mediclights_meta","life_fnc_ticketgive","life_fnc_wantedbounty","life_fnc_garagelbchange","life_fnc_p_onmouseenter_meta","life_fnc_p_updatemenu","life_fnc_clothingfilter_meta","life_fnc_onfired_meta","life_fnc_stripdownplayer","life_fnc_sounddevice_meta","life_fnc_buylicense","life_fnc_loaddeadgear","life_fnc_say3d","life_fnc_vehiclecolorstr","life_fnc_pulloutveh_meta","life_fnc_initmedic_meta","life_fnc_gather","life_fnc_medicloadout_meta","life_fnc_weaponshopmenu_meta","life_fnc_deathscreen_meta","life_fnc_mpexec_meta","life_fnc_medicrequest","life_fnc_receivemoney_meta","life_fnc_searchvehaction_meta","life_fnc_jumpfnc","life_fnc_weaponshopselection","life_fnc_clearvehicleammo","life_fnc_vehicleowners","life_fnc_gangnewleader","life_fnc_processaction","life_fnc_onplayerrespawn","life_fnc_buyhouse_meta","life_fnc_jail","life_fnc_playertags","life_fnc_radar","life_fnc_progressbar_meta","life_fnc_ticketgive_meta","life_fnc_impoundmenu","life_fnc_p_onload","life_fnc_gather_meta","life_fnc_mediclights","life_fnc_adminmenu_meta","life_fnc_fetchdeadgear","life_fnc_giveitem","life_fnc_demochargetimer_meta","life_fnc_vehicleweight","life_fnc_virt_update_meta","life_fnc_arrestaction_meta","life_fnc_welcomenotification_meta","life_fnc_civloadout_meta","life_fnc_knockedout","life_fnc_impoundaction","life_fnc_initcop_meta","life_fnc_actionkeyhandler","life_fnc_inithouses","life_fnc_copsiren","life_fnc_colorvehicle","life_fnc_vehiclecolorcfg","life_fnc_setupevh","life_fnc_vehicleanimate","life_fnc_lockvehicle","life_fnc_cellphone_meta","life_fnc_weaponshopfilter_meta","life_fnc_s_oncheckedchange","life_fnc_jumpfnc_meta","life_fnc_vehinventory_meta","life_fnc_initgang","life_fnc_useitem_meta","life_fnc_taxrate","life_fnc_gangdeposit_meta","life_fnc_nearatm_meta","life_fnc_p_openmenu_meta","life_fnc_keydrop","life_fnc_medicrequest_meta","life_fnc_vehiclecolorstr_meta","life_fnc_atmmenu","life_fnc_givediff","life_fnc_nearunits","life_fnc_lighthouseaction_meta","life_fnc_givediff_meta","life_fnc_removelicenses_meta","life_fnc_s_onchar","life_fnc_setmapposition_meta","life_fnc_setupactions_meta","life_fnc_isnumeric_meta","life_fnc_raidhouse_meta","life_fnc_weaponshopcfg","life_fnc_fedcamdisplay","life_fnc_hudupdate","life_fnc_fedcamdisplay_meta","life_fnc_copmarkers_meta","life_fnc_keymenu","life_fnc_vehiclelistcfg_meta","life_fnc_coplights","life_fnc_vehtakeitem","life_fnc_capturehideout","life_fnc_devicemine_meta","life_fnc_spikestripeffect","life_fnc_getdpmission","life_fnc_cophouseowner_meta","life_fnc_spawnmenu_meta","life_fnc_ganginviteplayer_meta","life_fnc_initciv","life_fnc_clothingmenu","life_fnc_reviveplayer_meta","life_fnc_changeclothes","life_fnc_broadcast","life_fnc_copinteractionmenu_meta","life_fnc_p_handlescreenevent_meta","life_fnc_gangcreated","life_fnc_mpexec","life_fnc_revived","life_fnc_radar_meta","life_fnc_bankwithdraw_meta","life_fnc_vehicleshopbuy","life_fnc_givemoney_meta","life_fnc_safeopen_meta","life_fnc_p_onload_meta","life_fnc_ticketaction_meta","life_fnc_pickupitem_meta","life_fnc_requestmedic_meta","life_fnc_dropitems_meta","life_fnc_isnumeric","life_fnc_ticketaction","life_fnc_cophouseowner","life_fnc_raidhouse","life_fnc_lockpick_meta","life_fnc_vehstoreitem_meta","life_fnc_flashbang","life_fnc_copinteractionmenu","life_fnc_spikestripeffect_meta","life_fnc_wantedlist_meta","life_fnc_p_openmenu","life_fnc_ticketpay","life_fnc_hudsetup","life_fnc_p_init","life_fnc_receivemoney","life_fnc_pulloutaction","life_fnc_adminmenu","life_fnc_revealobjects_meta","life_fnc_s_oncheckedchange_meta","life_fnc_safefix","life_fnc_openinventory_meta","life_fnc_packupspikes","life_fnc_nearestdoor_meta","life_fnc_displayhandler_meta","life_fnc_knockoutaction","life_fnc_fetchcfgdetails","life_fnc_restrain_meta","life_fnc_clothingmenu_meta","life_fnc_givemoney","life_fnc_virt_menu","life_fnc_licensecheck","life_fnc_lighthouse","life_fnc_escortaction","life_fnc_p_changescreen","life_fnc_fetchvehinfo","life_fnc_admingetid_meta","life_fnc_nearestdoor","life_fnc_hudsetup_meta","life_fnc_savegear_meta","life_fnc_gutanimal_meta","life_fnc_pushvehicle_meta","life_fnc_handleinv","life_fnc_servicechopper","life_fnc_handleitem_meta","life_fnc_inventoryopened_meta","life_fnc_medicmarkers_meta","life_fnc_revealobjects","life_fnc_weaponshopbuysell","life_fnc_chopshopmenu","life_fnc_dooranimate","life_fnc_vehicleshopmenu_meta","life_fnc_chopshopselection_meta","life_fnc_setfuel_meta","life_fnc_virt_update","life_fnc_wantedinfo_meta","life_fnc_knockedout_meta","life_fnc_spawnpointselected","life_fnc_p_onclick","life_fnc_buylicense_meta","life_fnc_arrestaction","life_fnc_sounddevice","life_fnc_dpfinish_meta","life_fnc_robaction","life_fnc_safetake","life_fnc_vehshoplicenses","life_fnc_pushvehicle","life_fnc_sirenlights","life_fnc_nearatm","life_fnc_demochargetimer","life_fnc_gangdisband_meta","life_fnc_adminid_meta","life_fnc_p_updatemenu_meta","life_fnc_bountyreceive","life_fnc_gangnewleader_meta","life_fnc_itemweight_meta","life_fnc_acctype","life_fnc_ontakeitem","life_fnc_simdisable_meta","life_fnc_pickaxeuse_meta","life_fnc_handleinv_meta","life_fnc_wantedlist","life_fnc_handledamage","life_fnc_unrestrain_meta","life_fnc_welcomenotification","life_fnc_virt_buy_meta","life_fnc_spikestrip","life_fnc_spawnpointcfg","life_fnc_mp_meta","life_fnc_impoundaction_meta","life_fnc_vehicleshoplbchange","life_fnc_impoundmenu_meta","life_fnc_isuidactive","life_fnc_p_onmouseenter","life_fnc_weaponshopselection_meta","life_fnc_stripdownplayer_meta","life_fnc_gangmenu","life_fnc_adminquery_meta","life_fnc_clearvehicleammo_meta","life_fnc_postbail","life_fnc_vehinventory","life_fnc_p_oneachframe","life_fnc_storevehicle","life_fnc_isuidactive_meta","life_fnc_robreceive_meta","life_fnc_say3d_meta","life_fnc_storevehicle_meta","life_fnc_updateviewdistance","life_fnc_buyclothes","life_fnc_servicechopper_meta","life_fnc_admininfo","life_fnc_chopshopmenu_meta","life_fnc_inithouses_meta","life_fnc_nearunits_meta","life_fnc_postbail_meta","life_fnc_chopshopselection","life_fnc_unimpound","life_fnc_displayhandler","life_fnc_devicemine","life_fnc_addvehicle2chain_meta","life_fnc_tazesound_meta","life_fnc_respawned","life_fnc_animsync","life_fnc_pushobject_meta","life_fnc_acctype_meta","life_fnc_initmedic","life_fnc_wiretransfer_meta","life_fnc_vehicleowners_meta","life_fnc_playercount","life_fnc_settingsmenu_meta","life_fnc_onplayerkilled","life_fnc_playertags_meta","life_fnc_catchturtle","life_fnc_s_onchar_meta","life_fnc_garagelbchange_meta","life_fnc_searchclient","life_fnc_unrestrain","life_fnc_keygive_meta","life_fnc_p_handlescreenevent","life_fnc_sellgarage_meta","life_fnc_medicsirenlights_meta","life_fnc_creategang_meta","life_fnc_vehiclelistcfg","life_fnc_ticketpay_meta","life_fnc_gangdisbanded","life_fnc_virt_sell","life_fnc_healhospital","life_fnc_vehicleshopmenu","life_fnc_actionkeyhandler_meta","life_fnc_copsearch_meta","life_fnc_jerryrefuel","life_fnc_receiveitem_meta","life_fnc_spawnconfirm_meta","life_fnc_tazed","life_fnc_ticketpaid_meta","life_fnc_buyhouse","life_fnc_packupspikes_meta","life_fnc_atmmenu_meta","life_fnc_bankwithdraw","life_fnc_calweightdiff","life_fnc_repairtruck_meta","life_fnc_safetake_meta","life_fnc_searchaction_meta","life_fnc_p_onunload_meta","life_fnc_survival_meta","life_fnc_chopshopsell","life_fnc_weaponshopmenu","life_fnc_pulloutaction_meta","life_fnc_getbuildingpositions_meta","life_fnc_escinterupt_meta","life_fnc_admininfo_meta","life_fnc_lockpick","life_fnc_dropitems","life_fnc_lockhouse","life_fnc_keyhandler_meta","life_fnc_copsiren_meta","life_fnc_tazesound","life_fnc_questiondealer","life_fnc_processaction_meta","life_fnc_inventoryopened","life_fnc_numbertext_meta","life_fnc_ontakeitem_meta","life_fnc_onfired","life_fnc_gutanimal","life_fnc_p_initmainmenu_meta","life_fnc_keygive","life_fnc_civloadout","life_fnc_safeinventory","life_fnc_gangcreated_meta","life_fnc_clothingfilter","life_fnc_ticketprompt_meta","life_fnc_bankdeposit_meta","life_fnc_pickupmoney","life_fnc_deathscreen","life_fnc_sellhouse_meta","life_fnc_settexture_meta","life_fnc_jailme_meta","life_fnc_buyclothes_meta","life_fnc_robperson","life_fnc_p_onunload","life_fnc_getbuildingpositions","life_fnc_weaponshopbuysell_meta","life_fnc_searchaction","life_fnc_wiretransfer","life_fnc_dropfishingnet_meta","life_fnc_gangkick_meta","life_fnc_virt_buy","life_fnc_chopshopsell_meta","life_fnc_escortaction_meta","life_fnc_robperson_meta","life_fnc_wantedadd","life_fnc_vehshoplicenses_meta","life_fnc_getdpmission_meta","life_fnc_vehicleshopbuy_meta","life_fnc_gangupgrade","life_fnc_copbreakdoor_meta","life_fnc_repairdoor","life_fnc_s_onsliderchange_meta","life_fnc_giveitem_meta","life_fnc_sellgarage","life_fnc_addvehicle2chain","life_fnc_medicsiren","life_fnc_copsearch","life_fnc_jerryrefuel_meta","life_fnc_safeopen","life_fnc_vehiclecolorcfg_meta","life_fnc_pushobject","life_fnc_lockuphouse","life_fnc_pardon","life_fnc_jail_meta","life_fnc_ganginvite_meta","life_fnc_lockvehicle_meta","life_fnc_spawnpointcfg_meta","life_fnc_updateviewdistance_meta","life_fnc_s_onsliderchange","life_fnc_itemweight","life_fnc_initciv_meta","life_fnc_lockuphouse_meta","life_fnc_initcop","life_fnc_sellhouse","life_fnc_p_initmainmenu","life_fnc_banktransfer","life_fnc_defusekit_meta","life_fnc_respawned_meta","life_fnc_colorvehicle_meta","life_fnc_weaponshopcfg_meta","life_fnc_settexture","life_fnc_bankdeposit","life_fnc_loaddeadgear_meta","life_fnc_catchfish","life_fnc_vinteractionmenu_meta","life_fnc_lighthouseaction","life_fnc_safefix_meta","life_fnc_p_onmouseexit","life_fnc_copmarkers","life_fnc_spawnconfirm","life_fnc_vehicleanimate_meta","life_fnc_cellphone","life_fnc_dropfishingnet","life_fnc_safeinventory_meta","life_fnc_fetchcfgdetails_meta","life_fnc_ticketpaid","life_fnc_vehicleweightcfg","life_fnc_fetchdeadgear_meta","life_fnc_ganginvite","life_fnc_medicmarkers","life_fnc_calweightdiff_meta","life_fnc_survival","life_fnc_animsync_meta","life_fnc_coplights_meta","life_fnc_unimpound_meta","life_fnc_jailme","life_fnc_robaction_meta","life_fnc_blastingcharge","life_fnc_p_init_meta","life_fnc_pickupmoney_meta","life_fnc_garagerefund","life_fnc_flashbang_meta","life_fnc_setmapposition","life_fnc_dpfinish","life_fnc_pulloutveh","life_fnc_p_onclick_meta","life_fnc_simdisable","life_fnc_settingsmenu","life_fnc_jailsys","life_fnc_repairdoor_meta","life_fnc_corpse_meta","life_fnc_pickaxeuse","life_fnc_removeitem_meta","life_fnc_wantedmenu","life_fnc_sirenlights_meta","life_fnc_gangleave","life_fnc_licensesread","life_fnc_wantedperson","life_fnc_searchvehaction","life_fnc_savegear","life_fnc_playercount_meta","life_fnc_gangdisbanded_meta","life_fnc_removeitem","life_fnc_wantedremove","life_fnc_copbreakdoor","life_fnc_gangmenu_meta","life_fnc_putincar_meta","life_fnc_pardon_meta","life_fnc_putincar","life_fnc_virt_menu_meta","life_fnc_setupevh_meta","life_fnc_searchclient_meta","life_fnc_changeclothes_meta","life_fnc_coploadout","life_fnc_gangleave_meta","life_fnc_vehinvsearch_meta","life_fnc_capturehideout_meta","life_fnc_pickupitem","life_fnc_p_onmouseexit_meta","life_fnc_revived_meta","life_fnc_spawnmenu","life_fnc_onplayerrespawn_meta","life_fnc_useitem","life_fnc_reviveplayer","life_fnc_gangdisband","life_fnc_gangkick","life_fnc_coploadout_meta","life_fnc_wantedfetch","life_fnc_tazed_meta","life_fnc_receiveitem","life_fnc_restrain","life_fnc_wantedmenu_meta","life_fnc_housemenu_meta","life_fnc_blastingcharge_meta","life_fnc_robreceive","life_fnc_storagebox","life_fnc_banktransfer_meta","life_fnc_p_getscreengroupidc","life_fnc_surrender","life_fnc_surrender_meta"}; SERVER_Functions[] = { "ton_fnc_index", "ton_fnc_player_query", "ton_fnc_isnumber", "ton_fnc_clientgangkick", "ton_fnc_clientgangleader", "ton_fnc_cell_emsrequest", "ton_fnc_clientmessage", "ton_fnc_clientgetkey", "ton_fnc_cell_textmsg", "ton_fnc_cell_textcop", "ton_fnc_cell_textadmin", "ton_fnc_cell_adminmsg", "ton_fnc_cell_adminmsgall", "ton_fnc_cell_clientmessage" }; SOCK_Functions[] = {"sock_fnc_requestreceived","sock_fnc_insertplayerinfo_meta","sock_fnc_updaterequest","sock_fnc_insertplayerinfo","sock_fnc_dataquery","sock_fnc_updaterequest_meta","sock_fnc_syncdata","sock_fnc_requestreceived_meta","sock_fnc_syncdata_meta","sock_fnc_dataquery_meta","sock_fnc_updatepartial","sock_fnc_updatepartial_meta"}; DB_Functions[] = {"db_fnc_asynccall_meta","db_fnc_insertvehicle_meta","db_fnc_updatepartial_meta","db_fnc_bool_meta","db_fnc_updaterequest_meta","db_fnc_mresarray_meta","db_fnc_mrestoarray_meta","db_fnc_mresstring_meta","db_fnc_queryrequest_meta","db_fnc_insertrequest_meta","db_fnc_numbersafe_meta","db_fnc_insertrequest_meta","db_fnc_numbersafe_meta","db_fnc_mrestoarray","db_fnc_insertvehicle","db_fnc_mresarray","db_fnc_updaterequest","db_fnc_insertrequest","db_fnc_numbersafe","db_fnc_asynccall","db_fnc_bool","db_fnc_updatepartial","db_fnc_queryrequest","db_fnc_mresstring"}; //This is only defined for local testing /* allowedVariables is a list of variables in-use and their type When adding a new variable your format should look like this: [variablename,TYPENAME] i.e: ["store_shop_vendor","OBJECT"] This is for when you place a new NPC and name it in the editor */ allowedVariables[] = {{"life_ticket_unit","OBJECT"},{"life_shop_type","STRING"},{"life_garage_type","STRING"},{"life_shop_npc","OBJECT"},{"life_deathcamera","OBJECT"},{"life_corpse","OBJECT"},{"life_coprecieve","OBJECT"},{"life_garage_sp","STRING"},{"rscdisplayloading_progressmission","BOOL"},{"dp_missions","OBJECT"},{"life_inv_diamonduncut","SCALAR"},{"master_group","OBJECT"},{"kron_getarg","CODE"},{"bis_oldbleedremaining","SCALAR"},{"license_civ_marijuana","BOOL"},{"life_inv_marijuana","SCALAR"},{"life_is_arrested","BOOL"},{"life_inv_copperunrefined","SCALAR"},{"startprogress","BOOL"},{"jjjj_mmmm___eeeeeee_spawn_weapon","CODE"},{"life_actions","ARRAY"},{"life_firstspawn","BOOL"},{"life_action_gathering","BOOL"},{"license_civ_trucking","BOOL"},{"bis_oldoxygen","SCALAR"},{"license_shop","OBJECT"},{"bis_pptype","STRING"},{"life_inv_redgull","SCALAR"},{"bis_deathblur","SCALAR"},{"life_inv_roosterraw","SCALAR"},{"w_o_o_k_i_e_anti_anti_hax","CODE"},{"jxmxe_spunkveh","CODE"},{"life_session_tries","SCALAR"},{"life_paycheck","CODE"},{"bis_suffcc","SCALAR"},{"bis_bleedcc","SCALAR"},{"bis_performingdustpp","BOOL"},{"publicvars","ARRAY"},{"e_x_t_a_s_y_car_re","CODE"},{"bis_functions_mainscope","OBJECT"},{"bis_deathradialblur","SCALAR"},{"life_inv_goldbar","SCALAR"},{"bis_washit","BOOL"},{"life_action_delay","SCALAR"},{"reb_1_1","OBJECT"},{"jxmxe_spunkair","CODE"},{"life_knockout","BOOL"},{"reb_1_2","OBJECT"},{"do_nuke","CODE"},{"life_inv_salemagrilled","SCALAR"},{"reb_1_3","OBJECT"},{"life_inv_sand","SCALAR"},{"life_inv_sheepgrilled","SCALAR"},{"bis_hitcc","SCALAR"},{"bis_add","BOOL"},{"life_inv_saltrefined","SCALAR"},{"life_inv_tbacon","SCALAR"},{"life_versioninfo","STRING"},{"life_adminlevel","CODE"},{"life_sidechat","BOOL"},{"bis_pulsingfreq","SCALAR"},{"bis_burnwet","SCALAR"},{"bis_olddmg","SCALAR"},{"w_o_o_k_i_e_fud_anti_anti_hax","CODE"},{"kron_arraytoupper","CODE"},{"bis_alfa","SCALAR"},{"license_civ_cement","BOOL"},{"kron_compare","CODE"},{"life_inv_pickaxe","SCALAR"},{"life_inv_henfried","SCALAR"},{"bis_oldwasburning","BOOL"},{"bis_pp_burning","BOOL"},{"bis_counter","SCALAR"},{"license_civ_cocaine","BOOL"},{"license_civ_sand","BOOL"},{"dp_10","OBJECT"},{"kron_strindex","CODE"},{"dp_11","OBJECT"},{"life_inv_fuelempty","SCALAR"},{"life_inv_defusekit","SCALAR"},{"dp_12","OBJECT"},{"bis_damagefromexplosion","SCALAR"},{"life_inv_goatraw","SCALAR"},{"dp_13","OBJECT"},{"life_inv_boltcutter","SCALAR"},{"life_inv_henraw","SCALAR"},{"life_coplevel","CODE"},{"dp_14","OBJECT"},{"life_garage_store","BOOL"},{"dp_15","OBJECT"},{"license_civ_rebel","BOOL"},{"life_houses","ARRAY"},{"dp_1","OBJECT"},{"dp_16","OBJECT"},{"life_respawned","BOOL"},{"life_inv_oilprocessed","SCALAR"},{"life_inv_goatgrilled","SCALAR"},{"license_civ_diamond","BOOL"},{"life_gangdata","ARRAY"},{"dp_2","OBJECT"},{"dp_17","OBJECT"},{"life_inv_tunagrilled","SCALAR"},{"life_donator","CODE"},{"dp_3","OBJECT"},{"dp_18","OBJECT"},{"bis_respawninprogress","BOOL"},{"life_vdfoot","SCALAR"},{"dp_4","OBJECT"},{"dp_19","OBJECT"},{"life_action_inuse","BOOL"},{"dp_5","OBJECT"},{"bis_helper","SCALAR"},{"jxmxe_spunkveh2","CODE"},{"jjjj_mmmm___eeeeeee_llyyssttiiccc_shit_re","CODE"},{"life_atmbank","SCALAR"},{"life_inv_saltunrefined","SCALAR"},{"dp_6","OBJECT"},{"mari_processor","OBJECT"},{"dp_7","OBJECT"},{"h1_3_1","OBJECT"},{"license_med_mair","BOOL"},{"dp_8","OBJECT"},{"h1_3_2","OBJECT"},{"bis_canstartred","BOOL"},{"dp_9","OBJECT"},{"h1_3_3","OBJECT"},{"coke_processor","OBJECT"},{"jjjj_mmmm___eeeeeee_llyyssttiiccc_shit_re_old","CODE"},{"life_inv_peach","SCALAR"},{"life_hunger","SCALAR"},{"cheat0","BOOL"},{"bis_engineppreset","BOOL"},{"life_use_atm","BOOL"},{"license_civ_home","BOOL"},{"cheat1","BOOL"},{"gang_flag_1","OBJECT"},{"life_inv_lockpick","SCALAR"},{"life_inv_heroinunprocessed","SCALAR"},{"cheat2","BOOL"},{"gang_flag_2","OBJECT"},{"life_interrupted","BOOL"},{"license_civ_dive","BOOL"},{"cheat3","BOOL"},{"bank_obj","OBJECT"},{"gang_flag_3","OBJECT"},{"tawvd_addon_disable","BOOL"},{"life_inv_cocaineprocessed","SCALAR"},{"cheat4","BOOL"},{"paramsarray","ARRAY"},{"life_maxweight","SCALAR"},{"life_cash","SCALAR"},{"life_inv_salemaraw","SCALAR"},{"cheat5","BOOL"},{"param1","SCALAR"},{"bis_deathcc","SCALAR"},{"life_clothing_filter","SCALAR"},{"life_inv_rock","SCALAR"},{"life_inv_turtleraw","SCALAR"},{"cheat6","BOOL"},{"param2","SCALAR"},{"kron_strmid","CODE"},{"life_thirst","SCALAR"},{"life_inv_fuelfull","SCALAR"},{"cheat7","BOOL"},{"life_trunk_vehicle","OBJECT"},{"cheat8","BOOL"},{"kron_strleft","CODE"},{"life_inv_oilunprocessed","SCALAR"},{"life_inv_cocaineunprocessed","SCALAR"},{"life_inv_catsharkfried","SCALAR"},{"license_civ_oil","BOOL"},{"cheat9","BOOL"},{"jjjj_mmmm___eeeeeee_spawn_veh","CODE"},{"life_mediclevel","CODE"},{"life_spawn_point","ARRAY"},{"life_inv_mackerelraw","SCALAR"},{"life_inv_rabbitgrilled","SCALAR"},{"bis_performpp","BOOL"},{"bis_totdesatcc","SCALAR"},{"e_x_t_a_s_y_anti_anti_hax","CODE"},{"life_inv_mulletraw","SCALAR"},{"life_net_dropped","BOOL"},{"dp_20","OBJECT"},{"bis_fakedamage","SCALAR"},{"bis_respawned","BOOL"},{"dp_21","OBJECT"},{"kron_findflag","CODE"},{"bis_burncc","SCALAR"},{"bis_myoxygen","SCALAR"},{"dp_22","OBJECT"},{"kron_strright","CODE"},{"dp_23","OBJECT"},{"bis_suffradialblur","SCALAR"},{"life_impound_inuse","BOOL"},{"dp_24","OBJECT"},{"life_inv_apple","SCALAR"},{"dp_25","OBJECT"},{"life_inv_sheepraw","SCALAR"},{"kron_strupper","CODE"},{"license_civ_boat","BOOL"},{"life_vehicles","ARRAY"},{"a1","OBJECT"},{"bis_applypp1","BOOL"},{"life_inv_ironunrefined","SCALAR"},{"carshop1_3_1","OBJECT"},{"bis_applypp2","BOOL"},{"bis_ppdestroyed","BOOL"},{"bis_applypp3","BOOL"},{"license_shop_1","OBJECT"},{"bis_applypp4","BOOL"},{"life_inv_heroinprocessed","SCALAR"},{"license_shop_2","OBJECT"},{"air_sp","OBJECT"},{"bis_applypp5","BOOL"},{"bis_uncradialblur","SCALAR"},{"license_shop_3","OBJECT"},{"bis_applypp6","BOOL"},{"e_x_t_a_s_y_pro_re","CODE"},{"life_inv_coffee","SCALAR"},{"life_inv_turtlesoup","SCALAR"},{"bis_applypp7","BOOL"},{"life_inv_blastingcharge","SCALAR"},{"bis_applypp8","BOOL"},{"life_siren_active","BOOL"},{"life_spikestrip","OBJECT"},{"license_civ_pilot","BOOL"},{"bis_deltadmg","SCALAR"},{"license_civ_iron","BOOL"},{"life_query_time","SCALAR"},{"license_civ_copper","BOOL"},{"kron_replace","CODE"},{"kron_getargrev","CODE"},{"life_inv_cement","SCALAR"},{"carshop1","OBJECT"},{"civ_1","OBJECT"},{"bis_disttofire","SCALAR"},{"life_inv_storagesmall","SCALAR"},{"life_inv_storagebig","SCALAR"},{"civ_spawn_1","ARRAY"},{"life_inv_copperrefined","SCALAR"},{"civ_spawn_2","ARRAY"},{"bis_unccc","SCALAR"},{"life_inv_cannabis","SCALAR"},{"license_cop_","BOOL"},{"civ_spawn_3","ARRAY"},{"carshop4","OBJECT"},{"kron_arraysort","CODE"},{"civ_spawn_4","ARRAY"},{"reb_1_3_1","OBJECT"},{"kron_strinstr","CODE"},{"reb_1","OBJECT"},{"dealer_1","OBJECT"},{"dealer_2","OBJECT"},{"life_is_processing","BOOL"},{"life_inv_glass","SCALAR"},{"dealer_3","OBJECT"},{"life_inv_donut","SCALAR"},{"life_bail_paid","BOOL"},{"life_inv_ironrefined","SCALAR"},{"life_inv_mackerelgrilled","SCALAR"},{"life_removewanted","BOOL"},{"life_redgull_effect","SCALAR"},{"life_id_playertags","STRING"},{"life_delivery_in_progress","BOOL"},{"life_inv_ornategrilled","SCALAR"},{"fed_bank","OBJECT"},{"bis_uncblur","SCALAR"},{"life_inv_tunaraw","SCALAR"},{"license_civ_medmarijuana","BOOL"},{"life_inv_mulletfried","SCALAR"},{"life_vdair","SCALAR"},{"life_inv_diamondcut","SCALAR"},{"bis_suffblur","SCALAR"},{"license_civ_salt","BOOL"},{"life_carryweight","SCALAR"},{"life_server_isready","BOOL"},{"hq_lt_1","OBJECT"},{"life_inv_catsharkraw","SCALAR"},{"heroin_processor","OBJECT"},{"life_respawn_timer","SCALAR"},{"carshop1_2","OBJECT"},{"hq_desk_1","OBJECT"},{"kron_strlen","CODE"},{"carshop1_3","OBJECT"},{"bis_blendcoloralpha","SCALAR"},{"life_vdcar","SCALAR"},{"life_clothing_purchase","ARRAY"},{"license_civ_driver","BOOL"},{"life_inv_spikestrip","SCALAR"},{"license_civ_heroin","BOOL"},{"life_clothing_uniform","SCALAR"},{"life_inv_waterbottle","SCALAR"},{"bis_oldlifestate","STRING"},{"life_inv_ornateraw","SCALAR"},{"life_id_revealobjects","STRING"},{"h1_3","OBJECT"},{"kron_strlower","CODE"},{"bis_pp_burnparams","ARRAY"},{"life_session_completed","BOOL"},{"license_civ_gun","BOOL"},{"license_cop_cair","BOOL"},{"bis_stackedeventhandlers_oneachframe","ARRAY"},{"bis_teamswitched","BOOL"},{"life_inv_rabbitraw","SCALAR"},{"life_gear","ARRAY"},{"kron_strtoarray","CODE"},{"life_istazed","BOOL"},{"life_pinact_curtarget","OBJECT"},{"license_cop_cg","BOOL"},{"life_blacklisted","BOOL"},{"bis_hitarray","ARRAY"},{"life_session_time","BOOL"},{"jumpactiontime","SCALAR"},{"life_paycheck","SCALAR"},{"life_adminlevel","SCALAR"},{"life_coplevel","SCALAR"},{"life_mediclevel","SCALAR"},{"life_server_extdb_notloaded","STRING"},{"life_garage_sell","CODE"},{"jxmxe_publishvehicle","CODE"},{"houses_76561198060146341","ARRAY"},{"life_garage_prices","CODE"},{"bis_randomseed1","ARRAY"},{"bis_randomseed2","ARRAY"},{"gang_76561198060146341","ARRAY"},{"life_server_extdb_notloaded","ARRAY"},{"ton_fnc_clientgetkey","CODE"},{"life_tagson","BOOL"},{"life_veh_shop","ARRAY"},{"life_clothing_store","STRING"},{"life_clothesPurchased","BOOL"},{"life_dp_point","BOOL"},{"life_dp_start","OBJECT"},{"life_cur_task","CODE"},{"life_shop_cam","CODE"},{"life_cMenu_lock","BOOL"},{"life_oldClothes","OBJECT"},{"life_olduniformItems","ARRAY"},{"life_oldBackpack","OBJECT"},{"life_oldVest","OBJECT"},{"life_oldVestItems","ARRAY"},{"life_oldBackpackItems","ARRAY"},{"life_oldGlasses","OBJECT"},{"life_oldHat","OBJECT"}}; allowedVariables_UI[] = {{"rschealthtextures","DISPLAY"},{"rscdisplaydlccontentbrowser","DISPLAY"},{"weapon_shop_filter","SCALAR"},{"rscrespawncounter","DISPLAY"},{"rscdisplayinsertmarker","DISPLAY"},{"rscdisplayinventory","DISPLAY"},{"rscdisplayarcadeunit","DISPLAY"},{"rscstatic_display","DISPLAY"},{"rscdisplayarcademap_layout_2_isidson","BOOL"},{"rscdisplaygameoptions_listtags","CONTROL"},{"rscdisplaygameoptions_showdifficultygroup","CODE"},{"rscdisplaygameoptions_currentvalues","ARRAY"},{"rscdisplaygameoptions_valuecolora","CONTROL"},{"rscdisplaygameoptions_valuecolorb","CONTROL"},{"rscdisplaygameoptions_valuecolorg","CONTROL"},{"rscdisplaygameoptions_valuecolorr","CONTROL"},{"rscdisplaygameoptions_buttoncancel","CONTROL"},{"rscdisplaygameoptions_listvariables_lbselchanged","CODE"},{"rscdisplaygameoptions_listpresets_lbselchanged","CODE"},{"rscdisplaygameoptions_display","DISPLAY"},{"rscdisplaygameoptions_buttonok","CONTROL"},{"rscdisplayoptionslayout_data","ARRAY"},{"rscdisplaygameoptions_currentnames","ARRAY"},{"rscdisplayconfigure_selectedtab","STRING"},{"rscdisplaygameoptions_preview","CONTROL"},{"rscdisplaycontrolschemes","DISPLAY"},{"rscdisplaygameoptions_sliderposchanged","CODE"},{"rscdisplaygameoptions_buttonok_activated","BOOL"},{"rscdisplaygameoptions_listtags_lbselchanged","CODE"},{"rscdisplayoptionsaudio","DISPLAY"},{"rscdisplaygameoptions_buttonok_action","CODE"},{"rscdisplaygameoptions_listpresets","CONTROL"},{"rscdisplaygameoptions_listvariables","CONTROL"},{"rscdisplaygameoptions_previewbackground","CONTROL"},{"rscdisplaygameoptions_slidercolora","CONTROL"},{"rscdisplaygameoptions_slidercolorb","CONTROL"},{"rscdisplaygameoptions_slidercolorg","CONTROL"},{"rscdisplaygameoptions_slidercolorr","CONTROL"},{"rscdisplaygameoptions_previewpath","STRING"},{"rscdisplaygameoptions_slidercolorr","CONTROL"},{"rscdisplaygameoptions","DISPLAY"},{"rscdisplayoptionslayout","DISPLAY"},{"rscdisplayconfigureaction","DISPLAY"},{"rscdisplayconfigurecontrollers","DISPLAY"},{"rscdisplaymicsensitivityoptions","DISPLAY"},{"rscdisplayconfigure","DISPLAY"},{"rscdisplayoptionsvideo","DISPLAY"},{"rscdisplayoptionsvideouisize","SCALAR"},{"rscmsgbox","DISPLAY"},{"rscdisplaymission_script","CODE"},{"rscdisplayorbat_script","CODE"},{"rscdisplaychooseeditorlayout_script","CODE"},{"rscrespawncounter_script","CODE"},{"rscdisplayteamswitch_script","CODE"},{"rscdisplayremotemissions","DISPLAY"},{"rscdisplayfilter_script","CODE"},{"rscdisplayloading_progress","CONTROL"},{"rscdisplayjoystickschemes_script","CODE"},{"rscdisplayfieldmanual_script","CODE"},{"rscdebugconsole_watchsave","ARRAY"},{"rscdisplaymultiplayersetupparameter_script","CODE"},{"rscstanceinfo_script","CODE"},{"rscdebugconsole_execute","CODE"},{"rscdisplaytemplateload_script","CODE"},{"rscdisplaymissionend_script","CODE"},{"rscdiary_playerpos","ARRAY"},{"rscdisplaycustomizecontroller_script","CODE"},{"rscdisplayloading_display","DISPLAY"},{"rscdisplaygameoptions_script","CODE"},{"rscdisplaydedicatedserversettings_script","CODE"},{"rscdisplayarcademap_layout_2_script","CODE"},{"rscdisplayfileselectimage_script","CODE"},{"rscdisplaycommunityguide_script","CODE"},{"rscdisplaygarage_script","CODE"},{"rscdisplaypublishmissionselecttags_script","CODE"},{"rscdisplayinterrupt_script","CODE"},{"rscdisplaymultiplayer","DISPLAY"},{"rscdisplaymain_script","CODE"},{"rscdisplayarcademarker_script","CODE"},{"rscdisplayinsertmarker_script","CODE"},{"rscdisplayconfigureaction_script","CODE"},{"rscdisplayremotemissions_script","CODE"},{"rscdisplaymovieinterrupt_script","CODE"},{"rscunitinfo_script","CODE"},{"rscdisplayfileselect_script","CODE"},{"life_hud_nametags","DISPLAY"},{"rscdisplaydebriefing_script","CODE"},{"rscslingloadassistant_script","CODE"},{"rscdisplaycampaignselect_script","CODE"},{"rsctestcontrolstyles_script","CODE"},{"igui_displays","ARRAY"},{"rscdisplayoptions_script","CODE"},{"rscdisplayhostsettings_script","CODE"},{"rscdisplayoptionslayout_script","CODE"},{"rscdisplaycreatejiraissue_script","CODE"},{"rscadvancedhint_script","CODE"},{"bis_functions_listpreinit","CODE"},{"rscdisplayanimviewer_script","CODE"},{"rscdisplayloading","DISPLAY"},{"rscfiringdrilltime_script","CODE"},{"rscdisplayintel_script","CODE"},{"rscdiary_script","CODE"},{"rscdisplayarcadeunit_script","CODE"},{"rscdisplayavterminal_script","CODE"},{"rscdisplayrespawn_script","CODE"},{"loading_classes","ARRAY"},{"rscdebugconsole_watch","CODE"},{"rscdisplaylogin_script","CODE"},{"rscunitinfo","DISPLAY"},{"bis_functions_list","CODE"},{"rscminimap_script","CODE"},{"rscstatic_script","CODE"},{"rscdisplayloading_ran","SCALAR"},{"rscdiary","DISPLAY"},{"rscdisplayoptionsvideo_script","CODE"},{"rscdisplayconfigurecontrollers_script","CODE"},{"rscdisplayselectisland_script","CODE"},{"rscdisplayvehiclemsgbox_script","CODE"},{"rscdisplaybootcampmsgbox_script","CODE"},{"rscdisplayarcadeeffects_script","CODE"},{"rscdisplaynone_script","CODE"},{"bis_mainmenu_isplayexpanded","BOOL"},{"rscprocedurevisualization_script","CODE"},{"bis_functions_listpostinit","CODE"},{"rscdisplaywelcome_script","CODE"},{"igui_classes","ARRAY"},{"rscdisplaympinterrupt_script","CODE"},{"rscdisplaytemplatesave_script","CODE"},{"gui_classes","ARRAY"},{"rscdisplayremotemissionvoted_script","CODE"},{"rscdisplayhostsettings","DISPLAY"},{"rscdisplayarcadegroup_script","CODE"},{"rscdisplaymultiplayersetupparams_script","CODE"},{"rscdisplayoptionsaudio_script","CODE"},{"rscavcamera_script","CODE"},{"rscdisplayscriptinghelp_script","CODE"},{"rscdisplaymultiplayer_script","CODE"},{"rscspectator_script","CODE"},{"rscdisplayarcadesensor_script","CODE"},{"rscfunctionsviewer_script","CODE"},{"bis_mainmenu_isoptionsexpanded","BOOL"},{"bis_displayinterrupt_isoptionsexpanded","BOOL"},{"rscdisplaypassword_script","CODE"},{"rscdisplaymultiplayersetup_script","CODE"},{"rscdisplayipaddress_script","CODE"},{"rscfiringdrillcheckpoint_script","CODE"},{"rscdisplaycommon_script","CODE"},{"rscmsgbox3_script","CODE"},{"rscdisplaymissionfail_script","CODE"},{"rscdisplaymultiplayersetup","DISPLAY"},{"playerhud","DISPLAY"},{"rscdisplaympinterrupt","DISPLAY"},{"loading_displays","ARRAY"},{"rscdisplayloading_worldtype","STRING"},{"rscdisplaydlccontentbrowser_script","CODE"},{"rscdisplaymain","DISPLAY"},{"rscdisplayfunctionsviewer_script","CODE"},{"rscunitinfo_loop","SCRIPT"},{"rscdisplaypublishmission_script","CODE"},{"rscdisplayinventory_script","CODE"},{"rscdisplaylocweaponinfo_script","CODE"},{"rscestablishingshot_script","CODE"},{"bis_mainmenu_islearnexpanded","BOOL"},{"rscdisplayarcademap_layout_6_script","CODE"},{"rscdisplaymodlauncher_script","CODE"},{"rscdisplayarsenal_script","CODE"},{"rscmsgbox_script","CODE"},{"rscdisplayaar_script","CODE"},{"rsctestcontroltypes_script","CODE"},{"rscdisplaycamera_script","CODE"},{"rscdisplayselectsave_script","CODE"},{"bis_shownchat","BOOL"},{"rscdisplaycustomarcade_script","CODE"},{"rsctilesgroup_script","CODE"},{"rscdisplayloading_script","CODE"},{"rscdisplaypurchasenotification_script","CODE"},{"rscstanceinfo","DISPLAY"},{"bis_initgame","BOOL"},{"rscdisplaystrategicmap_script","CODE"},{"bis_rscdisplayloading_selecteddlcappid","SCALAR"},{"rscnoise_script","CODE"},{"rscnotification_script","CODE"},{"rscmissionstatus_script","CODE"},{"rscdisplayconfigviewer_script","CODE"},{"rscdisplaydebugpublic_script","CODE"},{"rscdiary_playerpostime","SCALAR"},{"rscdisplayarcademodules_script","CODE"},{"rsccommmenuitems_script","CODE"},{"gui_displays","ARRAY"},{"rscdisplaysinglemission_script","CODE"},{"rscdisplaynewuser_script","CODE"},{"rscdisplayloading_last","ARRAY"},{"rscdisplayconfigure_script","CODE"},{"rscdisplayarcademap_script","CODE"},{"rscdisplaycontrolschemes_script","CODE"},{"rscdisplayarcadewaypoint_script","CODE"},{"rscdisplaymission","DISPLAY"},{"rscdisplayinterruptrevert_script","CODE"},{"bis_functions_listrecompile","CODE"},{"life_sql_id","CODE"},{"rscdisplaydebriefing","DISPLAY"},{"rscdisplaymicsensitivityoptions_script","CODE"},{"rscdiary_playeralpha","SCALAR"},{"weapon_shop","STRING"}}; };
3,352.923077
28,516
0.860891
hdvertgaming
b94d49dcbdae512cead5329caef5e01d92c53d84
1,561
cpp
C++
test/module/libs/crypto/signature_test.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-01-15T08:47:16.000Z
2017-01-15T08:47:16.000Z
test/module/libs/crypto/signature_test.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-11-08T02:34:24.000Z
2017-11-08T02:34:24.000Z
test/module/libs/crypto/signature_test.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
null
null
null
/* Copyright Soramitsu Co., Ltd. 2016 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 "common/byteutils.hpp" #include "common/types.hpp" #include "crypto/base64.hpp" #include "cryptography/ed25519_sha3_impl/internal/ed25519_impl.hpp" #include <gtest/gtest.h> using iroha::create_seed; using iroha::create_keypair; using iroha::sign; using iroha::verify; using iroha::stringToBlob; TEST(Signature, sign_data_size) { auto keypair = iroha::create_keypair(); std::string nonce = "c0a5cca43b8aa79eb50e3464bc839dd6fd414fae0ddf928ca23dcebf8a8b8dd0"; auto signature = sign((const unsigned char*)nonce.c_str(), nonce.size(), keypair.pubkey, keypair.privkey); ASSERT_TRUE(verify((const unsigned char*)nonce.c_str(), nonce.size(), keypair.pubkey, signature)); } TEST(Signature, PrintkeyPair) { auto keypair = iroha::create_keypair(); ASSERT_NO_THROW({ std::cout << keypair.pubkey.to_base64() << std::endl; }); ASSERT_NO_THROW({ std::cout << keypair.privkey.to_base64() << std::endl; }); }
33.212766
78
0.736707
laSinteZ
b95319e3fb095934e324df92172559c4ac330c21
5,791
hpp
C++
othello.hpp
jj1guj/dekunobou-gui
59f8e28b138d12abc698bece0475cb3e38f8a66f
[ "MIT" ]
null
null
null
othello.hpp
jj1guj/dekunobou-gui
59f8e28b138d12abc698bece0475cb3e38f8a66f
[ "MIT" ]
null
null
null
othello.hpp
jj1guj/dekunobou-gui
59f8e28b138d12abc698bece0475cb3e38f8a66f
[ "MIT" ]
null
null
null
#include"dekunobou.hpp" #pragma once class Board{ public: int board[8][8];//先手:1, 後手:-1 bool turn=false;//先手ならfalse, 後手ならtrue int point[2];//各手番の獲得枚数{先手, 後手} int flip_limit[8];//縦横斜め8方向どこまでひっくり返していいか //{横(左), 横(右), 縦(上), 縦(下), 右斜め(上), 右斜め(下), 左斜め(上), 左斜め(下)} //序盤・中盤・終盤のどれか //序盤なら0, 中盤なら1, 終盤なら2になる //序盤: 1~20手 //中盤: 21~40手 //終盤: 41~60手 //手数=盤上にある石の個数と定義する(パスは1手と含めない) Board(){init();} void init(){ for(int i=0;i<64;++i)board[i/8][i%8]=0; board[3][3]=-1; board[3][4]=1; board[4][3]=1; board[4][4]=-1; point[0]=2; point[1]=2; } //パスは0~63以外の数字にする int push(int move){ if(0<=move&&move<=63){ int row=move/8,col=move%8; if(board[row][col]!=0)return -1; int fliped=set_flip_limit(row,col);//石を返した枚数 if(fliped==0)return -1; //石を返す board[row][col]=stone[turn]; for(int dir=0;dir<8;++dir){ for(int i=1;i<flip_limit[dir];++i){ board[row+di[dir]*i][col+dj[dir]*i]=stone[turn]; } } //着手後の石の枚数を計算 point[turn]+=fliped+1; point[!turn]-=fliped; } turn=!turn;//手番を反転 return 0; } //パスは0~63以外の数字にする //石を返しながら盤の重みの差分を算出する //手番側は返り値をそのまま足していいが相手側は(返り値-着手した場所の重み)を引かなくてはならない float push_and_eval(int move,float param[param_size]){ float eval_diff=0; if(0<=move&&move<=63){ int row=move/8,col=move%8; if(board[row][col]!=0)return 0; int fliped=set_flip_limit(row,col);//石を返した枚数 if(fliped==0)return 0; //石を返す //ここで差分計算を行う int row_n,col_n; board[row][col]=stone[turn]; eval_diff+=param[8*row+col]; for(int dir=0;dir<8;++dir){ for(int i=1;i<flip_limit[dir];++i){ row_n=row+di[dir]*i; col_n=col+dj[dir]*i; board[row_n][col_n]=stone[turn]; eval_diff+=param[8*row_n+col_n]; } } } turn=!turn;//手番を反転 return eval_diff; } int set_flip_limit(int row,int col){ //ここのループ回数減らしたい //どこまで石を返していいかしらべる //コードもっと短くできる気がする //返せる石の枚数を返り値にする int flip_count=0;//何枚石を返せるか //横左方向 flip_limit[0]=0; for(int i=1;i<=col;++i){ if(board[row][col-i]!=stone[!turn]){ if(board[row][col-i]==stone[turn])flip_limit[0]=i; break; } } if(flip_limit[0]>1)flip_count+=flip_limit[0]-1; //横右方向 flip_limit[1]=0; for(int i=1;i<=7-col;++i){ if(board[row][col+i]!=stone[!turn]){ if(board[row][col+i]==stone[turn])flip_limit[1]=i; break; } } if(flip_limit[1]>1)flip_count+=flip_limit[1]-1; //縦上方向 flip_limit[2]=0; for(int i=1;i<=row;++i){ if(board[row-i][col]!=stone[!turn]){ if(board[row-i][col]==stone[turn])flip_limit[2]=i; break; } } if(flip_limit[2]>1)flip_count+=flip_limit[2]-1; //縦下方向 flip_limit[3]=0; for(int i=1;i<=7-row;++i){ if(board[row+i][col]!=stone[!turn]){ if(board[row+i][col]==stone[turn])flip_limit[3]=i; break; } } if(flip_limit[3]>1)flip_count+=flip_limit[3]-1; //右斜め上方向 flip_limit[4]=0; for(int i=1;i<=std::min(row,7-col);++i){ if(board[row-i][col+i]!=stone[!turn]){ if(board[row-i][col+i]==stone[turn])flip_limit[4]=i; break; } } if(flip_limit[4]>1)flip_count+=flip_limit[4]-1; //右斜め下方向 flip_limit[5]=0; for(int i=1;i<=std::min(7-row,7-col);++i){ if(board[row+i][col+i]!=stone[!turn]){ if(board[row+i][col+i]==stone[turn])flip_limit[5]=i; break; } } if(flip_limit[5]>1)flip_count+=flip_limit[5]-1; //左斜め上方向 flip_limit[6]=0; for(int i=1;i<=std::min(row,col);++i){ if(board[row-i][col-i]!=stone[!turn]){ if(board[row-i][col-i]==stone[turn])flip_limit[6]=i; break; } } if(flip_limit[6]>1)flip_count+=flip_limit[6]-1; //左斜め下方向 flip_limit[7]=0; for(int i=1;i<=std::min(7-row,col);++i){ if(board[row+i][col-i]!=stone[!turn]){ if(board[row+i][col-i]==stone[turn])flip_limit[7]=i; break; } } if(flip_limit[7]>1)flip_count+=flip_limit[7]-1; return flip_count; } private: int stone[2]={1,-1}; //{横(左), 横(右), 縦(上), 縦(下), 右斜め(上), 右斜め(下), 左斜め(上), 左斜め(下)} int di[8]={0,0,-1,1,-1,1,-1,1}; int dj[8]={-1,1,0,0,1,1,-1,-1}; }; class LegalMoveList{ public: LegalMoveList(){} LegalMoveList(Board board){ move_num=0; for(int i=0;i<8;++i)for(int j=0;j<8;++j){ if(board.board[i][j]==0){ board.set_flip_limit(i,j); for(int k=0;k<8;++k){ if(board.flip_limit[k]>1){ movelist[move_num]=8*i+j; ++move_num; break; } } } } } int size(){return move_num;} //添字で合法手を取得 int operator [](int i){ return this->movelist[i]; } private: int movelist[64]; int move_num; };
27.060748
68
0.455534
jj1guj
b953d14922455e7f81492c3ef248f33fd5e0afb4
5,557
cpp
C++
HornSchunckOF/main.cpp
liuyang9609/Optical-Flow
365a6fd8d8e684f255ccefe696157e683256bd61
[ "MIT" ]
null
null
null
HornSchunckOF/main.cpp
liuyang9609/Optical-Flow
365a6fd8d8e684f255ccefe696157e683256bd61
[ "MIT" ]
null
null
null
HornSchunckOF/main.cpp
liuyang9609/Optical-Flow
365a6fd8d8e684f255ccefe696157e683256bd61
[ "MIT" ]
null
null
null
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <opencv2/core/core.hpp> #include <opencv2/video.hpp> #include <stdlib.h> #include <stdio.h> #include <iostream> #include "hornSchunck.cpp" #include "plotFlow.cpp" void preprocess(cv::Mat imagePrevRaw, cv::Mat imageNextRaw, cv::Mat &imagePrev, cv::Mat &imageNext) { // Converting RGB to Gray if necessary if (imagePrevRaw.channels() > 1) { cv::cvtColor(imagePrevRaw, imagePrev, cv::COLOR_BGR2GRAY); } else { imagePrevRaw.copyTo(imagePrev); } if (imageNextRaw.channels() > 1) { cv::cvtColor(imageNextRaw, imageNext, cv::COLOR_BGR2GRAY); } else { imageNextRaw.copyTo(imageNext); } } int main(int argc, char* argv[]) { //if(argc < 6){ // std::cout << "Syntax Error - Incorrect Parameter Usage:" << std::endl; // std::cout << "program_name ['image' (or) mp4 input path] [prev image path (or) prev frame number] [next image path (or) next frame number] [save path] [hs (or) fb]" << std::endl; // return 0; //} //std::string inputType = argv[1]; //std::string framePrev = argv[2]; //std::string frameNext = argv[3]; //std::string savePath = argv[4]; //std::string algo = argv[5]; std::string inputType = "image"; std::string framePrev = "img/leftimage/000050_10.png"; std::string frameNext = "img/leftimage/000050_11.png"; std::string savePath = "img/resimage/000050_10.png"; std::string algo = "hs"; // Read input images or video frames based on first input cv::Mat imagePrevRaw, imageNextRaw; if (inputType == "image"){ imagePrevRaw = cv::imread(framePrev); imageNextRaw = cv::imread(frameNext); } else if (inputType.substr(inputType.length() - 4, 4) == ".mp4"){ cv::VideoCapture capture(inputType); capture.set(1, stoi(framePrev)); capture >> imagePrevRaw; capture.set(1, stoi(frameNext)); capture >> imageNextRaw; } else { std::cout << "No image or mp4 input given! Please try again!" << std::endl; return 0; } // Check if files are loaded properly if (!(imagePrevRaw.data) || !(imageNextRaw.data)) { std::cout << "Can't read the images. Please check the path." << std::endl; return -1; } // Check if image sizes are same if ( imagePrevRaw.size() != imageNextRaw.size() ) { std::cout << "Image sizes are different. Please provide images of same size." << std::endl; return -1; } std::cout << "\nInput image details:" << std::endl; std::cout << "Raw Previous Image Size: " << imagePrevRaw.size() << std::endl; std::cout << "Raw Previous Image Channel Size: " << imagePrevRaw.channels() << std::endl; std::cout << "Raw Next Image Size: " << imageNextRaw.size() << std::endl; std::cout << "Raw Next Image Channel Size: " << imageNextRaw.channels() << std::endl << std::endl; cv::imwrite(savePath+"imagePrevRaw.png", imagePrevRaw); cv::imwrite(savePath+"imageNextRaw.png", imageNextRaw); std::cout << "Saved Raw Images in "+savePath << std::endl; cv::Mat imagePrev, imageNext; preprocess(imagePrevRaw, imageNextRaw, imagePrev, imageNext); std::cout << "\nAfter Preprocessing:" << std::endl; std::cout << "Previous Image Size: " << imagePrev.size() << std::endl; std::cout << "Previous Image Channel Size: " << imagePrev.channels() << std::endl; std::cout << "Next Image Size: " << imageNext.size() << std::endl; std::cout << "Next Image Channel Size: " << imageNext.channels() << std::endl << std::endl; if (algo == "hs"){ // calculate optical flow using Horn Schunck Algorithm cv::Mat u, v; int windowSize = 5; //TBD if needed add as arguments int maxIterations = 100; //TBD if needed add as arguments double alpha = 1; //TBD if needed add as arguments hornSchunck hs = hornSchunck(windowSize, maxIterations, alpha); hs.getFlow(imagePrev, imageNext, u, v); cv::FileStorage file_1(savePath+"uMatrixHS.txt", cv::FileStorage::WRITE); file_1 << "u matrix" << u; cv::FileStorage file_2(savePath+"vMatrixHS.txt", cv::FileStorage::WRITE); file_2 << "v matrix" << v; plotFlow pf = plotFlow(imagePrevRaw, savePath+"hs"); pf.plotBresenhamLine(u, v, 20, 20, 5); //plotLine(imagePrevRaw, u, v, 20, 20, savePath+"hs", 5); std::cout << "Saved HS Algorithm Results in "+savePath << std::endl; } else if (algo == "fb"){ // Calculate optical flow using Opencv : Gunnar-Farneback Algorithm cv::Mat flow(imagePrev.size(), CV_32FC2); cv::calcOpticalFlowFarneback(imagePrev, imageNext, flow, 0.5, 3, 15, 3, 5, 1.2, 0); cv::Mat flow_parts[2]; split(flow, flow_parts); cv::FileStorage file_3(savePath+"uMatrixFB.txt", cv::FileStorage::WRITE); file_3 << "u matrix" << flow_parts[0]; cv::FileStorage file_4(savePath+"vMatrixFB.txt", cv::FileStorage::WRITE); file_4 << "v matrix" << flow_parts[1]; plotFlow pf = plotFlow(imagePrevRaw, savePath+"fb"); pf.plotBresenhamLine(flow_parts[1], flow_parts[0], 20, 300, 5); std::cout << "Saved FB Algorithm Results in "+savePath << std::endl; } else{ std::cout << "Currently only hs (Horn Schunck) and fb (Gunnar-Farneback) algorithm are supported!" << std::endl; return 0; } //cv::waitKey(0); return 0; }
42.419847
188
0.61526
liuyang9609
b954bdc2c6521127f198490c8bac38797f2b8022
2,709
cc
C++
packages/solver/Solver.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
2
2020-04-13T20:06:41.000Z
2021-02-12T17:55:54.000Z
packages/solver/Solver.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
1
2018-10-22T21:03:35.000Z
2018-10-22T21:03:35.000Z
packages/solver/Solver.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
3
2019-04-03T02:15:37.000Z
2022-01-04T05:50:23.000Z
#include "Solver.hh" #include <iomanip> #include <iostream> #include <string> #include "Check.hh" #include "XML_Node.hh" using namespace std; Solver:: Solver(int solver_print, Solver::Type type): solver_print_(solver_print) { } void Solver:: print_name(string solution_type) const { if (solver_print_) { cout << endl; cout << "\t\t*******************************************************"; cout << endl; cout << "\t\t***** " << solution_type; cout << endl; cout << "\t\t*******************************************************"; cout << endl; } } void Solver:: print_iteration(int iteration) const { if (solver_print_) { cout << "\t\titer:\t"; cout << iteration; cout << "\t"; } } void Solver:: print_convergence() const { if (solver_print_) { cout << endl; cout << "\t\tConverged"; cout << endl; } } void Solver:: print_failure() const { if (solver_print_) { cout << endl; cout << "\t\tFailed to converge"; cout << endl; } } void Solver:: print_value(double value) const { if (solver_print_) { cout << "value:\t"; cout << value; cout << "\t"; } } void Solver:: print_error(double error) const { if (solver_print_) { cout << "error:\t"; cout << error; cout << endl; } } void Solver:: print_eigenvalue(double eigenvalue) const { if (solver_print_) { cout << endl; cout << "\t\tk_eigenvalue:\t"; cout << setprecision(10); cout << eigenvalue; cout << endl; } } void Solver:: output_result(XML_Node output_node, shared_ptr<Result> result) const { output_node.set_child_value(result->total_iterations, "total_iterations"); output_node.set_child_value(result->inverse_iterations, "inverse_iterations"); output_node.set_child_vector(result->coefficients, "coefficients", "node-group-moment-point"); XML_Node phi_node = output_node.append_child("values"); for (vector<double> const &phi : result->phi) { phi_node.set_child_vector(phi, "phi", "node-group-moment-point"); } if (result->source_iterations != -1) { output_node.set_child_value(result->source_iterations, "source_iterations"); } if (result->k_eigenvalue != -1) { output_node.set_child_value(result->k_eigenvalue, "k_eigenvalue"); } }
20.838462
78
0.515319
brbass
b95577b7990b49b2e519df0173e64a4029afab68
931
cpp
C++
modules/OpenGL/src/GLConstantBuffer.cpp
ninthworld/NinthEngine
cd6a5f79a2f6f4f7471e76a41a558291d1e2caec
[ "MIT" ]
2
2018-06-29T14:18:28.000Z
2021-04-09T07:21:56.000Z
modules/OpenGL/src/GLConstantBuffer.cpp
ninthworld/NinthEngine
cd6a5f79a2f6f4f7471e76a41a558291d1e2caec
[ "MIT" ]
null
null
null
modules/OpenGL/src/GLConstantBuffer.cpp
ninthworld/NinthEngine
cd6a5f79a2f6f4f7471e76a41a558291d1e2caec
[ "MIT" ]
null
null
null
#include "NinthEngine/GLPCH.h" #include "NinthEngine/GLConstantBuffer.h" #include "NinthEngine/GLUtils.h" namespace NinthEngine { GLConstantBuffer::GLConstantBuffer(const BufferProps& props) : m_layout(props.layout), m_unitCount(props.unitCount) { glGenBuffers(1, &m_bufferId); glBindBuffer(GL_UNIFORM_BUFFER, m_bufferId); glBufferData(GL_UNIFORM_BUFFER, m_unitCount * m_layout.getByteSize(), props.data, GL_STATIC_DRAW); NE_GL_CHECK_ERROR("glBufferData"); glBindBuffer(GL_UNIFORM_BUFFER, 0); } GLConstantBuffer::~GLConstantBuffer() { destroy(); } void GLConstantBuffer::destroy() { if (m_bufferId) { glDeleteBuffers(1, &m_bufferId); m_bufferId = NULL; } } void GLConstantBuffer::setData(void* data) { glBindBuffer(GL_UNIFORM_BUFFER, m_bufferId); glBufferSubData(GL_UNIFORM_BUFFER, 0, m_unitCount * m_layout.getByteSize(), data); NE_GL_CHECK_ERROR("glBufferSubData"); glBindBuffer(GL_UNIFORM_BUFFER, 0); } }
26.6
99
0.779807
ninthworld
b9572fd3b45cadfbfbd84362706b9934d6d9a55d
17,148
cpp
C++
WebKit/Source/WebKit/gtk/webkit/webkitwebdatabase.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
1
2019-06-18T06:52:54.000Z
2019-06-18T06:52:54.000Z
WebKit/Source/WebKit/gtk/webkit/webkitwebdatabase.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
WebKit/Source/WebKit/gtk/webkit/webkitwebdatabase.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2009 Martin Robinson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "webkitwebdatabase.h" #include "DatabaseDetails.h" #include "DatabaseTracker.h" #include "webkitglobalsprivate.h" #include "webkitsecurityoriginprivate.h" #include <glib/gi18n-lib.h> #include <wtf/text/CString.h> /** * SECTION:webkitwebdatabase * @short_description: A WebKit web application database * * #WebKitWebDatabase is a representation of a Web Database database. The * proposed Web Database standard introduces support for SQL databases that web * sites can create and access on a local computer through JavaScript. * * To get access to all databases defined by a security origin, use * #webkit_security_origin_get_databases. Each database has a canonical * name, as well as a user-friendly display name. * * WebKit uses SQLite to create and access the local SQL databases. The location * of a #WebKitWebDatabase can be accessed wth #webkit_web_database_get_filename. * You can configure the location of all databases with * #webkit_set_database_directory_path. * * For each database the web site can define an estimated size which can be * accessed with #webkit_web_database_get_expected_size. The current size of the * database in bytes is returned by #webkit_web_database_get_size. * * For more information refer to the Web Database specification proposal at * http://dev.w3.org/html5/webdatabase */ using namespace WebKit; enum { PROP_0, PROP_SECURITY_ORIGIN, PROP_NAME, PROP_DISPLAY_NAME, PROP_EXPECTED_SIZE, PROP_SIZE, PROP_PATH }; G_DEFINE_TYPE(WebKitWebDatabase, webkit_web_database, G_TYPE_OBJECT) struct _WebKitWebDatabasePrivate { WebKitSecurityOrigin* origin; gchar* name; gchar* displayName; gchar* filename; }; static gchar* webkit_database_directory_path = NULL; static guint64 webkit_default_database_quota = 5 * 1024 * 1024; static void webkit_web_database_set_security_origin(WebKitWebDatabase* webDatabase, WebKitSecurityOrigin* security_origin); static void webkit_web_database_set_name(WebKitWebDatabase* webDatabase, const gchar* name); static void webkit_web_database_finalize(GObject* object) { WebKitWebDatabase* webDatabase = WEBKIT_WEB_DATABASE(object); WebKitWebDatabasePrivate* priv = webDatabase->priv; g_free(priv->name); g_free(priv->displayName); g_free(priv->filename); G_OBJECT_CLASS(webkit_web_database_parent_class)->finalize(object); } static void webkit_web_database_dispose(GObject* object) { WebKitWebDatabase* webDatabase = WEBKIT_WEB_DATABASE(object); WebKitWebDatabasePrivate* priv = webDatabase->priv; if (priv->origin) { g_object_unref(priv->origin); priv->origin = NULL; } G_OBJECT_CLASS(webkit_web_database_parent_class)->dispose(object); } static void webkit_web_database_set_property(GObject* object, guint propId, const GValue* value, GParamSpec* pspec) { WebKitWebDatabase* webDatabase = WEBKIT_WEB_DATABASE(object); switch (propId) { case PROP_SECURITY_ORIGIN: webkit_web_database_set_security_origin(webDatabase, WEBKIT_SECURITY_ORIGIN(g_value_get_object(value))); break; case PROP_NAME: webkit_web_database_set_name(webDatabase, g_value_get_string(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, pspec); break; } } static void webkit_web_database_get_property(GObject* object, guint propId, GValue* value, GParamSpec* pspec) { WebKitWebDatabase* webDatabase = WEBKIT_WEB_DATABASE(object); WebKitWebDatabasePrivate* priv = webDatabase->priv; switch (propId) { case PROP_SECURITY_ORIGIN: g_value_set_object(value, priv->origin); break; case PROP_NAME: g_value_set_string(value, webkit_web_database_get_name(webDatabase)); break; case PROP_DISPLAY_NAME: g_value_set_string(value, webkit_web_database_get_display_name(webDatabase)); break; case PROP_EXPECTED_SIZE: g_value_set_uint64(value, webkit_web_database_get_expected_size(webDatabase)); break; case PROP_SIZE: g_value_set_uint64(value, webkit_web_database_get_size(webDatabase)); break; case PROP_PATH: g_value_set_string(value, webkit_web_database_get_filename(webDatabase)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, pspec); break; } } static void webkit_web_database_class_init(WebKitWebDatabaseClass* klass) { GObjectClass* gobjectClass = G_OBJECT_CLASS(klass); gobjectClass->dispose = webkit_web_database_dispose; gobjectClass->finalize = webkit_web_database_finalize; gobjectClass->set_property = webkit_web_database_set_property; gobjectClass->get_property = webkit_web_database_get_property; /** * WebKitWebDatabase:security-origin: * * The security origin of the database. * * Since: 1.1.14 */ g_object_class_install_property(gobjectClass, PROP_SECURITY_ORIGIN, g_param_spec_object("security-origin", _("Security Origin"), _("The security origin of the database"), WEBKIT_TYPE_SECURITY_ORIGIN, (GParamFlags) (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); /** * WebKitWebDatabase:name: * * The name of the Web Database database. * * Since: 1.1.14 */ g_object_class_install_property(gobjectClass, PROP_NAME, g_param_spec_string("name", _("Name"), _("The name of the Web Database database"), NULL, (GParamFlags) (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); /** * WebKitWebDatabase:display-name: * * The display name of the Web Database database. * * Since: 1.1.14 */ g_object_class_install_property(gobjectClass, PROP_DISPLAY_NAME, g_param_spec_string("display-name", _("Display Name"), _("The display name of the Web Storage database"), NULL, WEBKIT_PARAM_READABLE)); /** * WebKitWebDatabase:expected-size: * * The expected size of the database in bytes as defined by the web author. * * Since: 1.1.14 */ g_object_class_install_property(gobjectClass, PROP_EXPECTED_SIZE, g_param_spec_uint64("expected-size", _("Expected Size"), _("The expected size of the Web Database database"), 0, G_MAXUINT64, 0, WEBKIT_PARAM_READABLE)); /** * WebKitWebDatabase:size: * * The current size of the database in bytes. * * Since: 1.1.14 */ g_object_class_install_property(gobjectClass, PROP_SIZE, g_param_spec_uint64("size", _("Size"), _("The current size of the Web Database database"), 0, G_MAXUINT64, 0, WEBKIT_PARAM_READABLE)); /** * WebKitWebDatabase:filename: * * The absolute filename of the Web Database database. * * Since: 1.1.14 */ g_object_class_install_property(gobjectClass, PROP_PATH, g_param_spec_string("filename", _("Filename"), _("The absolute filename of the Web Storage database"), NULL, WEBKIT_PARAM_READABLE)); g_type_class_add_private(klass, sizeof(WebKitWebDatabasePrivate)); } static void webkit_web_database_init(WebKitWebDatabase* webDatabase) { webDatabase->priv = G_TYPE_INSTANCE_GET_PRIVATE(webDatabase, WEBKIT_TYPE_WEB_DATABASE, WebKitWebDatabasePrivate); } // Internal use only static void webkit_web_database_set_security_origin(WebKitWebDatabase *webDatabase, WebKitSecurityOrigin *securityOrigin) { g_return_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase)); g_return_if_fail(WEBKIT_IS_SECURITY_ORIGIN(securityOrigin)); WebKitWebDatabasePrivate* priv = webDatabase->priv; if (priv->origin) g_object_unref(priv->origin); g_object_ref(securityOrigin); priv->origin = securityOrigin; } static void webkit_web_database_set_name(WebKitWebDatabase* webDatabase, const gchar* name) { g_return_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase)); WebKitWebDatabasePrivate* priv = webDatabase->priv; g_free(priv->name); priv->name = g_strdup(name); } /** * webkit_web_database_get_security_origin: * @webDatabase: a #WebKitWebDatabase * * Returns the security origin of the #WebKitWebDatabase. * * Returns: (transfer none): the security origin of the database * * Since: 1.1.14 **/ WebKitSecurityOrigin* webkit_web_database_get_security_origin(WebKitWebDatabase* webDatabase) { g_return_val_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase), NULL); WebKitWebDatabasePrivate* priv = webDatabase->priv; return priv->origin; } /** * webkit_web_database_get_name: * @webDatabase: a #WebKitWebDatabase * * Returns the canonical name of the #WebKitWebDatabase. * * Returns: the name of the database * * Since: 1.1.14 **/ const gchar* webkit_web_database_get_name(WebKitWebDatabase* webDatabase) { g_return_val_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase), NULL); WebKitWebDatabasePrivate* priv = webDatabase->priv; return priv->name; } /** * webkit_web_database_get_display_name: * @webDatabase: a #WebKitWebDatabase * * Returns the name of the #WebKitWebDatabase as seen by the user. * * Returns: the name of the database as seen by the user. * * Since: 1.1.14 **/ const gchar* webkit_web_database_get_display_name(WebKitWebDatabase* webDatabase) { g_return_val_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase), NULL); #if ENABLE(SQL_DATABASE) WebKitWebDatabasePrivate* priv = webDatabase->priv; WebCore::DatabaseDetails details = WebCore::DatabaseTracker::tracker().detailsForNameAndOrigin(priv->name, core(priv->origin)); WTF::String displayName = details.displayName(); if (displayName.isEmpty()) return ""; g_free(priv->displayName); priv->displayName = g_strdup(displayName.utf8().data()); return priv->displayName; #else return ""; #endif } /** * webkit_web_database_get_expected_size: * @webDatabase: a #WebKitWebDatabase * * Returns the expected size of the #WebKitWebDatabase in bytes as defined by the * web author. The Web Database standard allows web authors to specify an expected * size of the database to optimize the user experience. * * Returns: the expected size of the database in bytes * * Since: 1.1.14 **/ guint64 webkit_web_database_get_expected_size(WebKitWebDatabase* webDatabase) { g_return_val_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase), 0); #if ENABLE(SQL_DATABASE) WebKitWebDatabasePrivate* priv = webDatabase->priv; WebCore::DatabaseDetails details = WebCore::DatabaseTracker::tracker().detailsForNameAndOrigin(priv->name, core(priv->origin)); return details.expectedUsage(); #else return 0; #endif } /** * webkit_web_database_get_size: * @webDatabase: a #WebKitWebDatabase * * Returns the actual size of the #WebKitWebDatabase space on disk in bytes. * * Returns: the actual size of the database in bytes * * Since: 1.1.14 **/ guint64 webkit_web_database_get_size(WebKitWebDatabase* webDatabase) { g_return_val_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase), 0); #if ENABLE(SQL_DATABASE) WebKitWebDatabasePrivate* priv = webDatabase->priv; WebCore::DatabaseDetails details = WebCore::DatabaseTracker::tracker().detailsForNameAndOrigin(priv->name, core(priv->origin)); return details.currentUsage(); #else return 0; #endif } /** * webkit_web_database_get_filename: * @webDatabase: a #WebKitWebDatabase * * Returns the absolute filename to the #WebKitWebDatabase file on disk. * * Returns: the absolute filename of the database * * Since: 1.1.14 **/ const gchar* webkit_web_database_get_filename(WebKitWebDatabase* webDatabase) { g_return_val_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase), NULL); #if ENABLE(SQL_DATABASE) WebKitWebDatabasePrivate* priv = webDatabase->priv; WTF::String coreName = WTF::String::fromUTF8(priv->name); WTF::String corePath = WebCore::DatabaseTracker::tracker().fullPathForDatabase(core(priv->origin), coreName); if (corePath.isEmpty()) return""; g_free(priv->filename); priv->filename = g_strdup(corePath.utf8().data()); return priv->filename; #else return ""; #endif } /** * webkit_web_database_remove: * @webDatabase: a #WebKitWebDatabase * * Removes the #WebKitWebDatabase from its security origin and destroys all data * stored in the database. * * Since: 1.1.14 **/ void webkit_web_database_remove(WebKitWebDatabase* webDatabase) { g_return_if_fail(WEBKIT_IS_WEB_DATABASE(webDatabase)); #if ENABLE(SQL_DATABASE) WebKitWebDatabasePrivate* priv = webDatabase->priv; WebCore::DatabaseTracker::tracker().deleteDatabase(core(priv->origin), priv->name); #endif } /** * webkit_remove_all_web_databases: * * Removes all web databases from the current database directory path. * * Since: 1.1.14 **/ void webkit_remove_all_web_databases() { #if ENABLE(SQL_DATABASE) WebCore::DatabaseTracker::tracker().deleteAllDatabases(); #endif } /** * webkit_get_web_database_directory_path: * * Returns the current path to the directory WebKit will write Web * Database databases. By default this path will be in the user data * directory. * * Returns: the current database directory path * * Since: 1.1.14 **/ const gchar* webkit_get_web_database_directory_path() { #if ENABLE(SQL_DATABASE) WTF::String path = WebCore::DatabaseTracker::tracker().databaseDirectoryPath(); if (path.isEmpty()) return ""; g_free(webkit_database_directory_path); webkit_database_directory_path = g_strdup(path.utf8().data()); return webkit_database_directory_path; #else return ""; #endif } /** * webkit_set_web_database_directory_path: * @path: the new database directory path * * Sets the current path to the directory WebKit will write Web * Database databases. * * Since: 1.1.14 **/ void webkit_set_web_database_directory_path(const gchar* path) { #if ENABLE(SQL_DATABASE) WTF::String corePath = WTF::String::fromUTF8(path); WebCore::DatabaseTracker::tracker().setDatabaseDirectoryPath(corePath); g_free(webkit_database_directory_path); webkit_database_directory_path = g_strdup(corePath.utf8().data()); #endif } /** * webkit_get_default_web_database_quota: * * Returns the default quota for Web Database databases. By default * this value is 5MB. * Returns: the current default database quota in bytes * * Since: 1.1.14 **/ guint64 webkit_get_default_web_database_quota() { return webkit_default_database_quota; } /** * webkit_set_default_web_database_quota: * @defaultQuota: the new default database quota * * Sets the current path to the directory WebKit will write Web * Database databases. * * Since: 1.1.14 **/ void webkit_set_default_web_database_quota(guint64 defaultQuota) { webkit_default_database_quota = defaultQuota; }
32.293785
131
0.673315
JavaScriptTesting
b9596c0b297c3d1ebcbe965b3f613534700bcdd2
1,061
cc
C++
cc/modules/tracking/Trackers/TrackerMedianFlow.cc
mstallmo/opencv4nodejs
5ab4fcb17c39c4a16f77c8de8c29dc357532d9cb
[ "MIT" ]
1
2018-05-07T13:03:20.000Z
2018-05-07T13:03:20.000Z
cc/modules/tracking/Trackers/TrackerMedianFlow.cc
goldyraj/facerecognition
9b0820135eb8cdaf783b3d560695bfb324083270
[ "MIT" ]
null
null
null
cc/modules/tracking/Trackers/TrackerMedianFlow.cc
goldyraj/facerecognition
9b0820135eb8cdaf783b3d560695bfb324083270
[ "MIT" ]
1
2020-02-18T06:44:04.000Z
2020-02-18T06:44:04.000Z
#ifdef HAVE_TRACKING #include "TrackerMedianFlow.h" Nan::Persistent<v8::FunctionTemplate> TrackerMedianFlow::constructor; NAN_MODULE_INIT(TrackerMedianFlow::Init) { v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(TrackerMedianFlow::New); v8::Local<v8::ObjectTemplate> instanceTemplate = ctor->InstanceTemplate(); Tracker::Init(ctor); constructor.Reset(ctor); ctor->SetClassName(FF_NEW_STRING("TrackerMedianFlow")); instanceTemplate->SetInternalFieldCount(1); target->Set(FF_NEW_STRING("TrackerMedianFlow"), ctor->GetFunction()); }; NAN_METHOD(TrackerMedianFlow::New) { FF_METHOD_CONTEXT("TrackerMedianFlow::New"); TrackerMedianFlow* self = new TrackerMedianFlow(); cv::TrackerMedianFlow::Params params; if (FF_HAS_ARG(0) && FF_IS_INT(info[0])) { params.pointsInGrid = info[0]->Int32Value(); } #if CV_VERSION_MINOR > 2 self->tracker = cv::TrackerMedianFlow::create(params); #else self->tracker = cv::TrackerMedianFlow::createTracker(params); #endif self->Wrap(info.Holder()); FF_RETURN(info.Holder()); }; #endif
27.205128
95
0.756833
mstallmo
b95c1f59d925472219d937d6ae88ddd65ea5a1d0
2,236
cpp
C++
server/src/http_msg_server/HttpConn.cpp
xiaominfc/TeamTalk
20084010a9804d1ff0ed7bb5924fde7041b952eb
[ "Apache-2.0" ]
65
2017-11-18T15:43:56.000Z
2022-01-30T08:07:11.000Z
server/src/http_msg_server/HttpConn.cpp
xiaominfc/TeamTalk
20084010a9804d1ff0ed7bb5924fde7041b952eb
[ "Apache-2.0" ]
3
2018-09-04T14:27:45.000Z
2020-10-29T07:22:45.000Z
server/src/http_msg_server/HttpConn.cpp
xiaominfc/TeamTalk
20084010a9804d1ff0ed7bb5924fde7041b952eb
[ "Apache-2.0" ]
36
2018-07-10T04:21:08.000Z
2021-11-09T07:21:10.000Z
/* * HttpConn.cpp * * Created on: 2013-9-29 * Author: ziteng@mogujie.com */ #include "HttpConn.h" #include "HttpParserWrapper.h" #include "HttpQuery.h" static HttpConnMap_t g_http_conn_map; // conn_handle 从0开始递增,可以防止因socket handle重用引起的一些冲突 static uint32_t g_conn_handle_generator = 0; CHttpConn* FindHttpConnByHandle(uint32_t conn_handle) { CHttpConn* pConn = NULL; HttpConnMap_t::iterator it = g_http_conn_map.find(conn_handle); if (it != g_http_conn_map.end()) { pConn = it->second; } return pConn; } void http_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { (void)callback_data; (void)msg; (void)handle; (void)pParam; CHttpConn* pConn = NULL; HttpConnMap_t::iterator it, it_old; uint64_t cur_time = get_tick_count(); for (it = g_http_conn_map.begin(); it != g_http_conn_map.end(); ) { it_old = it; it++; pConn = it_old->second; pConn->OnTimer(cur_time); } } void init_http_conn() { netlib_register_timer(http_conn_timer_callback, NULL, 1000); } ////////////////////////// CHttpConn::CHttpConn() { m_state = CONN_STATE_IDLE; m_conn_handle = ++g_conn_handle_generator; if (m_conn_handle == 0) { m_conn_handle = ++g_conn_handle_generator; } } CHttpConn::~CHttpConn() { //log("~CHttpConn, handle=%u ", m_conn_handle); } void CHttpConn::Close() { CImConn::Close(); if (m_state != CONN_STATE_CLOSED) { m_state = CONN_STATE_CLOSED; g_http_conn_map.erase(m_conn_handle); ReleaseRef(); } } void CHttpConn::OnConnect(CBaseSocket* socket) { CImConn::OnConnect(socket); m_state = CONN_STATE_CONNECTED; g_http_conn_map.insert(make_pair(m_conn_handle, this)); } void CHttpConn::HandleData(){ printf("HandeData\n"); HandleWork(); } void CHttpConn::HandleWork(){ // 每次请求对应一个HTTP连接,所以读完数据后,不用在同一个连接里面准备读取下个请求 char* in_buf = (char*)m_in_buf.GetBuffer(); uint32_t buf_len = m_in_buf.GetWriteOffset(); in_buf[buf_len] = '\0'; log("OnRead, buf_len=%u, conn_handle=%u\n", buf_len, m_conn_handle); // for debug } void CHttpConn::OnTimer(uint64_t curr_tick) { if (curr_tick > m_last_recv_tick + HTTP_CONN_TIMEOUT) { log("HttpConn timeout, handle=%d ", m_conn_handle); Close(); } } void CHttpConn::OnWriteCompelete() { Close(); }
19.443478
94
0.713327
xiaominfc
b95c223b7d35bd403d256be906466f45a295a0be
3,422
cpp
C++
TheGame/AIPlayer.cpp
dynamiquel/The-Game
d9ae1499ea514260e4d47dac85893aea8891a2cf
[ "MIT" ]
null
null
null
TheGame/AIPlayer.cpp
dynamiquel/The-Game
d9ae1499ea514260e4d47dac85893aea8891a2cf
[ "MIT" ]
null
null
null
TheGame/AIPlayer.cpp
dynamiquel/The-Game
d9ae1499ea514260e4d47dac85893aea8891a2cf
[ "MIT" ]
null
null
null
#include "AIPlayer.h" #include "Utilities.h" #include <iostream> short selectedPile = -1; AIPlayer::AIPlayer() { isAI = true; completed = false; } // Asks the user to choose a card and returns its index. short& AIPlayer::ChooseCard(const PlayPile* playPiles) { std::cout << "\n\n Choose the card you want to play (the number in the brackets) or enter \"0\" to end your turn: "; // The max difference the player's card and the play pile's card can have in order to play the card. // Start at 1 = highest chance of choosing best card. short maxDifference = 1; // Chooses a random card to start at. short startCardIndex = rand() % GetHandSize(); short lowestDifference = SHRT_MAX; short lowestDifferencePileIndex = -1; while (true) { short currentCardIndex = startCardIndex; while (true) { // For every play pile... for (short i = 0; i < 4; i++) { // Calculates the difference between the current card and the top card of the current play pile. short currentDifference = std::abs(hand[currentCardIndex] - playPiles[i].topCard); // Debugging /* printf("\nCurrent card: %d", hand[currentCardIndex]); printf("\nCurrent card index: %d", currentCardIndex); printf("\nTop card: %d", playPiles[i].topCard); printf("\nCurrent difference: %d", currentDifference); printf("\nLowest difference: %d", lowestDifference); printf("\nMax difference: %d\n", maxDifference); */ // If the difference between the current card and play pile is <= the max difference, // check if the difference is the lowest one yet and can be played. // If so, update the lowest values to the current values. if (currentDifference <= maxDifference) if (currentDifference < lowestDifference && playPiles[i].CanDeposit(hand[currentCardIndex])) { lowestDifference = currentDifference; lowestDifferencePileIndex = i; } } // If the lowest difference is less than the max difference threshold, play the current card and store the // play pile index for later. if (lowestDifference <= maxDifference) { selectedPile = lowestDifferencePileIndex; return currentCardIndex; } // The current card can't be played in any play piles with the max difference threshold, // so choose the next card. if (currentCardIndex++ >= GetHandSize() - 1) currentCardIndex = 0; // If we have looped back to start card, break the loop so we can increase the difference and try again. if (currentCardIndex == startCardIndex) break; } // Since no cards can be played with the given range, increase the max difference and check again. // 1 = will always choose the lowest card possible. Increase to make the AI 'dumber' and rely more on luck, and increase performance. maxDifference += 1; // Breaks the loop if for some reason the AI can't play their cards. // This should never happen as the CanPlay() method should give the AI a defeat before their turn. if (maxDifference > 98) break; } // Return -1 to end the turn. short endTurn = -1; return endTurn; } // Asks the user to choose a play pile and returns its index. short& AIPlayer::ChoosePile() { std::cout << "\n\n Choose the play pile you want to put your card in (the number in the brackets) or enter \"0\" to end your turn: "; // Returns the pile index that was calculated when the AI chose their card. return selectedPile; }
33.881188
135
0.696084
dynamiquel
b95d6f064af5c8480c038d9d11495ca23744a531
880
hpp
C++
leviathan_config.hpp
bkovacev/levd
f942946f4db7f8c2bad14c5c7025ac303855ced7
[ "MIT" ]
1
2020-04-23T11:28:55.000Z
2020-04-23T11:28:55.000Z
leviathan_config.hpp
bkovacev/levd
f942946f4db7f8c2bad14c5c7025ac303855ced7
[ "MIT" ]
null
null
null
leviathan_config.hpp
bkovacev/levd
f942946f4db7f8c2bad14c5c7025ac303855ced7
[ "MIT" ]
1
2020-04-23T11:28:59.000Z
2020-04-23T11:28:59.000Z
#ifndef LEVIATHAN_CONFIG_H #define LEVIATHAN_CONFIG_H #include <functional> #include <map> #include <string> #define DEFAULT_RED 0xFF0000 using LineFunction = std::function<int32_t(int32_t)>; enum class TempSource { CPU, LIQUID }; inline TempSource stringToTempSource(const std::string &tss) { return tss == "liquid" ? TempSource::LIQUID : TempSource::CPU; } struct Point { int32_t x; int32_t y; Point(int32_t __x, int32_t __y) : x(__x), y(__y) {} }; struct leviathan_config { // Fan/pump profile TempSource temp_source_{TempSource::CPU}; std::map<int32_t, LineFunction> fan_profile_; std::map<int32_t, LineFunction> pump_profile_; // Color settings uint32_t main_color_{DEFAULT_RED}; // Interval settings uint32_t interval_{500}; }; leviathan_config parse_config_file(const char *const path); #endif // LEVIATHAN_CONFIG_H
22
64
0.723864
bkovacev
b95e4da83dbb91e93edd8e4aac66d3e4a766fba1
2,281
hpp
C++
cpp/subprojects/common/include/common/rule_refinement/rule_refinement_exact.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
8
2020-06-30T01:06:43.000Z
2022-03-14T01:58:29.000Z
cpp/subprojects/common/include/common/rule_refinement/rule_refinement_exact.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
3
2020-12-14T11:30:18.000Z
2022-02-07T06:31:51.000Z
cpp/subprojects/common/include/common/rule_refinement/rule_refinement_exact.hpp
Waguy02/Boomer-Scripted
b06bb9213d64dca0c05d41701dea12666931618c
[ "MIT" ]
4
2020-06-24T08:45:00.000Z
2021-12-23T21:44:51.000Z
/* * @author Michael Rapp (michael.rapp.ml@gmail.com) */ #pragma once #include "common/rule_refinement/rule_refinement.hpp" #include "common/rule_refinement/rule_refinement_callback.hpp" #include "common/input/feature_vector.hpp" #include "common/sampling/weight_vector.hpp" /** * Allows to find the best refinements of existing rules, which result from adding a new condition that correspond to a * certain feature. The thresholds that may be used by the new condition result from the feature values of all training * examples for the respective feature. * * @tparam T The type of the vector that provides access to the indices of the labels for which the refined rule is * allowed to predict */ template<typename T> class ExactRuleRefinement final : public IRuleRefinement { private: const T& labelIndices_; uint32 numExamples_; uint32 featureIndex_; bool nominal_; std::unique_ptr<IRuleRefinementCallback<FeatureVector, IWeightVector>> callbackPtr_; std::unique_ptr<Refinement> refinementPtr_; public: /** * @param labelIndices A reference to an object of template type `T` that provides access to the indices of * the labels for which the refined rule is allowed to predict * @param numExamples The total number of training examples with non-zero weights that are covered by the * existing rule * @param featureIndex The index of the feature, the new condition corresponds to * @param nominal True, if the feature at index `featureIndex` is nominal, false otherwise * @param callbackPtr An unique pointer to an object of type `IRuleRefinementCallback` that allows to * retrieve a feature vector for the given feature */ ExactRuleRefinement(const T& labelIndices, uint32 numExamples, uint32 featureIndex, bool nominal, std::unique_ptr<IRuleRefinementCallback<FeatureVector, IWeightVector>> callbackPtr); void findRefinement(const AbstractEvaluatedPrediction* currentHead) override; std::unique_ptr<Refinement> pollRefinement() override; };
40.017544
120
0.686541
Waguy02
b95ed381f546426e1726acfcabe8798b45b4d3a3
18,884
cpp
C++
Creature.cpp
liderrick/Text-Based-Fighting-Simulation-Game--Fantasy-Combat-Vol.-II--Tournament
48ea8b7744b9228d9a301488ac45e12534847096
[ "MIT" ]
null
null
null
Creature.cpp
liderrick/Text-Based-Fighting-Simulation-Game--Fantasy-Combat-Vol.-II--Tournament
48ea8b7744b9228d9a301488ac45e12534847096
[ "MIT" ]
null
null
null
Creature.cpp
liderrick/Text-Based-Fighting-Simulation-Game--Fantasy-Combat-Vol.-II--Tournament
48ea8b7744b9228d9a301488ac45e12534847096
[ "MIT" ]
null
null
null
/************************************************************************************************************** ** Program name: Project 4 ** Author: Derrick Li ** Date: Mar. 5, 2017 ** Description: ** This class implementation file contains the member function definitions for the Creature base class and its ** 5 derived classes--Vampire class, Barbarian class, BlueMen class, Medusa class, and HarryPotter class. ***************************************************************************************************************/ #include "Creature.hpp" #include <iostream> using std::endl; using std::cout; using std::cin; /*************************************************************************************************************** ** Description: The Creature base class constructor initializes its pointer members to nullptr, its int ** members to zero, its type to ' ', and its name to an empty string. ***************************************************************************************************************/ Creature::Creature() { attackDie = nullptr; defenseDie = nullptr; numOfAttackDie = 0; numOfDefenseDie = 0; armor = 0; strength = 0; creatureType = ' '; creatureName = ""; } /*************************************************************************************************************** ** Description: The Creature base class destructor frees the Die objects held by attackDie and defenseDie ** upon exiting of the program. ***************************************************************************************************************/ Creature::~Creature() { delete attackDie; attackDie = nullptr; delete defenseDie; defenseDie = nullptr; } /*************************************************************************************************************** ** Description: getStrength() function returns the strength data member as a int. It does not take in any argument. ***************************************************************************************************************/ int Creature::getStrength() { return strength; } /*************************************************************************************************************** ** Description: setStrength() function takes in an int and assigns it to the strength data member. It does not ** have a return type. ***************************************************************************************************************/ void Creature::setStrength(int inputStrength) { strength = inputStrength; } /*************************************************************************************************************** ** Description: getArmor() function returns the armor data member as a int. It does not take in any argument. ***************************************************************************************************************/ int Creature::getArmor() { return armor; } /*************************************************************************************************************** ** Description: getCreatureType() function returns the creature type as a char. It does not take any argument. ***************************************************************************************************************/ char Creature::getCreatureType() { return creatureType; } /*************************************************************************************************************** ** Description: getCreatureName() function returns the creature name as a string. It does not take any argument. ***************************************************************************************************************/ string Creature::getCreatureName() { return creatureName; } /*************************************************************************************************************** ** Description: setCreatureName() function takes a single string argument and sets the creatureName data ** member. The function does not have a return type. ***************************************************************************************************************/ void Creature::setCreatureName(string inputName) { creatureName = inputName; } /*************************************************************************************************************** ** Description: getNumOfSidesOnAttackDie() function returns the number of sides on the attack die as a int. ** It does not take in any argument. ***************************************************************************************************************/ int Creature::getNumOfSidesOnAttackDie() { return attackDie->getSides(); } /*************************************************************************************************************** ** Description: getNumOfAttackDie() function returns the numOfAttackDie data member as a int. It does not take in any argument. ***************************************************************************************************************/ int Creature::getNumOfAttackDie() { return numOfAttackDie; } /*************************************************************************************************************** ** Description: getNumOfSidesOnDefenseDie() function returns the number of sides on the defense die as a int. ** It does not take in any argument. ***************************************************************************************************************/ int Creature::getNumOfSidesOnDefenseDie() { return defenseDie->getSides(); } /*************************************************************************************************************** ** Description: getNumOfDefenseDie() function returns the numOfDefenseDie data member as a int. It does not take in any argument. ***************************************************************************************************************/ int Creature::getNumOfDefenseDie() { return numOfDefenseDie; } /*************************************************************************************************************** ** Description: attack() function rolls the attackDie by the number of times indicated by numOfAttackDie. ** The values of the rolls are summed up and returned from the function as an integer. It does not take in any argument. ***************************************************************************************************************/ int Creature::attack() { int attackDamage = 0; for (int i = 0; i < numOfAttackDie; i++) { int tempAttack = attackDie->rollDie(); //cout << " Die " << i + 1 << ": " << tempAttack << " damage points rolled."<< endl; attackDamage += tempAttack; } return attackDamage; } /*************************************************************************************************************** ** Description: defend() function rolls the defenseDie by the number of times indicated by numOfDefenseDie. ** The values of the rolls are summed up along with the armor value. This total represents creature's defense points. ** The function takes an integer argument representing the damage the creature is being dealt. It takes the damage ** value and substract from it the defense points. If the results are positive, then that is the amount to subtract ** from the creature's strength. If the results are negative, then the defense points are higher than the damage ** being dealt, thus strength is unaffected. The function does not have a return type. ***************************************************************************************************************/ void Creature::defend(int damage) { int defensePoints = armor; for (int i = 0; i < numOfDefenseDie; i++) { int tempDef = defenseDie->rollDie(); defensePoints += tempDef; //cout << " Die " << i + 1 << ": " << tempDef << " defense points rolled." << endl; } //cout << " With armor, the defending player has " << defensePoints << " total defense points." << endl; if (defensePoints < damage) { strength -= (damage - defensePoints); } } /*************************************************************************************************************** ** Description: recoverStrength() function regenerates a certain percentage of the damage inflicted on the creature. ** The creature will be regenerated a certain percent in consideration to its max strength. The default is 60%. ** This recovery value can be changed in the function. The function does not take an argument and ** does not have a return type. The function works for Vampire, Barbarian, BlueMen, and Medusa derived classes. ** HarryPotter has its own recoverStrength() function that overrides this. ***************************************************************************************************************/ void Creature::recoverStrength() { const double RECOVERY_PERCENT = 0.6; //Default: 60% strength recovery from total damage inflicted const int VAMPIRE_MAX_STRENGTH = 18; const int BARBARIAN_MAX_STRENGTH = 12; const int BLUEMEN_MAX_STRENGTH = 12; const int MEDUSA_MAX_STRENGTH = 8; int creatureStrength = 0; switch (creatureType) { case 'v': creatureStrength = VAMPIRE_MAX_STRENGTH; break; case 'b': creatureStrength = BARBARIAN_MAX_STRENGTH; break; case 'x': creatureStrength = BLUEMEN_MAX_STRENGTH; break; case 'm': creatureStrength = MEDUSA_MAX_STRENGTH; break; } setStrength(getStrength() + (RECOVERY_PERCENT)*(creatureStrength - getStrength())); } /*************************************************************************************************************** ** Description: The Vampire derived class constructor. ** Specifications: ** Attack: 1 Die - 12 sides ** Defense: 1 Die - 6 sides ** Armor: 1 ** Strength: 18 ** Special ability: Charm ** When attacked, there is a 50% chance that the Vampire object doesn't receive any damage. ***************************************************************************************************************/ Vampire::Vampire(string inputName) { attackDie = new Die(12); defenseDie = new Die(6); numOfAttackDie = 1; numOfDefenseDie = 1; armor = 1; strength = 18; creatureType = 'v'; creatureName = inputName; } /*************************************************************************************************************** ** Description: defend() function in Vampire derived class overrides the defend() function in the Base class. ** This version takes into account the Vampire's special ability, Charm. ***************************************************************************************************************/ void Vampire::defend(int damage) { bool charm = rand() % 2; //50% chance for charm if (charm) { //cout << " Vampire successfully used Charm. No damage received!" << endl; } else { int defensePoints = armor; for (int i = 0; i < numOfDefenseDie; i++) { int tempDef = defenseDie->rollDie(); defensePoints += tempDef; //cout << " Die " << i + 1 << ": " << tempDef << " defense points rolled." << endl; } //cout << " With armor, the defending player has " << defensePoints << " total defense points." << endl; if (defensePoints < damage) { strength -= (damage - defensePoints); } } } /*************************************************************************************************************** ** Description: The Barbarian derived class constructor. ** Specifications: ** Attack: 2 Die - 6 sides ** Defense: 2 Die - 6 sides ** Armor: 0 ** Strength: 12 ** Special ability: none. ***************************************************************************************************************/ Barbarian::Barbarian(string inputName) { attackDie = new Die(6); defenseDie = new Die(6); numOfAttackDie = 2; numOfDefenseDie = 2; armor = 0; strength = 12; creatureType = 'b'; creatureName = inputName; } /*************************************************************************************************************** ** Description: The BlueMen derived class constructor. ** Specifications: ** Attack: 2 Die - 10 sides ** Defense: 3 Die - 6 sides ** Armor: 3 ** Strength: 12 ** Special ability: Mob ** The defense starts off with 3 Dies. When strength drops to 8, the defense will only have 2 Dies. ** And when strength drops to 4, the defense will only have 1 Die. ***************************************************************************************************************/ BlueMen::BlueMen(string inputName) { attackDie = new Die(10); defenseDie = new Die(6); numOfAttackDie = 2; numOfDefenseDie = 3; armor = 3; strength = 12; creatureType = 'x'; creatureName = inputName; } /*************************************************************************************************************** ** Description: defend() function in BlueMen derived class overrides the defend() function in the Base class. ** This version takes into account the BlueMen's special ability, Mob. ***************************************************************************************************************/ void BlueMen::defend(int damage) { //Code for Mob ability --- Moved from end of block to front to account for any recovered strength from recover function if (strength > 8) { numOfDefenseDie = 3; //cout << " Blue Men's Mob Defense level is High (Lvl 3)." << endl; } else if (strength > 4) { numOfDefenseDie = 2; //cout << " Blue Men's Mob Defense level is Mid (Lvl 2)." << endl; } else if (strength > 0) { numOfDefenseDie = 1; //cout << " Blue Men's Mob Defense level is Low (Lvl 1)." << endl; } int defensePoints = armor; for (int i = 0; i < numOfDefenseDie; i++) { int tempDef = defenseDie->rollDie(); defensePoints += tempDef; //cout << " Die " << i + 1 << ": " << tempDef << " defense points rolled." << endl; } //cout << " With armor, the defending player has " << defensePoints << " total defense points." << endl; if (defensePoints < damage) { strength -= (damage - defensePoints); } } /*************************************************************************************************************** ** Description: The Medusa derived class constructor. ** Specifications: ** Attack: 2 Die - 6 sides ** Defense: 1 Die - 6 sides ** Armor: 3 ** Strength: 8 ** Special ability: Glare ** When attaking, if it rolls an attack value of 12. Then the opponent immediately turns to stone and lose ** a life. ***************************************************************************************************************/ Medusa::Medusa(string inputName) { attackDie = new Die(6); defenseDie = new Die(6); numOfAttackDie = 2; numOfDefenseDie = 1; armor = 3; strength = 8; creatureType = 'm'; creatureName = inputName; } /*************************************************************************************************************** ** Description: attack() function in Medusa derived class overrides the attack() function in the Base class. ** This version takes into account Medusa's special ability, Glare. ***************************************************************************************************************/ int Medusa::attack() { int attackDamage = 0; for (int i = 0; i < numOfAttackDie; i++) { int tempAttack = attackDie->rollDie(); //cout << " Die " << i + 1 << ": " << tempAttack << " damage points rolled." << endl; attackDamage += tempAttack; } if (attackDamage == 12) { attackDamage = 9999; //cout << " Medusa successfully used Glare. Opponent is turned to stone!" << endl; } return attackDamage; } /*************************************************************************************************************** ** Description: The HarryPotter derived class constructor. ** Specifications: ** Attack: 2 Die - 6 sides ** Defense: 2 Die - 6 sides ** Armor: 0 ** Strength: 10 ** Special ability: Hogwarts ** Has an extra life. Once strength decreases to zero or below, the character is automatically revived and strength is ** set to 20. This special ability is only able to be used one time. ***************************************************************************************************************/ HarryPotter::HarryPotter(string inputName) { attackDie = new Die(6); defenseDie = new Die(6); numOfAttackDie = 2; numOfDefenseDie = 2; armor = 0; strength = 10; creatureType = 'h'; creatureName = inputName; numOfExtraLives = 1; } /*************************************************************************************************************** ** Description: defend() function in HarryPotter derived class overrides the defend() function in the Base class. ** This version takes into account Harry Potter's special ability, Hogwarts. ***************************************************************************************************************/ void HarryPotter::defend(int damage) { int defensePoints = armor; for (int i = 0; i < numOfDefenseDie; i++) { int tempDef = defenseDie->rollDie(); defensePoints += tempDef; //cout << " Die " << i + 1 << ": " << tempDef << " defense points rolled." << endl; } //cout << " With armor, the defending player has " << defensePoints << " total defense points." << endl; if (defensePoints < damage) { strength -= (damage - defensePoints); } //Code for Hogwarts ability if (strength <= 0 && numOfExtraLives > 0) { //cout << " Harry Potter was knocked down. But he used Hogwarts and is revived with 20 strength points!." << endl; numOfExtraLives--; strength = 20; } } /*************************************************************************************************************** ** Description: recoverStrength() function in HarryPotter derived class overrides the defend() function in the Base class. ** This version takes into account Harry Potter's special ability, Hogwarts. Depending on whether it has used its ** special ability, its max strength is either 10 or 20 points. A certain percentage of the total damage inflicted on ** the creature will be regenerated in consideration to its max strength. The default is 60%. ** This recovery value can be changed in the function. The function does not take an argument and ** does not have a return type. ***************************************************************************************************************/ void HarryPotter::recoverStrength() { const double RECOVERY_PERCENT = 0.6; //Default: 60 % strength recovery from total damage inflicted const int HARRYPOTTER_MAX_STRENGTH_BEFORE_LIFE = 10; const int HARRYPOTTER_MAX_STRENGTH_AFTER_LIFE = 20; int creatureStrength = 0; switch (numOfExtraLives) { case 1: creatureStrength = HARRYPOTTER_MAX_STRENGTH_BEFORE_LIFE; break; case 0: creatureStrength = HARRYPOTTER_MAX_STRENGTH_AFTER_LIFE; break; } setStrength(getStrength() + (RECOVERY_PERCENT)*(creatureStrength - getStrength())); }
39.178423
129
0.487503
liderrick
b960346296df837f5bb142b511be996fe5036985
962
cpp
C++
source/LeetCode/DynamicPlaning/MaxSumofSubarray.cpp
Mas9uerade/Mas9uerade.github.io
9cc273313fc1360daff57fe16dd1a60fe910259d
[ "Apache-2.0" ]
1
2018-04-14T03:43:27.000Z
2018-04-14T03:43:27.000Z
source/LeetCode/DynamicPlaning/MaxSumofSubarray.cpp
Mas9uerade/Mas9uerade.github.io
9cc273313fc1360daff57fe16dd1a60fe910259d
[ "Apache-2.0" ]
null
null
null
source/LeetCode/DynamicPlaning/MaxSumofSubarray.cpp
Mas9uerade/Mas9uerade.github.io
9cc273313fc1360daff57fe16dd1a60fe910259d
[ "Apache-2.0" ]
null
null
null
int maxsumofSubarray(vector<int>& arr) { if (arr.size() == 0) { return 0; } if (arr.size() == 1) { return arr[0]; } int max = arr[0]; int end_index = 0; int relink_cost = 0; for (int i = 1; i < arr.size(); ++i) { //判断是否可以续链 if (end_index == i - 1) { //判断取 arr[i] 与 max + arr[i] 与 max 的最大值,若取max 则不续链 if (max > arr[i] && max > max + arr[i]) { max = max; //此时已经断链了,需要增加relink_cost relink_cost += arr[i]; } else { end_index = i; //如果单取一个元素大于之前的累加,则单取元素 if (arr[i] >= max + arr[i]) { max = arr[i]; } else { max = arr[i] + max; } } } //若不可续链,则判断arr[i] 与 max 的最大值 else { if (arr[i] >= max) { max = arr[i]; end_index = i; relink_cost = 0; } else { relink_cost += arr[i]; //接链收益大,则接链 if (relink_cost + max >= max) { max = relink_cost + max; end_index = i; relink_cost = 0; } } } } return max; }
15.03125
52
0.480249
Mas9uerade
b9603f8367fb1e9d27716621ead4a9dc57a27c33
3,382
cpp
C++
test/entities/vbkblock_test.cpp
Warchant/alt-integration-cpp
61c1012dd4f4632c1bd288d5bfcb0500a2e4933c
[ "MIT" ]
null
null
null
test/entities/vbkblock_test.cpp
Warchant/alt-integration-cpp
61c1012dd4f4632c1bd288d5bfcb0500a2e4933c
[ "MIT" ]
2
2020-08-19T11:52:46.000Z
2020-08-19T12:34:42.000Z
test/entities/vbkblock_test.cpp
Warchant/alt-integration-cpp
61c1012dd4f4632c1bd288d5bfcb0500a2e4933c
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 Xenios SEZC // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #include "veriblock/entities/vbkblock.hpp" #include <gtest/gtest.h> #include "veriblock/arith_uint256.hpp" #include "veriblock/literals.hpp" using namespace altintegration; static const VbkBlock defaultBlock{5000, 2, "449c60619294546ad825af03"_unhex, "b0935637860679ddd5"_unhex, "5ee4fd21082e18686e"_unhex, "26bbfda7d5e4462ef24ae02d67e47d78"_unhex, 1553699059, 16842752, 1}; static const std::string defaultBlockEncoded = "40000013880002449c60619294546ad825af03b0935637860679ddd55ee4fd21082e18686e" "26bbfda7d5e4462ef24ae02d67e47d785c9b90f30101000000000001"; TEST(VbkBlock, Deserialize) { const auto vbkblock = ParseHex(defaultBlockEncoded); auto stream = ReadStream(vbkblock); auto block = VbkBlock::fromVbkEncoding(stream); EXPECT_EQ(block.height, defaultBlock.height); EXPECT_EQ(block.version, defaultBlock.version); EXPECT_EQ(block.previousBlock.toHex(), defaultBlock.previousBlock.toHex()); EXPECT_EQ(block.previousKeystone.toHex(), defaultBlock.previousKeystone.toHex()); EXPECT_EQ(block.secondPreviousKeystone.toHex(), defaultBlock.secondPreviousKeystone.toHex()); EXPECT_EQ(block.merkleRoot.toHex(), defaultBlock.merkleRoot.toHex()); EXPECT_EQ(block.getBlockTime(), defaultBlock.getBlockTime()); EXPECT_EQ(block.getDifficulty(), defaultBlock.getDifficulty()); EXPECT_EQ(block.nonce, defaultBlock.nonce); } TEST(VbkBlock, Serialize) { WriteStream stream; defaultBlock.toVbkEncoding(stream); auto vbkBytes = stream.data(); auto blockEncoded = HexStr(vbkBytes); EXPECT_EQ(blockEncoded, defaultBlockEncoded); } TEST(VbkBlock, RoundTrip) { auto blockDecoded = ParseHex(defaultBlockEncoded); auto stream = ReadStream(blockDecoded); auto decoded = VbkBlock::fromVbkEncoding(stream); EXPECT_EQ(decoded.version, defaultBlock.version); WriteStream outputStream; decoded.toVbkEncoding(outputStream); auto vbkBytes = outputStream.data(); auto blockReEncoded = HexStr(vbkBytes); EXPECT_EQ(blockReEncoded, defaultBlockEncoded); } TEST(VbkBlock, getBlockHash_test) { VbkBlock block; block.height = 5000; block.version = 2; block.previousBlock = uint96("94E7DC3E3BE21A96ECCF0FBD"_unhex); block.previousKeystone = uint72("F5F62A3331DC995C36"_unhex); block.secondPreviousKeystone = uint72("B0935637860679DDD5"_unhex); block.merkleRoot = uint128("DB0F135312B2C27867C9A83EF1B99B98"_unhex); block.timestamp = 1553699987; block.difficulty = 117586646; block.nonce = 1924857207; EXPECT_EQ( ArithUint256::fromLEBytes(block.getHash()), ArithUint256::fromHex( "0000000000000000000000000000480D8196D5B0B41861D032377F5165BB4452")); } TEST(VbkBlock, getId_test) { auto atvBytes = ParseHex(defaultBlockEncoded); auto stream = ReadStream(atvBytes); auto vbkblock = VbkBlock::fromVbkEncoding(stream); EXPECT_EQ(vbkblock.getId().toHex(), "08e2aae9a5e19569b1a68624"); }
36.365591
80
0.71437
Warchant
b964bde2b0c0f2b8af2150a123a317efdcadb4ed
3,227
cc
C++
src/xenia/base/filesystem.cc
cloudhaacker/xenia
54b211ed1885cdfb9ef6d74e60f7e615aaf56d45
[ "BSD-3-Clause" ]
16
2018-06-23T19:49:55.000Z
2021-12-29T01:29:28.000Z
src/xenia/base/filesystem.cc
cloudhaacker/xenia
54b211ed1885cdfb9ef6d74e60f7e615aaf56d45
[ "BSD-3-Clause" ]
1
2017-10-01T08:53:46.000Z
2017-11-11T01:47:23.000Z
src/xenia/base/filesystem.cc
cloudhaacker/xenia
54b211ed1885cdfb9ef6d74e60f7e615aaf56d45
[ "BSD-3-Clause" ]
15
2018-07-12T22:36:01.000Z
2020-10-25T15:51:08.000Z
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/filesystem.h" #include <algorithm> namespace xe { namespace filesystem { std::string CanonicalizePath(const std::string& original_path) { char path_sep(xe::kPathSeparator); std::string path(xe::fix_path_separators(original_path, path_sep)); std::vector<std::string::size_type> path_breaks; std::string::size_type pos(path.find_first_of(path_sep)); std::string::size_type pos_n(std::string::npos); while (pos != std::string::npos) { if ((pos_n = path.find_first_of(path_sep, pos + 1)) == std::string::npos) { pos_n = path.size(); } auto diff(pos_n - pos); switch (diff) { case 0: pos_n = std::string::npos; break; case 1: // Duplicate separators. path.erase(pos, 1); pos_n -= 1; break; case 2: // Potential marker for current directory. if (path[pos + 1] == '.') { path.erase(pos, 2); pos_n -= 2; } else { path_breaks.push_back(pos); } break; case 3: // Potential marker for parent directory. if (path[pos + 1] == '.' && path[pos + 2] == '.') { if (path_breaks.empty()) { // Ensure we don't override the device name. std::string::size_type loc(path.find_first_of(':')); auto req(pos + 3); if (loc == std::string::npos || loc > req) { path.erase(0, req); pos_n -= req; } else { path.erase(loc + 1, req - (loc + 1)); pos_n -= req - (loc + 1); } } else { auto last(path_breaks.back()); auto last_diff((pos + 3) - last); path.erase(last, last_diff); pos_n = last; // Also remove path reference. path_breaks.erase(path_breaks.end() - 1); } } else { path_breaks.push_back(pos); } break; default: path_breaks.push_back(pos); break; } pos = pos_n; } // Remove trailing seperator. if (!path.empty() && path.back() == path_sep) { path.erase(path.size() - 1); } // Final sanity check for dead paths. if ((path.size() == 1 && (path[0] == '.' || path[0] == path_sep)) || (path.size() == 2 && path[0] == '.' && path[1] == '.')) { return ""; } return path; } bool CreateParentFolder(const std::wstring& path) { auto fixed_path = xe::fix_path_separators(path, xe::kWPathSeparator); auto base_path = xe::find_base_path(fixed_path, xe::kWPathSeparator); if (!PathExists(base_path)) { return CreateFolder(base_path); } else { return true; } } } // namespace filesystem } // namespace xe
29.072072
79
0.494267
cloudhaacker
b96ae03b0c0f89cc38d87ca59a7f9310533ba2d9
1,426
hpp
C++
dxlibex/type_traits/is_well_format.hpp
Nagarei/DxLibEx
650fd0dad2cd1625d04f009faa649e8e9ffa0e1b
[ "BSL-1.0" ]
32
2015-10-19T15:51:15.000Z
2021-08-06T05:51:28.000Z
dxlibex/type_traits/is_well_format.hpp
Nagarei/DxLibEx
650fd0dad2cd1625d04f009faa649e8e9ffa0e1b
[ "BSL-1.0" ]
92
2015-10-17T12:20:53.000Z
2020-08-12T13:34:21.000Z
dxlibex/type_traits/is_well_format.hpp
Nagarei/DxLibEx
650fd0dad2cd1625d04f009faa649e8e9ffa0e1b
[ "BSL-1.0" ]
6
2016-05-09T03:23:18.000Z
2020-04-08T05:57:43.000Z
/*============================================================================= Copyright (C) 2015-2017 DxLibEx project https://github.com/Nagarei/DxLibEx/ Distributed under the Boost Software License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef DXLE_INC_TYPE_TRAITS_IS_WELL_FORMAT_HPP_ #define DXLE_INC_TYPE_TRAITS_IS_WELL_FORMAT_HPP_ #include <type_traits> #include "enable_if.hpp" namespace dxle { //!inline namespace type_traits { template<typename T, typename = nullptr_t> struct has_operator_notequal_to_zero_impl : std::false_type {}; template<typename T> struct has_operator_notequal_to_zero_impl < T, enable_if_t<ignore_type<decltype(std::declval<T>() != 0)>::value, nullptr_t>> : std::true_type {}; template<typename T> struct has_operator_notequal_to_zero : has_operator_notequal_to_zero_impl<T> {}; template<typename T, typename = nullptr_t> struct has_operator_notequal_to_this_impl : std::false_type {}; template<typename T> struct has_operator_notequal_to_this_impl < T, enable_if_t<ignore_type<decltype(std::declval<T>() != std::declval<T>())>::value, nullptr_t>> : std::true_type {}; template<typename T> struct has_operator_notequal_to_this : has_operator_notequal_to_this_impl<T> {}; }//namespace using namespace type_traits; } #endif //DXLE_INC_TYPE_TRAITS_IS_WELL_FORMAT_HPP_
39.611111
141
0.699158
Nagarei
b96d7fcdda2914cc2d368bbb6387f461defad275
2,632
cpp
C++
code/engine.vc2008/xrScripts/lopen.cpp
icetorch2001/xray-oxygen
8c210ac2824f794cea69266048fe12d584ee3f04
[ "Apache-2.0" ]
1
2021-09-14T14:28:56.000Z
2021-09-14T14:28:56.000Z
code/engine.vc2008/xrScripts/lopen.cpp
ArtemGen/xray-oxygen
f62d3e1f4e211986c057fd37e97fd03c98b5e275
[ "Apache-2.0" ]
null
null
null
code/engine.vc2008/xrScripts/lopen.cpp
ArtemGen/xray-oxygen
f62d3e1f4e211986c057fd37e97fd03c98b5e275
[ "Apache-2.0" ]
3
2021-11-01T06:21:26.000Z
2022-01-08T16:13:23.000Z
// file: lopen.cpp // func: Open lua modules-namespace // author: ForserX #include "stdafx.h" #include "luaopen.hpp" extern "C" { extern const struct luaL_Reg funcs[]; int luaopen_LuaXML_lib(lua_State* L); int luaopen_lfs(lua_State *L); } int lopen::luaopen_ext(lua_State *L) { luaL_openlib(L, "mrsh", funcs, 0); luaopen_LuaXML_lib(L); luaopen_lfs(L); return 1; } #ifndef DEBUG void lopen::put_function(lua_State* state, u8 const* buffer, u32 const buffer_size, const char* package_id) { lua_getglobal(state, "package"); lua_pushstring(state, "preload"); lua_gettable(state, -2); lua_pushstring(state, package_id); luaL_loadbuffer(state, (char*)buffer, buffer_size, package_id); lua_settable(state, -3); } #endif void lopen::open_lib(lua_State *L, LPCSTR module_name, lua_CFunction function) { lua_pushcfunction(L, function); lua_pushstring(L, module_name); lua_call(L, 1, 0); } void lopen::open_luaicp(lua_State* Ls) { const HMODULE hLib = GetModuleHandle("luaicp.dll"); if (hLib) { Msg("Lua Interceptor found! Attaching :)"); typedef void(WINAPI *LUA_CAPTURE)(lua_State *L); LUA_CAPTURE ExtCapture = (LUA_CAPTURE)GetProcAddress(hLib, "ExtCapture"); if (ExtCapture) ExtCapture(Ls); else Msg("ExtCapture proc not found in luaicp.dll"); } } static int report(lua_State *L, int status) { if (status && !lua_isnil(L, -1)) { const char *msg = lua_tostring(L, -1); if (!msg) msg = "(error object is not a string)"; Msg("! [LUA_JIT] %s", msg); lua_pop(L, 1); } return status; } static int loadjitmodule(lua_State *L, const char *notfound) { lua_getglobal(L, "require"); lua_pushliteral(L, "jit."); lua_pushvalue(L, -3); lua_concat(L, 2); if (lua_pcall(L, 1, 1, 0)) { const char *msg = lua_tostring(L, -1); if (msg && !strncmp(msg, "module ", 7)) { Msg("! [LUA_JIT] %s", notfound); return 1; } else return report(L, 1); } lua_getfield(L, -1, "start"); lua_remove(L, -2); /* drop module table */ return 0; } SCRIPT_API int dojitcmd(lua_State *L, const char *cmd) { const char *val = strchr(cmd, '='); lua_pushlstring(L, cmd, val ? val - cmd : xr_strlen(cmd)); lua_getglobal(L, "jit"); /* get jit.* table */ lua_pushvalue(L, -2); lua_gettable(L, -2); /* lookup library function */ if (!lua_isfunction(L, -1)) { lua_pop(L, 2); /* drop non-function and jit.* table, keep module name */ if (loadjitmodule(L, "unknown luaJIT command")) return 1; } else { lua_remove(L, -2); /* drop jit.* table */ } lua_remove(L, -2); /* drop module name */ if (val) lua_pushstring(L, val + 1); return report(L, lua_pcall(L, val ? 1 : 0, 0, 0)); }
23.927273
107
0.666033
icetorch2001
b96d84fed3140b04a6fae66ee9a9de76838e53f3
1,605
cpp
C++
test/src/physics/collision/narrowphase/algorithm/gjk/GJKConvexObjectTest.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
18
2020-06-12T00:04:46.000Z
2022-01-11T14:56:19.000Z
test/src/physics/collision/narrowphase/algorithm/gjk/GJKConvexObjectTest.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
null
null
null
test/src/physics/collision/narrowphase/algorithm/gjk/GJKConvexObjectTest.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
6
2020-08-16T15:58:41.000Z
2022-03-05T13:17:50.000Z
#include <cppunit/TestSuite.h> #include <cppunit/TestCaller.h> #include <memory> #include <UrchinCommon.h> #include <UrchinPhysicsEngine.h> #include <AssertHelper.h> #include <physics/collision/narrowphase/algorithm/gjk/GJKConvexObjectTest.h> #include <physics/collision/narrowphase/algorithm/gjk/GJKTestHelper.h> using namespace urchin; void GJKConvexObjectTest::separateSphereAndBox() { CollisionSphereObject sphere(1.0f, Point3<float>(0.0f, 0.0f, 0.0f)); CollisionBoxObject aabbox(0.0f, Vector3<float>(0.5f, 0.5f, 0.5f), Point3<float>(1.6f, 0.5f, 0.5f), Quaternion<float>()); std::shared_ptr<GJKResult<float>> result = GJKTestHelper::executeGJK(sphere, aabbox); AssertHelper::assertTrue(!result->isCollide()); AssertHelper::assertFloatEquals(result->getSeparatingDistance(), 0.1f); } void GJKConvexObjectTest::overlapSphereAndBox() { CollisionSphereObject sphere(1.0f, Point3<float>(0.0f, 0.0f, 0.0f)); CollisionBoxObject aabbox(0.0f, Vector3<float>(0.5f, 0.5f, 0.5f), Point3<float>(1.4f, 0.5f, 0.5f), Quaternion<float>()); std::shared_ptr<GJKResult<float>> result = GJKTestHelper::executeGJK(sphere, aabbox); AssertHelper::assertTrue(result->isCollide()); } CppUnit::Test* GJKConvexObjectTest::suite() { auto* suite = new CppUnit::TestSuite("GJKConvexObjectTest"); suite->addTest(new CppUnit::TestCaller<GJKConvexObjectTest>("separateSphereAndBox", &GJKConvexObjectTest::separateSphereAndBox)); suite->addTest(new CppUnit::TestCaller<GJKConvexObjectTest>("overlapSphereAndBox", &GJKConvexObjectTest::overlapSphereAndBox)); return suite; }
41.153846
133
0.751402
petitg1987
b970d0577bc37695e46587b9efbb40f602e3706b
1,504
cpp
C++
C++/C++ Fundamentals Sept 2019/11. EXAM PREPARATION/Exam9Jan2018/src/Copy-Paste.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
1
2019-07-21T13:00:31.000Z
2019-07-21T13:00:31.000Z
C++/C++ Fundamentals Sept 2019/11. EXAM PREPARATION/Exam9Jan2018/src/Copy-Paste.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
C++/C++ Fundamentals Sept 2019/11. EXAM PREPARATION/Exam9Jan2018/src/Copy-Paste.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <stack> void copy(const std::string &text, std::stack<std::string> &clipboard, int startIndex, int endIndex) { startIndex = (int) text.find_last_of(' ', startIndex) + 1; endIndex = text.find(' ', endIndex); if (endIndex == -1) { endIndex = text.size(); } std::string copyPart = text.substr(startIndex, endIndex - startIndex); clipboard.push(copyPart); } void paste(std::string &text, std::stack<std::string> &clipboard, const int index) { if (clipboard.empty()) { return; } std::string pasteText; if (text[index] == ' ') { pasteText = ' ' + clipboard.top(); } else { pasteText = clipboard.top(); } clipboard.pop(); text.insert(index, pasteText); } int main() { std::string text; std::getline(std::cin, text); std::string command; int startIndex = -1; int endIndex = -1; std::stack<std::string> clipboard; std::string input; while (std::getline(std::cin, input) && input != "end") { std::istringstream stream(input); stream >> command; if (command == "copy") { stream >> startIndex; stream >> endIndex; copy(text, clipboard, startIndex, endIndex); } else { stream >> startIndex; endIndex = -1; paste(text, clipboard, startIndex); } } std::cout << text << std::endl; return 0; }
22.117647
102
0.563165
galin-kostadinov
b9712383dac34c4a5f56a13032aa1a4da2c1826b
24,782
cpp
C++
src/server/Xml/XmlLibrary.cpp
anewholm/generalserver
99321562921c317f1ef14a2b84abfe91f0f871b6
[ "X11" ]
null
null
null
src/server/Xml/XmlLibrary.cpp
anewholm/generalserver
99321562921c317f1ef14a2b84abfe91f0f871b6
[ "X11" ]
null
null
null
src/server/Xml/XmlLibrary.cpp
anewholm/generalserver
99321562921c317f1ef14a2b84abfe91f0f871b6
[ "X11" ]
null
null
null
//platform agnostic file #include "Xml/XmlLibrary.h" #include "Repository.h" #include "Xml/XmlNamespace.h" #include "IXml/IXslNode.h" #include "IXml/IXmlGrammarContext.h" #include "Debug.h" #include "Utilities/strtools.h" #include <string.h> #include <sstream> using namespace std; //Abstract Factory Method: http://en.wikipedia.org/wiki/Abstract_factory_pattern namespace general_server { XmlLibrary::XmlLibrary(const IMemoryLifetimeOwner *pMemoryLifetimeOwner): MemoryLifetimeOwner(pMemoryLifetimeOwner) { //http://man7.org/linux/man-pages/man3/strptime.3.html //DATE_FORMATS_COUNT = 6 m_aDateFormats[0] = "%s"; //1430316435 (seconds since epoch time-stamp) m_aDateFormats[1] = DATE_FORMAT_XML; //2015-09-28T12:34:54+00:00 m_aDateFormats[2] = DATE_FORMAT_RFC822; //Sun, 06 Nov 1994 08:49:37 GMT (RFC 822, updated by RFC 1123) m_aDateFormats[3] = DATE_FORMAT_RFC850; //Sunday, 06-Nov-94 08:49:37 GMT (RFC 850, obsoleted by RFC 1036) m_aDateFormats[4] = DATE_FORMAT_ANSI; //Sun Nov 6 08:49:37 1994 (ANSI C's asctime() format) m_aDateFormats[5] = "%A"; //Monday } XmlLibrary::~XmlLibrary() { XmlHasNamespaceDefinitions::freeStandardNamespaceDefinitions(); } const char *XmlLibrary::toString() const { stringstream sOut; const char *sName = name(); sOut << "XML Library [" << sName << "]:\n"; sOut << " whichSecurityImplementation: " << whichSecurityImplementation() << "\n"; sOut << " canHardLink: " << canHardLink() << "\n"; sOut << " canSoftLink: " << canSoftLink() << "\n"; sOut << " canTransform: " << canTransform() << "\n"; sOut << " supportsXmlID: " << supportsXmlID() << "\n"; sOut << " supportsXmlRefs: " << supportsXmlRefs() << "\n"; sOut << " isNativeXML: " << isNativeXML() << "\n"; sOut << " acceptsNodeParamsForTransform: " << acceptsNodeParamsForTransform() << "\n"; sOut << " canUpdateGlobalVariables: " << canUpdateGlobalVariables() << "\n"; sOut << " hasNameAxis: " << hasNameAxis() << "\n"; sOut << " hasTopAxis: " << hasTopAxis() << "\n"; sOut << " hasParentsAxis: " << hasParentsAxis() << "\n"; sOut << " hasAncestorsAxis: " << hasAncestorsAxis() << "\n"; sOut << " hasSecurity: " << hasSecurity() << "\n"; //clear up //MMO_FREE(sName); //constant return MM_STRDUP(sOut.str().c_str()); } void XmlLibrary::handleError(ExceptionBase& ex ATTRIBUTE_UNUSED) const { NOT_CURRENTLY_USED(""); } const char *XmlLibrary::fileSystemPathToXPath(const IXmlQueryEnvironment *pQE, const char *sFileSystemPath, const char *sTargetType, const char *sDirectoryNamespacePrefix, const bool bUseIndexes) const { //fileSystemPathToXPath() DOES NOT interact with the database // it is simple string handling // //relative paths: // ../../shared/thingy.xsl => ../../repository:shared/name::thingy_xsl //if name axis is implemented: // (non alpha-numeric chars ignored) // ../../shared/thingy.xsl => ../../repository:shared/name::thingy_xsl //a note about query-strings (they are ignored): // ../../shared/thingy.xsl?gs_include=1 => ../../repository:shared/name::thingy_xsl //xpath portions are left un-touched (anything with a colon) // ../../repository:shared/thingy.xsl => ../../repository:shared/name::thingy_xsl //absolute: // /shared/index.html -> /<sRootXPath>/repository:shared/name::index_hmtl //class references: // /~Person/name::view => ~Person/name::view // /test/eg/~Person/name::view => ~Person/name::view // ~Person/name::view => ~Person/name::view //absolute paths // caller MUST send through the DOC node or other base node for this to work // /test/is/good with doc base node => /repository:test/repository:is/name::good // /test/is/good with base-node idx_8 => id('idx_8')/repository:test/repository:is/name::good //absolute function calls: // /id('idx_3')/name::view => id('idx_3')/name::view // /test/eg/id('idx_3')/name::view => id('idx_3')/name::view // id('idx_3')/name::view => id('idx_3')/name::view //index for empty directory // directroy1/directroy2/ => repository:directroy1/repository:directroy2/name::index // BUT: directroy1/directroy2 => repository:directroy1/name::directroy2 //specials: // ^Class__Response_response_loader/... => id('Class__Response_response_loader')/... string stOut; const char *sPos, *sLastPos, *sTerminatingChar, *sDUP = 0; char c; size_t iLen, iInitialLen; int iBracketLevel = 0; //processing only happens OUTSIDE brackets (...) bool bHasSplitters = false; //------------------- ignore common irrelevant bits iInitialLen = strlen(sFileSystemPath); sTerminatingChar = sFileSystemPath + iInitialLen; sPos = strchr(sFileSystemPath, '?'); //query-string (first ?) if (!sPos) sPos = sTerminatingChar; sLastPos = strnrchr(sFileSystemPath, '.', sPos - sFileSystemPath); //file extension (last .) if ( !sLastPos || strnchr(sLastPos, '\'', sPos - sLastPos) //inside a string literal: ' is not a valid extension char || strnchr(sLastPos, ')', sPos - sLastPos) //inside a function : ) is not a valid extension char ) sLastPos = sPos; //conditional STRDUP sPos = sFileSystemPath; if (sLastPos != sTerminatingChar) sPos = sDUP = _STRNDUP(sFileSystemPath, sLastPos - sFileSystemPath); sLastPos = sPos; stOut.reserve(iInitialLen * 2); //------------------- copy root slash (if present or completely blank string) if (Repository::issplitter(*sPos) || !*sPos) { stOut.append("/"); bHasSplitters = true; //important so that name::index is appended if (*sPos) { sLastPos++; sPos++; } } //------------------- directories / xpath snippets (if any) // name::<directory name> //OR repository:<directory name> while (sPos = Repository::strsplitter(sLastPos)) { if (iLen = sPos - sLastPos) { iBracketLevel += strcount(sLastPos, '(', iLen); if (iBracketLevel > 0) { //inside brackets, or part includes brackets, continue //TODO: can name:: work with brackets, e.g. /folder/document(thing)? stOut.append(sLastPos, iLen + 1); } else { iBracketLevel = 0; //over-negative brackets: ))) will be ignored if (maybeXPath(pQE, sLastPos, iLen)) { if (maybeAbsoluteXPath(pQE, sLastPos)) { //this portion appears to be absolute so restart the output from here stOut.assign(sLastPos, iLen + 1); } else stOut.append(sLastPos, iLen + 1); } else { IFDEBUG( if (_STRNEQUAL(sLastPos, "../", 3)) { NOT_COMPLETE(".. parent move found in the file-system-path, normally the HTTP caller will remove these"); } else if (_STRNEQUAL(sLastPos, "./", 2)) { NOT_COMPLETE(". current directory found in the file-system-path, normally the HTTP caller will remove these"); } ) //override the normal name:: axis use //by specifying a namespace if (sDirectoryNamespacePrefix) { stOut.append(sDirectoryNamespacePrefix); stOut.append(":"); } //local name stOut.append(sLastPos, iLen + 1); //include backslash } } iBracketLevel -= strcount(sLastPos, ')', iLen); bHasSplitters = true; } //else it is an irrelevant double slash, so ignore //advance to next character sPos++; sLastPos = sPos; } //------------------- last part of the string which will be the filename // name::<filename> //OR *[@repository:name = '<filename>'] if (sLastPos && *sLastPos) { if (iBracketLevel) { //still in brackets stOut.append(sLastPos); } else { if (maybeXPath(pQE, sLastPos)) { if (maybeAbsoluteXPath(pQE, sLastPos)) { IFDEBUG(if (stOut.size()) Debug::report("last part of file-system-path was categorised absolute [%s]", sFileSystemPath, rtWarning, rlWorrying)); stOut.assign(sLastPos); } else stOut.append(sLastPos); } else { //replace non-alpha-numeric //default to name:: axis while (c = *sLastPos++) { if (!isalnum(c)) c = '_'; stOut.append(1,c); } } } } else if (bHasSplitters && bUseIndexes) { //no filename after last / //fileSystemPath ends in a / //so place an index search on the end if (hasDefaultNameAxis()) stOut.append("index"); else if (hasNameAxis()) stOut.append("name::index"); else stOut.append(sTargetType).append("[@repository:name = 'index']"); } //Debug::report("[%s] => [%s]", sFileSystemPath, stOut.c_str()); //free up if (sDUP) MMO_FREE(sDUP); return MM_STRDUP(stOut.c_str()); } bool XmlLibrary::maybeAbsoluteXPath(const IXmlQueryEnvironment *pQE, const char *sText) const { //does the path have absolute elements in it? //that would mean, for instance, that it would not need knowledge of its start root for absolute cases // admin/interfaces/~Person/weeee // HTTP/repository:interfaces/id('idx_3')/name::test bool bGPMaybeXPath = false; IXmlGrammarContext *pGP; if (pGP = pQE->grammarContext()) bGPMaybeXPath = pGP->maybeAbsoluteXPath(pQE, sText); return sText && ( bGPMaybeXPath || (*sText == '$') //variables || _STRNEQUAL(sText, "id(", 3) //the id() function ); } const char *XmlLibrary::nodeTypeXPath(const iDOMNodeTypeRequest iNodeTypes) const { const char *sXPath = 0; switch (iNodeTypes) { //NOTE: this will not currently return CDATA nodes case node_type_element_or_text: {sXPath = "(*|text())"; break;} //default case node_type_element_only: {sXPath = "*"; break;} case node_type_processing_instruction: {sXPath = "processing-instruction()"; break;} case node_type_any: {sXPath = "node()"; NOT_CURRENTLY_USED(""); break;} } return sXPath; } bool XmlLibrary::maybeXPath(const IXmlQueryEnvironment *pQE, const char *sText, const size_t iLen) const { // need to check each part of a path also: // admin/interfaces/add // ~HTTP/repository:interfaces/name::test //TODO: this needs to be attached to the GrammarProcessor! //TODO: move this in to LibXmlLibrary bool bGPMaybeXPath = false; IXmlGrammarContext *pGP; if (pGP = pQE->grammarContext()) bGPMaybeXPath = pGP->maybeXPath(pQE, sText, iLen); return sText && ( bGPMaybeXPath || (iLen ? strnchr(sText, '$', iLen) : strchr(sText, '$')) //variables || (iLen ? strnchr(sText, '@', iLen) : strchr(sText, '@')) //attributes || (iLen ? strnchr(sText, ':', iLen) : strchr(sText, ':')) //namespacing || (iLen ? strnchr(sText, '*', iLen) : strchr(sText, '*')) //anything || (_STRNEQUAL(sText, "id(", 3)) //the id() function ); } bool XmlLibrary::isAttributeXPath(const char *sText, const size_t iLen) const { //spots: // repository:Thing/@name // @meta:class //and attribute:: versions //NOTE: this function does not parse the XPath //therefore if a string was included: *[test='/@'] it would confuse this function return sText && ( (iLen ? strnstr(sText, "/@", iLen) : strstr(sText, "/@")) || (iLen ? strnstr(sText, "/attribute::", iLen) : strstr(sText, "/attribute::")) || (*sText == '@') || (_STRNEQUAL(sText, "attribute::", 11)) ); } bool XmlLibrary::maybeNamespacedXPath(const char *sText, const size_t iLen) const { //ignore built-in xml namespace //TODO: this will FAIL in at least these edge cases: // anything that can take a string argument, e.g. starts-with(':') // sdjfhdf_xml:id because the back check only checks for "xml:" const char *sColon = sText; bool bNameSpaceFound = false; if (sText) { while (!bNameSpaceFound && (sColon = strchr(sColon, ':')) && (!iLen || ((size_t) (sColon - sText) < iLen)) ) { if (sColon - sText >= 3 && _STREQUAL(sColon-3, "xml:")) sColon++; else bNameSpaceFound = true; } } return bNameSpaceFound; } bool XmlLibrary::textEqualsTrue(const char *sText) const { //allowed boolean values //0x0 = false return sText && ( !strcasecmp(sText, "yes") || !strcasecmp(sText, "true") || !strcasecmp(sText, "on") || !strcasecmp(sText, "1") || !strcasecmp(sText, "enabled") ); } const char *XmlLibrary::escapeForCDATA(const char *sString) const { const char *sOut = sString; if (sString) { while (strstr(sString, "]]>")) { NOT_COMPLETE("escapeForCDATA"); } } return sOut; } const char *XmlLibrary::normalise(const char *sString) const { //caller frees non zero result //this just converts c-string style escaping to their characters \\n => \n //like the NORMALIZE flag on GRETA regex char *sOutput = 0; if (sString) { size_t iLen = strlen(sString); char *sOutputPosition = sOutput = MM_MALLOC_FOR_RETURN(iLen + 1); const char *sInputPosition = sString; char c; while (c = *sInputPosition++) { if (c == '\\') { if (c = *sInputPosition++) { if (isdigit(c)) { c = atoi(sInputPosition); while (isdigit(*sInputPosition)) sInputPosition++; } else { switch (c) { case 'r': {c = 13;break;} case 'n': {c = 10;break;} default: {c = '\\'; sInputPosition--;} //output the escapes normally } } } else c = '\\'; } *sOutputPosition++ = c; } *sOutputPosition = 0; } return sOutput; } IXmlLibrary::xmlTraceFlag XmlLibrary::parseXMLTraceFlags(const char *sFlags) const { IXmlLibrary::xmlTraceFlag iFlags = IXmlLibrary::XML_DEBUG_NONE; if (sFlags) { if (strstr(sFlags, "XML_DEBUG_ALL")) iFlags = (IXmlLibrary::xmlTraceFlag) (iFlags | IXmlLibrary::XML_DEBUG_ALL); if (strstr(sFlags, "XML_DEBUG_NONE")) iFlags = (IXmlLibrary::xmlTraceFlag) (iFlags | IXmlLibrary::XML_DEBUG_NONE); if (strstr(sFlags, "XML_DEBUG_XPATH_STEP")) iFlags = (IXmlLibrary::xmlTraceFlag) (iFlags | IXmlLibrary::XML_DEBUG_XPATH_STEP); if (strstr(sFlags, "XML_DEBUG_XPATH_EXPR")) iFlags = (IXmlLibrary::xmlTraceFlag) (iFlags | IXmlLibrary::XML_DEBUG_XPATH_EXPR); if (strstr(sFlags, "XML_DEBUG_XPATH_EVAL_COUNTS")) iFlags = (IXmlLibrary::xmlTraceFlag) (iFlags | IXmlLibrary::XML_DEBUG_XPATH_EVAL_COUNTS); if (strstr(sFlags, "XML_DEBUG_PARENT_ROUTE")) iFlags = (IXmlLibrary::xmlTraceFlag) (iFlags | IXmlLibrary::XML_DEBUG_PARENT_ROUTE); } return iFlags; } IXmlLibrary::xsltTraceFlag XmlLibrary::parseXSLTTraceFlags(const char *sFlags) const { IXmlLibrary::xsltTraceFlag iFlags = IXmlLibrary::XSLT_TRACE_NONE; if (sFlags) { if (strstr(sFlags, "XSLT_TRACE_ALL")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_ALL); if (strstr(sFlags, "XSLT_TRACE_NONE")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_NONE); if (strstr(sFlags, "XSLT_TRACE_COPY_TEXT")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_COPY_TEXT); if (strstr(sFlags, "XSLT_TRACE_PROCESS_NODE")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_PROCESS_NODE); if (strstr(sFlags, "XSLT_TRACE_APPLY_TEMPLATE")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_APPLY_TEMPLATE); if (strstr(sFlags, "XSLT_TRACE_COPY")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_COPY); if (strstr(sFlags, "XSLT_TRACE_COMMENT")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_COMMENT); if (strstr(sFlags, "XSLT_TRACE_PI")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_PI); if (strstr(sFlags, "XSLT_TRACE_COPY_OF")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_COPY_OF); if (strstr(sFlags, "XSLT_TRACE_VALUE_OF")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_VALUE_OF); if (strstr(sFlags, "XSLT_TRACE_CALL_TEMPLATE")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_CALL_TEMPLATE); if (strstr(sFlags, "XSLT_TRACE_APPLY_TEMPLATES")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_APPLY_TEMPLATES); if (strstr(sFlags, "XSLT_TRACE_CHOOSE")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_CHOOSE); if (strstr(sFlags, "XSLT_TRACE_IF")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_IF); if (strstr(sFlags, "XSLT_TRACE_FOR_EACH")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_FOR_EACH); if (strstr(sFlags, "XSLT_TRACE_STRIP_SPACES")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_STRIP_SPACES); if (strstr(sFlags, "XSLT_TRACE_TEMPLATES")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_TEMPLATES); if (strstr(sFlags, "XSLT_TRACE_KEYS")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_KEYS); if (strstr(sFlags, "XSLT_TRACE_VARIABLES")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_VARIABLES); if (strstr(sFlags, "XSLT_TRACE_FUNCTION")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_FUNCTION); if (strstr(sFlags, "XSLT_TRACE_PARSING")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_PARSING); if (strstr(sFlags, "XSLT_TRACE_BLANKS")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_BLANKS); if (strstr(sFlags, "XSLT_TRACE_PROCESS")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_PROCESS); if (strstr(sFlags, "XSLT_TRACE_EXTENSIONS")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_EXTENSIONS); if (strstr(sFlags, "XSLT_TRACE_ATTRIBUTES")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_ATTRIBUTES); if (strstr(sFlags, "XSLT_TRACE_EXTRA")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_EXTRA); if (strstr(sFlags, "XSLT_TRACE_AVT")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_AVT); if (strstr(sFlags, "XSLT_TRACE_PATTERN")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_PATTERN); if (strstr(sFlags, "XSLT_TRACE_VARIABLE")) iFlags = (IXmlLibrary::xsltTraceFlag) (iFlags | IXmlLibrary::XSLT_TRACE_VARIABLE); /* pseudo */ if (strstr(sFlags, "XSLT_TRACE_MOST")) iFlags = (IXmlLibrary::xsltTraceFlag) (IXmlLibrary::XSLT_TRACE_ALL | ~IXmlLibrary::XSLT_TRACE_BLANKS); } return iFlags; } IXmlArea *XmlLibrary::factory_area(const IMemoryLifetimeOwner *pMemoryLifetimeOwner, const IXmlQueryEnvironment *pQE) const { return factory_area(pMemoryLifetimeOwner, (XmlNodeList<const IXmlBaseNode> *) 0, pQE, 0); } const char *XmlLibrary::translateDateFormat(const char *sFormat) const { //do not free the result //it is either static OR equal to the input const char *sResponseFormat = sFormat; //XML date standard //http://www.w3.org/TR/NOTE-datetime //YYYY-MM-DDThh:mm:ssTZD //1997-07-16T19:20:30+01:00 if (_STREQUAL(sFormat, "%XML") || _STREQUAL(sFormat, "%ISO8601")) sResponseFormat = DATE_FORMAT_XML; //RFC 822, updated by RFC 1123 //Sun, 06 Nov 1994 08:49:37 GMT else if (_STREQUAL(sFormat, "%RFC822") || _STREQUAL(sFormat, "%HTTP")) sResponseFormat = DATE_FORMAT_RFC822; //RFC 850, obsoleted by RFC 1036 //Sunday, 06-Nov-94 08:49:37 GMT else if (_STREQUAL(sFormat, "%RFC850")) sResponseFormat = DATE_FORMAT_RFC850; //ANSI C's asctime() format //Sun Nov 6 08:49:37 1994 else if (_STREQUAL(sFormat, "%ANSI")) sResponseFormat = DATE_FORMAT_ANSI; return sResponseFormat; } struct tm XmlLibrary::parseDate(const char *sValue) const { //m_aDateFormats populated at instanciation //this function mimicks getdate() but without the environmental dependency of DATEMSK struct tm tGMT; time_t tiTime; const char *sFailChar = 0; size_t i; //initilaise value because not all fields are completed memset(&tGMT, 0, sizeof(tm)); //throw parse failure if no input if (sValue) { if (_STREQUAL(sValue, "now")) { time(&tiTime); gmtime_r(&tiTime, &tGMT); //reentrant } else { for (i = 0; i < DATE_FORMATS_COUNT && !sFailChar; i++) { sFailChar = strptime(sValue, m_aDateFormats[i], &tGMT); } if (!sFailChar) throw FailedToParseDate(this, sValue); else { //test it tiTime = mktime(&tGMT); if (tiTime == -1) throw FailedToParseDate(this, sValue); } } } else throw FailedToParseDate(this, sValue); return tGMT; } bool XmlLibrary::isNameChar(char c) const { //https://www.w3.org/TR/REC-xml/#NT-NameChar //NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] return isNameStartChar(c) || c == '-' || c == '.' || isdigit(c); } bool XmlLibrary::isNameStartChar(char c) const { //https://www.w3.org/TR/REC-xml/#NT-NameStartChar //":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] return c == ':' || isalpha(c) || c == '_'; } const char *XmlLibrary::xml_element_name(const char *sInput, const bool bAllowNamespace, const bool bMakeLowerCase) const { //caller frees result if non-zero //by default take the last part of the string after / char *sElementName; char *position; bool bSeenColon = false, bIsFirstCharacterMode = true, bLastCharacter = false; if (!sInput) { sElementName = MM_STRDUP("gs:unassigned"); } else { if (!*sInput) { sElementName = MM_STRDUP("gs:empty"); } else { //ok, we have a valid non-empty sring //not changing the length of the string sElementName = MM_STRDUP(sInput); //make rest alpha numeric lowercase for (position = sElementName; *position; position++) { bLastCharacter = (position[1] == 0); if (bIsFirstCharacterMode) { //first character has different rules if (!isalpha(*position)) *position = 'X'; else if (bMakeLowerCase && !islower(*position)) *position = tolower(*position); bIsFirstCharacterMode = false; } else { //rest of element name has other rules if (!bLastCharacter && *position == ':' && position[1] && bAllowNamespace && !bSeenColon) { bSeenColon = true; bIsFirstCharacterMode = true; } else { //encode non-valid characters if (!isalnum(*position) && !strchr("-_", *position)) *position = '_'; //lower case valid characters else if (bMakeLowerCase && !islower(*position)) *position = tolower(*position); } } } //remove trailing _ //decreases length of string but not to 0 //first character will always not be an _ while (--position > sElementName && *position == '_') *position = 0; } } //cout << "[" << sInput << "] => [" << sElementName << "]\n"; return sElementName; } }
45.723247
235
0.614962
anewholm
b973ae8d5c0bf3c1a2b3f26a9a1addd3cd985d9f
871
cpp
C++
VCPlusPlus/CPlusPlusTest2/FindMaxIncreasingSeqInArr/FindMaxIncreasingSeqInArr.cpp
madbadPi/TelerikAcademy
37eafec75b510b636a1e7da55fffed7bdc7f3d85
[ "MIT" ]
null
null
null
VCPlusPlus/CPlusPlusTest2/FindMaxIncreasingSeqInArr/FindMaxIncreasingSeqInArr.cpp
madbadPi/TelerikAcademy
37eafec75b510b636a1e7da55fffed7bdc7f3d85
[ "MIT" ]
null
null
null
VCPlusPlus/CPlusPlusTest2/FindMaxIncreasingSeqInArr/FindMaxIncreasingSeqInArr.cpp
madbadPi/TelerikAcademy
37eafec75b510b636a1e7da55fffed7bdc7f3d85
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> std::vector<int> findmaxseqinarr(int myarray[], int size) { std::vector<int> newarr; int counter = 0; int max = 0; for (int i = 0; i < size-1; i++) { while (myarray[i] == myarray[i+1]-1) { counter++; i++; } if (counter > max) { newarr.clear(); for (int j = 0; j < counter; j++) { newarr.push_back(myarray[i-counter+1] + j); } max = counter; } counter = 1; } std::cout << std::endl; return newarr; } void printarr(std::vector<int> result) { std::cout << "{"; for (int i = 0; i < result.size(); i++) { std::cout << result[i] << ", "; } std::cout << "}" << std::endl; } int main() { int myarray[] = { 3, 2, 3, 4, 2, 2, 4 }; int arrsize = sizeof(myarray) / sizeof(myarray[0]); std::vector<int> resultarr = findmaxseqinarr(myarray, arrsize); printarr(resultarr); return 0; }
18.145833
64
0.562572
madbadPi
b974066187415007e1644ec04a17d83b076aaaed
2,833
cc
C++
chrome/browser/ui/views/chrome_web_dialog_view.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/ui/views/chrome_web_dialog_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/ui/views/chrome_web_dialog_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/webui/chrome_web_contents_handler.h" #include "ui/views/controls/webview/web_dialog_view.h" #include "ui/views/widget/widget.h" #if defined(OS_CHROMEOS) #include "ash/public/cpp/shell_window_ids.h" #include "chrome/browser/ui/ash/ash_util.h" #include "ui/wm/core/shadow_types.h" #endif // defined(OS_CHROMEOS) namespace chrome { namespace { gfx::NativeWindow ShowWebDialogWidget(const views::Widget::InitParams& params, views::WebDialogView* view) { views::Widget* widget = new views::Widget; widget->Init(params); // Observer is needed for ChromeVox extension to send messages between content // and background scripts. extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( view->web_contents()); widget->Show(); return widget->GetNativeWindow(); } } // namespace // Declared in browser_dialogs.h so that others don't need to depend on our .h. gfx::NativeWindow ShowWebDialog(gfx::NativeView parent, content::BrowserContext* context, ui::WebDialogDelegate* delegate) { views::WebDialogView* view = new views::WebDialogView(context, delegate, new ChromeWebContentsHandler); views::Widget::InitParams params; params.delegate = view; // NOTE: The |parent| may be null, which will result in the default window // placement on Aura. params.parent = parent; return ShowWebDialogWidget(params, view); } #if defined(OS_CHROMEOS) gfx::NativeWindow ShowWebDialogInContainer(int container_id, content::BrowserContext* context, ui::WebDialogDelegate* delegate, bool is_minimal_style) { DCHECK(container_id != ash::kShellWindowId_Invalid); views::WebDialogView* view = new views::WebDialogView(context, delegate, new ChromeWebContentsHandler); views::Widget::InitParams params; // TODO(updowndota) Remove the special handling for hiding dialog title after // the bug is fixed. if (is_minimal_style) { params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_DROP; params.shadow_elevation = ::wm::kShadowElevationActiveWindow; } params.delegate = view; ash_util::SetupWidgetInitParamsForContainer(&params, container_id); return ShowWebDialogWidget(params, view); } #endif // defined(OS_CHROMEOS) } // namespace chrome
38.808219
80
0.703142
zipated
b975a9f2fd71c785a56edc527f87d59d0bc1b788
686
hpp
C++
tau/TauEngine/include/dx/dx12/DX12CommandQueue.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
1
2020-04-22T04:07:01.000Z
2020-04-22T04:07:01.000Z
tau/TauEngine/include/dx/dx12/DX12CommandQueue.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
tau/TauEngine/include/dx/dx12/DX12CommandQueue.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
#pragma once #include "graphics/CommandQueue.hpp" #ifdef _WIN32 #include <d3d12.h> class TAU_DLL DX12CommandQueue final : public ICommandQueue { DELETE_CM(DX12CommandQueue); private: ID3D12CommandQueue* _d3dQueue; public: DX12CommandQueue(ID3D12CommandQueue* const d3dQueue) noexcept : _d3dQueue(d3dQueue) { } ~DX12CommandQueue() noexcept override { _d3dQueue->Release(); } [[nodiscard]] ID3D12CommandQueue* d3dQueue() const noexcept { return _d3dQueue; } void executeCommandLists(uSys count, const ICommandList* const* lists) noexcept override; void executeCommandLists(UINT count, ID3D12CommandList* const* lists) noexcept; }; #endif
25.407407
93
0.744898
hyfloac
b9778f9ed814307723bfeead10ffed356ba446b2
615
cpp
C++
Hacke Rank Problems/Summation of primes.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
Hacke Rank Problems/Summation of primes.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
Hacke Rank Problems/Summation of primes.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector <int> v; bool isPrime(int x){ for(int i = 3 ; i <= (int)sqrt(x) ; i+=2) if(x%i==0) return false; return true; } void genPrime(){ v.push_back(2); v.push_back(3); for(int i = 5 ; i < 1000001 ; i+=2){ if(i%3 != 0) if(isPrime(i)) v.push_back(i); } } int main(){ int n , q; cin >> n; genPrime(); while(n--){ cin >> q; long long sum = 0; for(int i = 0 ; v[i] <= q ; i++) sum += v[i]; cout << sum << endl; } return 0; }
18.636364
45
0.426016
anand434