blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
811fa85045fa60482d0e07020a7b8cb8b020e922 | cb80a8562d90eb969272a7ff2cf52c1fa7aeb084 | /inletTest3/0.118/uniform/cumulativeContErr | b8b82ee2a0700f0ea4e6c7692331f48a23ccb6b3 | [] | no_license | mahoep/inletCFD | eb516145fad17408f018f51e32aa0604871eaa95 | 0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2 | refs/heads/main | 2023-08-30T22:07:41.314690 | 2021-10-14T19:23:51 | 2021-10-14T19:23:51 | 314,657,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2006 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class uniformDimensionedScalarField;
location "0.118/uniform";
object cumulativeContErr;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
value -0.00137922;
// ************************************************************************* //
| [
"mhoeper3234@gmail.com"
] | mhoeper3234@gmail.com | |
1f7e6ac9a107e15e4390de2cce108744afb49d82 | ec8db7de14c3b159be388d9cd84b7ffb2759fa0f | /libraries/protocol/odyssey_operations.cpp | 65cae767efa5aacdef922e88188b796497d6e596 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | lucien-tronlab/odyssey | 48264db827cf8e0d8f29713b9b33e89bc0389f79 | 9ea6771aff74f922d8d98fd36dd003a49d8e778a | refs/heads/master | 2021-01-22T04:23:33.782797 | 2017-11-10T03:51:21 | 2017-11-10T03:51:21 | 102,265,342 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,161 | cpp | #include <odyssey/protocol/odyssey_operations.hpp>
#include <fc/io/json.hpp>
#include <locale>
namespace odyssey { namespace protocol {
bool inline is_asset_type( asset asset, asset_symbol_type symbol )
{
return asset.symbol == symbol;
}
void account_create_operation::validate() const
{
validate_account_name( new_account_name );
FC_ASSERT( is_asset_type( fee, ODYSSEY_SYMBOL ), "Account creation fee must be ODYSSEY" );
owner.validate();
active.validate();
if ( json_metadata.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
FC_ASSERT( fee >= asset( 0, ODYSSEY_SYMBOL ), "Account creation fee cannot be negative" );
}
void account_create_with_delegation_operation::validate() const
{
validate_account_name( new_account_name );
validate_account_name( creator );
FC_ASSERT( is_asset_type( fee, ODYSSEY_SYMBOL ), "Account creation fee must be ODYSSEY" );
FC_ASSERT( is_asset_type( delegation, VESTS_SYMBOL ), "Delegation must be VESTS" );
owner.validate();
active.validate();
posting.validate();
if( json_metadata.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
FC_ASSERT( fee >= asset( 0, ODYSSEY_SYMBOL ), "Account creation fee cannot be negative" );
FC_ASSERT( delegation >= asset( 0, VESTS_SYMBOL ), "Delegation cannot be negative" );
}
void account_update_operation::validate() const
{
validate_account_name( account );
/*if( owner )
owner->validate();
if( active )
active->validate();
if( posting )
posting->validate();*/
if ( json_metadata.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_metadata), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
}
void comment_operation::validate() const
{
FC_ASSERT( title.size() < 256, "Title larger than size limit" );
FC_ASSERT( fc::is_utf8( title ), "Title not formatted in UTF8" );
FC_ASSERT( body.size() > 0, "Body is empty" );
FC_ASSERT( fc::is_utf8( body ), "Body not formatted in UTF8" );
if( parent_author.size() )
validate_account_name( parent_author );
validate_account_name( author );
validate_permlink( parent_permlink );
validate_permlink( permlink );
if( json_metadata.size() > 0 )
{
FC_ASSERT( fc::json::is_valid(json_metadata), "JSON Metadata not valid JSON" );
}
}
struct comment_options_extension_validate_visitor
{
comment_options_extension_validate_visitor() {}
typedef void result_type;
void operator()( const comment_payout_beneficiaries& cpb ) const
{
cpb.validate();
}
};
void comment_payout_beneficiaries::validate()const
{
uint32_t sum = 0;
FC_ASSERT( beneficiaries.size(), "Must specify at least one beneficiary" );
FC_ASSERT( beneficiaries.size() < 128, "Cannot specify more than 127 beneficiaries." ); // Require size serializtion fits in one byte.
validate_account_name( beneficiaries[0].account );
FC_ASSERT( beneficiaries[0].weight <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to one account" );
sum += beneficiaries[0].weight;
FC_ASSERT( sum <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to a comment" ); // Have to check incrementally to avoid overflow
for( size_t i = 1; i < beneficiaries.size(); i++ )
{
validate_account_name( beneficiaries[i].account );
FC_ASSERT( beneficiaries[i].weight <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to one account" );
sum += beneficiaries[i].weight;
FC_ASSERT( sum <= ODYSSEY_100_PERCENT, "Cannot allocate more than 100% of rewards to a comment" ); // Have to check incrementally to avoid overflow
FC_ASSERT( beneficiaries[i - 1] < beneficiaries[i], "Benficiaries must be specified in sorted order (account ascending)" );
}
}
void comment_options_operation::validate()const
{
validate_account_name( author );
FC_ASSERT( percent_odyssey_dollars <= ODYSSEY_100_PERCENT, "Percent cannot exceed 100%" );
FC_ASSERT( max_accepted_payout.symbol == SBD_SYMBOL, "Max accepted payout must be in SBD" );
FC_ASSERT( max_accepted_payout.amount.value >= 0, "Cannot accept less than 0 payout" );
validate_permlink( permlink );
for( auto& e : extensions )
e.visit( comment_options_extension_validate_visitor() );
}
void delete_comment_operation::validate()const
{
validate_permlink( permlink );
validate_account_name( author );
}
void challenge_authority_operation::validate()const
{
validate_account_name( challenger );
validate_account_name( challenged );
FC_ASSERT( challenged != challenger, "cannot challenge yourself" );
}
void prove_authority_operation::validate()const
{
validate_account_name( challenged );
}
void vote_operation::validate() const
{
validate_account_name( voter );
validate_account_name( author );\
FC_ASSERT( abs(weight) <= ODYSSEY_100_PERCENT, "Weight is not a ODYSSEY percentage" );
validate_permlink( permlink );
}
void transfer_operation::validate() const
{ try {
validate_account_name( from );
validate_account_name( to );
FC_ASSERT( amount.symbol != VESTS_SYMBOL, "transferring of Odyssey Power (STMP) is not allowed." );
FC_ASSERT( amount.amount > 0, "Cannot transfer a negative amount (aka: stealing)" );
FC_ASSERT( memo.size() < ODYSSEY_MAX_MEMO_SIZE, "Memo is too large" );
FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
} FC_CAPTURE_AND_RETHROW( (*this) ) }
void transfer_to_vesting_operation::validate() const
{
validate_account_name( from );
FC_ASSERT( is_asset_type( amount, ODYSSEY_SYMBOL ), "Amount must be ODYSSEY" );
if ( to != account_name_type() ) validate_account_name( to );
FC_ASSERT( amount > asset( 0, ODYSSEY_SYMBOL ), "Must transfer a nonzero amount" );
}
void withdraw_vesting_operation::validate() const
{
validate_account_name( account );
FC_ASSERT( is_asset_type( vesting_shares, VESTS_SYMBOL), "Amount must be VESTS" );
}
void set_withdraw_vesting_route_operation::validate() const
{
validate_account_name( from_account );
validate_account_name( to_account );
FC_ASSERT( 0 <= percent && percent <= ODYSSEY_100_PERCENT, "Percent must be valid odyssey percent" );
}
void witness_update_operation::validate() const
{
validate_account_name( owner );
FC_ASSERT( url.size() > 0, "URL size must be greater than 0" );
FC_ASSERT( fc::is_utf8( url ), "URL is not valid UTF8" );
FC_ASSERT( fee >= asset( 0, ODYSSEY_SYMBOL ), "Fee cannot be negative" );
props.validate();
}
void account_witness_vote_operation::validate() const
{
validate_account_name( account );
validate_account_name( witness );
}
void account_witness_proxy_operation::validate() const
{
validate_account_name( account );
if( proxy.size() )
validate_account_name( proxy );
FC_ASSERT( proxy != account, "Cannot proxy to self" );
}
void custom_operation::validate() const {
/// required auth accounts are the ones whose bandwidth is consumed
FC_ASSERT( required_auths.size() > 0, "at least on account must be specified" );
}
void custom_json_operation::validate() const {
/// required auth accounts are the ones whose bandwidth is consumed
FC_ASSERT( (required_auths.size() + required_posting_auths.size()) > 0, "at least on account must be specified" );
FC_ASSERT( id.size() <= 32, "id is too long" );
FC_ASSERT( fc::is_utf8(json), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json), "JSON Metadata not valid JSON" );
}
void custom_binary_operation::validate() const {
/// required auth accounts are the ones whose bandwidth is consumed
FC_ASSERT( (required_owner_auths.size() + required_active_auths.size() + required_posting_auths.size()) > 0, "at least on account must be specified" );
FC_ASSERT( id.size() <= 32, "id is too long" );
for( const auto& a : required_auths ) a.validate();
}
fc::sha256 pow_operation::work_input()const
{
auto hash = fc::sha256::hash( block_id );
hash._hash[0] = nonce;
return fc::sha256::hash( hash );
}
void pow_operation::validate()const
{
props.validate();
validate_account_name( worker_account );
FC_ASSERT( work_input() == work.input, "Determninistic input does not match recorded input" );
work.validate();
}
struct pow2_operation_validate_visitor
{
typedef void result_type;
template< typename PowType >
void operator()( const PowType& pow )const
{
pow.validate();
}
};
void pow2_operation::validate()const
{
props.validate();
work.visit( pow2_operation_validate_visitor() );
}
struct pow2_operation_get_required_active_visitor
{
typedef void result_type;
pow2_operation_get_required_active_visitor( flat_set< account_name_type >& required_active )
: _required_active( required_active ) {}
template< typename PowType >
void operator()( const PowType& work )const
{
_required_active.insert( work.input.worker_account );
}
flat_set<account_name_type>& _required_active;
};
void pow2_operation::get_required_active_authorities( flat_set<account_name_type>& a )const
{
if( !new_owner_key )
{
pow2_operation_get_required_active_visitor vtor( a );
work.visit( vtor );
}
}
void pow::create( const fc::ecc::private_key& w, const digest_type& i )
{
input = i;
signature = w.sign_compact(input,false);
auto sig_hash = fc::sha256::hash( signature );
public_key_type recover = fc::ecc::public_key( signature, sig_hash, false );
work = fc::sha256::hash(recover);
}
void pow2::create( const block_id_type& prev, const account_name_type& account_name, uint64_t n )
{
input.worker_account = account_name;
input.prev_block = prev;
input.nonce = n;
auto prv_key = fc::sha256::hash( input );
auto input = fc::sha256::hash( prv_key );
auto signature = fc::ecc::private_key::regenerate( prv_key ).sign_compact(input);
auto sig_hash = fc::sha256::hash( signature );
public_key_type recover = fc::ecc::public_key( signature, sig_hash );
fc::sha256 work = fc::sha256::hash(std::make_pair(input,recover));
pow_summary = work.approx_log_32();
}
void equihash_pow::create( const block_id_type& recent_block, const account_name_type& account_name, uint32_t nonce )
{
input.worker_account = account_name;
input.prev_block = recent_block;
input.nonce = nonce;
auto seed = fc::sha256::hash( input );
proof = fc::equihash::proof::hash( ODYSSEY_EQUIHASH_N, ODYSSEY_EQUIHASH_K, seed );
pow_summary = fc::sha256::hash( proof.inputs ).approx_log_32();
}
void pow::validate()const
{
FC_ASSERT( work != fc::sha256() );
FC_ASSERT( public_key_type(fc::ecc::public_key( signature, input, false )) == worker );
auto sig_hash = fc::sha256::hash( signature );
public_key_type recover = fc::ecc::public_key( signature, sig_hash, false );
FC_ASSERT( work == fc::sha256::hash(recover) );
}
void pow2::validate()const
{
validate_account_name( input.worker_account );
pow2 tmp; tmp.create( input.prev_block, input.worker_account, input.nonce );
FC_ASSERT( pow_summary == tmp.pow_summary, "reported work does not match calculated work" );
}
void equihash_pow::validate() const
{
validate_account_name( input.worker_account );
auto seed = fc::sha256::hash( input );
FC_ASSERT( proof.n == ODYSSEY_EQUIHASH_N, "proof of work 'n' value is incorrect" );
FC_ASSERT( proof.k == ODYSSEY_EQUIHASH_K, "proof of work 'k' value is incorrect" );
FC_ASSERT( proof.seed == seed, "proof of work seed does not match expected seed" );
FC_ASSERT( proof.is_valid(), "proof of work is not a solution", ("block_id", input.prev_block)("worker_account", input.worker_account)("nonce", input.nonce) );
FC_ASSERT( pow_summary == fc::sha256::hash( proof.inputs ).approx_log_32() );
}
void feed_publish_operation::validate()const
{
validate_account_name( publisher );
FC_ASSERT( ( is_asset_type( exchange_rate.base, ODYSSEY_SYMBOL ) && is_asset_type( exchange_rate.quote, SBD_SYMBOL ) )
|| ( is_asset_type( exchange_rate.base, SBD_SYMBOL ) && is_asset_type( exchange_rate.quote, ODYSSEY_SYMBOL ) ),
"Price feed must be a ODYSSEY/SBD price" );
exchange_rate.validate();
}
void limit_order_create_operation::validate()const
{
validate_account_name( owner );
FC_ASSERT( ( is_asset_type( amount_to_sell, ODYSSEY_SYMBOL ) && is_asset_type( min_to_receive, SBD_SYMBOL ) )
|| ( is_asset_type( amount_to_sell, SBD_SYMBOL ) && is_asset_type( min_to_receive, ODYSSEY_SYMBOL ) ),
"Limit order must be for the ODYSSEY:SBD market" );
(amount_to_sell / min_to_receive).validate();
}
void limit_order_create2_operation::validate()const
{
validate_account_name( owner );
FC_ASSERT( amount_to_sell.symbol == exchange_rate.base.symbol, "Sell asset must be the base of the price" );
exchange_rate.validate();
FC_ASSERT( ( is_asset_type( amount_to_sell, ODYSSEY_SYMBOL ) && is_asset_type( exchange_rate.quote, SBD_SYMBOL ) ) ||
( is_asset_type( amount_to_sell, SBD_SYMBOL ) && is_asset_type( exchange_rate.quote, ODYSSEY_SYMBOL ) ),
"Limit order must be for the ODYSSEY:SBD market" );
FC_ASSERT( (amount_to_sell * exchange_rate).amount > 0, "Amount to sell cannot round to 0 when traded" );
}
void limit_order_cancel_operation::validate()const
{
validate_account_name( owner );
}
void convert_operation::validate()const
{
validate_account_name( owner );
/// only allow conversion from SBD to ODYSSEY, allowing the opposite can enable traders to abuse
/// market fluxuations through converting large quantities without moving the price.
FC_ASSERT( is_asset_type( amount, SBD_SYMBOL ), "Can only convert SBD to ODYSSEY" );
FC_ASSERT( amount.amount > 0, "Must convert some SBD" );
}
void report_over_production_operation::validate()const
{
validate_account_name( reporter );
validate_account_name( first_block.witness );
FC_ASSERT( first_block.witness == second_block.witness );
FC_ASSERT( first_block.timestamp == second_block.timestamp );
FC_ASSERT( first_block.signee() == second_block.signee() );
FC_ASSERT( first_block.id() != second_block.id() );
}
void escrow_transfer_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
FC_ASSERT( fee.amount >= 0, "fee cannot be negative" );
FC_ASSERT( sbd_amount.amount >= 0, "sbd amount cannot be negative" );
FC_ASSERT( odyssey_amount.amount >= 0, "odyssey amount cannot be negative" );
FC_ASSERT( sbd_amount.amount > 0 || odyssey_amount.amount > 0, "escrow must transfer a non-zero amount" );
FC_ASSERT( from != agent && to != agent, "agent must be a third party" );
FC_ASSERT( (fee.symbol == ODYSSEY_SYMBOL) || (fee.symbol == SBD_SYMBOL), "fee must be ODYSSEY or SBD" );
FC_ASSERT( sbd_amount.symbol == SBD_SYMBOL, "sbd amount must contain SBD" );
FC_ASSERT( odyssey_amount.symbol == ODYSSEY_SYMBOL, "odyssey amount must contain ODYSSEY" );
FC_ASSERT( ratification_deadline < escrow_expiration, "ratification deadline must be before escrow expiration" );
if ( json_meta.size() > 0 )
{
FC_ASSERT( fc::is_utf8(json_meta), "JSON Metadata not formatted in UTF8" );
FC_ASSERT( fc::json::is_valid(json_meta), "JSON Metadata not valid JSON" );
}
}
void escrow_approve_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
validate_account_name( who );
FC_ASSERT( who == to || who == agent, "to or agent must approve escrow" );
}
void escrow_dispute_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
validate_account_name( who );
FC_ASSERT( who == from || who == to, "who must be from or to" );
}
void escrow_release_operation::validate()const
{
validate_account_name( from );
validate_account_name( to );
validate_account_name( agent );
validate_account_name( who );
validate_account_name( receiver );
FC_ASSERT( who == from || who == to || who == agent, "who must be from or to or agent" );
FC_ASSERT( receiver == from || receiver == to, "receiver must be from or to" );
FC_ASSERT( sbd_amount.amount >= 0, "sbd amount cannot be negative" );
FC_ASSERT( odyssey_amount.amount >= 0, "odyssey amount cannot be negative" );
FC_ASSERT( sbd_amount.amount > 0 || odyssey_amount.amount > 0, "escrow must release a non-zero amount" );
FC_ASSERT( sbd_amount.symbol == SBD_SYMBOL, "sbd amount must contain SBD" );
FC_ASSERT( odyssey_amount.symbol == ODYSSEY_SYMBOL, "odyssey amount must contain ODYSSEY" );
}
void request_account_recovery_operation::validate()const
{
validate_account_name( recovery_account );
validate_account_name( account_to_recover );
new_owner_authority.validate();
}
void recover_account_operation::validate()const
{
validate_account_name( account_to_recover );
FC_ASSERT( !( new_owner_authority == recent_owner_authority ), "Cannot set new owner authority to the recent owner authority" );
FC_ASSERT( !new_owner_authority.is_impossible(), "new owner authority cannot be impossible" );
FC_ASSERT( !recent_owner_authority.is_impossible(), "recent owner authority cannot be impossible" );
FC_ASSERT( new_owner_authority.weight_threshold, "new owner authority cannot be trivial" );
new_owner_authority.validate();
recent_owner_authority.validate();
}
void change_recovery_account_operation::validate()const
{
validate_account_name( account_to_recover );
validate_account_name( new_recovery_account );
}
void transfer_to_savings_operation::validate()const {
validate_account_name( from );
validate_account_name( to );
FC_ASSERT( amount.amount > 0 );
FC_ASSERT( amount.symbol == ODYSSEY_SYMBOL || amount.symbol == SBD_SYMBOL );
FC_ASSERT( memo.size() < ODYSSEY_MAX_MEMO_SIZE, "Memo is too large" );
FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
}
void transfer_from_savings_operation::validate()const {
validate_account_name( from );
validate_account_name( to );
FC_ASSERT( amount.amount > 0 );
FC_ASSERT( amount.symbol == ODYSSEY_SYMBOL || amount.symbol == SBD_SYMBOL );
FC_ASSERT( memo.size() < ODYSSEY_MAX_MEMO_SIZE, "Memo is too large" );
FC_ASSERT( fc::is_utf8( memo ), "Memo is not UTF8" );
}
void cancel_transfer_from_savings_operation::validate()const {
validate_account_name( from );
}
void decline_voting_rights_operation::validate()const
{
validate_account_name( account );
}
void reset_account_operation::validate()const
{
validate_account_name( reset_account );
validate_account_name( account_to_reset );
FC_ASSERT( !new_owner_authority.is_impossible(), "new owner authority cannot be impossible" );
FC_ASSERT( new_owner_authority.weight_threshold, "new owner authority cannot be trivial" );
new_owner_authority.validate();
}
void set_reset_account_operation::validate()const
{
validate_account_name( account );
if( current_reset_account.size() )
validate_account_name( current_reset_account );
validate_account_name( reset_account );
FC_ASSERT( current_reset_account != reset_account, "new reset account cannot be current reset account" );
}
void claim_reward_balance_operation::validate()const
{
validate_account_name( account );
FC_ASSERT( is_asset_type( reward_odyssey, ODYSSEY_SYMBOL ), "Reward Odyssey must be ODYSSEY" );
FC_ASSERT( is_asset_type( reward_sbd, SBD_SYMBOL ), "Reward Odyssey must be SBD" );
FC_ASSERT( is_asset_type( reward_vests, VESTS_SYMBOL ), "Reward Odyssey must be VESTS" );
FC_ASSERT( reward_odyssey.amount >= 0, "Cannot claim a negative amount" );
FC_ASSERT( reward_sbd.amount >= 0, "Cannot claim a negative amount" );
FC_ASSERT( reward_vests.amount >= 0, "Cannot claim a negative amount" );
FC_ASSERT( reward_odyssey.amount > 0 || reward_sbd.amount > 0 || reward_vests.amount > 0, "Must claim something." );
}
void delegate_vesting_shares_operation::validate()const
{
validate_account_name( delegator );
validate_account_name( delegatee );
FC_ASSERT( delegator != delegatee, "You cannot delegate VESTS to yourself" );
FC_ASSERT( is_asset_type( vesting_shares, VESTS_SYMBOL ), "Delegation must be VESTS" );
FC_ASSERT( vesting_shares >= asset( 0, VESTS_SYMBOL ), "Delegation cannot be negative" );
}
} } // odyssey::protocol
| [
"keelson@tronlab.com"
] | keelson@tronlab.com |
3d316e72c7f5274478932575ed375aa09361e246 | 3db588f4b1e21035610daa5d937d9571f690b249 | /School Attendance System/SchoolAttendanceSystem/SchoolAttendanceSystem/SchoolAttendanceSystemDlg.h | 16c2cdc25bb8777b84ecde24553eb7d196554189 | [] | no_license | sanketjaind/Projects | 1d6cd1abc04c368c13a92e75eb5019854fcb656c | 02e035ad09e93ff971f52019fc706f3a0c5e9e44 | refs/heads/master | 2022-04-25T13:26:57.421503 | 2020-04-25T07:10:18 | 2020-04-25T07:10:18 | 258,704,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | h |
// SchoolAttendanceSystemDlg.h : header file
//
#pragma once
#include "inc.h"
#include "StaffMenu.h"
#include "AdminPanel.h"
#include "CheckAttendance.h"
// CSchoolAttendanceSystemDlg dialog
class CSchoolAttendanceSystemDlg : public CDialogEx, public inc
{
// Construction
public:
CSchoolAttendanceSystemDlg(CWnd* pParent = NULL); // standard constructor
StaffMenu StaffMenu;
AdminPanel admin;
CheckAttendance Check;
// Dialog Data
enum { IDD = IDD_SCHOOLATTENDANCESYSTEM_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedRadio1();
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedRadio2();
afx_msg void OnBnClickedRadio3();
afx_msg void OnEnChangeEdit1();
CString username;
CString pass;
afx_msg void OnEnChangeEdit2();
};
| [
"sanketjaind@gmail.com"
] | sanketjaind@gmail.com |
d5e11a2527b2c59523b9783bdd8267dbf583d14f | 00c528f1ac1223d264fccba7633c6cd40f8ef104 | /io.cpp | 35349bcce437e13e4d6ada422fbe5165c04efbe3 | [] | no_license | lyinch/ncurses-howto | cb5011053438c9f4e5e79cfc2db25ca6b9a33b59 | da16d4a98d5aa6be0b456bb6d990fabdc8779912 | refs/heads/master | 2020-05-30T12:03:59.083040 | 2019-06-06T13:11:21 | 2019-06-06T13:11:21 | 189,722,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | cpp | #include <iostream>
#include <ncurses.h>
int main() {
int ch;
initscr(); // start cursed mode
raw(); // Send all keys to the program instantly
//cbreak(); // Disable terminal buffering, but let terminal handle interrupt keys normally
noecho(); // don't print user input
keypad(stdscr,TRUE); // enable reading of function keys F1,... and arrow keys
addch('a');
addch('b' | A_BOLD);
addch('c' | A_BLINK);
printw("Print at the cursor \n");
printw("Print %s at the cursor \n","formatted text");
mvprintw(10,2,"Print %s at the cursor at coordinates y: %d x: %d \n","formatted text",10,2);
addstr("Print full string to screen \n");
addnstr("Print only the first 5 characters...",5);
mvprintw(20,0,"Type any key \n");
ch = getch();
if(ch == KEY_UP)
printw("Arrow UP pressed");
else{
printw("The key pressed is ");
attron(A_UNDERLINE); // activate attribute
printw("%c", ch);
attroff(A_UNDERLINE); // turn attribute off
printw("\n");
}
refresh(); // print buffer to screen
printw("Type a string \n");
refresh();
char str[80];
getstr(str);
printw("Your string is: %s \n",str);
refresh();
int age = 0;
printw("How old are you \n");
refresh();
scanw("%d",&age);
printw("You are %d years old \n",age);
mvprintw(LINES-2,0,"We can print at the bottom with the LINES value");
refresh();
getch();
endwin();
return 0;
} | [
"backes.thierry@gmail.com"
] | backes.thierry@gmail.com |
f93e64068ce9c22c43d16a66b2343e873fc4eb34 | 0288d2fff958e5b7dbc0c4e3d765bfb842a885af | /PA1/pa1-b/09.cpp | 10e05f568e4542d2de5d592cd0a55884d5132f1e | [] | no_license | georgao35/DSA | e0daf1e0eec57abb750a896b3a9b1faa206d514b | c6e13917bf7c1122db83423473c220359a633fef | refs/heads/master | 2023-02-05T20:10:30.680401 | 2021-01-01T04:02:53 | 2021-01-01T04:02:53 | 295,629,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,520 | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
char a[1 << 22]; // 不分块的珠子
int realn; // 珠子总长度
const int cut = 1 << 11; // 分块时每一块的长度
const int sec = 1 << 12; // 每块最大长度
char p[1 << 12][sec]; // 分的块
int plen[1 << 12]; // 每一块的长度
int pn; // 块数
struct Rank {
int first, second;
};
// a to p:将 a 切分成 p
void a2p() {
if (realn == 0) {
pn = 1;
plen[0] = 0;
return;
}
int i = 0, j = 0;
for (; j < realn; i++, j += cut) {
int m = realn - j < cut ? realn - j : cut;
memcpy(p[i], &a[j], m);
plen[i] = m;
}
pn = i;
}
// p to a:将 p “组装”回 a
void p2a() {
int old_realn = realn;
realn = 0;
for (int i = 0; i < pn; i++) {
memcpy(&a[realn], p[i], plen[i]);
realn += plen[i];
}
}
// 调试用:打印所有块,每块一行
void viewp() {
for (int i = 0; i < pn; i++) {
for (int j = 0; j < plen[i]; j++)
putchar(p[i][j]);
putchar('\n');
}
}
Rank find(int rank) {
int group = 0;
while (group < pn - 1 && rank > plen[group]) {
rank -= plen[group];
group++;
}
return {group, rank};
}
inline char &get(Rank pos) {
return p[pos.first][pos.second];
}
// 在 p 上计算珠子的插入和消除
void play(int rank, char ch) {
Rank pos = find(rank);
char *cur = &get(pos);
int succ_len = plen[pos.first] - pos.second;
if (succ_len > 0) {
memmove(cur + 1, cur, succ_len);
}
*cur = ch;
realn++;
plen[pos.first]++;
// 块过长,重组
if (plen[pos.first] >= sec) {
p2a();
a2p();
pos = find(rank);
}
Rank l = pos, r = pos;
Rank lbound, rbound;
int dis = 0;
int decrease = 0;
while (1) {
while (l.first >= 0 && get(l) == ch) {
l.second--;
dis++;
while (l.second < 0 && l.first >= 0) {
l.first--;
if (l.first >= 0)
l.second += plen[l.first];
}
}
while (r.first < pn && get(r) == ch) {
r.second++;
dis++;
while (r.second >= plen[r.first] && r.first < pn) {
r.second -= plen[r.first];
r.first++;
}
}
if (dis > 3) {
decrease += dis - 1;
lbound = l;
rbound = r;
ch = get(l);
dis = 1;
} else {
break;
}
}
if (decrease > 0) {
realn -= decrease;
l = lbound;
r = rbound;
if (l.first >= 0) {
plen[l.first] = l.second + 1;
}
if (r.first < pn) {
int len = plen[r.first] - r.second;
if (len > 0) {
memmove(&p[r.first][0], &p[r.first][r.second], len);
}
plen[r.first] = len;
}
for (int i = l.first + 1; i < r.first; i++)
plen[i] = 0;
}
}
int main() {
int n;
fgets(a, sizeof(a), stdin);
realn = strlen(a);
while (realn > 0 && (a[realn - 1] == '\n' || a[realn - 1] == '\r'))
realn--;
a2p();
scanf("%d", &n);
while (n--) {
char buf[16];
char &ch = buf[0];
int rank;
scanf("%d%s", &rank, &ch);
play(rank, ch);
}
p2a();
a[realn] = '\0';
puts(a);
return 0;
}
| [
"gaojy19@mails.tsinghua.edu.cn"
] | gaojy19@mails.tsinghua.edu.cn |
13483a798c60e427aa70bca5f51436b18d12fada | cfa625b06d4924a6b69d5b9add2c19da0ba4f92c | /PhysX_3.4/Samples/SampleBase/RenderBoxActor.h | 448ab361dad63bc54d100ff5877b5282a55ac065 | [] | no_license | ldotn/simple-physx | a731775fe27281b55b03d646f72dd275eaa4befa | a065a9c734c134074c63c80a9109a398b22d040c | refs/heads/master | 2022-03-22T20:49:42.997588 | 2019-12-01T15:45:01 | 2019-12-01T15:49:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,160 | h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef RENDER_BOX_ACTOR_H
#define RENDER_BOX_ACTOR_H
#include "RenderBaseActor.h"
#include "foundation/PxVec3.h"
namespace SampleRenderer
{
class Renderer;
}
class RenderBoxActor : public RenderBaseActor
{
public:
RenderBoxActor(SampleRenderer::Renderer& renderer, const PxVec3& extents, const PxReal* uvs=NULL);
RenderBoxActor(const RenderBoxActor&);
virtual ~RenderBoxActor();
};
#endif
| [
"pachesantiago@gmail.com"
] | pachesantiago@gmail.com |
cab303b87853fef00684bc26586cde4e01c915c0 | bff9ee7f0b96ac71e609a50c4b81375768541aab | /src/external/armadillo/tests/gen_randu.cpp | c2811c4e21ca8dc1ae52089932983ee48409f2d2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
] | permissive | rohitativy/turicreate | d7850f848b7ccac80e57e8042dafefc8b949b12b | 1c31ee2d008a1e9eba029bafef6036151510f1ec | refs/heads/master | 2020-03-10T02:38:23.052555 | 2018-04-11T02:20:16 | 2018-04-11T02:20:16 | 129,141,488 | 1 | 0 | BSD-3-Clause | 2018-04-11T19:06:32 | 2018-04-11T19:06:31 | null | UTF-8 | C++ | false | false | 1,670 | cpp | // Copyright 2015 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2015 National ICT Australia (NICTA)
//
// 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 <numerics/armadillo.hpp>
#include "catch.hpp"
using namespace arma;
TEST_CASE("gen_randu_1")
{
const uword n_rows = 100;
const uword n_cols = 101;
mat A(n_rows,n_cols, fill::randu);
mat B(n_rows,n_cols); B.randu();
mat C; C.randu(n_rows,n_cols);
REQUIRE( (accu(A)/A.n_elem) == Approx(0.5).epsilon(0.01) );
REQUIRE( (accu(B)/A.n_elem) == Approx(0.5).epsilon(0.01) );
REQUIRE( (accu(C)/A.n_elem) == Approx(0.5).epsilon(0.01) );
REQUIRE( (mean(vectorise(A))) == Approx(0.5).epsilon(0.01) );
}
TEST_CASE("gen_randu_2")
{
mat A(50,60,fill::zeros);
A(span(1,48),span(1,58)).randu();
REQUIRE( accu(A.head_cols(1)) == Approx(0.0) );
REQUIRE( accu(A.head_rows(1)) == Approx(0.0) );
REQUIRE( accu(A.tail_cols(1)) == Approx(0.0) );
REQUIRE( accu(A.tail_rows(1)) == Approx(0.0) );
REQUIRE( mean(vectorise(A(span(1,48),span(1,58)))) == Approx(double(0.5)).epsilon(0.01) );
}
| [
"znation@apple.com"
] | znation@apple.com |
7caa7967d5227dbf322a3863fd42311860f3febc | 4e035c6d51fa19cbdf4f584867b55e7813b69869 | /include/Rendering/SRenderTargetViewDesc.h | 2c95de5fcf46471c864b4de9d9ef1adde4570355 | [] | no_license | ipoopedmypantsuups/HitmanAbsolutionSDK | d28ec117f8da8c2f1bab3068a17c7143c5f83ea4 | c4a211550dc66687df9bdae5d4c0bf665d48f5ad | refs/heads/main | 2023-03-08T05:04:24.939062 | 2021-02-20T08:07:30 | 2021-02-20T08:07:30 | 359,103,783 | 0 | 0 | null | 2021-04-18T09:50:59 | 2021-04-18T09:50:58 | null | UTF-8 | C++ | false | false | 821 | h | #pragma once
#include "ERenderFormat.h"
class SRenderTargetViewDesc
{
public:
ERenderFormat eFormat;
enum EViewDimension
{
VIEW_DIMENSION_TEXTURE2D = 0x1,
VIEW_DIMENSION_TEXTURE2DMS = 0x2,
VIEW_DIMENSION_TEXTURE2DARRAY = 0x3,
VIEW_DIMENSION_TEXTURE3D = 0x4,
} eViewDimension;
union
{
struct SViewTexture2D
{
unsigned int nMipSlice;
} viewTexture2D;
struct SViewTexture2DArray
{
unsigned int nMipSlice;
unsigned int nFirstArraySlice;
unsigned int nArraySize;
} viewTexture2DArray;
struct SViewTexture3D
{
unsigned int nMipSlice;
unsigned int nFirstWSlice;
unsigned int nWSize;
} viewTexture3D;
};
};
| [
"pavle_nis@yahoo.com"
] | pavle_nis@yahoo.com |
c751b8d4e8132afadbfe268cb947e1d59adf0ba8 | 439ac415df5b8e6b7d167591180930138703280e | /Assignment/2학년 1학기/C++/0517/캐릭터,아이템 관리_팩토리 패턴/LoginManager.h | eb5486ea757b8cf328c47f1beb85f0933c47e39a | [] | no_license | nier0525/SchoolAssignment | f13f34eb7766ad69977a848844427c9d9277554f | 4b3ffc7828dd18a8cb30514b94b97d0090b87ce7 | refs/heads/main | 2023-03-18T02:57:21.745285 | 2021-03-04T14:51:43 | 2021-03-04T14:51:43 | 344,366,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | h | #pragma once
#include "User.h"
class LoginManager {
private:
ListNode<User*>* UserList;
Node<User*>* SearchUser;
User* NowUser;
static LoginManager* pthis;
LoginManager();
~LoginManager();
public:
static LoginManager* GetInstance();
static void Destory();
User* GetNowUser();
void Init();
void New();
bool Login();
void LogOut();
void Delete();
}; | [
"goja8303@gmail.com"
] | goja8303@gmail.com |
c75f928de8c74e5c06aa5e4ebe794fc6b5c3996e | 53a4b38250794b8745bf0a478e340c94df2e4802 | /projects/compiler-rt/test/asan/TestCases/Posix/stack-use-after-return.cc | 237c880f8e613a9c2e8348521b704d9a7c2c7e90 | [
"NCSA",
"MIT"
] | permissive | steleman/flang7 | 8ac9b0f4c9aa3f3660463c0fa5b191e27806ccc7 | b1835583939b41ba3ef91080498fba12e582340f | refs/heads/master | 2020-05-20T01:09:00.314856 | 2020-01-10T23:45:50 | 2020-01-10T23:45:50 | 185,304,403 | 0 | 0 | NOASSERTION | 2019-05-07T02:17:53 | 2019-05-07T02:17:53 | null | UTF-8 | C++ | false | false | 3,970 | cc | // RUN: %clangxx_asan -O0 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
// RUN: %env_asan_opts=detect_stack_use_after_return=0 %run %t
// Regression test for a CHECK failure with small stack size and large frame.
// RUN: %clangxx_asan -O3 %s -pthread -o %t -DkSize=10000 -DUseThread -DkStackSize=131072 && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck --check-prefix=THREAD %s
//
// Test that we can find UAR in a thread other than main:
// RUN: %clangxx_asan -DUseThread -O2 %s -pthread -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck --check-prefix=THREAD %s
//
// Test the max_uar_stack_size_log/min_uar_stack_size_log flag.
//
// RUN: %env_asan_opts=detect_stack_use_after_return=1:max_uar_stack_size_log=20:verbosity=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK-20 %s
// RUN: %env_asan_opts=detect_stack_use_after_return=1:min_uar_stack_size_log=24:max_uar_stack_size_log=24:verbosity=1 not %run %t 2>&1 | FileCheck --check-prefix=CHECK-24 %s
// This test runs out of stack on AArch64.
// UNSUPPORTED: aarch64
// stack size log lower than expected
// XFAIL: freebsd
// FIXME: Fix this test for dynamic runtime on arm linux.
// UNSUPPORTED: (arm-linux || armhf-linux) && asan-dynamic-runtime
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef kSize
# define kSize 1
#endif
#ifndef UseThread
# define UseThread 0
#endif
#ifndef kStackSize
# define kStackSize 0
#endif
__attribute__((noinline))
char *Ident(char *x) {
fprintf(stderr, "1: %p\n", x);
return x;
}
__attribute__((noinline))
char *Func1() {
char local[kSize];
return Ident(local);
}
__attribute__((noinline))
void Func2(char *x) {
fprintf(stderr, "2: %p\n", x);
*x = 1;
// CHECK: WRITE of size 1 {{.*}} thread T0
// CHECK: #0{{.*}}Func2{{.*}}stack-use-after-return.cc:[[@LINE-2]]
// CHECK: is located in stack of thread T0 at offset
// CHECK: 'local'{{.*}} <== Memory access at offset {{16|32}} is inside this variable
// THREAD: WRITE of size 1 {{.*}} thread T{{[1-9]}}
// THREAD: #0{{.*}}Func2{{.*}}stack-use-after-return.cc:[[@LINE-6]]
// THREAD: is located in stack of thread T{{[1-9]}} at offset
// THREAD: 'local'{{.*}} <== Memory access at offset {{16|32}} is inside this variable
// CHECK-20: T0: FakeStack created:{{.*}} stack_size_log: 20
// CHECK-24: T0: FakeStack created:{{.*}} stack_size_log: 24
}
void *Thread(void *unused) {
Func2(Func1());
return NULL;
}
int main(int argc, char **argv) {
#if UseThread
pthread_attr_t attr;
pthread_attr_init(&attr);
if (kStackSize > 0) {
size_t desired_stack_size = kStackSize;
if (desired_stack_size < PTHREAD_STACK_MIN) {
desired_stack_size = PTHREAD_STACK_MIN;
}
int ret = pthread_attr_setstacksize(&attr, desired_stack_size);
if (ret != 0) {
fprintf(stderr, "pthread_attr_setstacksize returned %d\n", ret);
abort();
}
size_t stacksize_check;
ret = pthread_attr_getstacksize(&attr, &stacksize_check);
if (ret != 0) {
fprintf(stderr, "pthread_attr_getstacksize returned %d\n", ret);
abort();
}
if (stacksize_check != desired_stack_size) {
fprintf(stderr, "Unable to set stack size to %d, the stack size is %d.\n",
(int)desired_stack_size, (int)stacksize_check);
abort();
}
}
pthread_t t;
pthread_create(&t, &attr, Thread, 0);
pthread_attr_destroy(&attr);
pthread_join(t, 0);
#else
Func2(Func1());
#endif
return 0;
}
| [
"stefan.teleman@cavium.com"
] | stefan.teleman@cavium.com |
d74fc193a4bd0a5848eb006d980b44e22bd429e4 | aafa842bd4e19d0c4b49d82777015322d5f28302 | /Curseur.h | 39518a0da8e1035d9309a28e673ac5e090e6fe13 | [] | no_license | carodak/Gomoku | b967aeb915835c593ecd56b1bdc81b1dbc2530a3 | a30ecb9e770490aa76828392933b223d106845b3 | refs/heads/master | 2021-06-27T23:25:33.081315 | 2020-09-11T21:58:45 | 2020-09-11T21:58:45 | 151,996,493 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | h | #ifndef CURSEUR_H
#define CURSEUR_H
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "Cellule.h"
#include "Pions.h"
class Curseur
{
public:
Curseur(sf::Event &event);
//Accesseurs en lecture
float getX() const;
float getY() const;
//Accesseurs en écriture
void setX(sf::Event);
void setY(sf::Event);
//Autres
void Pion_cree_apres_click(Pions &, sf::Event, sf::RenderWindow &, Cellule &,int &, bool&, bool&);
void playsound(int);
void restriction(Pions &,sf::RenderWindow&,Cellule&);
private:
float position_souris_x; //Coordonnées du curseur dans la fenêtre de jeu
float position_souris_y;
};
#endif // CURSEUR_H
| [
"xialah@MacBook-Pro.local"
] | xialah@MacBook-Pro.local |
16e1b53ade3ff3282879353184c63f45e37dad40 | fad7ec9c943f951cbf49f21de2a0fc2b45dd8523 | /src/engine/core/InputHandler.cpp | 1379f184f8ce32e53833d5d470a35776c0c546fb | [] | no_license | templeblock/GraphicEngine | 962c5bc97ab4c1a9253352275904115c48d8dcfc | 1f8abf39e709dbe0a281fb1e343a1a2736d4eb4a | refs/heads/master | 2022-11-23T06:56:58.574532 | 2020-07-30T20:33:31 | 2020-07-30T20:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,870 | cpp | #include "InputHandler.h"
std::vector<MouseButton> InputHandler::mouseButtonListeners;
std::vector<MousePressed> InputHandler::mousePressedListeners;
std::vector<MouseRelease> InputHandler::mouseReleaseListeners;
std::vector<CursorPosition> InputHandler::cursorPositionListeners;
std::vector<CursorOffset> InputHandler::cursorOffsetListeners;
std::vector<KeyPressed> InputHandler::keyPressedListeners;
std::vector<ScrollOffset> InputHandler::scrollOffsetListeners;
std::vector<CharacterCode> InputHandler::charactersListeners;
std::vector<PathDrop> InputHandler::dropListeners;
bool InputHandler::buttons[8];
bool InputHandler::keys[512];
double InputHandler::x, InputHandler::y;
bool InputHandler::updated = false;
void InputHandler::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if (action == GLFW_RELEASE && keys[key]) {
for (const auto &listener: keyPressedListeners) {
listener(key);
}
}
keys[key] = action != GLFW_RELEASE;
}
void InputHandler::characterCallback(GLFWwindow* window, unsigned int codepoint) {
for(const auto &listener: charactersListeners) {
listener(codepoint);
}
}
void InputHandler::cursorPositionCallback(GLFWwindow* window, double xpos, double ypos) {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
ypos = height - ypos;
for (const auto &listener: cursorPositionListeners) {
listener(xpos, ypos);
}
if (InputHandler::updated) {
for (const auto &listener: cursorOffsetListeners) {
listener(xpos-x, y-ypos);
}
}
InputHandler::x = xpos;
InputHandler::y = ypos;
InputHandler::updated = true;
}
void InputHandler::mouseButtonCallback(GLFWwindow *window, int btn, int action, int mods) {
if (action == GLFW_RELEASE && buttons[btn]) {
for(const auto &listener: mousePressedListeners) {
listener(InputHandler::x, InputHandler::y);
}
}
if (action == GLFW_PRESS && !buttons[btn]) {
for(const auto &listener: mouseButtonListeners) {
listener(InputHandler::x, InputHandler::y);
}
}
if (action == GLFW_RELEASE && buttons[btn]) {
for(const auto &listener: mouseReleaseListeners) {
listener(InputHandler::x, InputHandler::y);
}
}
buttons[btn] = action != GLFW_RELEASE;
}
void InputHandler::scrollCallback(GLFWwindow* window, double xoffset, double yoffset) {
for(const auto &listener: scrollOffsetListeners) {
listener(xoffset, yoffset);
}
}
void InputHandler::dropCallback(GLFWwindow* window, int count, const char **paths) {
for (int i = 0; i < count; ++i) {
BOOST_LOG_TRIVIAL(info) << "Dropped path: " <<paths[i];
for (const auto &listener: dropListeners) {
listener(paths[i]);
}
}
}
| [
"przemekpapla@gmail.com"
] | przemekpapla@gmail.com |
db8d8158186846e466d08cae3b6d24ed88674eab | fafce52a38479e8391173f58d76896afcba07847 | /uppsrc/ide/Update.cpp | 9bb7ef9c6a001c46cd569f55036d97064b6772e7 | [
"BSD-2-Clause"
] | permissive | Sly14/upp-mirror | 253acac2ec86ad3a3f825679a871391810631e61 | ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7 | refs/heads/master | 2020-05-17T08:25:56.142366 | 2015-08-24T18:08:09 | 2015-08-24T18:08:09 | 41,750,819 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 962 | cpp | #include "ide.h"
#define LLOG(x) //RLOG(x)
#define LDUMP(x) //RDUMP(x)
#ifdef PLATFORM_POSIX
GLOBAL_VAR(UpdaterConfig,UpdaterCfg);
void Ide::CheckUpdates(bool verbose){
LLOG("CheckUpdates, verbose="<<verbose);
if(verbose){
su.NeedsUpdate(true);
SetBar();
}else{
su.WhenUpdateAvailable=THISBACK(SetBar);
su.CheckUpdates();
}
}
void Ide::CheckUpdatesManual(){
int tmp=UpdaterCfg().ignored;
UpdaterCfg().ignored=0;
su.ClearError();
if(su.NeedsUpdate(true)){
su.Execute();
}else{
String err=su.GetError();
if(err=="CANCEL") return;
if(!err.IsEmpty()){
Exclamation("Unable to check for updates. "+err);
}else{
PromptOK("No update found. You are using version "+su.GetLocal()+".");
}
UpdaterCfg().ignored=tmp;
}
SetBar();
}
void Ide::SetUpdateTimer(int period){
LLOG("SetUpdateTimer, period="<<period);
PostCallback(THISBACK1(CheckUpdates,false));
SetTimeCallback(-60000*period,THISBACK1(CheckUpdates,false));
}
#endif
| [
"dolik@05275033-79c2-2956-22f4-0a99e774df92"
] | dolik@05275033-79c2-2956-22f4-0a99e774df92 |
ad770dd495c7b9bdd5fc3d690a42518e9e212392 | 6f5379f9dc222a2b409cdf54ac62617e988e7754 | /TCP/Draft/Connet_tcp thread/Custom/Custom/mythread.h | 56b87573692cd7e7e07ddfbfdd9ac2754c0c69f8 | [] | no_license | ToSaySomething/Leaning | b581379b9bf572682bd45ac11c5a315552cea51f | 523e040f16a6de3d4bf2e5de8a1e65fd1a7ff4e8 | refs/heads/master | 2020-03-28T11:57:04.180983 | 2018-09-12T02:50:27 | 2018-09-12T02:50:27 | 148,258,479 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 199 | h | #ifndef MYTHREAD_H
#define MYTHREAD_H
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include <iostream>
class ThreadRunnable : public Poco::Runnable
{
void run();
};
#endif // MYTHREAD_H
| [
"dengyuting@cloudwalk.cn"
] | dengyuting@cloudwalk.cn |
ab51ab12768e29f769574a96eecbe733c83ca2aa | 40fbcd5e1160a77e3e694476c68439638b7fc139 | /objectDetection/objectDetection.cpp | d5f2265612d7d6583831731f6919d5c2b74a1919 | [
"Apache-2.0"
] | permissive | yaodix/stereoTracking | 6bfdc7e72f86b669f3346f77cc2a798794c16964 | d7f72fd743666b640f0577d1cca2dc5877623430 | refs/heads/main | 2023-03-18T10:16:50.066856 | 2021-03-14T10:03:24 | 2021-03-14T10:03:24 | 347,580,692 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,404 | cpp | // objectDetection.cpp : 建立双目相机坐标系与舵机坐标系映射关系,并标定舵机工作频率和运动角度。
#include <opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
Point2f center(Mat &img, double threshValueOfCircle);
int stereoImgCap()
{
VideoCapture cam1;
VideoCapture cam2;
Mat frame1,frame2;
cam1.open(1);
cam2.open(0);
while (1)
{
cam1 >> frame1;
cam2 >> frame2;
cout << center(frame1, 0.75) << " ";
cout << center(frame2, 0.75) << endl;
imshow("frame1", frame1);
imshow("frame2", frame2);
if (waitKey(100) == 27)
{
return 0;
}
}
return 0;
}
// 圆形目标提取
Point2f center(Mat &img, double threshValueOfCircle)
{
Mat gray,threImg;
Mat morTmp1, morTmp2;
Point2f center;
cvtColor(img, gray, CV_BGR2GRAY);
threshold(gray, threImg, 20, 255, CV_THRESH_BINARY_INV);
Mat mor1 = getStructuringElement(MORPH_RECT, Size(5, 5));
Mat mor2 = getStructuringElement(MORPH_RECT, Size(13, 13));
morphologyEx(threImg, morTmp1, MORPH_DILATE, mor1);
morphologyEx(morTmp1, morTmp2, MORPH_ERODE, mor2);
//morphologyEx(tmpH2, tmpH3, MORPH_ERODE, mor1);
//morphologyEx(tmpH3, morphOut1,MORPH_DILATE , mor1);
vector<Vec4i> v4i;
double area, len;
vector<vector<Point>> contours, vecCircleRes;
findContours(morTmp2, contours, v4i, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
for (int i = 0; i < contours.size(); i++)
{
area = contourArea(contours[i]);
len = arcLength(contours[i], true);
double ratio = (4 * CV_PI*area) / (len*len);
if (ratio>threshValueOfCircle&& area > 1000)
{
vecCircleRes.push_back(contours[i]);
}
}
Moments mome;
if (vecCircleRes.size() > 0)
{
mome = moments(vecCircleRes[0]);
center=Point2f(mome.m10 / mome.m00, mome.m01 / mome.m00);
circle(img, center, 3, Scalar(0, 0, 255));
drawContours(img, vecCircleRes, -1, Scalar(0, 0, 255));
}
return center;
}
void transformPosToServoFrameAndSend(Vec3d camPos);
int main()
{
Vec3d pos1(0, 0, 64),pos2(0,1,0),pos3(-10,-100,100);
transformPosToServoFrameAndSend(pos1);
//transformPosToServoFrameAndSend(pos2);
//transformPosToServoFrameAndSend(pos3);
return 0;
}
void transformPosToServoFrameAndSend(Vec3d camPos)
{
Mat objPosMat = Mat_<float>(4, 1);
Mat camPosMat = (Mat_ < float>(4, 1) << camPos[0], camPos[1], camPos[2], 1);
Mat rotateX_90 = (Mat_<double>(3, 3) << 1, 0, 0,
0, 0, 1,
0, -1, 0);
Mat rotateZ_90 = (Mat_<double>(3, 3) << 0, 1, 0,
-1, 0, 0,
0, 0, 1);
Mat rotation = rotateZ_90*rotateX_90;
Mat camFrame2ServoFrame = (Mat_<float>(4, 4) <<
rotation.at<double>(0, 0), rotation.at<double>(0, 1), rotation.at<double>(0, 2), 15,
rotation.at<double>(1, 0), rotation.at<double>(1, 1), rotation.at<double>(1, 2), -90,
rotation.at<double>(2, 0), rotation.at<double>(2, 1), rotation.at<double>(2, 2), 135,
0, 0, 0, 1);
objPosMat = camFrame2ServoFrame*camPosMat;
//发送指令给云台
int laserHeight = 50;
int horAngle, verAngle;
int x = objPosMat.at<float>(0, 0);
int y = objPosMat.at<float>(1, 0);
int z = objPosMat.at<float>(2, 0);
horAngle = (atan2(y, x) / CV_PI) * 180;
verAngle = (atan2(z - laserHeight, sqrtf(x*x + y*y)) / CV_PI) * 180;
//角度转换为舵机旋转频率
int horHZ = 700 + 4.55* horAngle;//水平方向舵机,每度频率变换5个占空比,角度方向为负
int verHz = 700 - 4.55*verAngle;
cout << objPosMat << endl;
} | [
"liuyao199111@163.com"
] | liuyao199111@163.com |
26d72e3fa1d2af1d6fea074bcd90fba1e4de3d13 | 93472455504e51c40e9807e32187a633d0964b86 | /executor.cpp | 0397228d39f311bce1661d69ec8b3b308b1a0b83 | [] | no_license | guohengkai/yaush | bffa4f0f07cbe325df3732306d7b554cd5dfed56 | 6b8381e2d85fa9b156d89b80ff78c84910f526c8 | refs/heads/master | 2016-09-06T00:37:29.026805 | 2015-06-13T06:11:23 | 2015-06-13T06:11:23 | 35,334,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,764 | cpp | /*************************************************************************
> File Name: executor.cpp
> Author: Guo Hengkai
> Description: Command executor class implementation for YAUSH
> Created Time: Sun 17 May 2015 03:27:19 PM CST
************************************************************************/
#include "executor.h"
#include <cstring>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <queue>
#include <vector>
#include "command_registry.h"
#include "common.h"
#include "error_util.h"
#include "job_handler.h"
using std::string;
using std::queue;
using std::vector;
namespace ghk
{
Executor::Executor()
{
}
FuncStatus Executor::Execute(const vector<CommandGroup> &command_list)
{
bool is_execute = true;
for (auto group: command_list)
{
FuncStatus flag = FuncStatus::Error;
if (is_execute)
{
flag = Execute(group.cmd, group.str,
group.logic == CommandLogic::Background);
}
if ((flag == FuncStatus::Success && group.logic == CommandLogic::Or)
|| (flag == FuncStatus::Error && group.logic == CommandLogic::And))
{
is_execute = false;
string info = (group.logic == CommandLogic::Or ? "OR" : "AND");
LogDebug("%s triggered.", info.c_str());
}
else
{
is_execute = true;
}
}
return FuncStatus::Success;
}
FuncStatus Executor::Execute(const vector<Command> &cmds,
const string &str, bool is_bg)
{
if (cmds.empty())
{
return FuncStatus::Success;
}
JobHandler *handler = JobHandler::GetInstance();
CommandRegistry *registry = CommandRegistry::GetInstance();
int pipes[cmds.size() - 1][2];
for (size_t i = 0; i < cmds.size() - 1; ++i)
{
if (pipe(pipes[i]) < 0)
{
ErrorPrint(ShellError::PipeCreation, cmds[i].name);
return FuncStatus::Error;
}
}
Job current_job;
current_job.status = JobStatus::Running;
current_job.cmd = str;
for (int i = static_cast<int>(cmds.size()) - 1; i >= 0; --i) // Reversely connect pipes
{
int pid = fork();
if (pid > 0) // parent
{
current_job.pids.push_back(pid);
}
else if (pid == 0) // child
{
// Input
if (cmds[i].io_type[0] == CommandIOType::Pipe)
{
dup2(pipes[i - 1][0], STDIN_FILENO);
LogDebug("command %s duplicate pipe to stdin",
cmds[i].name.c_str());
}
else if (cmds[i].io_type[0] == CommandIOType::File)
{
for (auto name: cmds[i].io_file_name[0])
{
int fid = open(name.c_str(), O_RDONLY);
if (fid == -1)
{
ErrorPrint(ShellError::FileError, name);
exit(-1);
}
dup2(fid, STDIN_FILENO);
close(fid);
LogDebug("command %s duplicate %s to stdin",
cmds[i].name.c_str(), name.c_str());
}
}
// Output
if (cmds[i].io_type[1] == CommandIOType::Pipe)
{
dup2(pipes[i][1], STDOUT_FILENO);
LogDebug("command %s duplicate pipe to stdout",
cmds[i].name.c_str()); // Must use stderr
}
else if (cmds[i].io_type[1] == CommandIOType::File)
{
for (auto name: cmds[i].io_file_name[1])
{
int fid = open(name.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fid == -1)
{
ErrorPrint(ShellError::FileError, name);
exit(-1);
}
dup2(fid, STDOUT_FILENO);
close(fid);
LogDebug("command %s duplicate %s to stdout",
cmds[i].name.c_str(), name.c_str());
}
}
// Close all the pipe descriptors
for (size_t j = 0; j < cmds.size() - 1; ++j)
{
close(pipes[j][0]);
close(pipes[j][1]);
}
// Execute the command
if (registry->IsCommandMain(cmds[i].name))
{
exit(0);
}
auto status = registry->ExecuteCommand(cmds[i].name,
cmds[i].arg_list);
if (status == CmdStatus::Notfound) // System command
{
char *argv[cmds[i].arg_list.size() + 1];
for (size_t j = 0; j < cmds[i].arg_list.size(); ++j)
{
argv[j] = const_cast<char*>(cmds[i].arg_list[j].c_str());
}
argv[cmds[i].arg_list.size()] = NULL;
int flag = execvp(cmds[i].name.c_str(), argv);
if (flag < 0)
{
ErrorPrint(ShellError::ExecError,
cmds[i].name + ": " + strerror(errno));
exit(-1);
}
}
else if (status == CmdStatus::Fail)
{
ErrorPrint(ShellError::ExecError,
cmds[i].name + ": " + registry->error_info());
exit(-1);
}
else
{
exit(0);
}
}
else // fail to fork
{
ErrorPrint(ShellError::ForkFail, cmds[i].name);
return FuncStatus::Error;
}
}
// Close all the pipe descriptors
for (size_t i = 0; i < cmds.size() - 1; ++i)
{
close(pipes[i][0]);
close(pipes[i][1]);
}
if (is_bg) // background
{
int job_num = handler->InsertBackgroundJob(current_job);
handler->PrintJob(job_num);
}
else // foreground
{
handler->fg_job = current_job;
auto &pid_list = handler->fg_job.pids;
bool is_success = true;
while (!pid_list.empty())
{
auto pid = pid_list.front();
int status;
int val = waitpid(pid, &status, 0);
if (val > 0)
{
LogDebug("process %d is waited successfully", pid);
if (!WIFEXITED(status)
|| (WIFEXITED(status) && WEXITSTATUS(status) != 0))
{
is_success = false;
}
}
else if (errno == ECHILD) // pid not found
{
LogDebug("process %d not found", pid);
is_success = false;
}
else
{
ErrorPrint(ShellError::UnknownError, "waitpid");
is_success = false;
}
pid_list.pop_front();
}
if (cmds.size() == 1 && registry->IsCommandMain(cmds[0].name))
{
auto status = registry->ExecuteCommand(cmds[0].name,
cmds[0].arg_list);
if (status == CmdStatus::Fail)
{
ErrorPrint(ShellError::ExecError,
cmds[0].name + ": " + registry->error_info());
return FuncStatus::Error;
}
}
if (!is_success)
{
return FuncStatus::Error;
}
}
return FuncStatus::Success;
}
} // namespace ghk
| [
"guohengkaighk@gmail.com"
] | guohengkaighk@gmail.com |
4a8ad9b326306f7477c12837cb090c8055309bfd | 0dca3325c194509a48d0c4056909175d6c29f7bc | /dms-enterprise/src/model/ListSQLReviewOriginSQLResult.cc | df4196fbc7079bd810b6d06ab9ed6c4ff24accba | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,025 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/dms-enterprise/model/ListSQLReviewOriginSQLResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dms_enterprise;
using namespace AlibabaCloud::Dms_enterprise::Model;
ListSQLReviewOriginSQLResult::ListSQLReviewOriginSQLResult() :
ServiceResult()
{}
ListSQLReviewOriginSQLResult::ListSQLReviewOriginSQLResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListSQLReviewOriginSQLResult::~ListSQLReviewOriginSQLResult()
{}
void ListSQLReviewOriginSQLResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allOriginSQLListNode = value["OriginSQLList"]["OriginSQLListItem"];
for (auto valueOriginSQLListOriginSQLListItem : allOriginSQLListNode)
{
OriginSQLListItem originSQLListObject;
if(!valueOriginSQLListOriginSQLListItem["SQLId"].isNull())
originSQLListObject.sQLId = std::stol(valueOriginSQLListOriginSQLListItem["SQLId"].asString());
if(!valueOriginSQLListOriginSQLListItem["FileId"].isNull())
originSQLListObject.fileId = std::stol(valueOriginSQLListOriginSQLListItem["FileId"].asString());
if(!valueOriginSQLListOriginSQLListItem["FileName"].isNull())
originSQLListObject.fileName = valueOriginSQLListOriginSQLListItem["FileName"].asString();
if(!valueOriginSQLListOriginSQLListItem["SQLContent"].isNull())
originSQLListObject.sQLContent = valueOriginSQLListOriginSQLListItem["SQLContent"].asString();
if(!valueOriginSQLListOriginSQLListItem["CheckStatus"].isNull())
originSQLListObject.checkStatus = valueOriginSQLListOriginSQLListItem["CheckStatus"].asString();
if(!valueOriginSQLListOriginSQLListItem["StatusDesc"].isNull())
originSQLListObject.statusDesc = valueOriginSQLListOriginSQLListItem["StatusDesc"].asString();
if(!valueOriginSQLListOriginSQLListItem["CheckedTime"].isNull())
originSQLListObject.checkedTime = valueOriginSQLListOriginSQLListItem["CheckedTime"].asString();
if(!valueOriginSQLListOriginSQLListItem["SqlHash"].isNull())
originSQLListObject.sqlHash = valueOriginSQLListOriginSQLListItem["SqlHash"].asString();
if(!valueOriginSQLListOriginSQLListItem["ReviewSummary"].isNull())
originSQLListObject.reviewSummary = valueOriginSQLListOriginSQLListItem["ReviewSummary"].asString();
if(!valueOriginSQLListOriginSQLListItem["SQLReviewQueryKey"].isNull())
originSQLListObject.sQLReviewQueryKey = valueOriginSQLListOriginSQLListItem["SQLReviewQueryKey"].asString();
originSQLList_.push_back(originSQLListObject);
}
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
if(!value["ErrorMessage"].isNull())
errorMessage_ = value["ErrorMessage"].asString();
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["TotalCount"].isNull())
totalCount_ = std::stoi(value["TotalCount"].asString());
}
int ListSQLReviewOriginSQLResult::getTotalCount()const
{
return totalCount_;
}
std::string ListSQLReviewOriginSQLResult::getErrorCode()const
{
return errorCode_;
}
std::string ListSQLReviewOriginSQLResult::getErrorMessage()const
{
return errorMessage_;
}
std::vector<ListSQLReviewOriginSQLResult::OriginSQLListItem> ListSQLReviewOriginSQLResult::getOriginSQLList()const
{
return originSQLList_;
}
bool ListSQLReviewOriginSQLResult::getSuccess()const
{
return success_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
f6400b46c51ee873966fea8514a37c888773b2c1 | f76bc8ad904513df8a812ec8f9b81894a5850518 | /proj.win32/Classes/Pawn.cpp | b97d1e9408806c3829b6fb252b2d9f1038320d38 | [] | no_license | bartlomiejwolk/MetroidPacMan | c30735d63a7fa73de33a2ddee155a1419507826c | 27fc3bc1f11a824db349883d445a3a0c32434040 | refs/heads/master | 2021-07-09T02:58:18.988039 | 2019-05-30T16:10:54 | 2019-05-30T16:10:54 | 183,427,106 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | #include "Pawn.h"
#include "cocos2d.h"
#include "Utils.h"
USING_NS_CC;
Pawn::Pawn(SpriteFrameCache* frameCache)
{
m_SpriteFrameCache = frameCache;
}
Pawn::~Pawn()
{
}
void Pawn::CreateSprite()
{
// intentionally left empty
}
void Pawn::MoveToPoint(Vec2 point)
{
// TODO magic number
MoveTo* moveToAction = MoveTo::create(0.3f, point);
auto callback = CallFunc::create([this]() { Pawn::TargetPointReached.emit(); });
auto sequence = Sequence::create(moveToAction, callback, nullptr);
m_PawnSprite->runAction(sequence);
}
| [
"bartlomiejwolk@gmail.com"
] | bartlomiejwolk@gmail.com |
085ebc07e08990451e76a6a1d35d5ba2e7919144 | bf9efdf9c30b8730d7e0aa2cbdcf2045fa14bcec | /arduino/ros_lib/asv_msgs/Heading.h | 9cf6f03dd256b878aaec12b9340ed7a033584810 | [
"MIT"
] | permissive | championway/asv_ros | d91ae81853904302300df0ef442436774a519a00 | 4ded50c48077e1e63586cd32be2354633c163975 | refs/heads/master | 2023-07-08T18:47:15.759512 | 2021-08-10T17:48:23 | 2021-08-10T17:48:23 | 215,058,858 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,485 | h | #ifndef _ROS_asv_msgs_Heading_h
#define _ROS_asv_msgs_Heading_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace asv_msgs
{
class Heading : public ros::Msg
{
public:
typedef float _phi_type;
_phi_type phi;
typedef float _speed_type;
_speed_type speed;
Heading():
phi(0),
speed(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
union {
float real;
uint32_t base;
} u_phi;
u_phi.real = this->phi;
*(outbuffer + offset + 0) = (u_phi.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_phi.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_phi.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_phi.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->phi);
union {
float real;
uint32_t base;
} u_speed;
u_speed.real = this->speed;
*(outbuffer + offset + 0) = (u_speed.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_speed.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_speed.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_speed.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->speed);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
union {
float real;
uint32_t base;
} u_phi;
u_phi.base = 0;
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_phi.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->phi = u_phi.real;
offset += sizeof(this->phi);
union {
float real;
uint32_t base;
} u_speed;
u_speed.base = 0;
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_speed.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->speed = u_speed.real;
offset += sizeof(this->speed);
return offset;
}
const char * getType(){ return "asv_msgs/Heading"; };
const char * getMD5(){ return "8fe8a91eef3de9ae7860b3f07a1529db"; };
};
}
#endif | [
"cpwearth.eed03@g2.nctu.edu.tw"
] | cpwearth.eed03@g2.nctu.edu.tw |
a425505928a38703ce15162f0f61d059cd7d654a | 9300cbc7fd196b7f503783e1280f7bf263ebacc9 | /robot/Patte.cpp | 932848f92554f08b4051542cdfd15cd2b01c16ac | [] | no_license | cipion/Porjet_Hexapod | 604233ef35d38d272dfa099bc9d77cb92ec0e4d5 | ad6f6c629f434430893b0398da988435a056be61 | refs/heads/master | 2020-03-29T14:41:09.238379 | 2015-01-22T20:28:58 | 2015-01-22T20:28:58 | 27,351,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,702 | cpp | #include "Patte.h"
#define M_Pi 3.14159265359
Patte::Patte()
{
}
Patte::~Patte()
{}
Patte::Patte(SerialRPi liaison, int Step, char IDCoxa, char IDFemur, char IDTibia) {
initStep = Step;
step = Step;
servoCoxa = new AX12(liaison, IDCoxa);
servoFemur = new AX12(liaison, IDFemur);
servoTibia = new AX12(liaison, IDTibia);
}
bool Patte::testAngle(int angle) {
return ( (angle >= 0) && (angle < 360) );
}
bool Patte::testLongueur(double longueur) {
return ( (longueur >= 0) && (longueur <= Robot.LONGUEUR_MAX) );
}
void Patte::setPosAll(char PosCoxa, char PosFemur, char PosTibia)
{
setPosCoxa(PosCoxa);
setPosFemur(PosFemur);
setPosTibia(PosTibia);
}
void Patte::setPosAll(char PosCoxa, char PosFemur, char PosTibia, char vitesse)
{
setPosCoxa(PosCoxa, vitesse);
setPosFemur(PosFemur, vitesse);
setPosTibia(PosTibia, vitesse);
}
void Patte::setGroundAll() {
if(step > (Robot.STEP_MAX/2))
;// TODO
}
void Patte::upDateDroiteMov(int angle, double longueur, char vitesse)
{
if(!testAngle(angle))
std::cout<<"Erreur angle droite mouvement : " << angle<< std::endl;
if(!testLongueur(longueur))
std::cout<<"Erreur longueur droite mouvement : " << longueur<< std::endl;
StructPatte w_position;
if(longueur != 0)
w_position = getPoint(angle, longueur);
else
w_position = getPointMiddle();
servoCoxa.setPositionExtrapol(w_position.getAngleCoxa(), vitesse);
servoFemur.setPositionExtrapol(w_position.getAngleFemur(), vitesse);
servoTibia.setPositionExtrapol(w_position.getAngleTibia(), vitesse);
step++;
if(step > Robot.STEP_MAX)
step = 0;
}
void Patte::setPosCoxa(char position)
{
if((position < 405) || (position > 620))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoCoxa.setPosition(position);
}
void Patte::setPosCoxa(char position, char vitesse)
{
if((position < 405) || (position > 620))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoCoxa.setPositionExtrapol(position, vitesse);
}
void Patte::setPosFemur(char position)
{
if((position < 300) || (position > 700))
std::cout<<"Erreur angle servomoteur Femur : " << (int)position<< std::endl;
servoFemur.setPosition(position);
}
void Patte::setPosFemur(char position, char vitesse)
{
if((position < 300) || (position > 700))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoFemur.setPositionExtrapol(position, vitesse);
}
void Patte::setPosTibia(char position)
{
if((position < 220) || (position > 710))
std::cout<<"Erreur angle servomoteur Tibia : " <<(int)position<< std::endl;
servoTibia.setPosition(position);
}
void Patte::setPosTibia(char position, char vitesse)
{
if((position < 220) || (position > 710))
std::cout<<"Erreur angle servomoteur Coxa : " << (int)position<< std::endl;
servoTibia.setPositionExtrapol(position, vitesse);
}
void Patte::resetStep() {
step = initStep;
}
static StructPatte Patte::upPatte(StructPatte position) {
position.setAngleFemur((char)(position.getAngleFemur() - Robot.VAL_UP_PATTE));
//position.setAngleTibia((char)(position.getAngleTibia() - Robot.VAL_UP_PATTE));
return position;
}
static StructPatte Patte::getPointMiddle() {
return new StructPatte((char)512, (char)575, (char)362);
}
static StructPatte Patte::getPointTop(int angle, double longueur) {
double longueurDemiCarre = ((longueur / 2) * (longueur / 2));
double w_dist1 = sqrt( longueurDemiCarre + 19321 - (longueur * 139 * cos((M_Pi *(angle)) / 180)) );
double w_dist2 = sqrt( ((w_dist1 - 52) * (w_dist1 - 52)) + 13225 );
char angleCoxa;
if(angle > 180)
angleCoxa = (char)(512 + (((180 * (acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) ))/ M_Pi) * 256) / 75));
else
angleCoxa = (char)(512 - (((180 * (acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) )) / M_Pi) * 256) / 75));
char angleFemur = (char)(556 + ((((180 * (acos( ((w_dist2 * w_dist2) - 13200) / (134 * w_dist2) ))/ M_Pi + 180 * (Math.acos(115 / w_dist2))/ M_Pi ) - 90) * 256) / 75));
char angleTibia = (char)(512 - (((138 - 180 *(acos( (22178 - (w_dist2 * w_dist2)) / 17822 ))/ M_Pi) * 256) / 75));
return new StructPatte(angleCoxa, angleFemur, angleTibia);
}
static Patte::StructPatte getPointBottom(int angle, double longueur) {
double longueurDemiCarre = ((longueur / 2) * (longueur / 2));
double w_dist1 = sqrt( longueurDemiCarre + 19321 - (longueur * 139 * cos(M_Pi *(180-angle) / 180)) );
double w_dist2 = sqrt( ((w_dist1 - 52) * (w_dist1 - 52)) + 13225 );
char angleCoxa;
if(angle > 180)
angleCoxa = (char)(512 - (((180 *(acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) ))/ M_Pi) * 256) / 75));
else
angleCoxa = (char)(512 + (((180 *(acos( (((w_dist1 * w_dist1) + 19321 - longueurDemiCarre) / (2 * 139 * w_dist1)) ))/ M_Pi) * 256) / 75));
char angleFemur = (char)(556 + ((((180 * (acos( ((w_dist2 * w_dist2) - 13200) / (134 * w_dist2) ))/ M_Pi + 180 * (Math.acos(115 / w_dist2))/ M_Pi ) - 90) * 256) / 75));
char angleTibia = (char)(512 - (((138 - 180 *(acos( (22178 - (w_dist2 * w_dist2)) / 17822 ))/ M_Pi) * 256) / 75));
return new StructPatte(angleCoxa, angleFemur, angleTibia);
}
StructPatte Patte::getPoint(int angle, double longueur) {
int demiStep = (Robot.STEP_MAX/2);
int quartStep = (Robot.STEP_MAX/4);
int w_step = abs(step - demiStep);
StructPatte w_middle = getPointMiddle();
StructPatte w_extrem;
if(w_step < quartStep)
{
w_extrem = getPointTop(angle, longueur);
}
else if(w_step > quartStep)
{
w_step = demiStep - w_step;
w_extrem = getPointBottom(angle, longueur);
}
else
{
if((step > demiStep) && (step < Robot.STEP_MAX))
return upPatte(w_middle);
else
return w_middle;
}
StructPatte w_position = new StructPatte((char)( (((quartStep - w_step) * w_extrem.getAngleCoxa()) + (w_step * w_middle.getAngleCoxa())) / quartStep ),
(char)( (((quartStep - w_step) * w_extrem.getAngleFemur()) + (w_step * w_middle.getAngleFemur())) / quartStep ),
(char)( (((quartStep - w_step) * w_extrem.getAngleTibia()) + (w_step * w_middle.getAngleTibia())) / quartStep ));
// On leve la patte pour pisser
if((step > demiStep) && (step < Robot.STEP_MAX))
w_position = upPatte(w_position);
return w_position;
}
| [
"thomas.gache@yahoo.fr"
] | thomas.gache@yahoo.fr |
d0b1e17638e74e21d6280ef192a072f3b9baeb92 | 8d74ac4708e6c58662ca2daa18f4af86d138c719 | /CSGO_Multihack/CSGO_Multihack/Hooks.h | 9e9d2635bc0d98b00701215cf78f0f3b05dd9ecb | [] | no_license | mr-nv/phantomhack | 760bcc6bd54ba37d77414e674c2a7a46e179fb73 | bf9a8b221fc5c62171517cb71744ce391bc53e3a | refs/heads/master | 2023-02-26T10:34:28.705391 | 2021-02-02T18:31:36 | 2021-02-02T18:31:36 | 335,384,137 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,676 | h | #pragma once
/*
Type: Namespace
Name: Hooks
Intended for: Hooked Source Engine functions
*/
#include "sdk/include/valve_sdk/csgostructs.hpp"
#include "sdk/include/helpers/vfunc_hook.hpp"
#include "globals.h"
#include <d3d9.h>
namespace index
{
constexpr auto PaintTraverse = 41;
constexpr auto CreateMove = 21;
constexpr auto PlaySound = 82;
constexpr auto FrameStageNotify = 36;
constexpr auto DrawModelExecute = 21;
constexpr auto DoPostScreenSpaceEffects = 44;
constexpr auto EndScene = 42;
constexpr auto Reset = 16;
constexpr auto DrawIndexedPrimitive = 82;
constexpr auto SetCrosshairAngle = 29;
constexpr auto OverrideView = 18;
constexpr auto GetViewModelFOV = 35;
constexpr auto ShouldDrawViewModel = 27;
}
namespace Hooks
{
void Initialize();
void Shutdown();
extern vfunc_hook hlclient_hook;
extern vfunc_hook vguipanel_hook;
extern vfunc_hook vguisurf_hook;
extern vfunc_hook mdlrender_hook;
extern vfunc_hook viewrender_hook;
extern vfunc_hook renderveiw_hook;
extern vfunc_hook d3d_hook;
using CreateMove = void(__thiscall*)(IBaseClientDLL*, int, float, bool);
using PaintTraverse = void(__thiscall*)(IPanel*, vgui::VPANEL, bool, bool);
using FrameStageNotify = void(__thiscall*)(IBaseClientDLL*, ClientFrameStage_t);
using PlaySound = void(__thiscall*)(ISurface*, const char* name);
using DrawModelExecute = void(__thiscall*)(IVModelRender*, IMatRenderContext*, const DrawModelState_t&, const ModelRenderInfo_t&, matrix3x4_t*);
using FireEvent = bool(__thiscall*)(IGameEventManager2*, IGameEvent* pEvent);
using DoPostScreenEffects = int(__thiscall*)(IClientMode*, int);
using SetCrosshairAngle = void(__thiscall*)(const QAngle&);
using OverrideView_t = void(__thiscall*)(void*,CViewSetup* view);
using GetViewModelFOV_t = float(__thiscall*)(void*);
using ShouldDrawViewModel_t = bool(__thiscall*)(void*);
void __stdcall hkCreateMove(int sequence_number, float input_sample_frametime, bool active, bool& bSendPacket);
void __stdcall hkCreateMove_Proxy(int sequence_number, float input_sample_frametime, bool active);
void __stdcall hkPaintTraverse(vgui::VPANEL panel, bool forceRepaint, bool allowForce);
void __stdcall hkPlaySound(const char* name);
void __stdcall hkDrawModelExecute(IMatRenderContext* ctx, const DrawModelState_t& state, const ModelRenderInfo_t& pInfo, matrix3x4_t* pCustomBoneToWorld);
void __stdcall hkFrameStageNotify(ClientFrameStage_t stage);
int __stdcall hkDoPostScreenEffects(int a1);
void __fastcall hkOverrideView(void* ecx, void* edx, CViewSetup* view);
float __fastcall hkGetViewModelFOV(void* ecx, void* edx);
bool __fastcall hkShouldDrawViewModel(void* ecx, void* edx);
}
| [
"31269663+mr-nv@users.noreply.github.com"
] | 31269663+mr-nv@users.noreply.github.com |
67da957bc6b3ee2a27b9666c51168a014489c837 | 5dbe920ec7584281c75843d64c7b22ae608ba4ef | /analysis/higgs_analysis/isLoosePP.cc | 9754f4056e098039e1974ee73e1de0d31e083d0d | [] | no_license | jodier/atlas_HiggsAnalysis2 | f4f60f8052137846038c91070b206a139d8ffd8b | 28dcbca9126112c21073a4bb554a47afa22aff2c | refs/heads/master | 2021-01-01T18:33:47.933912 | 2012-04-25T13:37:57 | 2012-04-25T13:37:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,146 | cc | /*-------------------------------------------------------------------------*/
#include "utils.h"
#include <HiggsZZ4lUtils/IsEMPlusPlusH4lDefs.h>
/*-------------------------------------------------------------------------*/
bool isLoosePlusPlusH4l_cr(
double eta,
double eT,
double rHad,
double rHad1,
double Reta,
double w2,
double f1,
double wstot,
double DEmaxs1,
double deltaEta,
int nSi,
int nSiOutliers,
int nPix,
int nPixOutliers,
bool debug,
bool isTrigger
) {
unsigned int eTBin = getEtBinH4l(eT);
if(isTrigger)
{
eTBin = getEtBinH4l(21.0f * 1000.0f);
}
unsigned int etaBin = getEtaBinH4l(eta);
if(passRHad_looseH4l(rHad, rHad1, eTBin, etaBin) == false)
{
return false;
}
if(passReta_looseH4l(Reta, eTBin, etaBin) == false)
{
return false;
}
if(passW2_looseH4l(w2, eTBin, etaBin) == false)
{
return false;
}
if(f1 > 0.005)
{
if(passWstot_looseH4l(wstot, eTBin, etaBin) == false)
{
return false;
}
}
if(nSi + nSiOutliers < 4)
{
return false;
}
return true;
}
/*-------------------------------------------------------------------------*/
Bool_t TLeptonAnalysis::el_loosePP_at(Int_t index)
{
float eta = el_cl_eta->at(index);
float eT = el_cl_E->at(index) / coshf(eta);
if(eT == 0.0f)
{
return false;
}
float rHad = el_Ethad->at(index) / eT;
float rHad1 = el_Ethad1->at(index) / eT;
float Reta = el_reta->at(index);
float w2 = el_weta2->at(index);
float f1 = el_f1->at(index);
float wstot = el_wstot->at(index);
float DEmaxs1 = (el_emaxs1->at(index) - el_Emax2->at(index)) / (el_emaxs1->at(index) + el_Emax2->at(index));
float deltaEta = el_deltaeta1->at(index);
Int_t nSi = el_nSiHits->at(index);
Int_t nSiOutliers = el_nPixelOutliers->at(index) + el_nSCTOutliers->at(index);
Int_t nPix = el_nPixHits->at(index);
Int_t nPixOutliers = el_nPixelOutliers->at(index);
return isLoosePlusPlusH4l(
eta,
eT,
rHad,
rHad1,
Reta,
w2,
f1,
wstot,
DEmaxs1,
deltaEta,
nSi,
nSiOutliers,
nPix,
nPixOutliers,
false,
false
);
}
/*-------------------------------------------------------------------------*/
Bool_t TLeptonAnalysis::el_loosePP_cr_at(Int_t index)
{
float eta = el_cl_eta->at(index);
float eT = el_cl_E->at(index) / coshf(eta);
if(eT == 0.0f)
{
return false;
}
float rHad = el_Ethad->at(index) / eT;
float rHad1 = el_Ethad1->at(index) / eT;
float Reta = el_reta->at(index);
float w2 = el_weta2->at(index);
float f1 = el_f1->at(index);
float wstot = el_wstot->at(index);
float DEmaxs1 = (el_emaxs1->at(index) - el_Emax2->at(index)) / (el_emaxs1->at(index) + el_Emax2->at(index));
float deltaEta = el_deltaeta1->at(index);
Int_t nSi = el_nSiHits->at(index);
Int_t nSiOutliers = el_nPixelOutliers->at(index) + el_nSCTOutliers->at(index);
Int_t nPix = el_nPixHits->at(index);
Int_t nPixOutliers = el_nPixelOutliers->at(index);
return isLoosePlusPlusH4l_cr(
eta,
eT,
rHad,
rHad1,
Reta,
w2,
f1,
wstot,
DEmaxs1,
deltaEta,
nSi,
nSiOutliers,
nPix,
nPixOutliers,
false,
false
);
}
/*-------------------------------------------------------------------------*/
| [
"odier.jerome@gmail.com"
] | odier.jerome@gmail.com |
2cd2f2b722213bed4e5653a03fafbf262ff20c9d | a585193dcc42e10a9462de37bcb42bb5e2f75125 | /Chapter05/Section0x/Quiz01/constants.cpp | 8614f18e91eba0817b2a7b5507a739e1ce40f508 | [] | no_license | NiltonGMJunior/learn-cpp | 9765968f84c86352849013670fc5353c49f9a6a7 | 613797a6362ae658a2df676f53fdf0c032fc8184 | refs/heads/master | 2020-04-18T04:59:01.926327 | 2019-04-19T21:36:04 | 2019-04-19T21:36:04 | 167,259,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61 | cpp | namespace Constants
{
extern const double gravity(9.8);
} | [
"nilton.junior51@hotmail.com"
] | nilton.junior51@hotmail.com |
e2c839299ef7a2aea2ff63aca8944c5c588f6882 | a6e16f8b4e3e9dfb7a8b6f323b7e35fb82537222 | /Various/Modula 2/Holger Kleinschmidt/M2POSX14/SRC/SIG.IPP | 21ddba9ac93759ca306fee37b5735f019efb3b3c | [] | no_license | pjones1063/Atari_ST_Sources | 59cd4af5968d20eb3bf16836fc460f018aa05e7c | fe7d2d16d3919274547efbd007f5e0ec1557396d | refs/heads/master | 2020-09-04T20:21:44.756895 | 2019-10-30T12:54:05 | 2019-10-30T12:54:05 | 219,878,695 | 2 | 0 | null | 2019-11-06T00:40:39 | 2019-11-06T00:40:39 | null | UTF-8 | C++ | false | false | 22,244 | ipp | IMPLEMENTATION MODULE sig;
__IMP_SWITCHES__
__DEBUG__
#ifdef HM2
#ifdef __LONG_WHOLE__
(*$!i+: Modul muss mit $i- uebersetzt werden! *)
(*$!w+: Modul muss mit $w- uebersetzt werden! *)
#else
(*$!i-: Modul muss mit $i+ uebersetzt werden! *)
(*$!w-: Modul muss mit $w+ uebersetzt werden! *)
#endif
#endif
(*****************************************************************************)
(* Basiert auf der MiNTLIB von Eric R. Smith und anderen *)
(* --------------------------------------------------------------------------*)
(* 14-Mai-94, Holger Kleinschmidt *)
(*****************************************************************************)
VAL_INTRINSIC
CAST_IMPORT
FROM SYSTEM IMPORT
(* TYPE *) ADDRESS,
(* PROC *) ADR;
FROM PORTAB IMPORT
(* CONST*) NULL,
(* TYPE *) UNSIGNEDWORD, SIGNEDLONG, UNSIGNEDLONG, WORDSETRANGE, WORDSET;
FROM types IMPORT
(* CONST*) ClkTck,
(* TYPE *) int, unsigned, signedlong, pidT;
IMPORT e;
FROM pLONGSET IMPORT
(* PROC *) UNIONlong, DIFFlong, INCLlong, EXCLlong, INlong;
FROM DosSystem IMPORT
(* VAR *) BASEP,
(* PROC *) SysClock, DosPid, MiNTVersion;
FROM DosSupport IMPORT
(* CONST*) MINSIG, MAXSIG,
(* VAR *) SIGMASK, SIGPENDING, SIGHANDLER;
FROM OSCALLS IMPORT
(* PROC *) Pkill, Psigpause, Psigblock, Psigsetmask, Psigpending, Pause,
Psignal, Psigaction, Pterm, Talarm, Tmalarm, Fselect, Pgetpid,
Syield, Pgetpgrp;
(*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*)
TYPE
LONGsigset = RECORD
CASE TAG_COLON BOOLEAN OF
FALSE: sigset : sigsetT;
|TRUE : siglong : UNSIGNEDLONG;
END;
END;
VAR
MiNT : BOOLEAN;
hasMask : BOOLEAN; (* Werden 'Psigblock' und 'Psigsetmask' unterstuetzt ? *)
#if !((defined HM2) || (defined TDIM2))
VAR
Wrapper : RECORD
code1 : UNSIGNEDLONG;
code2 : UNSIGNEDWORD;
code3 : UNSIGNEDWORD;
call : SigHandler;
code4 : UNSIGNEDWORD;
END;
#endif
VAR
Catch : UNSIGNEDWORD;
(*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*)
PROCEDURE sigemptyset ((* -- /AUS *) VAR set : sigsetT );
BEGIN
set[0] := WORDSET{};
set[1] := WORDSET{};
END sigemptyset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigfillset ((* -- /AUS *) VAR set : sigsetT );
BEGIN
set[0] := WORDSET{0..15};
set[1] := WORDSET{0..15};
END sigfillset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigaddset ((* EIN/AUS *) VAR set : sigsetT;
(* EIN/ -- *) sig : int ): int;
VAR cast : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
cast.sigset := set;
INCLlong(cast.siglong, VAL(UNSIGNEDWORD,sig));
set := cast.sigset;
RETURN(0);
END sigaddset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigdelset ((* EIN/AUS *) VAR set : sigsetT;
(* EIN/ -- *) sig : int ): int;
VAR cast : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
cast.sigset := set;
EXCLlong(cast.siglong, VAL(UNSIGNEDWORD,sig));
set := cast.sigset;
RETURN(0);
END sigdelset;
(*---------------------------------------------------------------------------*)
PROCEDURE sigismember ((* EIN/ -- *) set : sigsetT;
(* EIN/ -- *) sig : int ): int;
VAR cast : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
cast.sigset := set;
RETURN(INT(INlong(VAL(UNSIGNEDWORD,sig), cast.siglong)));
END sigismember;
(*---------------------------------------------------------------------------*)
#if (defined HM2)
(*$E+*)
#endif
(* Ohne MiNT fuer alle Compiler, mit MiNT nur fuer LPR, SPC und MM
* noetig.
*)
PROCEDURE dispatch ((* EIN/ -- *) sig : UNSIGNEDLONG );
VAR handler : SignalHandler;
BEGIN
handler.long := SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER;
handler.proc(sig);
END dispatch;
#if (defined HM2)
(*$E=*)
#endif
(*---------------------------------------------------------------------------*)
PROCEDURE kill ((* EIN/ -- *) pid : pidT;
(* EIN/ -- *) sig : int ): int;
VAR handler : SignalHandler;
res : INTEGER;
savemask : UNSIGNEDLONG;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
IF Pkill(pid, sig, res) THEN
RETURN(0);
ELSIF res <> e.eINVFN THEN
(* 'Pkill'-Aufruf wird unterstuetzt, anderer Fehler *)
e.errno := res;
RETURN(-1);
ELSE
(* 'Pkill'-Aufruf wird nicht unterstuetzt *)
IF (pid < 0) OR (pid > 0) AND (pid <> DosPid(BASEP)) THEN
e.errno := e.ESRCH;
RETURN(-1);
END;
handler.long := SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER;
IF (sig = SIGNULL) OR (handler.long = SigIgn) THEN
(* Signal wird ignoriert *)
RETURN(0);
ELSIF (sig <> SIGKILL) (* kann nicht maskiert werden *)
AND (sig <> SIGSTOP) (* -""- *)
AND (sig <> SIGCONT) (* -""- *)
AND INlong(VAL(UNSIGNEDWORD,sig), SIGMASK)
THEN
(* Falls Signal in der Signalmaske gesetzt -> nur vermerken *)
INCLlong(SIGPENDING, VAL(UNSIGNEDWORD,sig));
RETURN(0);
ELSE
EXCLlong(SIGPENDING, VAL(UNSIGNEDWORD,sig));
IF handler.long = SigDfl THEN
(* Kein Handler installiert -> Defaultaktion *)
IF (sig=SIGCONT) OR (sig=SIGCHLD) OR (sig=SIGWINCH) OR (sig=SIGFPE) THEN
(* Defaultaktion: Signal ignorieren *)
RETURN(0);
ELSE
(* Defaultaktion: Programm beenden *)
Pterm(VAL(CARDINAL,sig) * 256); (* Signal in obere 8 Bit *)
END;
ELSE
(* Installierten Signalhandler ausfuehren, Signalmaske solange
* aendern.
*)
savemask := SIGMASK;
SIGMASK := UNIONlong(SIGMASK, SIGHANDLER[VAL(UNSIGNEDWORD,sig)].MASK);
(* Zusaetzlich ist das behandelte Signal blockiert *)
INCLlong(SIGMASK, VAL(UNSIGNEDWORD,sig));
handler.proc(VAL(UNSIGNEDLONG,sig));
(* Alte Signalmaske wiederherstellen *)
SIGMASK := savemask;
RETURN(0);
END;
END;
END;
END kill;
(*---------------------------------------------------------------------------*)
PROCEDURE DeliverUnblocked;
(**)
VAR __REG__ unblocked : UNSIGNEDLONG;
__REG__ sig : UNSIGNEDWORD;
__REG__ void : INTEGER;
BEGIN
unblocked := DIFFlong(SIGPENDING, SIGMASK);
IF unblocked <> VAL(UNSIGNEDLONG,0) THEN
FOR sig := 1 TO NSIG - 1 DO
IF INlong(sig, unblocked) THEN
void := kill(0, INT(sig));
END;
END;
END;
END DeliverUnblocked;
(*---------------------------------------------------------------------------*)
PROCEDURE signal ((* EIN/ -- *) sig : int;
(* EIN/ -- *) handler : SignalHandler;
(* -- /AUS *) VAR old : SignalHandler ): int;
VAR func : ADDRESS;
prev : ADDRESS;
void : INTEGER;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
old.long := SigErr;
RETURN(-1);
END;
#if !((defined HM2) || (defined TDIM2))
WITH handler DO WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
old.long := HANDLER;
HANDLER := long;
IF (long = SigDfl) OR (long = SigIgn) THEN
func := CAST(ADDRESS,long);
ELSE
func := ADR(Wrapper);
END;
END; END;
#else
func := CAST(ADDRESS,handler.long);
#endif
IF Psignal(sig, func, prev) THEN
#if !((defined HM2) || (defined TDIM2))
IF prev <> ADR(Wrapper) THEN
old.long := CAST(SIGNEDLONG,prev);
END;
#else
old.long := CAST(SIGNEDLONG,prev);
#endif
RETURN(0);
ELSIF CAST(SIGNEDLONG,prev) <> VAL(SIGNEDLONG,e.eINVFN) THEN
(* 'Psignal'-Aufruf wird unterstuetzt, anderer Fehler *)
#if !((defined HM2) || (defined TDIM2))
(* Geaenderten Handler restaurieren *)
SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER := old.long;
#endif
e.errno := INT(CAST(SIGNEDLONG,prev));
old.long := SigErr;
RETURN(-1);
ELSE
(* 'Psignal'-Aufruf wird nicht unterstuetzt *)
WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
#if (defined HM2) || (defined TDIM2)
old.long := HANDLER;
HANDLER := handler.long;
#endif
MASK := 0;
END;
(* Blockierung fuer behandeltes Signal aufheben und evtl. anstehendes
* Signal ausfuehren.
*)
EXCLlong(SIGMASK, VAL(UNSIGNEDWORD,sig));
DeliverUnblocked;
RETURN(0);
END;
END signal;
(*---------------------------------------------------------------------------*)
PROCEDURE sigaction ((* EIN/ -- *) sig : int;
(* EIN/ -- *) act : SigactionPtr;
(* EIN/ -- *) oact : SigactionPtr ): int;
VAR oldh : SIGNEDLONG;
tmp : SigactionRec;
res : INTEGER;
mask : LONGsigset;
BEGIN
IF (sig < 0) OR (sig >= NSIG) THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
#if !((defined HM2) || (defined TDIM2))
WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
oldh := HANDLER;
IF act <> NULL THEN
(* act^ nicht veraendern, nur eine Kopie *)
tmp := act^;
act := CAST(SigactionPtr,ADR(tmp));
WITH tmp.saHandler DO
HANDLER := long;
IF (long <> SigDfl) AND (long <> SigIgn) THEN
long := CAST(SIGNEDLONG,ADR(Wrapper));
END;
END;
END;
END;
#endif
IF Psigaction(sig, act, oact, res) THEN
#if !((defined HM2) || (defined TDIM2))
IF oact <> NULL THEN
WITH oact^.saHandler DO
IF CAST(ADDRESS,long) = ADR(Wrapper) THEN
long := oldh;
END;
END;
END;
#endif
RETURN(0);
ELSIF res <> e.eINVFN THEN
(* 'Psigaction'-Aufruf wird unterstuetzt, anderer Fehler *)
#if !((defined HM2) || (defined TDIM2))
(* Geaenderten Handler restaurieren *)
SIGHANDLER[VAL(UNSIGNEDWORD,sig)].HANDLER := oldh;
#endif
e.errno := res;
RETURN(-1);
ELSE
(* 'Psigaction'-Aufruf wird nicht unterstuetzt *)
WITH SIGHANDLER[VAL(UNSIGNEDWORD,sig)] DO
IF oact <> NULL THEN
WITH oact^ DO
#if (defined HM2) || (defined TDIM2)
saHandler.long := HANDLER;
#else
saHandler.long := oldh;
#endif
saFlags := CAST(SaFlags,FLAGS);
mask.siglong := MASK;
saMask := mask.sigset;
END;
END;
IF act <> NULL THEN
WITH act^ DO
#if (defined HM2) || (defined TDIM2)
HANDLER := saHandler.long;
#endif
FLAGS := CAST(WORDSET,saFlags);
(* Innerhalb des Handlers zusaetzlich die angegebene Signalmaske
* beruecksichtigen.
*)
mask.sigset := saMask;
MASK := mask.siglong;
END;
END;
END; (* WITH SIGHANDLER *)
(* Blockierung fuer behandeltes Signal aufheben und evtl. anstehendes
* Signal ausfuehren.
*)
EXCLlong(SIGMASK, VAL(UNSIGNEDWORD,sig));
DeliverUnblocked;
RETURN(0);
END;
END sigaction;
(*---------------------------------------------------------------------------*)
PROCEDURE raise ((* EIN/ -- *) sig : int ): int;
VAR pid : INTEGER;
BEGIN
pid := Pgetpid();
IF pid < 0 THEN
(* 'Pgetpid'-Aufruf wird nicht unterstuetzt *)
RETURN(kill(0, sig));
ELSE
RETURN(kill(pid, sig));
END;
END raise;
(*---------------------------------------------------------------------------*)
PROCEDURE killpg ((* EIN/ -- *) pgrp : pidT;
(* EIN/ -- *) sig : int ): int;
BEGIN
IF pgrp < 0 THEN
e.errno := e.EINVAL;
RETURN(-1);
END;
IF Pgetpgrp() <> e.eINVFN THEN
(* Prozessgruppen werden unterstuetzt *)
RETURN(kill(-pgrp, sig));
ELSE
RETURN(kill(pgrp, sig));
END;
END killpg;
(*---------------------------------------------------------------------------*)
PROCEDURE sigprocmask ((* EIN/ -- *) how : SigBlockType;
(* EIN/ -- *) set : SigsetPtr;
(* EIN/ -- *) oset : SigsetPtr ): int;
VAR old : UNSIGNEDLONG;
mask : LONGsigset;
cast : LONGsigset;
BEGIN
mask.siglong := SIGMASK;
CASE how OF
SigBlock:
IF hasMask THEN
IF set = NULL THEN
mask.siglong := 0;
ELSE
mask.sigset := set^;
END;
mask.siglong := Psigblock(mask.siglong);
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
ELSE
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
IF set <> NULL THEN
cast.sigset := set^;
SIGMASK := UNIONlong(SIGMASK, cast.siglong);
END;
END;
|SigUnBlock:
IF hasMask THEN
mask.siglong := Psigblock(0);
END;
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
IF set <> NULL THEN
cast.sigset := set^;
mask.siglong := DIFFlong(mask.siglong, cast.siglong);
IF hasMask THEN
old := Psigsetmask(mask.siglong);
ELSE
SIGMASK := mask.siglong;
DeliverUnblocked;
END;
END;
ELSE (* SigSetMask *)
IF hasMask THEN
IF set = NULL THEN
mask.siglong := Psigblock(0);
ELSE
mask.sigset := set^;
mask.siglong := Psigsetmask(mask.siglong);
END;
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
ELSE
IF oset <> NULL THEN
oset^ := mask.sigset;
END;
IF set <> NULL THEN
mask.sigset := set^;
SIGMASK := mask.siglong;
DeliverUnblocked;
END;
END;
END;
RETURN(0);
END sigprocmask;
(*---------------------------------------------------------------------------*)
PROCEDURE sigpending ((* -- /AUS *) VAR set : sigsetT ): int;
VAR pending : LONGsigset;
res : SIGNEDLONG;
BEGIN
res := Psigpending();
IF res < VAL(SIGNEDLONG,0) THEN
(* 'Psigpending'-Aufruf wird nicht unterstuetzt *)
pending.siglong := SIGPENDING;
ELSE
pending.siglong := res;
END;
set := pending.sigset;
RETURN(0);
END sigpending;
(*---------------------------------------------------------------------------*)
PROCEDURE pause;
VAR void : INTEGER;
BEGIN
void := Pause();
e.errno := e.EINTR;
END pause;
(*---------------------------------------------------------------------------*)
PROCEDURE sigsuspend ((* EIN/ -- *) sigmask : sigsetT );
VAR mask : LONGsigset;
old : UNSIGNEDLONG;
BEGIN
mask.sigset := sigmask;
IF Psigpause(mask.siglong) < 0 THEN
(* 'Psigpause'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := mask.siglong;
DeliverUnblocked;
SIGMASK := old;
END;
e.errno := e.EINTR;
END sigsuspend;
(*---------------------------------------------------------------------------*)
PROCEDURE alarm ((* EIN/ -- *) sec : unsigned ): unsigned;
CONST MAXSEC = LC(2147483);
VAR secs : SIGNEDLONG;
rem : SIGNEDLONG;
BEGIN
IF VAL(UNSIGNEDLONG,sec) > MAXSEC THEN
(* sonst gibts Ueberlauf in MiNT *)
sec := VAL(unsigned,MAXSEC);
END;
rem := Talarm(VAL(SIGNEDLONG,sec));
IF rem < VAL(SIGNEDLONG,0) THEN
(* 'Talarm'-Aufruf wird nicht unterstuetzt *)
RETURN(0);
ELSE
RETURN(VAL(CARDINAL,rem));
END;
END alarm;
(*---------------------------------------------------------------------------*)
PROCEDURE sleep ((* EIN/ -- *) seconds : unsigned ): unsigned;
CONST MAXSEC = LC(2147483);
VAR until : UNSIGNEDLONG;
voidB : BOOLEAN;
voidL : UNSIGNEDLONG;
voidA : ADDRESS;
alarmSecs : SIGNEDLONG;
secs : SIGNEDLONG;
remain : SIGNEDLONG;
oldHandler : ADDRESS;
oldMask : UNSIGNEDLONG;
cast : LONGsigset;
res : INTEGER;
BEGIN
IF seconds = 0 THEN
RETURN(0);
END;
IF VAL(UNSIGNEDLONG,seconds) > MAXSEC THEN
(* sonst gibts Ueberlauf in MiNT *)
seconds := VAL(CARDINAL,MAXSEC);
END;
secs := VAL(SIGNEDLONG,seconds);
IF MiNT THEN
(* Das folgende Algorithmus stammt aus der MiNTLib: *)
alarmSecs := Talarm(0);
oldMask := Psigblock(0FFFFFFFFH);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), oldHandler);
voidL := Psigblock(0FFFFFFFFH);
until := SysClock() DIV ClkTck + VAL(UNSIGNEDLONG,seconds);
IF (alarmSecs > VAL(SIGNEDLONG,0)) AND (alarmSecs < secs) THEN
voidL := Talarm(alarmSecs);
ELSE
voidL := Talarm(secs);
END;
EXCLlong(oldMask, VAL(UNSIGNEDWORD,SIGALRM));
res := Psigpause(oldMask);
alarmSecs := Talarm(0);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), voidA);
res := Syield();
voidL := Psigblock(0FFFFFFFFH);
remain := CAST(SIGNEDLONG,until) - CAST(SIGNEDLONG,SysClock() DIV ClkTck);
IF alarmSecs > VAL(SIGNEDLONG,0) THEN
DEC(alarmSecs, secs - remain);
IF alarmSecs > VAL(SIGNEDLONG,0) THEN
voidL := Talarm(alarmSecs);
ELSE
voidB := Pkill(Pgetpid(), ORD(SIGALRM), res);
END;
END;
voidB := Psignal(ORD(SIGALRM), oldHandler, voidA);
voidL := Psigsetmask(oldMask);
res := Syield();
IF remain > VAL(SIGNEDLONG,0) THEN
RETURN(VAL(CARDINAL,remain));
ELSE
RETURN(0);
END;
ELSE
until := SysClock() + VAL(UNSIGNEDLONG,seconds) * ClkTck;
REPEAT
UNTIL SysClock() >= until;
RETURN(0);
END;
END sleep;
(*---------------------------------------------------------------------------*)
PROCEDURE usleep ((* EIN/ -- *) useconds : signedlong ): signedlong;
VAR until : UNSIGNEDLONG;
voidB : BOOLEAN;
voidL : UNSIGNEDLONG;
voidA : ADDRESS;
alarmMSecs : SIGNEDLONG;
mSecs : SIGNEDLONG;
remain : SIGNEDLONG;
oldHandler : ADDRESS;
oldMask : UNSIGNEDLONG;
cast : LONGsigset;
res : INTEGER;
BEGIN
mSecs := useconds DIV VAL(SIGNEDLONG,1000);
IF mSecs <= VAL(SIGNEDLONG,0) THEN
RETURN(0);
END;
(* 'useconds': Zeit in Millisekunden *)
IF MiNT THEN
(* Das folgende Algorithmus stammt aus der MiNTLib: *)
alarmMSecs := Tmalarm(0);
oldMask := Psigblock(0FFFFFFFFH);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), oldHandler);
voidL := Psigblock(0FFFFFFFFH);
until := SysClock() * VAL(UNSIGNEDLONG,5) + CAST(UNSIGNEDLONG,mSecs);
IF (alarmMSecs > VAL(SIGNEDLONG,0)) AND (alarmMSecs < mSecs) THEN
voidL := Tmalarm(alarmMSecs);
ELSE
voidL := Tmalarm(mSecs);
END;
EXCLlong(oldMask, VAL(UNSIGNEDWORD,SIGALRM));
res := Psigpause(oldMask);
alarmMSecs := Tmalarm(0);
voidB := Psignal(ORD(SIGALRM), ADR(Catch), voidA);
res := Syield();
voidL := Psigblock(0FFFFFFFFH);
remain := CAST(SIGNEDLONG,until) - CAST(SIGNEDLONG,SysClock() * LC(5));
IF alarmMSecs > VAL(SIGNEDLONG,0) THEN
DEC(alarmMSecs, mSecs - remain);
IF alarmMSecs > VAL(SIGNEDLONG,0) THEN
voidL := Tmalarm(alarmMSecs);
ELSE
voidB := Pkill(Pgetpid(), ORD(SIGALRM), res);
END;
END;
voidB := Psignal(ORD(SIGALRM), oldHandler, voidA);
voidL := Psigsetmask(oldMask);
res := Syield();
IF remain > VAL(SIGNEDLONG,0) THEN
RETURN(VAL(UNSIGNEDLONG,remain) * VAL(UNSIGNEDLONG,1000));
ELSE
RETURN(0);
END;
ELSE
until := SysClock() + VAL(UNSIGNEDLONG,mSecs) DIV LC(5);
REPEAT
UNTIL SysClock() >= until;
END;
RETURN(0);
END usleep;
(*---------------------------------------------------------------------------*)
PROCEDURE sigmask ((* EIN/ -- *) sig : int ): UNSIGNEDLONG;
VAR cast : LONGsigset;
BEGIN
cast.siglong := 0H;
INCLlong(cast.siglong, VAL(UNSIGNEDWORD,sig));
RETURN(cast.siglong);
END sigmask;
(*---------------------------------------------------------------------------*)
PROCEDURE sigsetmask ((* EIN/ -- *) mask : UNSIGNEDLONG ): UNSIGNEDLONG;
VAR old : UNSIGNEDLONG;
BEGIN
IF hasMask THEN
RETURN(Psigsetmask(mask));
ELSE
(* 'Psigsetmask'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := mask;
DeliverUnblocked;
RETURN(old);
END;
END sigsetmask;
(*---------------------------------------------------------------------------*)
PROCEDURE sigblock ((* EIN/ -- *) mask : UNSIGNEDLONG ): UNSIGNEDLONG;
VAR old : UNSIGNEDLONG;
BEGIN
IF hasMask THEN
RETURN(Psigblock(mask));
ELSE
(* 'Psigblock'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := UNIONlong(SIGMASK, mask);
RETURN(old);
END;
END sigblock;
(*---------------------------------------------------------------------------*)
PROCEDURE sigpause ((* EIN/ -- *) mask : UNSIGNEDLONG );
(**)
VAR old : UNSIGNEDLONG;
BEGIN
IF Psigpause(mask) < 0 THEN
(* 'Psigpause'-Aufruf wird nicht unterstuetzt *)
old := SIGMASK;
SIGMASK := mask;
DeliverUnblocked;
SIGMASK := old;
END;
e.errno := e.EINTR;
END sigpause;
(*===========================================================================*)
CONST
EINVFN = 0FFFFFFE0H; (* = e.EINVFN als (UN)SIGNEDLONG-Konstante *)
BEGIN (* sig *)
MiNT := MiNTVersion() > 0;
hasMask := Psigblock(0) <> EINVFN;
(* Wenn der 'Psigblock'-Aufruf unterstuetzt wird, kann dieses Bitmuster
* nicht auftreten, weil SIGSTOP (Bit 17) und SIGCONT (Bit 19) nicht
* blockiert werden/sein koennen. Es wird angenommen, dass das Ergebnis
* des Tests auch fuer 'Psigsetmask' gilt.
*)
#if !((defined HM2) || (defined TDIM2))
WITH Wrapper DO
code1 := 202F0004H; (* move.l 4(SP),D0 *)
#ifdef MM2
code2 := 26C0H; (* move.l D0,(A3)+ *)
#else
code2 := 2F00H; (* move.l D0,-(SP) *)
#endif
code3 := 4EB9H; (* jsr ... *)
call := dispatch; (* ... dispatch *)
code4 := 4E75H; (* rts *)
END;
#endif
Catch := 4E75H; (* rts, ein sehr einfacher Signalhandler... *)
END sig.
| [
"ggn.dbug@gmail.com"
] | ggn.dbug@gmail.com |
607d8d4585904eff3be6dbdb3d366c167df07f94 | 0cddab604dc4ff7cb383d6c9ad9bf9280273f9ef | /M1ProgramDesign-PYQ/2015/MaritimeRadio/main.cpp | b701e716cc09fb6fe5ac09ab1967b422c08d5369 | [
"MIT"
] | permissive | chowder/imperial-pyqs | bf7e2d176b3a3d6d076e469469c6e781bb8423d0 | 76edf454c5cd96a70a78698d61f3f3cf742d83ea | refs/heads/master | 2021-07-24T13:10:33.955943 | 2020-06-13T09:59:59 | 2020-06-13T09:59:59 | 183,113,197 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 294 | cpp | #include "Ship.h"
#include "Ocean.h"
int main() {
Ship* endeavor = new Ship("Endeavor", "2FBA7", 20, 36.158, -5.357);
Ship* seaswan = new Ship("Sea Swan", "2CEU8", 10, 36.180, -5.390);
seaswan->setEmergency(true);
seaswan->broadcast();
endeavor->moveTo(36.179, -5.391);
}
| [
"andrewcxw@gmail.com"
] | andrewcxw@gmail.com |
1eb3c2f599011802c36062a257d83aae9b13c820 | 485ff07efdbb3e56b9633e3134b1c81271c2d8a3 | /cpp/SampleCommands/SampleAttributeUserData.h | eee410006afa6b35282eb8330e7fe645ba1b0d86 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | mcneel/rhino-developer-samples | 8f8a332d4d6a9a5fa064be6c1532e665d37c8f13 | 4fb376adcf94f9d583878d1c1208038f86bde312 | refs/heads/7 | 2023-08-18T22:04:34.036498 | 2023-06-08T16:28:43 | 2023-06-08T16:28:43 | 72,225,588 | 526 | 362 | NOASSERTION | 2023-09-06T20:29:31 | 2016-10-28T16:52:21 | C++ | UTF-8 | C++ | false | false | 1,626 | h | #pragma once
class CSampleAttributeUserData : public ON_UserData
{
// Opennurbs classes that are saved in .3dm files require
// an ON_OBJECT_DECLARE call in their declaration.
ON_OBJECT_DECLARE(CSampleAttributeUserData);
public:
/*
Returns:
Uuid used to identify this type of user data.
This is the value saved in m_userdata_uuid and
passed to ON_Object::GetUserData().
*/
static ON_UUID Id();
CSampleAttributeUserData();
~CSampleAttributeUserData();
// NOTE WELL:
// Because the members of this class are class are types
// that have fully functional copy constructors and
// operator=s, it is NOT necessary to provide an explicit
// a copy constructor and operator=. In fact, it would
// be best to use the ones C++ generates.
// They are included in this example to demonstrate the
// correct way to implement a copy constructor and
// operator= because this is a task that trips up
// many people that attempt to implement them.
CSampleAttributeUserData(const CSampleAttributeUserData& src);
CSampleAttributeUserData& operator=(const CSampleAttributeUserData& src);
// override virtual ON_UserData::GetDescription()
bool GetDescription(ON_wString& description) override;
// override virtual ON_UserData::Archive()
bool Archive() const override;
// override virtual ON_UserData::Write()
bool Write(
ON_BinaryArchive& binary_archive
) const override;
// override virtual ON_UserData::Read()
bool Read(
ON_BinaryArchive& binary_archive
) override;
public:
ON_wString m_my_string;
ON_3dPoint m_my_point;
};
| [
"dale@mcneel.com"
] | dale@mcneel.com |
795db6ac3e23834a31eab5edf15ab3d0d1c59f3c | 5f4fd92950d1111d6bd17a8b78366fd09e5584b0 | /AssimpTest/Saved/animation.cpp | abcae7936c6787291a3b68959a7afe306e274986 | [] | no_license | DuckMonster/AssimpTesting | 08de71cc4fe07c8e4dbb6d587d40336877a29991 | ea0f3623401d8d37dd40d46882338c098b03bbd2 | refs/heads/master | 2020-05-23T11:15:33.786783 | 2017-02-20T21:22:49 | 2017-02-20T21:22:49 | 80,369,762 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,030 | cpp | #include "stdafx.h"
#include "animation.h"
CAnimation::CAnimation( ) : CAnimation( 0.f, 0.f ) {
}
CAnimation::CAnimation( float length, float framerate ) :
m_Time( 0.f ), m_Length( length ), m_Framerate( framerate ),
m_PositionAttribute( vec3( 0.f ) ),
m_ScaleAttribute( vec3( 1.f ) ),
m_RotationAttribute( quat( ) ) {
}
vec3 CAnimation::GetPositionValue( ) {
return m_PositionAttribute.GetValue( m_Time );
}
vec3 CAnimation::GetScaleValue( ) {
return m_ScaleAttribute.GetValue( m_Time );
}
quat CAnimation::GetRotationValue( ) {
return m_RotationAttribute.GetValue( m_Time );
}
mat4 CAnimation::GetTransform( ) {
/*return translate( mat4( 1.f ), GetPositionValue( ) ) *
scale( mat4( 1.f ), GetScaleValue( ) ) *
mat4( GetRotationValue( ) );*/
mat4 t = translate( mat4( 1.f ), GetPositionValue( ) );
mat4 s = scale( mat4( 1.f ), GetScaleValue( ) );
mat4 r = mat4( GetRotationValue( ) );
return t * r * s;
}
void CAnimation::Update( float delta ) {
m_Time = mod( m_Time + delta * m_Framerate, m_Length );
} | [
"emil.strm@gmail.com"
] | emil.strm@gmail.com |
a13254d80552f0711d65f41bcf5d56ec7ccfdca5 | 4c304cd281a19bd4a903b0a1b1eb54692649d477 | /CodeBahasaPemrograman/Latihan/belajar1.cpp | 65dadc5cf43bb9b130274b99e1ad72c09d1d7ad3 | [] | no_license | alinnural/TugasKuliah | fc017e339485421e357a8db14abc8f88013baff8 | d1fe03fdc694203561547e154f19d0689dfec5af | refs/heads/master | 2021-01-21T02:27:15.530183 | 2016-05-30T09:22:17 | 2016-05-30T09:22:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | cpp | #include<iostream>
#include<iomanip>
using namespace std;
int main(){
long a,b;
float c;
cin >> a >> b;
c=(a*1.00) + b;
cout << c << endl;
return 0;
}
| [
"ihsan_arif@apps.ipb.ac.id"
] | ihsan_arif@apps.ipb.ac.id |
1f226181a8b3afd8698db85412b5bbd13056aaf8 | 8a096b1a813326deac53d55cc3b9d5ddaca875e9 | /aws-cpp-sdk-appmesh/include/aws/appmesh/model/DescribeMeshResult.h | ba41a4a0df3ed343c9d4c746bf3bb38de67d29fc | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | pixvana/aws-sdk-cpp | 993d976b880fdf2a48d60c73d6748796f69546ec | 7ba3f49c8a2636b48342c71e038aa09b6e47077c | refs/heads/master | 2020-03-30T02:52:38.628422 | 2019-02-27T00:57:08 | 2019-02-27T00:57:08 | 150,655,889 | 0 | 0 | Apache-2.0 | 2018-11-15T16:22:02 | 2018-09-27T22:40:14 | C++ | UTF-8 | C++ | false | false | 2,224 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/appmesh/AppMesh_EXPORTS.h>
#include <aws/appmesh/model/MeshData.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace AppMesh
{
namespace Model
{
/**
* <p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/appmesh-2018-10-01/DescribeMeshOutput">AWS
* API Reference</a></p>
*/
class AWS_APPMESH_API DescribeMeshResult
{
public:
DescribeMeshResult();
DescribeMeshResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeMeshResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The full description of your service mesh.</p>
*/
inline const MeshData& GetMesh() const{ return m_mesh; }
/**
* <p>The full description of your service mesh.</p>
*/
inline void SetMesh(const MeshData& value) { m_mesh = value; }
/**
* <p>The full description of your service mesh.</p>
*/
inline void SetMesh(MeshData&& value) { m_mesh = std::move(value); }
/**
* <p>The full description of your service mesh.</p>
*/
inline DescribeMeshResult& WithMesh(const MeshData& value) { SetMesh(value); return *this;}
/**
* <p>The full description of your service mesh.</p>
*/
inline DescribeMeshResult& WithMesh(MeshData&& value) { SetMesh(std::move(value)); return *this;}
private:
MeshData m_mesh;
};
} // namespace Model
} // namespace AppMesh
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
5fb2ad92c4ff78f9216ae1be52d462842950fe6d | 374e168d54493661154912e180ca05f133ec83a3 | /include/yandex/contest/invoker/lxc/OutputConfigArchive.hpp | 3450282ac69c0c8243c5668cd89e5ae59691b9a8 | [] | no_license | bunsanorg/yandex_contest_invoker | 59a0f7428b5e675d0e43d4d177768959360fa752 | b1e8c116962944da7ce71c4c0fe186aead8f8778 | refs/heads/master | 2016-09-15T11:35:51.608160 | 2016-05-22T21:39:15 | 2016-05-22T23:21:21 | 5,658,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | hpp | #pragma once
#include <boost/noncopyable.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <type_traits>
namespace yandex {
namespace contest {
namespace invoker {
namespace lxc {
namespace config {
class OutputArchive {
public:
using is_loading = std::integral_constant<bool, false>;
using is_saving = std::integral_constant<bool, true>;
unsigned int get_library_version() { return 0; }
public:
OutputArchive(std::ostream &out, const std::string &prefix)
: out_(&out), prefix_(prefix) {}
template <typename T>
OutputArchive &operator<<(const T &obj) {
save(obj);
return *this;
}
template <typename T>
OutputArchive &operator<<(const boost::serialization::nvp<T> &nvp) {
saveToStream(nvp.value(), out_, prefix_ + "." + nvp.name());
return *this;
}
template <typename T>
OutputArchive &operator<<(
const boost::serialization::nvp<boost::optional<T>> &nvp) {
using boost::serialization::make_nvp;
if (nvp.value()) *this << make_nvp(nvp.name(), nvp.value().get());
return *this;
}
template <typename T>
static void saveToStream(const T &obj, std::ostream &out,
const std::string &prefix) {
OutputArchive oa(out, prefix);
oa << obj;
}
private:
template <typename T>
void save(const T &obj) {}
private:
std::ostream &out_;
std::string prefix_;
};
} // namespace config
} // namespace lxc
} // namespace invoker
} // namespace contest
} // namespace yandex
| [
"sarum9in@gmail.com"
] | sarum9in@gmail.com |
74ae17fefabf4038c9a5d0d8fe5c5947504d95d2 | 3f58fff76162db4026e22f3587a2f2425dd43f27 | /c++ code/week1/examples/basic functions/basic functions/cropandresize.cpp | fa7f5278341e408971b13bdf15ef2621f53c7b8a | [] | no_license | AndroidMediaCodec/cv4faces | 30e61a59a5aae6ccd6598b8163717493405b06c6 | 17424715206454754dfdc343b54d4682d01abe9f | refs/heads/master | 2021-06-21T13:41:38.891315 | 2017-07-10T15:36:01 | 2017-07-10T15:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | #include <opencv2/opencv.hpp>
int main2()
{
cv::Mat source, scaleDown, scaleUp;
// read souce image
source = cv::imread("../../../../../images/lena.jpg");
// scaling factors
double scaleX = 0.6;
double scaleY = 0.6;
// scaling down the image 0.6 times
cv::resize(source, scaleDown, cv::Size(), scaleX, scaleY, cv::INTER_LINEAR);
// scaling up the image 1.8 times
cv::resize(source, scaleUp, cv::Size(), scaleX * 3, scaleY * 3, cv::INTER_LINEAR);
// cropped image
cv::Mat crop = source(cv::Range(50, 150), cv::Range(20, 200));
// create dsiplay windows for all three images
cv::namedWindow("Original", cv::WINDOW_AUTOSIZE);
cv::namedWindow("Scale Down", cv::WINDOW_AUTOSIZE);
cv::namedWindow("Scale Up", cv::WINDOW_AUTOSIZE);
cv::namedWindow("Croped Image", cv::WINDOW_AUTOSIZE);
// show image
cv::imshow("Original", source);
cv::imshow("Scale Down", scaleDown);
cv::imshow("Scale Up", scaleUp);
cv::imshow("Cropped Image", crop);
cv::waitKey(0);
return EXIT_SUCCESS;
} | [
"ntthienphuc6195@gmail.com"
] | ntthienphuc6195@gmail.com |
04203c7d8f105fc5acf8446c72088e3594efb46f | 625c21aaaf8641dfb467106cde73c7cb12db7528 | /external/randSpg/include/randSpg.h | 9c8ba2ff9a714900815c66d2a8d75c507cd5b5e2 | [
"BSD-3-Clause"
] | permissive | lilithean/XtalOpt | 35f2152dc15cb47d1b649b55d54aae5507afedec | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | refs/heads/master | 2020-03-07T01:34:19.459881 | 2019-04-26T20:57:18 | 2019-04-26T20:57:18 | 127,186,804 | 0 | 0 | NOASSERTION | 2019-04-26T21:00:31 | 2018-03-28T19:14:50 | C++ | UTF-8 | C++ | false | false | 12,141 | h | /**********************************************************************
randSpg.h - Header file for spacegroup initialization functions
Copyright (C) 2015 - 2016 by Patrick S. Avery
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***********************************************************************/
#ifndef RAND_SPG_H
#define RAND_SPG_H
#include <string>
#include <vector>
#include <tuple>
#include <utility>
#include "crystal.h"
typedef unsigned int uint;
// output file name
extern std::string e_logfilename;
// verbosity
extern char e_verbosity;
// wyckPos is a tuple of a char (representing the Wyckoff letter),
// an int (representing the multiplicity), a string (that contains the first
// Wyckoff position), and a bool indicating whether the position is unique
// or not. This bool is part of the tuple for improved speed.
typedef std::tuple<char, int, std::string, bool> wyckPos;
// Each spacegroup has a variable number of wyckoff positions. So each
// spacegroup will have it's own vector of wyckoff positions.
typedef std::vector<wyckPos> wyckoffPositions;
// This assign an atom with a specific atomic number to be placed in a specific
// wyckoff position
// 'uint' is the atomic number
typedef std::pair<wyckPos, uint> atomAssignment;
// This is a vector of atom assignments
typedef std::vector<atomAssignment> atomAssignments;
// number of atoms and atomic number
typedef std::pair<uint, uint> numAndType;
typedef std::pair<std::string, std::string> fillCellInfo;
struct randSpgInput {
// The space group to be generated. Set in constructor.
uint spg;
// The vector of atomic numbers. Set in constructor.
std::vector<uint> atoms;
// The min values for the lattice. Set in constructor.
latticeStruct latticeMins;
// The max values for the lattice. Set in constructor.
latticeStruct latticeMaxes;
// Scaling factor for interatomic distances. For example, "0.5" would imply
//that all atomic radii are 0.5 of their original value. Default is 1.0.
double IADScalingFactor;
// Minimum radius for atomic radii in Angstroms. All atomic radii below this
// radius will be set to this value. Default is 0.0
double minRadius;
// A vector of pairs. Each pair is an atomic number followed by a radius in
// Angstroms. You may append to this vector to set your own radii. The
// default is that it is empty.
std::vector<std::pair<uint, double>> manualAtomicRadii;
// Minimum volume for the final crystal in Angstroms cubed. Default is
// -1 (No min volume).
double minVolume;
// Maximum volume for the final crystal in Angstroms cubed. Default is
// -1 (No max volume).
double maxVolume;
// A vector of pairs. Each pair is an atomic number followed by a char
// representing a Wyckoff letter. This essentially "forces" the program
// to use the specified atomic number for the Wyckoff position defined by the
// Wyckoff letter. If you wish to have an atom type in a Wyckoff position
// multiple times, just add to this vector multiple items of it.
std::vector<std::pair<uint, char>> forcedWyckAssignments;
// Verbosity for log file printing. 'v' for verbose (prints all possibilities
// found), 'r' for regular (prints Wyckoff assignments), or 'n' for none
// (prints nothing other than what the options were set to). Default is 'n'
char verbosity;
// Max number of attempts to satisfy the minIAD requirements when placing
// atoms in the Wyckoff positions. If it fails this many times, it will abort
// the operation. Default is 100.
int maxAttempts;
// This forces the program to use the most general Wyckoff position at
// least once. This ensures that the crystal will be of the correct space
// group. If this is not set to true, then more compositions are possible for
// some space groups, but the final space group will not be guaranteed to be
// the correct space group. Default is true.
bool forceMostGeneralWyckPos;
// Most basic constructor
randSpgInput(uint _spg, const std::vector<uint>& _atoms,
const latticeStruct& _lmins,
const latticeStruct& _lmaxes) :
spg(_spg),
atoms(_atoms),
latticeMins(_lmins),
latticeMaxes(_lmaxes),
IADScalingFactor(1.0),
minRadius(0.0),
manualAtomicRadii(std::vector<std::pair<uint, double>>()),
minVolume(-1.0),
maxVolume(-1.0),
forcedWyckAssignments(std::vector<std::pair<uint, char>>()),
verbosity('n'),
maxAttempts(100),
forceMostGeneralWyckPos(true) {}
// Defining-everything constructor
randSpgInput(uint _spg, const std::vector<uint>& _atoms,
const latticeStruct& _lmins,
const latticeStruct& _lmaxes,
double _IADSF, double _minRadius,
const std::vector<std::pair<uint, double>>& _mar,
double _minVolume, double _maxVolume,
std::vector<std::pair<uint, char>> _fwa,
char _v, int _maxAttempts, bool _fmgwp) :
spg(_spg),
atoms(_atoms),
latticeMins(_lmins),
latticeMaxes(_lmaxes),
IADScalingFactor(_IADSF),
minRadius(_minRadius),
manualAtomicRadii(_mar),
minVolume(_minVolume),
maxVolume(_maxVolume),
forcedWyckAssignments(_fwa),
verbosity(_v),
maxAttempts(_maxAttempts),
forceMostGeneralWyckPos(_fmgwp) {}
};
class RandSpg {
public:
// Get the info from the tuple in the database
static char getWyckLet(const wyckPos& pos) {return std::get<0>(pos);};
static uint getMultiplicity(const wyckPos& pos) {return std::get<1>(pos);};
static std::string getWyckCoords(const wyckPos& pos) {return std::get<2>(pos);};
static bool containsUniquePosition(const wyckPos& pos) {return std::get<3>(pos);};
/*
* Obtain the wyckoff positions of a spacegroup from the database
*
* @param spg The spacegroup from which to obtain the wyckoff positions
*
* @return Returns a constant reference to a vector of wyckoff positions
* for the spacegroup from the database in wyckoffDatabase.h. Returns an
* empty vector if an invalid spg is entered.
*/
static const wyckoffPositions& getWyckoffPositions(uint spg);
static wyckPos getWyckPosFromWyckLet(uint spg, char wyckLet);
static const fillCellInfo& getFillCellInfo(uint spg);
static std::vector<std::string> getVectorOfDuplications(uint spg);
static std::vector<std::string> getVectorOfFillPositions(uint spg);
static double interpretComponent(const std::string& component,
double x, double y, double z);
/*
* Used to determine if a spacegroup is possible for a given set of atoms.
* It is determined by using the multiplicities in the Wyckoff database.
*
* @param spg The spacegroup to check.
* @param atomTypes A vector of atomic numbers (one for each atom). So if
* our system were Ti1O2, it should be {22, 8, 8}
*
* @return True if the spacegroup may be generated. False if it cannot.
*
*/
static bool isSpgPossible(uint spg, const std::vector<uint>& atomTypes);
/*
* Generates a latticeStruct (contains a, b, c, alpha, beta, and gamma as
* doubles) with randomly generated parameters for a given
* spacegroup, mins, and maxes. If a parameter must be constrained due
* to the spacegroup, it will be.
*
* @param spg The spacegroup for which to generate a lattice.
* @param mins The minimum values for the lattice parameters
* @param maxes The maximum values for the lattice parameters
*
* @return Returns the lattice struct that was generated. Returns a struct
* with all zero values if a proper lattice struct cannot be generated
* for a specific spacegroup due to invalid mins or maxes.
* An error message will be printed to stdout with information if it fails.
*/
static latticeStruct generateLatticeForSpg(uint spg,
const latticeStruct& mins,
const latticeStruct& maxes);
/*
* Attempts to add an atom randomly to a wyckoff position of a given crystal.
* The position of the atom is constrained by the given wyckoff position.
* It will attempt to add an atom randomly to satisfy minimum IAD for
* maxAttempts times, and if it fails, it returns false. If a fixed wyckoff
* position is given, it will just add the atom to the fixed wyckoff position.
* After it adds a Wyckoff atom, it attempts to fill the cell with it
* according to the spacegroup. If it fails, it will remove the new Wyckoff
* atom and try again.
*
* @param crystal The Crystal object for which an atom will be added
* @param position The wyckoff position to add the atom to
* @param atomicNum The atomic number of the atom to be added
* @param spg The spacegroup which we are creating.
* @param maxAttempts The number of attempts to make to add the atom randomly
* before the function returns false. Default is 1000.
*
* @return True if it succeeded, and false if it failed.
*/
static bool addWyckoffAtomRandomly(Crystal& crystal, const wyckPos& position,
uint atomicNum, uint spg,
int maxAttempts = 1000);
/*
* Initialze and return a Crystal object with a given spacegroup!
* The lattice mins and lattice maxes provide constraints for the lattice
* to be generated. The list of atom types tell it which atoms to be added.
* Returns a zero-volume Crystal object if it failed to generate it.
*
* @param spg The international number for the spacegroup to be generated
* @param atomTypes A vector of atomic numbers (one for each atom). So if
* our system were Ti1O2, it should be {22, 8, 8}
* @param latticeMins A latticeStruct that contains the minima for a, b, c,
* alpha, beta, and gamma.
* @param latticeMaxes A latticeStruct that contains the maxima for a, b, c,
* alpha, beta, and gamma.
* @param IADScalingFactor A scaling factor used to scale the IAD
* @param minVolume The minimum volume for the crystal to be generated.
* If set to -1, there is no minimum volume.
* @param maxVolume The maximum volume for the crystal to be generated.
* If set to -1, there is no maximum volume.
* @param numAttempts The max number number of attempts to generate a crystal
* given these conditions. It will still only find all
* combinations once (that's the most time consuming
* step). It will randomly pick combinations for every
* subsequent attempt from the combinations it found
* originally.
*
* @return A Crystal object with the given spacegroup, atoms,
* and lattice within the provided lattice constraints. Returns a Crystal
* with zero volume if it failed to generate one successfully.
*/
static Crystal randSpgCrystal(const randSpgInput& input);
static std::vector<numAndType> getNumOfEachType(
const std::vector<uint>& atoms);
static std::string getAtomAssignmentsString(const atomAssignments& a);
static void printAtomAssignments(const atomAssignments& a);
static void appendToLogFile(const std::string& text);
};
#endif
| [
"zfalls@me.com"
] | zfalls@me.com |
62b17dd7639bc184b96f4bbb0b81060739717e34 | d305e9667f18127e4a1d4d65e5370cf60df30102 | /tests/ut/cpp/stub/parallel_strategy_checkpoint/parallel_strategy_checkpoint_stub.cc | 6ae883cfbddc3b9954dc7e4e55694621d4a97d7e | [
"Apache-2.0",
"MIT",
"Libpng",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"AGPL-3.0-only",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"MPL-1.1",
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI",
"MPL-1.0",
"GPL-2.0-only",
"MPL-2.0",
"BSL-1.0",
"LicenseRef-scancode-unknow... | permissive | imyzx2017/mindspore_pcl | d8e5bd1f80458538d07ef0a8fc447b552bd87420 | f548c9dae106879d1a83377dd06b10d96427fd2d | refs/heads/master | 2023-01-13T22:28:42.064535 | 2020-11-18T11:15:41 | 2020-11-18T11:15:41 | 313,906,414 | 6 | 1 | Apache-2.0 | 2020-11-18T11:25:08 | 2020-11-18T10:57:26 | null | UTF-8 | C++ | false | false | 1,349 | cc | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <memory>
#include "frontend/parallel/strategy_checkpoint/parallel_strategy_checkpoint.h"
#include "utils/log_adapter.h"
namespace mindspore {
namespace parallel {
StrategyCheckpoint& StrategyCheckpoint::GetInstance() {
static StrategyCheckpoint instance = StrategyCheckpoint();
return instance;
}
bool StrategyCheckpoint::CheckPointExit(const std::string path) const { return false; }
Status StrategyCheckpoint::Load(StrategyMap* strategy_map) { return SUCCESS; }
Status StrategyCheckpoint::Save(const StrategyMap &strategy_map, const TensorInfoMap &tensor_info_map,
ManualShapeMap *manual_shape_map) { return SUCCESS; }
} // namespace parallel
} // namespace mindspore
| [
"513344092@qq.com"
] | 513344092@qq.com |
8f0bf8a21d7b5c2d991a80f63c12609a0e9353f0 | 18a3f93e4b94f4f24ff17280c2820497e019b3db | /geant4/G4PenelopeBremsstrahlungAngular.hh | 6989a61f4ca88b30460863eb682f7a2c850f53c1 | [] | no_license | jjzhang166/BOSS_ExternalLibs | 0e381d8420cea17e549d5cae5b04a216fc8a01d7 | 9b3b30f7874ed00a582aa9526c23ca89678bf796 | refs/heads/master | 2023-03-15T22:24:21.249109 | 2020-11-22T15:11:45 | 2020-11-22T15:11:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,160 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// -------------------------------------------------------------------
// $Id: G4PenelopeBremsstrahlungAngular.hh,v 1.3 2006/06/29 19:36:17 gunter Exp $
// GEANT4 tag $Name: geant4-09-03-patch-01 $
//
// Author: L.Pandola
//
// History:
// -----------
// 04 Feb 2003 L. Pandola 1st implementation
// 07 Nov 2003 L. Pandola Added method for testing
// Class description:
// Calculation of angular distribution for Penelope Bremsstrahlung
// --------------------------------------------------------------
#ifndef G4PENELOPEBREMSSTRAHLUNGANGULAR_HH
#define G4PENELOPEBREMSSTRAHLUNGANGULAR_HH 1
#include "globals.hh"
class G4PenelopeBremsstrahlungAngular
{
private:
enum{NumberofZPoints=6,
NumberofEPoints=6,
NumberofKPoints=4,
reducedEnergyGrid=21};
public:
G4PenelopeBremsstrahlungAngular(G4int Zmat);
~G4PenelopeBremsstrahlungAngular();
G4double ExtractCosTheta(G4double PrimaryEnergy,G4double GammaEnergy);
G4int GetAtomicNumber(); //testing purpose
private:
void InterpolationTableForZ(); //Initialization of tables (part 1)
void InterpolationForK(); //Initialization of tables (part 2)
G4double betas[NumberofEPoints]; //betas for interpolation
//tables for interpolation
G4double Q1[NumberofEPoints][NumberofKPoints],Q2[NumberofEPoints][NumberofKPoints];
//expanded tables for interpolation
G4double Q1E[NumberofEPoints][reducedEnergyGrid],Q2E[NumberofEPoints][reducedEnergyGrid];
//Z of the element
G4int Zmat;
};
#endif
| [
"r.e.deboer@students.uu.nl"
] | r.e.deboer@students.uu.nl |
dd4fc152e034689f653e90fe1376b61d5c021ac9 | 3f0f439d57f2185cb484f8faad78d49bab648627 | /src/CryptoNoteCore/CryptoNoteFormatUtils.h | 15bef559d29e05ae5170791dff17ae335283ac6d | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | b2n-project/bitcoin2network | f0f0d8c67e901004c9def6b39906c9edbc241554 | 0861d44ca8efd2c34c63acabe5468a094593d25d | refs/heads/master | 2020-03-18T04:40:53.034521 | 2019-02-16T07:32:31 | 2019-02-16T07:32:31 | 134,300,206 | 0 | 7 | MIT | 2019-02-16T07:32:32 | 2018-05-21T17:09:54 | C++ | UTF-8 | C++ | false | false | 4,701 | h | /*
* Copyright (c) 2018, The bitcoin2network developers.
* Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers.
*
* This file is part of bitcoin2network.
*
* This file is subject to the terms and conditions defined in the
* file 'LICENSE', which is part of this source code package.
*/
#pragma once
#include <boost/utility/value_init.hpp>
#include "CryptoNoteBasic.h"
#include "CryptoNoteSerialization.h"
#include "Serialization/BinaryOutputStreamSerializer.h"
#include "Serialization/BinaryInputStreamSerializer.h"
namespace Logging {
class ILogger;
}
namespace CryptoNote {
bool parseAndValidateTransactionFromBinaryArray(const BinaryArray& transactionBinaryArray, Transaction& transaction, Crypto::Hash& transactionHash, Crypto::Hash& transactionPrefixHash);
struct TransactionSourceEntry {
typedef std::pair<uint32_t, Crypto::PublicKey> OutputEntry;
std::vector<OutputEntry> outputs; //index + key
size_t realOutput; //index in outputs vector of real output_entry
Crypto::PublicKey realTransactionPublicKey; //incoming real tx public key
size_t realOutputIndexInTransaction; //index in transaction outputs vector
uint64_t amount; //money
};
struct TransactionDestinationEntry {
uint64_t amount; //money
AccountPublicAddress addr; //destination address
TransactionDestinationEntry() : amount(0), addr(boost::value_initialized<AccountPublicAddress>()) {}
TransactionDestinationEntry(uint64_t amount, const AccountPublicAddress &addr) : amount(amount), addr(addr) {}
};
bool constructTransaction(
const AccountKeys& senderAccountKeys,
const std::vector<TransactionSourceEntry>& sources,
const std::vector<TransactionDestinationEntry>& destinations,
std::vector<uint8_t> extra, Transaction& transaction, uint64_t unlock_time, Logging::ILogger& log);
bool is_out_to_acc(const AccountKeys& acc, const KeyOutput& out_key, const Crypto::PublicKey& tx_pub_key, size_t keyIndex);
bool is_out_to_acc(const AccountKeys& acc, const KeyOutput& out_key, const Crypto::KeyDerivation& derivation, size_t keyIndex);
bool lookup_acc_outs(const AccountKeys& acc, const Transaction& tx, const Crypto::PublicKey& tx_pub_key, std::vector<size_t>& outs, uint64_t& money_transfered);
bool lookup_acc_outs(const AccountKeys& acc, const Transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered);
bool get_tx_fee(const Transaction& tx, uint64_t & fee);
uint64_t get_tx_fee(const Transaction& tx);
bool generate_key_image_helper(const AccountKeys& ack, const Crypto::PublicKey& tx_public_key, size_t real_output_index, KeyPair& in_ephemeral, Crypto::KeyImage& ki);
bool get_block_hashing_blob(const BlockTemplate& block_template, BinaryArray& blob);
void get_tx_tree_hash(const std::vector<Crypto::Hash>& tx_hashes, Crypto::Hash& h);
Crypto::Hash get_tx_tree_hash(const std::vector<Crypto::Hash>& tx_hashes);
Crypto::Hash get_tx_tree_hash(const BlockTemplate& block_template);
bool getInputsMoneyAmount(const Transaction& tx, uint64_t& money);
bool checkInputTypesSupported(const TransactionPrefix& tx);
bool checkOutsValid(const TransactionPrefix& tx, std::string* error = nullptr);
bool checkMoneyOverflow(const TransactionPrefix &tx);
bool checkInputsOverflow(const TransactionPrefix &tx);
bool checkOutsOverflow(const TransactionPrefix& tx);
uint64_t get_outs_money_amount(const Transaction& tx);
std::string short_hash_str(const Crypto::Hash& h);
std::vector<uint32_t> relativeOutputOffsetsToAbsolute(const std::vector<uint32_t>& off);
std::vector<uint32_t> absolute_output_offsets_to_relative(const std::vector<uint32_t>& off);
// 62387455827 -> 455827 + 7000000 + 80000000 + 300000000 + 2000000000 + 60000000000, where 455827 <= dust_threshold
template<typename chunk_handler_t, typename dust_handler_t>
void decompose_amount_into_digits(uint64_t amount, uint64_t dust_threshold, const chunk_handler_t& chunk_handler, const dust_handler_t& dust_handler) {
if (0 == amount) {
return;
}
bool is_dust_handled = false;
uint64_t dust = 0;
uint64_t order = 1;
while (0 != amount) {
uint64_t chunk = (amount % 10) * order;
amount /= 10;
order *= 10;
if (dust + chunk <= dust_threshold) {
dust += chunk;
} else {
if (!is_dust_handled && 0 != dust) {
dust_handler(dust);
is_dust_handled = true;
}
if (0 != chunk) {
chunk_handler(chunk);
}
}
}
if (!is_dust_handled && 0 != dust) {
dust_handler(dust);
}
}
}
| [
"devs@bitcoin2.network"
] | devs@bitcoin2.network |
4a6aa025057f6c806831fd3fc1d0d8ec7d9ef581 | e3b809a8d1dc3432066d345b9d9deed8ed9bb5ef | /include/tim/vx/ops/layernormalization.h | e2803a226438579e5129e5be57339eae0f3f0890 | [
"MIT"
] | permissive | janoslim/TIM-VX | c389c8760c3f443a55cfe33ff7beb0e0dae338d2 | 2173730d8172504f10529523c128a73e4bdaf52c | refs/heads/main | 2023-05-10T14:52:10.890197 | 2021-06-16T04:25:49 | 2021-06-16T04:25:49 | 377,174,202 | 0 | 0 | MIT | 2021-06-15T13:33:54 | 2021-06-15T13:33:53 | null | UTF-8 | C++ | false | false | 1,729 | h | /****************************************************************************
*
* Copyright (c) 2021 Vivante Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TIM_VX_OPS_LAYERNOMALIZATION_H_
#define TIM_VX_OPS_LAYERNOMALIZATION_H_
#include <cstdint>
#include "tim/vx/operation.h"
namespace tim {
namespace vx {
namespace ops {
class LayerNormalization : public Operation {
public:
LayerNormalization(Graph* graph, int32_t axis = 0, float eps = 1e-5f);
protected:
int32_t axis_;
int32_t eps_;
};
} // namespace ops
} // namespace vx
} // namespace tim
#endif
| [
"kainan.cha@verisilicon.com"
] | kainan.cha@verisilicon.com |
dcb7d9767f77c097d263895720a7c72205d345d3 | 61b6e703410776462686efab82b4eb97add44567 | /LTIRobotics_v00/src/ardrone/tcp.cpp | ccb7682a8f9667e1673a0415a93bbf7c6a1563a9 | [] | no_license | mottamx/LTI_Robotics | 62012bdcf4b70110ed611ff38929ef6dfe88a256 | ded4d1ead9898bd0fd9f9f840009efcb42490b91 | refs/heads/master | 2016-09-05T15:25:02.423455 | 2013-08-13T05:36:32 | 2013-08-13T05:36:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,372 | cpp | #include "ardrone.h"
// --------------------------------------------------------------------------
// TCPSocket::TCPSocket()
// Constructor of TCPSocket class. This will be called when you create it.
// --------------------------------------------------------------------------
TCPSocket::TCPSocket()
{
sock = INVALID_SOCKET;
}
// --------------------------------------------------------------------------
// TCPSocket::~TCPSocket()
// Destructor of TCPSocket class. This will be called when you destroy it.
// --------------------------------------------------------------------------
TCPSocket::~TCPSocket()
{
closeE();
}
// --------------------------------------------------------------------------
// TCPSocket::open(IP address, Port number)
// Initialize specified socket.
// Return value SUCCESS: 1 FAILED: 0
// --------------------------------------------------------------------------
int TCPSocket::open(const char *addr, int port)
{
// Create a socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
printf("ERROR: socket() failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Set the port and address of server
memset(&server_addr, 0, sizeof(sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons((u_short)port);
//server_addr.sin_addr.S_un.S_addr = inet_addr(addr);
server_addr.sin_addr.s_addr= inet_addr(addr);
// Connect the socket
if (connect(sock, (sockaddr*)&server_addr, sizeof(sockaddr_in)) == SOCKET_ERROR) {
printf("ERROR: connect() failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Set to the non-blocking mode
u_long nonblock = 1;
//if (ioctlsocket(sock, FIONBIO, &nonblock) == SOCKET_ERROR) {
if (ioctl(sock, FIONBIO, &nonblock) == SOCKET_ERROR) {
printf("ERROR: ioctlsocket() failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Enable re-use address option
int reuse = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) == SOCKET_ERROR) {
printf("ERROR: setsockopt() failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
return 1;
}
// --------------------------------------------------------------------------
// TCPSocket:::send2(Sending data, Size of data)
// Sending the specified data.
// Return value SUCCESS: Number of sent bytes FAILED: 0
// --------------------------------------------------------------------------
int TCPSocket::send2(void *data, int size)
{
// The socket is invalid
if (sock == INVALID_SOCKET) return 0;
// Send the data
int n = send(sock, (char*)data, size, 0);
if (n < 1) return 0;
return n;
}
// --------------------------------------------------------------------------
// TCPSocket:::sendf(Your messages)
// Sending the data with printf()-like format.
// Return value SUCCESS: Number of sent bytes FAILED: 0
// --------------------------------------------------------------------------
int TCPSocket::sendf(char *str, ...)
{
va_list arg;
char msg[1024];
// The socket is invalid
if (sock == INVALID_SOCKET) return 0;
// Apply format
va_start(arg, str);
vsprintf_s(msg, sizeof(msg), str, arg);
va_end(arg);
// Send data
return send2(msg, (int)strlen(msg) + 1);
}
// --------------------------------------------------------------------------
// TCPSocket::receive(Receiving data, Size of data)
// Receive the data.
// Return value SUCCESS: Number of received bytes FAILED: 0
// --------------------------------------------------------------------------
int TCPSocket::receive(void *data, int size)
{
// The socket is invalid
if (sock == INVALID_SOCKET) return 0;
// Receive data
int received = 0;
while (received < size) {
int n = recv(sock, (char*)data + received, size - received, 0);
if (n < 1) break;
received += n;
}
return received;
}
// --------------------------------------------------------------------------
// TCPSocket::close()
// Finalize the socket.
// Return value NONE
// --------------------------------------------------------------------------
void TCPSocket::closeE(void)
{
// Close the socket
if (sock != INVALID_SOCKET) {
close(sock);
sock = INVALID_SOCKET;
}
}
| [
"cmottaa@gmail.com"
] | cmottaa@gmail.com |
b5fa222c0cc281d88392c681e66b341826fb1789 | aa1ef21bf7aa0fab6d5b9f429b086eced97c7b8e | /codeforces/667div3/5.cpp | 874877fa77cb1d7d960784211cd23b222bd76fe3 | [] | no_license | vd-07/CP | ad8f7a0b71e53e2f83b0a69d344f3cf9b9c77580 | 15b0c69574111ebca4b9f428f84d10884bc65bcd | refs/heads/main | 2021-09-08T07:35:16.804319 | 2021-08-04T16:58:47 | 2021-08-04T16:58:47 | 207,377,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,898 | cpp | //Author : Vivek Dubey
#include <bits/stdc++.h>
using namespace std;
// debug start
template <typename A, typename B>
string to_string(pair<A, B> p);
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {
return '"' + s + '"';
}
string to_string(const char* s) {
return to_string((string) s);
}
string to_string(bool b) {
return (b ? "true" : "false");
}
string to_string(vector<bool> v) {
bool first = true;
string res = "{";
for (int i = 0; i < static_cast<int>(v.size()); i++) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(v[i]);
}
res += "}";
return res;
}
template <size_t N>
string to_string(bitset<N> v) {
string res = "";
for (size_t i = 0; i < N; i++) {
res += static_cast<char>('0' + v[i]);
}
return res;
}
template <typename A>
string to_string(A v) {
bool first = true;
string res = "{";
for (const auto &x : v) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(x);
}
res += "}";
return res;
}
template <typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}
template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
#ifndef ONLINE_JUDGE
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif
// end debug
#define int long long
const int mxN = 3e5 + 1;
int n, k;
int a[mxN];
int intersection(int l1, int r1, int l2, int r2) {
if(l1 > l2) {
swap(l1, l2);
swap(r1, r2);
}
if(l1 == l2) {
if(r1 > r2) {
swap(r1, r2);
}
l2 = r1;
}
if(l2 <= r1 ) {
l2 = r1;
}
if(r2 < r1) {
r2 = r1;
}
if(r1 == l2) {
return r1 - l1 + r2 - l2 + 1;
}
return r1 - l1 + r2 - l2 + 2;
}
void solve() {
cin >> n >> k;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
int temp;
for(int i = 0; i < n; i++) {
cin >> temp;
}
if(n <= 2) {
cout << n << "\n";
return;
}
sort(a, a + n);
// for(int i = 0; i < n; i++) {
// cerr << i << " : " << a[i] << " ; ";
// }
// int total1 = 0;
vector<int> suffix(n), prefix(n);
int j = 0;
for(int i = 0; i < n; i++) {
while(a[i] - a[j] > k) j++;
prefix[i] = i - j + 1;
}
j = n - 1;
for(int i = n - 1; i >= 0; i--) {
while(a[j] - a[i] > k) j--;
suffix[i] = j - i + 1;
}
for(int i = n - 2; i >= 0; i--) {
suffix[i] = max(suffix[i + 1], suffix[i]);
}
for(int i = 1; i < n; i++) {
prefix[i] = max(prefix[i], prefix[i - 1]);
}
int total = 0;
for(int i = 0; i < n - 1; i++) {
// no clear thoughts
total = max(total, prefix[i] + suffix[i + 1]);
}
cout << min(total, n) << "\n";
}
int32_t main() {
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input.txt", "r", stdin);
// for writing output to output.txt
//this can be opted out if you want to print the output to the sublime console
freopen("output.txt", "w", stdout);
#endif
// for fast i/o
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// test cases
int t = 1;
cin >> t;
while(t--) {
solve();
}
return 0;
} | [
"dubey.vivek.2805@gmail.com"
] | dubey.vivek.2805@gmail.com |
c0d7bbd94e8e5f2fabed421af1a3f7abb99b6149 | 62d23b5249c771f599f882a1508fef1d3403f64d | /sf_perm.cc | b35b28ea1b341f75a049f802e60bd187b8ed7c27 | [] | no_license | dgleich/sparfun | d5b63fbf7b7e7ad7b0a6ee2141ef8c62edcdec8a | ca8454f51530c17efb4d677e23829a09f0d29290 | refs/heads/master | 2016-08-03T09:48:14.555192 | 2013-08-08T14:50:03 | 2013-08-08T14:50:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cc | /**
* @file sf_perm.hpp
* Simple codes to work with permutations
*/
/**
* History
* -------
* :2011-03-05: Initial version based on overlapping/hypercluster.cc
*/
// TODO add tests for this code
// TODO add documentation for inverse_permutation
// TODO add sparfun.h headers for these functions
#include <vector>
#include <algorithm>
template <typename T, typename index_type = int>
class sort_order_comparison {
const std::vector<T>& items;
public:
sort_order_comparison(const std::vector<T>& i) : items(i) {}
bool operator() (index_type i, index_type j) {
return items[i] > items[j];
}
};
/**
* This function sorts in descending order
* @param order this parameter is an output and will be initialized
*/
template <typename T>
void sort_permutation(const std::vector<T>& a, std::vector<int>& order) {
order.resize(a.size());
for (size_t i=0; i<a.size(); ++i) {
order[i] = (int)i;
}
sort_order_comparison<T> comp(a);
std::sort( order.begin(), order.end(), comp );
}
template <typename Index>
void inverse_permutation(const std::vector<Index>& perm, std::vector<Index>& inv) {
inv.resize(perm.size());
for (size_t i=0; i<perm.size(); ++i) {
inv[perm[i]] = i;
}
}
| [
"dfgleic@sandia.gov"
] | dfgleic@sandia.gov |
222b323df65173c6ef27668e46c681f01c63fbbe | f835c659cc4990ac8b83891148119f9380dc11f3 | /docs/algorithm/leetcode/dynamic programming/DP_M_seconde_N_meter_goHOME.cpp | 536b189ed7e768a54de3e172198b4b914dce8aed | [] | no_license | qwfand/Blogs | 843880d6717a0612974f78fdb25c8bb3a9d28ea8 | b99430046a7f78fd2f721b4047b3b3eae21ee898 | refs/heads/master | 2021-11-24T02:52:44.326679 | 2021-10-25T07:42:14 | 2021-10-25T07:42:14 | 253,464,817 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include<bits/stdc++.h>
#define inf 100
using namespace std;
typedef long long ll;
int main()
{
int m, n;
//vector<vector<int> >dp(1000,)
//int dp[100001][10001];
vector< vector<int> > dp(1001, vector<int>(1001, 0));
cin >> n >> m;
int cost[10001];
for (int i = 1; i <= m; i++)
cin >> cost[i];
dp[1][1] = cost[1]/3;
dp[1][2] = cost[1] / 2;
dp[1][3] = cost[1];
for (int i = 4; i <= n; i++)
dp[1][i] = inf;
for (int i = 1; i <= m; i++)//second
{
dp[0][i] =inf;
}
for(int i=2;i<=m;i++)//second
for (int j = 1; j <= n; j++)//distance
{
vector<int> v;
v.push_back(dp[i - 1][j]);
if (j - 1 >= 0)
v.push_back(dp[i - 1][j - 1] + cost[i] / 3);
if (j - 2 >= 0)
v.push_back(dp[i - 1][j - 2] + cost[i] / 2);
if (j - 3 >= 0)
v.push_back(dp[i - 1][j - 3] + cost[i]);
sort(v.begin(), v.end());
dp[i][j] = v[0];
}
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
cout << dp[i][j] << " ";
cout << endl;
}
system("pause");
/*
5 5
10000 2 3 4 10000*/
return 0;
} | [
"qwfand@qq.com"
] | qwfand@qq.com |
f1de16480397badec9afb7eacd7accd2f62fd11d | 50ae4239fe59bb384aa0ffa9d0010eacd36c6d83 | /Ferry/Bus.cpp | bc92579fc1ffe983ab2c62524d3daf7c528914f7 | [] | no_license | Walkmilton/Software-Design | 8e817a91f585e04643a210d7239c6f6652bd9aae | f794b9733dca6d3f31ef57eb5f3ce9d48ff13b6a | refs/heads/master | 2020-04-23T16:03:41.847358 | 2019-02-18T13:08:36 | 2019-02-18T13:08:36 | 171,285,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp |
#include "Bus.h"
//constructor and destructor
Bus::Bus(int p, int c, string r, float l) : Vehicle(r, l)
{
PSV = p;
capacity = c;
}
Bus::~Bus()
{
}
//getters and setters
int Bus::getPSV()
{
return PSV;
}
void Bus::setPSV(int p)
{
PSV = p;
}
int Bus::getCapacity()
{
return capacity;
}
void Bus::setCapacity(int c)
{
capacity = c;
}
| [
"dex.doyle@me.com"
] | dex.doyle@me.com |
95258a15a4562f39a8a1242ba527f5b5dadf6f75 | 054d51d90fc6abb0a6153f5fcf18ecbdacd18407 | /interview_Code/Code/Huisu-6-LeetCode60-getPermutation.cc | b94c58329e7e4a7a221bd56c967dda50b177ee22 | [] | no_license | Stephenhua/CPP | c40c4c69bffc37546ed00f16289e0b24293c59f9 | bbaa84aabf17cf8e9c1eccaa73ba150c8ca20ec4 | refs/heads/master | 2020-12-30T03:42:44.502470 | 2020-09-18T14:56:38 | 2020-09-18T14:56:38 | 238,844,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,117 | cc | #include <iostream>
#include <vector>
#include <cmath>
#include <map>
#include <algorithm>
#include <string.h>
using namespace std;
/*
60. 第k个排列
给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定 n 和 k,返回第 k 个排列。
说明:
给定 n 的范围是 [1, 9]。
给定 k 的范围是[1, n!]。
示例 1:
输入: n = 3, k = 3
输出: "213"
示例 2:
输入: n = 4, k = 9
输出: "2314"
*/
int getMul( int n){
int res = 1;
for( int i=2 ;i<=n ;i++){
res *= i;
}
return res;
}
string getPermutation(int n, int k) {
string res = "";
vector<int> nums;
for( int i=1 ;i<=n ;i++){
nums.push_back(i);
}
for( int j = 0 ; j < n ; j++){
int len = nums.size();
for( int i = 1 ; i <= len ; i++){
int n = getMul( len-1);
if( (( i-1) * n < k ) && (k<= i*n)){
char c = '0' + nums[i-1];
res += c;
nums.erase(nums.begin()+(i-1));
k -= (i-1) * n;
break;
}
}
}
return res;
}
//根据节点固定的位置进行选择求解;
/*
我们可以从左往右遍历原先字符串的最小排列,每一次找到应该放在左边第一个位置的数字,将其添加到结果字符串中,并从原字符串中删除,然后对剩下的字符串重复这一操作,直到k==0。此外由于字符串最初的状态就是第1个排列,所以要将输入的k先减一。
*/
vector<int> fac = {0,1,2,6,24,120,720,5040,40320,362880,3628800};
string getPermutation(int n, int k) {
string res;
string s = string("123456789").substr(0,n);
--k;
while( k > 0 ){
int i = k /fac[n-1];//表示在这个字符之前的个数都是小于K的;
res.push_back(s[i]);
s.erase(s.begin()+i);//减枝操作;去掉当前存在的元素;
k %= fac[n-1];
--n;
}
return res+s;
} | [
"04121390@cumt.edu.cn"
] | 04121390@cumt.edu.cn |
c0837d20b5446a9b27046d54265bcea7a6084ae4 | ce9c27588fc2bb76d7f813f6b02082c07b03d6b8 | /GoogleCodeJam/2015/qualification/d.cpp | 13142941fb6e29e329dda86a3ceddbc1248f4bd1 | [] | no_license | mrain/acm | e1c163a7a360b5296b5f2026ba0115e12aac1453 | 1db45a01ca37a1483d291eb5142708347e886684 | refs/heads/master | 2021-01-17T09:25:55.963574 | 2016-05-26T08:23:37 | 2016-05-26T08:23:37 | 2,046,928 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#include <map>
#include <vector>
#include <sstream>
using namespace std;
int T, x, n, m;
int main() {
cin >> T;
for (int t = 0; t < T; ++ t) {
cin >> x >> n >> m;
}
return 0;
}
| [
"linmrain@gmail.com"
] | linmrain@gmail.com |
502e3cfb5ae92b7c72d763b602f2021d34342f21 | ebb12cac1c29373be6d2bc2c3571970f83132ccc | /Microsoft/Maker/Serial/Serial/USBSerial.h | 6950bfb554cb928cbff34b7f83bb2533ea6ee417 | [] | no_license | yvanvds/interact | a39d85eee9fbb8a94e74ef1f4db6db31a4ca62b8 | f2ccb4731d4a1a2af2116e457fce5e3ddc8989dc | refs/heads/master | 2022-12-09T20:11:20.667610 | 2019-10-30T18:57:51 | 2019-10-30T18:57:51 | 94,017,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,918 | h | /*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
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.
*/
#pragma once
#include "IStream.h"
#include <mutex>
namespace Microsoft {
namespace Maker {
namespace Serial {
public ref class UsbSerial sealed : public IStream
{
public:
virtual event IStreamConnectionCallback ^ConnectionEstablished;
virtual event IStreamConnectionCallbackWithMessage ^ConnectionLost;
virtual event IStreamConnectionCallbackWithMessage ^ConnectionFailed;
[Windows::Foundation::Metadata::DefaultOverload]
///<summary>
///A constructor which accepts a string corresponding to a device VID to connect to.
///</summary>
UsbSerial(
Platform::String ^vid_
);
///<summary>
///A constructor which accepts two strings corresponding to a device VID and PID to connect to.
///</summary>
UsbSerial(
Platform::String ^vid_,
Platform::String ^pid_
);
///<summary>
///A constructor which accepts a DeviceInformation object to explicitly specify which device to connect to.
///</summary>
UsbSerial(
Windows::Devices::Enumeration::DeviceInformation ^device_
);
virtual
~UsbSerial(
void
);
virtual
uint16_t
available(
void
);
virtual
void
begin(
uint32_t baud_,
SerialConfig config_
);
virtual
bool
connectionReady(
void
);
virtual
void
end(
void
);
virtual
void
flush(
void
);
virtual
void
lock(
void
);
virtual
uint16_t
read(
void
);
virtual
void
unlock(
void
);
virtual
uint32_t
write(
uint8_t c_
);
///<summary>
///Begins an asyncronous request for all USB devices that are connected and may be used to attempt a device connection.
///</summary>
static
Windows::Foundation::IAsyncOperation<Windows::Devices::Enumeration::DeviceInformationCollection ^> ^
listAvailableDevicesAsync(
void
);
private:
//maximum amount of data that may be read at a time, allows efficient reads
static const uint8_t MAX_READ_SIZE = 100;
// Device specific members (set during instantation)
Windows::Devices::Enumeration::DeviceInformation ^_device;
Platform::String ^_pid;
Platform::String ^_vid;
//thread-safe mechanisms. std::unique_lock used to manage the lifecycle of std::mutex
std::mutex _usbutex;
std::unique_lock<std::mutex> _usb_lock;
uint32_t _baud;
SerialConfig _config;
std::atomic_bool _connection_ready;
Windows::Storage::Streams::DataReaderLoadOperation ^_current_load_operation;
Windows::Devices::Enumeration::DeviceInformationCollection ^_device_collection;
Windows::Devices::SerialCommunication::SerialDevice ^_serial_device;
Windows::Storage::Streams::DataReader ^_rx;
Windows::Storage::Streams::DataWriter ^_tx;
Concurrency::task<void>
connectToDeviceAsync(
Windows::Devices::Enumeration::DeviceInformation ^device_
);
Windows::Devices::Enumeration::DeviceInformation ^
identifyDeviceFromCollection(
Windows::Devices::Enumeration::DeviceInformationCollection ^devices_
);
};
} // namespace Serial
} // namespace Maker
} // namespace Microsoft
| [
"yvan@attr-x.net"
] | yvan@attr-x.net |
183396ea430d46d8b062373a33c54b820aaa9064 | 40f66039299eaadb3556087470199c056d09e366 | /2019_11_week5/niklasjang_12929.cpp | b4c32a7b99e6db427a37112b3d351692b24498ef | [] | no_license | kau-algorithm-study/algorithm | e76d34142f40bee2dab40ed5cf478de3b90f0add | 86ab97c67d75b71fbd0e82b4170ad34ee4ebbb0b | refs/heads/master | 2020-09-03T00:58:57.941964 | 2019-12-30T12:28:20 | 2019-12-30T12:28:20 | 219,346,077 | 2 | 12 | null | 2019-12-02T10:42:40 | 2019-11-03T18:26:43 | C++ | UTF-8 | C++ | false | false | 1,959 | cpp | /*
괄호문제는 일단 stack이 먼저 생각난다. 하지만 ((()))의 경우 (((까지 넣었을 때 왼쪽 괄호를 몇개 넣었느지 알고있어야 한다는 문제가 있다. 재귀의 매개변수가 많아지기도 하고 복잡해진다. 더 간단한 방법을 생각해보자.
1. n을 입력받아서 최대 2*n개의 괄호를 넣을 수 있다. 왼쪽 괄호를 +1, 오른쪽 괄호를 -1로 생각하자.
2. ((()))의 예제에서 볼 수 있듯이 왼쪽괄호가 먼저 많이 들어가는 것은 문제가 되지 않는다. 오른쪽 괄호를 맞춰서 넣으면 되니까.
3. 하지만 오른쪽 괄호를 왼쪽괄호보다 많이 넣으면 고칠 수가 없다. 이는 +1/-1의 개념을 적용해서 음수가 된 경우 오른쪽 괄호가 왼쪽 괄호보다 많은 경우라고 생각할 수 있다.
4. 재귀가 끝나는 조건은 자명하게 2*n개의 괄호를 넣었을 때이고,
5. 중간에 재귀를 더이상 진행하지 않아도 되는 경우는 음수가 되었을 때다.
6. 그리고 매 재귀마다 왼쪽괄호를 넣을 수도 있고, 오른쪽 괄호를 넣을 수도 있다.
7. ndl 14이므로 2*n 은 28이고 2^28은 1억보다 작다.
*/
#include <string>
#include <vector>
using namespace std;
int len = 0;
int foo(int count, int sum){
if(sum < 0) return 0;
if(count == 2 * len){
if(sum == 0) return 1;
else return 0;
}
return foo(count+1, sum+1) + foo(count+1, sum-1);
}
int solution(int n) {
len = n;
return foo(0,0);
}
/*
sum을 사용하지 않고 왼쪽 괄호/오른쪽 괄호의 갯수로 푼 경우
*/
#include <string>
#include <vector>
using namespace std;
int len = 0;
int foo(int left, int right){
if(left < right) return 0;
if(left + right == 2 * len){
if(left == right) return 1;
else return 0;
}
return foo(left+1, right) + foo(left, right+1);
}
int solution(int n) {
len = n;
return foo(0,0);
}
| [
"niklasjang@gmail.com"
] | niklasjang@gmail.com |
b2abaebe9222c2844662644e78bdad9c25445354 | 7e0b03d81a57407f199238559daa3335ed7353ab | /answers/pr39_ans.cpp | 560b60edd36165df306f6c2a6fd95a99bb6c6196 | [] | no_license | U-Ar/ModernCppChallengePractice | 460e925579e0f1eac097cb421e5f5c333d529e5a | 6d3f31d654eb52faa437d94745942aa60bd373f4 | refs/heads/main | 2023-01-01T11:53:30.984636 | 2020-10-22T00:45:48 | 2020-10-22T00:45:48 | 306,176,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | cpp | #include<iostream>
#include<sstream>
#include<string>
#include<algorithm>
#include<iterator>
#include<cmath>
#include<cassert>
#include<array>
#include<vector>
#include<iomanip>
#include<locale>
#include<regex> //regexヘッダで正規表現
#include<optional> //optional(C++17)
#include<ios>
#include<iomanip>
#include<fstream>
#include<chrono>
#include<functional>
#include<thread>
//#include<filesystem>
namespace ch = std::chrono;
template <typename Time = std::chrono::microseconds,
typename Clock = std::chrono::high_resolution_clock>
struct perf_timer
{
template <typename F, typename... Args>
static Time duration(F&& f, Args... args)
{
auto start = Clock::now();
std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
auto end = Clock::now();
return std::chrono::duration_cast<Time>(end-start);
}
};
using namespace std::chrono_literals;
void f()
{
std::this_thread::sleep_for(2s);
}
void g(const int a, const int b)
{
std::this_thread::sleep_for(1s);
}
int main()
{
std::cout << perf_timer<std::chrono::microseconds>::duration(f).count() << " " <<
perf_timer<std::chrono::milliseconds>::duration(g,4,3).count() << std::endl;
}
| [
"yuma.arakawa82128awakara.amuy@gmail.com"
] | yuma.arakawa82128awakara.amuy@gmail.com |
031d752b74c8101eada98cdf7f6f2d4d6640bab8 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /components/exo/wayland/wl_output.h | 9721629c231a96c59f59e11576f3aa64b452f7ca | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 547 | h | // Copyright 2018 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.
#ifndef COMPONENTS_EXO_WAYLAND_WL_OUTPUT_H_
#define COMPONENTS_EXO_WAYLAND_WL_OUTPUT_H_
#include <stdint.h>
struct wl_client;
namespace exo {
namespace wayland {
constexpr uint32_t kWlOutputVersion = 3;
void bind_output(wl_client* client, void* data, uint32_t version, uint32_t id);
} // namespace wayland
} // namespace exo
#endif // COMPONENTS_EXO_WAYLAND_WL_OUTPUT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
88a656c5f742e80cd72a327ee8e528749c562db6 | 079704a778fe46edb2ac5e9488599e731e8cd5cf | /Arduino/Stair_First_Floor.ino | c2b82f5a42bd2fb05ddbbdfdd3b764e1cc6a5566 | [] | no_license | jpservices01/Stair-Shield | 0097ac99e637ae585f141f1fdbf623fb6307e87f | 84625766187a0e8a0563c3f635d60bb77774331a | refs/heads/master | 2021-01-17T18:57:03.608520 | 2016-06-08T18:44:45 | 2016-06-08T18:44:45 | 60,711,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,108 | ino |
#include <TimerOne.h>
#include <TimerThree.h>
int DAI = 6; // Serial input DM13A pin 2
int DCK = 7; // Clock DM13A pin 3
int LAT = 8; // Output latch DM13A pin 4
int EN = 9; // Output enable (active low) DM13A pin 21
int feedSpeed = 100; // speed at wich the leds will be rolled on
int dropSpeed = 200; // speed at wich the leds will be rolled off
int brightness = 0; // how bright the LED is
int fadeAmount = 1; // how many points to fade the LED (ATTENTION cannot changed without checking the brightness control)
boolean fadeIn = false; // when true then a fade in sequence is starting and runing until full fade in
// when switched to true to false then start a fade out sequence
int fadeInSpeed = 10000; // speed at which the fadeIn /out will be performed (in micro seconds)
volatile int fadeCounter = 0;
byte motionUpStairs=10;
byte motionMidStairs=11;
boolean goingUp=false;
void pwmHandler(){
fadeCounter = (fadeCounter + 1)%255;
if (fadeCounter >= brightness)
{
digitalWrite(EN,HIGH);
}
else
{
digitalWrite(EN,LOW);
}
}
void brightnessControl()
{
noInterrupts();
if (fadeIn)
{
brightness = brightness + fadeAmount;
if (brightness > 255) brightness = 255;
}
else
{
brightness = brightness - fadeAmount;
if (brightness < 0) brightness = 0;
}
interrupts();
// analogWrite(13,brightness);
// analogWrite(13,0);
}
void clockReg()
{
digitalWrite(DCK,HIGH);
digitalWrite(DCK,LOW);
}
void latchReg()
{
digitalWrite(LAT,HIGH);
digitalWrite(LAT,LOW);
}
void writeReg (word val)
{
int i;
word value;
value = val;
for (i=0;i<16;i++)
{
digitalWrite(DAI,value>32767);
value = value << 1;
clockReg();
}
latchReg();
}
void feedDown (word nbLed)
{
int i;
digitalWrite(DAI,HIGH);
fadeIn = true;
for (i=0;i<nbLed;i++)
{
clockReg();
latchReg();
delay(feedSpeed);
if (i == 6)
{
delay(2000); // delay if light reached the half floor
}
}
}
void dropDown (word nbLed)
{
int i;
digitalWrite(DAI,LOW);
fadeIn = false;
for (i=0;i<nbLed;i++)
{
clockReg();
latchReg();
delay(dropSpeed);
}
}
void feedUp (word nbLed)
{
int i;
word val=0;
fadeIn = true;
for (i=nbLed-1;i>=0;i--)
{
val = val + round(pow(2,i));
writeReg(val);
delay(feedSpeed);
if (i == 7)
{
delay(2000); // delay if light reached the half floor
}
}
}
void dropUp (word nbLed)
{
int i;
word val=0;
val = round(pow(2,nbLed))-1;
fadeIn = false;
for (i=nbLed-1;i>=0;i--)
{
val = val - round(pow(2,i));
writeReg(val);
delay(dropSpeed);
}
}
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(13, OUTPUT);
pinMode(DAI, OUTPUT);
pinMode(DCK, OUTPUT);
pinMode(LAT, OUTPUT);
pinMode(EN, OUTPUT);
digitalWrite(DAI,LOW);
digitalWrite(DCK,LOW);
digitalWrite(LAT,LOW);
digitalWrite(EN,LOW);
pinMode(motionUpStairs,INPUT);
pinMode(motionMidStairs,INPUT);
Serial.begin(9600);
Timer1.initialize(50); // initialize timer1 to handle the software PWM
Timer1.attachInterrupt(pwmHandler); // attaches callback() as a timer overflow interrupt
Timer3.initialize(fadeInSpeed); // initialize timer3 to handle the feed in/out speed of leds
Timer3.attachInterrupt(brightnessControl); // attaches callback() as a timer overflow interrupt
}
// the loop routine runs over and over again forever:
void loop() {
int val = 1;
int i=0;
int j=0;
Serial.println("Start...");
writeReg(0);
delay(1000);
writeReg(1);
fadeIn=true;
delay(1000);
writeReg(2);
delay(1000);
writeReg(4);
delay(1000);
writeReg(8);
delay(1000);
writeReg(128);
delay(1000);
fadeIn=false;
delay(5000);
writeReg(0);
delay(1000);
feedUp(15);
delay(1000);
dropDown(15);
delay(1000);
writeReg(0);
while(1)
{
i = 0;
j = 0;
while ((i < 3) && (j < 3))
{
i = i + 1;
j = j + 1;
if (digitalRead(motionUpStairs) == 0)
{
i = 0;
}
if (digitalRead(motionMidStairs) == 0)
{
j= 0;
}
delay(10);
}
analogWrite(13,120);
goingUp = false;
writeReg(0);
if (i > (3-1))
{
Serial.println("Turn on down");
feedDown(15);
}
else if (j > (3-1))
{
Serial.println("Turn on up");
feedUp(15);
goingUp = true;
}
delay(10000);
// wait for motion detector to reset
i = 0;
while (i < 5)
{
i = i + 1;
if ((digitalRead(motionUpStairs) != 0) || (digitalRead(motionMidStairs) != 0))
{
i = 0;
}
delay(10);
}
if (goingUp)
{
Serial.println("Turn off up");
dropUp(15);
}
else
{
Serial.println("Turn off down");
dropDown(15);
}
analogWrite(13,0);
}
}
| [
"besuchetjp@compuserve.com"
] | besuchetjp@compuserve.com |
d3bd8ed0973307cf75fdc3f811d7b4e4ec59d534 | ad65bc6556c6ceda1ece13f46ffe236617981b1c | /sequential-operations-4/bruteforce.cpp | 4f19abc30fb8b690cd28005116169592efae4f76 | [] | no_license | MamnoonSiam/polygon | 381df073553e0a73e4a97e5cb20b9c632aed93b6 | eaf7d680ecaa1554a7fa0678b0d8d387b6158805 | refs/heads/main | 2023-07-14T01:33:43.615049 | 2021-08-20T23:40:45 | 2021-08-20T23:40:45 | 398,422,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
#define all(v) begin(v), end(v)
#define sz(v) (int)(v).size()
#define fi first
#define se second
const int md = 1e9 + 7;
int add(int x, int y) {
if((x += y) >= md) x -= md;
return x;
}
int sub(int x, int y) {
if((x -= y) < 0) x += md;
return x;
}
struct pt {
int x = 0, y = 0;
pt() {}
pt(int _x, int _y) : x(_x), y(_y) {}
pt operator - (const pt& o) const {
return pt(sub(x, o.x), sub(y, o.y));
}
pt operator + (const pt& o) const {
return pt(add(x, o.x), add(y, o.y));
}
};
void rotate90ccw(pt& p) {
swap(p.x, p.y);
// p.y = sub(0, p.y);
p.x = sub(0, p.x);
}
void rotateccwwrt(pt p, pt& q, int t) {
q = q - p;
while(t--) rotate90ccw(q);
q = q + p;
}
int main(int argc, char const *argv[])
{
#ifdef LOCAL
freopen("in", "r", stdin);
#endif
int n, q;
scanf("%d %d", &n, &q);
vector<int> x(n), y(n), t(n);
for(int i = 0; i < n; ++i) {
scanf("%d", &x[i]);
x[i] = add(md, x[i]);
}
for(int i = 0; i < n; ++i) {
scanf("%d", &y[i]);
y[i] = add(y[i], md);
}
for(int i = 0; i < n; ++i) {
scanf("%d", &t[i]);
}
while(q--) {
int T; scanf("%d", &T);
if(T == 1) {
int i, xp, yp, tp;
scanf("%d %d %d %d", &i, &xp, &yp, &tp);
--i;
x[i] = add(md, xp), y[i] = add(md, yp), t[i] = tp;
} else {
int l, r, xx, yy;
scanf("%d %d %d %d", &l, &r, &xx, &yy);
pt p(add(md, xx), add(md, yy));
for(int i = l-1; i < r; ++i) {
rotateccwwrt(pt(x[i], y[i]), p, t[i]);
}
printf("%d %d\n", p.x, p.y);
}
}
return 0;
}
/*
* use std::array instead of std::vector, if u can
* overflow?
* array bounds
*/ | [
"siammamnoon@gmail.com"
] | siammamnoon@gmail.com |
28cc5ba9052c4531cca55f45b75a9c279fe2a7ea | 4a50dedb00faee7f03d5d5615eb2104f1a32968e | /final_jjennin/checkvalid.cpp | edc75f9aec7942802ba03b8bdb94eb57528f8b59 | [] | no_license | jjennin/odu-cs250 | 75b03cfe19edb3cd879497e68924d618dfb5d948 | 0697ec01527263e22b03c1a44a28d9b6440c34e6 | refs/heads/master | 2021-09-10T07:00:02.610538 | 2018-03-22T01:33:51 | 2018-03-22T01:33:51 | 124,950,536 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | #include "checkvalid.h"
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
// checks validity of email
void checkEmail(string& x)
{
bool valid = false;
while(!valid)
{
for(unsigned i = 0; i < x.length(); i++)
{
if(x[i] == '@')
valid = true;
}
if(!valid)
{
cout << "Please enter a valid email! (includes @): ";
cin >> x;
}
}
}
// checks validity of phone
void checkPhone(string& x)
{
while(x.length() != 10)
{
if(x.length() < 10)
cout << "Number too short! Try again: ";
if(x.length() > 10)
cout << "Number too long! Try again: ";
cin >> x;
}
}
// checks validity of phone
void checkGender(char& x)
{
while(x != 'M' && x!= 'F')
{
cout << "Enter a valid gender (M/F): ";
cin >> x;
}
}
// checks validity of blood type
void checkBloodType(string &x)
{
while(x != "A+" && x != "A-" && x != "B+" && x != "B-" && x != "O+" && x != "O-" && x != "AB" )
{
cout << "(A+,A-,B+,B-,O+,O-,AB)" << endl;
cout << "Incorrect Blood Type: ";
cin >> x;
}
}
| [
"jjenn001@odu.edu"
] | jjenn001@odu.edu |
591665389d881c01f41d31e7b19b3804c27abda0 | 608919a5b53cf3950cd8849ff30dca3eb94b4ad8 | /templet/ACM_SCL-master-8e1daef41d93438743425115141b3d259f08f673/code/Trie.cpp | d93cb25e94a58f87feb121cb0335dabac1911326 | [] | no_license | demerzel1/ACM-code | 302c693fbd9f4d40071e13e674ec3c9b8dc15a24 | 42e3f59a585832b0fc4556d130be4c158b3bd2ec | refs/heads/master | 2021-04-26T22:21:09.891295 | 2018-03-31T08:16:54 | 2018-03-31T08:16:54 | 124,077,438 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 942 | cpp | template<char L=' ',char R='~'> struct Trie{
int size;
struct node{
node *son[R-L+1];
int size;
bool is;
}pool[MAXN];
node *root;
node* add(){
memset(&pool[size],NULL,sizeof(node));
return &pool[size++];
}
Trie(){size=0;root=add();}
pair<node*,int> find(const string& s){
node *now=root;
for(const auto&c:s){
if(!now->son[c-L]){
return make_pair(root,-1);//不存在
}
now=now->son[c-L];
}
if(now->is)
return make_pair(now,1);//存在
return make_pair(now,0);//只存在前缀
}
node* insert(const string& s){
node *now=root;
for(const auto&c:s){
if(!now->son[c-L]){
now->son[c-L]=add();
}
now->size++;now=now->son[c-L];
}
now->is=1;now->size++;
return now;
}
}; | [
"mengzhaoxin@hotmail.com"
] | mengzhaoxin@hotmail.com |
3f1ada2f8db76c7f6e7dbd3c2b6c45d16eaa22f5 | 0f89594f912d00639e3498e7c318e16577770d72 | /sdk/cpp/samples/licHtmlView/HHCTRL.H | 69bf8d1eede57e588c45f090d895905641e00857 | [] | no_license | renkun-cook/E_DevelopKits | 00feb743d165a505c8faa3ab7141783f14c6c27d | c4cd5c531a2f5ba59d39d3c2d98669996aec23ba | refs/heads/master | 2022-03-25T22:30:29.202119 | 2020-01-02T11:47:35 | 2020-01-02T11:47:35 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,698 | h |
/*
版权声明:
本文件版权为易语言作者吴涛所有,仅授权给第三方用作开发易语言支持库,禁止用于其他任何场合。
*/
#ifndef __HHCTRL_H__
#define __HHCTRL_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "lib2.h"
#include "untshare.h"
#define CUR_UNIT_VER 1
class CPIHtmlViewer : public CPropertyInfo
{
public:
INT m_nFontSize;
BOOL m_blOffline;
BOOL m_blSilent;
CString m_strURL;
public:
CPIHtmlViewer () { }
virtual void init ();
virtual BOOL Serialize (CArchive& ar);
};
extern "C"
PFN_INTERFACE WINAPI htmlview_GetInterface_HtmlViewer (INT nInterfaceNO);
HUNIT WINAPI Create_HtmlViewer (LPBYTE pAllData, INT nAllDataSize,
DWORD dwStyle, HWND hParentWnd, UINT uID, HMENU hMenu, INT x, INT y, INT cx, INT cy,
DWORD dwWinFormID, DWORD dwUnitID, HWND hDesignWnd = 0, BOOL blInDesignMode = FALSE);
BOOL WINAPI NotifyPropertyChanged_HtmlViewer (HUNIT hUnit, INT nPropertyIndex,
PUNIT_PROPERTY_VALUE pPropertyVaule, LPTSTR* ppszTipText);
BOOL WINAPI GetPropertyData_HtmlViewer (HUNIT hUnit, INT nPropertyIndex,
PUNIT_PROPERTY_VALUE pPropertyVaule);
HGLOBAL WINAPI GetAllPropertyData_HtmlViewer (HUNIT hUnit);
//////////////////////////////////////
#ifndef AFX_OLE_TRUE
#define AFX_OLE_TRUE (-1)
#define AFX_OLE_FALSE 0
#endif
class CHHCtrl : public CWnd
{
public:
CHHCtrl();
virtual ~CHHCtrl();
///////////////////////////
CPIHtmlViewer m_info;
DWORD m_dwWinFormID, m_dwUnitID;
BOOL m_blInDesignMode;
BOOL m_blHasForceURL, m_blHasTitle;
CString m_strForceURL;
CString m_strTitle, m_strStatusText;
///////////////////////////
BOOL Create (HWND hParentWnd, DWORD dwStyle, UINT nID,
INT x, INT y, INT cx, INT cy);
DECLARE_EVENTSINK_MAP()
public:
IWebBrowser2* GetBrowser() { return m_pBrowserApp; }
CString GetType() const;
BOOL GetBusy() const;
READYSTATE GetReadyState() const;
CString GetLocationName() const;
long GetLeft() const;
void SetLeft(long nNewValue) { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->put_Left(nNewValue); }
long GetTop() const;
void SetTop(long nNewValue) { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->put_Top(nNewValue); }
long GetHeight() const;
void SetHeight(long nNewValue) { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->put_Height(nNewValue); }
BOOL GetVisible() const;
void SetVisible(BOOL fNewValue) { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->put_Visible((short) (fNewValue ? AFX_OLE_TRUE : AFX_OLE_FALSE)); }
BOOL GetOffline() const;
void SetOffline(BOOL fNewValue) { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->put_Offline((short) (fNewValue ? AFX_OLE_TRUE : AFX_OLE_FALSE)); }
BOOL GetSilent() const;
void SetSilent(BOOL fNewValue) { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->put_Silent((short) (fNewValue ? AFX_OLE_TRUE : AFX_OLE_FALSE)); }
CString GetLocationURL() const;
void GoBack() { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->GoBack(); }
void GoForward() { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->GoForward(); }
void GoHome() { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->GoHome(); }
void GoSearch() { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->GoSearch(); }
void Refresh() { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->Refresh(); }
void Stop() { ASSERT(m_pBrowserApp != NULL); m_pBrowserApp->Stop(); }
void RunCmd (OLECMDID cmdid);
void ExecWB(OLECMDID cmdID, OLECMDEXECOPT cmdexecopt, VARIANT* pvaIn, VARIANT* pvaOut);
HRESULT Navigate(LPCTSTR URL, DWORD dwFlags = 0,
LPCTSTR lpszTargetFrameName = NULL,
LPCTSTR lpszHeaders = NULL, LPVOID lpvPostData = NULL,
DWORD dwPostDataLen = 0);
HRESULT NavigateChm(LPCTSTR szChmFileName, LPCTSTR URL, LPCTSTR lpszTargetFrameName = NULL);
// Events
virtual void OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags,
LPCTSTR lpszTargetFrameName,
CByteArray& baPostedData,
LPCTSTR lpszHeaders, BOOL* pfCancel);
virtual void OnNavigateComplete2(LPCTSTR strURL);
virtual void OnDownloadBegin();
virtual void OnProgressChange(long nProgress, long nProgressMax);
virtual void OnDownloadComplete();
virtual void OnDocumentComplete(LPCTSTR lpszURL);
virtual void OnStatusTextChange(LPCTSTR lpszText);
virtual void OnTitleChange(LPCTSTR lpszText);
virtual void OnCommandStateChange(long nCommand, BOOL fEnable);
virtual void OnNewWindow2(LPDISPATCH* ppDisp, BOOL* Cancel);
virtual void OnQuit();
virtual void OnVisible(BOOL fVisible);
virtual void OnPropertyChange(LPCTSTR lpszProperty);
public:
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Event reflectors (not normally overridden)
protected:
virtual void NavigateComplete2(LPDISPATCH pDisp, VARIANT* URL);
virtual void BeforeNavigate2(LPDISPATCH pDisp, VARIANT* URL,
VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData,
VARIANT* Headers, BOOL* Cancel);
virtual void DocumentComplete(LPDISPATCH pDisp, VARIANT* URL);
virtual void OnDraw(CDC* pDC);
virtual void PostNcDestroy();
public:
//{{AFX_MSG(CHHCtrl)
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnPaint();
afx_msg void OnDestroy();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
protected:
CWnd m_wndBrowser;
IWebBrowser2* m_pBrowserApp;
};
#endif // __HHCTRL_H__
| [
"1002062607@qq.com"
] | 1002062607@qq.com |
594f138f33ba1d867da01320af1485eb152c7c07 | 02a249c0c48ad11f8b5476626e42a7a2af889637 | /solutions/UVALive/6442/18929791_AC_196ms_0kB.cpp | f8e502c83559a771a4747246ab02bf6556080b2d | [] | no_license | Kanaricc/MyICPC | 3a3351fc02d7f36e7438eb1c92a87c9263028c8f | 73e80b2263ae8e2fe87009743defb59ff36e38ca | refs/heads/master | 2023-07-06T14:38:39.495821 | 2023-07-06T09:18:58 | 2023-07-06T09:18:58 | 186,849,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | cpp | #include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXN=20010;
int coins[MAXN];
int len,clen;
bool check(int x){
int seq=len/clen;
int lastl=coins[1]-x,lasth=coins[1]+x;
for(int i=2;i<=clen;i++){
int curl=max(lastl+seq,coins[i]-x);
int curh=min(lasth+seq,coins[i]+x);
if(curl>curh)return false;
lastl=curl;lasth=curh;
}
return true;
}
int main(){
int kase;cin>>kase;
for(int ki=1;ki<=kase;ki++){
cin>>len>>clen;
for(int i=1;i<=clen;i++){
cin>>coins[i];
}
sort(coins+1,coins+1+clen);
int l=0,r=len;
while(l<r){
int mid=(l+r)/2;
if(check(mid)){
r=mid;
}else l=mid+1;
}
cout<<"Case #"<<ki<<": "<<l<<endl;
}
return 0;
}
| [
"iovo7c@gmail.com"
] | iovo7c@gmail.com |
cc26698fa441f643bc6804c03b54fae0e90acc5d | b4bde3b08dcf74a5e47200c203a180bac7964134 | /Depends/include/live555/groupsock_version.hh | 7e3f087874373d80b8c7715b877ea6fbfa362c70 | [] | no_license | hellocao/DXGICapture | c747818142af3fd276e24140256680fb0eebac3f | f8518c00c1388d8fa015213a73e858bd71d50cb4 | refs/heads/master | 2020-06-21T05:35:20.072895 | 2019-07-22T02:05:24 | 2019-07-22T02:05:24 | 197,357,354 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 294 | hh | // Version information for the "groupsock" library
// Copyright (c) 1996-2018 Live Networks, Inc. All rights reserved.
#ifndef _GROUPSOCK_VERSION_HH
#define _GROUPSOCK_VERSION_HH
#define GROUPSOCK_LIBRARY_VERSION_STRING "2018.10.10"
#define GROUPSOCK_LIBRARY_VERSION_INT 1539129600
#endif
| [
"729239462@qq.com"
] | 729239462@qq.com |
f47acc540a4d73846f04293ba0dd2c8ab7f60106 | 308f5596f1c7d382520cfce13ceaa5dff6f4f783 | /hphp/runtime/ext/facts/logging.cpp | 752aa6a556a7faebe41bd5f38ab88c228514f283 | [
"PHP-3.01",
"Zend-2.0",
"MIT"
] | permissive | facebook/hhvm | 7e200a309a1cad5304621b0516f781c689d07a13 | d8203129dc7e7bf8639a2b99db596baad3d56b46 | refs/heads/master | 2023-09-04T04:44:12.892628 | 2023-09-04T00:43:05 | 2023-09-04T00:43:05 | 455,600 | 10,335 | 2,326 | NOASSERTION | 2023-09-14T21:24:04 | 2010-01-02T01:17:06 | C++ | UTF-8 | C++ | false | false | 14,496 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source path is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the path LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/facts/logging.h"
#include <cstdio>
#include <memory>
#include <string>
#include <unistd.h>
#include <folly/Conv.h>
#include <folly/SynchronizedPtr.h>
#include <folly/futures/FutureSplitter.h>
#include <folly/io/async/ScopedEventBaseThread.h>
#include <folly/logging/Init.h>
#include <folly/logging/LogConfig.h>
#include <folly/logging/LogFormatter.h>
#include <folly/logging/LogHandlerFactory.h>
#include <folly/logging/LogLevel.h>
#include <folly/logging/Logger.h>
#include <folly/logging/LoggerDB.h>
#include <folly/logging/StandardLogHandler.h>
#include <folly/logging/StandardLogHandlerFactory.h>
#include "hphp/util/cronolog.h"
#include "hphp/util/logger.h"
namespace HPHP {
namespace Facts {
namespace {
const std::string kDefaultFactsLogCategory = "hphp.runtime.ext.facts";
folly::SynchronizedPtr<std::unique_ptr<Cronolog>> make_synchronized_crono(
const std::string& file_template,
const std::string& link,
const std::string& owner,
int period_multiple) {
if (file_template.empty() || link.empty()) {
throw std::runtime_error("File template and link are required settings.");
}
// First, let's attempt to honor the logging settings as specified by the
// logging config.
auto crono = std::make_unique<Cronolog>();
crono->m_template = file_template;
crono->m_linkName = link;
crono->setPeriodicity();
crono->m_periodMultiple = period_multiple;
// Next, let's test if we can actually create the file and use it. If the
// user doesn't have permissions on the file, we'll use a temp file instead.
// The common case for this would be the user running a command line script
// which won't be able to write to a file owned by apache.
if (crono->getOutputFile() == nullptr) {
crono->m_template =
folly::sformat("/tmp/facts.%Y-%m-%d.log_{}.log", ::getpid());
crono->m_linkName.clear();
}
#if !defined(SKIP_USER_CHANGE)
if (!owner.empty()) {
Cronolog::changeOwner(owner, link);
}
#endif
return folly::SynchronizedPtr<std::unique_ptr<Cronolog>>(std::move(crono));
}
bool isTtyHelper(FILE* fp) {
return (fp != nullptr) && (::isatty(::fileno(fp)) == 1);
}
/*
* HHVM has a Cronolog class which creates and maintains a FILE* point to
* a log file which should be written to based on a template. This offers
* conveniences like automatically rolling the log file over on date boundaries.
* The CronoLogWriter class wraps a Cronolog for writing Facts related log
* information.
*/
struct CronoLogWriter final : public folly::LogWriter {
public:
struct Options {
std::string file_template;
std::string link;
std::string owner;
int period_multiple = 1;
bool flush_after_write = true;
bool drop_on_error = true;
};
explicit CronoLogWriter(const Options& options)
: m_crono{make_synchronized_crono(
options.file_template,
options.link,
options.owner,
options.period_multiple)},
m_tty{isTtyHelper(m_crono.wlock()->getOutputFile())},
m_flush{options.flush_after_write},
m_drop_on_error{options.drop_on_error} {}
void writeMessage(folly::StringPiece buffer, uint32_t flags = 0) override {
auto crono = m_crono.wlock();
FILE* output = crono->getOutputFile();
if (output != nullptr) {
bool should_flush =
m_flush || (flags & folly::LogWriter::Flags::NEVER_DISCARD);
bool write_failed =
::fwrite(buffer.data(), buffer.size(), 1, output) != 1;
bool flush_failed = should_flush && ::fflush(output) != 1;
if ((write_failed || flush_failed) && !m_drop_on_error) {
std::cerr << buffer;
if (should_flush) {
std::cerr << std::flush;
}
}
}
}
void writeMessage(std::string&& buffer, uint32_t flags = 0) override {
writeMessage(folly::StringPiece{buffer}, flags);
}
void flush() override {
// Only flush if we aren't already flushing after every write.
if (!m_flush) {
auto wlock = m_crono.wlock();
FILE* output = wlock->getOutputFile();
if (output != nullptr) {
::fflush(output);
}
}
}
bool ttyOutput() const override {
return m_tty;
}
private:
folly::SynchronizedPtr<std::unique_ptr<Cronolog>> m_crono;
const bool m_tty;
const bool m_flush;
const bool m_drop_on_error;
};
/*
* The CronoLogHandlerFactory is a custom log handler for folly logging which
* selects a destination file to write to using the Cronolog class.
*/
struct CronoLogHandlerFactory final : public folly::LogHandlerFactory {
public:
explicit CronoLogHandlerFactory(const std::string& owner) : m_owner(owner) {}
folly::StringPiece getType() const override {
return "crono";
}
std::shared_ptr<folly::LogHandler> createHandler(
const Options& options) override;
private:
std::string m_owner;
struct WriterFactory;
};
/*
* Supported settings:
*
* See Cronolog code for further information on the file, link, and period
* settings.
*
* async - Instead of writing to the file within the path of logging, queues
* the message for writing by a different thread. This is the default setting.
*
* flush_after_write - Perform a flush after each message to be sure the message
* has been written. If using asynchronously, the flush will occur after the
* file write has occurred. If async is disabled, this setting may have
* performance impacts. The default setting is true.
*
* drop_on_error - If a write error occurs while logging the message will be
* dropped if this is set to true, or written to stderr if set to false. The
* default setting is true. Note that setting this to false does not guarantee
* that nothing will be dropped. If a previous write is buffered, it may be
* lost.
*/
struct CronoLogHandlerFactory::WriterFactory final
: public folly::StandardLogHandlerFactory::WriterFactory {
public:
explicit WriterFactory(const std::string& owner) {
m_options.owner = owner;
}
bool processOption(folly::StringPiece name, folly::StringPiece value)
override {
try {
if (name == "file_template") {
m_options.file_template = value.str();
return true;
} else if (name == "link") {
m_options.link = value.str();
return true;
} else if (name == "owner") {
m_options.owner = value.str();
return true;
} else if (name == "async") {
m_async = folly::to<bool>(value);
return true;
} else if (name == "flush_after_write") {
m_options.flush_after_write = folly::to<bool>(value);
return true;
} else if (name == "period_multiple") {
m_options.period_multiple = folly::to<int>(value);
return true;
} else if (name == "drop_on_error") {
m_options.drop_on_error = folly::to<bool>(value);
return true;
}
} catch (...) {
Logger::FError(
"Caught exception while parsing arguments: {} = {}", name, value);
}
return false;
}
std::shared_ptr<folly::LogWriter> createWriter() override {
if (m_async) {
return std::make_shared<AsyncLogWriter>(
std::make_unique<CronoLogWriter>(m_options));
} else {
return std::make_shared<CronoLogWriter>(m_options);
}
}
private:
bool m_async = true;
CronoLogWriter::Options m_options;
};
std::shared_ptr<folly::LogHandler> CronoLogHandlerFactory::createHandler(
const Options& options) {
WriterFactory writerFactory(m_owner);
return folly::StandardLogHandlerFactory::createHandler(
getType(), &writerFactory, options);
}
struct HhvmLogWriter final : public folly::LogWriter {
public:
void writeMessage(folly::StringPiece buffer, uint32_t /* flags */ = 0)
override {
Logger::Error(buffer.str());
}
void writeMessage(std::string&& buffer, uint32_t /* flags */ = 0) override {
Logger::Error(buffer);
}
void flush() override {}
bool ttyOutput() const override {
return false;
}
};
struct HhvmLogFormatter final : public folly::LogFormatter {
public:
std::string formatMessage(
const folly::LogMessage& message,
const folly::LogCategory* /* handlerCategory */) override {
auto level = message.getLevel();
folly::StringPiece level_string;
if (level >= folly::LogLevel::FATAL) {
level_string = "<level:fatal>";
} else if (level >= folly::LogLevel::WARN) {
level_string = "<level:warning>";
} else if (level >= folly::LogLevel::INFO) {
level_string = "<level:info>";
} else {
level_string = "<level:none>";
}
return folly::sformat(
"{} {} {}:{} {}",
level_string,
message.getThreadID(),
message.getFileBaseName(),
message.getLineNumber(),
message.getMessage());
}
};
/*
* The HhvmLogHandlerFactory is a custom log handler for folly logging which
* writes to a log using the Logger::Error method.
*/
struct HhvmLogHandlerFactory final : public folly::LogHandlerFactory {
public:
folly::StringPiece getType() const override {
return "hhvm";
}
std::shared_ptr<folly::LogHandler> createHandler(
const Options& options) override;
private:
struct WriterFactory;
struct FormatterFactory;
};
struct HhvmLogHandlerFactory::FormatterFactory final
: public folly::StandardLogHandlerFactory::FormatterFactory {
bool processOption(
folly::StringPiece /* name */,
folly::StringPiece /* value */) override {
return false;
}
std::shared_ptr<folly::LogFormatter> createFormatter(
const std::shared_ptr<folly::LogWriter>& /* logWriter */) override {
return std::make_shared<HhvmLogFormatter>();
}
};
/*
* Supported settings:
*
* async - Instead of writing calling Logger::Error within path of logging, this
* queues the message for writing by a different thread. Be warned that the
* HHVM logger displays adds its own thread information in the output and that
* logging to it asynchronously probably means that thread information is going
* to be a lie. The logger includes valid thread information if needed.
*/
struct HhvmLogHandlerFactory::WriterFactory final
: public folly::StandardLogHandlerFactory::WriterFactory {
public:
bool processOption(folly::StringPiece name, folly::StringPiece value)
override {
try {
if (name == "async") {
m_async = folly::to<bool>(value);
return true;
}
} catch (...) {
Logger::FError(
"Caught exception while parsing arguments: {} = {}", name, value);
}
return false;
}
std::shared_ptr<folly::LogWriter> createWriter() override {
if (m_async) {
return std::make_shared<AsyncLogWriter>(
std::make_unique<HhvmLogWriter>());
} else {
return std::make_shared<HhvmLogWriter>();
}
}
private:
bool m_async = false;
};
std::shared_ptr<folly::LogHandler> HhvmLogHandlerFactory::createHandler(
const Options& options) {
WriterFactory writerFactory;
FormatterFactory formatterFactory;
return folly::StandardLogHandlerFactory::createHandler(
getType(), &writerFactory, &formatterFactory, options);
}
} // namespace
AsyncLogWriter::AsyncLogWriter(std::unique_ptr<folly::LogWriter> writer)
: m_is_tty{writer->ttyOutput()},
m_writer{std::move(writer)},
m_exec{std::make_unique<folly::ScopedEventBaseThread>("AsyncLogging")},
m_syncedFuture{folly::makeFuture().via(m_exec.get())} {}
void AsyncLogWriter::writeMessage(folly::StringPiece buffer, uint32_t flags) {
writeMessage(buffer.str(), flags);
}
void AsyncLogWriter::writeMessage(std::string&& buffer, uint32_t flags) {
auto wlock = m_syncedFuture.wlock();
*wlock = std::move(*wlock).thenValue(
[this, buffer{std::move(buffer)}, flags](auto) mutable {
m_writer->writeMessage(std::move(buffer), flags);
});
}
void AsyncLogWriter::flush() {
m_syncedFuture
.withWLock([this](folly::Future<folly::Unit>& future) {
auto splitter =
folly::splitFuture(std::move(future).thenValue([this](auto) {
m_writer->flush();
return folly::Unit();
}));
future = splitter.getFuture();
return splitter.getFuture();
})
.wait();
}
void enableFactsLogging(
const std::string& owner,
const std::string& options,
bool allow_propagation) {
folly::LoggerDB::get().registerHandlerFactory(
std::make_unique<CronoLogHandlerFactory>(owner));
folly::LoggerDB::get().registerHandlerFactory(
std::make_unique<HhvmLogHandlerFactory>());
// It appears that this should be safe to call twice and this will merge
// in the new options, but it does seem like if elsewhere in HHVM begins
// to use folly logging and overrides the base logging configuration, we
// might end up overwriting the overridden settings with the base
// configuration before applying our own settings.
folly::initLogging(options);
// We don't really want facts messages to propagate up because if nothing
// has configured logging higher up in the hierarchy, this will result in
// logging being emitted to stderr. Sadly, this can't be configured via
// options in initLogging, so we have to do this.
if (!allow_propagation) {
auto* facts = folly::LoggerDB::get().getCategory(kDefaultFactsLogCategory);
facts->setPropagateLevelMessagesToParent(folly::LogLevel::MAX_LEVEL);
}
}
} // namespace Facts
} // namespace HPHP
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
8e9d4f1a6d43db17026abda0216c6550bd118bff | bc032f174cce2fcbae767d8ca17a59f37e0eb2f6 | /src/gens/cpp/TcpStream.cpp | 340e975f93078278abdabab328360e89be96f070 | [
"MIT"
] | permissive | kuviman/trans-gen | 1d55442d4b71e8296edc6cee27c0baee22a671b8 | c52672830c60e1cedc9affe8c210dcf05eae345f | refs/heads/main | 2021-07-11T18:33:34.646242 | 2021-02-25T01:40:05 | 2021-02-25T01:58:08 | 234,373,222 | 0 | 2 | MIT | 2021-02-12T12:22:11 | 2020-01-16T17:23:45 | Rust | UTF-8 | C++ | false | false | 3,309 | cpp | #include "TcpStream.hpp"
#include <cstring>
#include <stdexcept>
TcpStream::TcpStream(const std::string& host, int port)
: readBufferPos(0)
, readBufferSize(0)
, writeBufferPos(0)
, writeBufferSize(0)
{
#ifdef _WIN32
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(1, 1), &wsa_data) != 0) {
throw std::runtime_error("Failed to initialize sockets");
}
#endif
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
throw std::runtime_error("Failed to create socket");
}
int yes = 1;
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&yes, sizeof(int)) < 0) {
throw std::runtime_error("Failed to set TCP_NODELAY");
}
addrinfo hints, *servinfo;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints,
&servinfo)
!= 0) {
throw std::runtime_error("Failed to get addr info");
}
if (connect(sock, servinfo->ai_addr, servinfo->ai_addrlen) == -1) {
throw std::runtime_error("Failed to connect");
}
freeaddrinfo(servinfo);
}
void TcpStream::readBytes(char* buffer, size_t byteCount)
{
while (byteCount > 0) {
if (readBufferSize > 0) {
if (readBufferSize >= byteCount) {
memcpy(buffer, this->readBuffer + readBufferPos, byteCount);
readBufferPos += byteCount;
readBufferSize -= byteCount;
return;
}
memcpy(buffer, this->readBuffer + readBufferPos, readBufferSize);
buffer += readBufferSize;
byteCount -= readBufferSize;
readBufferPos += readBufferSize;
readBufferSize = 0;
}
if (readBufferPos == BUFFER_CAPACITY) {
readBufferPos = 0;
}
RECV_SEND_T received = recv(sock, this->readBuffer + readBufferPos + readBufferSize,
BUFFER_CAPACITY - readBufferPos - readBufferSize, 0);
if (received < 0) {
throw std::runtime_error("Failed to read from socket");
}
readBufferSize += received;
}
}
TcpStream::~TcpStream()
{
#ifdef _WIN32
if (closesocket(sock) != 0)
#else
if (close(sock) != 0)
#endif
{
throw std::runtime_error("Failed to close socket");
}
}
void TcpStream::writeBytes(const char* buffer, size_t byteCount)
{
while (byteCount > 0) {
size_t capacity = BUFFER_CAPACITY - writeBufferPos - writeBufferSize;
if (capacity >= byteCount) {
memcpy(this->writeBuffer + writeBufferPos + writeBufferSize, buffer, byteCount);
writeBufferSize += byteCount;
return;
}
memcpy(this->writeBuffer + writeBufferPos + writeBufferSize, buffer, capacity);
writeBufferSize += capacity;
byteCount -= capacity;
buffer += capacity;
flush();
}
}
void TcpStream::flush()
{
while (writeBufferSize > 0) {
RECV_SEND_T sent = send(sock, writeBuffer + writeBufferPos, writeBufferSize, 0);
if (sent < 0) {
throw std::runtime_error("Failed to write to socket");
}
writeBufferPos += sent;
writeBufferSize -= sent;
}
writeBufferPos = 0;
} | [
"kuviman@gmail.com"
] | kuviman@gmail.com |
b4efe2f5447d61dccf8bed6d72a62e84f55e0c8b | 193cacbe89f5b2ef2208ef075dedc1871464f5f4 | /src/api/exchanges/include/cryptowatchapi.hpp | 8c4d3654aa2726661167a9d715b63f6a0f355951 | [
"MIT"
] | permissive | sssong81/coincenter | 6c867fc39d9b096bafb71a9cb41295ed76dd29f5 | 5f46b89af3a10c4a85a1fe6d3cbda950b7b3c949 | refs/heads/master | 2023-04-22T21:43:08.753950 | 2021-05-05T06:53:20 | 2021-05-06T13:40:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,184 | hpp | #pragma once
#include <chrono>
#include <optional>
#include <unordered_map>
#include "cachedresult.hpp"
#include "cct_flatset.hpp"
#include "cct_run_modes.hpp"
#include "curlhandle.hpp"
#include "exchangebase.hpp"
#include "market.hpp"
namespace cct {
namespace api {
/// Public API connected to different exchanges, providing fast methods to retrieve huge amount of data.
class CryptowatchAPI : public ExchangeBase {
public:
using Clock = std::chrono::high_resolution_clock;
using TimePoint = std::chrono::time_point<Clock>;
/// Cryptowatch markets are represented by one unique string pair, it's not trivial to split the two currencies
/// acronyms. A second match will be needed to transform it to a final 'cct::Market'
using PricesPerMarketMap = std::unordered_map<std::string, double>;
explicit CryptowatchAPI(settings::RunMode runMode = settings::kProd,
Clock::duration fiatsUpdateFrequency = std::chrono::hours(6),
bool loadFromFileCacheAtInit = true);
/// Tells whether given exchange is supported by Cryptowatch.
bool queryIsExchangeSupported(const std::string &exchangeName) {
return _supportedExchanges.get().contains(exchangeName);
}
/// Get a map containing all the average prices for all markets of given exchange.
/// The Markets are represented as a unique string with the concatenation of both currency acronyms in upper case:
/// Example: Market Bitcoin - Euro would have "BTCEUR" as key.
PricesPerMarketMap queryAllPrices(std::string_view exchangeName) { return _allPricesCache.get(exchangeName); }
/// Query the approximate price of market 'm' for exchange name 'exchangeName'.
/// Data may not be up to date, but should respond quickly.
std::optional<double> queryPrice(std::string_view exchangeName, Market m);
/// Tells whether given currency code is a fiat currency or not.
/// Fiat currencies are traditionnal currencies, such as EUR, USD, GBP, KRW, etc.
/// Information here: https://en.wikipedia.org/wiki/Fiat_money
bool queryIsCurrencyCodeFiat(CurrencyCode currencyCode);
void updateCacheFile() const override;
private:
using Fiats = cct::FlatSet<CurrencyCode>;
using SupportedExchanges = cct::FlatSet<std::string>;
CryptowatchAPI(const CryptowatchAPI &) = delete;
CryptowatchAPI(CryptowatchAPI &&) = default;
CryptowatchAPI &operator=(const CryptowatchAPI &) = delete;
CryptowatchAPI &operator=(CryptowatchAPI &&) = default;
struct SupportedExchangesFunc {
explicit SupportedExchangesFunc(CurlHandle &curlHandle) : _curlHandle(curlHandle) {}
SupportedExchanges operator()();
CurlHandle &_curlHandle;
};
struct AllPricesFunc {
explicit AllPricesFunc(CurlHandle &curlHandle) : _curlHandle(curlHandle) {}
PricesPerMarketMap operator()(std::string_view exchangeName);
CurlHandle &_curlHandle;
};
void queryFiats();
CurlHandle _curlHandle;
Fiats _fiats;
TimePoint _lastUpdatedFiatsTime;
Clock::duration _fiatsUpdateFrequency;
CachedResult<SupportedExchangesFunc> _supportedExchanges;
CachedResult<AllPricesFunc, std::string> _allPricesCache;
};
} // namespace api
} // namespace cct | [
"stephane.janel@amadeus.com"
] | stephane.janel@amadeus.com |
b3d932a24a5873f8760d814a481e555ea9c5381e | 2f838df8024c08087f87adfd2e751d2f96035cac | /cppPrimer/ch8progex.cpp | caaeeb86a386fb0784af0311e58f141d637adc58 | [] | no_license | danielsbonnin/samsCppPrimer5thEd | 5bf7bcb4f642b0a0c05f414da05bdeb5e9ad4428 | d88aef40db99e541f678d000f596d0d065cc219f | refs/heads/master | 2021-04-24T21:16:08.737418 | 2018-02-10T18:22:37 | 2018-02-10T18:22:37 | 116,745,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,623 | cpp | #include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
#include <cstring>
using namespace std;
/*
Chapter 8 review questions
1. What kinds of functions are good candidates for inline status?
Short/nonrecursive/one line.
2. Suppose the song() function has this prototype:
void song(char * name, int times);
a. How would you modify the prototype so that the default value for times is 1?
void song(char * name, int times = 1);
b. What changes would you make in the function definition?
None, because 1 is in the domain of acceptable answers already?
c. Can you provide a default value of "O, My Papa" for name?
Yes, only if you also provide the default value for times.: -> void song(char * name = "O, My Papa", int times = 1);
3. Write overloaded versions of iquote(), a function rhat displays its argument enclosed in double quotation marks.
Write three versions: one for an int argument, one for a double argument, and one for a string argumen.
void iquote(int num);
void iquote(double num);
void iquote(char * quote);
void iquote(int num)
{
cout << "\"" << num << "\"" << endl;
}
void iquote(double num)
{
cout << "\"" << num << "\"" << endl;
}
void iquote(const char * quote)
{
cout << "\"" << quote << "\"" << endl;
}
4. The following is a structure template:
struct box
{
char maker[40];
float height;
float widgth;
float length;
float volume;
};
a. Write a function that has a reference to a box structure as its formal argument and
displays the value of each member.
void showBox(const box & input)
{
cout << "maker: " << input.maker << endl;
cout << "height: " << input.height << endl;
cout << "width: " << input.width << endl;
cout << "length: " << input.length << endl;
cout << "volume: " << input.volume << endl;
}
b. Write a function that has a reference to a box structure as its formal argument and
sets the volume member to the product of the other three dimensions.
void setVolume(box & input)
{
input.volume = input.height * input.width * input.length;
}
5. The following are some desired effects. Indicate whether each can be accomplished with
default arguments, function overloading, both, or neither. Provide appropriate proto-
types.
a. mass(density, volume) returns the mass of an object having a density of
density and a volume of volume, whereas mass(density) returns the mass hav-
ing a density of density and a volume of 1.0 cubic meters. All quantities are type
double.
default arguments or function overloading:
mass(double density, double volume = 1.0); // default arguments
b. repeat(10, "I'm OK") displays the indicated string 10 times, and repeat("But
you're kind of stupid") displays the indicated string 5 times.
overloading:
repeat(int n, char * phrase);
repeat(char * phrase);
c. average(3,6) returns the int average of two int arguments, and average(3.0,
6.0) returns the double average of two double values.
function overloading:
int average(int x, int y);
double average(double x, double y);
d. mangle("I'm glad to meet you") returns the character I or a pointer to the
string "I'm mad to gleet you", depending on whether you assign the return
value to a char variable or to a char* variable.
neither: the return value is not part of the function signature.
6. Write a function template that returns the larger of its two arguments.
template <typename T>
T max(T x, T y)
{
if (x > y) return x;
else return y;
}s
7. Given the template of Review Question 6 and the box structure of Review Question 4,
provide a template specialization that takes two box arguments and returns the one with
the larger volume.
template <> box max<box>(box x, box y)
{
if (x.volume > y.volume) return x;
else return y;
}
*/
using namespace std;
void multi_printer(char * str, int times = 0) {
static int calledTimes = 0;
calledTimes++;
times = times > 0 ? calledTimes : 1;
for (int i = 0; i < times; ++i)
cout << str << endl;
}
void ex8_1(void)
{
cout << "multi_printer(\"test phrase\"): \n";
multi_printer("test phrase");
cout << "multi_printer(\"test phrase\", 1): \n";
multi_printer("test phrase", 1);
cout << "multi_printer(\"test phrase\"): \n";
multi_printer("test phrase");
cout << "multi_printer(\"test phrase\", 1): \n";
multi_printer("test phrase", 1);
}
const int MAX_STR = 64;
struct CandyBar {
char * brand;
double weight;
int calories;
};
void updateBar(CandyBar & bar, char * brand = "Millenium Munch", double weight = 2.85, int calories = 350)
{
bar.brand = brand;
bar.weight = weight;
bar.calories = calories;
}
void showBar(const struct CandyBar & bar)
{
cout << "Brand: " << bar.brand << " weight: " << bar.weight << " calories: " << bar.calories << endl;
}
void ex8_2(void)
{
struct CandyBar testBar = { "test brand", 6.66, 600 };
cout << "Test Bar: ";
showBar(testBar);
updateBar(testBar, "test brand #2", 5.55, 500);
cout << "After updating: " << endl;
showBar(testBar);
cout << "updating to all default vals: {\"Millenium Munch\", 2.85, 350}" << endl;
updateBar(testBar);
showBar(testBar);
}
void upperConv(std::string & phrase)
{
for (int i = 0; i < phrase.length(); ++i)
{
phrase[i] = toupper(phrase[i]);
}
}
void ex8_3(void)
{
std::string input = "";
cout << "Enter a string (q to quit): ";
getline(cin, input);
while (input.compare("q"))
{
upperConv(input);
cout << input << endl;
cout << "Enter a string (q to quit): ";
getline(cin, input);
}
}
struct stringy {
char * str; // points to a string
int ct; // length of string (not counting '\0')
};
// prototypes for set(), show(), and show() go here
void set(struct stringy & beany, const char * testing);
void show(const struct stringy & beany);
void show(const struct stringy & beany, int times);
void show(const char * phrase);
void show(const char * phrase, int times);
void ex8_4(void)
{
stringy beany;
char testing[] = "Reality isn't what it used to be.";
set(beany, testing); // first argument is a reference,
// allocates space to hold copy of testing,
// sets str member of beany to point to the
// new block, copies testing to new block,
// and sets ct member of beany
show(beany); // prints member string once
show(beany, 2); // prints member string twice
testing[0] = 'D';
testing[1] = 'u';
show(testing); // prints testing string once
show(testing, 3); // prints testing string thrice
show("Done!");
}
void set(struct stringy & beany, const char * testing)
{
char * newStr = new char[strlen(testing)];
beany.str = newStr;
strcpy(beany.str, testing);
beany.ct = strlen(testing);
}
void show(const struct stringy & beany)
{
cout << beany.str << endl;
}
void show(const struct stringy & beany, int times)
{
for (int i = 0; i < times; ++i)
cout << beany.str << endl;
}
void show(const char * phrase)
{
cout << phrase << endl;
}
void show(const char * phrase, int times)
{
for (int i = 0; i < times; ++i)
cout << phrase << endl;
}
template <typename T>
T max5(const T * arr)
{
T theMax = arr[0];
for (int i = 1; i < 5; ++i)
theMax = (arr[i] > theMax) ? arr[i] : theMax;
return theMax;
}
void ex8_5(void)
{
int intTest[5] = { 1, 6, 2, 4, 3 };
double doubleTest[5] = { 10.0, 6.0, 2.0, 2.6, 3.0 };
cout << "the max of the ints: " << max5(intTest) << endl;
cout << "The max of the doubles: " << max5(doubleTest) << endl;
}
template <typename T>
T maxn(T arr[], int n);
template <>
const char * maxn(const char * arr[], int size);
void ex8_6(void)
{
int intTest[] = { 1, 6, 2, 4, 3, 7};
double doubleTest[] = { 10.0, 6.0, 2.0, 2.6 };
const char * words[4] = { "cat", "doggy", "marmot", "elephant" };
cout << "the max of the ints: " << (int)maxn(intTest, 6) << endl;
cout << "The max of the doubles: " << (double)maxn(doubleTest, 4) << endl;
cout << "Array of cstrings: {cat, doggy, marmot, elephant}" << endl;
cout << "The longest cstring is: " << (char *)maxn(words, 4) << endl;
}
template <typename T>
T maxn(T arr[], int n)
{
T theMax = arr[0];
for (int i = 1; i < n; ++i)
theMax = (arr[i] > theMax) ? arr[i] : theMax;
return theMax;
}
template <> const char * maxn(const char * arr[], int size)
{
int best_len = 0;
int best_idx = 0;
for (int i = 0; i < size; ++i)
{
int cur = strlen(arr[i]);
if (cur > best_len)
{
best_len = cur;
best_idx = i;
}
}
return arr[best_idx];
}
template <typename T> // template A
T ShowArray(T arr[], int n);
template <typename T> // template B
T ShowArray(T * arr[], int n);
struct debts
{
char name[50];
double amount;
};
/*
Modify Listing 8.14 so that the template functions return the sum of the array contents
instead of displaying the contents. The program now should report the total number of
things and the sum of all the debts
*/
void ex8_7(void)
{
int things[6] = { 13, 31, 103, 301, 310, 130 };
struct debts mr_E[3] =
{
{ "Ima Wolfe", 2400.0 },
{ "Ura Fox", 1300.0 },
{ "Iby Stout", 1800.0 }
};
double * pd[3];
// set pointers to the amount members of the structures in the arr mr_E
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout << "Mr. E's has " << ShowArray(things, 6) << " things." << endl;
cout << "Mr.E's debts total : $" << ShowArray(pd, 3) << endl;
}
template <typename T>
T ShowArray(T arr[], int n)
{
cout << "template A\n";
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
template <typename T>
T ShowArray(T * arr[], int n)
{
T sum = 0;
cout << "template B\n";
for (int i = 0; i < n; i++)
sum += *arr[i];
return sum;
} | [
"danielsbonnin@gmail.com"
] | danielsbonnin@gmail.com |
215cb3ed5698a8bf806ec54febcadbf8ddcf095f | 9be246df43e02fba30ee2595c8cec14ac2b355d1 | /dlls/tf2_dll/order_repair.cpp | 2c249f23134a96b2b6556df17db783dfd7f968a5 | [] | no_license | Clepoy3/LeakNet | 6bf4c5d5535b3824a350f32352f457d8be87d609 | 8866efcb9b0bf9290b80f7263e2ce2074302640a | refs/heads/master | 2020-05-30T04:53:22.193725 | 2019-04-12T16:06:26 | 2019-04-12T16:06:26 | 189,544,338 | 18 | 5 | null | 2019-05-31T06:59:39 | 2019-05-31T06:59:39 | null | WINDOWS-1252 | C++ | false | false | 3,587 | cpp | //========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "order_repair.h"
#include "tf_team.h"
#include "tf_class_defender.h"
#include "order_helpers.h"
#include "tf_obj.h"
IMPLEMENT_SERVERCLASS_ST( COrderRepair, DT_OrderRepair )
END_SEND_TABLE()
static int SortFn_Defender( void *pUserData, int a, int b )
{
CSortBase *p = (CSortBase*)pUserData;
const Vector &vOrigin1 = p->m_pPlayer->GetTFTeam()->GetObject( a )->GetAbsOrigin();
const Vector &vOrigin2 = p->m_pPlayer->GetTFTeam()->GetObject( b )->GetAbsOrigin();
return p->m_pPlayer->GetAbsOrigin().DistTo( vOrigin1 ) < p->m_pPlayer->GetAbsOrigin().DistTo( vOrigin2 );
}
static bool IsValidFn_RepairFriendlyObjects( void *pUserData, int a )
{
// Only pick objects that are damaged.
CSortBase *p = (CSortBase*)pUserData;
CBaseObject *pObj = p->m_pPlayer->GetTFTeam()->GetObject( a );
// Skip objects under construction
if ( pObj->IsBuilding() )
return false;
return ( pObj->m_iHealth < pObj->m_iMaxHealth );
}
static bool IsValidFn_RepairOwnObjects( void *pUserData, int a )
{
// Only pick objects that are damaged.
CSortBase *pSortBase = (CSortBase*)pUserData;
CBaseObject *pObj = pSortBase->m_pPlayer->GetObject(a);
// Skip objects under construction
if ( !pObj || pObj->IsBuilding() )
return false;
return pObj->m_iHealth < pObj->m_iMaxHealth;
}
bool COrderRepair::CreateOrder_RepairFriendlyObjects( CPlayerClassDefender *pClass )
{
if( !pClass->CanBuildSentryGun() )
return false;
CBaseTFPlayer *pPlayer = pClass->GetPlayer();
CTFTeam *pTeam = pClass->GetTeam();
// Sort the list and filter out fully healed objects..
CSortBase info;
info.m_pPlayer = pPlayer;
int sorted[MAX_TEAM_OBJECTS];
int nSorted = BuildSortedActiveList(
sorted,
MAX_TEAM_OBJECTS,
SortFn_Defender,
IsValidFn_RepairFriendlyObjects,
&info,
pTeam->GetNumObjects() );
// If the player is close enough to the closest damaged object, issue an order.
if( nSorted )
{
CBaseObject *pObjToHeal = pTeam->GetObject( sorted[0] );
static float flClosestDist = 1024;
if( pPlayer->GetAbsOrigin().DistTo( pObjToHeal->GetAbsOrigin() ) < flClosestDist )
{
COrder *pOrder = new COrderRepair;
pTeam->AddOrder(
ORDER_REPAIR,
pObjToHeal,
pPlayer,
1e24,
60,
pOrder
);
return true;
}
}
return false;
}
bool COrderRepair::CreateOrder_RepairOwnObjects( CPlayerClass *pClass )
{
CSortBase info;
info.m_pPlayer = pClass->GetPlayer();
int sorted[16];
int nSorted = BuildSortedActiveList(
sorted,
sizeof( sorted ) / sizeof( sorted[0] ),
SortFn_PlayerObjectsByDistance,
IsValidFn_RepairOwnObjects,
&info,
info.m_pPlayer->GetObjectCount() );
if( nSorted )
{
// Make an order to repair the closest damaged object.
CBaseObject *pObj = info.m_pPlayer->GetObject( sorted[0] );
if (!pObj)
return false;
COrderRepair *pOrder = new COrderRepair;
info.m_pPlayer->GetTFTeam()->AddOrder(
ORDER_REPAIR,
pObj,
info.m_pPlayer,
1e24,
60,
pOrder
);
return true;
}
else
{
return false;
}
}
bool COrderRepair::Update()
{
CBaseEntity *pEnt = GetTargetEntity();
if( !pEnt )
return true;
// Kill the order when the object is repaired.
return pEnt->m_iHealth >= pEnt->m_iMaxHealth;
}
| [
"uavxp29@gmail.com"
] | uavxp29@gmail.com |
e1938506ea142d8915fdc32339e0af17691bcec8 | dffe88d6ef7951ff1e5dabe75d6b2bfcdeeed3f0 | /3rdParty/OpenImageIO/src/softimage.imageio/softimageinput.cpp | ec7023c60c49cf393a07a14f324e10878dfa4d44 | [
"BSD-3-Clause"
] | permissive | mmmovania/PVR_Windows | 86889f4d89c3acf4480444a5da975c24fff32ebe | 9d3d44dc315188f41202b20ba852a3616ab70d71 | refs/heads/master | 2023-01-27T23:43:06.481706 | 2023-01-16T10:15:39 | 2023-01-16T10:15:39 | 40,956,427 | 6 | 2 | null | 2021-07-31T10:11:47 | 2015-08-18T07:06:05 | C++ | UTF-8 | C++ | false | false | 18,205 | cpp | /*
OpenImageIO and all code, documentation, and other materials contained
therein are:
Copyright 2010 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(This is the Modified BSD License)
*/
#include "softimage_pvt.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
using namespace softimage_pvt;
class SoftimageInput : public ImageInput
{
public:
SoftimageInput() {
init();
}
virtual ~SoftimageInput() {
close();
}
virtual const char *format_name (void) const {
return "softimage";
}
virtual bool open (const std::string &name, ImageSpec &spec);
virtual bool close();
virtual bool read_native_scanline (int y, int z, void *data);
private:
/// Resets the core data members to defaults.
///
void init ();
/// Read a scanline from m_fd.
///
bool read_next_scanline (void * data);
/// Read uncompressed pixel data from m_fd.
///
bool read_pixels_uncompressed (const softimage_pvt::ChannelPacket & curPacket,
void * data);
/// Read pure run length encoded pixels.
///
bool read_pixels_pure_run_length (const softimage_pvt::ChannelPacket & curPacket,
void * data);
/// Read mixed run length encoded pixels.
///
bool read_pixels_mixed_run_length (const softimage_pvt::ChannelPacket & curPacket,
void * data);
FILE *m_fd;
softimage_pvt::PicFileHeader m_pic_header;
std::vector<softimage_pvt::ChannelPacket> m_channel_packets;
std::string m_filename;
std::vector<fpos_t> m_scanline_markers;
};
// symbols required for OpenImageIO plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT ImageInput *softimage_input_imageio_create() {
return new SoftimageInput;
}
OIIO_EXPORT const char *softimage_input_extensions[] = {
"pic", NULL
};
OIIO_PLUGIN_EXPORTS_END
void
SoftimageInput::init ()
{
m_fd = NULL;
m_filename.clear();
m_channel_packets.clear();
m_scanline_markers.clear();
}
bool
SoftimageInput::open (const std::string& name, ImageSpec& spec)
{
// Remember the filename
m_filename = name;
m_fd = Filesystem::fopen (m_filename, "rb");
if (!m_fd) {
error ("Could not open file \"%s\"", name.c_str());
return false;
}
// Try read the header
if (! m_pic_header.read_header (m_fd)) {
error ("\"%s\": failed to read header", m_filename.c_str());
close();
return false;
}
// Check whether it has the pic magic number
if (m_pic_header.magic != 0x5380f634) {
error ("\"%s\" is not a Softimage Pic file, magic number of 0x%X is not Pic",
m_filename.c_str(), m_pic_header.magic);
close();
return false;
}
// Get the ChannelPackets
ChannelPacket curPacket;
int nchannels = 0;
do {
// Read the next packet into curPacket and store it off
if (fread (&curPacket, 1, sizeof (ChannelPacket), m_fd) != sizeof (ChannelPacket)) {
error ("Unexpected end of file \"%s\".", m_filename.c_str());
close();
return false;
}
m_channel_packets.push_back (curPacket);
// Add the number of channels in this packet to nchannels
nchannels += curPacket.channels().size();
} while (curPacket.chained);
// Get the depth per pixel per channel
TypeDesc chanType = TypeDesc::UINT8;
if (curPacket.size == 16)
chanType = TypeDesc::UINT16;
// Set the details in the ImageSpec
m_spec = ImageSpec (m_pic_header.width, m_pic_header.height, nchannels, chanType);
m_spec.attribute ("BitsPerSample", (int)curPacket.size);
if (m_pic_header.comment[0] != 0) {
char comment[81];
strncpy (comment, m_pic_header.comment, 80);
comment[80] = 0;
m_spec.attribute ("ImageDescription", comment);
}
// Build the scanline index
fpos_t curPos;
fgetpos (m_fd, &curPos);
m_scanline_markers.push_back(curPos);
spec = m_spec;
return true;
}
bool
SoftimageInput::read_native_scanline (int y, int z, void* data)
{
bool result = false;
if (y == (int)m_scanline_markers.size() - 1) {
// we're up to this scanline
result = read_next_scanline(data);
// save the marker for the next scanline if we haven't got the who images
if (m_scanline_markers.size() < m_pic_header.height) {
fpos_t curPos;
fgetpos(m_fd, &curPos);
m_scanline_markers.push_back(curPos);
}
} else if (y >= (int)m_scanline_markers.size()) {
// we haven't yet read this far
fpos_t curPos;
// Store the ones before this without pulling the pixels
do {
if (!read_next_scanline(NULL))
return false;
fgetpos(m_fd, &curPos);
m_scanline_markers.push_back(curPos);
} while ((int)m_scanline_markers.size() <= y);
result = read_next_scanline(data);
fgetpos(m_fd, &curPos);
m_scanline_markers.push_back(curPos);
} else {
// We've already got the index for this scanline and moved past
// Let's seek to the scanline's data
if (fsetpos (m_fd, &m_scanline_markers[y])) {
error ("Failed to seek to scanline %d in \"%s\"", y, m_filename.c_str());
close();
return false;
}
result = read_next_scanline(data);
// If the index isn't complete let's shift the file pointer back to the latest readline
if (m_scanline_markers.size() < m_pic_header.height) {
if (fsetpos (m_fd, &m_scanline_markers[m_scanline_markers.size() - 1])) {
error ("Failed to restore to scanline %llu in \"%s\"",
(long long unsigned int)m_scanline_markers.size() - 1, m_filename.c_str());
close();
return false;
}
}
}
return result;
}
bool
SoftimageInput::close()
{
if (m_fd) {
fclose (m_fd);
m_fd = NULL;
}
init ();
return true;
}
inline bool
SoftimageInput::read_next_scanline (void * data)
{
// Each scanline is stored using one or more channel packets.
// We go through each of those to pull the data
for (size_t i = 0; i < m_channel_packets.size(); i++) {
if (m_channel_packets[i].type & UNCOMPRESSED) {
if (!read_pixels_uncompressed (m_channel_packets[i], data)) {
error ("Failed to read uncompressed pixel data from \"%s\"", m_filename.c_str());
close();
return false;
}
} else if (m_channel_packets[i].type & PURE_RUN_LENGTH) {
if (!read_pixels_pure_run_length (m_channel_packets[i], data)) {
error ("Failed to read pure run length encoded pixel data from \"%s\"", m_filename.c_str());
close();
return false;
}
} else if (m_channel_packets[i].type & MIXED_RUN_LENGTH) {
if (!read_pixels_mixed_run_length (m_channel_packets[i], data)) {
error ("Failed to read mixed run length encoded pixel data from \"%s\"", m_filename.c_str());
close();
return false;
}
}
}
return true;
}
inline bool
SoftimageInput::read_pixels_uncompressed (const softimage_pvt::ChannelPacket & curPacket, void * data)
{
// We're going to need to use the channels more than once
std::vector<int> channels = curPacket.channels();
// We'll need to use the pixelChannelSize a bit
size_t pixelChannelSize = curPacket.size / 8;
if (data) {
// data pointer is set so we're supposed to write data there
uint8_t * scanlineData = (uint8_t *)data;
for (size_t pixelX=0; pixelX < m_pic_header.width; pixelX++) {
for (size_t curChan=0; curChan < channels.size(); curChan++) {
for (size_t byte=0; byte < pixelChannelSize; byte++) {
// Get which byte we should be placing this in depending on endianness
size_t curByte = byte;
if (littleendian())
curByte = ((pixelChannelSize) - 1) - curByte;
//read the data into the correct place
if (fread (&scanlineData[(pixelX * pixelChannelSize * m_spec.nchannels) + (channels[curChan] * pixelChannelSize) + curByte],
1, 1, m_fd) != 1)
return false;
}
}
}
} else {
// data pointer is null so we should just seek to the next scanline
// If the seek fails return false
if (fseek (m_fd, m_pic_header.width * pixelChannelSize * channels.size(), SEEK_CUR))
return false;
}
return true;
}
inline bool
SoftimageInput::read_pixels_pure_run_length (const softimage_pvt::ChannelPacket & curPacket, void * data)
{
// How many pixels we've read so far this line
size_t linePixelCount = 0;
// Number of repeats of this value
uint8_t curCount = 0;
// We'll need to use the pixelChannelSize a bit
size_t pixelChannelSize = curPacket.size / 8;
// We're going to need to use the channels more than once
std::vector<int> channels = curPacket.channels();
// Read the pixels until we've read them all
while (linePixelCount < m_pic_header.width) {
// Read the repeats for the run length - return false if read fails
if (fread (&curCount, 1, 1, m_fd) != 1)
return false;
if (data) {
// data pointer is set so we're supposed to write data there
size_t pixelSize = pixelChannelSize * channels.size();
uint8_t * pixelData = new uint8_t[pixelSize];
if (fread (pixelData, pixelSize, 1, m_fd) != pixelSize)
return false;
// Now we've got the pixel value we need to push it into the data
uint8_t * scanlineData = (uint8_t *)data;
for (size_t pixelX=linePixelCount; pixelX < linePixelCount+curCount; pixelX++) {
for (size_t curChan=0; curChan < channels.size(); curChan++) {
for (size_t byte=0; byte < pixelChannelSize; byte++) {
// Get which byte we should be placing this in depending on endianness
size_t curByte = byte;
if (littleendian())
curByte = ((pixelChannelSize) - 1) - curByte;
//put the data into the correct place
scanlineData[(pixelX * pixelChannelSize * m_spec.nchannels) + (channels[curChan] * pixelChannelSize) + curByte] =
pixelData[(curChan * pixelChannelSize) + curByte];
}
}
}
delete[] pixelData;
} else {
// data pointer is null so we should just seek to the next scanline
// If the seek fails return false
if (fseek (m_fd, pixelChannelSize * channels.size(), SEEK_CUR))
return false;
}
// Add these pixels to the current pixel count
linePixelCount += curCount;
}
return true;
}
inline bool
SoftimageInput::read_pixels_mixed_run_length (const softimage_pvt::ChannelPacket & curPacket, void * data)
{
// How many pixels we've read so far this line
size_t linePixelCount = 0;
// Number of repeats of this value
uint8_t curCount = 0;
// We'll need to use the pixelChannelSize a bit
size_t pixelChannelSize = curPacket.size / 8;
// We're going to need to use the channels more than once
std::vector<int> channels = curPacket.channels();
// Read the pixels until we've read them all
while (linePixelCount < m_pic_header.width) {
// Read the repeats for the run length - return false if read fails
if (fread (&curCount, 1, 1, m_fd) != 1)
return false;
if (curCount < 128) {
// It's a raw packet - so this means the count is 1 less then the actual value
curCount++;
// Just to be safe let's make sure this wouldn't take us
// past the end of this scanline
if (curCount + linePixelCount > m_pic_header.width)
curCount = m_pic_header.width - linePixelCount;
if (data) {
// data pointer is set so we're supposed to write data there
uint8_t * scanlineData = (uint8_t *)data;
for (size_t pixelX=linePixelCount; pixelX < linePixelCount+curCount; pixelX++) {
for (size_t curChan=0; curChan < channels.size(); curChan++) {
for (size_t byte=0; byte < pixelChannelSize; byte++) {
// Get which byte we should be placing this in depending on endianness
size_t curByte = byte;
if (littleendian())
curByte = ((pixelChannelSize) - 1) - curByte;
//read the data into the correct place
if (fread (&scanlineData[(pixelX * pixelChannelSize * m_spec.nchannels) + (channels[curChan] * pixelChannelSize) + curByte],
1, 1, m_fd) != 1)
return false;
}
}
}
} else {
// data pointer is null so we should just seek to the
// next scanline If the seek fails return false.
if (fseek (m_fd, curCount * pixelChannelSize * channels.size(), SEEK_CUR))
return false;
}
// Add these pixels to the current pixel count
linePixelCount += curCount;
} else {
// It's a run length encoded packet
uint16_t longCount = 0;
if (curCount == 128) {
// This is a long count so the next 16bits of the file
// are an unsigned int containing the count. If the
// read fails we should return false.
if (fread (&longCount, 1, 2, m_fd) != 2)
return false;
// longCount is in big endian format - if we're not
// let's swap it
if (littleendian())
OIIO::swap_endian (&longCount);
} else {
longCount = curCount - 127;
}
if (data) {
// data pointer is set so we're supposed to write data there
size_t pixelSize = pixelChannelSize * channels.size();
uint8_t * pixelData = new uint8_t[pixelSize];
if (fread (pixelData, 1, pixelSize, m_fd) != pixelSize)
return false;
// Now we've got the pixel value we need to push it into
// the data.
uint8_t * scanlineData = (uint8_t *)data;
for (size_t pixelX=linePixelCount; pixelX < linePixelCount+longCount; pixelX++) {
for (size_t curChan=0; curChan < channels.size(); curChan++) {
for (size_t byte=0; byte < pixelChannelSize; byte++) {
// Get which byte we should be placing this
// in depending on endianness.
size_t curByte = byte;
if (littleendian())
curByte = ((pixelChannelSize) - 1) - curByte;
//put the data into the correct place
scanlineData[(pixelX * pixelChannelSize * m_spec.nchannels) + (channels[curChan] * pixelChannelSize) + curByte] =
pixelData[(curChan * pixelChannelSize) + curByte];
}
}
}
delete[] pixelData;
} else {
// data pointer is null so we should just seek to the
// next scanline. If the seek fails return false.
if (fseek (m_fd, pixelChannelSize * channels.size(), SEEK_CUR))
return false;
}
// Add these pixels to the current pixel count.
linePixelCount += longCount;
}
}
return true;
}
OIIO_PLUGIN_NAMESPACE_END
| [
"mova0002@e.ntu.edu.sg"
] | mova0002@e.ntu.edu.sg |
9ee69256955c489090bf68f3a74eb4def3266963 | 379ac4db4a9b5e958bfa462a9bb609ded9b0f6c9 | /PROBLEM_SOLVING/CODE_FORCES/CF_266B.cpp | 392f0698e7a3169135bf40975d7da19d8687bfe5 | [] | no_license | GolamRabbani20/CPP | ad395e7afbde89839596944ec1dbfe2323505458 | 24c205131ac2e507fd8195a794b43247abaf9d58 | refs/heads/master | 2023-03-25T12:15:15.325028 | 2021-03-15T18:43:36 | 2021-03-15T18:43:36 | 348,081,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,t;
string s;
cin>>n>>t>>s;
while(t>0)
{
for(i=0; i<n; i++)
if(s[i]=='B'&&s[i+1]=='G')//swap(s[i],s[i+1]),i++;
{
s[i]='G';
s[i+1]='B';
i++;
}
t--;
}
cout<<s<<endl;
return 0;
}
| [
"mdgolamrabbani96@gmail.com"
] | mdgolamrabbani96@gmail.com |
b2b20ff815f81273c2d4769b73b499cf81a0497b | e82a55c68733e1883d38ba7eb13d64619a5966f6 | /Source/ARPG/Public/Character/CharacterUtil/ARPG_DamageFunctionLibrary.h | dd4ab53bc8beb472ee8b35ce80f7568e911fdeca | [] | no_license | YaXing-yx/ARPG | 850464507fdec69f67c42c981b07288e05cbeca3 | b9c1b7b6887fd7d8fc52807a73574dc336be78aa | refs/heads/master | 2022-03-06T08:51:09.041737 | 2019-11-09T11:10:51 | 2019-11-09T11:10:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "ARPG_DamageFunctionLibrary.generated.h"
/**
*
*/
UCLASS()
class ARPG_API UARPG_DamageFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
};
| [
"450614754@qq.com"
] | 450614754@qq.com |
548ba3e0a0e5e232afd10cfb24e1785d8981fb83 | e87489fd9c604c6193c4b0170865ef8b37007242 | /Demo2_AI/main.cpp | a72d19a970818408f983b499d9b5cdab8fc4c5df | [] | no_license | cneal111/Tower-of-Hanoi | 746639ea7cdb0f3fedfb32089cec13d6bfd87910 | 14ec6be2e77057ff2d7b7794abbfd2c045058852 | refs/heads/master | 2020-10-02T03:56:19.732275 | 2019-12-12T21:01:00 | 2019-12-12T21:01:00 | 227,695,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,644 | cpp | //CS4346
//AI Project 2
//Professor Dr. Ali
//Authors: Alhaeth Alomari, Mesut April, Cody Neal
//
#include <iostream>
#include <chrono>
#include <algorithm>
#include <queue>
#include <limits>
#include <time.h>
#include "AStar/AStar.h"
#include "RBFS/RBFS.h"
#include "Hanoi/Hanoi.h"
int main()
{
std::cout << "Hello, World!" << std::endl;
std::chrono::time_point<std::chrono::system_clock> aStart, aEnd, rbfsStart, rbfsEnd;
int numOfDisk;
std::cout << "Enter number of disks: ";
std::cin >> numOfDisk;
Hanoi start(numOfDisk);
Hanoi goal(true, numOfDisk);
std::cout << start << std::endl;
AStar aStar;
int aOpen = 0;
int aExpand = 0;
aStart = std::chrono::system_clock::now();
aStar.search(&start, &goal, aOpen, aExpand);
aEnd = std::chrono::system_clock::now();
RBRS rbrs;
int rbfsOpen = 0;
int rbfsExpand = 0;
rbfsStart = std::chrono::system_clock::now();
rbrs.search(&start, &goal, rbfsOpen, rbfsExpand);
rbfsEnd = std::chrono::system_clock::now();
std::chrono::duration<double> aStartSeconds = aEnd - aStart;
std::chrono::duration<double> rbfsSeconds = rbfsEnd - rbfsStart;
std::cout << "Astar time = " << aStartSeconds.count() << std::endl;
std::cout << "nodes opened = " << aOpen << std::endl;
std::cout << "nodes expanded = " << aExpand << std::endl;
std::cout << "RBFS time = " << rbfsSeconds.count() << std::endl;
std::cout << "nodes opened = " << rbfsOpen << std::endl;
std::cout << "nodes expanded = " << rbfsExpand << std::endl;
std::cout << "End Program" << std::endl;
return 0;
}
| [
"codyrneal1@gmail.com"
] | codyrneal1@gmail.com |
108708c3477363657a454a2ce4b7da6dd17d39ab | de5abf369d4f1c2475bc4e22ad9d689b0c40ac04 | /1040/1040.cpp | 368ce51fe59160303ad5cfb9412f6abadf088c5d | [] | no_license | ccuwxy/PAT_Basic_Level_Practice | e4bec21efd47e9686c4759e891b1b3cd2b3a1cbb | 915e29ff50b7648015535390c26dcf9805b74a78 | refs/heads/master | 2023-08-20T12:30:17.791714 | 2021-10-30T08:39:58 | 2021-10-30T08:39:58 | 184,578,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | cpp | #include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cin >> s;
int len = s.length(), countP = 0, countT = 0, ans = 0;
for (int i = 0; i < len; i++)
if (s.at(i) == 'T')
countT++;
for (int i = 0; i < len; i++)
{
if (s.at(i) == 'P')
countP++;
if (s.at(i) == 'T')
countT--;
if (s.at(i) == 'A')
ans = (ans + (countP * countT) % 1000000007) % 1000000007;
}
cout << ans;
return 0;
} | [
"wxy990212@126.com"
] | wxy990212@126.com |
bbae5cb0ab7efe467af66fba6d4da36b09ca75e2 | 71cfbaf028c260719e18c02525dead095d7d8d0b | /src/juman_morph.cc | 1cabe7eb104defb6b9f815a9c0978bdcc5c58506 | [] | no_license | tiwanari/coling_order_concept | 9c72dbdb7f1cecb3fb90f085feb6689b4ffb5dd2 | 3664d1210fac967ee8191df3b7ba3e8a563995f3 | refs/heads/master | 2020-06-17T21:35:08.214432 | 2016-12-07T15:01:01 | 2016-12-07T16:07:25 | 74,967,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,037 | cc | #include <iostream>
#include <stdexcept>
#include "juman_morph.h"
namespace order_concepts {
void JumanMorph::init(
const std::string& morph,
const std::vector<std::string>& infos)
throw (std::runtime_error)
{
if (infos.size() < 5) {
std::stringstream ss;
for (const auto& info : infos)
ss << info << ", ";
ss << "size: " << infos.size() << std::endl;
throw std::runtime_error(
"Not enough params for juman morph (" + morph + "): " + ss.str());
}
m_morph = morph;
m_pos = POSFrom(infos[0]);
m_sub_poss = std::vector<std::string>({infos[1]});
m_ctype = infos[2];
m_cform = infos[3];
m_lemma = infos[4];
}
JumanMorph::JumanMorph(const std::string& infos)
{
std::vector<std::string> splitted_line;
util::splitStringUsing(infos, "\t", &splitted_line);
if (splitted_line.size() != 2) {
std::stringstream ss;
ss << "Invalid params for morph (size: " << splitted_line.size()
<< "): " << infos << std::endl;
throw std::runtime_error(ss.str());
}
std::vector<std::string> morph_infos;
util::splitStringUsing(splitted_line[1], ",", &morph_infos);
init(splitted_line[0], morph_infos);
}
JumanMorph::JumanMorph(
const std::string& morph,
const std::string& infos)
{
std::vector<std::string> morph_infos;
util::splitStringUsing(infos, ",", &morph_infos);
init(morph, morph_infos);
}
JumanMorph::JumanMorph(
const std::string& morph,
const std::vector<std::string>& infos)
{
init(morph, infos);
}
Morph::POS_TAG JumanMorph::POSFrom(const std::string& str)
{
if (str == STR_POS_NOUN) {
return POS_TAG::NOUN;
}
else if (str == STR_POS_VERB) {
return POS_TAG::VERB;
}
else if (str == STR_POS_ADJECTIVE) {
return POS_TAG::ADJECTIVE;
}
else if (str == STR_POS_AUXILIARY_VERB) {
return POS_TAG::AUXILIARY_VERB;
}
return POS_TAG::OTHER;
};
} // namespace order_concepts
| [
"tatsuyaw0c@gmail.com"
] | tatsuyaw0c@gmail.com |
02b72a89f9f74cf05107590a8f2ebe7007beaf03 | 25e99a0af5751865bce1702ee85cc5c080b0715c | /ds_algo/src/leetcode_v2/algorithms/HouseRobberIII/tree.cpp | 0eb549f6abc84b76b59055d9959421c2eae46147 | [
"MIT"
] | permissive | jasonblog/note | 215837f6a08d07abe3e3d2be2e1f183e14aa4a30 | 4471f95736c60969a718d854cab929f06726280a | refs/heads/master | 2023-05-31T13:02:27.451743 | 2022-04-04T11:28:06 | 2022-04-04T11:28:06 | 35,311,001 | 130 | 67 | null | 2023-02-10T21:26:36 | 2015-05-09T02:04:40 | C | UTF-8 | C++ | false | false | 1,418 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution
{
public:
int rob(TreeNode* root)
{
int yes = 0, no = 0;
dfs(root, &yes, &no);
return max(yes, no);
}
private:
void dfs(TreeNode* root, int* yes, int* no)
{
if (root == nullptr) {
*yes = 0;
*no = 0;
return;
}
int left_yes, left_no, right_yes, right_no;
dfs(root->left, &left_yes, &left_no);
dfs(root->right, &right_yes, &right_no);
*yes = left_no + right_no + root->val;
*no = max(left_yes, left_no) + max(right_yes, right_no);
}
};
TreeNode* mk_node(int val)
{
return new TreeNode(val);
}
TreeNode* mk_child(TreeNode* root, TreeNode* left, TreeNode* right)
{
root->left = left;
root->right = right;
return root;
}
TreeNode* mk_child(TreeNode* root, int left, int right)
{
return mk_child(root, new TreeNode(left), new TreeNode(right));
}
TreeNode* mk_child(int root, int left, int right)
{
return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right));
}
int main(int argc, char** argv)
{
Solution solution;
TreeNode* root = mk_child(4, 1, 0);
return 0;
}
| [
"jason_yao@htc.com"
] | jason_yao@htc.com |
1278f59f46142b319e853372808606ffb133e245 | 39921d049a882220193fb45f4023a6831fb79908 | /Pods/FirebaseFirestore/Firestore/core/src/model/precondition.cc | d3e99032f198e5b38fc65c978e05e5802ba803cd | [] | no_license | furydeveloper/SearchCoinKaraoke | a48bb7f0a4032735a2fc8895bd6bb02626b392b3 | 98043d3e280814f75c4f6c7957e6c0eee320a9b9 | refs/heads/master | 2023-08-10T23:24:28.780365 | 2021-10-03T02:51:57 | 2021-10-03T02:51:57 | 409,012,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | cc | version https://git-lfs.github.com/spec/v1
oid sha256:faf2ffc7ab9b4d4e23abaa38432d1c723694daece7c59b6a4b9d363921cc9aba
size 2489
| [
"furysecu@gmail.com"
] | furysecu@gmail.com |
960bdd38a66a050f109256f3e55e8432908763bd | 721869917e1d1be22b780e6aa609dfb65cd7b682 | /RichPresencePlugin/RichPresenceComponent.h | 550a62e62630f9c77656c61dce5cc5d43c2b07d9 | [] | no_license | artumino/RichPresencePlugin | 3549edd3aa700383d5ee5a4327f1425afa3f3afe | 7bc132b69cf74c3ca8863f9f5c840798b7e99968 | refs/heads/master | 2022-11-30T20:07:44.844132 | 2020-08-14T12:08:33 | 2020-08-14T12:08:33 | 287,417,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | h | #pragma once
#include <string>
#include <windows.h>
#define STEAMWORKS_CLIENT_INTERFACES
#include "Steamworks.h"
class RichPresenceComponent
{
public:
RichPresenceComponent(UINT parentId, const wchar_t* gameName);
virtual ~RichPresenceComponent();
void InitializeMain();
void InitializeGameParent();
void InitializeGameChild();
protected:
std::wstring GetCurrentProcessName();
std::wstring GetChildProcessCmd(const wchar_t* marker, const wchar_t* gameName);
std::wstring GetCurrentDirectoryName();
private:
UINT m_parentAppID;
UINT m_parentProcID;
std::wstring m_wsGameName;
HANDLE m_hParentClosedEvent;
HSteamPipe m_hPipe;
HSteamUser m_hUser;
ISteamClient017* m_pSteamClient;
IClientEngine* m_pClientEngine;
IClientUser* m_pClientUser;
IClientShortcuts* m_pClientShortcuts;
bool LoadSteamworks();
void InitializePublicAPI();
void InitializeClientAPI();
void InitializePresence();
void UpdateRichPresence(const char* status);
void SpawnChildProcess();
}; | [
"jacopo.libe@gmail.com"
] | jacopo.libe@gmail.com |
27855faad162c287c25ed837877da3d5bda90a6f | d2249116413e870d8bf6cd133ae135bc52021208 | /hp-socket/Common/Src/socket/TcpServer.cpp | 3545586a8f2ad93134d9664db0a450dace238545 | [
"Apache-2.0"
] | permissive | Unknow-man/mfc-4 | ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5 | b58abf9eb4c6d90ef01b9f1203b174471293dfba | refs/heads/master | 2023-02-17T18:22:09.276673 | 2021-01-20T07:46:14 | 2021-01-20T07:46:14 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 24,752 | cpp | /*
* Copyright Bruce Liang (ldcsaa@gmail.com)
*
* Version : 3.1.1
* Author : Bruce Liang
* Website : http://www.jessma.org
* Porject : https://code.google.com/p/ldcsaa
* Bolg : http://www.cnblogs.com/ldcsaa
* WeiBo : http://weibo.com/u/1402935851
* QQ Group : 75375912
*
* 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 "stdafx.h"
#include "TcpServer.h"
#include "../WaitFor.h"
#include "../FuncHelper.h"
#include <malloc.h>
#include <process.h>
#define IOCP_SI_EXIT 0x00000000
#define IOCP_SI_ACCEPT 0xFFFFFFF1
#define IOCP_SI_DISCONNECT 0xFFFFFFF2
#define IOCP_SI_RS_GONO 0
#define IOCP_SI_RS_CONTINUE 1
#define IOCP_SI_RS_BREAK 2
const DWORD CTcpServer::MAX_WORKER_THREAD_COUNT = 500;
const DWORD CTcpServer::MIN_SOCKET_BUFFER_SIZE = 64;
const DWORD CTcpServer::DEFAULT_WORKER_THREAD_COUNT = min((::GetCpuCount() * 2 + 2), MAX_WORKER_THREAD_COUNT);
const DWORD CTcpServer::DEFAULT_ACCEPT_SOCKET_COUNT = 1 * DEFAULT_WORKER_THREAD_COUNT;
const DWORD CTcpServer::DEFAULT_SOCKET_BUFFER_SIZE = 4 * 1024 - sizeof(TBufferObj);
const DWORD CTcpServer::DEFAULT_SOCKET_LISTEN_QUEUE = 30;
const DWORD CTcpServer::DEFAULT_FREE_SOCKETOBJ_LOCK_TIME= 3 * 1000;
const DWORD CTcpServer::DEFAULT_FREE_SOCKETOBJ_POOL = 100;
const DWORD CTcpServer::DEFAULT_FREE_BUFFEROBJ_POOL = 200;
const DWORD CTcpServer::DEFAULT_FREE_SOCKETOBJ_HOLD = 300;
const DWORD CTcpServer::DEFAULT_FREE_BUFFEROBJ_HOLD = 600;
const DWORD CTcpServer::DEFALUT_KEEPALIVE_TIME = 5 * 1000;
const DWORD CTcpServer::DEFALUT_KEEPALIVE_INTERVAL = 3 * 1000;
const DWORD CTcpServer::DEFAULT_MAX_SHUTDOWN_WAIT_TIME = 15 * 1000;
void CTcpServer::SetLastError(EnServerError code, LPCSTR func, int ec)
{
m_enLastError = code;
TRACE3("%s --> Error: %d, EC: %d\n", func, code, ec);
}
BOOL CTcpServer::Start(LPCTSTR pszBindAddress, USHORT usPort)
{
if(!CheckParams() || !CheckStarting())
return FALSE;
if(CreateListenSocket(pszBindAddress, usPort))
if(CreateCompletePort())
if(CreateWorkerThreads())
if(StartAccept())
{
m_enState = SS_STARTED;
return TRUE;
}
Stop();
return FALSE;
}
BOOL CTcpServer::CheckParams(BOOL bPreconditions)
{
if(bPreconditions)
if((int)m_dwWorkerThreadCount > 0 && m_dwWorkerThreadCount <= MAX_WORKER_THREAD_COUNT)
if((int)m_dwAcceptSocketCount > 0)
if((int)m_dwSocketBufferSize >= MIN_SOCKET_BUFFER_SIZE)
if((int)m_dwSocketListenQueue > 0)
if((int)m_dwFreeSocketObjLockTime >= 0 && m_dwFreeSocketObjLockTime <= MAXLONG)
if((int)m_dwFreeSocketObjPool >= 0)
if((int)m_dwFreeBufferObjPool >= 0)
if((int)m_dwFreeSocketObjHold >= m_dwFreeSocketObjPool)
if((int)m_dwFreeBufferObjHold >= m_dwFreeBufferObjPool)
if((int)m_dwKeepAliveTime >= 0)
if((int)m_dwKeepAliveInterval >= 0)
if((int)m_dwMaxShutdownWaitTime >= 0)
return TRUE;
SetLastError(SE_INVALID_PARAM, __FUNCTION__, ERROR_INVALID_PARAMETER);
return FALSE;
}
BOOL CTcpServer::CheckStarting()
{
if(m_enState == SS_STOPED)
m_enState = SS_STARTING;
else
{
SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_OPERATION);
return FALSE;
}
return TRUE;
}
BOOL CTcpServer::CheckStoping()
{
if(m_enState == SS_STARTED || m_enState == SS_STARTING)
m_enState = SS_STOPING;
else
{
SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_OPERATION);
return FALSE;
}
return TRUE;
}
BOOL CTcpServer::CreateListenSocket(LPCTSTR pszBindAddress, USHORT usPort)
{
BOOL isOK = FALSE;
m_soListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(m_soListen != INVALID_SOCKET)
{
SOCKADDR_IN addr;
::sockaddr_A_2_IN(AF_INET, pszBindAddress, usPort, addr);
if(::bind(m_soListen, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN)) != SOCKET_ERROR)
{
if(FirePrepareListen(m_soListen) != ISocketListener::HR_ERROR)
{
if(::listen(m_soListen, m_dwSocketListenQueue) != SOCKET_ERROR)
{
m_pfnAcceptEx = ::Get_AcceptEx_FuncPtr(m_soListen);
m_pfnGetAcceptExSockaddrs = ::Get_GetAcceptExSockaddrs_FuncPtr(m_soListen);
m_pfnDisconnectEx = ::Get_DisconnectEx_FuncPtr(m_soListen);
ASSERT(m_pfnAcceptEx);
ASSERT(m_pfnGetAcceptExSockaddrs);
ASSERT(m_pfnDisconnectEx);
isOK = TRUE;
}
else
SetLastError(SE_SOCKET_LISTEN, __FUNCTION__, ::WSAGetLastError());
}
else
SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ERROR_FUNCTION_FAILED);
}
else
SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
}
else
SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
return isOK;
}
BOOL CTcpServer::CreateCompletePort()
{
m_hCompletePort = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 0);
if(m_hCompletePort == nullptr)
SetLastError(SE_CP_CREATE, __FUNCTION__, ::GetLastError());
return (m_hCompletePort != nullptr);
}
BOOL CTcpServer::CreateWorkerThreads()
{
BOOL isOK = TRUE;
for(DWORD i = 0; i < m_dwWorkerThreadCount; i++)
{
HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, WorkerThreadProc, (LPVOID)this, 0, nullptr);
if(hThread)
m_vtWorkerThreads.push_back(hThread);
else
{
SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ::GetLastError());
isOK = FALSE;
break;
}
}
return isOK;
}
BOOL CTcpServer::StartAccept()
{
BOOL isOK = FALSE;
if(::CreateIoCompletionPort((HANDLE)m_soListen, m_hCompletePort, m_soListen, 0))
{
isOK = TRUE;
for(DWORD i = 0; i < m_dwAcceptSocketCount; i++)
::PostQueuedCompletionStatus(m_hCompletePort, IOCP_SI_ACCEPT, 0, nullptr);
}
else
SetLastError(SE_SOCKE_ATTACH_TO_CP, __FUNCTION__, ::GetLastError());
return isOK;
}
BOOL CTcpServer::Stop()
{
if(!CheckStoping())
return FALSE;
CloseListenSocket();
DisconnectClientSocket();
WaitForClientSocketClose();
WaitForWorkerThreadEnd();
ReleaseClientSocket();
FireServerShutdown();
ReleaseFreeSocket();
ReleaseFreeBuffer();
CloseCompletePort();
Reset();
return TRUE;
}
void CTcpServer::Reset()
{
m_phSocket.Reset();
m_phBuffer.Reset();
m_dwConnID = 0;
m_pfnAcceptEx = nullptr;
m_pfnGetAcceptExSockaddrs = nullptr;
m_pfnDisconnectEx = nullptr;
m_enState = SS_STOPED;
}
void CTcpServer::CloseListenSocket()
{
if(m_soListen != INVALID_SOCKET)
{
::ManualCloseSocket(m_soListen);
m_soListen = INVALID_SOCKET;
}
}
void CTcpServer::DisconnectClientSocket()
{
CReentrantWriteLock locallock(m_csClientSocket);
for(TSocketObjPtrMapI it = m_mpClientSocket.begin(); it != m_mpClientSocket.end(); ++it)
Disconnect(it->first);
}
void CTcpServer::ReleaseClientSocket()
{
CReentrantWriteLock locallock(m_csClientSocket);
for(TSocketObjPtrMapI it = m_mpClientSocket.begin(); it != m_mpClientSocket.end(); ++it)
{
TSocketObj* pSocketObj = it->second;
CloseSocketObj(pSocketObj);
DeleteSocketObj(pSocketObj);
}
m_mpClientSocket.clear();
}
TSocketObj* CTcpServer::GetFreeSocketObj()
{
TSocketObj* pSocketObj = nullptr;
if(m_lsFreeSocket.size() > 0)
{
CCriSecLock locallock(m_csFreeSocket);
if(m_lsFreeSocket.size() > 0)
{
pSocketObj = m_lsFreeSocket.front();
if(::GetTimeGap32(pSocketObj->freeTime) >= m_dwFreeSocketObjLockTime)
m_lsFreeSocket.pop_front();
else
pSocketObj = nullptr;
}
}
if(!pSocketObj) pSocketObj = CreateSocketObj();
pSocketObj->extra = nullptr;
return pSocketObj;
}
void CTcpServer::AddFreeSocketObj(CONNID dwConnID)
{
BOOL bDone = FALSE;
TSocketObj* pSocketObj = nullptr;
{
CReentrantWriteLock locallock(m_csClientSocket);
pSocketObj = FindSocketObj(dwConnID);
if(pSocketObj != nullptr)
{
m_mpClientSocket.erase(dwConnID);
bDone = TRUE;
}
}
if(bDone)
{
CloseSocketObj(pSocketObj);
{
CCriSecLock locallock(m_csFreeSocket);
pSocketObj->freeTime = ::TimeGetTime();
m_lsFreeSocket.push_back(pSocketObj);
}
if(m_lsFreeSocket.size() > m_dwFreeSocketObjHold)
CompressFreeSocket(m_dwFreeSocketObjPool);
}
}
void CTcpServer::AddClientSocketObj(CONNID dwConnID, TSocketObj* pSocketObj)
{
CReentrantWriteLock locallock(m_csClientSocket);
ASSERT(FindSocketObj(dwConnID) == nullptr);
pSocketObj->connTime = ::TimeGetTime();
m_mpClientSocket[dwConnID] = pSocketObj;
}
void CTcpServer::ReleaseFreeSocket()
{
CompressFreeSocket(0, TRUE);
}
void CTcpServer::CompressFreeSocket(size_t size, BOOL bForce)
{
CCriSecLock locallock(m_csFreeSocket);
while(m_lsFreeSocket.size() > size)
{
TSocketObj* pSocketObj = m_lsFreeSocket.front();
if(bForce || ::GetTimeGap32(pSocketObj->freeTime) >= m_dwFreeSocketObjLockTime)
{
m_lsFreeSocket.pop_front();
DeleteSocketObj(pSocketObj);
}
else
break;
}
}
TSocketObj* CTcpServer::CreateSocketObj()
{
TSocketObj* pSocketObj = (TSocketObj*)m_phSocket.Alloc(sizeof(TSocketObj) + sizeof(CRITICAL_SECTION), HEAP_ZERO_MEMORY);
CRITICAL_SECTION* pcrisec = (CRITICAL_SECTION*)(((char*)pSocketObj) + sizeof(TSocketObj));
ASSERT(pSocketObj);
::InitializeCriticalSection(pcrisec);
pSocketObj->crisec.Attach(pcrisec);
return pSocketObj;
}
void CTcpServer::DeleteSocketObj(TSocketObj* pSocketObj)
{
CRITICAL_SECTION* pcrisec = pSocketObj->crisec.Detach();
::DeleteCriticalSection(pcrisec);
m_phSocket.Free(pSocketObj);
}
TBufferObj* CTcpServer::GetFreeBufferObj(int iLen)
{
ASSERT(iLen >= 0 && iLen <= (int)m_dwSocketBufferSize);
TBufferObj* pBufferObj = nullptr;
if(m_lsFreeBuffer.size() > 0)
{
CCriSecLock locallock(m_csFreeBuffer);
if(m_lsFreeBuffer.size() > 0)
{
pBufferObj = m_lsFreeBuffer.front();
m_lsFreeBuffer.pop_front();
}
}
if(!pBufferObj) pBufferObj = CreateBufferObj();
if(iLen <= 0) iLen = m_dwSocketBufferSize;
pBufferObj->buff.len = iLen;
return pBufferObj;
}
void CTcpServer::AddFreeBufferObj(TBufferObj* pBufferObj)
{
{
CCriSecLock locallock(m_csFreeBuffer);
m_lsFreeBuffer.push_back(pBufferObj);
}
if(m_lsFreeBuffer.size() > m_dwFreeBufferObjHold)
CompressFreeBuffer(m_dwFreeBufferObjPool);
}
void CTcpServer::ReleaseFreeBuffer()
{
CompressFreeBuffer(0);
}
void CTcpServer::CompressFreeBuffer(size_t size)
{
CCriSecLock locallock(m_csFreeBuffer);
while(m_lsFreeBuffer.size() > size)
{
TBufferObj* pBufferObj = m_lsFreeBuffer.front();
m_lsFreeBuffer.pop_front();
DeleteBufferObj(pBufferObj);
}
}
TBufferObj* CTcpServer::CreateBufferObj()
{
TBufferObj* pBufferObj = (TBufferObj*)m_phBuffer.Alloc(sizeof(TBufferObj) + m_dwSocketBufferSize, HEAP_ZERO_MEMORY);
pBufferObj->buff.buf = ((char*)pBufferObj) + sizeof(TBufferObj);
ASSERT(pBufferObj);
return pBufferObj;
}
void CTcpServer::DeleteBufferObj(TBufferObj* pBufferObj)
{
m_phBuffer.Free(pBufferObj);
}
TSocketObj* CTcpServer::FindSocketObj(CONNID dwConnID)
{
TSocketObj* pSocketObj = nullptr;
CReentrantReadLock locallock(m_csClientSocket);
TSocketObjPtrMapCI it = m_mpClientSocket.find(dwConnID);
if(it != m_mpClientSocket.end())
pSocketObj = it->second;
return pSocketObj;
}
void CTcpServer::CloseSocketObj(TSocketObj* pSocketObj, int iShutdownFlag)
{
if(TSocketObj::IsValid(pSocketObj))
{
CCriSecLock2 locallock(pSocketObj->crisec);
if(pSocketObj->socket != INVALID_SOCKET)
{
::ManualCloseSocket(pSocketObj->socket, iShutdownFlag);
pSocketObj->socket = INVALID_SOCKET;
}
}
}
BOOL CTcpServer::GetListenAddress(LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
ASSERT(lpszAddress != nullptr && iAddressLen > 0);
return ::GetSocketLocalAddress(m_soListen, lpszAddress, iAddressLen, usPort);
}
BOOL CTcpServer::GetClientAddress(CONNID dwConnID, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
ASSERT(lpszAddress != nullptr && iAddressLen > 0);
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TSocketObj::IsValid(pSocketObj))
{
ADDRESS_FAMILY usFamily;
return ::sockaddr_IN_2_A(pSocketObj->clientAddr, usFamily, lpszAddress, iAddressLen, usPort);
}
return FALSE;
}
BOOL CTcpServer::SetConnectionExtra(CONNID dwConnID, PVOID pExtra)
{
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TSocketObj::IsValid(pSocketObj))
{
pSocketObj->extra = pExtra;
return TRUE;
}
return FALSE;
}
BOOL CTcpServer::GetConnectionExtra(CONNID dwConnID, PVOID* ppExtra)
{
ASSERT(ppExtra != nullptr);
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TSocketObj::IsValid(pSocketObj))
{
*ppExtra = pSocketObj->extra;
return TRUE;
}
return FALSE;
}
DWORD CTcpServer::GetConnectionCount()
{
return (DWORD)m_mpClientSocket.size();
}
BOOL CTcpServer::GetConnectPeriod(CONNID dwConnID, DWORD& dwPeriod)
{
BOOL isOK = TRUE;
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TSocketObj::IsValid(pSocketObj))
dwPeriod = GetTimeGap32(pSocketObj->connTime);
else
isOK = FALSE;
return isOK;
}
BOOL CTcpServer::Disconnect(CONNID dwConnID, BOOL bForce)
{
BOOL isOK = FALSE;
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TSocketObj::IsValid(pSocketObj))
{
if(bForce)
isOK = ::PostQueuedCompletionStatus(m_hCompletePort, IOCP_SI_DISCONNECT, dwConnID, nullptr);
else
isOK = m_pfnDisconnectEx(pSocketObj->socket, nullptr, 0, 0);
}
return isOK;
}
BOOL CTcpServer::DisconnectLongConnections(DWORD dwPeriod, BOOL bForce)
{
ulong_ptr_list ls;
{
CReentrantReadLock locallock(m_csClientSocket);
size_t size = m_mpClientSocket.size();
if(size > 0)
{
for(TSocketObjPtrMapCI it = m_mpClientSocket.begin(); it != m_mpClientSocket.end(); ++it)
{
if(::GetTimeGap32(it->second->connTime) >= dwPeriod)
ls.push_back(it->first);
}
}
}
size_t size = ls.size();
if(size > 0)
{
for(ulong_ptr_list::const_iterator it = ls.begin(); it != ls.end(); ++it)
Disconnect(*it, bForce);
}
return size > 0;
}
void CTcpServer::WaitForClientSocketClose()
{
DWORD dwWait = 0;
DWORD dwOrig = ::TimeGetTime();
while(m_mpClientSocket.size() > 0 && dwWait < m_dwMaxShutdownWaitTime)
{
::WaitWithMessageLoop(100);
dwWait = ::GetTimeGap32(dwOrig);
}
}
void CTcpServer::WaitForWorkerThreadEnd()
{
int count = (int)m_vtWorkerThreads.size();
for(int i = 0; i < count; i++)
::PostQueuedCompletionStatus(m_hCompletePort, IOCP_SI_EXIT, 0, nullptr);
int remain = count;
int index = 0;
while(remain > 0)
{
int wait = min(remain, MAXIMUM_WAIT_OBJECTS);
HANDLE* pHandles = (HANDLE*)_alloca(sizeof(HANDLE) * wait);
for(int i = 0; i < wait; i++)
pHandles[i] = m_vtWorkerThreads[i + index];
VERIFY(::WaitForMultipleObjects((DWORD)wait, pHandles, TRUE, INFINITE) == WAIT_OBJECT_0);
for(int i = 0; i < wait; i++)
::CloseHandle(pHandles[i]);
remain -= wait;
index += wait;
}
m_vtWorkerThreads.clear();
}
void CTcpServer::TerminateWorkerThread()
{
size_t count = m_vtWorkerThreads.size();
for(size_t i = 0; i < count; i++)
{
HANDLE hThread = m_vtWorkerThreads[i];
::TerminateThread(hThread, 1);
::CloseHandle(hThread);
}
m_vtWorkerThreads.clear();
}
void CTcpServer::CloseCompletePort()
{
if(m_hCompletePort != nullptr)
{
::CloseHandle(m_hCompletePort);
m_hCompletePort = nullptr;
}
}
BOOL CTcpServer::DoAccept()
{
BOOL isOK = FALSE;
if(HasStarted())
{
SOCKET soClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
TBufferObj* pBufferObj = GetFreeBufferObj();
ASSERT(soClient != INVALID_SOCKET);
isOK = (::PostAccept(m_pfnAcceptEx, m_soListen, soClient, pBufferObj) == NO_ERROR);
if(!isOK)
{
VERIFY(!HasStarted());
::ManualCloseSocket(soClient);
AddFreeBufferObj(pBufferObj);
}
}
return isOK;
}
UINT WINAPI CTcpServer::WorkerThreadProc(LPVOID pv)
{
CTcpServer* pServer = (CTcpServer*)pv;
while (TRUE)
{
DWORD dwErrorCode = NO_ERROR;
DWORD dwBytes;
OVERLAPPED* pOverlapped;
TSocketObj* pSocketObj;
BOOL result = ::GetQueuedCompletionStatus
(
pServer->m_hCompletePort,
&dwBytes,
(PULONG_PTR)&pSocketObj,
&pOverlapped,
INFINITE
);
if(pOverlapped == nullptr)
{
int indative = pServer->CheckSpecialIndative(pOverlapped, dwBytes, pSocketObj);
if(indative == IOCP_SI_RS_CONTINUE)
continue;
else if(indative == IOCP_SI_RS_BREAK)
break;
}
TBufferObj* pBufferObj = CONTAINING_RECORD(pOverlapped, TBufferObj, ov);
CONNID dwConnID = pBufferObj->operation != SO_ACCEPT ? pSocketObj->connID : 0;
if (!result)
{
DWORD dwFlag = 0;
DWORD dwSysCode = ::GetLastError();
if(pServer->HasStarted())
{
SOCKET sock = pBufferObj->operation != SO_ACCEPT ? pSocketObj->socket : (SOCKET)pSocketObj;
result = ::WSAGetOverlappedResult(sock, &pBufferObj->ov, &dwBytes, FALSE, &dwFlag);
if (!result)
{
dwErrorCode = ::WSAGetLastError();
TRACE("GetQueuedCompletionStatus error (<S-CNNID: %Iu> SYS: %d, SOCK: %d, FLAG: %d)\n", dwConnID, dwSysCode, dwErrorCode, dwFlag);
}
}
else
dwErrorCode = dwSysCode;
}
pServer->HandleIo(dwConnID, pSocketObj, pBufferObj, dwBytes, dwErrorCode);
}
return 0;
}
int CTcpServer::CheckSpecialIndative(OVERLAPPED* pOverlapped, DWORD dwBytes, TSocketObj* pSocketObj)
{
int indative = 0;
if(pOverlapped == nullptr)
{
if(dwBytes == IOCP_SI_ACCEPT)
{
DoAccept();
indative = IOCP_SI_RS_CONTINUE;
}
else if(dwBytes == IOCP_SI_DISCONNECT)
{
ForceDisconnect((CONNID)pSocketObj);
indative = IOCP_SI_RS_CONTINUE;
}
else if(dwBytes == IOCP_SI_EXIT && pSocketObj == nullptr)
indative = IOCP_SI_RS_BREAK;
else
VERIFY(FALSE);
}
return indative;
}
void CTcpServer::ForceDisconnect(CONNID dwConnID)
{
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(TSocketObj::IsValid(pSocketObj))
{
FireClose(dwConnID);
AddFreeSocketObj(dwConnID);
}
}
void CTcpServer::HandleIo(CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj, DWORD dwBytes, DWORD dwErrorCode)
{
ASSERT(pBufferObj != nullptr);
ASSERT(pSocketObj != nullptr);
if(dwErrorCode != NO_ERROR)
{
HandleError(dwConnID, pBufferObj, dwErrorCode);
return;
}
if(dwBytes == 0 && pBufferObj->operation != SO_ACCEPT)
{
FireClose(dwConnID);
AddFreeSocketObj(dwConnID);
AddFreeBufferObj(pBufferObj);
return;
}
pBufferObj->buff.len = dwBytes;
switch(pBufferObj->operation)
{
case SO_ACCEPT:
HandleAccept((SOCKET)pSocketObj, pBufferObj);
break;
case SO_SEND:
HandleSend(dwConnID, pSocketObj, pBufferObj);
break;
case SO_RECEIVE:
HandleReceive(dwConnID, pSocketObj, pBufferObj);
break;
default:
ASSERT(FALSE);
}
}
void CTcpServer::HandleError(CONNID dwConnID, TBufferObj* pBufferObj, DWORD dwErrorCode)
{
if(pBufferObj->operation != SO_ACCEPT)
CheckError(dwConnID, pBufferObj->operation, dwErrorCode);
else
{
::ManualCloseSocket(pBufferObj->client);
::PostQueuedCompletionStatus(m_hCompletePort, IOCP_SI_ACCEPT, 0, nullptr);
}
AddFreeBufferObj(pBufferObj);
}
void CTcpServer::HandleAccept(SOCKET soListen, TBufferObj* pBufferObj)
{
::PostQueuedCompletionStatus(m_hCompletePort, IOCP_SI_ACCEPT, 0, nullptr);
int iLocalSockaddrLen;
int iRemoteSockaddrLen;
SOCKADDR* pLocalSockAddr;
SOCKADDR* pRemoteSockAddr;
m_pfnGetAcceptExSockaddrs
(
pBufferObj->buff.buf,
0,
sizeof(SOCKADDR_IN) + 16,
sizeof(SOCKADDR_IN) + 16,
(SOCKADDR **)&pLocalSockAddr,
&iLocalSockaddrLen,
(SOCKADDR **)&pRemoteSockAddr,
&iRemoteSockaddrLen
);
SOCKET socket = pBufferObj->client;
CONNID dwConnID = ::GenerateConnectionID(m_dwConnID);
TSocketObj* pSocketObj = GetFreeSocketObj();
pSocketObj->socket = socket;
pSocketObj->connID = dwConnID;
memcpy(&pSocketObj->clientAddr, pRemoteSockAddr, sizeof(SOCKADDR_IN));
AddClientSocketObj(dwConnID, pSocketObj);
VERIFY(::SSO_UpdateAcceptContext(socket, soListen) == NO_ERROR);
BOOL bOnOff = (m_dwKeepAliveTime > 0 && m_dwKeepAliveInterval > 0);
VERIFY(::SSO_KeepAliveVals(socket, bOnOff, m_dwKeepAliveTime, m_dwKeepAliveInterval) == NO_ERROR);
if(FireAccept(dwConnID, socket) != ISocketListener::HR_ERROR)
{
VERIFY(::CreateIoCompletionPort((HANDLE)socket, m_hCompletePort, (ULONG_PTR)pSocketObj, 0));
DoReceive(dwConnID, pSocketObj, pBufferObj);
}
else
{
AddFreeSocketObj(dwConnID);
AddFreeBufferObj(pBufferObj);
}
}
void CTcpServer::HandleSend(CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
if(FireSend(dwConnID, (BYTE*)pBufferObj->buff.buf, pBufferObj->buff.len) == ISocketListener::HR_ERROR)
{
TRACE1("<S-CNNID: %Iu> OnSend() event should not return 'HR_ERROR' !!\n", dwConnID);
ASSERT(FALSE);
}
AddFreeBufferObj(pBufferObj);
}
void CTcpServer::HandleReceive(CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
if(FireReceive(dwConnID, (BYTE*)pBufferObj->buff.buf, pBufferObj->buff.len) != ISocketListener::HR_ERROR)
DoReceive(dwConnID, pSocketObj, pBufferObj);
else
{
TRACE1("<S-CNNID: %Iu> OnReceive() event return 'HR_ERROR', connection will be closed !\n", dwConnID);
FireError(dwConnID, SO_RECEIVE, ERROR_FUNCTION_FAILED);
AddFreeSocketObj(dwConnID);
AddFreeBufferObj(pBufferObj);
}
}
int CTcpServer::DoReceive(CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
pBufferObj->buff.len = m_dwSocketBufferSize;
int result = ::PostReceive(pSocketObj, pBufferObj);
if(result != NO_ERROR)
{
CheckError(dwConnID, SO_RECEIVE, result);
AddFreeBufferObj(pBufferObj);
}
return result;
}
BOOL CTcpServer::Send(CONNID dwConnID, const BYTE* pBuffer, int iLength)
{
ASSERT(pBuffer && iLength > 0);
TSocketObj* pSocketObj = FindSocketObj(dwConnID);
if(pSocketObj == nullptr)
return FALSE;
int result = DoSend(dwConnID, pSocketObj, pBuffer, iLength);
if(result != NO_ERROR)
CheckError(dwConnID, SO_SEND, result);
return (result == NO_ERROR);
}
int CTcpServer::DoSend(CONNID dwConnID, TSocketObj* pSocketObj, const BYTE* pBuffer, int iLen)
{
int result = NO_ERROR;
int iRemain = iLen;
CCriSecLock2 locallock(pSocketObj->crisec);
while(iRemain > 0)
{
int iBufferSize = min(iRemain, (int)m_dwSocketBufferSize);
TBufferObj* pBufferObj = GetFreeBufferObj(iBufferSize);
memcpy(pBufferObj->buff.buf, pBuffer, iBufferSize);
result = ::PostSend(pSocketObj, pBufferObj);
if(result != NO_ERROR)
{
AddFreeBufferObj(pBufferObj);
break;
}
iRemain -= iBufferSize;
pBuffer += iBufferSize;
}
return result;
}
void CTcpServer::CheckError(CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
if(iErrorCode != WSAENOTSOCK && iErrorCode != ERROR_OPERATION_ABORTED)
{
FireError(dwConnID, enOperation, iErrorCode);
AddFreeSocketObj(dwConnID);
}
}
LPCTSTR CTcpServer::GetLastErrorDesc()
{
switch(m_enLastError)
{
case SE_OK: return _T("成功");
case SE_ILLEGAL_STATE: return _T("当前状态不允许操作");
case SE_INVALID_PARAM: return _T("非法参数");
case SE_SOCKET_CREATE: return _T("创建监听 SOCKET 失败");
case SE_SOCKET_BIND: return _T("绑定监听地址失败");
case SE_SOCKET_PREPARE: return _T("设置监听 SOCKET 失败");
case SE_SOCKET_LISTEN: return _T("启动监听失败");
case SE_CP_CREATE: return _T("创建完成端口失败");
case SE_WORKER_THREAD_CREATE: return _T("创建工作线程失败");
case SE_SOCKE_ATTACH_TO_CP: return _T("监听 SOCKET 绑定到完成端口失败");
default: ASSERT(FALSE); return _T("");
}
}
| [
"chenchao0632@163.com"
] | chenchao0632@163.com |
fab069da66072e5fe5234200e196b4ecb9b5461c | d3b2d0432a4f488128c2798829d017a1a2377318 | /caffe/include/caffe/layers/softmax_layer.hpp | 6b0ea7d4e2057c985318a8415452d6c820f83d9e | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | openvinotoolkit/training_toolbox_caffe | 94b65290724e839cdb50e4accf6a79776190402d | 5e543a49c73190a091fe6ff364444a9714962ec0 | refs/heads/develop | 2023-01-05T17:07:42.279772 | 2022-12-21T06:50:52 | 2022-12-21T06:50:52 | 165,683,591 | 4 | 3 | Apache-2.0 | 2022-12-21T06:50:53 | 2019-01-14T15:19:52 | Jupyter Notebook | UTF-8 | C++ | false | false | 3,451 | hpp | /*
All modification made by Intel Corporation: © 2016 Intel Corporation
All contributions by the University of California:
Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
All rights reserved.
All other contributions:
Copyright (c) 2014, 2015, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAFFE_SOFTMAX_LAYER_HPP_
#define CAFFE_SOFTMAX_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Computes the softmax function.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class SoftmaxLayer : public Layer<Dtype> {
public:
explicit SoftmaxLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Softmax"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
int outer_num_;
int inner_num_;
int softmax_axis_;
/// sum_multiplier is used to carry out sum using BLAS
Blob<Dtype> sum_multiplier_;
/// scale is an intermediate Blob to hold temporary results.
Blob<Dtype> scale_;
};
} // namespace caffe
#endif // CAFFE_SOFTMAX_LAYER_HPP_
| [
"evgeny.izutov@intel.com"
] | evgeny.izutov@intel.com |
761a6b87ebc1725e01b23c039354bfad62babb5a | 4f27ee76eeca2422e84d29d483f1f9570d26b6b4 | /Finance/Design Patterns/PolyOption/Instrument.h | 0e537a9970acff7a2af84a4e3431f4ff84aee41d | [] | no_license | dsocaciu/Projects | 5a52b98600400d66f4a4f00bb59676bed70ad602 | aa722562534408f6c84f6ca2c0b928d038c74cb3 | refs/heads/master | 2021-01-19T13:01:22.288458 | 2017-06-14T19:25:59 | 2017-06-14T19:25:59 | 82,357,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | h | //File: Instrument.h
//Info: Provides base information for security
//Author: Dan Socaciu
using namespace std;
#ifndef INSTRUMENT_H_
#define INSTRUMENT_H_
//Instrument
//contains the shared components of the stock and option
class Instrument{
protected:
float bidPrice;
int bidSize;
float askPrice;
int askSize;
public:
char name[12];
void setName(char *str);
void setBidPrice(float bPrice);
void setBidSize(int bSize);
void setAskPrice(float aPrice);
void setAskSize(int aSize);
float getBidPrice();
int getBidSize();
float getAskPrice();
int getAskSize();
Instrument();
virtual ~Instrument();
};
//contains the inherited features of the Instrument class
//along with stock specific functionality
class Stock: public Instrument
{
protected:
string exchange;
public:
void setExchange(string exc);
string getExchange();
Stock();
virtual ~Stock();
};
//contains the inherited features of the Instrument class
//along with Option specific functionality
class Option: public Instrument
{
protected:
string expiration;
public:
char option_name[26];
void setExpiration(string exp);
string getExpiration();
Option();
virtual ~Option();
};
#endif /*INSTRUMENT_H_*/
| [
"dan.socaciu@gmail.com"
] | dan.socaciu@gmail.com |
ce92b263587f3d5fe7ea6d787e950e7bffa59663 | e217eaf05d0dab8dd339032b6c58636841aa8815 | /IfcRoad/src/OpenInfraPlatform/IfcRoad/entity/IfcCivilElementType.cpp | a4e79d1dd50629819d51a5b18c9a66751453ecd9 | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | UTF-8 | C++ | false | false | 4,689 | cpp | /*! \verbatim
* \copyright Copyright (c) 2015 Julian Amann. All rights reserved.
* \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann)
* \brief This file is part of the OpenInfraPlatform.
* \endverbatim
*/
#include <sstream>
#include <limits>
#include "OpenInfraPlatform/IfcRoad/model/IfcRoadException.h"
#include "OpenInfraPlatform/IfcRoad/reader/ReaderUtil.h"
#include "OpenInfraPlatform/IfcRoad/writer/WriterUtil.h"
#include "OpenInfraPlatform/IfcRoad/IfcRoadEntityEnums.h"
#include "include/IfcCivilElementType.h"
#include "include/IfcGloballyUniqueId.h"
#include "include/IfcIdentifier.h"
#include "include/IfcLabel.h"
#include "include/IfcOwnerHistory.h"
#include "include/IfcPropertySetDefinition.h"
#include "include/IfcRelAggregates.h"
#include "include/IfcRelAssigns.h"
#include "include/IfcRelAssignsToProduct.h"
#include "include/IfcRelAssociates.h"
#include "include/IfcRelDeclares.h"
#include "include/IfcRelDefinesByType.h"
#include "include/IfcRelNests.h"
#include "include/IfcRepresentationMap.h"
#include "include/IfcText.h"
namespace OpenInfraPlatform
{
namespace IfcRoad
{
// ENTITY IfcCivilElementType
IfcCivilElementType::IfcCivilElementType() { m_entity_enum = IFCCIVILELEMENTTYPE; }
IfcCivilElementType::IfcCivilElementType( int id ) { m_id = id; m_entity_enum = IFCCIVILELEMENTTYPE; }
IfcCivilElementType::~IfcCivilElementType() {}
// method setEntity takes over all attributes from another instance of the class
void IfcCivilElementType::setEntity( shared_ptr<IfcRoadEntity> other_entity )
{
shared_ptr<IfcCivilElementType> other = dynamic_pointer_cast<IfcCivilElementType>(other_entity);
if( !other) { return; }
m_GlobalId = other->m_GlobalId;
m_OwnerHistory = other->m_OwnerHistory;
m_Name = other->m_Name;
m_Description = other->m_Description;
m_ApplicableOccurrence = other->m_ApplicableOccurrence;
m_HasPropertySets = other->m_HasPropertySets;
m_RepresentationMaps = other->m_RepresentationMaps;
m_Tag = other->m_Tag;
m_ElementType = other->m_ElementType;
}
void IfcCivilElementType::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "=IFCCIVILELEMENTTYPE" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->getId(); } else { stream << "$"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_ApplicableOccurrence ) { m_ApplicableOccurrence->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
writeEntityList( stream, m_HasPropertySets );
stream << ",";
writeEntityList( stream, m_RepresentationMaps );
stream << ",";
if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_ElementType ) { m_ElementType->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcCivilElementType::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcCivilElementType::readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcRoadEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args<9 ){ std::stringstream strserr; strserr << "Wrong parameter count for entity IfcCivilElementType, expecting 9, having " << num_args << ". Object id: " << getId() << std::endl; throw IfcRoadException( strserr.str().c_str() ); }
#ifdef _DEBUG
if( num_args>9 ){ std::cout << "Wrong parameter count for entity IfcCivilElementType, expecting 9, having " << num_args << ". Object id: " << getId() << std::endl; }
#endif
m_GlobalId = IfcGloballyUniqueId::readStepData( args[0] );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::readStepData( args[2] );
m_Description = IfcText::readStepData( args[3] );
m_ApplicableOccurrence = IfcIdentifier::readStepData( args[4] );
readEntityReferenceList( args[5], m_HasPropertySets, map );
readEntityReferenceList( args[6], m_RepresentationMaps, map );
m_Tag = IfcLabel::readStepData( args[7] );
m_ElementType = IfcLabel::readStepData( args[8] );
}
void IfcCivilElementType::setInverseCounterparts( shared_ptr<IfcRoadEntity> ptr_self_entity )
{
IfcElementType::setInverseCounterparts( ptr_self_entity );
}
void IfcCivilElementType::unlinkSelf()
{
IfcElementType::unlinkSelf();
}
} // end namespace IfcRoad
} // end namespace OpenInfraPlatform
| [
"planung.cms.bv@tum.de"
] | planung.cms.bv@tum.de |
5e9a69b48687d6493ac8bc43f20dd7a5187b13cc | 8fd935d0bcf03a176dc1c042602e731aab016f43 | /libvis/src/libvis/cuda/cuda_unprojection_lookup.h | 77b9f0d78cbfb85f8fba7713185c19e67ab58d6d | [
"BSD-3-Clause"
] | permissive | ETH3D/badslam | 9ce088d96672ee5385f721928d3e6536778e1574 | c66bdc841658cc04f9feae229c746b32f4284102 | refs/heads/master | 2022-07-08T05:39:08.983448 | 2022-05-11T19:12:04 | 2022-05-11T19:12:04 | 192,239,549 | 691 | 124 | BSD-3-Clause | 2022-04-27T23:52:53 | 2019-06-16T21:43:54 | C++ | UTF-8 | C++ | false | false | 3,233 | h | // Copyright 2017, 2019 ETH Zürich, Thomas Schöps
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <cuda_runtime.h>
#include "libvis/camera.h"
#include "libvis/cuda/cuda_buffer.h"
#include "libvis/eigen.h"
#include "libvis/libvis.h"
namespace vis {
class CUDAUnprojectionLookup2D_;
// Creates a lookup texture for 2D unprojection of image pixels to directions,
// i.e., assuming that the z component of the unprojected vectors is always 1.
class CUDAUnprojectionLookup2D {
public:
inline CUDAUnprojectionLookup2D(const Camera& camera, cudaStream_t stream)
: lookup_buffer_(camera.height(), camera.width()) {
IDENTIFY_CAMERA(camera, Initialize(_camera, stream));
}
inline ~CUDAUnprojectionLookup2D() {
cudaDestroyTextureObject(lookup_texture_);
}
inline cudaTextureObject_t lookup_texture() const {
return lookup_texture_;
}
private:
template <typename CameraT>
void Initialize(const CameraT& camera, cudaStream_t stream) {
Image<float2> lookup_buffer_cpu(camera.width(), camera.height());
for (int y = 0; y < camera.height(); ++ y) {
for (int x = 0; x < camera.width(); ++ x) {
Vec2f dir = camera.UnprojectFromPixelCenterConv(Vec2d(x, y).cast<typename CameraT::ScalarT>()).template cast<float>().template topRows<2>();
lookup_buffer_cpu(x, y) = make_float2(dir.x(), dir.y());
}
}
lookup_buffer_.UploadAsync(stream, lookup_buffer_cpu);
lookup_buffer_.CreateTextureObject(
cudaAddressModeClamp, cudaAddressModeClamp,
cudaFilterModeLinear, cudaReadModeElementType,
false, &lookup_texture_);
cudaStreamSynchronize(stream);
}
CUDABuffer<float2> lookup_buffer_;
cudaTextureObject_t lookup_texture_;
};
}
| [
"tom.schoeps@gmail.com"
] | tom.schoeps@gmail.com |
58e847b09abb48cc43d7e5a36428e7b2147fef15 | 19079c088fc306ac773d4a6f7e85715a3fc8cc9d | /challenge/flutter/all_samples/material_restorationmixin_1/linux/my_application.cc | 9104527c8279a4f10dab5d32fb3ee1e2193022e4 | [
"Apache-2.0"
] | permissive | davidzou/WonderingWall | 75929193af4852675209b21dd544cb8b60da5fa5 | 1060f6501c432510e164578d4af60a49cd5ed681 | refs/heads/master | 2022-11-03T22:33:12.340125 | 2022-10-14T08:12:14 | 2022-10-14T08:12:14 | 5,868,257 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cc | #include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "material_restorationmixin_1");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "material_restorationmixin_1");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
"flags", G_APPLICATION_NON_UNIQUE,
nullptr));
}
| [
"wearecisco@gmail.com"
] | wearecisco@gmail.com |
3b26c2d3643805e57954d2f14e0c07f82a4bd229 | f99c0194278639456604ebf76443b65bf1c6ed04 | /core/src/extension/Message/JoiningContract.cpp | 02b6f7863e036c1791093c0287851651230b26ad | [] | no_license | RdeWilde/JoyStream | e4ed42ff61af1f348cb49469caa8e30ccf3f8a52 | 95c2b6fc50251fbe4730b19d47c18bec86e18bf4 | refs/heads/master | 2021-06-11T20:26:46.682624 | 2016-05-10T08:27:05 | 2016-05-10T08:27:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,367 | cpp | /**
* Copyright (C) JoyStream - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Bedeho Mender <bedeho.mender@gmail.com>, June 26 2015
*/
#include <core/extension/Message/JoiningContract.hpp>
#include <core/extension/Message/MessageType.hpp>
#include <QDataStream>
#include <common/PublicKey.hpp>
JoiningContract::JoiningContract() {
}
JoiningContract::JoiningContract(const Coin::PublicKey & contractPk, const Coin::PublicKey & finalPk)
: _contractPk(contractPk)
, _finalPk(finalPk) {
}
JoiningContract::JoiningContract(QDataStream & stream) {
// DOESN'T LINK: stream >> _contractPk >> _finalPk;
Coin::operator >> (stream, _contractPk);
Coin::operator >> (stream, _finalPk);
}
Coin::PublicKey JoiningContract::contractPk() const {
return _contractPk;
}
Coin::PublicKey JoiningContract::finalPk() const {
return _finalPk;
}
MessageType JoiningContract::messageType() const {
return MessageType::joining_contract;
}
quint32 JoiningContract::length() const {
return Coin::PublicKey::length() + Coin::PublicKey::length();
}
void JoiningContract::write(QDataStream & stream) const {
// DOESN'T LINK: stream << _contractPk << _finalPk;
Coin::operator << (stream, _contractPk);
Coin::operator << (stream, _finalPk);
}
| [
"bedeho.mender@gmail.com"
] | bedeho.mender@gmail.com |
4368fcdaf21fcb24166c0506c433f1f3bf79ef20 | 2d3e99f8329f49bfb07d6a2da1f0c4bef028131b | /TimBall TomBall/TimBall TomBall/Vector2.cpp | 65e02556f15e051926a3bea778b6bd8bd92e1f1a | [] | no_license | twbentley/PinballFinal | 23f1498a448a76f5b5b7226029d9d2dc2109d14c | 40f300f0c5c84199a044fdeec2023a9cea6ab064 | refs/heads/master | 2021-01-10T20:58:54.254314 | 2013-05-19T03:12:11 | 2013-05-19T03:12:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,628 | cpp | // Based off of Angel's vec2 functionality
#include "Vector2.h"
// Default Constructor
Vector2::Vector2()
{
x = 0;
y = 0;
}
// Parameterized Constructor
Vector2::Vector2(GLfloat px, GLfloat py)
{
x = px;
y = py;
}
// Copy Constructor
Vector2::Vector2(const Vector2& v)
{
x = v.x;
y = v.y;
}
// Destructor
Vector2::~Vector2() { }
// Copy assignment
Vector2& Vector2::operator=(const Vector2& other)
{
x = other.x;
y = other.y;
return *this;
}
// Indexers (make safer?)
GLfloat& Vector2::operator[](int i)
{
return *(&x + i);
}
const GLfloat Vector2::operator[](int i) const
{
return *(&x + i);
}
// Vector value negation operator (return Vector using new values)
Vector2 Vector2::operator - () const
{
return Vector2( -x, -y);
}
// Vector-Vector addition operator (return Vector using new values)
Vector2 Vector2::operator + ( const Vector2& v ) const
{
return Vector2( x + v.x, y + v.y);
}
// Vector-Vector subtraction operator (return Vector using new values)
Vector2 Vector2::operator - ( const Vector2& v ) const
{
return Vector2(x - v.x, y - v.y);
}
// Vector-scalar multiplication operator (return Vector using new values)
Vector2 Vector2::operator * ( const GLfloat s ) const
{
return Vector2(s * x, s * y);
}
// Vector-Vector multiplication operator (return Vector using new values)
Vector2 Vector2::operator * ( const Vector2& v ) const
{
return Vector2(v.x * x, v.y * y);
}
// Vector-scalar division operator
Vector2 Vector2::operator / ( const GLfloat s ) const
{
GLfloat temp = GLfloat(1.0) / s;
return *this * temp;
}
// Vector-Vector addition applied to this object
Vector2& Vector2::operator += ( const Vector2& v )
{
x += v.x; y += v.y; return *this;
}
// Vector-Vector subtraction applied to this object
Vector2& Vector2::operator -= ( const Vector2& v )
{
x -= v.x; y -= v.y; return *this;
}
// Vector-scalar multiplication applied to this object
Vector2& Vector2::operator *= ( const GLfloat s )
{
x *= s; y *= s; return *this;
}
// Vector-Vector multiplication applied to this object
Vector2& Vector2::operator *= ( const Vector2& v )
{
x *= v.x; y *= v.y; return *this;
}
// Vector-scalar division applied to this object
Vector2& Vector2::operator /= ( const GLfloat s )
{
GLfloat r = GLfloat(1.0) / s;
*this *= r;
return *this;
}
// Vector-Vector dot product
GLfloat Vector2::dot( const Vector2& v ) const
{
return x*v.x + y*v.y;
}
// Vector length
GLfloat Vector2::length( ) const
{
return std::sqrt(dot(*this));
}
// Vector normalize
Vector2 Vector2::normalize( ) const
{
return *this / length();
}
Vector2::operator double()
{
return length();
} | [
"twb1193@OH1370-23.main.ad.rit.edu"
] | twb1193@OH1370-23.main.ad.rit.edu |
b7e3dae465f3a6fae2aca018f5870e950dd75568 | bd893ed31f5a50d5be969625f8c6c233734b60ac | /sprout/functional/member.hpp | 1a5312d6c56538d73a53408abf58daa17d817143 | [
"BSL-1.0"
] | permissive | kennethho/Sprout | 021fb3b7583fcf05e59c6c2916292073cd210981 | dad087cd69627897da31a531c9da989c661866cc | refs/heads/master | 2021-01-22T00:50:54.516815 | 2013-12-12T14:38:33 | 2013-12-12T14:38:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | hpp | /*=============================================================================
Copyright (c) 2011-2013 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_FUNCTIONAL_MEMBER_HPP
#define SPROUT_FUNCTIONAL_MEMBER_HPP
#include <utility>
#include <sprout/config.hpp>
#include <sprout/utility/forward.hpp>
namespace sprout {
//
// member
//
template<typename T = void>
struct member;
template<>
struct member<void> {
public:
typedef void is_transparent;
public:
template<typename T, typename U>
SPROUT_CONSTEXPR decltype(std::declval<T>().*std::declval<U>())
operator()(T&& x, U&& y)
const SPROUT_NOEXCEPT_EXPR(SPROUT_NOEXCEPT_EXPR(std::declval<T>().*std::declval<U>()))
{
return sprout::forward<T>(x).*sprout::forward<U>(y);
}
};
} // namespace sprout
#endif // #ifndef SPROUT_FUNCTIONAL_MEMBER_HPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
89d9993f76b98ba595dbcdb5ec614341a1a96deb | 17af777718e66d1735632c171e5286ff04c42665 | /00BOJ4195.cpp | eb1eecffe19353d0bee8c4242302ca49a891ed3c | [] | no_license | girinssh/BOJ | 4ddff350e309d85a153232062426f660e1144498 | 0964033e66081ecc81da6db421812ffb7f2eeacd | refs/heads/master | 2023-07-14T19:08:52.364347 | 2021-08-17T09:11:24 | 2021-08-17T09:11:24 | 284,575,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | cpp | #include <iostream>
#include <map>
#include <unordered_map>
using namespace std;
int main(void) {
cin.tie(NULL);
cin.sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
map<string, string> net;
int n;
cin >> n;
}
} | [
"tngus5851@naver.com"
] | tngus5851@naver.com |
9f951489741f62fb51100539b53a7e84592b021b | 7f515e54ff817bc8da374f2d1eca4c6ec88528f2 | /GraphicsApps/src/15_5-TextureMappedMesh.cpp | ce2a1a7f6d15113cad5ebfc6db49ef1077c273a7 | [] | no_license | rosshoyt/Computer-Graphics-FA19 | 21c02f1484f602d0ab5421e86b4d65fb7c13c80b | bacf3db38958465d51bf4e227fa57d24b252dca2 | refs/heads/master | 2020-08-05T19:35:09.870617 | 2019-12-03T23:20:49 | 2019-12-03T23:20:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,010 | cpp | // Ross Hoyt and Chris Downing - Assignment 5 - Phong face with Texture
#include <glad.h>
#include <glfw/glfw3.h>
#include <float.h>
#include <stdio.h>
#include <string.h>
#include "GLXtras.h"
#include "Camera.h"
#include "Draw.h"
#include <Misc.h>
#include <Numbers.h>
#include "VecMat.h"
#include <algorithm>
#include <vector>
// vertices for left half of face
vec3 leftPoints[] = {
vec3(722,244,434), vec3(912,269,488), vec3(1052,318,670), // 0-2
vec3(722,447,284), vec3(978,450,366), vec3(1093,496,490), vec3(1143,586,561), vec3(1173,732,687), // 3-7
vec3(722,660,216), vec3(1018,593,308), vec3(1147,787,516), // 8-10
vec3(722,1103,50), vec3(793,951,196), vec3(833,900,307), vec3(1065,923,409), // 11-14
vec3(722,1275,176),vec3(898,1134,286), vec3(1100,1095,417), vec3(1128,1219,543), // 15-18
vec3(904,1298,241),vec3(1024,1356,333), // 19-20
vec3(722,1480,162),vec3(853,1578,201), vec3(957,1594,440), vec3(1120,1255,818), // 21-24
vec3(722,1741,154),vec3(722,1802,554), vec3(977,1650,782), // 25-27
vec3(1185,914,653) // 28
};
// triangles for left half of face
int leftTriangles[][3] = {
{0,1,3}, {1,4,3}, {1,2,4}, {2,5,4}, {2,6,5},
{3,4,8}, {4,9,8}, {4,5,10}, {4,9,10}, {5,6,10}, {6,7,10}, {7,28,10}, {7,24,28},
/*{8,9,13},*/{8,13,12}, {8,12,11}, /*{9,10,14}, {9,14,13},*/ {10,28,18}, {10,18,17}, {10,17,14},
{11,12,16}, {11,16,15}, {12,13,16}, {13,14,16}, {14,17,16},
{15,16,19}, {15,19,21}, {16,17,18}, {16,18,20}, {16,20,19}, {17,10,18}, {18,28,24}, {18,24,23}, {18,23,20},
{19,20,21}, {20,23,22}, {20,22,21},
{21,22,25}, {22,23,25}, {23,24,27}, {23,27,26}, {23,26,25}
};
// entire face
const int nLeftPoints = sizeof(leftPoints)/sizeof(leftPoints[0]);
const int nLeftTriangles = sizeof(leftTriangles)/sizeof(leftTriangles[0]);
const int npoints = 2*nLeftPoints, ntriangles = 2*nLeftTriangles;
vec3 normals[npoints], points[npoints];
int triangles[ntriangles][3];
int sizePts = sizeof(points);
int midX = leftPoints[0].x; // midpoint of face
std::vector<vec2> uvs; // vertex texture coordinates
int textureUnit = 0;
const char* filename = "C:\\Users\\Ross\ Hoyt\\Desktop\\ComputerGraphics_FA19\\GraphicsApps\\res\\texturesFaceCropped_Texture.tga";
GLuint textureName;
// shaders
const char *vShader = "\
#version 130 \n\
in vec3 point; \n\
in vec3 normal; \n\
in vec2 uv; \n\
uniform mat4 modelview; \n\
uniform mat4 persp; \n\
uniform mat4 textureTransform = mat4(1); \n\
out vec3 vPoint; \n\
out vec3 vNormal; \n\
out ve2 vuv; \n\
void main() { \n\
vPoint = (modelview*vec4(point, 1)).xyz; \n\
vNormal = (modelview*vec4(normal, 0)).xyz; \n\
vuv = (textureTransform * vec4(uv, 0, 1)).xy; \n\
gl_Position = persp*vec4(vPoint, 1); \n\
}";
const char *pShader = "\
#version 130 \n\
in vec2 vuv; \n\
in vec3 vPoint; \n\
in vec3 vNormal; \n\
uniform sampler2D textureImage; \n\
uniform float a = 0.1; \n\
uniform vec3 lightPos = vec3(-1, 0, -2); \n\
uniform vec3 color = texture(textureImage, vuv).rgb; \n\
out vec4 pColor; \n\
void main() { \n\
vec3 N = normalize(vNormal); \n\
vec3 L = normalize(lightPos-vPoint); \n\
vec3 R = reflect(L, N); \n\
vec3 E = normalize(vPoint); \n\
float d = abs(dot(L, N)); \n\
float h = max(0, dot(R, E)); \n\
float s = pow(h, 100); \n\
float intensity = clamp(a+d+s, 0, 1); \n\
pColor = vec4(intensity*color, 1); \n\
}";
// OpenGL identifiers
GLuint vBuffer = 0, program = 0;
// window size and camera
int winWidth = 800, winHeight = 1000;
Camera camera(winWidth, winHeight, vec3(0, 0, 0), vec3(0, 0, -5), 30, 0.001f, 500, false);
// display
bool annotate = false;
void Display(GLFWwindow* w) {
// clear to gray, use app's shader
glClearColor(0.5, 0.5, 0.5, 1);
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
// use program, bind vertex buffer, set vertex feed, set uniforms
glUseProgram(program);
glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, textureName);
float dx = 0, dy = 0, s = 1;
mat4 t = Translate(dx, dy, 0) * Scale(s);
SetUniform(program, "textureImage", textureUnit);
SetUniform(program, "textureTransform", t);
SetUniform(program, "modelview", camera.modelview);
SetUniform(program, "persp", camera.persp);
// set color, draw shape
SetUniform(program, "color", vec3(1, 1, 1));
VertexAttribPointer(program, "point", 3, 0, (void*)0);
VertexAttribPointer(program, "normal", 3, 0, (void*)sizePts);
VertexAttribPointer(program, "uv", 2, 0, (void*)(sizePts + sizeof(normals)));
glDrawElements(GL_TRIANGLES, 3*ntriangles, GL_UNSIGNED_INT, triangles);
// optional vertex and triangle annotation
if (annotate) {
glDisable(GL_DEPTH_TEST);
SetUniform(program, "color", vec3(0, 0, 1));
for (int i = 0; i < ntriangles; i++)
glDrawElements(GL_LINE_LOOP, 3, GL_UNSIGNED_INT, &triangles[i]);
for (int i = 0; i < npoints; i++)
Number(points[i], camera.fullview, i, vec3(0,0,0), 10);
}
glFlush();
}
// scale points to lie within +/-1
void Normalize() {
vec3 mn(FLT_MAX), mx(-FLT_MAX);
for (int i = 0; i < npoints; i++) {
vec3 p = points[i];
for (int k = 0; k < 3; k++) {
if (p[k] < mn[k]) mn[k] = p[k];
if (p[k] > mx[k]) mx[k] = p[k];
}
}
vec3 center = .5f*(mn+mx), range = mx-mn;
float maxrange = std::max(range.x, std::max(range.y, range.z)), s = 2/maxrange;
for (int i = 0; i < npoints; i++)
points[i] = s*(points[i]-center);
}
bool Mid(float x) { return fabs(x-midX) < .0001f; }
// is x close to the middle of the face?
void Reflect() {
// copy left face vertices and triangles to full face
for (int i = 0; i < nLeftPoints; ++i)
points[i] = leftPoints[i];
for (int i = 0; i < nLeftTriangles; ++i) {
int *tLeft = leftTriangles[i], *t = triangles[i];
for (int k = 0; k < 3; k++)
t[k] = tLeft[k];
}
// fill second half of points, reflecting points around midX
for (int i = 0; i < nLeftPoints; ++i)
points[i+nLeftPoints] = vec3(2*midX-leftPoints[i].x, leftPoints[i].y, leftPoints[i].z);
// fill second half of triangles
for (int i = 0; i < nLeftTriangles; ++i) {
int *t = leftTriangles[i];
// test each triangle vertex for proximity to midX; if close, use original vertex, else use reflected vertex
for (int k = 0; k < 3; k++)
triangles[i+nLeftTriangles][2-k] = Mid(points[t[k]].x)? t[k] : t[k]+nLeftPoints;
// 2-k reverses order of reflected triangles to ensure still ccw
}
}
void ComputeNormals() {
// initialize to zero
for (int i = 0; i < npoints; ++i)
normals[i] = vec3(0, 0, 0);
// for each triangle: compute surface normal and add to each corresponding vertex normal
for (int i = 0; i < ntriangles; ++i) {
int* t = triangles[i];
vec3 p1(points[t[0]]), p2(points[t[1]]), p3(points[t[2]]);
vec3 n = normalize(cross(p3-p2, p2-p1));
for (int k = 0; k < 3; k++)
normals[t[k]] += n;
}
// set normals to unit length
for (int i = 0; i < npoints; ++i)
normals[i] = normalize(normals[i]);
}
// Method that copies X and Y coordinates of Face into Vertex Texture Coordinate Vector
void SetVertexTextureCoordinates() {
for (int i = 0; i < nLeftPoints; i++) {
uvs.push_back(vec2(leftPoints[i].x, leftPoints[i].y));
}
}
void Resize(GLFWwindow* w, int width, int height) {
camera.Resize(width, height);
glViewport(0, 0, width, height);
}
bool Shift(GLFWwindow *w) {
return glfwGetKey(w, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS ||
glfwGetKey(w, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS;
}
void MouseButton(GLFWwindow* w, int butn, int action, int mods) {
if (action == GLFW_PRESS) {
double x, y;
glfwGetCursorPos(w, &x, &y);
camera.MouseDown((int) x, (int) y);
}
if (action == GLFW_RELEASE)
camera.MouseUp();
}
void MouseWheel(GLFWwindow *w, double xoffset, double yoffset) {
camera.MouseWheel((int) yoffset, Shift(w));
}
void MouseMove(GLFWwindow* w, double x, double y) {
if (glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
camera.MouseDrag((int) x, (int) y, Shift(w));
}
void Key(GLFWwindow* w, int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS)
switch (key) {
case 'A':
annotate = !annotate;
break;
}
}
void InitVertexBuffer() {
// create GPU buffer, make it active
glGenBuffers(1, &vBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
// allocate memory for points and normals
glBufferData(GL_ARRAY_BUFFER, 2*sizePts + sizeof(uvs), NULL, GL_STATIC_DRAW);
// copy
glBufferSubData(GL_ARRAY_BUFFER, 0, sizePts, &points[0]);
glBufferSubData(GL_ARRAY_BUFFER, sizePts, sizePts, &normals[0]);
glBufferSubData(GL_ARRAY_BUFFER, sizePts * 2, sizeof(uvs), &uvs);
textureName = LoadTexture(filename, textureUnit);
}
int main() {
if (!glfwInit())
return 1;
GLFWwindow *w = glfwCreateWindow(winWidth, winHeight, "Face", NULL, NULL);
if (!w) {
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(w);
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
PrintGLErrors();
program = LinkProgramViaCode(&vShader, &pShader);
Reflect(); // reflect leftPoints to create entire face
Normalize(); // set points within +/- 1.
ComputeNormals(); // estimate vertex normals from surrounding triangles
SetVertexTextureCoordinates();
InitVertexBuffer(); // store in GPU
glfwSetKeyCallback(w, Key);
glfwSetScrollCallback(w, MouseWheel);
glfwSetMouseButtonCallback(w, MouseButton);
glfwSetCursorPosCallback(w, MouseMove);
glfwSetWindowSizeCallback(w, Resize);
printf("Usage:\n\tA: toggle annotation\n");
glfwSwapInterval(1);
while (!glfwWindowShouldClose(w)) {
Display(w);
glfwSwapBuffers(w);
glfwPollEvents();
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vBuffer);
glfwDestroyWindow(w);
glfwTerminate();
}
| [
"43669429+rosshoyt@users.noreply.github.com"
] | 43669429+rosshoyt@users.noreply.github.com |
d6c2278a1fa3696e598d085a4c4d8b8080ff3d52 | 244d361c0c7bf84d24eb2cfb64cd65221bc59861 | /SCI/src/include/casaChecks.h | c8fa811eb84ef29ed5395b0b482e1a1399873332 | [] | no_license | sanbee/capps | bc35582671208a18ca59a565d190a03195b2aab8 | 495a05115f96d272f87751c814e4c10ae45cf70f | refs/heads/master | 2021-07-10T04:21:20.762101 | 2019-03-01T22:44:00 | 2019-03-01T22:44:00 | 38,459,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | h | #include <casa/aips.h>
#include <casa/BasicSL/String.h>
#include <casa/Exceptions/Error.h>
#include <casa/sstream.h>
#include <strstream>
namespace casa
{
Bool checkCASAEnv(String pathVar="CASAPATH");
};
| [
"bhatnagar.sanjay@6c983b56-0e34-0410-bb18-b3d48ac8bcd4"
] | bhatnagar.sanjay@6c983b56-0e34-0410-bb18-b3d48ac8bcd4 |
84108294915bb5ccf26d814ee0d40f4c39592509 | 4bcc9806152542ab43fc2cf47c499424f200896c | /tensorflow/lite/kernels/pooling3d.cc | 3ab8701f247ec5ae20be0e0322f5ed1978154e29 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | tensorflow/tensorflow | 906276dbafcc70a941026aa5dc50425ef71ee282 | a7f3934a67900720af3d3b15389551483bee50b8 | refs/heads/master | 2023-08-25T04:24:41.611870 | 2023-08-25T04:06:24 | 2023-08-25T04:14:08 | 45,717,250 | 208,740 | 109,943 | Apache-2.0 | 2023-09-14T20:55:50 | 2015-11-07T01:19:20 | C++ | UTF-8 | C++ | false | false | 18,279 | cc | /* Copyright 2021 The TensorFlow Authors. 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 <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cstdlib>
#include <string>
#include "flatbuffers/flexbuffers.h" // from @flatbuffers
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/padding.h"
namespace tflite {
namespace ops {
namespace custom {
namespace pooling_3d {
namespace {
// TODO(b/175003241): If promoting this op to a builtin op, move this struct to
// lite/c/builtin_opdata.h.
struct Pool3DParams {
TfLiteFusedActivation activation;
TfLitePadding padding_type;
Padding3DValues padding_values;
int stride_depth;
int stride_height;
int stride_width;
int filter_depth;
int filter_height;
int filter_width;
// int8_t and int16_t activation params.
int32_t quantized_activation_min;
int32_t quantized_activation_max;
// float activation params.
float float_activation_min;
float float_activation_max;
};
template <typename T, typename ActivationT>
inline T RoundAndAverage(ActivationT sum, int count) {
// Round to the closest integer value.
return sum > 0 ? (sum + count / 2) / count : (sum - count / 2) / count;
}
template <>
inline float RoundAndAverage(float sum, int count) {
// No rounding for float type.
return sum / count;
}
// TODO(b/175003241): If promoting this op to a builtin op, move AveragePool3D
// and MaxPool3D to a dedicated header.
template <typename T, typename ActivationT>
inline void AveragePool3D(const Pool3DParams& params,
const RuntimeShape& input_shape, const T* input_data,
const RuntimeShape& output_shape, T* output_data) {
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 5);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 5);
ActivationT activation_min, activation_max;
GetActivationParams(params, &activation_min, &activation_max);
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
const int channels = MatchingDim(input_shape, 4, output_shape, 4);
const int in_spatial_dim_1 = input_shape.Dims(1);
const int in_spatial_dim_2 = input_shape.Dims(2);
const int in_spatial_dim_3 = input_shape.Dims(3);
const int out_spatial_dim_1 = output_shape.Dims(1);
const int out_spatial_dim_2 = output_shape.Dims(2);
const int out_spatial_dim_3 = output_shape.Dims(3);
const int stride_spatial_dim_1 = params.stride_depth;
const int stride_spatial_dim_2 = params.stride_height;
const int stride_spatial_dim_3 = params.stride_width;
const int filter_spatial_dim_1 = params.filter_depth;
const int filter_spatial_dim_2 = params.filter_height;
const int filter_spatial_dim_3 = params.filter_width;
const int padding_spatial_dim_1 = params.padding_values.depth;
const int padding_spatial_dim_2 = params.padding_values.height;
const int padding_spatial_dim_3 = params.padding_values.width;
for (int batch = 0; batch < batches; ++batch) {
for (int out_d1 = 0; out_d1 < out_spatial_dim_1; ++out_d1) {
const int in_d1_origin =
(out_d1 * stride_spatial_dim_1) - padding_spatial_dim_1;
const int filter_d1_start = std::max(0, -in_d1_origin);
const int filter_d1_end =
std::min(filter_spatial_dim_1, in_spatial_dim_1 - in_d1_origin);
for (int out_d2 = 0; out_d2 < out_spatial_dim_2; ++out_d2) {
const int in_d2_origin =
(out_d2 * stride_spatial_dim_2) - padding_spatial_dim_2;
const int filter_d2_start = std::max(0, -in_d2_origin);
const int filter_d2_end =
std::min(filter_spatial_dim_2, in_spatial_dim_2 - in_d2_origin);
for (int out_d3 = 0; out_d3 < out_spatial_dim_3; ++out_d3) {
const int in_d3_origin =
(out_d3 * stride_spatial_dim_3) - padding_spatial_dim_3;
const int filter_d3_start = std::max(0, -in_d3_origin);
const int filter_d3_end =
std::min(filter_spatial_dim_3, in_spatial_dim_3 - in_d3_origin);
for (int channel = 0; channel < channels; ++channel) {
ActivationT total = 0;
for (int filter_d1 = filter_d1_start; filter_d1 < filter_d1_end;
++filter_d1) {
const int in_d1 = in_d1_origin + filter_d1;
for (int filter_d2 = filter_d2_start; filter_d2 < filter_d2_end;
++filter_d2) {
const int in_d2 = in_d2_origin + filter_d2;
for (int filter_d3 = filter_d3_start; filter_d3 < filter_d3_end;
++filter_d3) {
const int in_d3 = in_d3_origin + filter_d3;
total += input_data[Offset(input_shape, batch, in_d1, in_d2,
in_d3, channel)];
}
}
}
const int filter_count = (filter_d1_end - filter_d1_start) *
(filter_d2_end - filter_d2_start) *
(filter_d3_end - filter_d3_start);
T average = pooling_3d::RoundAndAverage<T, ActivationT>(
total, filter_count);
average = std::max<T>(average, activation_min);
average = std::min<T>(average, activation_max);
output_data[Offset(output_shape, batch, out_d1, out_d2, out_d3,
channel)] = average;
}
}
}
}
}
}
template <typename T, typename ActivationT>
inline void MaxPool3D(const Pool3DParams& params,
const RuntimeShape& input_shape, const T* input_data,
const RuntimeShape& output_shape, T* output_data) {
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 5);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 5);
ActivationT activation_min, activation_max;
GetActivationParams(params, &activation_min, &activation_max);
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
const int channels = MatchingDim(input_shape, 4, output_shape, 4);
const int in_spatial_dim_1 = input_shape.Dims(1);
const int in_spatial_dim_2 = input_shape.Dims(2);
const int in_spatial_dim_3 = input_shape.Dims(3);
const int out_spatial_dim_1 = output_shape.Dims(1);
const int out_spatial_dim_2 = output_shape.Dims(2);
const int out_spatial_dim_3 = output_shape.Dims(3);
const int stride_spatial_dim_1 = params.stride_depth;
const int stride_spatial_dim_2 = params.stride_height;
const int stride_spatial_dim_3 = params.stride_width;
const int filter_spatial_dim_1 = params.filter_depth;
const int filter_spatial_dim_2 = params.filter_height;
const int filter_spatial_dim_3 = params.filter_width;
const int padding_spatial_dim_1 = params.padding_values.depth;
const int padding_spatial_dim_2 = params.padding_values.height;
const int padding_spatial_dim_3 = params.padding_values.width;
for (int batch = 0; batch < batches; ++batch) {
for (int out_d1 = 0; out_d1 < out_spatial_dim_1; ++out_d1) {
const int in_d1_origin =
(out_d1 * stride_spatial_dim_1) - padding_spatial_dim_1;
const int filter_d1_start = std::max(0, -in_d1_origin);
const int filter_d1_end =
std::min(filter_spatial_dim_1, in_spatial_dim_1 - in_d1_origin);
for (int out_d2 = 0; out_d2 < out_spatial_dim_2; ++out_d2) {
const int in_d2_origin =
(out_d2 * stride_spatial_dim_2) - padding_spatial_dim_2;
const int filter_d2_start = std::max(0, -in_d2_origin);
const int filter_d2_end =
std::min(filter_spatial_dim_2, in_spatial_dim_2 - in_d2_origin);
for (int out_d3 = 0; out_d3 < out_spatial_dim_3; ++out_d3) {
const int in_d3_origin =
(out_d3 * stride_spatial_dim_3) - padding_spatial_dim_3;
const int filter_d3_start = std::max(0, -in_d3_origin);
const int filter_d3_end =
std::min(filter_spatial_dim_3, in_spatial_dim_3 - in_d3_origin);
for (int channel = 0; channel < channels; ++channel) {
T max = std::numeric_limits<T>::lowest();
for (int filter_d1 = filter_d1_start; filter_d1 < filter_d1_end;
++filter_d1) {
const int in_d1 = in_d1_origin + filter_d1;
for (int filter_d2 = filter_d2_start; filter_d2 < filter_d2_end;
++filter_d2) {
const int in_d2 = in_d2_origin + filter_d2;
for (int filter_d3 = filter_d3_start; filter_d3 < filter_d3_end;
++filter_d3) {
const int in_d3 = in_d3_origin + filter_d3;
max =
std::max(max, input_data[Offset(input_shape, batch, in_d1,
in_d2, in_d3, channel)]);
}
}
}
max = std::max<T>(max, activation_min);
max = std::min<T>(max, activation_max);
output_data[Offset(output_shape, batch, out_d1, out_d2, out_d3,
channel)] = max;
}
}
}
}
}
}
} // namespace
enum PoolType {
kAverage,
kMax,
};
constexpr const char kPoolSizeStr[] = "ksize";
constexpr const char kStridesStr[] = "strides";
constexpr const char kPaddingStr[] = "padding";
constexpr const char kDataFormatStr[] = "data_format";
constexpr const char kPaddingSameStr[] = "SAME";
constexpr const char kPaddingValidStr[] = "VALID";
struct OpData {
Pool3DParams params;
};
void* Init(TfLiteContext* context, const char* buffer, size_t length) {
OpData* opdata = new OpData;
opdata->params.activation = kTfLiteActNone;
const flexbuffers::Map& m =
flexbuffers::GetRoot(reinterpret_cast<const uint8_t*>(buffer), length)
.AsMap();
const std::string data_format = m[kDataFormatStr].AsString().str();
TFLITE_CHECK_EQ(data_format, "NDHWC");
const std::string padding = m[kPaddingStr].AsString().str();
if (padding == kPaddingValidStr) {
opdata->params.padding_type = kTfLitePaddingValid;
} else if (padding == kPaddingSameStr) {
opdata->params.padding_type = kTfLitePaddingSame;
} else {
opdata->params.padding_type = kTfLitePaddingUnknown;
}
// The first and last element of pool_size are always 1.
const auto pool_size = m[kPoolSizeStr].AsTypedVector();
TFLITE_CHECK_EQ(pool_size.size(), 5);
TFLITE_CHECK_EQ(pool_size[0].AsInt32(), 1);
TFLITE_CHECK_EQ(pool_size[4].AsInt32(), 1);
opdata->params.filter_depth = pool_size[1].AsInt32();
opdata->params.filter_height = pool_size[2].AsInt32();
opdata->params.filter_width = pool_size[3].AsInt32();
// The first and last element of strides are always 1.
const auto strides = m[kStridesStr].AsTypedVector();
TFLITE_CHECK_EQ(strides.size(), 5);
TFLITE_CHECK_EQ(strides[0].AsInt32(), 1);
TFLITE_CHECK_EQ(strides[4].AsInt32(), 1);
opdata->params.stride_depth = strides[1].AsInt32();
opdata->params.stride_height = strides[2].AsInt32();
opdata->params.stride_width = strides[3].AsInt32();
return opdata;
}
void Free(TfLiteContext* context, void* buffer) {
delete reinterpret_cast<OpData*>(buffer);
}
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {
OpData* opdata = reinterpret_cast<OpData*>(node->user_data);
Pool3DParams& params = opdata->params;
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 5);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
TF_LITE_ENSURE_EQ(context,
input->type == kTfLiteFloat32 ||
input->type == kTfLiteInt16 ||
input->type == kTfLiteInt8,
true);
int batches = input->dims->data[0];
int depth = input->dims->data[1];
int height = input->dims->data[2];
int width = input->dims->data[3];
int channels = input->dims->data[4];
// Prevent division by 0 in optimized pooling implementations
TF_LITE_ENSURE(context, params.stride_depth > 0);
TF_LITE_ENSURE(context, params.stride_height > 0);
TF_LITE_ENSURE(context, params.stride_width > 0);
// Matching GetWindowedOutputSize in TensorFlow.
int out_width, out_height, out_depth;
params.padding_values = ComputePadding3DValues(
params.stride_height, params.stride_width, params.stride_depth, 1, 1, 1,
height, width, depth, params.filter_height, params.filter_width,
params.filter_depth, params.padding_type, &out_height, &out_width,
&out_depth);
if (input->type == kTfLiteInt8) {
TF_LITE_ENSURE_NEAR(context, input->params.scale, output->params.scale,
1.0e-6);
TFLITE_DCHECK_EQ(input->params.zero_point, output->params.zero_point);
}
TfLiteIntArray* output_size = TfLiteIntArrayCreate(5);
output_size->data[0] = batches;
output_size->data[1] = out_depth;
output_size->data[2] = out_height;
output_size->data[3] = out_width;
output_size->data[4] = channels;
return context->ResizeTensor(context, output, output_size);
}
TfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) {
OpData* opdata = reinterpret_cast<OpData*>(node->user_data);
Pool3DParams& params = opdata->params;
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
#define TF_LITE_AVERAGE_POOL_3D(type, activation_type) \
SetActivationParams(activation_min, activation_max, ¶ms); \
AveragePool3D<type, activation_type>( \
params, GetTensorShape(input), GetTensorData<type>(input), \
GetTensorShape(output), GetTensorData<type>(output))
switch (input->type) {
case kTfLiteFloat32: {
float activation_min, activation_max;
CalculateActivationRange(params.activation, &activation_min,
&activation_max);
TF_LITE_AVERAGE_POOL_3D(float, float);
} break;
case kTfLiteInt8: {
int32_t activation_min;
int32_t activation_max;
CalculateActivationRangeQuantized(context, params.activation, output,
&activation_min, &activation_max);
TF_LITE_AVERAGE_POOL_3D(int8_t, int32_t);
} break;
case kTfLiteInt16: {
int32_t activation_min;
int32_t activation_max;
CalculateActivationRangeQuantized(context, params.activation, output,
&activation_min, &activation_max);
TF_LITE_AVERAGE_POOL_3D(int16_t, int32_t);
} break;
default:
TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
#undef TF_LITE_AVERAGE_POOL_3D
return kTfLiteOk;
}
TfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) {
OpData* opdata = reinterpret_cast<OpData*>(node->user_data);
Pool3DParams& params = opdata->params;
#define TF_LITE_MAX_POOL_3D(type, activation_type) \
SetActivationParams(activation_min, activation_max, ¶ms); \
MaxPool3D<type, activation_type>( \
params, GetTensorShape(input), GetTensorData<type>(input), \
GetTensorShape(output), GetTensorData<type>(output))
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
switch (input->type) {
case kTfLiteFloat32: {
float activation_min, activation_max;
CalculateActivationRange(params.activation, &activation_min,
&activation_max);
TF_LITE_MAX_POOL_3D(float, float);
} break;
case kTfLiteInt8: {
int32_t activation_min;
int32_t activation_max;
CalculateActivationRangeQuantized(context, params.activation, output,
&activation_min, &activation_max);
TF_LITE_MAX_POOL_3D(int8_t, int32_t);
} break;
case kTfLiteInt16: {
int32_t activation_min;
int32_t activation_max;
CalculateActivationRangeQuantized(context, params.activation, output,
&activation_min, &activation_max);
TF_LITE_MAX_POOL_3D(int16_t, int32_t);
} break;
default:
TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
#undef TF_LITE_MAX_POOL_3D
return kTfLiteOk;
}
} // namespace pooling_3d
TfLiteRegistration* Register_AVG_POOL_3D() {
static TfLiteRegistration r = {pooling_3d::Init, pooling_3d::Free,
pooling_3d::GenericPrepare,
pooling_3d::AverageEval};
return &r;
}
TfLiteRegistration* Register_MAX_POOL_3D() {
static TfLiteRegistration r = {pooling_3d::Init, pooling_3d::Free,
pooling_3d::GenericPrepare,
pooling_3d::MaxEval};
return &r;
}
} // namespace custom
} // namespace ops
} // namespace tflite
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
1cb843a1f143d863f94f99f54ea23d70b06f7873 | 8fc37bc4e6dac53575c80619fe9ab893c8af7567 | /image_processing/include/image_processing/DetectPlates.h | 55cb19b3c6cd61e1f5b5c7b97f3c7ac7d31441bf | [] | no_license | tlnminh/p3at | 8acd22f1469b4f407b121794342c867489d05839 | d5ead96ebb79659bc73e0e25afa5df7b0fc11b44 | refs/heads/master | 2021-04-26T22:12:45.270856 | 2018-03-06T07:54:02 | 2018-03-06T07:54:02 | 124,040,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | h |
// DetectPlates.h
#ifndef DETECT_PLATES_H
#define DETECT_PLATES_H
/*
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include "Main.h"
#include "PossiblePlate.h"
#include "PossibleChar.h"
#include "Preprocess.h"
#include "DetectChars.h"
*/
// global constants ///////////////////////////////////////////////////////////////////////////////
const double PLATE_WIDTH_PADDING_FACTOR = 1.3;
const double PLATE_HEIGHT_PADDING_FACTOR = 1.5;
// function prototypes ////////////////////////////////////////////////////////////////////////////
std::vector<PossiblePlate> detectPlatesInScene(cv::Mat &imgOriginalScene);
std::vector<PossibleChar> findPossibleCharsInScene(cv::Mat &imgThresh);
PossiblePlate extractPlate(cv::Mat &imgOriginal, std::vector<PossibleChar> &vectorOfMatchingChars);
# endif // DETECT_PLATES_H
| [
"josephtraminh1996@gmail.com"
] | josephtraminh1996@gmail.com |
c91798099dad2d01c40e42f09425d945d08f8cde | 7fc9ca1aa8c9281160105c7f2b3a96007630add7 | /1208A.cpp | 77af0e87fbe9397294ffdb9edbe657e34a910502 | [] | no_license | PatelManav/Codeforces_Backup | 9b2318d02c42d8402c9874ae0c570d4176348857 | 9671a37b9de20f0f9d9849cd74e00c18de780498 | refs/heads/master | 2023-01-04T03:18:14.823128 | 2020-10-27T12:07:22 | 2020-10-27T12:07:22 | 300,317,389 | 2 | 1 | null | 2020-10-27T12:07:23 | 2020-10-01T14:54:31 | C++ | UTF-8 | C++ | false | false | 966 | cpp | /*May The Force Be With Me*/
#include <bits/stdc++.h>
#include <stdio.h>
#include <ctype.h>
#pragma GCC optimize ("Ofast")
#define ll long long
#define MOD 1000000007
#define endl "\n"
#define vll vector<long long>
#define pll pair<long long, long long>
#define all(c) c.begin(),c.end()
#define pb push_back
#define f first
#define s second
#define inf INT_MAX
#define size_1d 10000000
#define size_2d 1000
//Snippets: graph, segtree, delta, sieve, fastexp
using namespace std;
ll a, b, n;
void Input() {
cin >> a >> b >> n;
n++;
}
void Solve() {
ll x = a ^ b;
if (n % 3 == 1)cout << a << endl;
else if (n % 3 == 2)cout << b << endl;
else cout << x << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ll T = 1;
cin >> T;
//ll t = 1;
while (T--) {
Input();
//cout << "Case " << t << ": ";
Solve();
//t++;
}
return 0;
} | [
"helewrer3@gmail.com"
] | helewrer3@gmail.com |
30223caf5ddbca7f76bd6ea234d4c792b2990f34 | dce3cd14bce63b4d2f8a5fb71be2b1bfeae45c86 | /OsisSwitcher/osis/element/criteria.h | 527d984fe6801fd68bd54722f7c1cc46246afad2 | [] | no_license | omishukov/dsu_osis | 7016239031c54246c21e847befd58e91087415be | fea6315699ce8d276f2edcae337b453a60e82707 | refs/heads/master | 2020-04-06T05:53:18.162417 | 2017-01-31T20:38:55 | 2017-01-31T20:38:55 | 43,024,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | h | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Contributor(s):
* Oleksander Mishukov <dsu@mishukov.dk> */
#ifndef OSISCRITERIA_H
#define OSISCRITERIA_H
#include <QObject>
#include <QDomDocument>
#include <QMultiMap>
#include "osisdata.h"
/*
* <Criteria Index="1" Cri_Name="Skating Skills" Cri_Abbrev="SS" Cri_Factor="0.80"/>
*/
class OsisCriteria : public QObject, public OsisData
{
Q_OBJECT
public:
enum OsisElementAttributes
{
Index, // Index, used as identifier
Cri_Name, // 40
Cri_Abbrev, // 10
Cri_Factor, // Format “9.99”
Points // Format “9.99”
};
Q_ENUM(OsisElementAttributes)
public:
explicit OsisCriteria(QDomElement& osisElement, QString& elementName, QObject *parent = 0);
int Id;
};
typedef QMultiMap <int, OsisCriteria*> OsisCriteriaMap;
#endif // OSISCRITERIA_H
| [
"github@mishukov.dk"
] | github@mishukov.dk |
98d554944b8c2215d96a4c42d556a75fa1ff5ab4 | ae78d3776d12aff43b65d94e51f584d9a35bfc3f | /Notes/compilerGNUMake.cpp | 4e0d1bdbdf828411cf0bc4b0d34ca98fba02e96b | [] | no_license | DowerChest/cb_misc | 9d40264463bbbefd506127a936df1ad43424eb72 | af99e7068ede7463ea0420a6618130fc74117a3e | refs/heads/master | 2020-12-29T00:55:10.631202 | 2016-01-16T18:08:41 | 2016-01-16T18:08:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,158 | cpp | /*
* This file is part of the Code::Blocks IDE and licensed under the GNU General Public License, version 3
* http://www.gnu.org/licenses/gpl-3.0.html
*
* $Revision$
* $Id$
* $HeadURL$
*/
#include <sdk.h>
#ifndef CB_PRECOMP
// wxWidgets non GUI headers in sdk_common.h
#include <wx/dir.h>
#include <wx/filename.h>
#include <wx/intl.h>
#include <wx/regex.h>
// wxWidgets GUI headers in sdk_common.h
#include <wx/msgdlg.h>
// CB SDK Headers in sdk_common.h
#include <manager.h>
#include <configmanager.h>
#include <logmanager.h>
#include <macrosmanager.h>
#endif // #ifndef CB_PRECOMP
#include <wx/config.h>
#include <wx/fileconf.h>
#include <wx/filefn.h>
#ifdef __WXMSW__
#include <wx/msw/registry.h>
#endif
#include "CompilerGNUMake.h"
CompilerGNUMake::CompilerGNUMake(const wxString& name, const wxString& ID)
: Compiler(name, ID)
{
m_Weight = 99;
Reset();
}
CompilerGNUMake::~CompilerGNUMake()
{
//dtor
}
Compiler * CompilerGNUMake::CreateCopy()
{
return (new CompilerGNUMake(*this));
}
AutoDetectResult CompilerGNUMake::AutoDetectInstallationDir()
{
// try to find MinGW in environment variable PATH first
wxString pathValues;
wxGetEnv(_T("PATH"), &pathValues);
if (!pathValues.IsEmpty())
{
wxString sep = platform::windows ? _T(";") : _T(":");
wxChar pathSep = platform::windows ? _T('\\') : _T('/');
wxArrayString pathArray = GetArrayFromString(pathValues, sep);
for (size_t i = 0; i < pathArray.GetCount(); ++i)
{
if (wxFileExists(pathArray[i] + pathSep + m_Programs.MAKE))
{
if (pathArray[i].AfterLast(pathSep).IsSameAs(_T("bin")))
{
m_MasterPath = pathArray[i].BeforeLast(pathSep);
return adrDetected;
}
}
}
}
wxString sep = wxFileName::GetPathSeparator();
if (platform::windows)
{
// look first if MinGW was installed with Code::Blocks (new in beta6)
m_MasterPath = ConfigManager::GetExecutableFolder();
if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.MAKE))
// if that didn't do it, look under C::B\MinGW, too (new in 08.02)
m_MasterPath += sep + _T("MinGW");
if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.MAKE))
{
// no... search for MinGW installation dir
wxString windir = wxGetOSDirectory();
wxFileConfig ini(_T(""), _T(""), windir + _T("/MinGW.ini"), _T(""), wxCONFIG_USE_LOCAL_FILE | wxCONFIG_USE_NO_ESCAPE_CHARACTERS);
m_MasterPath = ini.Read(_T("/InstallSettings/InstallPath"), _T("C:\\MinGW"));
if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.MAKE))
{
#ifdef __WXMSW__ // for wxRegKey
// not found...
// look for dev-cpp installation
wxRegKey key; // defaults to HKCR
key.SetName(_T("HKEY_LOCAL_MACHINE\\Software\\Dev-C++"));
if (key.Exists() && key.Open(wxRegKey::Read))
{
// found; read it
key.QueryValue(_T("Install_Dir"), m_MasterPath);
}
else
{
// installed by inno-setup
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Minimalist GNU for Windows 4.1_is1
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\TDM-GCC
wxString name;
long index;
key.SetName(_T("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"));
for (int i = 0; i < 2; ++i)
{
bool ok = key.GetFirstKey(name, index);
while (ok && !name.StartsWith(wxT("Minimalist GNU for Windows")) && name != wxT("TDM-GCC"))
{
ok = key.GetNextKey(name, index);
}
if (ok)
{
name = key.GetName() + wxT("\\") + name;
key.SetName(name);
if (key.Exists() && key.Open(wxRegKey::Read))
{
key.QueryValue(wxT("InstallLocation"), m_MasterPath);
// determine configuration, eg: "x86_64-w64-mingw32-gcc.exe"
wxDir binFolder(m_MasterPath + sep + wxT("bin"));
if (binFolder.IsOpened() && binFolder.GetFirst(&name, wxT("*make*.exe"), wxDIR_FILES))
{
m_Programs.MAKE = name;
while (binFolder.GetNext(&name))
{
if (name.Length() < m_Programs.MAKE.Length())
m_Programs.MAKE = name; // avoid "x86_64-w64-mingw32-gcc-4.8.1.exe"
}
m_Programs.C = m_Programs.MAKE;
break;
}
}
}
// on 64 bit Windows
key.SetName(wxT("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"));
}
}
#endif
}
// check for PortableApps.com installation
if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.MAKE))
{
wxString drive = wxFileName(ConfigManager::GetExecutableFolder()).GetVolume() + wxT(":\\");
if (wxFileExists(drive + wxT("PortableApps\\CommonFiles\\MinGW\\bin\\") + m_Programs.MAKE))
m_MasterPath = drive + wxT("PortableApps\\CommonFiles\\MinGW");
else if (wxFileExists(drive + wxT("CommonFiles\\MinGW\\bin\\") + m_Programs.MAKE))
m_MasterPath = drive + wxT("CommonFiles\\MinGW");
else if (wxFileExists(drive + wxT("MinGW\\bin\\") + m_Programs.MAKE))
m_MasterPath = drive + wxT("MinGW");
}
}
}
else
m_MasterPath = _T("/usr");
AutoDetectResult ret = wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.MAKE) ? adrDetected : adrGuessed;
// don't add lib/include dirs. GCC knows where its files are located
SetVersionString();
return ret;
}
void CompilerGNUMake::SetVersionString()
{
// Manager::Get()->GetLogManager()->DebugLog(_T("Compiler detection for compiler ID: '") + GetID() + _T("' (parent ID= '") + GetParentID() + _T("')"));
wxArrayString output, errors;
wxString sep = wxFileName::GetPathSeparator();
wxString master_path = m_MasterPath;
wxString make_exe = m_Programs.MAKE;
/* We should read the master path from the configuration manager as
* the m_MasterPath is empty if AutoDetectInstallationDir() is not
* called
*/
ConfigManager* cmgr = Manager::Get()->GetConfigManager(_T("compiler"));
if (cmgr)
{
wxString settings_path;
wxString make_path;
/* Differ between user-defined compilers (copies of base compilers) */
if (GetParentID().IsEmpty())
{
settings_path = _T("/sets/") + GetID() + _T("/master_path");
make_path = _T("/sets/") + GetID() + _T("/make");
}
else
{
settings_path = _T("/user_sets/") + GetID() + _T("/master_path");
make_path = _T("/user_sets/") + GetID() + _T("/make");
}
cmgr->Read(settings_path, &master_path);
cmgr->Read(make_path, &make_exe);
}
if (master_path.IsEmpty())
{
/* Notice: In general this is bad luck as e.g. all copies of a
* compiler have a different path, most likely.
* Thus the following might even return a wrong command!
*/
if (platform::windows)
master_path = _T("C:\\MinGW");
else
master_path = _T("/usr");
}
wxString make_command = master_path + sep + _T("bin") + sep + make_exe;
Manager::Get()->GetMacrosManager()->ReplaceMacros(make_command);
if (!wxFileExists(make_command))
{
// Manager::Get()->GetLogManager()->DebugLog(_T("Make version detection: Make not found: ") + make_command);
return;
}
Manager::Get()->GetLogManager()->DebugLog(_T("Make version detection: Issuing command: ") + make_command);
int flags = wxEXEC_SYNC;
#if wxCHECK_VERSION(2, 9, 0)
// Stop event-loop while wxExecute runs, to avoid a deadlock on startup,
// that occurs from time to time on wx2.9
flags |= wxEXEC_NOEVENTS;
#else
flags |= wxEXEC_NODISABLE;
#endif
long result = wxExecute(make_command + _T(" --version"), output, errors, flags );
if(result != 0)
{
// Manager::Get()->GetLogManager()->DebugLog(_T("Make version detection: Error executing command."));
}
else
{
if (output.GetCount() > 0)
{
// Manager::Get()->GetLogManager()->DebugLog(_T("Extracting compiler version from: ") + output[0]);
wxRegEx reg_exp;
if (reg_exp.Compile(_T("[0-9][.][0-9][.][0-9]")) && reg_exp.Matches(output[0]))
{
m_VersionString = reg_exp.GetMatch(output[0]);
// Manager::Get()->GetLogManager()->DebugLog(_T("Make version via RegExp: ") + m_VersionString);
}
else
{
m_VersionString = output[0].Mid(10);
m_VersionString = m_VersionString.Left(5);
m_VersionString.Trim(false);
// Manager::Get()->GetLogManager()->DebugLog(_T("Make version: ") + m_VersionString);
}
}
}
}
| [
"stahta01@users.sourceforge.net"
] | stahta01@users.sourceforge.net |
e8607fbe9dfb7728e5e329a09bd55003e0ce3216 | 5086891f126912a535d62f9d1c4375de3ca05d1b | /CodeFiles/Maths and Number Theory/Count_Substrings_CodeChef.cpp | 29fdfb73aa49a77e5f425d4192a1d61f914f568d | [] | no_license | ConnectNitish/CompetitiveProgramming | 8ddc0bb95471f861e0deb25ed487242bb4e6c4eb | 9f1a40bb6ab03b2432660614617415169c098c76 | refs/heads/master | 2021-07-09T17:33:32.327610 | 2020-10-12T05:07:13 | 2020-10-12T05:07:13 | 206,482,557 | 0 | 6 | null | 2020-10-12T05:07:15 | 2019-09-05T05:34:34 | C++ | UTF-8 | C++ | false | false | 325 | cpp | #include<iostream>
using namespace std;
// https://www.codechef.com/problems/CSUB
int main()
{
int t;
cin >> t;
while(t--)
{
int l;
string s;
cin >> l;
cin >> s;
int count=0;
for(int k=0;k<l;k++)
if(s[k]=='1')
count++;
cout << ((((long long)count) * ((long long)count + 1)) >> 1) << endl;
}
} | [
"nitish068@gmail.com"
] | nitish068@gmail.com |
f8ecdd9311ab01203c91887400bcd9b5ddf15d4a | 9925d358982c91315717651ae537665e162ad147 | /projects/Project_Dragon/src/CPP/VertexTypes.cpp | a5616ba8eda4af6c07d9d57deb541e003cac37af | [] | no_license | christiannazar/PROJECT_DRAGON | 44df86b5294c687dacc12305fbb26ad4da552bb5 | 4bef1dd453e7d54322e76e0585a9d84d229fa3f4 | refs/heads/master | 2023-01-06T01:27:30.914149 | 2020-10-28T02:05:03 | 2020-10-28T02:05:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | cpp | #include "Header/VertexTypes.h"
#pragma warning( push )
VertexPosCol* VPC = nullptr;
VertexPosNormCol* VPNC = nullptr;
VertexPosNormTex* VPNT = nullptr;
VertexPosNormTexCol* VPNTC = nullptr;
const std::vector<BufferAttribute> VertexPosCol::V_DECL = {
BufferAttribute(0, 3, GL_FLOAT, false, sizeof(VertexPosCol), (size_t)&VPC->Position, AttribUsage::Position),
BufferAttribute(1, 4, GL_FLOAT, false, sizeof(VertexPosCol), (size_t)&VPC->Color, AttribUsage::Color),
};
const std::vector<BufferAttribute> VertexPosNormCol::V_DECL = {
BufferAttribute(0, 3, GL_FLOAT, false, sizeof(VertexPosNormCol), (size_t)&VPNC->Position, AttribUsage::Position),
BufferAttribute(1, 4, GL_FLOAT, false, sizeof(VertexPosNormCol), (size_t)&VPNC->Color, AttribUsage::Color),
BufferAttribute(2, 3, GL_FLOAT, false, sizeof(VertexPosNormCol), (size_t)&VPNC->Normal, AttribUsage::Normal),
};
const std::vector<BufferAttribute> VertexPosNormTex::V_DECL = {
BufferAttribute(0, 3, GL_FLOAT, false, sizeof(VertexPosNormTex), (size_t)&VPNT->Position, AttribUsage::Position),
BufferAttribute(2, 3, GL_FLOAT, false, sizeof(VertexPosNormTex), (size_t)&VPNT->Normal, AttribUsage::Normal),
BufferAttribute(3, 2, GL_FLOAT, false, sizeof(VertexPosNormTex), (size_t)&VPNT->UV, AttribUsage::Texture),
};
const std::vector<BufferAttribute> VertexPosNormTexCol::V_DECL = {
BufferAttribute(0, 3, GL_FLOAT, false, sizeof(VertexPosNormTexCol), (size_t)&VPNTC->Position, AttribUsage::Position),
BufferAttribute(1, 4, GL_FLOAT, false, sizeof(VertexPosNormTexCol), (size_t)&VPNTC->Color, AttribUsage::Color),
BufferAttribute(2, 3, GL_FLOAT, false, sizeof(VertexPosNormTexCol), (size_t)&VPNTC->Normal, AttribUsage::Normal),
BufferAttribute(3, 2, GL_FLOAT, false, sizeof(VertexPosNormTexCol), (size_t)&VPNTC->UV, AttribUsage::Texture),
};
#pragma warning(pop) | [
"noahglassford@gmail.com"
] | noahglassford@gmail.com |
0c33c43a3cf18ab7956f3724649705d6ce1fc28c | 70fd51580a32c4d7dbc376d4ff8ae1a4fd156fa1 | /Subject.cpp | 8459210a02278356482d0804bb6ed646ea727f29 | [] | no_license | kirillkuks/EngineWrapper | 4d7d821c27fdced2f376690d4e3f81fdd553586f | c74b0d0b9701221ff5acce63ef37c189935fc575 | refs/heads/main | 2023-02-01T17:00:31.222049 | 2020-12-16T13:13:21 | 2020-12-16T13:13:21 | 321,986,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | #include "Subject.h"
Subject::Subject() {}
int Subject::f3(int first, int second) {
return first - second;
}
int Subject::f1(int a1, int a2, int a3, int a4, int a5) {
return (a1 + a2 - a3 + a4) * a5;
} | [
"60854701+kirillkuks@users.noreply.github.com"
] | 60854701+kirillkuks@users.noreply.github.com |
5040e7a66532b4da84a281d527c5a1ab3204aad0 | 1e2858489cedb933bc532ddc63466bbfc3b3e865 | /watchdog.ino | 5a5bf74daf832a83aa46f2aed65f41fda0b6399c | [] | no_license | chinaza/watchdog-hardware | 475aec52c0912382147220944e3b2130e2f6b12b | dcbb757489496ab6a0bac79e337ec78a1d995f7d | refs/heads/master | 2021-05-16T03:51:18.686750 | 2017-10-03T12:15:35 | 2017-10-03T12:15:35 | 105,647,001 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,051 | ino | //Current Sensor power analog input
#define powerPin A0
//GSM Modem definition
#define TINY_GSM_MODEM_SIM800
//GSM LIBRARY
#include <TinyGsmClient.h>
//Software Serial Library
#include <SoftwareSerial.h>
bool thereIsPower();
void alertServer(bool);
bool serverAlertedForPower = false;
bool serverAlertedForNoPower = false;
// Your GPRS credentials
const char apn[] = "internet.ng.airtel.com";
const char user[] = "internet";
const char pass[] = "internet";
//Web server details
const char server[] = "watchdog.theonlyzhap.xyz";
const char resource[] = "/api/powerstate";
const int port = 80;
//GPRS Serial port
SoftwareSerial gprsSerial(10, 11);
//GSM Initialization
TinyGsm modem(gprsSerial);
TinyGsmClient client(modem);
void setup() {
// put your setup code here, to run once:
//Set power pin as input pin
pinMode(powerPin, INPUT);
//Initialize serials
Serial.begin(9600);
delay(10);
gprsSerial.begin(9600);
delay(1000);
//Prep the GPRS Module
modem.restart();
}
void loop() {
// put your main code here, to run repeatedly:
if (thereIsPower) {
if (!serverAlertedForPower) alertServer(true);
serverAlertedForPower = true;
serverAlertedForNoPower = false;
} else {
if (!serverAlertedForNoPower) alertServer(false);
serverAlertedForNoPower = true;
serverAlertedForPower = false;
}
}
bool thereIsPower() {
int rawValue = analogRead(powerPin);
double measuredVoltage = (rawValue / 1024.0) * 5000;
double referenceVoltage = 0.0; //Value should be changed after calibration with ac indicator light
if (measuredVoltage > referenceVoltage) return true;
return false;
}
void alertServer(bool powerState) {
Serial.println("Power state: " + String(powerState));
Serial.print(F("Waiting for network..."));
if (!modem.waitForNetwork()) {
Serial.println(" fail");
delay(5000);
return;
}
Serial.println(" OK");
Serial.print(F("Connecting to "));
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass)) {
Serial.println(" fail");
delay(5000);
return;
}
Serial.println(" OK");
Serial.print(F("Connecting to "));
Serial.print(server);
if (!client.connect(server, port)) {
Serial.println(" fail");
delay(5000);
return;
}
Serial.println(" OK");
// Make a HTTP POST request:
client.print(String("POST ") + resource + " HTTP/1.1\r\n");
client.print(String("Host: ") + server + "\r\n");
client.print("Content-Type: application/x-www-form-urlencoded\r\n");
client.print("Cache-Control: no-cache\r\n");
client.print("dogID=test&state=" + String(powerState) + "\r\n");
client.print("Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.connected() && millis() - timeout < 10000L) {
// Print available data
while (client.available()) {
char c = client.read();
Serial.print(c);
timeout = millis();
}
}
Serial.println();
client.stop();
Serial.println("Server disconnected");
modem.gprsDisconnect();
Serial.println("GPRS disconnected");
}
| [
"chinaza@zhaptek.com"
] | chinaza@zhaptek.com |
cb69d7c86b6fe50c8da8f171e5c05e4aabfeb615 | ccdcabdb0685f36d248a6e4f4a90ceaf00bc44f9 | /main.cpp | c68277d1d82e1b3fc3a84ab622c051ebe11728c2 | [] | no_license | JoedHernandez1995/Proyecto_Orga_2015 | d551ba6abbaebd14661771f353a20032ac67cbd2 | cb03dbd4fcfe11cb3ab80004ca92fbe69b04b3d6 | refs/heads/master | 2016-09-06T15:24:14.608092 | 2015-03-26T17:47:54 | 2015-03-26T17:47:54 | 30,837,668 | 0 | 0 | null | 2015-03-26T05:00:17 | 2015-02-15T18:49:20 | C++ | UTF-8 | C++ | false | false | 30,765 | cpp | #include <iostream>
#include <stack>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <map>
#include "primaryKey.h"
#include "nodo.h"
#include "arbolb.h"
using namespace std;
struct Campo{
string nombre;
int tipo;
int longitud;
bool isKey;
};
struct Informacion{
string texto;
int value;
};
struct Registro{
vector<Campo> estructura;
vector<Informacion> informacion;
};
int menu();
int menuCruzar();
void cargarIndices(string);
void imprimir(string);
void text2bin(string);
int inicioRegistros(string);
vector<int> cargarAvailList(string);
vector<Campo> cargarEstructura(string);
map<string,PrimaryKey*> indice;
ArbolB btree(16);
int main(int argc, char*argv[]){
int cantCampos;
string filename;
vector<Campo> campos;
vector<Informacion> info;
vector<Registro> registros;
bool continuar = true;
int useIndex;
int indexType;
int numPrimaryKeys = 0;
while(continuar){
int opcion = menu();
if(opcion == 1){
int usaIndice;
int tipoIndice;
cout << "Ingrese el nombre del archivo a abrir: ";
cin >> filename;
ifstream fileExists(filename,ios::binary);
if(fileExists){
fileExists.seekg(sizeof(int),ios::beg);
fileExists.read(reinterpret_cast<char*>(&usaIndice),sizeof(usaIndice));
fileExists.read(reinterpret_cast<char*>(&tipoIndice),sizeof(tipoIndice));
if(usaIndice == 1){
if(tipoIndice == 1){
cargarIndices(filename);
}else if(tipoIndice == 0){
cargarIndices(filename);
btree.recorrer();
}
}
cout << "Archivo Abierto!"<<endl;
fileExists.close();
}else{
cout << "El archivo no existe, se creara un archivo nuevo!"<<endl;
cout << "Desea utilizar indices en este archivo? (1-Si/0-No): ";
cin >> useIndex;
if(useIndex == 1){
cout << "Que tipo de indice le gustaria utilizar? (1-Lineal/0-Arbol B): ";
cin >> indexType;
}
cout << "Cuantos campos desea crear: ";
cin >> cantCampos;
for(int i = 0; i < cantCampos; i++){
Campo camp;
cout << "Ingrese nombre del campo: ";
cin >> camp.nombre;
if(numPrimaryKeys==0){
int llave;
cout << "Es llave primaria(1-Si/0-No): ";
cin >> llave;
if(llave==0){
camp.isKey = false;
}else if(llave==1){
camp.isKey = true;
}
if(!camp.isKey){
cout << "Ingrese tipo del campo(1-Int/2-Texto): ";
cin >> camp.tipo;
if(camp.tipo == 2){
cout << "Ingrese longitud del texto: ";
cin >> camp.longitud;
} else {
camp.longitud = sizeof(int);
}
} else {
camp.tipo = 2;
cout << "Ingrese longitud de la llave: ";
cin >> camp.longitud;
numPrimaryKeys++;
}
}else{
cout << "Ingrese tipo del campo(1-Int/2-Texto): ";
cin >> camp.tipo;
if(camp.tipo == 2){
cout << "Ingrese longitud del texto: ";
cin >> camp.longitud;
} else {
camp.longitud = sizeof(int);
}
camp.isKey = false;
}
campos.push_back(camp);
cout << "Campo Creado!"<<endl;
}
/* Crea el encabezado del archivo */
int position = 0; //primera posicion disponible en el availlist
ofstream file(filename,ios::binary|ios::app);
file.write(reinterpret_cast<const char*>(&cantCampos),sizeof(cantCampos)); //Guarda el numero de campos en el encabezado
file.write(reinterpret_cast<const char*>(&useIndex),sizeof(useIndex)); //Guarda si el archivo utiliza indices o no
file.write(reinterpret_cast<const char*>(&indexType),sizeof(indexType)); //Guarda que tipo de indice utiliza el archivo
file.write(reinterpret_cast<const char*>(&position),sizeof(position));//guarda la primera posicion disponible para agregar en el availlist
const char* pointer = reinterpret_cast<const char*>(&campos[0]);//Guarda la lista de campos con su respectiva informacion
size_t bytes = campos.size() * sizeof(campos[0]);
file.write(pointer, bytes);
file.close();
fileExists.close();
if(useIndex == 1){
if(indexType==1){
ofstream indexFile("index_"+filename,ios::binary|ios::app);
indexFile.close();
}
}
campos.clear();
}
numPrimaryKeys = 0;
}
if(opcion == 2){
ifstream archivo(filename,ios::binary);
if(archivo){
ofstream file2(filename,ios::binary|ios_base::app);
int useIndex,indexType;
archivo.seekg(sizeof(int),ios::beg);
archivo.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
archivo.read(reinterpret_cast<char*>(&indexType),sizeof(indexType));
vector<int> availList = cargarAvailList(filename);
campos = cargarEstructura(filename);
cout << campos.size() << endl << availList.size()<<endl;
/*Revisar el availlist */
if(availList.at(0) == 0){ //Si no hay posiciones que agregue al final
info.clear();
string text;
int data;
string key;
int start;
for(int i = 0; i < campos.size(); i++){
Informacion temp;
if(campos.at(i).tipo == 1){
cout << campos.at(i).nombre << ": ";
cin >> temp.value;
temp.texto = "";
info.push_back(temp);
}
if(campos.at(i).tipo == 2){
cout << campos.at(i).nombre << ": ";
cin >> temp.texto;
if(campos.at(i).isKey){
key = temp.texto;
}
temp.value = 0;
info.push_back(temp);
}
}
/*Escribe al final del archivo*/
const char* puntero = reinterpret_cast<const char*>(&info[0]);
size_t cantBytes = info.size() * sizeof(info[0]);
file2.write(puntero,cantBytes);
if(useIndex==1){
if(indexType==1){
start = ((int) file2.tellp()) - (campos.size()*sizeof(Informacion));//probablemente sumarle 1
indice.insert(pair<string,PrimaryKey*>(key,new PrimaryKey(key,start)));
string indexFile = "index_"+filename;
ofstream index(indexFile,ios::binary|ios::trunc);
index.close();
ofstream indice_file(indexFile,ios::binary|ios::app);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
string key = it->first;
int offset = it->second->getOffset();
indice_file.write(reinterpret_cast<char*>(&key),sizeof(key));
indice_file.write(reinterpret_cast<char*>(&offset),sizeof(offset));
}
}else if(indexType == 0){
btree.insertar(new PrimaryKey(key,start));
}
}
cout << "Registro Agregado"<<endl;
info.clear();
file2.close();
archivo.close();
}else{ // Si hay posiciones disponibles,escribe en esa posicion especifica
info.clear();
string text;
int data;
string key;
int start;
for(int i = 0; i < campos.size(); i++){
Informacion temp;
if(campos.at(i).tipo == 1){
cout << campos.at(i).nombre << ": ";
cin >> temp.value;
temp.texto = "";
info.push_back(temp);
}
if(campos.at(i).tipo == 2){
cout << campos.at(i).nombre << ": ";
cin >> temp.texto;
if(campos.at(i).isKey){
key = temp.texto;
}
temp.value = 0;
info.push_back(temp);
}
}
int rrn = availList.at(0);
int next = availList.at(1);
int offset = inicioRegistros(filename);
offset += (rrn-1)*campos.size()*sizeof(Informacion);
ofstream file2(filename,ios::binary| ios::in|ios::out);
file2.seekp(sizeof(int)+sizeof(int)+sizeof(int),ios::beg);
file2.write(reinterpret_cast<char*>(&next),sizeof(next));
file2.seekp(offset,ios::beg);
const char* puntero = reinterpret_cast<const char*>(&info[0]);
size_t cantBytes = info.size() * sizeof(info[0]);
file2.write(puntero,cantBytes);
start = ((int)file2.tellp())-(campos.size()*sizeof(Informacion)); //posiblemente sumarle 1
indice.insert(pair<string,PrimaryKey*>(key,new PrimaryKey(key,start)));
file2.close();
archivo.close();
if(useIndex==1){
if(indexType==1){
start = ((int) file2.tellp()) - (campos.size()*sizeof(Informacion));//probablemente sumarle 1
indice.insert(pair<string,PrimaryKey*>(key,new PrimaryKey(key,start)));
string indexFile = "index_"+filename;
ofstream index(indexFile,ios::binary|ios::trunc);
index.close();
ofstream indice_file(indexFile,ios::binary|ios::app);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
string key = it->first;
int offset = it->second->getOffset();
indice_file.write(reinterpret_cast<char*>(&key),sizeof(key));
indice_file.write(reinterpret_cast<char*>(&offset),sizeof(offset));
}
}else if(indexType == 0){
btree.insertar(new PrimaryKey(key,start));
}
}
cout << "Registro Agregado!!"<<endl<<endl;
availList.erase(availList.begin()); //borra el primer elemento, ya se uso esa posicion;
}
}else{
cout << "No ha abierto un archivo valido" << endl;
}
}
if(opcion == 3){
ifstream fileIsOpen(filename,ios::binary);
int useIndex,indexType;
if(fileIsOpen){
fileIsOpen.seekg(sizeof(int),ios::beg);
fileIsOpen.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
fileIsOpen.read(reinterpret_cast<char*>(&indexType),sizeof(useIndex));
if(useIndex==1){
if(indexType==1){
imprimir(filename);
cout << "Indice Lineal"<<endl;
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++)
cout << it->first << " => " << it->second->getOffset() << '\n';
}else (indexType==0){
imprimir(filename);
cout << "Arbol B Recorrido "<<endl;
btree.recorrer();
}
}else if(useIndex==0){
imprimir(filename);
}
}else{
cout << "No ha abierto un archivo valido" << endl;
}
}
if(opcion == 4){
ifstream file(filename,ios::binary);
if(file){
int useIndex,indexType;
file.seekg(sizeof(int),ios::beg);
file.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
file.read(reinterpret_cast<char*>(&indexType),sizeof(indexType));
if(useIndex == 0){
cargarIndices(filename);
}
campos = cargarEstructura(filename);
string llave;
cout << "Ingrese la llave primaria del registro que quiere modificar: ";
cin >> llave;
PrimaryKey* key = indice.find(llave)->second;
int offset = key->getOffset();
campos = cargarEstructura(filename);
int control = 0;
string llave1,llave2;
ifstream in(filename,ios::binary);
in.seekg(offset,ios::beg);
Informacion data;
vector<Informacion> info;
while(true){
if(control < campos.size()){
in.read(reinterpret_cast<char*>(&data),sizeof(data));
cout << campos.at(control).nombre<<": ";
if(campos.at(control).isKey){
llave1 = data.texto;
}
if(campos.at(control).tipo==1){
cin >> data.value;
}else{
cin >> data.texto;
if(campos.at(control).isKey){
llave2 = data.texto;
}
}
info.push_back(data);
} else if(control == campos.size()){
break;
}
control++;
}
indice.erase(llave1);
indice.insert(pair<string,PrimaryKey*>(llave2, new PrimaryKey(llave2,offset)));
ofstream out(filename,ios::binary|ios::in|ios::out);
out.seekp(offset,ios::beg);
out.write(reinterpret_cast<char*>(&info[0]),info.size()*sizeof(info[0]));
out.close();
in.close();
if(useIndex==1){
if(indexType==1){
string indexFile = "index_"+filename;
ofstream index(indexFile,ios::binary|ios::trunc);
index.close();
ofstream indice_file(indexFile,ios::binary|ios::app);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
string key = it->first;
int offset = it->second->getOffset();
indice_file.write(reinterpret_cast<char*>(&key),sizeof(key));
indice_file.write(reinterpret_cast<char*>(&offset),sizeof(offset));
}
}else if(indexType == 0){
ArbolB arbol(16);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
arbol.insertar(it->second);
}
btree = arbol;
}
}
cout << "Registro Modificado"<<endl;
}else{
cout << "No ha abierto un archivo valido"<<endl;
}
file.close();
}
if(opcion == 5){
ifstream file(filename,ios::binary);
if(file){
int useIndex,indexType;
file.seekg(sizeof(int),ios::beg);
file.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
file.read(reinterpret_cast<char*>(&indexType),sizeof(indexType));
campos = cargarEstructura(filename);
if(useIndex == 0){
cargarIndices(filename);
}
string llave;
cout << "Ingrese la llave primaria del registro que quiere borrar: ";
cin >> llave;
PrimaryKey* key = indice.find(llave)->second;
int original_offset;
int offset = key->getOffset();
char indicador = '&';
original_offset = offset;
int begin = sizeof(int) + sizeof(int) + sizeof (int) + sizeof(int) + (campos.size()*sizeof(Campo));
ofstream out(filename, ios::binary|ios::in|ios::out);
out.seekp(offset,ios::beg);
out.write(reinterpret_cast<char*>(&indicador),sizeof(indicador));
int first_avail;
ifstream in(filename,ios::binary|ios::in);
in.seekg(sizeof(int)+sizeof(int)+sizeof(int),ios::beg);
in.read(reinterpret_cast<char*>(&first_avail),sizeof(first_avail));
offset = offset-begin;
int rrn = offset/(campos.size()*sizeof(Informacion)) + 1;
cout << rrn<<endl;
out.write(reinterpret_cast<char*>(&first_avail),sizeof(first_avail));
out.seekp(sizeof(int)+sizeof(int)+sizeof(int),ios::beg);
out.write(reinterpret_cast<char*>(&rrn),sizeof(rrn));
out.close();
cout << "Registro borrado"<<endl;
indice.erase(llave);
if(useIndex==1){
if(indexType==1){
string indexFile = "index_"+filename;
ofstream index(indexFile,ios::binary|ios::trunc);
index.close();
ofstream indice_file(indexFile,ios::binary|ios::app);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
string key = it->first;
int offset = it->second->getOffset();
indice_file.write(reinterpret_cast<char*>(&key),sizeof(key));
indice_file.write(reinterpret_cast<char*>(&offset),sizeof(offset));
}
}else if(indexType == 0){
ArbolB arbol(16);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
arbol.insertar(it->second);
}
btree = arbol;
//btree.borrar(new PrimaryKey(key,original_offset));
}
}
}else{
cout << "No ha abierto un archivo valido"<<endl;
}
file.close();
}
if(opcion == 6){
ifstream file(filename,ios::binary);
if(file){
string filename2 = "nuevo_"+filename;
ofstream file2(filename2,ios::binary|ios_base::app);
campos = cargarEstructura(filename);
Informacion data;
int numero_Campos = campos.size();
int useIndex,indexType,avail;
file.read(reinterpret_cast<char*>(&numero_Campos),sizeof(numero_Campos));
file.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
file.read(reinterpret_cast<char*>(&indexType),sizeof(indexType));
file.read(reinterpret_cast<char*>(&avail),sizeof(avail));
file.read(reinterpret_cast<char*>(&campos[0]),sizeof(Campo)*campos.size());
avail = 0;
/*Reescribimos el header*/
file2.write(reinterpret_cast<char*>(&numero_Campos),sizeof(numero_Campos));
file2.write(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
file2.write(reinterpret_cast<char*>(&indexType),sizeof(indexType));
file2.write(reinterpret_cast<char*>(&avail),sizeof(avail));
file2.write(reinterpret_cast<char*>(&campos[0]),sizeof(Campo)*campos.size());
int control = 1;
int numReg = 1;
char c;
int start;
int offset = inicioRegistros(filename);
file.seekg(offset,ios::beg);
while(true){
if(control <= campos.size()){
start = file.tellg();
if(file.read(reinterpret_cast<char*>(&c),sizeof(c))){
if(c != '&'){
file.seekg(start,ios::beg);
if(file.read(reinterpret_cast<char*>(&data),sizeof(data))){
file2.write(reinterpret_cast<char*>(&data),sizeof(data));
control++;
} else {
break;
}
}else{
int control2 = 1;
file.seekg(start,ios::beg);
while(control2 <= campos.size()){
if(file.read(reinterpret_cast<char*>(&data),sizeof(data))){
control2++;
}
}
numReg++;
control = 1;
}
}
} else if(control > campos.size()){
control = 1;
numReg++;
}
if(file.eof()){
break;
}
}
file.close();
file2.close();
char original[filename.size()+1];
char temp[filename2.size()+1];
strcpy(original, filename.c_str());
strcpy(temp,filename2.c_str());
remove(original);
rename(temp,original);
}else{
cout << "No ha abierto un archivo valido"<<endl;
}
file.close();
}
if(opcion == 7){
string llave;
ifstream file(filename,ios::binary);
if(file){
int useIndex,indexType;
file.seekg(sizeof(int),ios::beg);
file.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
file.read(reinterpret_cast<char*>(&indexType),sizeof(indexType));
if(useIndex == 0){
cargarIndices(filename);
}
cout << "Ingrese la llave primaria del registro que quiere buscar: ";
cin >> llave;
PrimaryKey* key = indice.find(llave)->second;
int offset = key->getOffset();
file.seekg(offset,ios::beg);
vector<Informacion> info;
Informacion data;
campos = cargarEstructura(filename);
int control = 0;
while(true){
if(control < campos.size()){
file.read(reinterpret_cast<char*>(&data),sizeof(data));
cout << campos.at(control).nombre << ": ";
if(campos.at(control).tipo == 1){
cout << data.value;
}else{
cout << data.texto;
}
control++;
cout << endl;
}else{
break;
}
}
}else{
cout << "No ha abierto un archivo valido"<<endl;
}
file.close();
}
if(opcion == 8){
while(true){
int option = menuCruzar();
if(option == 1){
string filename1,filename2;
cout << "Ingrese el nombre del primer archivo: ";
cin >> filename1;
cout << "Ingrese el nombre del segundo archivo: ";
cin >> filename2;
ifstream archivo1(filename1,ios::binary);
ifstream archivo2(filename2,ios::binary);
if(archivo1 && archivo2){
vector<Campo> estructura1 = cargarEstructura(filename1);
vector<Campo> estructura2 = cargarEstructura(filename2);
vector<int> seleccion1;
vector<int> seleccion2;
cout << "Seleccione los campos del archivo 1: "<<endl;
for(int i = 0; i < estructura1.size(); i++){
if(estructura1.at(i).isKey){
cout << i+1<<" - *"<<estructura1.at(i).nombre<<endl;
}else{
cout << i+1<<" - "<<estructura1.at(i).nombre<<endl;
}
}
int fields = 0;
int llavePrimaria = 0;
int selection,continuar;
while(fields <= estructura1.size()){
cout << "Campo a seleccionar: ";
cin >> selection;
seleccion1.push_back(selection-1);
cout << "Desea agregar otro campo? (1-Si/0-No): ";
cin >> continuar;
if(continuar == 0){
break;
}else{
fields++;
}
}
cout << "Seleccione los campos del archivo 2: "<<endl;
for(int i = 0; i < estructura2.size(); i++){
if(estructura2.at(i).isKey){
cout << i+1<<" - *"<<estructura2.at(i).nombre<<endl;
}else{
cout << i+1<<" - "<<estructura2.at(i).nombre<<endl;
}
}
fields = 0;
while(fields <= estructura2.size()){
cout << "Campo a seleccionar: ";
cin >> selection;
seleccion2.push_back(selection-1);
cout << "Desea agregar otro campo? (1-Si/0-No): ";
cin >> continuar;
if(continuar == 0){
break;
}else{
fields++;
}
}
string newFileName;
cout << "Ingrese el nombre del nuevo archivo: ";
cin >> newFileName;
int useIndex,indexType;
cout << "Desea utilizar indices con este nuevo archivo?: (1-Si/0-No)";
cin >> useIndex;
if(useIndex == 1){
cout << "Que tipo de indice le gustaria usar? (1-Lineal/0-ArbolB): ";
cin >> indexType;
}
ofstream newFile(newFileName,ios::binary|ios_base::app);
int totalFields = seleccion1.size()+seleccion2.size();
int disponible = 0;
newFile.write(reinterpret_cast<char*>(&totalFields),sizeof(totalFields));
newFile.write(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
newFile.write(reinterpret_cast<char*>(&indexType),sizeof(indexType));
newFile.write(reinterpret_cast<char*>(&disponible),sizeof(disponible));
Campo data;
for(int i = 0; i < estructura1.size(); i++){
for(int j = 0; j < seleccion1.size(); j++){
if(i == seleccion1.at(j)){
data = estructura1.at(i);
newFile.write(reinterpret_cast<char*>(&data),sizeof(data));
}
}
}
for(int i = 0; i < estructura2.size(); i++){
for(int j = 0; j < seleccion2.size(); j++){
if(i == seleccion2.at(j)){
data = estructura2.at(i);
newFile.write(reinterpret_cast<char*>(&data),sizeof(data));
}
}
}
}else{
cout << "Uno o ambos archivos no existen"<<endl;
}
}
if(option == 2){
}
if(option == 3){
}
if(option == 4){
break;
}
}
btree.recorrer();
}
if(opcion == 9){
cout << "Ingrese el nombre del archivo de texto: ";
cin >> filename;
text2bin(filename);
cout << "Terminado"<<endl;
}
if(opcion == 10){
continuar = false;
}
}
return 0;
}
int menu(){
int opcion;
cout << "1 - Abrir Archivo" << endl;
cout << "2 - Agregar Registros" << endl;
cout << "3 - Listar" << endl;
cout << "4 - Modificar Registro"<<endl;
cout << "5 - Borrar Registro"<<endl;
cout << "6 - Compactar"<<endl;
cout << "7 - Buscar"<<endl;
cout << "8 - Cruzar Archivo" << endl;
cout << "9 - Convertir un archivo de texto a binario"<<endl;
cout << "10 - Salir"<<endl;
cout << "Ingrese opcion: ";
cin >> opcion;
return opcion;
}
int menuCruzar(){
int opcion;
cout << "1 - Cruzar Sin Indices"<<endl;
cout << "2 - Cruzar Con Indice Lineal"<<endl;
cout << "3 - Cruzar usando Arbol B"<<endl;
cout << "4 - Salir: "<<endl;
cout << "Ingrese Opcion: ";
cin >> opcion;
return opcion;
}
void cargarIndices(string filename){
indice.clear();
string indexFileName = "index_"+filename;
ifstream file(filename,ios::binary);
int useIndex,indexType;
file.seekg(sizeof(int),ios::beg);
file.read(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
file.read(reinterpret_cast<char*>(&indexType),sizeof(indexType));
ifstream fileExists(indexFileName,ios::binary);
int offset = inicioRegistros(filename);
file.seekg(offset,ios::beg);
vector<Informacion> info;
vector<Campo> campos = cargarEstructura(filename);
Informacion info1;
int control = 1;
int start = -1;
string llave;
while(true){
if(control <= campos.size()){
if(control == 1){
start = file.tellg();
}
if(file.read(reinterpret_cast<char*>(&info1),sizeof(info1))){
info.push_back(info1);
if(campos.at(control-1).isKey){
indice.insert(pair<string,PrimaryKey*>(info.at(control-1).texto,new PrimaryKey(info.at(control-1).texto,start)));
}
control++;
} else {
break;
}
} else if(control > campos.size()){
info.clear();
control = 1;
}
if(file.eof()){
break;
}
}
file.close();
if(useIndex == 1){
if(indexType == 1){
if(fileExists){
ofstream borrar(indexFileName,ios::binary|ios::trunc);
borrar.close();
ofstream file2(indexFileName,ios::binary|ios::app);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
string key = it->first;
int offset = it->second->getOffset();
file2.write(reinterpret_cast<char*>(&key),sizeof(key));
file2.write(reinterpret_cast<char*>(&offset),sizeof(offset));
}
file2.close();
}else{
ofstream file2(indexFileName,ios::binary|ios_base::app);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
string key = it->first;
int offset = it->second->getOffset();
file2.write(reinterpret_cast<char*>(&key),sizeof(key));
file2.write(reinterpret_cast<char*>(&offset),sizeof(offset));
}
file2.close();
}
}else if(indexType == 0){
ArbolB arbol(16);
for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++){
arbol.insertar(it->second);
}
btree = arbol;
cout << "Termine de agregar al arbol"<<endl;
}
}
}
void imprimir(string filename){
cout << endl;
ifstream file(filename,ios::binary);
int offset = inicioRegistros(filename);
file.seekg(offset,ios::beg);
vector<Informacion> info;
vector<Campo> campos = cargarEstructura(filename);
Informacion info1;
int control = 1;
int numReg = 1;
char c;
int start;
while(true){
if(control <= campos.size()){
start = file.tellg();
if(file.read(reinterpret_cast<char*>(&c),sizeof(c))){
if(c != '&'){
file.seekg(start,ios::beg);
if(file.read(reinterpret_cast<char*>(&info1),sizeof(info1))){
info.push_back(info1);
control++;
} else {
break;
}
}else{
int control2 = 1;
file.seekg(start,ios::beg);
while(control2 <= campos.size()){
if(file.read(reinterpret_cast<char*>(&info1),sizeof(info1))){
info.push_back(info1);
control2++;
}
}
info.clear();
numReg++;
control = 1;
}
}
} else if(control > campos.size()){
cout << "Registro #"<<numReg<<endl;
for(int i = 0; i < campos.size(); i++){
cout << campos.at(i).nombre<<": ";
if(campos.at(i).tipo == 1){
cout << info.at(i).value;
}else if(campos.at(i).tipo == 2){
cout << info.at(i).texto;
}
cout << endl;
}
cout << endl;
info.clear();
control = 1;
numReg++;
}
if(file.eof()){
break;
}
}
file.close();
/*for (map<string,PrimaryKey*>::iterator it=indice.begin(); it!=indice.end(); it++)
cout << it->first << " => " << it->second->getOffset() << '\n';*/
}
vector<Campo> cargarEstructura(string filename){
vector<Campo> campos;
ifstream file(filename,ios::binary|ios::in);
Campo camp;
int cantCampos = 0;
int position;
int offset = 0;
file.seekg(0,ios::beg);
file.read(reinterpret_cast<char*>(&cantCampos),sizeof(cantCampos)); //lee el numero de campos
offset = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(int);
file.seekg(offset,ios::beg);
int max = sizeof(int) + sizeof(int)+ sizeof(int) + (cantCampos * sizeof(Campo));
while(offset < max){
file.read(reinterpret_cast<char*>(&camp), sizeof(camp));
campos.push_back(camp);
offset += sizeof(Campo);
}
return campos;
file.close();
}
int inicioRegistros(string filename){
ifstream file(filename,ios::binary|ios::in);
int cantCampos = 0;
file.read(reinterpret_cast<char*>(&cantCampos),sizeof(cantCampos));
int offset = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(int) + (cantCampos*sizeof(Campo));
return offset;
}
vector<int> cargarAvailList(string filename){
int first_avail=0, offset, cantCampos;
int readPosition = sizeof(int) + sizeof(int) + sizeof(int);
vector<int> posiciones;
ifstream file(filename,ios::binary|ios::in);
file.read(reinterpret_cast<char*>(&cantCampos),sizeof(cantCampos));
file.seekg(readPosition,ios::beg);
file.read(reinterpret_cast<char*>(&first_avail),sizeof(first_avail));
//cout << first_avail << endl;
posiciones.push_back(first_avail);
offset = inicioRegistros(filename);
//cout << offset << endl;
file.seekg(offset,ios::beg);
offset += (first_avail-1)*cantCampos*sizeof(Informacion);
file.seekg(offset+1,ios::beg);
int next;
if(first_avail == 0){
file.close();
return posiciones;
} else {
while(true){
file.read(reinterpret_cast<char*>(&next),sizeof(next));
//cout << next << endl;
offset = inicioRegistros(filename);
offset += (next-1)*cantCampos*sizeof(Informacion);
file.seekg(offset+1,ios::beg);
posiciones.push_back(next);
if(next == 0){
break;
}
}
file.close();
return posiciones;
}
}
void text2bin(string filename){
ifstream in(filename);
if(in){
int useIndex = 0;
int indexType = 0;
cout << "Desea utilizar indices en este archivo? (1-Si/0-No): ";
cin >> useIndex;
if(useIndex == 1){
cout << "Que tipo de indice le gustaria utilizar? (1-Lineal/0-Arbol B): ";
cin >> indexType;
}
filename.erase(filename.end()-4,filename.end());
string outputFile = filename+".bin";
ofstream out(outputFile,ios::binary|ios::app);
int control = 0;
string linea,token;
string delimitador = ",";
size_t pos = 0;
vector<string> splitString;
vector<Campo> estructura;
while(in >> linea){
if(control == 0){
while ((pos = linea.find(delimitador)) != std::string::npos) {
token = linea.substr(0, pos);
splitString.push_back(token);
linea.erase(0, pos + delimitador.length());
}
splitString.push_back(linea);
int fieldCount = splitString.size();
int available = 0;
out.write(reinterpret_cast<char*>(&fieldCount),sizeof(fieldCount));
out.write(reinterpret_cast<char*>(&useIndex),sizeof(useIndex));
out.write(reinterpret_cast<char*>(&indexType),sizeof(indexType));
out.write(reinterpret_cast<char*>(&available),sizeof(available));
for(int i = 0; i < splitString.size(); i++){
Campo campo;
campo.nombre = splitString.at(i);
if(i == 0){
campo.tipo = 2;
campo.isKey = true;
campo.longitud = 10;
}else{
campo.tipo = 2;
campo.isKey = false;
campo.longitud = 15;
}
out.write(reinterpret_cast<char*>(&campo),sizeof(campo));
}
control++;
splitString.clear();
}else{
while ((pos = linea.find(delimitador)) != std::string::npos) {
token = linea.substr(0, pos);
splitString.push_back(token);
linea.erase(0, pos + delimitador.length());
}
splitString.push_back(linea);
for(int i = 0; i < splitString.size(); i++){
Informacion data;
data.value = 0;
data.texto = splitString.at(i);
out.write(reinterpret_cast<char*>(&data),sizeof(data));
}
splitString.clear();
control++;
}
}
in.close();
out.close();
}else{
cout << "El archivo no existe"<<endl;
}
}
| [
"joedhernandez95@unitec.edu"
] | joedhernandez95@unitec.edu |
8427b6527b80dff635623421fb32923091e11190 | 898aba0ba23c7bfb1af1c0857ad56c814a6d32ba | /CppDesignPatterns/SimpleDemos/bridge/bridge.cpp | e0a027927d057644ddda30a5a1bdd982bc862a29 | [] | no_license | andrewbolster/cppqubmarch2013 | 735d4bdefc4e2413969a5bb7a3480969549281fe | cb033fc22f5262daba9f542062d2d0ac40b38f4a | refs/heads/master | 2016-09-05T19:03:32.343921 | 2013-03-22T13:41:27 | 2013-03-22T13:41:27 | 8,875,864 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,795 | cpp | #include "bridge.h"
/*
All the private members of Stack are encapsulated by StackImpl
*/
class Node{
private:
string item;
Node *next;
public:
Node(string in):item(in),next(0){}
void setNext(Node* n=0){ next=n; }
Node* getNext(){ return next; }
string getItem(){ return item; }
};
class StackImpl {
private:
Node *first;
int currentSize;
public:
StackImpl();
void add(string item);
int size();
string removeLast();
string get(int index);
};
StackImpl::StackImpl() : first(0), currentSize(0) {}
int StackImpl::size(){
return currentSize;
}
void StackImpl::add(string item){
if(!first){
first = new Node(item);
}
else {
Node *ptr = first;
while(ptr->getNext())
ptr = ptr->getNext();
ptr->setNext(new Node(item));
}
currentSize++;
}
string StackImpl::get(int index){
if(!first) throw "no element";
Node *ptr = first;
for(int i=1; i<index; i++) {
ptr = ptr->getNext();
if(!ptr) throw "no element";
}
return ptr->getItem();
}
string StackImpl::removeLast(){
Node *ptr = first;
Node *before_ptr = 0;
if(!first) throw "no element";
while(ptr->getNext()){
before_ptr = ptr;
ptr = ptr->getNext();
}
string item = ptr->getItem();
if(ptr != first) {
delete ptr;
before_ptr->setNext();
}
else {
delete first;
first = 0;
}
currentSize--;
return item;
}
//All the members of Stack are implemented using StackImpl
Stack::Stack() {
pimpl = new StackImpl();
}
Stack::~Stack() {
delete pimpl;
}
void Stack::add(string item){
pimpl->add(item);
}
string Stack::get(int index){
return pimpl->get(index);
}
string Stack::removeLast(){
return pimpl->removeLast();
}
int Stack::size(){
return pimpl->size();
}
| [
"bolster@localhost.(none)"
] | bolster@localhost.(none) |
5dd761cf76d300e2e1f7d1323b268ac1ce370664 | 45dd31b0f5784bbda278c6bfdc56517e61e793fd | /MyGraphics/MyGraphics/Source/Mesh.cpp | 014014a43118d792a0a450a941193359cd2db21a | [] | no_license | lyx97/SP2-Team-11 | f59def02f0a72f31a1588cea5e989fc1d82df2b8 | d4b1acdd13437082ced64c1acf6819f6528bd25f | refs/heads/master | 2021-01-10T07:47:30.899411 | 2016-03-03T15:28:27 | 2016-03-03T15:28:27 | 51,690,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,579 | cpp | #include "Mesh.h"
#include "GL\glew.h"
#include "Vertex.h"
#include "Material.h"
/******************************************************************************/
/*!
\brief
Default constructor - generate VBO/IBO here
\param meshName - name of mesh
*/
/******************************************************************************/
Mesh::Mesh(const std::string &meshName)
: name(meshName)
, mode(DRAW_TRIANGLES)
{
glGenBuffers(1, &vertexBuffer);
glGenBuffers(1, &indexBuffer);
textureID = 0;
}
/******************************************************************************/
/*!
\brief
Destructor - delete VBO/IBO here
*/
/******************************************************************************/
Mesh::~Mesh()
{
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &indexBuffer);
if (textureID > 0)
{
glDeleteTextures(1, &textureID);
}
}
/******************************************************************************/
/*!
\brief
OpenGL render code
*/
/******************************************************************************/
void Mesh::Render()
{
glEnableVertexAttribArray(0); // 1st attribute buffer : positions
glEnableVertexAttribArray(1); // 2nd attribute buffer : colors
glEnableVertexAttribArray(2); // 3rd attribute buffer : normals
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE , sizeof(Vertex), (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Position));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color)));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
if (textureID > 0)
{
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position)+sizeof(Color)+sizeof(Vector3)));
}
if (mode == DRAW_TRIANGLE_STRIP)
{
glDrawElements(GL_TRIANGLE_STRIP, indexSize, GL_UNSIGNED_INT, 0);
}
else if (mode == DRAW_LINES)
{
glDrawElements(GL_LINES, indexSize, GL_UNSIGNED_INT, 0);
}
else
{
glDrawElements(GL_TRIANGLES, indexSize, GL_UNSIGNED_INT, 0);
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
if (textureID > 0)
{
glDisableVertexAttribArray(3);
}
}
void Mesh::Render(unsigned offset, unsigned count)
{
glEnableVertexAttribArray(0); // 1st attribute buffer : positions
glEnableVertexAttribArray(1); // 2nd attribute buffer : colors
glEnableVertexAttribArray(2); // 3rd attribute buffer : normals
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Position));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position)+sizeof(Color)));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
if (textureID > 0)
{
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position)+sizeof(Color)+sizeof(Vector3)));
}
if (mode == DRAW_LINES)
glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint)));
else if (mode == DRAW_TRIANGLE_STRIP)
glDrawElements(GL_TRIANGLE_STRIP, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint)));
else
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint)));
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
if (textureID > 0)
{
glDisableVertexAttribArray(3);
}
} | [
"lyx10797@gmail.com"
] | lyx10797@gmail.com |
372efa7230d9ba1473ca9293631afed809c6858a | 182adfdfa907d3efc0395e293dcdbc46898d88eb | /Temp/il2cppOutput/il2cppOutput/mscorlib_System_Action_1_gen2899269018.h | b8591fa799b9a8d29dc63f6c62a22e23a6aa79af | [] | no_license | Launchable/1.1.3New | d1962418cd7fa184300c62ebfd377630a39bd785 | 625374fae90e8339cec0007d4d7202328bfa03d9 | refs/heads/master | 2021-01-19T07:40:29.930695 | 2017-09-15T17:20:45 | 2017-09-15T17:20:45 | 100,642,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_MulticastDelegate3201952435.h"
#include "mscorlib_System_Void1841601450.h"
// GooglePlayResult
struct GooglePlayResult_t3097469636;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Action`1<GooglePlayResult>
struct Action_1_t2899269018 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"zk.launchable@gmail.com"
] | zk.launchable@gmail.com |
7e6464069009c83a8ac0ae60ef521d4e0942b090 | 8f02939917edda1e714ffc26f305ac6778986e2d | /competitions/SCPC/2021/round-1/B.cc | 4796adc0dd216e75b4a5c460af22d5e166915a7c | [] | no_license | queuedq/ps | fd6ee880d67484d666970e7ef85459683fa5b106 | d45bd3037a389495d9937afa47cf0f74cd3f09cf | refs/heads/master | 2023-08-18T16:45:18.970261 | 2023-08-17T17:04:19 | 2023-08-17T17:04:19 | 134,966,734 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | cc | #include <bits/stdc++.h>
#define endl "\n"
using namespace std;
using lld = long long;
using pii = pair<int, int>;
using pll = pair<lld, lld>;
////////////////////////////////////////////////////////////////
const int MN = 50005;
int N, t, B[MN], D[MN][2], A[MN]; // D[i][j]: j is possible for A[i]
void solve(int test) {
string S;
cin >> N >> t >> S;
for (int i=0; i<N; i++) B[i] = S[i] - '0';
for (int i=0; i<N; i++) D[i][0] = D[i][1] = false;
for (int i=N-1; i>=N-t; i--) D[i][0] = D[i][1] = true;
for (int i=N-1-t; i>=0; i--) {
if (B[i+t] == 0) {
D[i][0] = true;
D[i][1] = false;
} else {
D[i][0] = i+t+t < N ? D[i+t+t][1] : false;
D[i][1] = true;
}
}
for (int i=0; i<t; i++) A[i] = D[i][0] ? 0 : 1;
for (int i=t; i<N; i++) {
if (B[i-t] == 0) {
A[i] = 0;
} else {
if (i-t-t >= 0 && A[i-t-t] == 1 && D[i][0]) A[i] = 0;
else A[i] = 1;
}
}
cout << "Case #" << test << endl;
for (int i=0; i<N; i++) cout << A[i];
cout << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
////////////////////////////////
int T; cin >> T;
for (int t=1; t<=T; t++) {
solve(t);
}
////////////////////////////////
return 0;
}
| [
"queuedq@gmail.com"
] | queuedq@gmail.com |
440293c40846684f091702df56a320d2b824d7b4 | 44227276cdce0d15ee0cdd19a9f38a37b9da33d7 | /alien/standalone/src/refsemantic/alien/ref/data/scalar/RedistributedVector.h | 0b2e3c72f5e7306eb96507535f319d1a7a73c2be | [
"Apache-2.0"
] | permissive | arcaneframework/framework | 7d0050f0bbceb8cc43c60168ba74fff0d605e9a3 | 813cfb5eda537ce2073f32b1a9de6b08529c5ab6 | refs/heads/main | 2023-08-19T05:44:47.722046 | 2023-08-11T16:22:12 | 2023-08-11T16:22:12 | 357,932,008 | 31 | 21 | Apache-2.0 | 2023-09-14T16:42:12 | 2021-04-14T14:21:07 | C++ | UTF-8 | C++ | false | false | 2,381 | h | /*
* Copyright 2020 IFPEN-CEA
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <alien/data/IVector.h>
#include <alien/kernels/redistributor/Redistributor.h>
#include <alien/ref/AlienRefSemanticPrecomp.h>
#include <alien/utils/ICopyOnWriteObject.h>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Alien
{
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
class ALIEN_REFSEMANTIC_EXPORT RedistributedVector final : public IVector
{
public:
RedistributedVector() = delete;
RedistributedVector(RedistributedVector&& vector) = delete;
RedistributedVector(IVector& vector, Redistributor& redist);
~RedistributedVector();
RedistributedVector& operator=(RedistributedVector&& vector) = delete;
RedistributedVector(const RedistributedVector& vector) = delete;
RedistributedVector& operator=(const RedistributedVector& vector) = delete;
public:
// Pour les expressions
void visit(ICopyOnWriteVector&) const;
const VectorDistribution& distribution() const;
const ISpace& space() const;
void setUserFeature(String feature);
bool hasUserFeature(String feature) const;
public:
MultiVectorImpl* impl();
const MultiVectorImpl* impl() const;
private:
std::shared_ptr<MultiVectorImpl> m_impl;
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
} // namespace Alien
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| [
"cedric.chevalier@cea.fr"
] | cedric.chevalier@cea.fr |
650c27721a016095b964b2c24c75261215ae9007 | 46a1bfb511c488f85cc5d030ac5824b3c4995f66 | /Source/PyramidGame/Litetspel_Horus_Pyramid/Litetspel_Horus_Pyramid/Chain.h | 986695cc13f4846a6d24e912b15e975dca5a22c2 | [] | no_license | 0Oskar/G4_HillClimber | 43086ae0d26ca508acf13cd941dcf6ba6db13dee | 34dbcfd1be6b470308c0f1f19f0634aed3625193 | refs/heads/development | 2023-08-17T12:15:51.808041 | 2023-08-05T15:03:46 | 2023-08-05T15:03:46 | 251,297,246 | 2 | 0 | null | 2020-06-03T00:22:20 | 2020-03-30T12:26:17 | C++ | UTF-8 | C++ | false | false | 935 | h | #pragma once
#include "GameObject.h"
#define NR_OF_CHAIN_LINKS 128
class Chain
{
private:
bool m_visible;
bool m_shooting;
bool m_retracting;
Timer m_timer;
std::vector<GameObject*>* m_chainGObjects;
std::vector<bool> m_retractedLinks;
int m_nrOfUnretractedLinks;
GameObject* m_hookGObject;
GameObject* m_gaunletGObject;
XMVECTOR m_gauntletSpawnPosition;
float m_constant;
float m_linkLength;
float m_friction;
void simulateLinks(GameObject* link1, GameObject* link2, bool notFirst, float dt);
void linkRetractionUpdate();
void calculateGauntletLinkSpawnPosition();
public:
Chain();
~Chain();
void initialize(GameObject* hookGObject, GameObject* gaunletGObject, std::vector<GameObject*>* chainGObjects);
bool isVisible() const;
XMVECTOR getLinkPosition(uint32_t index);
void setVisibility(bool visible);
void setShooting(bool shooting);
void setRetracting(bool retracting);
void update(float dt);
}; | [
"medoosman@outlook.com"
] | medoosman@outlook.com |
6b97a04470e9750b58efc09ea5f3a352e582058e | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/printscan/ui/printui/psetup.cxx | b1967d3ebe9e5c027d7742c992c1aee55aa00123 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,776 | cxx | /*++
Copyright (C) Microsoft Corporation, 1996 - 1998
All rights reserved.
Module Name:
PSetup.cxx
Abstract:
Printer setup class to gain access to the ntprint.dll
setup code.
Author:
Steve Kiraly (SteveKi) 19-Jan-1996
Revision History:
--*/
#include "precomp.hxx"
#pragma hdrstop
#include "psetup.hxx"
#include "psetup5.hxx"
#include "drvver.hxx"
/********************************************************************
Printer setup class.
********************************************************************/
TPSetup::
TPSetup(
VOID
) : _bValid( FALSE ),
_pPSetup50( NULL )
{
//
// Attemp to load the 5.0 version.
//
_pPSetup50 = new TPSetup50();
if( VALID_PTR( _pPSetup50 ) )
{
_bValid = TRUE;
return;
} else {
delete _pPSetup50;
_pPSetup50 = NULL;
}
}
TPSetup::
~TPSetup(
VOID
)
{
delete _pPSetup50;
}
BOOL
TPSetup::
bValid(
VOID
)
{
return _bValid;
}
/********************************************************************
Member functions, most of these functions are just a channing
call to the valid verion of the setup library.
********************************************************************/
HDEVINFO
TPSetup::
PSetupCreatePrinterDeviceInfoList(
IN HWND hwnd
)
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupCreatePrinterDeviceInfoList( hwnd );
}
return INVALID_HANDLE_VALUE;
}
VOID
TPSetup::
PSetupDestroyPrinterDeviceInfoList(
IN HDEVINFO h
)
{
if( _pPSetup50 )
{
_pPSetup50->PSetupDestroyPrinterDeviceInfoList( h );
}
}
BOOL
TPSetup::
PSetupProcessPrinterAdded(
IN HDEVINFO hDevInfo,
IN HANDLE hLocalData,
IN LPCTSTR pszPrinterName,
IN HWND hwnd
)
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupProcessPrinterAdded( hDevInfo, (PPSETUP_LOCAL_DATA)hLocalData, pszPrinterName, hwnd );
}
return FALSE;
}
BOOL
TPSetup::
bGetSelectedDriverName(
IN HANDLE hLocalData,
IN OUT TString &strDriverName,
IN PLATFORM platform
) const
{
if( _pPSetup50 )
{
TStatusB bStatus;
DRIVER_FIELD DrvField;
DrvField.Index = DRIVER_NAME;
bStatus DBGCHK = _pPSetup50->PSetupGetLocalDataField( (PPSETUP_LOCAL_DATA)hLocalData, platform, &DrvField );
if( bStatus )
{
bStatus DBGCHK = strDriverName.bUpdate( DrvField.pszDriverName );
_pPSetup50->PSetupFreeDrvField( &DrvField );
}
return bStatus;
}
return NULL;
}
BOOL
TPSetup::
bGetSelectedPrintProcessorName(
IN HANDLE hLocalData,
IN OUT TString &strPrintProcessor,
IN PLATFORM platform
) const
{
//
// This is only supported on NT5 version.
//
if( _pPSetup50 )
{
TStatusB bStatus;
DRIVER_FIELD DrvField;
DrvField.Index = PRINT_PROCESSOR_NAME;
bStatus DBGCHK = _pPSetup50->PSetupGetLocalDataField( (PPSETUP_LOCAL_DATA)hLocalData, platform, &DrvField );
if( bStatus )
{
bStatus DBGCHK = strPrintProcessor.bUpdate( DrvField.pszPrintProc );
_pPSetup50->PSetupFreeDrvField( &DrvField );
}
return bStatus;
}
return NULL;
}
BOOL
TPSetup::
bGetSelectedInfName(
IN HANDLE hLocalData,
IN OUT TString &strInfName,
IN PLATFORM platform
) const
{
if( _pPSetup50 )
{
TStatusB bStatus;
DRIVER_FIELD DrvField;
DrvField.Index = INF_NAME;
bStatus DBGCHK = _pPSetup50->PSetupGetLocalDataField( (PPSETUP_LOCAL_DATA)hLocalData, platform, &DrvField );
if( bStatus )
{
bStatus DBGCHK = strInfName.bUpdate( DrvField.pszInfName );
_pPSetup50->PSetupFreeDrvField( &DrvField );
}
return bStatus;
}
return NULL;
}
DWORD
TPSetup::
PSetupInstallPrinterDriver(
IN HDEVINFO h,
IN HANDLE hLocalData,
IN LPCTSTR pszDriverName,
IN PLATFORM platform,
IN DWORD dwVersion,
IN LPCTSTR pszServerName,
IN HWND hwnd,
IN LPCTSTR pszPlatformName,
IN LPCTSTR pszSourcePath,
IN DWORD dwInstallFlags,
IN DWORD dwAddDrvFlags,
OUT TString *pstrNewDriverName,
IN BOOL bOfferReplacement
)
{
DWORD dwRet = ERROR_INVALID_FUNCTION;
if (_pPSetup50)
{
LPTSTR pszNewDriverName = NULL;
PPSETUP_LOCAL_DATA pLocalData = (PPSETUP_LOCAL_DATA)hLocalData;
if (!bOfferReplacement)
{
// request from ntprint to suppress the driver replacement offering
dwInstallFlags |= DRVINST_DONT_OFFER_REPLACEMENT;
}
// call ntprint.dll ....
dwRet = _pPSetup50->PSetupInstallPrinterDriver(h, pLocalData, pszDriverName, platform, dwVersion,
pszServerName, hwnd, pszPlatformName, pszSourcePath, dwInstallFlags, dwAddDrvFlags, &pszNewDriverName);
// check to return the replacement driver name (if any)
if (ERROR_SUCCESS == dwRet && pszNewDriverName && pszNewDriverName[0] && pstrNewDriverName)
{
if (!pstrNewDriverName->bUpdate(pszNewDriverName))
{
dwRet = ERROR_OUTOFMEMORY;
}
}
if (pszNewDriverName)
{
// free up the memory allocated from ntprint
_pPSetup50->PSetupFreeMem(pszNewDriverName);
}
}
return dwRet;
}
HANDLE
TPSetup::
PSetupGetSelectedDriverInfo(
IN HDEVINFO h
)
{
HANDLE hHandle = NULL;
if( _pPSetup50 )
hHandle = _pPSetup50->PSetupGetSelectedDriverInfo( h );
return hHandle == NULL ? INVALID_HANDLE_VALUE : hHandle ;
}
HANDLE
TPSetup::
PSetupDriverInfoFromName(
IN HDEVINFO h,
IN LPCTSTR pszModel
)
{
HANDLE hHandle = NULL;
if( _pPSetup50 )
hHandle = _pPSetup50->PSetupDriverInfoFromName( h, pszModel );
return hHandle == NULL ? INVALID_HANDLE_VALUE : hHandle ;
}
VOID
TPSetup::
PSetupDestroySelectedDriverInfo(
IN HANDLE hLocalData
)
{
if( _pPSetup50 )
{
_pPSetup50->PSetupDestroySelectedDriverInfo( (PPSETUP_LOCAL_DATA)hLocalData );
}
}
BOOL
TPSetup::
PSetupIsDriverInstalled(
IN LPCTSTR pszServerName,
IN LPCTSTR pszDriverName,
IN PLATFORM platform,
IN DWORD dwMajorVersion
) const
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupIsDriverInstalled( pszServerName, pszDriverName, platform, dwMajorVersion );
}
return FALSE;
}
INT
TPSetup::
PSetupIsTheDriverFoundInInfInstalled(
IN LPCTSTR pszServerName,
IN HANDLE hLocalData,
IN PLATFORM platform,
IN DWORD dwMajorVersion,
IN DWORD dwMajorVersion2
) const
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupIsTheDriverFoundInInfInstalled( pszServerName, (PPSETUP_LOCAL_DATA)hLocalData, platform, dwMajorVersion2 );
}
return DRIVER_MODEL_NOT_INSTALLED;
}
BOOL
TPSetup::
PSetupSelectDriver(
IN HDEVINFO h,
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupSelectDriver( h );
return FALSE;
}
BOOL
TPSetup::
PSetupRefreshDriverList(
IN HDEVINFO h
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupRefreshDriverList( h );
return FALSE;
}
BOOL
TPSetup::
PSetupPreSelectDriver(
IN HDEVINFO h,
IN LPCTSTR pszManufacturer,
IN LPCTSTR pszModel
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupPreSelectDriver( h, pszManufacturer, pszModel );
return FALSE;
}
HPROPSHEETPAGE
TPSetup::
PSetupCreateDrvSetupPage(
IN HDEVINFO h,
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupCreateDrvSetupPage( h, hwnd );
return NULL;
}
HANDLE
TPSetup::
PSetupCreateMonitorInfo(
IN LPCTSTR pszServerName,
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupCreateMonitorInfo( hwnd, pszServerName);
return NULL;
}
VOID
TPSetup::
PSetupDestroyMonitorInfo(
IN OUT HANDLE h
)
{
if( _pPSetup50 )
_pPSetup50->PSetupDestroyMonitorInfo( h );
}
BOOL
TPSetup::
PSetupEnumMonitor(
IN HANDLE h,
IN DWORD dwIndex,
OUT LPTSTR pMonitorName,
IN OUT LPDWORD pdwSize
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupEnumMonitor( h, dwIndex, pMonitorName, pdwSize );
return FALSE;
}
BOOL
TPSetup::
PSetupInstallMonitor(
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupInstallMonitor( hwnd );
return FALSE;
}
BOOL
TPSetup::
PSetupBuildDriversFromPath(
IN HANDLE h,
IN LPCTSTR pszDriverPath,
IN BOOL bEnumSingleInf
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupBuildDriversFromPath( h, pszDriverPath, bEnumSingleInf );
return FALSE;
}
BOOL
TPSetup::
PSetupSetSelectDevTitleAndInstructions(
IN HDEVINFO hDevInfo,
IN LPCTSTR pszTitle,
IN LPCTSTR pszSubTitle,
IN LPCTSTR pszInstn
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupSetSelectDevTitleAndInstructions( hDevInfo, pszTitle, pszSubTitle, pszInstn );
return FALSE;
}
DWORD
TPSetup::
PSetupInstallPrinterDriverFromTheWeb(
IN HDEVINFO hDevInfo,
IN HANDLE pLocalData,
IN PLATFORM platform,
IN LPCTSTR pszServerName,
IN LPOSVERSIONINFO pOsVersionInfo,
IN HWND hwnd,
IN LPCTSTR pszSource
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupInstallPrinterDriverFromTheWeb( hDevInfo, (PPSETUP_LOCAL_DATA)pLocalData, platform, pszServerName, pOsVersionInfo, hwnd, pszSource );
return ERROR_INVALID_FUNCTION;
}
BOOL
TPSetup::
PSetupIsOemDriver(
IN HDEVINFO hDevInfo,
IN HANDLE pLocalData,
IN OUT PBOOL pbIsOemDriver
) const
{
if( _pPSetup50 )
return _pPSetup50->PSetupIsOemDriver( hDevInfo, (PPSETUP_LOCAL_DATA)pLocalData, pbIsOemDriver );
SetLastError( ERROR_INVALID_FUNCTION );
return FALSE;
}
BOOL
TPSetup::
PSetupSetWebMode(
IN HDEVINFO hDevInfo,
IN BOOL bWebButtonOn
)
{
DWORD dwFlagsSet = bWebButtonOn ? SELECT_DEVICE_FROMWEB : 0;
DWORD dwFlagsClear = bWebButtonOn ? 0 : SELECT_DEVICE_FROMWEB;
if( _pPSetup50 )
return _pPSetup50->PSetupSelectDeviceButtons( hDevInfo, dwFlagsSet, dwFlagsClear );
return FALSE;
}
BOOL
TPSetup::
PSetupShowOem(
IN HDEVINFO hDevInfo,
IN BOOL bShowOem
)
{
DWORD dwFlagsSet = bShowOem ? SELECT_DEVICE_HAVEDISK : 0;
DWORD dwFlagsClear = bShowOem ? 0 : SELECT_DEVICE_HAVEDISK;
if( _pPSetup50 )
return _pPSetup50->PSetupSelectDeviceButtons( hDevInfo, dwFlagsSet, dwFlagsClear );
return FALSE;
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
323d2b2ca51b1eb942a5b8a887026a0968e86fe7 | de404537c0d5d1142bbf4e9d8a9ab874766f75c7 | /sdk/bindings/xpcom/include/nsIObserver.h | 4ee928c19449a4384d6f6a6b9f06039670ec91be | [] | no_license | smoeller1/Hackathon | 6b6a0d3d59c2845b5709dffce5a1f14b3cb8b4da | acfac96ec4cc8e79ca622303fa4b16cd01277c6d | refs/heads/master | 2022-11-19T18:47:28.730061 | 2018-10-19T17:43:02 | 2018-10-19T17:43:02 | 55,860,568 | 0 | 0 | null | 2022-11-16T05:23:59 | 2016-04-09T18:29:40 | C | UTF-8 | C++ | false | false | 3,334 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /home/vbox/tinderbox/5.0-sdk/src/libs/xpcom18a4/xpcom/ds/nsIObserver.idl
*/
#ifndef __gen_nsIObserver_h__
#define __gen_nsIObserver_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIObserver */
#define NS_IOBSERVER_IID_STR "db242e01-e4d9-11d2-9dde-000064657374"
#define NS_IOBSERVER_IID \
{0xdb242e01, 0xe4d9, 0x11d2, \
{ 0x9d, 0xde, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74 }}
/**
* This interface is implemented by an object that wants
* to observe an event corresponding to a topic.
*
* @status FROZEN
*/
class NS_NO_VTABLE nsIObserver : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IOBSERVER_IID)
/**
* Observe will be called when there is a notification for the
* topic |aTopic|. This assumes that the object implementing
* this interface has been registered with an observer service
* such as the nsIObserverService.
*
* If you expect multiple topics/subjects, the impl is
* responsible for filtering.
*
* You should not modify, add, remove, or enumerate
* notifications in the implemention of observe.
*
* @param aSubject : Notification specific interface pointer.
* @param aTopic : The notification topic or subject.
* @param aData : Notification specific wide string.
* subject event.
*/
/* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) = 0;
};
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIOBSERVER \
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIOBSERVER(_to) \
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { return _to Observe(aSubject, aTopic, aData); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIOBSERVER(_to) \
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { return !_to ? NS_ERROR_NULL_POINTER : _to->Observe(aSubject, aTopic, aData); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsObserver : public nsIObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
nsObserver();
private:
~nsObserver();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsObserver, nsIObserver)
nsObserver::nsObserver()
{
/* member initializers and constructor code */
}
nsObserver::~nsObserver()
{
/* destructor code */
}
/* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
NS_IMETHODIMP nsObserver::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIObserver_h__ */
| [
"simon@quasily.com"
] | simon@quasily.com |
c4823df5c6e89b24a3d4fd3e71b0219e41645a54 | b2c7b04f9a31cd3dbf837af7729df5e221528c05 | /Shooters!/SceneBase.h | 8c1d73db373a6251faa1b61ffea48e199cebbb0d | [] | no_license | Nati-Ryuon/Shooters | dddd756e3c930dddc4e38882424fee6bbbfc8b07 | 012bbd11c7dcc82fbf9ee069903d2b6035301628 | refs/heads/master | 2020-03-28T20:50:07.485546 | 2018-12-24T08:25:35 | 2018-12-24T08:25:35 | 149,106,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | h | #pragma once
#include <memory>
/*
class SceneBase {
public:
virtual void draw() = 0;
virtual void update() = 0;
bool isFinished() {
return false;
}
std::unique_ptr<SceneBase> getNextScene() {
return next.get;
}
std::unique_ptr<SceneBase> getReturnScene() {
return prev.get;
}
std::unique_ptr<SceneBase> next;
std::unique_ptr<SceneBase> prev;
};
*/
class SceneBase {
protected:
bool returnScene;
bool saveScene;
std::unique_ptr<SceneBase> nextScene;
public:
SceneBase() : returnScene(false), nextScene(nullptr), saveScene(false) {}
bool isFinished() const;
bool getReturnScene() const;
bool getSaveScene() const;
bool nextSceneNullCheck() const { return nextScene != nullptr; }
std::unique_ptr<SceneBase> getNextScene();
virtual void draw() = 0;
virtual void update() = 0;
}; | [
"aries.zata@gmail.com"
] | aries.zata@gmail.com |
3c90b4e3cea5035ae24e38971e322fb8e0fdbd5d | 78de9ab02ba562058ba564e9f0e6b28bad02936b | /src/cpp/mem/private/mem/engine/MemoryEngine.cpp | 32109dd5f4ec6620495bb147e39034adf6e6ea7d | [
"MIT"
] | permissive | c0de4un/memory_manager | b5b6d7fa43074563de375046718023161cd0cf06 | ec63bc7d828d0f8675b53c5045674c22bd8902ef | refs/heads/master | 2022-12-11T14:20:28.520098 | 2020-09-03T04:05:01 | 2020-09-03T04:05:01 | 289,554,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,300 | cpp | /**
* All rights reserved.
* License: see LICENSE.txt
*
* 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 display the names 'Denis Zyamaev' and
* in the credits of the application, if such credits exist.
* The authors of this work must be notified via email (code4un@yandex.ru) in
* this case of redistribution.
* 3. Neither the name of 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 COPYRIGHT HOLDERS OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
**/
// -----------------------------------------------------------
// ===========================================================
// INCLUDES
// ===========================================================
// HEADER
#ifndef MEM_MEMORY_ENGINE_HPP
#include "../../public/mem/engine/MemoryEngine.hpp"
#endif // !MEM_MEMORY_ENGINE_HPP
// ===========================================================
// mem::MemoryEngine
// ===========================================================
namespace mem
{
// -----------------------------------------------------------
// -----------------------------------------------------------
} /// mem
// -----------------------------------------------------------
| [
"code4un@yandex.ru"
] | code4un@yandex.ru |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.