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 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
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 122
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ef02d8580b89143a065d0a5af03d8ca9a7fc84d
|
fb7b1068179053d6e1e9e52103fa2648a67ae95a
|
/src/Trie_cuckoo_noise_07_21.h
|
48ebc074a0400ae9f8f85cfffb98ff935750d591
|
[] |
no_license
|
yunhong111/3-24_prefilter_BLA
|
d20d314ac2eb4b4ea0686abf1ed7104bdc121ae1
|
0136518cdc643fe6dd2bdf279e97b555319d1173
|
refs/heads/master
| 2021-01-10T00:55:39.559674
| 2016-03-24T15:56:54
| 2016-03-24T15:56:54
| 54,654,778
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 592
|
h
|
/**
trie_cuckoo_noise_07_21.cpp
create by: Yunhong
create time: 07/21/2015
*/
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <iostream>
#include <numeric>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <sys/time.h>
#include <arpa/inet.h>
#include "aggregation_add_cuckoo.h"
# include <time.h>
using namespace std;
void feedbackBlackkey(vector<string>& overBigKeys);
void feedbackBlackkey1(strings& overBigKeys);
bool readFile0(ifstream& infile, vector<string> &flow, vector<size_t> &flow_cnt, size_t readNum, bool& isEndFlag);
|
[
"yunhong@tamu.edu"
] |
yunhong@tamu.edu
|
6d0d5e72c7ab10ed212ca007145866591b2e3b41
|
58ac7ce414dcbe875e26bb6fae692e3c74f39c4e
|
/net/socket/socks5_client_socket_fuzzer.cc
|
377b6614a5321378ca18395b3a8eb77f0381dc1e
|
[] |
no_license
|
markthomas93/tempwork
|
f4ba7b4620c1cb806aef40a66692115140b42c90
|
93c852f3d14c95b2d73077b00e7284ea6f416d84
|
refs/heads/master
| 2021-12-10T10:35:39.230466
| 2016-08-11T12:00:33
| 2016-08-11T12:00:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,633
|
cc
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/fuzzed_data_provider.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/log/test_net_log.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/fuzzed_socket.h"
#include "net/socket/socks5_client_socket.h"
// Fuzzer for Socks5ClientSocket. Only covers the SOCKS5 greeet and
// handshake.
//
// |data| is used to create a FuzzedSocket to fuzz reads and writes, see that
// class for details.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
// Use a test NetLog, to exercise logging code.
net::TestNetLog test_net_log;
net::FuzzedDataProvider data_provider(data, size);
net::TestCompletionCallback callback;
std::unique_ptr<net::FuzzedSocket> fuzzed_socket(
new net::FuzzedSocket(&data_provider, &test_net_log));
CHECK_EQ(net::OK, fuzzed_socket->Connect(callback.callback()));
std::unique_ptr<net::ClientSocketHandle> socket_handle(
new net::ClientSocketHandle());
socket_handle->SetSocket(std::move(fuzzed_socket));
net::HostResolver::RequestInfo request_info(net::HostPortPair("foo", 80));
net::SOCKS5ClientSocket socket(std::move(socket_handle), request_info);
int result = socket.Connect(callback.callback());
callback.GetResult(result);
return 0;
}
|
[
"gaoxiaojun@gmail.com"
] |
gaoxiaojun@gmail.com
|
0d2ae32eea01f27fde9b26e37740af662c7dd0f6
|
9126df6fc8a6786463bea1cbb2b8dcc29ccb7f39
|
/cpp/include/cuml/explainer/permutation_shap.hpp
|
b0546fbc415b67531884a625484ef8138e60fd36
|
[
"Apache-2.0"
] |
permissive
|
akaanirban/cuml
|
6667eb7fc7eb81bdc11977f259c2dd4993934dd0
|
9f924a2d8e7192c7b65a7efee7257dafdbebce06
|
refs/heads/main
| 2023-06-04T12:49:36.812511
| 2021-06-10T19:39:13
| 2021-06-10T19:39:13
| 371,710,939
| 0
| 0
|
Apache-2.0
| 2021-05-28T13:32:32
| 2021-05-28T13:32:31
| null |
UTF-8
|
C++
| false
| false
| 5,395
|
hpp
|
/*
* Copyright (c) 2020-2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace raft {
class handle_t;
}
namespace ML {
namespace Explainer {
/**
* Generates a dataset by tiling the `background` matrix into `out`, while
* adding a forward and backward permutation pass of the observation `row`
* on the positions defined by `idx`. Example:
*
* background = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
* idx = [2, 0, 1]
* row = [100, 101, 102]
* output:
* [[ 0, 1, 2]
* [ 3, 4, 5]
* [ 6, 7, 8]
* [ 0, 1, 102]
* [ 3, 4, 102]
* [ 6, 7, 102]
* [100, 1, 102]
* [100, 4, 102]
* [100, 7, 102]
* [100, 101, 102]
* [100, 101, 102]
* [100, 101, 102]
* [100, 101, 2]
* [100, 101, 5]
* [100, 101, 8]
* [ 0, 101, 2]
* [ 3, 101, 5]
* [ 6, 101, 8]
* [ 0, 1, 2]
* [ 3, 4, 5]
* [ 6, 7, 8]]
*
*
* @param[in] handle cuML handle
* @param[out] dataset generated data in either row major or column major
* format, depending on the `row_major` parameter [on device]
* [dim = (2 * ncols * nrows_bg + nrows_bg) * ncols]
* @param[in] background background data [on device] [dim = ncols * nrows_bg]
* @param[in] nrows_bg number of rows in background dataset
* @param[in] ncols number of columns
* @param[in] row row to scatter in a permutated fashion [dim = ncols]
* @param[in] idx permutation indexes [dim = ncols]
* @param[in] row_major boolean to generate either row or column major data
*
*/
void permutation_shap_dataset(const raft::handle_t& handle, float* dataset,
const float* background, int nrows_bg, int ncols,
const float* row, int* idx, bool row_major);
void permutation_shap_dataset(const raft::handle_t& handle, double* dataset,
const double* background, int nrows_bg, int ncols,
const double* row, int* idx, bool row_major);
/**
* Generates a dataset by tiling the `background` matrix into `out`, while
* adding a forward and backward permutation pass of the observation `row`
* on the positions defined by `idx`. Example:
*
* background = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
* idx = [2, 0, 1]
* row = [100, 101, 102]
* output:
* [[ 0, 1, 2]
* [ 3, 4, 5]
* [ 6, 7, 8]
* [ 0, 1, 102]
* [ 3, 4, 102]
* [ 6, 7, 102]
* [100, 1, 2]
* [100, 4, 5]
* [100, 7, 8]
* [ 0, 101, 2]
* [ 3, 101, 5]
* [ 6, 101, 8]]
*
*
* @param[in] handle cuML handle
* @param[out] dataset generated data [on device] [dim = (2 * ncols * nrows_bg + nrows_bg) * ncols]
* @param[in] background background data [on device] [dim = ncols * nrows_bg]
* @param[in] nrows_bg number of rows in background dataset
* @param[in] ncols number of columns
* @param[in] row row to scatter in a permutated fashion [dim = ncols]
* @param[in] idx permutation indexes [dim = ncols]
* @param[in] row_major boolean to generate either row or column major data
*
*/
void shap_main_effect_dataset(const raft::handle_t& handle, float* dataset,
const float* background, int nrows_bg, int ncols,
const float* row, int* idx, bool row_major);
void shap_main_effect_dataset(const raft::handle_t& handle, double* dataset,
const double* background, int nrows_bg, int ncols,
const double* row, int* idx, bool row_major);
/**
* Function that aggregates averages of the averatge of results of the model
* called with the permutation dataset, to estimate the SHAP values.
* It is equivalent to the Python code:
* for i,ind in enumerate(idx):
* shap_values[ind] += y_hat[i + 1] - y_hat[i]
* for i,ind in enumerate(idx):
* shap_values[ind] += y_hat[i + ncols] - y_hat[i + ncols + 1]
*
* @param[in] handle cuML handle
* @param[out] shap_values Array where the results are aggregated [dim = ncols]
* @param[in] y_hat Results to use for the aggregation [dim = ncols + 1]
* @param[in] ncols number of columns
* @param[in] idx permutation indexes [dim = ncols]
*/
void update_perm_shap_values(const raft::handle_t& handle, float* shap_values,
const float* y_hat, const int ncols,
const int* idx);
void update_perm_shap_values(const raft::handle_t& handle, double* shap_values,
const double* y_hat, const int ncols,
const int* idx);
} // namespace Explainer
} // namespace ML
|
[
"noreply@github.com"
] |
akaanirban.noreply@github.com
|
f711281b6260673dabfc43e0fff2589453aa24e3
|
8adfe707978a0de4f2c70a95878f1db563224536
|
/src/game/WorldSession.h
|
968fdee5ce9751bfa131fc1ea4acf83f2b8dcc5d
|
[] |
no_license
|
wuhongyi1977/StrawberryCore-1
|
4138e102bc8d2c1b7b6513b168587e7e59ec968f
|
3fdd0ca71208d97189166729be59832eff086db0
|
refs/heads/master
| 2020-12-24T15:49:06.047248
| 2012-01-17T01:03:11
| 2012-01-17T01:03:11
| 3,224,456
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 42,666
|
h
|
/*
* Copyright (C) 2010-2012 Strawberry-Pr0jcts <http://strawberry-pr0jcts.com/>
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/// \addtogroup u2w
/// @{
/// \file
#ifndef __WORLDSESSION_H
#define __WORLDSESSION_H
#include "Common.h"
#include "SharedDefines.h"
#include "ObjectGuid.h"
#include "AuctionHouseMgr.h"
#include "Item.h"
#include "WardenBase.h"
struct ItemPrototype;
struct AuctionEntry;
struct AuctionHouseEntry;
struct DeclinedName;
class ObjectGuid;
class Creature;
class Item;
class Object;
class Player;
class Unit;
class WorldPacket;
class WorldSocket;
class QueryResult;
class LoginQueryHolder;
class CharacterHandler;
class GMTicket;
class MovementInfo;
class WorldSession;
struct OpcodeHandler;
enum AccountDataType
{
GLOBAL_CONFIG_CACHE = 0, // 0x01 g
PER_CHARACTER_CONFIG_CACHE = 1, // 0x02 p
GLOBAL_BINDINGS_CACHE = 2, // 0x04 g
PER_CHARACTER_BINDINGS_CACHE = 3, // 0x08 p
GLOBAL_MACROS_CACHE = 4, // 0x10 g
PER_CHARACTER_MACROS_CACHE = 5, // 0x20 p
PER_CHARACTER_LAYOUT_CACHE = 6, // 0x40 p
PER_CHARACTER_CHAT_CACHE = 7, // 0x80 p
NUM_ACCOUNT_DATA_TYPES = 8
};
#define GLOBAL_CACHE_MASK 0x15
#define PER_CHARACTER_CACHE_MASK 0xEA
struct AccountData
{
AccountData() : Time(0), Data("") {}
time_t Time;
std::string Data;
};
struct AddonInfo
{
AddonInfo(const std::string& name, uint8 enabled, uint32 crc)
{
Name = name;
Enabled = enabled;
CRC = crc;
}
std::string Name;
uint8 Enabled;
uint32 CRC;
};
typedef std::list<AddonInfo> AddonsList;
enum PartyOperation
{
PARTY_OP_INVITE = 0,
PARTY_OP_LEAVE = 2,
PARTY_OP_SWAP = 4
};
enum PartyResult
{
ERR_PARTY_RESULT_OK = 0,
ERR_BAD_PLAYER_NAME_S = 1,
ERR_TARGET_NOT_IN_GROUP_S = 2,
ERR_TARGET_NOT_IN_INSTANCE_S = 3,
ERR_GROUP_FULL = 4,
ERR_ALREADY_IN_GROUP_S = 5,
ERR_NOT_IN_GROUP = 6,
ERR_NOT_LEADER = 7,
ERR_PLAYER_WRONG_FACTION = 8,
ERR_IGNORING_YOU_S = 9,
ERR_LFG_PENDING = 12,
ERR_INVITE_RESTRICTED = 13,
ERR_GROUP_SWAP_FAILED = 14, // if (PartyOperation == PARTY_OP_SWAP) ERR_GROUP_SWAP_FAILED else ERR_INVITE_IN_COMBAT
ERR_INVITE_UNKNOWN_REALM = 15,
ERR_INVITE_NO_PARTY_SERVER = 16,
ERR_INVITE_PARTY_BUSY = 17,
ERR_PARTY_TARGET_AMBIGUOUS = 18,
ERR_PARTY_LFG_INVITE_RAID_LOCKED = 19,
ERR_PARTY_LFG_BOOT_LIMIT = 20,
ERR_PARTY_LFG_BOOT_COOLDOWN_S = 21,
ERR_PARTY_LFG_BOOT_IN_PROGRESS = 22,
ERR_PARTY_LFG_BOOT_TOO_FEW_PLAYERS = 23,
ERR_PARTY_LFG_BOOT_NOT_ELIGIBLE_S = 24,
ERR_RAID_DISALLOWED_BY_LEVEL = 25,
ERR_PARTY_LFG_BOOT_IN_COMBAT = 26,
ERR_VOTE_KICK_REASON_NEEDED = 27,
ERR_PARTY_LFG_BOOT_DUNGEON_COMPLETE = 28,
ERR_PARTY_LFG_BOOT_LOOT_ROLLS = 29,
ERR_PARTY_LFG_TELEPORT_IN_COMBAT = 30
};
enum LfgJoinResult
{
ERR_LFG_OK = 0x00,
ERR_LFG_ROLE_CHECK_FAILED = 0x01,
ERR_LFG_GROUP_FULL = 0x02,
ERR_LFG_NO_LFG_OBJECT = 0x04,
ERR_LFG_NO_SLOTS_PLAYER = 0x05,
ERR_LFG_NO_SLOTS_PARTY = 0x06,
ERR_LFG_MISMATCHED_SLOTS = 0x07,
ERR_LFG_PARTY_PLAYERS_FROM_DIFFERENT_REALMS = 0x08,
ERR_LFG_MEMBERS_NOT_PRESENT = 0x09,
ERR_LFG_GET_INFO_TIMEOUT = 0x0A,
ERR_LFG_INVALID_SLOT = 0x0B,
ERR_LFG_DESERTER_PLAYER = 0x0C,
ERR_LFG_DESERTER_PARTY = 0x0D,
ERR_LFG_RANDOM_COOLDOWN_PLAYER = 0x0E,
ERR_LFG_RANDOM_COOLDOWN_PARTY = 0x0F,
ERR_LFG_TOO_MANY_MEMBERS = 0x10,
ERR_LFG_CANT_USE_DUNGEONS = 0x11,
ERR_LFG_ROLE_CHECK_FAILED2 = 0x12,
};
enum LfgUpdateType
{
LFG_UPDATE_JOIN = 5,
LFG_UPDATE_LEAVE = 7,
};
enum LfgType
{
LFG_TYPE_NONE = 0,
LFG_TYPE_DUNGEON = 1,
LFG_TYPE_RAID = 2,
LFG_TYPE_QUEST = 3,
LFG_TYPE_ZONE = 4,
LFG_TYPE_HEROIC_DUNGEON = 5,
LFG_TYPE_RANDOM_DUNGEON = 6
};
enum ChatRestrictionType
{
ERR_CHAT_RESTRICTED = 0,
ERR_CHAT_THROTTLED = 1,
ERR_USER_SQUELCHED = 2,
ERR_YELL_RESTRICTED = 3
};
enum TutorialDataState
{
TUTORIALDATA_UNCHANGED = 0,
TUTORIALDATA_CHANGED = 1,
TUTORIALDATA_NEW = 2
};
//class to deal with packet processing
//allows to determine if next packet is safe to be processed
class PacketFilter
{
public:
explicit PacketFilter(WorldSession * pSession) : m_pSession(pSession) {}
virtual ~PacketFilter() {}
virtual bool Process(WorldPacket * packet) { return true; }
virtual bool ProcessLogout() const { return true; }
protected:
WorldSession * const m_pSession;
};
//process only thread-safe packets in Map::Update()
class MapSessionFilter : public PacketFilter
{
public:
explicit MapSessionFilter(WorldSession * pSession) : PacketFilter(pSession) {}
~MapSessionFilter() {}
virtual bool Process(WorldPacket * packet);
//in Map::Update() we do not process player logout!
virtual bool ProcessLogout() const { return false; }
};
//class used to filer only thread-unsafe packets from queue
//in order to update only be used in World::UpdateSessions()
class WorldSessionFilter : public PacketFilter
{
public:
explicit WorldSessionFilter(WorldSession * pSession) : PacketFilter(pSession) {}
~WorldSessionFilter() {}
virtual bool Process(WorldPacket* packet);
};
/// Player session in the World
class STRAWBERRY_DLL_SPEC WorldSession
{
friend class CharacterHandler;
public:
WorldSession(uint32 id, WorldSocket *sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale);
~WorldSession();
bool PlayerLoading() const { return m_playerLoading; }
bool PlayerLogout() const { return m_playerLogout; }
bool PlayerLogoutWithSave() const { return m_playerLogout && m_playerSave; }
void SizeError(WorldPacket const& packet, uint32 size) const;
void ReadAddonsInfo(WorldPacket &data);
void SendAddonsInfo();
void ReadMovementInfo(WorldPacket &data, MovementInfo *mi);
void WriteMovementInfo(WorldPacket *data, MovementInfo *mi);
void SendPacket(WorldPacket const* packet);
void SendNotification(const char *format,...) ATTR_PRINTF(2,3);
void SendNotification(int32 string_id,...);
void SendPetNameInvalid(uint32 error, const std::string& name, DeclinedName *declinedName);
void SendLfgSearchResults(LfgType type, uint32 entry);
void SendLfgJoinResult(LfgJoinResult result);
void SendLfgUpdate(bool isGroup, LfgUpdateType updateType, uint32 id);
void SendPartyResult(PartyOperation operation, const std::string& member, PartyResult res);
void SendAreaTriggerMessage(const char* Text, ...) ATTR_PRINTF(2,3);
void SendSetPhaseShift(uint32 phaseShift);
void SendQueryTimeResponse();
void SendRedirectClient(std::string& ip, uint16 port);
AccountTypes GetSecurity() const { return _security; }
uint32 GetAccountId() const { return _accountId; }
Player* GetPlayer() const { return _player; }
char const* GetPlayerName() const;
void SetSecurity(AccountTypes security) { _security = security; }
std::string const& GetRemoteAddress() { return m_Address; }
void SetPlayer(Player *plr);
uint8 Expansion() const { return m_expansion; }
void InitWarden(BigNumber *K, std::string os);
/// Session in auth.queue currently
void SetInQueue(bool state) { m_inQueue = state; }
/// Is the user engaged in a log out process?
bool isLogingOut() const { return _logoutTime || m_playerLogout; }
/// Engage the logout process for the user
void LogoutRequest(time_t requestTime)
{
_logoutTime = requestTime;
}
/// Is logout cooldown expired?
bool ShouldLogOut(time_t currTime) const
{
return (_logoutTime > 0 && currTime >= _logoutTime + 20);
}
void LogoutPlayer(bool Save);
void KickPlayer();
void QueuePacket(WorldPacket* new_packet);
bool Update(PacketFilter& updater);
/// Handle the authentication waiting queue (to be completed)
void SendAuthWaitQue(uint32 position);
void SendNameCacheOpcode(Player* p);
void SendNameCacheOpcodeFromDB(ObjectGuid guid);
static void SendNameCacheOpcodeFromDBCallBack(QueryResult *result, uint32 accountId);
void SendTrainerList(ObjectGuid guid);
void SendTrainerList(ObjectGuid guid, const std::string& strTitle );
void SendListInventory(ObjectGuid guid);
bool CheckBanker(ObjectGuid guid);
void SendShowBank(ObjectGuid guid);
bool CheckMailBox(ObjectGuid guid);
void SendShowMailBox(ObjectGuid guid);
void SendTabardVendorActivate(ObjectGuid guid);
void SendSpiritResurrect();
void SendBindPoint(Creature* npc);
void SendGMTicketGetTicket(uint32 status, GMTicket *ticket = NULL);
void SendGMResponse(GMTicket *ticket);
void SendAttackStop(Unit const* enemy);
void SendBattlegGroundList(ObjectGuid guid, BattleGroundTypeId bgTypeId);
void SendTradeStatus(TradeStatus status);
void SendUpdateTrade(bool trader_state = true);
void SendCancelTrade();
void SendPetitionQueryOpcode(ObjectGuid petitionguid);
//pet
void SendPetNameQuery(ObjectGuid guid, uint32 petnumber);
void SendStablePet(ObjectGuid guid);
void SendStableResult(uint8 res);
bool CheckStableMaster(ObjectGuid guid);
// Account Data
AccountData *GetAccountData(AccountDataType type) { return &m_accountData[type]; }
void SetAccountData(AccountDataType type, time_t time_, std::string data);
void SendAccountDataTimes(uint32 mask);
void LoadGlobalAccountData();
void LoadAccountData(QueryResult* result, uint32 mask);
void LoadTutorialsData();
void SendTutorialsData();
void SaveTutorialsData();
uint32 GetTutorialInt(uint32 intId )
{
return m_Tutorials[intId];
}
void SetTutorialInt(uint32 intId, uint32 value)
{
if(m_Tutorials[intId] != value)
{
m_Tutorials[intId] = value;
if(m_tutorialState == TUTORIALDATA_UNCHANGED)
m_tutorialState = TUTORIALDATA_CHANGED;
}
}
//used with item_page table
bool SendItemInfo( uint32 itemid, WorldPacket data );
//auction
void SendAuctionHello(Unit *unit);
void SendAuctionCommandResult(AuctionEntry *auc, AuctionAction Action, AuctionError ErrorCode, InventoryResult invError = EQUIP_ERR_OK);
void SendAuctionBidderNotification(AuctionEntry *auction);
void SendAuctionOwnerNotification(AuctionEntry *auction);
void SendAuctionRemovedNotification(AuctionEntry* auction);
static void SendAuctionOutbiddedMail(AuctionEntry *auction);
void SendAuctionCancelledToBidderMail(AuctionEntry *auction);
void BuildListAuctionItems(std::vector<AuctionEntry*> const& auctions, WorldPacket& data, std::wstring const& searchedname, uint32 listfrom, uint32 levelmin,
uint32 levelmax, uint32 usable, uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, uint32& count, uint32& totalcount, bool isFull);
AuctionHouseEntry const* GetCheckedAuctionHouseForAuctioneer(ObjectGuid guid);
//Item Enchantment
void SendEnchantmentLog(ObjectGuid targetGuid, ObjectGuid casterGuid, uint32 itemId, uint32 spellId);
void SendItemEnchantTimeUpdate(ObjectGuid playerGuid, ObjectGuid itemGuid, uint32 slot, uint32 duration);
//Taxi
void SendTaxiStatus(ObjectGuid guid);
void SendTaxiMenu( Creature* unit );
void SendDoFlight( uint32 mountDisplayId, uint32 path, uint32 pathNode = 0 );
bool SendLearnNewTaxiNode( Creature* unit );
// Guild/Arena Team
void SendGuildCommandResult(uint32 typecmd, const std::string& str, uint32 cmdresult);
void SendArenaTeamCommandResult(uint32 team_action, const std::string& team, const std::string& player, uint32 error_id);
void SendNotInArenaTeamPacket(uint8 type);
void SendPetitionShowList(ObjectGuid guid);
void SendSaveGuildEmblem( uint32 msg );
void BuildPartyMemberStatsChangedPacket(Player *player, WorldPacket *data);
void DoLootRelease(ObjectGuid lguid);
// Account mute time
time_t m_muteTime;
// Locales
LocaleConstant GetSessionDbcLocale() const { return m_sessionDbcLocale; }
int GetSessionDbLocaleIndex() const { return m_sessionDbLocaleIndex; }
const char *GetStrawberryString(int32 entry) const;
uint32 GetLatency() const { return m_latency; }
void SetLatency(uint32 latency) { m_latency = latency; }
uint32 getDialogStatus(Player *pPlayer, Object* questgiver, uint32 defstatus);
public: // opcodes handlers
void HandleNULL(WorldPacket& recvPacket); // not used
void HandleEarlyProccess( WorldPacket& recvPacket);// just mark packets processed in WorldSocket::OnRead
void HandleServerSide(WorldPacket& recvPacket); // sever side only, can't be accepted from client
void Handle_Deprecated(WorldPacket& recvPacket); // never used anymore by client
void HandleCharEnumOpcode(WorldPacket& recvPacket);
void HandleCharDeleteOpcode(WorldPacket& recvPacket);
void HandleCharCreateOpcode(WorldPacket& recvPacket);
void HandleLoadingScreenNotify(WorldPacket& recvPacket);
void HandlePlayerLoginOpcode(WorldPacket& recvPacket);
void HandleCharEnum(QueryResult * result);
void HandlePlayerLogin(LoginQueryHolder * holder);
// played time
void HandlePlayedTime(WorldPacket& recvPacket);
// new
void HandleMoveUnRootAck(WorldPacket& recvPacket);
void HandleMoveRootAck(WorldPacket& recvPacket);
// new inspect
void HandleInspectOpcode(WorldPacket& recvPacket);
// new party stats
void HandleInspectHonorStatsOpcode(WorldPacket& recvPacket);
void HandleMoveWaterWalkAck(WorldPacket& recvPacket);
void HandleFeatherFallAck(WorldPacket &recv_data);
void HandleMoveHoverAck( WorldPacket & recv_data );
void HandleMountSpecialAnimOpcode(WorldPacket &recvdata);
// character view
void HandleShowingHelmOpcode(WorldPacket& recv_data);
void HandleShowingCloakOpcode(WorldPacket& recv_data);
// repair
void HandleRepairItemOpcode(WorldPacket& recvPacket);
// Knockback
void HandleMoveKnockBackAck(WorldPacket& recvPacket);
void HandleMoveTeleportAckOpcode(WorldPacket& recvPacket);
void HandleForceSpeedChangeAckOpcodes( WorldPacket & recv_data );
void HandlePingOpcode(WorldPacket& recvPacket);
void HandleAuthSessionOpcode(WorldPacket& recvPacket);
void HandleRepopRequestOpcode(WorldPacket& recvPacket);
void HandleAutostoreLootItemOpcode(WorldPacket& recvPacket);
void HandleLootMoneyOpcode(WorldPacket& recvPacket);
void HandleLootOpcode(WorldPacket& recvPacket);
void HandleLootReleaseOpcode(WorldPacket& recvPacket);
void HandleLootMasterGiveOpcode(WorldPacket& recvPacket);
void HandleWhoOpcode(WorldPacket& recvPacket);
void HandleLogoutRequestOpcode(WorldPacket& recvPacket);
void HandlePlayerLogoutOpcode(WorldPacket& recvPacket);
void HandleLogoutCancelOpcode(WorldPacket& recvPacket);
void HandleGMTicketGetTicketOpcode(WorldPacket& recvPacket);
void HandleGMTicketCreateOpcode(WorldPacket& recvPacket);
void HandleGMTicketSystemStatusOpcode(WorldPacket& recvPacket);
void HandleGMTicketDeleteTicketOpcode(WorldPacket& recvPacket);
void HandleGMTicketUpdateTextOpcode(WorldPacket& recvPacket);
void HandleGMSurveySubmitOpcode(WorldPacket& recvPacket);
void HandleGMResponseResolveOpcode(WorldPacket& recv_data);
void HandleTogglePvP(WorldPacket& recvPacket);
void HandleZoneUpdateOpcode(WorldPacket& recvPacket);
void HandleSetTargetOpcode(WorldPacket& recvPacket);
void HandleSetSelectionOpcode(WorldPacket& recvPacket);
void HandleStandStateChangeOpcode(WorldPacket& recvPacket);
void HandleEmoteOpcode(WorldPacket& recvPacket);
void HandleContactListOpcode(WorldPacket& recvPacket);
void HandleAddFriendOpcode(WorldPacket& recvPacket);
static void HandleAddFriendOpcodeCallBack(QueryResult *result, uint32 accountId, std::string friendNote);
void HandleDelFriendOpcode(WorldPacket& recvPacket);
void HandleAddIgnoreOpcode(WorldPacket& recvPacket);
static void HandleAddIgnoreOpcodeCallBack(QueryResult *result, uint32 accountId);
void HandleDelIgnoreOpcode(WorldPacket& recvPacket);
void HandleSetContactNotesOpcode(WorldPacket& recvPacket);
void HandleBugOpcode(WorldPacket& recvPacket);
void HandleSetAmmoOpcode(WorldPacket& recvPacket);
void HandleItemNameQueryOpcode(WorldPacket& recvPacket);
void HandleAreaTriggerOpcode(WorldPacket& recvPacket);
void HandleSetFactionAtWarOpcode( WorldPacket & recv_data );
void HandleSetWatchedFactionOpcode(WorldPacket & recv_data);
void HandleSetFactionInactiveOpcode(WorldPacket & recv_data);
void HandleUpdateAccountData(WorldPacket& recvPacket);
void HandleRequestAccountData(WorldPacket& recvPacket);
void HandleSetActionButtonOpcode(WorldPacket& recvPacket);
void HandleGameObjectUseOpcode(WorldPacket& recPacket);
void HandleGameobjectReportUse(WorldPacket& recvPacket);
void HandleNameCacheOpcode(WorldPacket& recvPacket);
void HandleQueryTimeOpcode(WorldPacket& recvPacket);
void HandleCreatureStatsOpcode(WorldPacket& recvPacket);
void HandleGameObjectStatsOpcode(WorldPacket& recvPacket);
void HandleMoveWorldportAckOpcode(WorldPacket& recvPacket);
void HandleMoveWorldportAckOpcode(); // for server-side calls
void HandleMovementOpcodes(WorldPacket& recvPacket);
void HandleSetActiveMoverOpcode(WorldPacket &recv_data);
void HandleMoveNotActiveMoverOpcode(WorldPacket &recv_data);
void HandleMoveTimeSkippedOpcode(WorldPacket &recv_data);
void HandleDismissControlledVehicle(WorldPacket &recv_data);
void HandleRequestVehicleExit(WorldPacket &recv_data);
void HandleRequestVehiclePrevSeat(WorldPacket &recv_data);
void HandleRequestVehicleNextSeat(WorldPacket &recv_data);
void HandleRequestVehicleSwitchSeat(WorldPacket &recv_data);
void HandleEnterPlayerVehicle(WorldPacket &recv_data);
void HandleEjectPasenger(WorldPacket &recv_data);
void HandleChangeSeatsOnControlledVehicle(WorldPacket &recv_data);
void HandleRequestRaidInfoOpcode( WorldPacket & recv_data );
void HandleGroupInviteOpcode(WorldPacket& recvPacket);
void HandleGroupAcceptOpcode(WorldPacket& recvPacket);
void HandleGroupDeclineOpcode(WorldPacket& recvPacket);
void HandleGroupUninviteOpcode(WorldPacket& recvPacket);
void HandleGroupUninviteGuidOpcode(WorldPacket& recvPacket);
void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket);
void HandleGroupDisbandOpcode(WorldPacket& recvPacket);
void HandleOptOutOfLootOpcode( WorldPacket &recv_data );
void HandleSetAllowLowLevelRaidOpcode( WorldPacket & recv_data );
void HandleLootMethodOpcode(WorldPacket& recvPacket);
void HandleLootRoll( WorldPacket &recv_data );
void HandleRequestPartyMemberStatsOpcode( WorldPacket &recv_data );
void HandleRaidTargetUpdateOpcode( WorldPacket & recv_data );
void HandleRaidReadyCheckOpcode( WorldPacket & recv_data );
void HandleRaidReadyCheckFinishedOpcode( WorldPacket & recv_data );
void HandleGroupRaidConvertOpcode( WorldPacket & recv_data );
void HandleGroupChangeSubGroupOpcode( WorldPacket & recv_data );
void HandleGroupAssistantLeaderOpcode( WorldPacket & recv_data );
void HandlePartyAssignmentOpcode( WorldPacket & recv_data );
void HandlePetitionBuyOpcode(WorldPacket& recv_data);
void HandlePetitionShowSignOpcode(WorldPacket& recv_data);
void HandlePetitionQueryOpcode(WorldPacket& recv_data);
void HandlePetitionRenameOpcode(WorldPacket& recv_data);
void HandlePetitionSignOpcode(WorldPacket& recv_data);
void HandlePetitionDeclineOpcode(WorldPacket& recv_data);
void HandleOfferPetitionOpcode(WorldPacket& recv_data);
void HandleTurnInPetitionOpcode(WorldPacket& recv_data);
void HandleGuildQueryOpcode(WorldPacket& recvPacket);
void HandleGuildCreateOpcode(WorldPacket& recvPacket);
void HandleGuildInviteOpcode(WorldPacket& recvPacket);
void HandleGuildRemoveOpcode(WorldPacket& recvPacket);
void HandleGuildAcceptOpcode(WorldPacket& recvPacket);
void HandleGuildDeclineOpcode(WorldPacket& recvPacket);
void HandleGuildInfoOpcode(WorldPacket& recvPacket);
void HandleGuildEventLogQueryOpcode(WorldPacket& recvPacket);
void HandleGuildRosterOpcode(WorldPacket& recvPacket);
void HandleGuildPromoteOpcode(WorldPacket& recvPacket);
void HandleGuildDemoteOpcode(WorldPacket& recvPacket);
void HandleGuildLeaveOpcode(WorldPacket& recvPacket);
void HandleGuildDisbandOpcode(WorldPacket& recvPacket);
void HandleGuildLeaderOpcode(WorldPacket& recvPacket);
void HandleGuildMOTDOpcode(WorldPacket& recvPacket);
void HandleGuildSetPublicNoteOpcode(WorldPacket& recvPacket);
void HandleGuildSetOfficerNoteOpcode(WorldPacket& recvPacket);
void HandleGuildRankOpcode(WorldPacket& recvPacket);
void HandleGuildAddRankOpcode(WorldPacket& recvPacket);
void HandleGuildDelRankOpcode(WorldPacket& recvPacket);
void HandleGuildChangeInfoTextOpcode(WorldPacket& recvPacket);
void HandleSaveGuildEmblemOpcode(WorldPacket& recvPacket);
void HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvPacket);
void HandleTaxiQueryAvailableNodes(WorldPacket& recvPacket);
void HandleActivateTaxiOpcode(WorldPacket& recvPacket);
void HandleActivateTaxiExpressOpcode(WorldPacket& recvPacket);
void HandleMoveSplineDoneOpcode(WorldPacket& recvPacket);
void HandleTabardVendorActivateOpcode(WorldPacket& recvPacket);
void HandleBankerActivateOpcode(WorldPacket& recvPacket);
void HandleBuyBankSlotOpcode(WorldPacket& recvPacket);
void HandleTrainerListOpcode(WorldPacket& recvPacket);
void HandleTrainerBuySpellOpcode(WorldPacket& recvPacket);
void HandlePetitionShowListOpcode(WorldPacket& recvPacket);
void HandleGossipHelloOpcode(WorldPacket& recvPacket);
void HandleGossipSelectOptionOpcode(WorldPacket& recvPacket);
void HandleSpiritHealerActivateOpcode(WorldPacket& recvPacket);
void HandleNpcTextQueryOpcode(WorldPacket& recvPacket);
void HandleBinderActivateOpcode(WorldPacket& recvPacket);
void HandleListStabledPetsOpcode(WorldPacket& recvPacket);
void HandleStablePet(WorldPacket& recvPacket);
void HandleUnstablePet(WorldPacket& recvPacket);
void HandleBuyStableSlot(WorldPacket& recvPacket);
void HandleStableRevivePet(WorldPacket& recvPacket);
void HandleStableSwapPet(WorldPacket& recvPacket);
void HandleDuelAcceptedOpcode(WorldPacket& recvPacket);
void HandleDuelCancelledOpcode(WorldPacket& recvPacket);
void HandleAcceptTradeOpcode(WorldPacket& recvPacket);
void HandleBeginTradeOpcode(WorldPacket& recvPacket);
void HandleBusyTradeOpcode(WorldPacket& recvPacket);
void HandleCancelTradeOpcode(WorldPacket& recvPacket);
void HandleClearTradeItemOpcode(WorldPacket& recvPacket);
void HandleIgnoreTradeOpcode(WorldPacket& recvPacket);
void HandleInitiateTradeOpcode(WorldPacket& recvPacket);
void HandleSetTradeGoldOpcode(WorldPacket& recvPacket);
void HandleSetTradeItemOpcode(WorldPacket& recvPacket);
void HandleUnacceptTradeOpcode(WorldPacket& recvPacket);
void HandleAuctionHelloOpcode(WorldPacket& recvPacket);
void HandleAuctionListItems( WorldPacket & recv_data );
void HandleAuctionListBidderItems( WorldPacket & recv_data );
void HandleAuctionSellItem( WorldPacket & recv_data );
void HandleAuctionRemoveItem( WorldPacket & recv_data );
void HandleAuctionListOwnerItems( WorldPacket & recv_data );
void HandleAuctionPlaceBid( WorldPacket & recv_data );
void AuctionBind( uint32 price, AuctionEntry * auction, Player * pl, Player* auction_owner );
void HandleAuctionListPendingSales( WorldPacket & recv_data );
void HandleGetMailList( WorldPacket & recv_data );
void HandleSendMail( WorldPacket & recv_data );
void HandleMailTakeMoney( WorldPacket & recv_data );
void HandleMailTakeItem( WorldPacket & recv_data );
void HandleMailMarkAsRead( WorldPacket & recv_data );
void HandleMailReturnToSender( WorldPacket & recv_data );
void HandleMailDelete( WorldPacket & recv_data );
void HandleItemTextQuery( WorldPacket & recv_data);
void HandleMailCreateTextItem(WorldPacket & recv_data );
void HandleQueryNextMailTime(WorldPacket & recv_data );
void HandleCancelChanneling(WorldPacket & recv_data );
void SendItemPageInfo( ItemPrototype *itemProto );
void HandleSplitItemOpcode(WorldPacket& recvPacket);
void HandleSwapInvItemOpcode(WorldPacket& recvPacket);
void HandleDestroyItemOpcode(WorldPacket& recvPacket);
void HandleAutoEquipItemOpcode(WorldPacket& recvPacket);
void HandleItemQuerySingleOpcode(WorldPacket& recvPacket);
void HandleSellItemOpcode(WorldPacket& recvPacket);
void HandleBuyItemInSlotOpcode(WorldPacket& recvPacket);
void HandleBuyItemOpcode(WorldPacket& recvPacket);
void HandleListInventoryOpcode(WorldPacket& recvPacket);
void HandleAutoStoreBagItemOpcode(WorldPacket& recvPacket);
void HandleReadItemOpcode(WorldPacket& recvPacket);
void HandleAutoEquipItemSlotOpcode(WorldPacket & recvPacket);
void HandleSwapItem( WorldPacket & recvPacket);
void HandleBuybackItem(WorldPacket & recvPacket);
void HandleAutoBankItemOpcode(WorldPacket& recvPacket);
void HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket);
void HandleWrapItemOpcode(WorldPacket& recvPacket);
void HandleAttackSwingOpcode(WorldPacket& recvPacket);
void HandleAttackStopOpcode(WorldPacket& recvPacket);
void HandleSetSheathedOpcode(WorldPacket& recvPacket);
void HandleUseItemOpcode(WorldPacket& recvPacket);
void HandleOpenItemOpcode(WorldPacket& recvPacket);
void HandleCastSpellOpcode(WorldPacket& recvPacket);
void HandleCancelCastOpcode(WorldPacket& recvPacket);
void HandleCancelAuraOpcode(WorldPacket& recvPacket);
void HandleCancelGrowthAuraOpcode(WorldPacket& recvPacket);
void HandleCancelAutoRepeatSpellOpcode(WorldPacket& recvPacket);
void HandleLearnTalentOpcode(WorldPacket& recvPacket);
void HandleLearnPreviewTalents(WorldPacket& recvPacket);
void HandleTalentWipeConfirmOpcode(WorldPacket& recvPacket);
void HandleUnlearnSkillOpcode(WorldPacket& recvPacket);
void HandleQuestgiverStatusQueryOpcode(WorldPacket& recvPacket);
void HandleQuestgiverStatusMultipleQuery(WorldPacket& recvPacket);
void HandleQuestgiverHelloOpcode(WorldPacket& recvPacket);
void HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvPacket);
void HandleQuestgiverQueryQuestOpcode(WorldPacket& recvPacket);
void HandleQuestgiverChooseRewardOpcode(WorldPacket& recvPacket);
void HandleQuestgiverRequestRewardOpcode(WorldPacket& recvPacket);
void HandleQuestQueryOpcode(WorldPacket& recvPacket);
void HandleQuestgiverCancel(WorldPacket& recv_data );
void HandleQuestLogSwapQuest(WorldPacket& recv_data );
void HandleQuestLogRemoveQuest(WorldPacket& recv_data);
void HandleQuestConfirmAccept(WorldPacket& recv_data);
void HandleQuestgiverCompleteQuest(WorldPacket& recv_data);
void HandleQuestgiverQuestAutoLaunch(WorldPacket& recvPacket);
void HandlePushQuestToParty(WorldPacket& recvPacket);
void HandleQuestPushResult(WorldPacket& recvPacket);
bool processChatmessageFurtherAfterSecurityChecks(std::string&, uint32);
void SendPlayerNotFoundNotice(std::string name);
void SendPlayerAmbiguousNotice(std::string name);
void SendWrongFactionNotice();
void SendChatRestrictedNotice(ChatRestrictionType restriction);
void HandleMessagechatOpcode(WorldPacket& recvPacket);
void HandleTextEmoteOpcode(WorldPacket& recvPacket);
void HandleChatIgnoredOpcode(WorldPacket& recvPacket);
void HandleReclaimCorpseOpcode( WorldPacket& recvPacket );
void HandleCorpseQueryOpcode( WorldPacket& recvPacket );
void HandleCorpseMapPositionQueryOpcode( WorldPacket& recvPacket );
void HandleResurrectResponseOpcode(WorldPacket& recvPacket);
void HandleSummonResponseOpcode(WorldPacket& recv_data);
void HandleJoinChannelOpcode(WorldPacket& recvPacket);
void HandleLeaveChannelOpcode(WorldPacket& recvPacket);
void HandleChannelListOpcode(WorldPacket& recvPacket);
void HandleChannelPasswordOpcode(WorldPacket& recvPacket);
void HandleChannelSetOwnerOpcode(WorldPacket& recvPacket);
void HandleChannelOwnerOpcode(WorldPacket& recvPacket);
void HandleChannelModeratorOpcode(WorldPacket& recvPacket);
void HandleChannelUnmoderatorOpcode(WorldPacket& recvPacket);
void HandleChannelMuteOpcode(WorldPacket& recvPacket);
void HandleChannelUnmuteOpcode(WorldPacket& recvPacket);
void HandleChannelInviteOpcode(WorldPacket& recvPacket);
void HandleChannelKickOpcode(WorldPacket& recvPacket);
void HandleChannelBanOpcode(WorldPacket& recvPacket);
void HandleChannelUnbanOpcode(WorldPacket& recvPacket);
void HandleChannelAnnouncementsOpcode(WorldPacket& recvPacket);
void HandleChannelModerateOpcode(WorldPacket& recvPacket);
void HandleChannelDisplayListQueryOpcode(WorldPacket& recvPacket);
void HandleGetChannelMemberCountOpcode(WorldPacket& recvPacket);
void HandleSetChannelWatchOpcode(WorldPacket& recvPacket);
void HandleCompleteCinematic(WorldPacket& recvPacket);
void HandleNextCinematicCamera(WorldPacket& recvPacket);
void HandlePageQuerySkippedOpcode(WorldPacket& recvPacket);
void HandlePageTextQueryOpcode(WorldPacket& recvPacket);
void HandleTutorialFlagOpcode ( WorldPacket & recv_data );
void HandleTutorialClearOpcode( WorldPacket & recv_data );
void HandleTutorialResetOpcode( WorldPacket & recv_data );
//Pet
void HandlePetAction( WorldPacket & recv_data );
void HandlePetStopAttack(WorldPacket& recv_data);
void HandlePetNameQueryOpcode( WorldPacket & recv_data );
void HandlePetSetAction( WorldPacket & recv_data );
void HandlePetAbandon( WorldPacket & recv_data );
void HandlePetRename( WorldPacket & recv_data );
void HandlePetCancelAuraOpcode( WorldPacket& recvPacket );
void HandlePetUnlearnOpcode( WorldPacket& recvPacket );
void HandlePetSpellAutocastOpcode( WorldPacket& recvPacket );
void HandlePetCastSpellOpcode( WorldPacket& recvPacket );
void HandlePetLearnTalent( WorldPacket& recvPacket );
void HandleLearnPreviewTalentsPet( WorldPacket& recvPacket );
void HandleSetActionBarTogglesOpcode(WorldPacket& recv_data);
void HandleCharRenameOpcode(WorldPacket& recv_data);
static void HandleChangePlayerNameOpcodeCallBack(QueryResult *result, uint32 accountId, std::string newname);
void HandleSetPlayerDeclinedNamesOpcode(WorldPacket& recv_data);
void HandleTotemDestroyed(WorldPacket& recv_data);
//BattleGround
void HandleBattlemasterHelloOpcode(WorldPacket &recv_data);
void HandleBattlemasterJoinOpcode(WorldPacket &recv_data);
void HandleBattleGroundPlayerPositionsOpcode(WorldPacket& recv_data);
void HandlePVPLogDataOpcode( WorldPacket &recv_data );
void HandleBattlefieldStatusOpcode(WorldPacket &recv_data);
void HandleBattleFieldPortOpcode( WorldPacket &recv_data );
void HandleBattlefieldListOpcode( WorldPacket &recv_data );
void HandleLeaveBattlefieldOpcode( WorldPacket &recv_data );
void HandleBattlemasterJoinArena( WorldPacket &recv_data );
void HandleReportPvPAFK( WorldPacket &recv_data );
void HandleWardenDataOpcode(WorldPacket& recv_data);
void HandleWorldTeleportOpcode(WorldPacket& recv_data);
void HandleMinimapPingOpcode(WorldPacket& recv_data);
void HandleRandomRollOpcode(WorldPacket& recv_data);
void HandleFarSightOpcode(WorldPacket& recv_data);
void HandleSetDungeonDifficultyOpcode(WorldPacket& recv_data);
void HandleSetRaidDifficultyOpcode(WorldPacket& recv_data);
void HandleMoveSetCanFlyAckOpcode(WorldPacket& recv_data);
void HandleLfgJoinOpcode(WorldPacket& recv_data);
void HandleLfgLeaveOpcode(WorldPacket& recv_data);
void HandleSearchLfgJoinOpcode(WorldPacket& recv_data);
void HandleSearchLfgLeaveOpcode(WorldPacket& recv_data);
void HandleSetLfgCommentOpcode(WorldPacket& recv_data);
void HandleSetTitleOpcode(WorldPacket& recv_data);
void HandleRealmSplitState(WorldPacket& recv_data);
void HandleTimeSyncResp(WorldPacket& recv_data);
void HandleWhoisOpcode(WorldPacket& recv_data);
void HandleResetInstancesOpcode(WorldPacket& recv_data);
void HandleHearthandResurrect(WorldPacket & recv_data);
// Arena Team
void HandleInspectArenaTeamsOpcode(WorldPacket& recv_data);
void HandleArenaTeamQueryOpcode(WorldPacket& recv_data);
void HandleArenaTeamRosterOpcode(WorldPacket& recv_data);
void HandleArenaTeamInviteOpcode(WorldPacket& recv_data);
void HandleArenaTeamAcceptOpcode(WorldPacket& recv_data);
void HandleArenaTeamDeclineOpcode(WorldPacket& recv_data);
void HandleArenaTeamLeaveOpcode(WorldPacket& recv_data);
void HandleArenaTeamRemoveOpcode(WorldPacket& recv_data);
void HandleArenaTeamDisbandOpcode(WorldPacket& recv_data);
void HandleArenaTeamLeaderOpcode(WorldPacket& recv_data);
void HandleAreaSpiritHealerQueryOpcode(WorldPacket& recv_data);
void HandleAreaSpiritHealerQueueOpcode(WorldPacket& recv_data);
void HandleCancelMountAuraOpcode(WorldPacket& recv_data);
void HandleSelfResOpcode(WorldPacket& recv_data);
void HandleComplainOpcode(WorldPacket& recv_data);
void HandleRequestPetInfoOpcode(WorldPacket& recv_data);
// Socket gem
void HandleSocketOpcode(WorldPacket& recv_data);
void HandleCancelTempEnchantmentOpcode(WorldPacket& recv_data);
void HandleItemRefundInfoRequest(WorldPacket& recv_data);
void HandleChannelVoiceOnOpcode(WorldPacket & recv_data);
void HandleVoiceSessionEnableOpcode(WorldPacket& recv_data);
void HandleSetActiveVoiceChannel(WorldPacket& recv_data);
void HandleSetTaxiBenchmarkOpcode(WorldPacket& recv_data);
// Guild Bank
void HandleGuildPermissions(WorldPacket& recv_data);
void HandleGuildBankMoneyWithdrawn(WorldPacket& recv_data);
void HandleGuildBankerActivate(WorldPacket& recv_data);
void HandleGuildBankQueryTab(WorldPacket& recv_data);
void HandleGuildBankLogQuery(WorldPacket& recv_data);
void HandleGuildBankDepositMoney(WorldPacket& recv_data);
void HandleGuildBankWithdrawMoney(WorldPacket& recv_data);
void HandleGuildBankSwapItems(WorldPacket& recv_data);
void HandleGuildBankUpdateTab(WorldPacket& recv_data);
void HandleGuildBankBuyTab(WorldPacket& recv_data);
void HandleQueryGuildBankTabText(WorldPacket& recv_data);
void HandleSetGuildBankTabText(WorldPacket& recv_data);
// Calendar
void HandleCalendarGetCalendar(WorldPacket& recv_data);
void HandleCalendarGetEvent(WorldPacket& recv_data);
void HandleCalendarGuildFilter(WorldPacket& recv_data);
void HandleCalendarArenaTeam(WorldPacket& recv_data);
void HandleCalendarAddEvent(WorldPacket& recv_data);
void HandleCalendarUpdateEvent(WorldPacket& recv_data);
void HandleCalendarRemoveEvent(WorldPacket& recv_data);
void HandleCalendarCopyEvent(WorldPacket& recv_data);
void HandleCalendarEventInvite(WorldPacket& recv_data);
void HandleCalendarEventRsvp(WorldPacket& recv_data);
void HandleCalendarEventRemoveInvite(WorldPacket& recv_data);
void HandleCalendarEventStatus(WorldPacket& recv_data);
void HandleCalendarEventModeratorStatus(WorldPacket& recv_data);
void HandleCalendarComplain(WorldPacket& recv_data);
void HandleCalendarGetNumPending(WorldPacket& recv_data);
void HandleSpellClick(WorldPacket& recv_data);
void HandleGetMirrorimageData(WorldPacket& recv_data);
void HandleAlterAppearanceOpcode(WorldPacket& recv_data);
void HandleRemoveGlyphOpcode(WorldPacket& recv_data);
void HandleCharCustomizeOpcode(WorldPacket& recv_data);
void HandleQueryInspectAchievementsOpcode(WorldPacket& recv_data);
void HandleEquipmentSetSaveOpcode(WorldPacket& recv_data);
void HandleEquipmentSetDeleteOpcode(WorldPacket& recv_data);
void HandleEquipmentSetUseOpcode(WorldPacket& recv_data);
void HandleUITimeRequestOpcode(WorldPacket& recv_data);
void HandleReadyForAccountDataTimes(WorldPacket& recv_data);
void HandleQueryQuestsCompletedOpcode(WorldPacket& recv_data);
void HandleQuestPOIQueryOpcode(WorldPacket& recv_data);
private:
// private trade methods
void moveItems(Item* myItems[], Item* hisItems[]);
bool VerifyMovementInfo(MovementInfo const& movementInfo, ObjectGuid const& guid) const;
void HandleMoverRelocation(MovementInfo& movementInfo);
void ExecuteOpcode( OpcodeHandler const& opHandle, WorldPacket* packet );
// logging helper
void LogUnexpectedOpcode(WorldPacket *packet, const char * reason);
void LogUnprocessedTail(WorldPacket *packet);
// EnumData helpers
bool CharCanLogin(uint32 lowGUID)
{
return _allowedCharsToLogin.find(lowGUID) != _allowedCharsToLogin.end();
}
// this stores the GUIDs of the characters who can login
// characters who failed on Player::BuildEnumData shouldn't login
std::set<uint32> _allowedCharsToLogin;
uint32 m_GUIDLow; // set logged or recently logout player (while m_playerRecentlyLogout set)
Player *_player;
WorldSocket *m_Socket;
std::string m_Address;
AccountTypes _security;
uint32 _accountId;
uint8 m_expansion;
// Warden
WardenBase *m_Warden;
time_t _logoutTime;
bool m_inQueue; // session wait in auth.queue
bool m_playerLoading; // code processed in LoginPlayer
bool m_playerLogout; // code processed in LogoutPlayer
bool m_playerRecentlyLogout;
bool m_playerSave; // code processed in LogoutPlayer with save request
LocaleConstant m_sessionDbcLocale;
int m_sessionDbLocaleIndex;
uint32 m_latency;
AccountData m_accountData[NUM_ACCOUNT_DATA_TYPES];
uint32 m_Tutorials[8];
TutorialDataState m_tutorialState;
AddonsList m_addonsList;
ACE_Based::LockedQueue<WorldPacket*, ACE_Thread_Mutex> _recvQueue;
};
#endif
/// @}
|
[
"fabian@strawberry-pr0jcts.com"
] |
fabian@strawberry-pr0jcts.com
|
b1ab20b42996148978b000093f2f8118a1372bf6
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_2464487_1/C++/ciceblue/GoogleCodeJam.cpp
|
2d52b7b542969fc37596299fdfb68ed7cffd9d9b
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,002
|
cpp
|
// GoogleCodeJam.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
#define fcin fin
#define fcout fout
ifstream fin("a.in");
ofstream fout("a.out");
int main(int argc, char* argv[])
{
int T;
fcin >> T;
unsigned long long r,t;
unsigned long long sum;
unsigned long long cnt;
unsigned long long left,right;
for(int iCase = 1; iCase <= T; ++iCase)
{
fin >> r >> t;
sum = 0,cnt=0;
left = 1;
right = t/(2*r-1)+10;
if(right > 1000000001)
{
right = 1000000001;
}
while(left < right)
{
cnt = (left+right)/2;
if(2*cnt*r+2*cnt*cnt-cnt>t)
{
right = cnt;
}
else
{
left = cnt+1;
}
}
if(2*cnt*r+2*cnt*cnt-cnt>t) cnt--;
fcout << "Case #" << iCase <<": " << cnt << endl;
cout << "Case #" << iCase <<": " << cnt << endl;
}
return 0;
}
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
6c12b1662b0546c079dd87696bbbb23e5675a031
|
2c33a3bfd10fdab4cd335f28615f61957ed66e88
|
/car_simulation/car_simulation/simulation/car_positions_container.cpp
|
d85d7081e4c48d771f11e3bcb4b0268d04061e09
|
[] |
no_license
|
istrandjev/car-parking-system
|
6c02148a23ef0b44574360e25a3b3d12245fd418
|
c428baa6acb87c0b4bdd76d6a6a1fd519a9375cf
|
refs/heads/master
| 2021-01-20T12:01:21.372201
| 2012-06-26T20:35:52
| 2012-06-26T20:35:52
| 32,250,532
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,096
|
cpp
|
#include "car_positions_container.h"
#include "geometry/bounding_box.h"
#include "simulation/car.h"
namespace simulation {
static const int VERTICAL_CELL_NUM = 200;
static const int HORIZONTAL_CELL_NUM = 300;
void CarPositionEntry::AddCarPosition(int position_index) {
carPositions_.push_back(position_index);
}
const std::vector<int>& CarPositionEntry::GetPositions() const {
return carPositions_;
}
CarPositionsContainer::CarPositionsContainer(
double minx, double maxx, double miny, double maxy)
: minx_(minx), maxx_(maxx), miny_(miny), maxy_(maxy) {
positionsGrid_.resize(VERTICAL_CELL_NUM);
for (int i = 0; i < VERTICAL_CELL_NUM; ++i) {
positionsGrid_[i].resize(HORIZONTAL_CELL_NUM);
}
}
CarPositionsContainer::~CarPositionsContainer() {
for (unsigned i = 0; i < positions_.size(); ++i) {
delete positions_[i];
}
}
void CarPositionsContainer::AddCarPosition(
const CarPosition& position, const geometry::RectangleObject* object) {
int i, j;
GetCellCoordinates(position.GetCenter(), i, j);
positionsGrid_[i][j].AddCarPosition(positions_.size());
unsigned object_index = 0;
std::map<const geometry::RectangleObject*, unsigned>::iterator it =
objectsMap_.find(object);
if (it == objectsMap_.end()) {
object_index = objects_.size();
objectsMap_.insert(std::make_pair(object, object_index));
objects_.push_back(object);
positionsForObjects_.push_back(std::vector<int>());
} else {
object_index = it->second;
}
positionsForObjects_[object_index].push_back(
static_cast<int>(positions_.size()));
positionObjectMap_.push_back(object_index);
positions_.push_back(new CarPosition(position));
}
std::vector<int> CarPositionsContainer::GetPositions(
const geometry::BoundingBox &bounding_box) const {
int mini, maxi, minj, maxj;
geometry::Point lower_left(bounding_box.GetMinX(), bounding_box.GetMinY());
geometry::Point upper_right(bounding_box.GetMaxX(), bounding_box.GetMaxY());
GetCellCoordinates(lower_left, mini, minj);
GetCellCoordinates(upper_right, maxi, maxj);
std::vector<int> result;
for (int i = mini; i <= maxi; ++i) {
for (int j = minj; j <= maxj; ++j) {
const std::vector<int>& positions =
positionsGrid_[i][j].GetPositions();
for (unsigned k = 0; k < positions.size(); ++k) {
const CarPosition* car_position = positions_[positions[k]];
if (bounding_box.Contains(car_position->GetCenter())) {
result.push_back(positions[k]);
}
}
}
}
return result;
}
std::vector<int> CarPositionsContainer::GetPositions() const {
std::vector<int> res;
for (unsigned i = 0; i < positions_.size(); ++i) {
res.push_back(i);
}
return res;
}
const CarPosition* CarPositionsContainer::GetPosition(
int position_index) const {
return positions_[position_index];
}
int CarPositionsContainer::GetNumberOfPositions() const {
return static_cast<int>(positions_.size());
}
unsigned CarPositionsContainer::GetNumberOfObjects() const {
return objects_.size();
}
const geometry::RectangleObject *CarPositionsContainer::GetObject(
int index) const {
return objects_[index];
}
unsigned CarPositionsContainer::GetObjectIndexForPosition(int position_index) {
return positionObjectMap_[position_index];
}
const std::vector<int>& CarPositionsContainer::GetCarPositionsForObject(
int object_index) const {
return positionsForObjects_[object_index];
}
void CarPositionsContainer::GetCellCoordinates(
const geometry::Point &point, int &i, int &j) const {
i = static_cast<int>(((point.x - minx_) * VERTICAL_CELL_NUM) / (maxx_ - minx_));
if (i >= VERTICAL_CELL_NUM) {
i = VERTICAL_CELL_NUM - 1;
}
if (i < 0) {
i = 0;
}
j = static_cast<int>(((point.y - miny_) * HORIZONTAL_CELL_NUM) / (maxy_ - miny_));
if (j >= HORIZONTAL_CELL_NUM) {
j = HORIZONTAL_CELL_NUM - 1;
}
if (j < 0) {
j = 0;
}
}
} // namespace simulation
|
[
"istrandjev@gmail.com@28d065b4-702d-1fc3-fb8c-6eee9887d1d4"
] |
istrandjev@gmail.com@28d065b4-702d-1fc3-fb8c-6eee9887d1d4
|
2cc77a56cd704e6df6876382d2115b9a7c7b2d09
|
7f63ce85c200ed894db5f57c2fbd822954de001a
|
/Assignment1/代码框架/main.cpp
|
7f29143cf6aae08fd10c4e702b8c9f3eccd0c7b6
|
[] |
no_license
|
MuLaF1aga/games101-assignments
|
f03ad6c31cfd7c7642278941927e10d9047e2dfe
|
891788335c7ab971e9039c541bcd3eff86d8d3ab
|
refs/heads/master
| 2023-07-03T15:34:12.541438
| 2021-08-08T14:48:25
| 2021-08-08T14:48:25
| 386,870,688
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,954
|
cpp
|
#include "Triangle.hpp"
#include "rasterizer.hpp"
#include <eigen3/Eigen/Eigen>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <cmath>
constexpr double MY_PI = 3.1415926;
Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
{
Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
Eigen::Matrix4f translate;
translate << 1, 0, 0, -eye_pos[0], 0, 1, 0, -eye_pos[1], 0, 0, 1,
-eye_pos[2], 0, 0, 0, 1;
view = translate * view;
return view;
}
Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
// TODO: Implement this function
// Create the model matrix for rotating the triangle around the Z axis.
// Then return it.
Eigen::Matrix4f model_rotatez;
model_rotatez <<
std::cos(rotation_angle/180.0*MY_PI),-std::sin(rotation_angle/180.0*MY_PI),0,0,
std::sin(rotation_angle/180.0*MY_PI),std::cos(rotation_angle/180.0*MY_PI),0,0,
0,0,1,0,
0,0,0,1;
model = model_rotatez * model;
// Eigen::Matrix4f model_rotatex;
// model_rotatex <<
// 1,0,0,0,
// 0,std::cos(rotation_angle/180.0*MY_PI),-std::sin(rotation_angle/180.0*MY_PI),0,
// 0,std::sin(rotation_angle/180.0*MY_PI),std::cos(rotation_angle/180.0*MY_PI),0,
// 0,0,0,1;
// model = model_rotatex * model;
return model;
}
Eigen::Matrix4f get_rotation(Eigen::Vector3f axis, float angle){
axis = axis.normalized();
Eigen::Matrix4f rotationMat = Eigen::Matrix4f::Identity();
Eigen::Vector3f t(1.0f,2.0f,8.0f);
t = t.normalized();
Eigen::Vector3f u = axis.cross(t).normalized();
Eigen::Vector3f v = axis.cross(u).normalized();
Eigen::Matrix4f rotateAxis;
rotateAxis <<
axis(0),axis(1),axis(2),0,
u(0),u(1),u(2),0,
v(0),v(1),v(2),0,
0,0,0,1;
Eigen::Matrix4f rotateBack = rotateAxis.transpose();
Eigen::Matrix4f model_rotatex;
model_rotatex <<
1,0,0,0,
0,std::cos(angle/180.0*MY_PI),-std::sin(angle/180.0*MY_PI),0,
0,std::sin(angle/180.0*MY_PI),std::cos(angle/180.0*MY_PI),0,
0,0,0,1;
rotationMat = rotateBack * model_rotatex * rotateAxis * rotationMat;
return rotationMat;
}
Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
float zNear, float zFar)
{
// Students will implement this function
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
// TODO: Implement this function
// Create the projection matrix for the given parameters.
// Then return it.
float top = std::tan(eye_fov/180.0*MY_PI) * zNear;
float bottom = -top;
float right = top * aspect_ratio;
float left = -right;
Eigen::Matrix4f move;
move <<
1,0,0,0,
0,1,0,0,
0,0,1,-(zNear+zFar)/2,
0,0,0,1;
Eigen::Matrix4f move_back;
move_back <<
1,0,0,0,
0,1,0,0,
0,0,1,(zNear+zFar)/2,
0,0,0,1;
Eigen::Matrix4f orthographic;
orthographic <<
2/(right-left),0,0,0,
0,2/(top-bottom),0,0,
0,0,2/(zNear-zFar),0,
0,0,0,1;
Eigen::Matrix4f perspective;
perspective <<
zNear,0,0,0,
0,zNear,0,0,
0,0,zNear+zFar,-zNear*zFar,
0,0,1,0;
Eigen::Matrix4f perspective_result;
perspective_result <<
2*zNear/(right-left),0,(left+right)/(left-right),0,
0,2*zNear/(top-bottom),(bottom+top)/(bottom-top),0,
0,0,(zFar+zNear)/(zNear-zFar),2*zFar*zNear/(zFar-zNear),
0,0,1,0;
// projection = perspective_result * projection;
projection = move_back * orthographic * move * perspective * projection;
return projection;
}
int main(int argc, const char** argv)
{
float angle = 0;
float angle_bonus = 0;//bonus
bool command_line = false;
std::string filename = "output.png";
if (argc >= 3) {
command_line = true;
angle = std::stof(argv[2]); // -r by default
if (argc == 4) {
filename = std::string(argv[3]);
}
else
return 0;
}
rst::rasterizer r(700, 700);
Eigen::Vector3f eye_pos = {0, 0, 5};
Eigen::Vector3f axis_bonus = {1, 0, 0};//bonus
std::vector<Eigen::Vector3f> pos{{2, 0, -2}, {0, 2, -2}, {-2, 0, -2}};
std::vector<Eigen::Vector3i> ind{{0, 1, 2}};
auto pos_id = r.load_positions(pos);
auto ind_id = r.load_indices(ind);
int key = 0;
int frame_count = 0;
if (command_line) {
r.clear(rst::Buffers::Color | rst::Buffers::Depth);
r.set_model(get_model_matrix(angle));
r.set_view(get_view_matrix(eye_pos));
r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
r.draw(pos_id, ind_id, rst::Primitive::Triangle);
cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
image.convertTo(image, CV_8UC3, 1.0f);
cv::imwrite(filename, image);
return 0;
}
while (key != 27) {
r.clear(rst::Buffers::Color | rst::Buffers::Depth);
// r.set_model(get_model_matrix(angle));
r.set_model(get_rotation(axis_bonus,angle_bonus));
r.set_view(get_view_matrix(eye_pos));
r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
r.draw(pos_id, ind_id, rst::Primitive::Triangle);
cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
image.convertTo(image, CV_8UC3, 1.0f);
cv::imshow("image", image);
key = cv::waitKey(10);
std::cout << "frame count: " << frame_count++ << '\n';
if (key == 'a') {
angle += 10;
}
else if (key == 'd') {
angle -= 10;
}
else if (key == 'w'){
angle_bonus += 10;
}
else if (key == 's'){
angle_bonus -= 10;
}
}
return 0;
}
|
[
"380650315@qq.com"
] |
380650315@qq.com
|
c1ce03439e983a972b7fa7ca8f516841c9825db7
|
bf9f3889b149cc9885528df8ef8f13bf46bcc197
|
/FWCore/Concurrency/test/limitedtaskqueue_t.cppunit.cpp
|
7c74abcbab0d77b9a0a7e343f93e4f353a3ee9cb
|
[
"Apache-2.0"
] |
permissive
|
cgemmell2/cmssw
|
b601815ceb2d8152d7a1a8933d9f007e50455d64
|
25dd0613be10f0c654f7556670b4968aa6b26122
|
refs/heads/master
| 2021-05-06T09:46:24.987318
| 2017-12-12T17:54:10
| 2017-12-12T17:54:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,656
|
cpp
|
//
// LimitedTaskQueue_test.cpp
// DispatchProcessingDemo
//
// Created by Chris Jones on 9/27/11.
//
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include <unistd.h>
#include <memory>
#include <atomic>
#include "tbb/task.h"
#include "FWCore/Concurrency/interface/LimitedTaskQueue.h"
#include "FWCore/Concurrency/interface/FunctorTask.h"
class LimitedTaskQueue_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(LimitedTaskQueue_test);
CPPUNIT_TEST(testPush);
CPPUNIT_TEST(testPushAndWait);
CPPUNIT_TEST(testPause);
CPPUNIT_TEST(stressTest);
CPPUNIT_TEST_SUITE_END();
public:
void testPush();
void testPushAndWait();
void testPause();
void stressTest();
void setUp(){}
void tearDown(){}
};
CPPUNIT_TEST_SUITE_REGISTRATION( LimitedTaskQueue_test );
void LimitedTaskQueue_test::testPush()
{
{
std::atomic<unsigned int> count{0};
edm::LimitedTaskQueue queue{1};
{
std::shared_ptr<tbb::task> waitTask{new (tbb::task::allocate_root()) tbb::empty_task{},
[](tbb::task* iTask){tbb::task::destroy(*iTask);} };
waitTask->set_ref_count(1+3);
tbb::task* pWaitTask = waitTask.get();
queue.push([&count,pWaitTask]{
CPPUNIT_ASSERT(count++ == 0);
usleep(10);
pWaitTask->decrement_ref_count();
});
queue.push([&count,pWaitTask]{
CPPUNIT_ASSERT(count++ == 1);
usleep(10);
pWaitTask->decrement_ref_count();
});
queue.push([&count,pWaitTask]{
CPPUNIT_ASSERT(count++ == 2);
usleep(10);
pWaitTask->decrement_ref_count();
});
waitTask->wait_for_all();
CPPUNIT_ASSERT(count==3);
}
}
{
std::atomic<unsigned int> count{0};
constexpr unsigned int kMax = 2;
edm::LimitedTaskQueue queue{kMax};
{
std::shared_ptr<tbb::task> waitTask{new (tbb::task::allocate_root()) tbb::empty_task{},
[](tbb::task* iTask){tbb::task::destroy(*iTask);} };
waitTask->set_ref_count(1+3);
tbb::task* pWaitTask = waitTask.get();
queue.push([&count,pWaitTask]{
CPPUNIT_ASSERT(count++ < kMax);
usleep(10);
--count;
pWaitTask->decrement_ref_count();
});
queue.push([&count,pWaitTask]{
CPPUNIT_ASSERT(count++ < kMax);
usleep(10);
--count;
pWaitTask->decrement_ref_count();
});
queue.push([&count,pWaitTask]{
CPPUNIT_ASSERT(count++ < kMax);
usleep(10);
--count;
pWaitTask->decrement_ref_count();
});
waitTask->wait_for_all();
CPPUNIT_ASSERT(count==0);
}
}
}
void LimitedTaskQueue_test::testPushAndWait()
{
{
std::atomic<unsigned int> count{0};
edm::LimitedTaskQueue queue{1};
{
queue.push([&count]{
CPPUNIT_ASSERT(count++ == 0);
usleep(10);
});
queue.push([&count]{
CPPUNIT_ASSERT(count++ == 1);
usleep(10);
});
queue.pushAndWait([&count]{
CPPUNIT_ASSERT(count++ == 2);
usleep(10);
});
CPPUNIT_ASSERT(count==3);
}
}
{
std::atomic<unsigned int> count{0};
std::atomic<unsigned int> countTasksRun{0};
constexpr unsigned int kMax = 2;
edm::LimitedTaskQueue queue{kMax};
{
queue.pushAndWait([&count,&countTasksRun]{
CPPUNIT_ASSERT(count++ < kMax);
usleep(10);
--count;
CPPUNIT_ASSERT( 1==++countTasksRun);
});
queue.pushAndWait([&count,&countTasksRun]{
CPPUNIT_ASSERT(count++ < kMax);
usleep(10);
--count;
CPPUNIT_ASSERT( 2==++countTasksRun);
});
queue.pushAndWait([&count,&countTasksRun]{
CPPUNIT_ASSERT(count++ < kMax);
usleep(10);
--count;
CPPUNIT_ASSERT( 3==++countTasksRun);
});
auto c = count.load();
if( c != 0) {
std::cout <<"ERROR count "<< c<<" != 0"<<std::endl;
}
CPPUNIT_ASSERT(count==0);
auto v = countTasksRun.load();
if(v != 3) {
std::cout <<"ERROR # tasks Run "<< v<<" != 3"<<std::endl;
}
CPPUNIT_ASSERT(v==3);
}
}
}
void LimitedTaskQueue_test::testPause()
{
std::atomic<unsigned int> count{0};
edm::LimitedTaskQueue queue{1};
{
{
std::shared_ptr<tbb::task> waitTask{new (tbb::task::allocate_root()) tbb::empty_task{},
[](tbb::task* iTask){tbb::task::destroy(*iTask);} };
waitTask->set_ref_count(1+3);
tbb::task* pWaitTask = waitTask.get();
edm::LimitedTaskQueue::Resumer resumer;
std::atomic<bool> resumerSet{false};
std::exception_ptr e1;
queue.pushAndPause([&resumer,&resumerSet,&count,&queue,pWaitTask,&e1](edm::LimitedTaskQueue::Resumer iResumer){
resumer = std::move(iResumer);
resumerSet = true;
try {
CPPUNIT_ASSERT(++count == 1);
} catch(...) {
e1 = std::current_exception();
}
pWaitTask->decrement_ref_count();
});
std::exception_ptr e2;
queue.push([&count,&queue,pWaitTask,&e2]{
try{
CPPUNIT_ASSERT(++count == 2);
} catch(...) {
e2 = std::current_exception();
}
pWaitTask->decrement_ref_count();
});
std::exception_ptr e3;
queue.push([&count,&queue,pWaitTask,&e3]{
try {
CPPUNIT_ASSERT(++count == 3);
}catch(...){
e3 = std::current_exception();
}
pWaitTask->decrement_ref_count();
});
usleep(100);
//can't do == since the queue may not have processed the first task yet
CPPUNIT_ASSERT(2>=count);
while(not resumerSet) {}
CPPUNIT_ASSERT(resumer.resume());
waitTask->wait_for_all();
CPPUNIT_ASSERT(count==3);
if(e1) { std::rethrow_exception(e1);}
if(e2) { std::rethrow_exception(e2);}
if(e3) { std::rethrow_exception(e3);}
}
}
}
void LimitedTaskQueue_test::stressTest()
{
constexpr unsigned int kMax = 3;
edm::LimitedTaskQueue queue{kMax};
unsigned int index = 100;
const unsigned int nTasks = 1000;
while(0 != --index) {
std::shared_ptr<tbb::task> waitTask{new (tbb::task::allocate_root()) tbb::empty_task{},
[](tbb::task* iTask){tbb::task::destroy(*iTask);} };
waitTask->set_ref_count(3);
tbb::task* pWaitTask=waitTask.get();
std::atomic<unsigned int> count{0};
std::atomic<unsigned int> nRunningTasks{0};
std::atomic<bool> waitToStart{true};
{
auto j = edm::make_functor_task(tbb::task::allocate_root(),
[&queue,&waitToStart,pWaitTask,&count,&nRunningTasks]{
//gcc 4.7 doesn't preserve the 'atomic' nature of waitToStart in the loop
while(waitToStart.load()) {__sync_synchronize();};
std::shared_ptr<tbb::task> guard{pWaitTask,[](tbb::task*iTask) {
iTask->decrement_ref_count();}};
for(unsigned int i = 0; i<nTasks;++i) {
pWaitTask->increment_ref_count();
queue.push([i,&count,pWaitTask,&nRunningTasks] {
std::shared_ptr<tbb::task> guard{pWaitTask,[](tbb::task*iTask) {
iTask->decrement_ref_count();}};
auto nrt = nRunningTasks++;
if( nrt >= kMax) {
std::cout <<"ERROR "<<nRunningTasks<< " >= "<<kMax<<std::endl;
}
CPPUNIT_ASSERT(nrt < kMax);
++count;
--nRunningTasks;
});
}
});
tbb::task::enqueue(*j);
waitToStart=false;
for(unsigned int i=0; i<nTasks;++i) {
pWaitTask->increment_ref_count();
queue.push([i,&count,pWaitTask,&nRunningTasks] {
std::shared_ptr<tbb::task> guard{pWaitTask,[](tbb::task*iTask) {
iTask->decrement_ref_count();}};
auto nrt = nRunningTasks++;
if( nrt >= kMax) {
std::cout <<"ERROR "<<nRunningTasks<< " >= "<<kMax<<std::endl;
}
CPPUNIT_ASSERT(nrt < kMax);
++count;
--nRunningTasks;
});
}
pWaitTask->decrement_ref_count();
}
waitTask->wait_for_all();
CPPUNIT_ASSERT( 0 == nRunningTasks);
CPPUNIT_ASSERT(2*nTasks==count);
}
}
|
[
"chrisdjones15@gmail.com"
] |
chrisdjones15@gmail.com
|
8d3254692e9b0b633340c8cd0a3d84cc6099d7e7
|
eb8c139fd770be28ac8369e9b6c408d4108e8cac
|
/tests/test_levelSet.cpp
|
8dda9e3420563b73f57ff7077b1064fa52daf01d
|
[
"MIT"
] |
permissive
|
GLorieul/FluidBoxPublic
|
2a10d059956665cf5e2c4f3c69edc83128c2785f
|
a026e16cf5c6efc606832a9f5bdac3738e0062e3
|
refs/heads/master
| 2020-05-25T09:28:30.159826
| 2019-05-21T01:00:45
| 2019-05-21T01:00:45
| 187,735,409
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,318
|
cpp
|
#include <gtest/gtest.h>
#include "levelSet.hpp"
using namespace fb;
TEST(levelSetReinitializer, test)
{
Domain domain(Resolution(9,9), Point(-1.0,-1.0), Distance(2.0,2.0));
LevelSet levelSet(domain, Anchor("C"), GhostCells(1,1,1,1));
LevelSet answer(domain, Anchor("C"), GhostCells(0,0,0,0));
//INITIALISE FIELDS
for(int i=0 ; i < domain.get_resolution().x ; i++) {
for(int j=0 ; j < domain.get_resolution().y ; j++) {
Point here = levelSet.get_positionOfNode(i,j);
levelSet(i,j) = 2.0*(sqrt(here.x*here.x + here.y*here.y) - 0.5);
}
}
// levelSet.display();
//REINITIALIZE LEVEL SET
LevelSetReinitializer reinitializer(levelSet);
reinitializer.reinitialize(levelSet, /*distanceToReinit*/ 1.0);
#if 0
Resolution res = domain.get_resolution();
for(int i = 0 ; i < res.x ; i++) {
for(int j = 0 ; j < res.y ; j++) {
for(int k = 0 ; k < res.z ; k++) {
levelSet(i,j,k) *= 100000.0;
}
}
}
#endif
levelSet.display();
//INITIALIZE ANSWER
answer.setValues({{+0.1863, +0.2575, +0.2604, +0.2564, +0.2548, +0.2564, +0.2604, +0.2575, +0.1863},
{+0.2575, +0.4558, +0.3651, +0.2320, +0.1835, +0.2320, +0.3651, +0.4558, +0.2575},
{+0.2604, +0.3651, +0.1634, -0.0019, -0.0530, -0.0019, +0.1634, +0.3651, +0.2604},
{+0.2564, +0.2320, -0.0019, -0.1727, -0.2756, -0.1727, -0.0019, +0.2320, +0.2564},
{+0.2548, +0.1835, -0.0530, -0.2756, -0.4560, -0.2756, -0.0530, +0.1835, +0.2548},
{+0.2564, +0.2320, -0.0019, -0.1727, -0.2756, -0.1727, -0.0019, +0.2320, +0.2564},
{+0.2604, +0.3651, +0.1634, -0.0019, -0.0530, -0.0019, +0.1634, +0.3651, +0.2604},
{+0.2575, +0.4558, +0.3651, +0.2320, +0.1835, +0.2320, +0.3651, +0.4558, +0.2575},
{+0.1863, +0.2575, +0.2604, +0.2564, +0.2548, +0.2564, +0.2604, +0.2575, +0.1863}});
answer.display();
answer.displayAsImage( ColorMap(Range(-1.0,1.0),"RdBu_r") );
// [check] improve values of answer by displaying results in scientific notation (and hence lower the tolerance)
//PASS OR FAIL TEST
ASSERT_TRUE(answer.equals(levelSet, 5e-2));
}
|
[
"gael.lorieul@coandev.com"
] |
gael.lorieul@coandev.com
|
537d163dab12524b81dd6ed9885ab06d39a65129
|
751e0d30c5699e398c1c81cce6195849d7328b20
|
/Source/WebKit/UIProcess/gtk/ViewGestureControllerGtk.cpp
|
9d0ba2205c704fd42a39d7b4ce974e88cd9a56c9
|
[] |
no_license
|
aswaunni/webkit
|
91f02b22bf9002befdd15d49d477147ab122d870
|
65ba051f1d39c614f148b3c2c552af71e18b29c7
|
refs/heads/master
| 2023-01-24T11:24:12.289987
| 2019-06-20T04:41:54
| 2019-06-20T04:41:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,447
|
cpp
|
/*
* Copyright (C) 2013, 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ViewGestureController.h"
#include "DrawingAreaProxy.h"
#include "WebBackForwardList.h"
namespace WebKit {
using namespace WebCore;
static const Seconds swipeMinAnimationDuration = 100_ms;
static const Seconds swipeMaxAnimationDuration = 400_ms;
static const double swipeAnimationBaseVelocity = 0.002;
// GTK divides all scroll deltas by 10, compensate for that
static const double gtkScrollDeltaMultiplier = 10;
static const double swipeTouchpadBaseWidth = 400;
// This is derivative of the easing function at t=0
static const double swipeAnimationDurationMultiplier = 3;
static const double swipeCancelArea = 0.5;
static const double swipeCancelVelocityThreshold = 0.001;
static const double swipeOverlayShadowOpacity = 0.06;
static const double swipeOverlayDimmingOpacity = 0.12;
static const double swipeOverlayShadowWidth = 81;
static const double swipeOverlayShadowGradientOffsets[] = { 0, 0.03125, 0.0625, 0.0938, 0.125, 0.1875, 0.25, 0.375, 0.4375, 0.5, 0.5625, 0.625, 0.6875, 0.75, 0.875, 1. };
static const double swipeOverlayShadowGradientAlpha[] = { 1, 0.99, 0.98, 0.95, 0.92, 0.82, 0.71, 0.46, 0.35, 0.25, 0.17, 0.11, 0.07, 0.04, 0.01, 0. };
static bool isEventStop(GdkEventScroll* event)
{
#if GTK_CHECK_VERSION(3, 20, 0)
return gdk_event_is_scroll_stop_event(reinterpret_cast<GdkEvent*>(event));
#else
return !event->delta_x && !event->delta_y;
#endif
}
void ViewGestureController::platformTeardown()
{
m_swipeProgressTracker.reset();
if (m_activeGestureType == ViewGestureType::Swipe)
removeSwipeSnapshot();
}
bool ViewGestureController::PendingSwipeTracker::scrollEventCanStartSwipe(GdkEventScroll*)
{
return true;
}
bool ViewGestureController::PendingSwipeTracker::scrollEventCanEndSwipe(GdkEventScroll* event)
{
return isEventStop(event);
}
bool ViewGestureController::PendingSwipeTracker::scrollEventCanInfluenceSwipe(GdkEventScroll* event)
{
GdkDevice* device = gdk_event_get_source_device(reinterpret_cast<GdkEvent*>(event));
GdkInputSource source = gdk_device_get_source(device);
// FIXME: Should it maybe be allowed on mice/trackpoints as well? The GDK_SCROLL_SMOOTH
// requirement already filters out most mice, and it works pretty well on a trackpoint
return gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), nullptr, nullptr) && (source == GDK_SOURCE_TOUCHPAD || source == GDK_SOURCE_TOUCHSCREEN);
}
static bool isTouchEvent(GdkEventScroll* event)
{
GdkDevice* device = gdk_event_get_source_device(reinterpret_cast<GdkEvent*>(event));
GdkInputSource source = gdk_device_get_source(device);
return source == GDK_SOURCE_TOUCHSCREEN;
}
FloatSize ViewGestureController::PendingSwipeTracker::scrollEventGetScrollingDeltas(GdkEventScroll* event)
{
double multiplier = isTouchEvent(event) ? Scrollbar::pixelsPerLineStep() : gtkScrollDeltaMultiplier;
double xDelta, yDelta;
gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), &xDelta, &yDelta);
// GdkEventScroll deltas are inverted compared to NSEvent, so invert them again
return -FloatSize(xDelta, yDelta) * multiplier;
}
bool ViewGestureController::handleScrollWheelEvent(GdkEventScroll* event)
{
return m_swipeProgressTracker.handleEvent(event) || m_pendingSwipeTracker.handleEvent(event);
}
void ViewGestureController::trackSwipeGesture(PlatformScrollEvent event, SwipeDirection direction, RefPtr<WebBackForwardListItem> targetItem)
{
m_swipeProgressTracker.startTracking(WTFMove(targetItem), direction);
m_swipeProgressTracker.handleEvent(event);
}
ViewGestureController::SwipeProgressTracker::SwipeProgressTracker(WebPageProxy& webPageProxy, ViewGestureController& viewGestureController)
: m_viewGestureController(viewGestureController)
, m_webPageProxy(webPageProxy)
{
}
void ViewGestureController::SwipeProgressTracker::startTracking(RefPtr<WebBackForwardListItem>&& targetItem, SwipeDirection direction)
{
if (m_state != State::None)
return;
m_targetItem = targetItem;
m_direction = direction;
m_state = State::Pending;
}
void ViewGestureController::SwipeProgressTracker::reset()
{
m_targetItem = nullptr;
m_state = State::None;
if (m_tickCallbackID) {
GtkWidget* widget = m_webPageProxy.viewWidget();
gtk_widget_remove_tick_callback(widget, m_tickCallbackID);
m_tickCallbackID = 0;
}
m_progress = 0;
m_startProgress = 0;
m_endProgress = 0;
m_startTime = 0_ms;
m_endTime = 0_ms;
m_prevTime = 0_ms;
m_velocity = 0;
m_cancelled = false;
}
bool ViewGestureController::SwipeProgressTracker::handleEvent(GdkEventScroll* event)
{
// Don't allow scrolling while the next page is loading
if (m_state == State::Finishing)
return true;
// Stop current animation, if any
if (m_state == State::Animating) {
GtkWidget* widget = m_webPageProxy.viewWidget();
gtk_widget_remove_tick_callback(widget, m_tickCallbackID);
m_tickCallbackID = 0;
m_cancelled = false;
m_state = State::Pending;
}
if (m_state == State::Pending) {
m_viewGestureController.beginSwipeGesture(m_targetItem.get(), m_direction);
m_state = State::Scrolling;
}
if (m_state != State::Scrolling)
return false;
if (isEventStop(event)) {
startAnimation();
return false;
}
uint32_t eventTime = gdk_event_get_time(reinterpret_cast<GdkEvent*>(event));
double eventDeltaX;
gdk_event_get_scroll_deltas(reinterpret_cast<GdkEvent*>(event), &eventDeltaX, nullptr);
double deltaX = -eventDeltaX;
if (isTouchEvent(event))
deltaX *= (double) Scrollbar::pixelsPerLineStep() / m_webPageProxy.viewSize().width();
else
deltaX *= gtkScrollDeltaMultiplier / swipeTouchpadBaseWidth;
Seconds time = Seconds::fromMilliseconds(eventTime);
if (time != m_prevTime)
m_velocity = deltaX / (time - m_prevTime).milliseconds();
m_prevTime = time;
m_progress += deltaX;
bool swipingLeft = m_viewGestureController.isPhysicallySwipingLeft(m_direction);
float maxProgress = swipingLeft ? 1 : 0;
float minProgress = !swipingLeft ? -1 : 0;
m_progress = clampTo<float>(m_progress, minProgress, maxProgress);
m_viewGestureController.handleSwipeGesture(m_targetItem.get(), m_progress, m_direction);
return true;
}
bool ViewGestureController::SwipeProgressTracker::shouldCancel()
{
bool swipingLeft = m_viewGestureController.isPhysicallySwipingLeft(m_direction);
if (swipingLeft && m_velocity < 0)
return true;
if (!swipingLeft && m_velocity > 0)
return true;
return (abs(m_progress) < swipeCancelArea && abs(m_velocity) < swipeCancelVelocityThreshold);
}
void ViewGestureController::SwipeProgressTracker::startAnimation()
{
m_cancelled = shouldCancel();
m_state = State::Animating;
m_viewGestureController.willEndSwipeGesture(*m_targetItem, m_cancelled);
m_startProgress = m_progress;
if (m_cancelled)
m_endProgress = 0;
else
m_endProgress = m_viewGestureController.isPhysicallySwipingLeft(m_direction) ? 1 : -1;
double velocity = swipeAnimationBaseVelocity;
if ((m_endProgress - m_progress) * m_velocity > 0)
velocity = m_velocity;
Seconds duration = Seconds::fromMilliseconds(std::abs((m_progress - m_endProgress) / velocity * swipeAnimationDurationMultiplier));
duration = clampTo<Seconds>(duration, swipeMinAnimationDuration, swipeMaxAnimationDuration);
GtkWidget* widget = m_webPageProxy.viewWidget();
m_startTime = Seconds::fromMicroseconds(gdk_frame_clock_get_frame_time(gtk_widget_get_frame_clock(widget)));
m_endTime = m_startTime + duration;
m_tickCallbackID = gtk_widget_add_tick_callback(widget, [](GtkWidget*, GdkFrameClock* frameClock, gpointer userData) -> gboolean {
auto* tracker = static_cast<SwipeProgressTracker*>(userData);
return tracker->onAnimationTick(frameClock);
}, this, nullptr);
}
static inline double easeOutCubic(double t)
{
double p = t - 1;
return p * p * p + 1;
}
gboolean ViewGestureController::SwipeProgressTracker::onAnimationTick(GdkFrameClock* frameClock)
{
ASSERT(m_state == State::Animating);
ASSERT(m_endTime > m_startTime);
Seconds frameTime = Seconds::fromMicroseconds(gdk_frame_clock_get_frame_time(frameClock));
double animationProgress = (frameTime - m_startTime) / (m_endTime - m_startTime);
if (animationProgress > 1)
animationProgress = 1;
m_progress = m_startProgress + (m_endProgress - m_startProgress) * easeOutCubic(animationProgress);
m_viewGestureController.handleSwipeGesture(m_targetItem.get(), m_progress, m_direction);
if (frameTime >= m_endTime) {
m_tickCallbackID = 0;
endAnimation();
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
void ViewGestureController::SwipeProgressTracker::endAnimation()
{
m_state = State::Finishing;
m_viewGestureController.endSwipeGesture(m_targetItem.get(), m_cancelled);
}
void ViewGestureController::beginSwipeGesture(WebBackForwardListItem* targetItem, SwipeDirection direction)
{
ASSERT(targetItem);
m_webPageProxy.navigationGestureDidBegin();
willBeginGesture(ViewGestureType::Swipe);
if (auto* snapshot = targetItem->snapshot()) {
m_currentSwipeSnapshot = snapshot;
FloatSize viewSize(m_webPageProxy.viewSize());
if (snapshot->hasImage() && shouldUseSnapshotForSize(*snapshot, viewSize, 0))
m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_for_surface(snapshot->surface()));
Color color = snapshot->backgroundColor();
if (color.isValid()) {
m_backgroundColorForCurrentSnapshot = color;
if (!m_currentSwipeSnapshotPattern) {
double red, green, blue, alpha;
color.getRGBA(red, green, blue, alpha);
m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_rgba(red, green, blue, alpha));
}
}
}
if (!m_currentSwipeSnapshotPattern)
m_currentSwipeSnapshotPattern = adoptRef(cairo_pattern_create_rgb(1, 1, 1));
}
void ViewGestureController::handleSwipeGesture(WebBackForwardListItem*, double, SwipeDirection)
{
gtk_widget_queue_draw(m_webPageProxy.viewWidget());
}
void ViewGestureController::draw(cairo_t* cr, cairo_pattern_t* pageGroup)
{
bool swipingLeft = isPhysicallySwipingLeft(m_swipeProgressTracker.direction());
float progress = m_swipeProgressTracker.progress();
double width = m_webPageProxy.drawingArea()->size().width();
double height = m_webPageProxy.drawingArea()->size().height();
double swipingLayerOffset = (swipingLeft ? 0 : width) + floor(width * progress);
double dimmingProgress = swipingLeft ? 1 - progress : -progress;
double remainingSwipeDistance = dimmingProgress * width;
double shadowFadeDistance = swipeOverlayShadowWidth;
double shadowOpacity = swipeOverlayShadowOpacity;
if (remainingSwipeDistance < shadowFadeDistance)
shadowOpacity = (remainingSwipeDistance / shadowFadeDistance) * swipeOverlayShadowOpacity;
RefPtr<cairo_pattern_t> shadowPattern = adoptRef(cairo_pattern_create_linear(0, 0, -swipeOverlayShadowWidth, 0));
for (int i = 0; i < 16; i++) {
double offset = swipeOverlayShadowGradientOffsets[i];
double alpha = swipeOverlayShadowGradientAlpha[i] * shadowOpacity;
cairo_pattern_add_color_stop_rgba(shadowPattern.get(), offset, 0, 0, 0, alpha);
}
cairo_save(cr);
cairo_rectangle(cr, 0, 0, swipingLayerOffset, height);
cairo_set_source(cr, swipingLeft ? m_currentSwipeSnapshotPattern.get() : pageGroup);
cairo_fill_preserve(cr);
cairo_set_source_rgba(cr, 0, 0, 0, dimmingProgress * swipeOverlayDimmingOpacity);
cairo_fill(cr);
cairo_translate(cr, swipingLayerOffset, 0);
if (progress) {
cairo_rectangle(cr, -swipeOverlayShadowWidth, 0, swipeOverlayShadowWidth, height);
cairo_set_source(cr, shadowPattern.get());
cairo_fill(cr);
}
cairo_rectangle(cr, 0, 0, width - swipingLayerOffset, height);
cairo_set_source(cr, swipingLeft ? pageGroup : m_currentSwipeSnapshotPattern.get());
cairo_fill(cr);
cairo_restore(cr);
}
void ViewGestureController::removeSwipeSnapshot()
{
m_snapshotRemovalTracker.reset();
m_hasOutstandingRepaintRequest = false;
if (m_activeGestureType != ViewGestureType::Swipe)
return;
m_currentSwipeSnapshotPattern = nullptr;
m_currentSwipeSnapshot = nullptr;
m_webPageProxy.navigationGestureSnapshotWasRemoved();
m_backgroundColorForCurrentSnapshot = Color();
didEndGesture();
m_swipeProgressTracker.reset();
}
bool ViewGestureController::beginSimulatedSwipeInDirectionForTesting(SwipeDirection)
{
return false;
}
bool ViewGestureController::completeSimulatedSwipeInDirectionForTesting(SwipeDirection)
{
return false;
}
} // namespace WebKit
|
[
"commit-queue@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc"
] |
commit-queue@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc
|
d102a5ec7a7d1b5e9798b9b577a391ba38a24710
|
ed080011612c9a6d43520218722f3fbfb913fed5
|
/Tool/Camera_Tool.h
|
445c80e2af4ba80dc6c157bc3e19df7605a42c14
|
[] |
no_license
|
iso5930/Direct-3D-Portfolio
|
53e6d6a4f0550000e3a513d2578fea964bd16b67
|
c8480cc23ee07b5f72a667a06f4a1c630c0c02fb
|
refs/heads/master
| 2021-08-23T07:46:28.834635
| 2017-12-04T05:56:27
| 2017-12-04T05:56:27
| 112,998,678
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 555
|
h
|
/*!
* \file Camera_Tool.h
* \date 2016/07/27 19:11
*
* \author Administrator
* Contact: user@company.com
*
* \brief
*
* TODO: long description
*
* \note
*/
#ifndef Camera_Tool_h__
#define Camera_Tool_h__
#include "Camera.h"
class CCamera_Tool : public Engine::CCamera
{
private:
float m_fSpeed;
public:
virtual int Update(void);
public:
HRESULT Initialize(D3DXVECTOR3 vEye, D3DXVECTOR3 vAt);
void KeyCheck(void);
public:
explicit CCamera_Tool(LPDIRECT3DDEVICE9 pDevice);
virtual ~CCamera_Tool(void);
};
#endif // Camera_Tool_h__
|
[
"iso5930@naver.com"
] |
iso5930@naver.com
|
6626ac28766ac27ed3d085877a3f001b7d50b5b2
|
286bf5d8afa9692fdef36ae2171da90d418a0889
|
/PoisonousPlnt.cpp
|
c23b6204bbec46f9eb8ec30d3bb81fe6958aa224
|
[] |
no_license
|
kanglicheng/CompetitiveProgramming
|
6863702712e3c902f1e3b1344b9a17bf611e141d
|
80a0fa8a5bf3793a1300ec15b3c4529e66b157cc
|
refs/heads/master
| 2020-07-07T05:46:01.437467
| 2018-02-17T15:26:13
| 2018-02-17T15:26:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,488
|
cpp
|
#include<bits/stdc++.h>
#define pb push_back
#define MOD (int)(1e9 + 7)
#define N 200000
#define pi pair<int,int>
using namespace std;
#define ll long long
ll arr[N], tree[N], c, a, b, x0, cof[N];
int n, m, type, q;
ll power(ll a, ll b){
if(b == 0) return 1ll;
if(b == 1) return a % MOD;
ll half = power(a, b / 2);
half = (half * half) % MOD;
if(b & 1) half *= a;
return half % MOD;
}
ll modinv(ll a){
return power(a, MOD - 2);
}
ll query(int idx){
ll sum = 0ll;
while(idx > 0){
sum = (tree[idx] + sum) % MOD;
idx -= idx & -idx;
}
return sum;
}
void update(ll val, int idx){
while(idx <= n){
tree[idx] = (tree[idx] + val) % MOD;
idx += idx & -idx;
}
}
void solve(){
cin >> n >> a >> b >> q;
x0 = (1ll * MOD - b) * modinv(a);
x0 = (x0 % MOD + MOD) % MOD;
ll tmp = 1ll;
for(int i = 1; i <= n; i++){
cin >> c;
cof[i] = c % MOD;
arr[i] = (tmp * c) % MOD;
tmp = (tmp * x0) % MOD;
}
for(int i = 1; i <= n; i++){
update(arr[i], i);
}
while(q--){
cin >> type;
if(type == 1){
int i; ll x; cin >> i >> x; i++;
update(-arr[i], i);
x %= MOD;
arr[i] = (x * power(x0, i - 1)) % MOD;
update(arr[i], i);
cof[i] = x % MOD;
}else if(type == 2){
int l, r; cin >> l >> r; l++; r++;
ll sum = query(r) - query(l - 1);
if(x0 == 0 && cof[l] == 0){
cout << "Yes" << endl;
}else if(x0 != 0 && sum == 0){
cout << "Yes" << endl;
}else cout << "No" << endl;
}else{
assert(1 == 2);
}
}
}
int main(){
solve();
return 0;
}
|
[
"lamthao1995@gmail.com"
] |
lamthao1995@gmail.com
|
451a1aff2395969a91398c183bd8dc5f1336d207
|
2bac86d234290f068e0cccc0d5ba7a51db8db617
|
/AI.h
|
009ddbe4a40f309c4eb51b86fbb9f286cd6c5501
|
[] |
no_license
|
schwadyl/Projects
|
0e23ae4fb0b9cf658b9e839c1a555edde5b5ab2d
|
5a0c5371b13ae58a93da5bf32a8c4261e9acf899
|
refs/heads/master
| 2020-10-01T10:56:48.536486
| 2019-12-12T04:41:53
| 2019-12-12T04:41:53
| 227,521,489
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,410
|
h
|
#ifndef _AI_H_
#define _AI_H_
#include <iostream>
#include "Utility.h"
#include "Move.h"
#include "BuildingState.h"
#include "Person.h"
////////////////////////////////////////////////////////
//////// DO NOT MODIFY ANY 😤 CODE IN THIS FILE ////////
/////////// 😡 ANY CONSTANTS/ETC SHOULD 😡 /////////////
////////////// 😡 BE ADDED IN THE .CPP 😡 //////////////
////////////////////////////////////////////////////////
/*
* Requires: buildingState is a valid state representing the current building
* Modifies: Nothing
* Effects: Returns a string that represents the decision the AI makes given the
* current state of the building, which it reads from buildingState.
* The string should share the exact format as a human player's move input.
*/
string getAIMoveString(const BuildingState& buildingState);
/*
* Requires: buildingState is a valid state representing the current building
* move is a pickup move that was generated by getAIMoveString()
* floorToPickup represents the floor the pickup move occurred.
* Modifies: move
* Effects: Returns a string representing which people indices should be picked up
* The string should share the exact format as a human player's pickup list input.
*/
string getAIPickupList(const Move& move, const BuildingState& buildingState, const Floor& floorToPickup);
#endif
|
[
"noreply@github.com"
] |
schwadyl.noreply@github.com
|
5ce3a459dabd22bf068065d5d110b283d7498e45
|
1917cc3414598031b02f6530a48af20ccc5dd2a6
|
/src/base/KikiFace.cpp
|
8d6993652d1f43f430a81154efcad9c1acb333dc
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Unlicense"
] |
permissive
|
Mistress-Anna/kiki
|
8cebcf4b7b737bb214bbea8908bbdc61bc325cb5
|
2f615044d72de6b3ca869e2230abdd0aced2aa00
|
refs/heads/master
| 2022-04-29T16:34:45.812039
| 2018-06-24T09:13:39
| 2020-01-04T23:38:22
| 42,407,357
| 2
| 1
|
Unlicense
| 2022-03-16T08:11:09
| 2015-09-13T18:23:04
|
C++
|
UTF-8
|
C++
| false
| false
| 1,666
|
cpp
|
/*
* KikiFace.cpp
* kiki
*/
#include "KikiFace.h"
// __________________________________________________________________________________________________
KQuaternion KikiFace::orientationForFace ( int face )
{
switch (face % 6)
{
case PZ: return KQuaternion();
case NZ: return KQuaternion::rotationAroundVector(180, KVector(1,0,0));
case PX: return KQuaternion::rotationAroundVector( 90, KVector(0,1,0));
case NX: return KQuaternion::rotationAroundVector(-90, KVector(0,1,0));
case PY: return KQuaternion::rotationAroundVector(-90, KVector(1,0,0));
case NY: return KQuaternion::rotationAroundVector( 90, KVector(1,0,0));
};
return KQuaternion();
}
// __________________________________________________________________________________________________
KVector KikiFace::normalVectorForFace ( int face )
{
float o = (face < 3) ? -1 : 1;
switch (face % 3)
{
case X: return KVector (o, 0, 0);
case Y: return KVector (0, o, 0);
case Z: return KVector (0, 0, o);
}
return KVector();
}
// __________________________________________________________________________________________________
void KikiFace::transformationForFace ( int face, float offset )
{
(offset * normalVectorForFace (face)).glTranslate();
switch (face)
{
case PZ: break;
case NZ: glRotatef (180, 0, 1, 0); break;
case PX: glRotatef ( 90, 0, 1, 0); break;
case NX: glRotatef (-90, 0, 1, 0); break;
case PY: glRotatef (-90, 1, 0, 0); break;
case NY: glRotatef ( 90, 1, 0, 0); break;
}
}
|
[
"monsterkodi@users.sourceforge.net"
] |
monsterkodi@users.sourceforge.net
|
9dcc79dae7f2a788b040a15c40d43e07d5a7feb4
|
7a897ee71adc3f1d80d1f9cf27808bdf5c136108
|
/gTests/main.cpp
|
c64d0a025b5228e39baf9993927c6846553d3ee3
|
[
"MIT"
] |
permissive
|
gabb99/tsjson
|
df5625d2e3c45435ca927f6553fddfba806f4ba0
|
0e1493ae3ee3ba1597e49751dcf714e04c93c88a
|
refs/heads/master
| 2020-04-13T23:56:05.138006
| 2019-01-07T12:15:01
| 2019-01-07T12:15:01
| 163,519,738
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 373
|
cpp
|
//
// main.cpp
// tsjson
//
// Created by Gabriel Beauchemin on 2018-11-27.
// Copyright © 2018 Gabriel Beauchemin. All rights reserved.
//
#include <iostream>
#include "tsobject.hpp"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
int main(int argc, const char * argv[])
{
testing::InitGoogleMock(&argc, const_cast<char**>(argv));
return RUN_ALL_TESTS();
}
|
[
"gbeauchemin@gmail.com"
] |
gbeauchemin@gmail.com
|
e63850c2eb791b53c5e22a9d39e64c602bf08c0a
|
cf5bbf2da605e067b689476757ba90579d331c2d
|
/src/Guidance-SDK-ROS/src/Guidance_Depthimage.cpp
|
d271a59a86d033a0ed3b09a925266f7d798ba9e5
|
[] |
no_license
|
levenberg/DJI2016_Challenge_v1.0
|
b8800819c34abc9b24db390d9754780ec91a2ab3
|
751c04a265d560f6c698b3baaa47265f59932483
|
refs/heads/master
| 2020-03-16T18:25:23.261720
| 2018-05-10T08:36:49
| 2018-05-10T08:36:49
| 132,872,221
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,584
|
cpp
|
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include "DJI_guidance.h"
#include "DJI_utility.h"
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <geometry_msgs/TransformStamped.h> // IMU
#include <geometry_msgs/Vector3Stamped.h> // velocity
#include <sensor_msgs/LaserScan.h> // obstacle distance & ultrasonic
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
ros::Publisher depth_image_pub;
using namespace cv;
#define WIDTH 320
#define HEIGHT 240
#define IMAGE_SIZE (HEIGHT * WIDTH)
char key = 0;
e_vbus_index CAMERA_ID = e_vbus1;
DJI_lock g_lock;
DJI_event g_event;
Mat g_depth(HEIGHT,WIDTH,CV_16SC1);
Mat depth8(HEIGHT, WIDTH, CV_8UC1);
int my_callback(int data_type, int data_len, char *content)
{
g_lock.enter();
/* image data */
if (e_image == data_type && NULL != content)
{
image_data* data = (image_data*)content;
if ( data->m_depth_image[CAMERA_ID] ){
memcpy(g_depth.data, data->m_depth_image[CAMERA_ID], IMAGE_SIZE * 2);
g_depth.convertTo(depth8, CV_8UC1);
imshow("depth", depth8);
//publish depth image
cv_bridge::CvImage depth_16;
g_depth.copyTo(depth_16.image);
depth_16.header.frame_id = "guidance";
depth_16.header.stamp = ros::Time::now();
depth_16.encoding = sensor_msgs::image_encodings::MONO16;
depth_image_pub.publish(depth_16.toImageMsg());
}
key = waitKey(1);
}
g_lock.leave();
g_event.set_event();
return 0;
}
#define RETURN_IF_ERR(err_code) { \
if(err_code) { \
release_transfer(); \
return -1; \
} \
}
int main(int argc, char** argv) {
/* initialize ros */
ros::init(argc, argv, "GuidanceNode");
ros::NodeHandle my_node;
depth_image_pub = my_node.advertise<sensor_msgs::Image>("image",1);
/* initialize guidance */
reset_config();
int err_code = init_transfer();
RETURN_IF_ERR(err_code);
int online_status[CAMERA_PAIR_NUM];
err_code = get_online_status(online_status);
RETURN_IF_ERR(err_code);
// get cali param
stereo_cali cali[CAMERA_PAIR_NUM];
err_code = get_stereo_cali(cali);
RETURN_IF_ERR(err_code);
/* select data */
err_code = select_greyscale_image(CAMERA_ID, true);
RETURN_IF_ERR(err_code);
err_code = select_greyscale_image(CAMERA_ID, false);
RETURN_IF_ERR(err_code);
err_code = select_depth_image(CAMERA_ID);
RETURN_IF_ERR(err_code);
select_imu();
select_ultrasonic();
select_obstacle_distance();
select_velocity();
/* start data transfer */
err_code = set_sdk_event_handler(my_callback);
RETURN_IF_ERR(err_code);
err_code = start_transfer();
RETURN_IF_ERR(err_code);
// for setting exposure
exposure_param para;
para.m_is_auto_exposure = 1;
para.m_step = 10;
para.m_expected_brightness = 120;
para.m_camera_pair_index = CAMERA_ID;
std::cout << "start_transfer" << std::endl;
while (ros::ok())
{
g_event.wait_event();
ros::spinOnce();
}
/* release data transfer */
err_code = stop_transfer();
RETURN_IF_ERR(err_code);
//make sure the ack packet from GUIDANCE is received
sleep(1);
std::cout << "release_transfer" << std::endl;
err_code = release_transfer();
RETURN_IF_ERR(err_code);
return 0;
}
|
[
"luckykelfor@163.com"
] |
luckykelfor@163.com
|
24a1d79bdf91f619937ae63da3a7fd40e11e4f10
|
4d0300263d28fb461f285cc2c3dfd7c51621cb4d
|
/platform/android/ndk/Rtt_AndroidTimer.h
|
38f18584d5c12e668168eb798c200875a6e870d4
|
[
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
coronalabs/corona
|
6a108e8bfc8026e8c85e6768cdd8590b5a83bdc2
|
5e853b590f6857f43f4d1eb98ee2b842f67eef0d
|
refs/heads/master
| 2023-08-30T14:29:19.542726
| 2023-08-22T15:18:29
| 2023-08-22T15:18:29
| 163,527,358
| 2,487
| 326
|
MIT
| 2023-09-02T16:46:40
| 2018-12-29T17:05:15
|
C++
|
UTF-8
|
C++
| false
| false
| 1,313
|
h
|
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#ifndef _Rtt_AndroidTimer_H__
#define _Rtt_AndroidTimer_H__
#include "librtt/Rtt_PlatformTimer.h"
class NativeToJavaBridge;
// ----------------------------------------------------------------------------
namespace Rtt
{
// ----------------------------------------------------------------------------
class AndroidTimer : public PlatformTimer
{
Rtt_CLASS_NO_COPIES( AndroidTimer )
public:
AndroidTimer( MCallback& callback, NativeToJavaBridge *ntjb );
virtual ~AndroidTimer();
public:
virtual void Start();
virtual void Stop();
virtual void SetInterval( U32 milliseconds );
virtual bool IsRunning() const;
private:
bool fRunning;
U32 fInterval;
NativeToJavaBridge *fNativeToJavaBridge;
};
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
#endif // _Rtt_AndroidTimer_H__
|
[
"vlad@coronalabs.com"
] |
vlad@coronalabs.com
|
6c451c5922550c497220affcaff26b1b235534c1
|
e118b47c785aaa6f26301c7567f24e9bacbcc44d
|
/tests/rendertest.cpp
|
504ecfbe5382efd4464ca2f7c1f51f20b3b03998
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
axnjaxn/libbyteimage
|
94b82b691d0ec36510f3919369b765a601420d57
|
ceba2ec2c5b619535c1d773df6d7e29561ceec8e
|
refs/heads/master
| 2021-01-14T12:39:36.210751
| 2015-07-23T17:54:10
| 2015-07-23T17:54:10
| 27,449,545
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,156
|
cpp
|
#include <byteimage/render.h>
#include <byteimage/byteimage_sdl2.h>
using namespace byteimage;
int main(int argc, char* argv[]) {
ByteImage img(256, 256, 3);
DrawLine(img, 0, 0, 255, 255, 255); //White line from top left to bottom right
DrawLine(img, Pt2f(255, 0), Pt2f(0, 255), Color(255, 255, 0), 3); //Yellow line, thickness 3, from top right to bottom left
DrawPoint(img, 128, 128, 0, 255, 255, 9); //Great big cyan point in the middle
DrawRect(img, 192, 0, 300, 255, 128); //Gray partially-offscreen rectangle
DrawRect(img, 0, 192, 255, 300, 64); //Dark Gray partially-offscreen rectangle
DrawRect(img, 0, 0, 4, 0, 0, 255, 0);//Zero-height green rectangle
DrawRect(img, 0, 0, 0, 4, 255, 0, 255);//Zero-width magenta rectangle
std::vector<Pt2f> path;
path.push_back(Pt2f(0, 255));
path.push_back(Pt2f(0, 0));
path.push_back(Pt2f(255, 0));
path.push_back(Pt2f(255, 255));
DrawBezier(img, path, Color(192, 0, 0), 5);
DrawTriangle(img, Pt2f(10, 10), Pt2f(30, 20), Pt2f(0, 40), Color(0, 0, 255));
DrawTriangle(img, Pt2f(10, 50), Pt2f(30, 20), Pt2f(0, 40), Color(0, 255, 0));
Display(img).main();
return 0;
}
|
[
"axnjaxn@axnjaxn.com"
] |
axnjaxn@axnjaxn.com
|
f1fb7a4aace33b058f981a2f097a1045f6942a6d
|
be48cb4b8debf0565c376a5409633933c576c800
|
/Source/MyProject/Private/TankBarrelComponent.cpp
|
2d09189768915ef42c4700fefcfd287835a0718f
|
[] |
no_license
|
natern/04_BattleTank
|
addbae4db5da0d7f0b8540bf17ebae59473a88b2
|
8a2df8ec21a7d94b7d53b23f8c848219ffff1065
|
refs/heads/master
| 2021-08-15T01:48:11.921996
| 2017-11-17T05:50:18
| 2017-11-17T05:50:18
| 109,541,156
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 977
|
cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyProject.h"
#include "TankBarrelComponent.h"
UTankBarrelComponent::UTankBarrelComponent() :
maxDegreesPerSecond(30.f),
minElevationDegrees(0.f),
maxElevationDegrees(35.f)
{
}
void UTankBarrelComponent::ElevateBarrel( float relativePitch)
{
relativePitch = FMath::Clamp<float>(relativePitch, -1.f, 1.f);
FRotator resultElevation(0.f);
resultElevation.Pitch = relativePitch * maxDegreesPerSecond * GetWorld()->GetDeltaSeconds();
resultElevation.Pitch += RelativeRotation.Pitch;
resultElevation.Pitch = FMath::Clamp<float>(resultElevation.Pitch, minElevationDegrees, maxElevationDegrees);
SetRelativeRotation(resultElevation);
}
FVector UTankBarrelComponent::GetProjectileLaunchPosition() const
{
return(GetSocketLocation(FName("LaunchPosition")));
}
FRotator UTankBarrelComponent::GetProjectileLaunchRotation() const
{
return(GetSocketRotation(FName("LaunchPosition")));
}
|
[
"natern@gmail.com"
] |
natern@gmail.com
|
ea95fd09bee1916a98d0cc518a12ddc0def41b04
|
5d83739af703fb400857cecc69aadaf02e07f8d1
|
/Archive2/79/49d1bcd39da26e/main.cpp
|
81801bb1e3d024596031672ed7326087eb2aa132
|
[] |
no_license
|
WhiZTiM/coliru
|
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
|
2c72c048846c082f943e6c7f9fa8d94aee76979f
|
refs/heads/master
| 2021-01-01T05:10:33.812560
| 2015-08-24T19:09:22
| 2015-08-24T19:09:22
| 56,789,706
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 261
|
cpp
|
#include <iostream>
#include <string>
#include <vector>
struct A {
int f() { return 5; }
};
struct B: public A {
void b() {
std::cout << f() << std::endl;
}
};
int main() {
B b{};
b.b();
std::cout << b.f() + 5 << std::endl;
}
|
[
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] |
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
|
5b12a3aeaa1a886bbd9c4eef88e372bfb70c07ec
|
99aaf505f9fae90731aba60fca223abaee228f68
|
/faq/mitbbs/sort_bolt_nut.cpp
|
15f3f44a6167347bc0a077696c59168084ba418f
|
[] |
no_license
|
pamd/foo
|
13c3c354141b456f79274787aeb3e71c1f26e56b
|
52ce658f3adac4aa618706d1256ead26e90ab6fe
|
refs/heads/master
| 2016-09-05T14:35:22.727306
| 2015-12-27T22:42:58
| 2015-12-27T22:42:58
| 31,291,416
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,256
|
cpp
|
/* Facebook Problem:
* http://www.mitbbs.com/article_t/JobHunting/32396691.html
*
* Suppose we have one group of distinct bolts and
* one group of distinct nuts. Each bolt matches a unique nut
* anf vice versa. We also have a robot that can match a certain
* bolt with a certain nut. If bolt is larger than nut, it returns
* 1; if bolt matches nut, it returns 0; if bolt is smaller than
* nut, it returns -1. Design an algorithm to sort both groups
* by calling the robot.
*
* This is actually a variant of Quick Sort. First use a random
* bolt to partition the nut group, then use the nut that matches
* the bolt above to partition the bolt group. Then recursively
* sort the left half of bolt and nut groups and the right half
* of bolt and nut groups.
*/
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
// Three color partition,
// returns index of the element that is equal to pivot.
int partition(vector<int>& group, int lower, int upper, int pivot) {
int left = lower;
int right = upper;
int idx = lower;
while (idx <= right) {
//int x = group[idx];
if (group[idx] < pivot) {
swap(group[left], group[idx]);
left++;
idx++;
}
else if (group[idx] == pivot) {
idx++;
}
else { // group[idx] > pivot
swap(group[idx], group[right]);
right--;
}
}
return left;
}
// Sort bolts and nuts recursively
void sort_bots_nuts(vector<int>& bolts, int b1, int b2,
vector<int>& nuts, int n1, int n2) {
if (b1 >= b2 || n1 >= n2)
return;
int pivot_bolt = bolts[b1];
int p_nut = partition(nuts, n1, n2, pivot_bolt);
int pivot_nut = nuts[p_nut];
int p_bolt = partition(bolts, b1, b2, pivot_nut);
sort_bots_nuts(bolts, b1, p_bolt-1, nuts, n1, p_nut-1);
sort_bots_nuts(bolts, p_bolt+1, b2, nuts, p_nut+1, n2);
}
// Test harness
int main() {
int a[] = { 2, 7, 8, 4, 6, 5, 1 };
vector<int> bolts(a, a + sizeof(a) / sizeof(int));
int b[] = { 4, 8, 6, 1, 2, 5, 7 };
vector<int> nuts(b, b + sizeof(b) / sizeof(int));
sort_bots_nuts(bolts, 0, bolts.size() - 1, nuts, 0, nuts.size() - 1);
for (size_t i = 0; i < nuts.size(); ++i) {
cout << bolts[i] << " " << nuts[i] << endl;
}
return 0;
}
|
[
"dhu@air.local"
] |
dhu@air.local
|
a46b44ef9d07b457dea70340faef39c737bad366
|
444a300b50564ab34020fc4ca6fd54bb8bceba7a
|
/externals/onut/src/UIControl.cpp
|
d24cf2e6625f236dc6abeb1f90c38d247dd09d2d
|
[
"MIT"
] |
permissive
|
ltjax/click_to_repair
|
2700c92695cf8f844f404bead2dcc033b12e9547
|
2fa898da8d10796c90fc16560cd7b26c97f93952
|
refs/heads/master
| 2020-12-26T11:09:41.833793
| 2020-02-09T21:25:00
| 2020-02-09T21:25:00
| 237,490,129
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 47,227
|
cpp
|
// Onut
#include <onut/ContentManager.h>
#include <onut/Crypto.h>
#include <onut/Log.h>
#include <onut/UIButton.h>
#include <onut/UICheckBox.h>
#include <onut/UIComponents.h>
#include <onut/UIContext.h>
#include <onut/UIControl.h>
#include <onut/UIImage.h>
#include <onut/UILabel.h>
#include <onut/UIPanel.h>
#include <onut/UIScrollView.h>
#include <onut/UITextBox.h>
#include <onut/UITreeView.h>
// Private
#include "UIJson.h"
OUIControlRef oUI;
namespace onut
{
// Strings to Enums used for loading/saving
static std::unordered_map<std::string, onut::Align> alignMap = {
{"TOP_LEFT", onut::Align::TopLeft},
{"TOP", onut::Align::Top},
{"TOP_RIGHT", onut::Align::TopRight},
{"LEFT", onut::Align::Left},
{"CENTER", onut::Align::Center},
{"RIGHT", onut::Align::Right},
{"BOTTOM_LEFT", onut::Align::BottomLeft},
{"BOTTOM", onut::Align::Bottom},
{"BOTTOM_RIGHT", onut::Align::BottomRight}
};
static std::unordered_map<std::string, UIControl::DimType> dimTypeMap = {
{"ABSOLUTE", UIControl::DimType::Absolute},
{"RELATIVE", UIControl::DimType::Relative},
{"PERCENTAGE", UIControl::DimType::Percentage}
};
static std::unordered_map<std::string, UIControl::PosType> posTypeMap = {
{"RELATIVE", UIControl::PosType::Relative},
{"PERCENTAGE", UIControl::PosType::Percentage}
};
static std::unordered_map<std::string, UIControl::AnchorType> anchorTypeMap = {
{"PIXEL", UIControl::AnchorType::Pixel},
{"PERCENTAGE", UIControl::AnchorType::Percentage}
};
static std::unordered_map<std::string, UIControl::Type> typeMap = {
{"UIControl", UIControl::Type::Control},
{"UIButton", UIControl::Type::Button},
{"UIPanel", UIControl::Type::Panel},
{"UILabel", UIControl::Type::Label},
{"UIImage", UIControl::Type::Image},
{"UICheckBox", UIControl::Type::CheckBox},
{"UITreeView", UIControl::Type::TreeView},
{"UITextBox", UIControl::Type::TextBox},
{"UIScrollView", UIControl::Type::ScrollView},
};
UIControl::Property::Property()
{
m_szString = nullptr;
m_bool = false;
m_int = 0;
m_float = 0.f;
m_type = Type::Int;
}
UIControl::Property::Property(const rapidjson::Value& jsonNode)
{
m_szString = nullptr;
m_bool = false;
m_int = 0;
m_float = 0.f;
if (jsonNode.IsNumber())
{
if (jsonNode.IsDouble())
{
m_type = Type::Float;
m_float = static_cast<float>(jsonNode.GetDouble());
}
else if (jsonNode.IsInt())
{
m_type = Type::Int;
m_int = jsonNode.GetInt();
}
else
{
assert(false);
}
}
else if (jsonNode.IsBool())
{
m_type = Type::Bool;
m_bool = jsonNode.GetBool();
}
else if (jsonNode.IsString())
{
m_type = Type::String;
auto len = jsonNode.GetStringLength();
auto szString = jsonNode.GetString();
m_szString = new char[len + 1];
memcpy(m_szString, szString, len + 1);
}
else
{
assert(false);
}
}
UIControl::Property::Property(const Property& other)
{
m_szString = nullptr;
m_bool = false;
m_int = 0;
m_float = 0.f;
m_type = other.m_type;
switch (m_type)
{
case Type::Bool:
m_bool = other.m_bool;
break;
case Type::Int:
m_int = other.m_int;
break;
case Type::Float:
m_float = other.m_float;
break;
case Type::String:
{
auto len = strlen(other.m_szString);
m_szString = new char[len + 1];
memcpy(m_szString, other.m_szString, len + 1);
break;
}
}
}
UIControl::Property& UIControl::Property::operator=(const UIControl::Property& other)
{
if (m_type == Type::String)
{
delete[] m_szString;
}
m_szString = nullptr;
m_bool = false;
m_int = 0;
m_float = 0.f;
m_type = other.m_type;
switch (m_type)
{
case Type::Bool:
m_bool = other.m_bool;
break;
case Type::Int:
m_int = other.m_int;
break;
case Type::Float:
m_float = other.m_float;
break;
case Type::String:
{
auto len = strlen(other.m_szString);
m_szString = new char[len + 1];
memcpy(m_szString, other.m_szString, len + 1);
break;
}
}
return *this;
}
UIControl::Property::~Property()
{
if (m_type == Type::String)
{
delete[] m_szString;
}
}
const char* UIControl::Property::getString() const
{
assert(m_type == Type::String);
return m_szString;
}
int UIControl::Property::getInt() const
{
assert(m_type == Type::Int);
return m_int;
}
float UIControl::Property::getFloat() const
{
assert(m_type == Type::Float || m_type == Type::Int);
if (m_type == Type::Float)
{
return m_float;
}
else
{
return static_cast<float>(m_int);
}
}
bool UIControl::Property::getBool() const
{
assert(m_type == Type::Bool || m_type == Type::Int);
if (m_type == Type::Bool)
{
return m_bool;
}
else
{
return m_int ? true : false;
}
}
OUIControlRef UIControl::create()
{
return std::shared_ptr<UIControl>(new UIControl());
}
OUIControlRef UIControl::createFromFile(const std::string& in_filename, OContentManagerRef pContentManager)
{
auto pControl = std::shared_ptr<UIControl>(new UIControl());
if (!pContentManager) pContentManager = oContentManager;
auto filename = oContentManager->findResourceFile(in_filename);
if (filename.empty()) filename = in_filename;
// Open json file
FILE* pFile = nullptr;
#if defined(WIN32)
auto fopenRet = fopen_s(&pFile, filename.c_str(), "r");
assert(!fopenRet);
#else
pFile = fopen(filename.c_str(), "r");
assert(pFile);
#endif
rapidjson::FileStream is(pFile);
rapidjson::Document doc;
doc.ParseStream<0>(is);
pControl->load(doc);
// Close the file
fclose(pFile);
return pControl;
}
UIControl::UIControl()
{
}
bool UIControl::visit(const std::function<bool(const OUIControlRef&, const Rect&)>& callback, const Rect& parentRect)
{
auto worldRect = getWorldRect(parentRect);
if (!callback(OThis, worldRect))
{
return false;
}
for (auto& pChild : m_children)
{
if (!pChild->visit(callback, worldRect))
{
return false;
}
}
return true;
}
bool UIControl::visitChildrenFirst(const std::function<bool(const OUIControlRef&, const Rect&)>& callback, const Rect& parentRect)
{
auto worldRect = getWorldRect(parentRect);
for (auto& pChild : m_children)
{
if (!pChild->visitChildrenFirst(callback, worldRect))
{
return false;
}
}
if (!callback(OThis, worldRect))
{
return false;
}
return true;
}
bool UIControl::visitEnabled(const std::function<bool(const OUIControlRef&, const Rect&)>& callback, const Rect& parentRect)
{
if (!isEnabled) return true;
if (!isVisible) return true;
auto worldRect = getWorldRect(parentRect);
if (!callback(OThis, worldRect))
{
return false;
}
for (auto& pChild : m_children)
{
if (!pChild->visitEnabled(callback, worldRect))
{
return false;
}
}
return true;
}
bool UIControl::visitChildrenFirstEnabled(const std::function<bool(const OUIControlRef&, const Rect&)>& callback, const Rect& parentRect)
{
if (!isEnabled) return true;
if (!isVisible) return true;
auto worldRect = getWorldRect(parentRect);
for (auto& pChild : m_children)
{
if (!pChild->visitChildrenFirstEnabled(callback, worldRect))
{
return false;
}
}
if (!callback(OThis, worldRect))
{
return false;
}
return true;
}
bool UIControl::visitVisible(const std::function<bool(const OUIControlRef&, const Rect&)>& callback, const Rect& parentRect)
{
if (!isVisible) return true;
auto worldRect = getWorldRect(parentRect);
if (!callback(OThis, worldRect))
{
return false;
}
for (auto& pChild : m_children)
{
if (!pChild->visitVisible(callback, worldRect))
{
return false;
}
}
return true;
}
bool UIControl::visitChildrenFirstVisible(const std::function<bool(const OUIControlRef&, const Rect&)>& callback, const Rect& parentRect)
{
if (!isVisible) return true;
auto worldRect = getWorldRect(parentRect);
for (auto& pChild : m_children)
{
if (!pChild->visitChildrenFirstVisible(callback, worldRect))
{
return false;
}
}
if (!callback(OThis, worldRect))
{
return false;
}
return true;
}
void UIControl::load(const rapidjson::Value& jsonNode)
{
rect.x = getJsonFloat(jsonNode["x"]);
rect.y = getJsonFloat(jsonNode["y"]);
rect.z = getJsonFloat(jsonNode["width"], 0.f);
rect.w = getJsonFloat(jsonNode["height"], 0.f);
anchor.x = getJsonFloat(jsonNode["xAnchor"]);
anchor.y = getJsonFloat(jsonNode["yAnchor"]);
align = getJsonEnum(alignMap, jsonNode["align"], onut::Align::TopLeft);
xType = getJsonEnum(posTypeMap, jsonNode["xType"], UIControl::PosType::Relative);
yType = getJsonEnum(posTypeMap, jsonNode["yType"], UIControl::PosType::Relative);
widthType = getJsonEnum(dimTypeMap, jsonNode["widthType"], UIControl::DimType::Absolute);
heightType = getJsonEnum(dimTypeMap, jsonNode["heightType"], UIControl::DimType::Absolute);
xAnchorType = getJsonEnum(anchorTypeMap, jsonNode["anchorType"], UIControl::AnchorType::Percentage);
yAnchorType = getJsonEnum(anchorTypeMap, jsonNode["anchorType"], UIControl::AnchorType::Percentage);
name = getJsonString(jsonNode["name"]);
m_styleName = getJsonString(jsonNode["style"]);
m_style = OHash(m_styleName.c_str());
isEnabled = getJsonBool(jsonNode["enabled"], true);
isVisible = getJsonBool(jsonNode["visible"], true);
isClickThrough = getJsonBool(jsonNode["clickThrough"], false);
clipChildren = getJsonBool(jsonNode["clipChildren"], false);
// Properties
auto& properties = jsonNode["properties"];
if (!properties.IsNull())
{
for (auto it = properties.MemberBegin(); it != properties.MemberEnd(); ++it)
{
m_properties[it->name.GetString()] = Property(it->value);
}
}
// Load children
auto& jsonChildren = jsonNode["children"];
if (jsonChildren.IsArray())
{
auto size = jsonChildren.Size();
for (decltype(size) i = 0; i < size; ++i)
{
auto& jsonChild = jsonChildren[i];
auto jsonChildType = getJsonString(jsonChild["type"], "UIControl");
OUIControlRef pChild;
if (!strcmp(jsonChildType, "UIControl"))
{
pChild = UIControl::create();
}
else if (!strcmp(jsonChildType, "UIButton"))
{
pChild = UIButton::create();
}
else if (!strcmp(jsonChildType, "UIPanel"))
{
pChild = UIPanel::create();
}
else if (!strcmp(jsonChildType, "UILabel"))
{
pChild = UILabel::create();
}
else if (!strcmp(jsonChildType, "UIImage"))
{
pChild = UIImage::create();
}
else if (!strcmp(jsonChildType, "UICheckBox"))
{
pChild = UICheckBox::create();
}
else if (!strcmp(jsonChildType, "UITreeView"))
{
pChild = UITreeView::create();
}
else if (!strcmp(jsonChildType, "UITextBox"))
{
pChild = UITextBox::create();
}
if (!pChild) continue;
add(pChild);
pChild->load(jsonChild);
}
}
}
void UIControl::save(const std::string& filename) const
{
rapidjson::Document doc;
doc.SetObject();
auto& allocator = doc.GetAllocator();
save(doc, allocator);
// Open json file
FILE* pFile = nullptr;
#if defined(WIN32)
auto fopenRet = fopen_s(&pFile, filename.c_str(), "wb");
assert(!fopenRet);
#else
pFile = fopen(filename.c_str(), "wb");
assert(pFile);
#endif
rapidjson::StringBuffer s;
rapidjson::Writer<rapidjson::StringBuffer> writer(s);
doc.Accept(writer);
auto str = s.GetString();
fwrite(str, 1, strlen(str), pFile);
fclose(pFile);
}
void UIControl::save(rapidjson::Value& jsonNode, rapidjson::Allocator& allocator) const
{
setJsonString(jsonNode, "type", enumToString(typeMap, getType()), allocator);
setJsonFloat(jsonNode, "x", rect.x, allocator);
setJsonFloat(jsonNode, "y", rect.y, allocator);
setJsonFloat(jsonNode, "width", rect.z, allocator);
setJsonFloat(jsonNode, "height", rect.w, allocator);
setJsonFloat(jsonNode, "xAnchor", anchor.x, allocator);
setJsonFloat(jsonNode, "yAnchor", anchor.y, allocator);
setJsonString(jsonNode, "align", enumToString(alignMap, align), allocator, "TOP_LEFT");
setJsonString(jsonNode, "xType", enumToString(posTypeMap, xType), allocator, "RELATIVE");
setJsonString(jsonNode, "yType", enumToString(posTypeMap, yType), allocator, "RELATIVE");
setJsonString(jsonNode, "widthType", enumToString(dimTypeMap, widthType), allocator, "ABSOLUTE");
setJsonString(jsonNode, "heightType", enumToString(dimTypeMap, heightType), allocator, "ABSOLUTE");
setJsonString(jsonNode, "xAnchorType", enumToString(anchorTypeMap, xAnchorType), allocator, "PERCENTAGE");
setJsonString(jsonNode, "yAnchorType", enumToString(anchorTypeMap, yAnchorType), allocator, "PERCENTAGE");
setJsonString(jsonNode, "name", name.c_str(), allocator);
setJsonString(jsonNode, "style", m_styleName.c_str(), allocator);
setJsonBool(jsonNode, "enabled", isEnabled, allocator, true);
setJsonBool(jsonNode, "visible", isVisible, allocator, true);
setJsonBool(jsonNode, "clickThrough", isClickThrough, allocator, false);
setJsonBool(jsonNode, "clipChildren", clipChildren, allocator, false);
for (auto& kv : m_properties)
{
switch (kv.second.getType())
{
case Property::Type::Bool:
jsonNode[kv.first.c_str()] = kv.second.getBool();
break;
case Property::Type::Float:
jsonNode[kv.first.c_str()] = kv.second.getFloat();
break;
case Property::Type::Int:
jsonNode[kv.first.c_str()] = kv.second.getInt();
break;
case Property::Type::String:
jsonNode[kv.first.c_str()] = kv.second.getString();
break;
}
}
if (!m_children.empty())
{
rapidjson::Value jsonChildren(rapidjson::kArrayType);
for (auto pChild : m_children)
{
rapidjson::Value jsonChild(rapidjson::kObjectType);
pChild->save(jsonChild, allocator);
jsonChildren.PushBack(jsonChild, allocator);
}
jsonNode.AddMember("children", jsonChildren, allocator);
}
}
void UIControl::operator=(const UIControl& other)
{
isEnabled = other.isEnabled;
isClickThrough = other.isClickThrough;
isVisible = other.isVisible;
clipChildren = other.clipChildren;
rect = other.rect;
align = other.align;
xType = other.xType;
yType = other.yType;
widthType = other.widthType;
heightType = other.heightType;
xAnchorType = other.xAnchorType;
yAnchorType = other.yAnchorType;
anchor = other.anchor;
name = other.name;
pUserData = other.pUserData;
pSharedUserData = other.pSharedUserData;
m_properties = other.m_properties;
m_style = other.m_style;
m_styleName = other.m_styleName;
m_children.clear();
for (auto pChild : other.m_children)
{
add(pChild->copy());
}
}
OUIControlRef UIControl::copy() const
{
OUIControlRef pRet;
switch (getType())
{
case Type::Control:
pRet = UIControl::create();
break;
case Type::Button:
pRet = UIButton::create();
break;
case Type::Panel:
pRet = UIPanel::create();
break;
case Type::Label:
pRet = UILabel::create();
break;
case Type::Image:
pRet = UIImage::create();
break;
case Type::CheckBox:
pRet = UICheckBox::create();
break;
case Type::TreeView:
pRet = UITreeView::create();
break;
case Type::TextBox:
pRet = UITextBox::create();
break;
case Type::ScrollView:
pRet = UIScrollView::create();
break;
default:
assert(false);
break;
}
*pRet.get() = *this;
return pRet;
}
void UIControl::add(OUIControlRef pChild)
{
if (!pChild) return;
if (auto pParent = pChild->m_pParent.lock())
{
pParent->remove(pChild);
}
pChild->m_pParent = OThis;
m_children.push_back(pChild);
}
void UIControl::insert(OUIControlRef pChild, const OUIControlRef& pBefore)
{
if (!pChild) return;
if (auto pParent = pChild->m_pParent.lock())
{
pParent->remove(pChild);
}
size_t i = 0;
for (auto& pC : m_children)
{
if (pC == pBefore) break;
++i;
}
pChild->m_pParent = OThis;
m_children.insert(m_children.begin() + i, pChild);
}
void UIControl::insertAfter(OUIControlRef pChild, const OUIControlRef& pAfter)
{
if (auto pParent = pChild->m_pParent.lock())
{
pParent->remove(pChild);
}
size_t i = 0;
for (auto& pC : m_children)
{
++i;
if (pC == pAfter) break;
}
pChild->m_pParent = OThis;
m_children.insert(m_children.begin() + i, pChild);
}
bool UIControl::insertAt(OUIControlRef pChild, size_t index)
{
if (index > m_children.size()) return false;
if (auto pParent = pChild->m_pParent.lock())
{
pParent->remove(pChild);
}
pChild->m_pParent = OThis;
m_children.insert(m_children.begin() + index, pChild);
return true;
}
void UIControl::remove()
{
if (auto pParent = m_pParent.lock())
{
pParent->remove(OThis);
}
}
void UIControl::remove(OUIControlRef in_pChild)
{
if (in_pChild->m_pParent.lock().get() != this) return;
auto size = m_children.size();
for (decltype(size) i = 0; i < size; ++i)
{
auto pChild = m_children[i];
if (pChild == in_pChild)
{
m_children.erase(m_children.begin() + i);
break;
}
}
in_pChild->m_pParent.reset();
}
void UIControl::removeAll()
{
auto size = m_children.size();
for (decltype(size) i = 0; i < size; ++i)
{
auto pChild = m_children[i];
pChild->m_pParent.reset();
}
m_children.clear();
}
OUIControlRef UIControl::getChild(const std::string& in_name, bool bSearchSubChildren)
{
for (auto pChild : m_children)
{
if (pChild->name == in_name)
{
return pChild;
}
}
if (bSearchSubChildren)
{
for (auto pChild : m_children)
{
auto pRet = pChild->getChild(in_name, bSearchSubChildren);
if (pRet)
{
return pRet;
}
}
}
return nullptr;
}
void UIControl::getChild(const OUIContextRef& context,
const Vector2& mousePos,
bool bSearchSubChildren,
bool bIgnoreClickThrough,
const Rect& parentRect,
OUIControlRef& pHoverControl)
{
if (!isVisible || (isClickThrough && bIgnoreClickThrough)) return;
Rect worldRect = getWorldRect(parentRect);
auto itend = m_children.rend();
for (auto it = m_children.rbegin(); it != itend; ++it)
{
auto pChild = *it;
pChild->getChild(context, mousePos, bSearchSubChildren, bIgnoreClickThrough, worldRect, pHoverControl);
}
if (!pHoverControl)
{
if (mousePos.x >= worldRect.x &&
mousePos.y >= worldRect.y &&
mousePos.x <= worldRect.x + worldRect.z &&
mousePos.y <= worldRect.y + worldRect.w)
{
pHoverControl = OThis;
}
}
}
OUIControlRef UIControl::getChild(const OUIContextRef& context,
const Vector2& mousePos,
bool bSearchSubChildren,
bool bIgnoreClickThrough)
{
Rect parentWorldRect;
if (getParent())
{
parentWorldRect = getParent()->getWorldRect(context);
}
else
{
parentWorldRect = {{0, 0}, context->getScreenSize()};
}
OUIControlRef pHoverControl;
getChild(context, mousePos, bSearchSubChildren, bIgnoreClickThrough, parentWorldRect, pHoverControl);
if (pHoverControl.get() == this)
{
pHoverControl = nullptr;
}
return pHoverControl;
}
void UIControl::setStyle(const char* szStyle)
{
m_styleName = szStyle;
m_style = OHash(szStyle);
}
bool isObstructed(const OUIContextRef& context, const OUIControlRef& pRoot, const OUIControlRef& pControl, const Rect& worldRect)
{
Rect parentRect = {{0, 0}, context->getScreenSize()};
bool passedUs = false;
return !pRoot->visitVisible([&worldRect, &passedUs, pControl](const OUIControlRef& pOther, const Rect& rect)
{
if (pOther == pControl)
{
passedUs = true;
return true;
}
if (!pOther->isClickThrough && passedUs)
{
if (rect.x + rect.z >= worldRect.x &&
rect.x <= worldRect.x + worldRect.z &&
rect.y + rect.w >= worldRect.y &&
rect.y <= worldRect.y + worldRect.w)
{
return false;
}
}
return true;
}, parentRect);
}
bool isReallyVisible(const OUIControlRef& pControl)
{
if (!pControl) return true;
return pControl->isVisible && isReallyVisible(pControl->getParent());
}
bool isReallyEnabled(const OUIControlRef& pControl)
{
if (!pControl) return true;
if (!pControl->getParent())
{
if (pControl != oUI)
{
return false;
}
}
return pControl->isEnabled && isReallyEnabled(pControl->getParent());
}
void UIControl::update(const OUIContextRef& context, const Vector2& mousePos, bool bMouse1Down, bool bMouse2Down, bool bMouse3Down, bool bNavL, bool bNavR, bool bNavU, bool bNavD, bool bControl, float scroll)
{
// Prepare our data
Rect parentRect = {{0, 0}, context->getScreenSize()};
context->m_mouseEvents[0].mousePos = mousePos;
context->m_mouseEvents[0].isMouseDown = bMouse1Down;
context->m_mouseEvents[0].pContext = context;
context->m_mouseEvents[0].button = 1;
context->m_mouseEvents[0].isCtrlDown = bControl;
context->m_mouseEvents[0].scroll = scroll;
context->m_mouseEvents[1].mousePos = mousePos;
context->m_mouseEvents[1].isMouseDown = bMouse2Down;
context->m_mouseEvents[1].pContext = context;
context->m_mouseEvents[1].button = 2;
context->m_mouseEvents[1].isCtrlDown = bControl;
context->m_mouseEvents[1].scroll = scroll;
context->m_mouseEvents[2].mousePos = mousePos;
context->m_mouseEvents[2].isMouseDown = bMouse3Down;
context->m_mouseEvents[2].pContext = context;
context->m_mouseEvents[2].button = 3;
context->m_mouseEvents[2].isCtrlDown = bControl;
context->m_mouseEvents[2].scroll = scroll;
context->m_pHoverControl = nullptr;
// Update UIs
if (context->useNavigation && context->m_pLastHoverControl)
{
if (!isReallyEnabled(context->m_pLastHoverControl) ||
!isReallyVisible(context->m_pLastHoverControl) ||
context->m_pLastHoverControl->isClickThrough ||
isObstructed(context, OThis, context->m_pLastHoverControl, context->m_pLastHoverControl->getWorldRect(context)))
{
context->m_pLastHoverControl = nullptr;
}
}
if (context->useNavigation)
{
if (!context->m_pLastHoverControl)
{
// Find the first unobstructed navigable
visitChildrenFirstEnabled([this, &context](const OUIControlRef& pControl, const Rect& rect) -> bool
{
if (!pControl->isNavigatable()) return true;
if (!isObstructed(context, OThis, pControl, rect))
{
context->m_pHoverControl = pControl;
return false;
}
return true;
}, parentRect);
}
}
else
{
updateInternal(context, parentRect);
}
if (context->useNavigation)
{
if (!context->m_pHoverControl)
{
context->m_pHoverControl = context->m_pLastHoverControl;
}
if (context->m_pHoverControl &&
(bNavR || bNavL || bNavU || bNavD))
{
auto worldRect = context->m_pHoverControl->getWorldRect(context);
auto pPreviousHover = context->m_pHoverControl;
float closest = 10000.f;
float closestH = 10000.f;
// Navigation
if (bNavR)
{
// Find closest down navigable
visitChildrenFirstEnabled([this, pPreviousHover, &context, &worldRect, &closest](const OUIControlRef& pControl, const Rect& rect) -> bool
{
if (!pControl->isNavigatable()) return true;
if (pControl == pPreviousHover) return true;
if (rect.y > worldRect.y + worldRect.w) return true;
if (rect.y + rect.w < worldRect.y) return true;
float distance = rect.x - worldRect.x;
if (distance < closest && distance > 0.f)
{
if (!isObstructed(context, OThis, pControl, rect))
{
closest = distance;
context->m_pHoverControl = pControl;
}
}
return true;
}, parentRect);
}
else if (bNavL)
{
// Find closest down navigable
visitChildrenFirstEnabled([this, pPreviousHover, &context, &worldRect, &closest](const OUIControlRef& pControl, const Rect& rect) -> bool
{
if (!pControl->isNavigatable()) return true;
if (pControl == pPreviousHover) return true;
if (rect.y > worldRect.y + worldRect.w) return true;
if (rect.y + rect.w < worldRect.y) return true;
float distance = worldRect.x - rect.x;
if (distance < closest && distance > 0.f)
{
if (!isObstructed(context, OThis, pControl, rect))
{
closest = distance;
context->m_pHoverControl = pControl;
}
}
return true;
}, parentRect);
}
else if (bNavD)
{
// Find closest down navigable
visitChildrenFirstEnabled([this, pPreviousHover, &context, &worldRect, &closest, &closestH](const OUIControlRef& pControl, const Rect& rect) -> bool
{
if (!pControl->isNavigatable()) return true;
if (pControl == pPreviousHover) return true;
float distance = rect.y - (worldRect.y + worldRect.w);
float distanceH = std::abs(rect.x - worldRect.x);
if ((distance < closest - 16.f && distance > 0.f) ||
(distance < closest + 16.f && distance > 0.f && distanceH < closestH))
{
if (!isObstructed(context, OThis, pControl, rect))
{
closest = distance;
closestH = distanceH;
context->m_pHoverControl = pControl;
}
}
return true;
}, parentRect);
}
else if (bNavU)
{
// Find closest down navigable
visitChildrenFirstEnabled([this, pPreviousHover, &context, &worldRect, &closest, &closestH](const OUIControlRef& pControl, const Rect& rect) -> bool
{
if (!pControl->isNavigatable()) return true;
if (pControl == pPreviousHover) return true;
float distance = worldRect.y - (rect.y + rect.w);
float distanceH = std::abs(rect.x - worldRect.x);
if ((distance < closest - 16.f && distance > 0.f) ||
(distance < closest + 16.f && distance > 0.f && distanceH < closestH))
{
if (!isObstructed(context, OThis, pControl, rect))
{
closest = distance;
closestH = distanceH;
context->m_pHoverControl = pControl;
}
}
return true;
}, parentRect);
}
}
}
// Resolve
context->resolve();
// Send events
context->dispatchEvents();
// Reset for next frame
context->reset();
}
void UIControl::render(const OUIContextRef& context)
{
Rect parentRect = {{0, 0}, context->getScreenSize()};
renderInternal(context, parentRect);
}
Rect UIControl::getWorldRect(const OUIContextRef& context) const
{
if (auto pParent = m_pParent.lock())
{
return std::move(getWorldRect(pParent->getWorldRect(context)));
}
else
{
Rect parentRect = {{0, 0}, context->getScreenSize()};
return std::move(getWorldRect(parentRect));
}
}
Rect UIControl::getWorldRect(const Rect& parentRect) const
{
Rect worldRect;
// Generate position and width values first
switch (xType)
{
case PosType::Relative:
worldRect.x = rect.x;
break;
case PosType::Percentage:
worldRect.x = parentRect.z * rect.x;
break;
}
switch (yType)
{
case PosType::Relative:
worldRect.y = rect.y;
break;
case PosType::Percentage:
worldRect.y = parentRect.w * rect.y;
break;
}
switch (widthType)
{
case DimType::Absolute:
worldRect.z = rect.z;
break;
case DimType::Relative:
worldRect.z = parentRect.z + rect.z;
break;
case DimType::Percentage:
worldRect.z = parentRect.z * rect.z;
break;
}
switch (heightType)
{
case DimType::Absolute:
worldRect.w = rect.w;
break;
case DimType::Relative:
worldRect.w = parentRect.w + rect.w;
break;
case DimType::Percentage:
worldRect.w = parentRect.w * rect.w;
break;
}
// Then do alignement
switch (align)
{
case onut::Align::TopLeft:
worldRect.x = parentRect.x + worldRect.x;
worldRect.y = parentRect.y + worldRect.y;
break;
case onut::Align::Top:
worldRect.x = parentRect.x + parentRect.z * .5f + worldRect.x;
worldRect.y = parentRect.y + worldRect.y;
break;
case onut::Align::TopRight:
worldRect.x = parentRect.x + parentRect.z + worldRect.x;
worldRect.y = parentRect.y + worldRect.y;
break;
case onut::Align::Left:
worldRect.x = parentRect.x + worldRect.x;
worldRect.y = parentRect.y + parentRect.w * .5f + worldRect.y;
break;
case onut::Align::Center:
worldRect.x = parentRect.x + parentRect.z * .5f + worldRect.x;
worldRect.y = parentRect.y + parentRect.w * .5f + worldRect.y;
break;
case onut::Align::Right:
worldRect.x = parentRect.x + parentRect.z + worldRect.x;
worldRect.y = parentRect.y + parentRect.w * .5f + worldRect.y;
break;
case onut::Align::BottomLeft:
worldRect.x = parentRect.x + worldRect.x;
worldRect.y = parentRect.y + parentRect.w + worldRect.y;
break;
case onut::Align::Bottom:
worldRect.x = parentRect.x + parentRect.z * .5f + worldRect.x;
worldRect.y = parentRect.y + parentRect.w + worldRect.y;
break;
case onut::Align::BottomRight:
worldRect.x = parentRect.x + parentRect.z + worldRect.x;
worldRect.y = parentRect.y + parentRect.w + worldRect.y;
break;
}
// Finally anchoring
switch (xAnchorType)
{
case AnchorType::Pixel:
worldRect.x -= anchor.x;
break;
case AnchorType::Percentage:
worldRect.x -= worldRect.z * anchor.x;
break;
}
switch (yAnchorType)
{
case AnchorType::Pixel:
worldRect.y -= anchor.y;
break;
case AnchorType::Percentage:
worldRect.y -= worldRect.w * anchor.y;
break;
}
// Snap to pixels
worldRect.x = std::roundf(worldRect.x);
worldRect.y = std::roundf(worldRect.y);
worldRect.w = std::roundf(worldRect.w);
worldRect.z = std::roundf(worldRect.z);
return std::move(worldRect);
}
void UIControl::updateInternal(const OUIContextRef& context, const Rect& parentRect)
{
if (!isEnabled || !isVisible) return;
Rect worldRect = getWorldRect(parentRect);
// Do children first, inverted
if (context->useNavigation)
{
for (auto pChild : m_children)
{
pChild->updateInternal(context, worldRect);
}
}
else
{
auto itend = m_children.rend();
for (auto it = m_children.rbegin(); it != itend; ++it)
{
auto pChild = *it;
pChild->updateInternal(context, worldRect);
}
}
if (!context->m_pHoverControl && !isClickThrough)
{
auto &mouseEvt = context->m_mouseEvents[0];
if (mouseEvt.mousePos.x >= worldRect.x &&
mouseEvt.mousePos.y >= worldRect.y &&
mouseEvt.mousePos.x <= worldRect.x + worldRect.z &&
mouseEvt.mousePos.y <= worldRect.y + worldRect.w)
{
context->m_mouseEvents[0].localMousePos.x = mouseEvt.mousePos.x - worldRect.x;
context->m_mouseEvents[0].localMousePos.y = mouseEvt.mousePos.y - worldRect.y;
context->m_mouseEvents[1].localMousePos = context->m_mouseEvents[0].localMousePos;
context->m_mouseEvents[2].localMousePos = context->m_mouseEvents[0].localMousePos;
context->m_pHoverControl = OThis;
}
}
}
void UIControl::renderInternal(const OUIContextRef& context, const Rect& parentRect)
{
if (!isVisible) return;
Rect worldRect = getWorldRect(parentRect);
if (clipChildren)
{
context->pushClip(worldRect);
}
renderControl(context, worldRect);
for (auto pChild : m_children)
{
pChild->renderInternal(context, worldRect);
}
if (clipChildren)
{
context->popClip();
}
}
void UIControl::setWorldRect(const Rect& in_rect, const OUIContextRef& context)
{
auto pParent = getParent();
if (pParent)
{
auto parentRect = pParent->getWorldRect(context);
Rect localRect = in_rect;
// Undo anchoring
switch (xAnchorType)
{
case AnchorType::Pixel:
localRect.x += anchor.x;
break;
case AnchorType::Percentage:
localRect.x += localRect.z * anchor.x;
break;
}
switch (yAnchorType)
{
case AnchorType::Pixel:
localRect.y += anchor.y;
break;
case AnchorType::Percentage:
localRect.y += localRect.w * anchor.y;
break;
}
// Undo alignement
switch (align)
{
case onut::Align::TopLeft:
localRect.x = localRect.x - parentRect.x;
localRect.y = localRect.y - parentRect.y;
break;
case onut::Align::Top:
localRect.x = localRect.x - parentRect.x - parentRect.z * .5f;
localRect.y = localRect.y - parentRect.y;
break;
case onut::Align::TopRight:
localRect.x = localRect.x - parentRect.x - parentRect.z;
localRect.y = localRect.y - parentRect.y;
break;
case onut::Align::Left:
localRect.x = localRect.x - parentRect.x;
localRect.y = localRect.y - parentRect.y - parentRect.w * .5f;
break;
case onut::Align::Center:
localRect.x = localRect.x - parentRect.x - parentRect.z * .5f;
localRect.y = localRect.y - parentRect.y - parentRect.w * .5f;
break;
case onut::Align::Right:
localRect.x = localRect.x - parentRect.x - parentRect.z;
localRect.y = localRect.y - parentRect.y - parentRect.w * .5f;
break;
case onut::Align::BottomLeft:
localRect.x = localRect.x - parentRect.x;
localRect.y = localRect.y - parentRect.y - parentRect.w;
break;
case onut::Align::Bottom:
localRect.x = localRect.x - parentRect.x - parentRect.z * .5f;
localRect.y = localRect.y - parentRect.y - parentRect.w;
break;
case onut::Align::BottomRight:
localRect.x = localRect.x - parentRect.x - parentRect.z;
localRect.y = localRect.y - parentRect.y - parentRect.w;
break;
}
// Undo position and width values
switch (xType)
{
case PosType::Relative:
localRect.x = localRect.x;
break;
case PosType::Percentage:
localRect.x = localRect.x / parentRect.z;
break;
}
switch (yType)
{
case PosType::Relative:
localRect.y = localRect.y;
break;
case PosType::Percentage:
localRect.y = localRect.y / parentRect.w;
break;
}
switch (widthType)
{
case DimType::Absolute:
localRect.z = localRect.z;
break;
case DimType::Relative:
localRect.z = localRect.z - parentRect.z;
break;
case DimType::Percentage:
localRect.z = localRect.z / parentRect.z;
break;
}
switch (heightType)
{
case DimType::Absolute:
localRect.w = localRect.w;
break;
case DimType::Relative:
localRect.w = localRect.w - parentRect.w;
break;
case DimType::Percentage:
localRect.w = localRect.w / parentRect.w;
break;
}
rect = std::move(localRect);
}
else
{
rect = in_rect;
}
}
Vector2 UIControl::getAnchorInPixel() const
{
Vector2 ret = anchor;
if (xAnchorType == AnchorType::Percentage)
{
ret.x = ret.x * rect.z;
}
if (yAnchorType == AnchorType::Percentage)
{
ret.y = ret.y * rect.w;
}
return std::move(ret);
}
Vector2 UIControl::getAnchorInPercentage() const
{
Vector2 ret = anchor;
if (xAnchorType == AnchorType::Pixel)
{
ret.x = ret.x / rect.z;
}
if (yAnchorType == AnchorType::Pixel)
{
ret.y = ret.y / rect.w;
}
return std::move(ret);
}
void UIControl::setAnchorPercent(const Vector2& in_anchor)
{
if (xAnchorType == AnchorType::Pixel)
{
anchor.x = rect.z * in_anchor.x;
}
else
{
anchor.x = in_anchor.x;
}
if (yAnchorType == AnchorType::Pixel)
{
anchor.y = rect.w * in_anchor.y;
}
else
{
anchor.y = in_anchor.y;
}
}
UIControl::State UIControl::getState(const OUIContextRef& context) const
{
if (isEnabled)
{
if (context->m_pHoverControl.get() == this)
{
if (context->m_pDownControls[0].get() == this)
{
return State::Down;
}
else
{
return State::Hover;
}
}
else if (context->m_pDownControls[0].get() == this)
{
return State::Hover;
}
else
{
return State::Normal;
}
}
else
{
return State::Disabled;
}
}
bool UIControl::hasFocus(const OUIContextRef& context) const
{
return (context->m_pFocus.get() == this);
}
const UIControl::Property& UIControl::getProperty(const std::string& name) const
{
auto it = m_properties.find(name);
return it->second;
}
};
OUIControlRef OFindUI(const std::string& name)
{
return oUI->getChild(name);
}
OUIControlRef OLoadUI(const std::string& filename)
{
return OUIControl::createFromFile(filename);
}
|
[
"marius.elvert@softwareschneiderei.de"
] |
marius.elvert@softwareschneiderei.de
|
bb7567b11cad5c0cf5438ea283d5dd73225db8e1
|
2c35da61dc41f8ff2c1588a2e66b61ca90cd1f3a
|
/src/lib/entityx/deps/Dependencies.h
|
1bfed72a876d5d3e2002c25336a7c0c3a5203e32
|
[] |
no_license
|
vkaytsanov/AngryBirds
|
5858b3dad02940f21dfa849153a134645ecc2191
|
2cc1a7494f1c2c337461df73c4f43c57bfa57770
|
refs/heads/master
| 2023-06-17T10:27:37.254180
| 2021-07-08T11:37:00
| 2021-07-08T11:37:00
| 364,853,524
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,425
|
h
|
/*
* Copyright (C) 2013 Alec Thomas <alec@swapoff.org>
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* Author: Alec Thomas <alec@swapoff.org>
*/
#pragma once
#include "entityx/System.h"
#include "entityx/Event.h"
#include "entityx/Entity.h"
namespace entityx {
namespace deps {
/**
* An entityx::System for declaring getComponent dependencies.
*
* eg. To declare that a `Physics` getComponent must always be paired with `Position`
* and `Direction` getComponents:
*
* system_manager->add<Dependency<Physics, Position, Direction>>();
*/
template <typename C, typename ... Deps>
class Dependency : public System<Dependency<C, Deps...>>, public Receiver<Dependency<C, Deps...>> {
public:
void receive(const ComponentAddedEvent<C> &event) {
assign<Deps...>(event.entity);
}
void configure(EventManager &events) override {
events.subscribe<ComponentAddedEvent<C>>(*this);
}
void update(EntityManager &entities, EventManager &events, TimeDelta dt) override {}
private:
template <typename D>
void assign(Entity entity) {
if (!entity.getComponent<D>()) entity.addComponent<D>();
}
template <typename D, typename D1, typename ... Ds>
void assign(Entity entity) {
assign<D>(entity);
assign<D1, Ds...>(entity);
}
};
} // namespace deps
} // namespace entityx
|
[
"vkaytsanov@yahoo.com"
] |
vkaytsanov@yahoo.com
|
a1c5b0935061e2ebdee000da918eb02454f67152
|
2efe5186105cf3707b640a693017c55e62344fb7
|
/Beautiful_Pairs.cpp
|
19f07bd9ab5969be2cdf3b0c33134f97aae67175
|
[] |
no_license
|
saraffa13/c-
|
2365f5edec034efc5de192631cda82191ad39220
|
c33cb4f1f024e6b7ebce9c3941478dc2eaf89cf2
|
refs/heads/main
| 2023-08-18T17:04:14.653556
| 2021-10-21T15:12:33
| 2021-10-21T15:12:33
| 385,671,493
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 913
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define IOS \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define ll long long
#define ld long double
#define MAX 1e5 + 1;
void init(ll arr[], ll n)
{
for (ll i = 0; i < n; i++)
cin >> arr[i];
}
// void inita(ll arr[][], ll n,ll m)
// {
// for (ll i = 0; i < n; i++)
// {
// for (ll j = 0; j < m; j++)
// {
// cin>>arr[i][j];
// }
// }
// }
void solve()
{
ll n,count=0;
cin>>n;
ll arr[n];
unordered_map<ll,ll>m;
for(ll i=0;i<n;i++)
{
cin>>arr[i];
m[arr[i]]++;
}
ll ans=0;
for(auto x:m)
{
ans+=(x.second*(n-x.second));
}
cout<<ans<<endl;
}
int main()
{
IOS;
// ll t=1;
ll t;
cin >> t;
while (t--)
solve();
return 0;
}
|
[
"ssaraffa786@gmail.com"
] |
ssaraffa786@gmail.com
|
149e3a0c12757b5c41f16c03ce166a46bf34f6ac
|
f81b774e5306ac01d2c6c1289d9e01b5264aae70
|
/chromeos/services/secure_channel/pending_connection_manager_impl.h
|
b81b0faf8ae252d99332f6fcd431a6ad3c39886e
|
[
"BSD-3-Clause"
] |
permissive
|
waaberi/chromium
|
a4015160d8460233b33fe1304e8fd9960a3650a9
|
6549065bd785179608f7b8828da403f3ca5f7aab
|
refs/heads/master
| 2022-12-13T03:09:16.887475
| 2020-09-05T20:29:36
| 2020-09-05T20:29:36
| 293,153,821
| 1
| 1
|
BSD-3-Clause
| 2020-09-05T21:02:50
| 2020-09-05T21:02:49
| null |
UTF-8
|
C++
| false
| false
| 5,188
|
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 CHROMEOS_SERVICES_SECURE_CHANNEL_PENDING_CONNECTION_MANAGER_IMPL_H_
#define CHROMEOS_SERVICES_SECURE_CHANNEL_PENDING_CONNECTION_MANAGER_IMPL_H_
#include <memory>
#include <vector>
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/macros.h"
#include "chromeos/services/secure_channel/ble_initiator_failure_type.h"
#include "chromeos/services/secure_channel/ble_listener_failure_type.h"
#include "chromeos/services/secure_channel/client_connection_parameters.h"
#include "chromeos/services/secure_channel/connection_attempt.h"
#include "chromeos/services/secure_channel/connection_attempt_delegate.h"
#include "chromeos/services/secure_channel/connection_role.h"
#include "chromeos/services/secure_channel/device_id_pair.h"
#include "chromeos/services/secure_channel/pending_connection_manager.h"
#include "chromeos/services/secure_channel/public/cpp/shared/connection_medium.h"
#include "chromeos/services/secure_channel/public/cpp/shared/connection_priority.h"
#include "device/bluetooth/bluetooth_adapter.h"
namespace chromeos {
namespace secure_channel {
class BleConnectionManager;
// Concrete PendingConnectionManager implementation. This class creates one
// ConnectionAttempt per ConnectionAttemptDetails requested; if more than one
// request shares the same ConnectionAttemptDetails, a single ConnectionAttempt
// attempts a connection for all associated requests.
//
// If a ConnectionAttempt successfully creates a channel, this class extracts
// client data from all requests to the same remote device and alerts its
// delegate, deleting all associated ConnectionAttempts when it is finished.
class PendingConnectionManagerImpl : public PendingConnectionManager,
public ConnectionAttemptDelegate {
public:
class Factory {
public:
static std::unique_ptr<PendingConnectionManager> Create(
Delegate* delegate,
BleConnectionManager* ble_connection_manager,
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter);
static void SetFactoryForTesting(Factory* test_factory);
protected:
virtual ~Factory();
virtual std::unique_ptr<PendingConnectionManager> CreateInstance(
Delegate* delegate,
BleConnectionManager* ble_connection_manager,
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter) = 0;
private:
static Factory* test_factory_;
};
~PendingConnectionManagerImpl() override;
private:
PendingConnectionManagerImpl(
Delegate* delegate,
BleConnectionManager* ble_connection_manager,
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter);
// PendingConnectionManager:
void HandleConnectionRequest(
const ConnectionAttemptDetails& connection_attempt_details,
std::unique_ptr<ClientConnectionParameters> client_connection_parameters,
ConnectionPriority connection_priority) override;
// ConnectionAttemptDelegate:
void OnConnectionAttemptSucceeded(
const ConnectionDetails& connection_details,
std::unique_ptr<AuthenticatedChannel> authenticated_channel) override;
void OnConnectionAttemptFinishedWithoutConnection(
const ConnectionAttemptDetails& connection_attempt_details) override;
void HandleBleRequest(
const ConnectionAttemptDetails& connection_attempt_details,
std::unique_ptr<ClientConnectionParameters> client_connection_parameters,
ConnectionPriority connection_priority);
void HandleBleInitiatorRequest(
const ConnectionAttemptDetails& connection_attempt_details,
std::unique_ptr<ClientConnectionParameters> client_connection_parameters,
ConnectionPriority connection_priority);
void HandleBleListenerRequest(
const ConnectionAttemptDetails& connection_attempt_details,
std::unique_ptr<ClientConnectionParameters> client_connection_parameters,
ConnectionPriority connection_priority);
void HandleNearbyRequest(
const ConnectionAttemptDetails& connection_attempt_details,
std::unique_ptr<ClientConnectionParameters> client_connection_parameters,
ConnectionPriority connection_priority);
void RemoveMapEntriesForFinishedConnectionAttempt(
const ConnectionAttemptDetails& connection_attempt_details);
base::flat_map<DeviceIdPair,
std::unique_ptr<ConnectionAttempt<BleInitiatorFailureType>>>
id_pair_to_ble_initiator_connection_attempts_;
base::flat_map<DeviceIdPair,
std::unique_ptr<ConnectionAttempt<BleListenerFailureType>>>
id_pair_to_ble_listener_connection_attempts_;
base::flat_map<ConnectionDetails, base::flat_set<ConnectionAttemptDetails>>
details_to_attempt_details_map_;
BleConnectionManager* ble_connection_manager_;
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter_;
DISALLOW_COPY_AND_ASSIGN(PendingConnectionManagerImpl);
};
} // namespace secure_channel
} // namespace chromeos
#endif // CHROMEOS_SERVICES_SECURE_CHANNEL_PENDING_CONNECTION_MANAGER_IMPL_H_
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
54bbdbfcaa0f135d7325f15ae9449e5fd5bedbe5
|
aaa9d1fa1aee3b8e30add439cf799be8004f1e28
|
/for_offer/06_min_of_rotate_array.cpp
|
f0d8776a4bb82cf971c98368eba75fad0f8cdeb5
|
[] |
no_license
|
Arjen0130/new_code
|
7dc909fb773a1f858e7183619c93a68438de8a5a
|
9d4e39dec4c8e298f66933482e9214f02ad0794d
|
refs/heads/master
| 2020-03-27T18:15:09.666773
| 2018-09-30T05:15:26
| 2018-09-30T05:15:26
| 146,908,857
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 938
|
cpp
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
题目:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
*/
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
int size = rotateArray.size();
if (0 >= size)
{
return 0;
}
int min = rotateArray[0];
for (int i = 1; i < size; i++)
{
if (rotateArray[i] < min)
{
min = rotateArray[i];
break;
}
}
return min;
}
};
int main()
{
Solution solution;
return 0;
}
|
[
"friendship0130@yeah.net"
] |
friendship0130@yeah.net
|
facb010ea18ab42aa6c1f13dece6f0cb650c60ec
|
b0cf510695a0062dbc0651df7085c347b7974bc2
|
/welcomewidget.h
|
9c0b2b1b7c15efe8190aad3fdf4950ed352d2021
|
[] |
no_license
|
semahkadri/Smart_Cinema-Application-Desktop-
|
acb138a1ed2707386cfb80835e93260de5871298
|
3aad23e3ce1f6e8a719d073a9de37d5606ce185c
|
refs/heads/master
| 2023-06-29T09:11:38.771672
| 2020-12-30T21:35:47
| 2020-12-30T21:35:47
| 314,355,134
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 367
|
h
|
#ifndef WELCOMEWIDGET_H
#define WELCOMEWIDGET_H
#include <QWidget>
#include <QPropertyAnimation>
#include "qtmaterialraisedbutton.h"
#include "qtmaterialtextfield.h"
class welcomewidget : public QWidget
{
Q_OBJECT
public:
explicit welcomewidget(QWidget *parent = nullptr);
private:
QWidget *Gw;
signals:
};
#endif // WELCOMEWIDGET_H
|
[
"noreply@github.com"
] |
semahkadri.noreply@github.com
|
b8e3d806f0cb504603257c98e03e6bf5808f752c
|
f9bf7e7aa1182e47fca41b6795c73c54cd57af24
|
/TD3/exo4CorrProf.cpp
|
d91d336498d5e0ca8343c9684412c67da97f3ecf
|
[] |
no_license
|
apolloLemon/algorithmique_s3
|
4160776905ad5d944f911cb258417a52fdc718b7
|
2737f3ed73771d2091eab1daace629d36202fa30
|
refs/heads/master
| 2020-03-30T12:18:51.575022
| 2018-12-15T15:07:02
| 2018-12-15T15:07:02
| 151,218,668
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 260
|
cpp
|
void long_chemin (mat G, int S, tab &M, tab &longeur){
M[s]=true;
printf("%d est visite a une distance de %d de la source",s,longeur[s]);
for(i<SIZE){
if(G[s][i]!=-1 && (!M[i])){
longeur[i] = longeur[s]+G[s][i];
long_chemin(G,i,M,longeur);
}
}
}
|
[
"matthew@coyle.fr"
] |
matthew@coyle.fr
|
d0c8a13097f56f70812f633306e53c73097a3002
|
4c39ed31fe1268302952bbe5c2cd456c8083281e
|
/ProjectEuler/99.cpp
|
37cae8fc41ef322921ea55f151b4a21dd6031e60
|
[] |
no_license
|
Abhay4/Algorithm
|
37e3b8bd3c9990b896d862f1aa20ad8312f20e75
|
50b157e027c7f0c085a8a15929422e75851fafc4
|
refs/heads/master
| 2020-12-11T01:37:58.200719
| 2018-01-24T18:24:05
| 2018-01-24T18:24:05
| 38,934,843
| 0
| 0
| null | 2015-07-11T17:46:17
| 2015-07-11T17:46:17
| null |
UTF-8
|
C++
| false
| false
| 1,528
|
cpp
|
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <set>
#include <cmath>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
typedef long long LL;
vector<string> split( const string& s, const string& delim =" " ) {
vector<string> res;
string t;
for ( int i = 0 ; i != s.size() ; i++ ) {
if ( delim.find( s[i] ) != string::npos ) {
if ( !t.empty() ) {
res.push_back( t );
t = "";
}
} else {
t += s[i];
}
}
if (!t.empty() ) {
res.push_back(t);
}
return res;
}
vector<int> splitInt( const string& s, const string& delim =" " ) {
vector<string> tok = split( s, delim );
vector<int> res;
for ( int i = 0 ; i != tok.size(); i++ )
res.push_back( atoi( tok[i].c_str() ) );
return res;
}
LL gcd(LL a,LL b){
return b?gcd(b,a%b):a;
}
inline LL lcm(LL a,LL b){
return a/gcd(a,b)*b;
}
int s2i(string s) {
stringstream ss;
ss << s;
int res;
ss >> res;
return res;
}
string i2s(int n) {
stringstream ss;
ss << n;
string res;
ss >> res;
return res;
}
void run() {
double ret = 0;
int idx = 0, now = 0;
string str;
while (cin >> str) {
++now;
vector<int> mm = splitInt(str, ",");
double base = mm[0];
double exp = mm[1];
double val = exp * log(base);
if (val > ret) {
ret = val;
idx = now;
}
}
cout << idx << endl;
}
int main() {
run();
}
|
[
"wendai@wendai1026.redmond.corp.microsoft.com"
] |
wendai@wendai1026.redmond.corp.microsoft.com
|
ad498a296bcbd31a31b31922276203e1a66dc5aa
|
9d672dec24baa22c51ad51fa73f1af1cbe07c3a2
|
/PO-pollard.hpp
|
f8370bb1449f3f79f5437d3fde11ff53665e548c
|
[] |
no_license
|
tomorrowzhuwt/rho-pollard
|
cd0b2596d0c6d0cb4b3b736be545b5e787571e6c
|
928bd36aba99dc7aa386d941be4ce7074f70fa9a
|
refs/heads/master
| 2020-03-19T03:17:06.830962
| 2016-05-08T13:59:08
| 2016-05-08T13:59:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,436
|
hpp
|
#ifndef PO_POLLARD_HPP_INCLUDED
#define PO_POLLARD_HPP_INCLUDED
/** \file PO-pollard.hpp
*
* \brief rho-Pollard & GCD implementaion
*
* \author Strizhniou Fiodar
* \copyright Creative Commons Attribution-NonCommercial-ShareAlike
*/
#include <iostream>
#include <assert.h>
/** \brief Binary GCD algorithm.
*
* GCD is well-known algorithm named great common divisor.
* Implementation binary GCD algorithm.
* This function accepts only integers.
*
* \return always GCD > 0
*
*/
template <typename T>
T gcd(T a, T b){
static_assert(std::is_integral<T>::value, "Only integer types allowed");
if(a<0) a=-a;
if(b<0) b=-b;
if(a%b==0) return b;
if(b%a==0) return a;
if(b==0) return (a>0)? a : -a;
T c = 1;
while((a%2 == 0)&&(b%2 == 0)){
a>>=1;
b>>=1;
c<<=1;
}
while(a!=b){
if(a%2 == 0)
a>>=1;
if(b%2 == 0)
b>>=1;
if(a>b)
a-=b;
if(b>a)
b-=a;
}
return c*a;
}
/** \brief Find polynomial result
* Internal component PoPollard(T src).
* \param x used to compute polynomial
* \param a used to change polynomial computation
* \param c used to change polynomial computation
* \param modN used to find remainder of division
* \return integer
*
*/
template <typename T>
T fx(T x, T a, T c, T modN){
auto tmp = (a*x*x + c)%modN;
// assert(tmp==0); // for tested simple numbers always tmp==0
return tmp;
}
/** \brief Rho-Pollard algorithm
*
* This is rho-Pollard algorithm implementation.
* It used to find smallest divisor.
* \param accepts only integers.
* \return smallest divisor
*
*/
template <typename T>
T PoPollard(T src){
static_assert(std::is_integral<T>::value, "Only integer types allowed");
if(src == 0){
std::cout << "argument shall not be zero!\n";
return -1;
}
T x1=2, x2=2, a=1, c=1, d=1;
while(d==1){
x1=fx(x1, a, c, src);
x2=fx(fx(x2, a, c, src), a, c, src);
if(x2==0) return 1; // looks like when src is simple number f(f(x))==0
if(x1==x2){
x1=2, x2=2;
a++;
continue;
}
d=gcd(abs(x1-x2), src);
std::cout << "*";
}
assert(src%d == 0);
return d;
}
#endif // PO_POLLARD_HPP_INCLUDED
|
[
"fedor_qd@mail.ru"
] |
fedor_qd@mail.ru
|
991125e0744c6eaa4b1c4aec52b819f5748d412f
|
5eac322d96620863c35f0aad1bd346d311e42724
|
/LeetCode/Array/Missing Number.cpp
|
efa677adef0fc2e9092566df93627e4e7a2562aa
|
[] |
no_license
|
ceosss/coding
|
fcff2934b9b3942e541ea8b9bac2f00dfc5f7fc0
|
26606ee955ca362539fd06cade7fca37f608e066
|
refs/heads/master
| 2023-09-02T18:17:08.291926
| 2021-11-19T15:33:51
| 2021-11-19T15:33:51
| 262,366,409
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 730
|
cpp
|
class Solution
{
public:
int missingNumber(vector<int> &nums)
{
// TC - o(n)
int n = nums.size();
int sum_original = (n * (n + 1)) / 2;
int sum_found = 0;
for (auto i : nums)
sum_found += i;
return sum_original - sum_found;
// TC - o(n^2)
// int n = nums.size();
// for(int i=0;i<=n;i++)
// {
// bool found = false;
// for(int j=0;j<n;j++){
// if(nums[j]==i){
// found = true;
// goto check;
// }
// }
// check:
// if(!found)
// return i;
// }
// return -1;
}
};
|
[
"sswarajsamant@gmail.com"
] |
sswarajsamant@gmail.com
|
02764b1715c3f7e829dafe70c263e15a48edd34d
|
0ef832d8eaedc16253cc220bc704a52597d248fe
|
/newntui/discovermdi/src/dormantprocessor.cpp
|
1595a9212e6b0fcad5843f764bde29d84a57f04a
|
[
"BSD-2-Clause"
] |
permissive
|
radtek/software-emancipation-discover
|
9c0474b1abe1a8a3f91be899a834868ee0edfc18
|
bec6f4ef404d72f361d91de954eae9a3bd669ce3
|
refs/heads/master
| 2020-05-24T19:03:26.967346
| 2015-11-21T22:23:54
| 2015-11-21T22:23:54
| 187,425,106
| 1
| 0
|
BSD-2-Clause
| 2019-05-19T02:26:08
| 2019-05-19T02:26:07
| null |
UTF-8
|
C++
| false
| false
| 7,156
|
cpp
|
/*************************************************************************
* Copyright (c) 2015, Synopsys, Inc. *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
*************************************************************************/
// DormantProcessor.cpp : implementation file
//
#include "stdafx.h"
#include "discovermdi.h"
#include "DormantProcessor.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDormantProcessor
IMPLEMENT_DYNCREATE(CDormantProcessor, CFormView)
CDormantProcessor::CDormantProcessor()
: CFormView(CDormantProcessor::IDD)
{
//{{AFX_DATA_INIT(CDormantProcessor)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_bLicensed = false;
}
CDormantProcessor::~CDormantProcessor()
{
}
void CDormantProcessor::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDormantProcessor)
DDX_Control(pDX, IDC_RUNDORMANT, m_StartButton);
DDX_Control(pDX, IDC_DORMANTTITLE, m_DormantTitle);
DDX_Control(pDX, IDC_DATASOURCE, m_DataSource);
DDX_Control(pDX, IDC_DORMANTSELECTION, m_SelectionList);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDormantProcessor, CFormView)
//{{AFX_MSG_MAP(CDormantProcessor)
ON_WM_CREATE()
ON_BN_CLICKED(IDC_RUNDORMANT, OnRunDormant)
ON_WM_SIZE()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDormantProcessor diagnostics
#ifdef _DEBUG
void CDormantProcessor::AssertValid() const
{
CFormView::AssertValid();
}
void CDormantProcessor::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CDormantProcessor message handlers
void CDormantProcessor::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
CString query="license v co";
BSTR sysQuery=query.AllocSysString();
CString res = m_DataSource.AccessSync(&sysQuery);
SysFreeString(sysQuery);
if(res!="1") {
MessageBox("No Dormant license is available.","Error",MB_OK|MB_ICONERROR);
CFrameWnd* pParent = this->GetParentFrame();
pParent->PostMessage(WM_CLOSE);
} else
m_bLicensed = true;
if(m_Updated!=TRUE) {
SIZE sizeTotal;
sizeTotal.cx=150;
sizeTotal.cy=150;
SetScrollSizes( MM_TEXT, sizeTotal);
m_Updated=TRUE;
LPDISPATCH lpDispatch;
m_DataSource.GetControlUnknown()->QueryInterface(IID_IDispatch,(void **)&lpDispatch);
m_SelectionList.SetDataSource(lpDispatch);
CRect w;
GetClientRect(w);
int cx=w.Width();
int cy=w.Height();
if(cx<150) cx=150;
if(cy<150) cy=150;
if(::IsWindow(m_DormantTitle)) {
CRect titleRect;
CRect startRect;
m_DormantTitle.GetWindowRect(&titleRect);
m_StartButton.GetWindowRect(&startRect);
int ypos=5;
m_DormantTitle.MoveWindow(5,ypos,cx-5,titleRect.Height());
ypos+=titleRect.Height()+5;
m_SelectionList.MoveWindow(0,ypos,cx,cy-titleRect.Height()-startRect.Height()-20);
ypos+=cy-titleRect.Height()-startRect.Height()-15;
m_StartButton.MoveWindow((cx-startRect.Width()-10)/2,ypos,startRect.Width(),startRect.Height());
}
UpdateSelection();
}
}
int CDormantProcessor::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFormView::OnCreate(lpCreateStruct) == -1)
return -1;
m_Updated=FALSE;
return 0;
}
void CDormantProcessor::UpdateSelection() {
CString query;
BSTR sysQuery;
// Set Dormant mode selection variable
query="set DormantSelection [nil_set]; sappend $DormantSelection $DiscoverSelection";
sysQuery=query.AllocSysString();
m_DataSource.AccessOutput(&sysQuery);
SysFreeString(sysQuery);
m_SelectionList.SetFullListName("DormantSelection");
m_SelectionList.SetFilterListName("DormantSelection_F");
m_SelectionList.SetSelectionName("DormantSelection_S");
m_SelectionList.SetQuery("");
m_SelectionList.Update();
}
void CDormantProcessor::OnRunDormant() {
CString query;
BSTR sysQuery;
// Set Dormant mode selection variable
query="RunDormantCodeAnalysis";
sysQuery=query.AllocSysString();
m_DataSource.AccessOutput(&sysQuery);
SysFreeString(sysQuery);
// Notifying user that the executinp process is finished.
MessageBox("Dormant code analysis completed.\nUse group manager to browse results.","Dormant",MB_OK | MB_ICONINFORMATION);
GetParent()->SendMessage(WM_UPDATEGROUPS,0,0);
}
void CDormantProcessor::OnSize(UINT nType, int cx, int cy)
{
CFormView::OnSize(nType, cx, cy);
if(cx<150) cx=150;
if(cy<150) cy=150;
CRect titleRect;
CRect startRect;
if(::IsWindow(m_DormantTitle)) {
m_DormantTitle.GetWindowRect(&titleRect);
m_StartButton.GetWindowRect(&startRect);
int ypos=5;
m_DormantTitle.MoveWindow(5,ypos,cx-5,titleRect.Height());
ypos+=titleRect.Height()+5;
m_SelectionList.MoveWindow(0,ypos,cx,cy-titleRect.Height()-startRect.Height()-20);
ypos+=cy-titleRect.Height()-startRect.Height()-15;
m_StartButton.MoveWindow((cx-startRect.Width()-10)/2,ypos,startRect.Width(),startRect.Height());
}
}
void CDormantProcessor::OnDestroy()
{
if(m_bLicensed) {
CString query="license v ci";
BSTR sysQuery=query.AllocSysString();
m_DataSource.AccessSync(&sysQuery);
SysFreeString(sysQuery);
}
CFormView::OnDestroy();
}
|
[
"ktransue@synopsys.com"
] |
ktransue@synopsys.com
|
a1b66521bfa9490197f39500c3814c0b11c8dc92
|
ac4c1958e54535b2e712c22ced38a41627c80107
|
/server/interface/ipriv.h
|
7849f5cbd7cf05ef6431afefd68248587e757f13
|
[] |
no_license
|
koziolekrg/b1chat
|
8c57b47f69c31412e025df4c2be94d17d3bd13bf
|
2be0859e97010050750473ddb93ab62ec5615fe8
|
refs/heads/master
| 2020-04-14T04:10:38.153417
| 2016-10-12T11:50:55
| 2016-10-12T11:50:55
| 68,181,039
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 359
|
h
|
#ifndef IPRIV_H
#define IPRIV_H
#include <string>
#include <vector>
class IPriv
{
public:
virtual ~IPriv(){};
virtual bool addNewGroup(std::string title, int16_t client) = 0 ;
virtual bool addNewClientToGroup(std::string title, int16_t client) = 0 ;
virtual std::vector <int16_t> getClients(std::string a_title) = 0 ;
};
#endif // IPRIV_H
|
[
"koziolekrg@gmail.com"
] |
koziolekrg@gmail.com
|
78ecec879b409cb576bac43c8495ef4f71056396
|
b66cc73bc19dc7127a7d77833e9010b8c791ad36
|
/lab6/Solve/Solve/Controller.cpp
|
cadf2404787aed481e09eda9edd494546586d4a9
|
[] |
no_license
|
exMifsan/oop-lab
|
b468194e7448b41f3e700f25a415b3966b266091
|
dbd553e59768e7a259928fd90e73a93dd2a322c6
|
refs/heads/master
| 2021-07-08T05:01:59.587681
| 2017-09-29T16:22:27
| 2017-09-29T16:22:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,468
|
cpp
|
#include "stdafx.h"
#include "Controller.h"
using namespace std;
using namespace std::placeholders;
CController::CController(std::istream& input, std::ostream& output)
: m_input(input)
, m_output(output)
, m_actions({
{ "Help", bind(&CController::Help, this) },
{ "Solve", bind(&CController::SolveTheEquation, this, _1) },
})
{
}
bool CController::HandleCommand()
{
string commandLine;
if (!getline(m_input, commandLine))
{
return false;
}
istringstream strm(commandLine);
string action;
strm >> action;
auto it = m_actions.find(action);
if (it != m_actions.end())
{
it->second(strm);
return true;
}
m_output << "> Invalid command!" "\n";
return false;
}
bool CController::Help()
{
m_output << "Commands:\n"
<< "> Solve <coef a> <coef b> <coef c>\n";
return true;
}
void CController::PrintSolution()
{
m_output << "The number of roots: " << m_roots.numRoots << endl;
for (size_t i = 0; i < m_roots.numRoots; i++)
{
m_output << "Root number " << i + 1 << " = " << m_roots.roots[i] << endl;
}
}
bool CController::SolveTheEquation(std::istream & args)
{
try
{
double a;
double b;
double c;
if (!(args >> a) || !(args >> b) || !(args >> c))
{
throw std::invalid_argument("Invalid count of arguments\nUsage: Solve <coef a> <coef b> <coef c>\n");
}
else
{
m_roots = Solve(a, b, c);
PrintSolution();
return true;
}
}
catch (exception const& e)
{
m_output << e.what();
return false;
}
}
|
[
"chocolatefckll@gmail.com"
] |
chocolatefckll@gmail.com
|
bb2eaafd0e9511f4592a883f06f516d09bd14cea
|
a2fc06cf458f896d2217592ac92098863e755a9c
|
/src/library/pointlist/facelist.cpp
|
a1eff2ad3c154605fa84214140683321c4ecf07e
|
[] |
no_license
|
MrBrood/Stanford-Junior-self-driving-car
|
ba3f2a07a9366d3566def59fd25f90bad55748d2
|
d999e94bb287933666dac82129cad6702923a8e1
|
refs/heads/master
| 2023-07-18T04:56:02.055754
| 2020-08-21T01:31:46
| 2020-08-21T01:31:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,389
|
cpp
|
#include <roadrunner.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include "facelist.h"
void dgc_facelist_new(dgc_facelist_p points, int num_points)
{
points->num_points = num_points;
points->points = (dgc_polygon_p)calloc(points->num_points,
sizeof(dgc_polygon_t));
dgc_test_alloc(points->points);
points->full = 0;
points->mark = 0;
}
void dgc_facelist_add_color_points(dgc_facelist_p points, dgc_polygon_p poly,
int n, double max_size)
{
int i;
double d1, d2, d3, d4;
for(i = 0; i < n; i++)
if(poly[i].v1.range < 40.0 && poly[i].v2.range < 40.0 &&
poly[i].v3.range < 40.0 && poly[i].v4.range < 40.0) {
points->points[points->mark] = poly[i];
d1 = hypot(poly[i].v1.x - poly[i].v2.x, poly[i].v1.y - poly[i].v2.y);
d2 = hypot(poly[i].v2.x - poly[i].v3.x, poly[i].v2.y - poly[i].v3.y);
d3 = hypot(poly[i].v3.x - poly[i].v4.x, poly[i].v3.y - poly[i].v4.y);
d4 = hypot(poly[i].v4.x - poly[i].v1.x, poly[i].v4.y - poly[i].v1.y);
if(d1 < max_size && d2 < max_size && d3 < max_size && d4 < max_size)
points->points[points->mark].fill = 1;
else
points->points[points->mark].fill = 0;
points->mark++;
if(points->mark == points->num_points) {
points->mark = 0;
points->full = 1;
}
}
}
void dgc_facelist_reset(dgc_facelist_p points)
{
points->mark = 0;
points->full = 0;
}
void dgc_facelist_draw_mesh(dgc_facelist_p points,
double origin_x, double origin_y, double origin_z)
{
int i, max;
if(points->full || points->mark > 0) {
max = points->full ? points->num_points : points->mark;
for(i = 0; i < max; i++)
if(points->points[i].fill) {
glBegin(GL_QUADS);
glColor3f(points->points[i].v1.r,
points->points[i].v1.g,
points->points[i].v1.b);
glVertex3f(points->points[i].v1.x - origin_x,
points->points[i].v1.y - origin_y,
points->points[i].v1.z - origin_z);
glColor3f(points->points[i].v2.r,
points->points[i].v2.g,
points->points[i].v2.b);
glVertex3f(points->points[i].v2.x - origin_x,
points->points[i].v2.y - origin_y,
points->points[i].v2.z - origin_z);
glColor3f(points->points[i].v3.r,
points->points[i].v3.g,
points->points[i].v3.b);
glVertex3f(points->points[i].v3.x - origin_x,
points->points[i].v3.y - origin_y,
points->points[i].v3.z - origin_z);
glColor3f(points->points[i].v4.r,
points->points[i].v4.g,
points->points[i].v4.b);
glVertex3f(points->points[i].v4.x - origin_x,
points->points[i].v4.y - origin_y,
points->points[i].v4.z - origin_z);
glEnd();
}
}
}
void dgc_facelist_draw_2D(dgc_facelist_p points,
double origin_x, double origin_y)
{
int i, max;
if(points->full || points->mark > 0) {
max = points->full ? points->num_points : points->mark;
for(i = 0; i < max; i++)
if(points->points[i].fill) {
glBegin(GL_QUADS);
glColor3f(points->points[i].v1.r,
points->points[i].v1.g,
points->points[i].v1.b);
glVertex2f(points->points[i].v1.x - origin_x,
points->points[i].v1.y - origin_y);
glColor3f(points->points[i].v2.r,
points->points[i].v2.g,
points->points[i].v2.b);
glVertex2f(points->points[i].v2.x - origin_x,
points->points[i].v2.y - origin_y);
glColor3f(points->points[i].v3.r,
points->points[i].v3.g,
points->points[i].v3.b);
glVertex2f(points->points[i].v3.x - origin_x,
points->points[i].v3.y - origin_y);
glColor3f(points->points[i].v4.r,
points->points[i].v4.g,
points->points[i].v4.b);
glVertex2f(points->points[i].v4.x - origin_x,
points->points[i].v4.y - origin_y);
glEnd();
}
}
}
|
[
"6959037@qq.com"
] |
6959037@qq.com
|
0b728a5d578a3c9e8e52f15bf6e4f9ce653f2b23
|
751d3736a4ae0ccad69122a53a65dcc6d242c63c
|
/SharedUtility/MyUtils/MyUtil.h
|
34b6a157c0b8c73878196f599c189f04f69be9aa
|
[
"MIT"
] |
permissive
|
RaphaelK12/FbxModelViewer
|
5108c920174beb3a4d4e02695cb8b75c08ee5daa
|
498e130494cf04aeabc49344baa335285094abd1
|
refs/heads/master
| 2022-12-29T01:04:03.792780
| 2020-09-26T02:39:03
| 2020-09-26T02:39:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,834
|
h
|
#pragma once
// FBX にも Direct3D にも OpenGL にも依存しないユーティリティを記述する。
// ただし CRT、Boost、WinAPI および MFC/ATL には依存する。
// NOTE: 文字列クラスは移植性よりも速度・メモリ効率や機能性が必要な部分や、MFC/ATL との境界面には、MFC/ATL の CString 系列を使う。
// なお、Windows ストア アプリでは ATL の CStringW, CPathW は使えるが、CStringA, CPathA が使えない。
// また、ANSI マルチバイト文字列が廃止されている。
// 明示的に ASCII 文字列もしくは UTF-8 文字列を扱う場合、std::string での置き換えを行なう必要がある。
// 特に必要がなければ、他の環境への移植性も考慮してストレージ用途にはできるかぎり std::wstring を使っておくのがよさげ。
// ちなみにストア アプリでも OutputDebugStringA() は使えるが、リリース ビルドで直接使ってしまうと認証キットが NG 判定するので注意。
#include "MyUtilTypes.hpp"
namespace MyUtils
{
struct StdFileDeleter
{
void operator()(FILE* fp) const
{
if (fp)
{
fclose(fp);
}
}
};
using TStdFileUniquePtr = std::unique_ptr<FILE, StdFileDeleter>;
// char の符号は処理系依存なため、オーバーロードを作成できることに注意。
// ただのバイナリファイルやバイトコードだけでなく、SPIR-V や Raw 点群データなどにも対応できるよう、基本的なオーバーロードを用意しておく。
extern bool LoadBinaryFromFile(LPCWSTR pFilePath, std::vector<char>& outBuffer);
extern bool LoadBinaryFromFile(LPCWSTR pFilePath, std::vector<int8_t>& outBuffer);
extern bool LoadBinaryFromFile(LPCWSTR pFilePath, std::vector<uint8_t>& outBuffer);
extern bool LoadBinaryFromFile(LPCWSTR pFilePath, std::vector<int32_t>& outBuffer);
extern bool LoadBinaryFromFile(LPCWSTR pFilePath, std::vector<uint32_t>& outBuffer);
extern bool LoadBinaryFromFile(LPCWSTR pFilePath, std::vector<float>& outBuffer);
// Windows API の TCHAR 用に tstring, tformat を定義。
// std 名前空間を汚染しないように、std::tstring とはしない。
typedef std::basic_string<TCHAR> tstring;
//typedef boost::basic_format<TCHAR> tformat;
#pragma region // プリミティブ型のシノニム。C# や MSIL の組込型に似せてある。要は signed, unsigned をいちいち付けたくないだけ。//
// C++11 対応環境では、stdint.h, cstdint ヘッダーで定義されている型を使うべき。//
#if 0
typedef signed char Int8;
typedef unsigned char UInt8;
typedef signed char SByte;
typedef unsigned char Byte;
typedef signed short Int16;
typedef unsigned short UInt16;
typedef signed short Short;
typedef unsigned short UShort;
typedef signed int Int32;
typedef unsigned int UInt32;
typedef signed int Int;
typedef unsigned int UInt;
typedef signed long Long32;
typedef unsigned long ULong32;
typedef signed long long Int64;
typedef unsigned long long UInt64;
#endif
#if 0
typedef signed char sbyte;
typedef unsigned char byte;
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned long ulong32;
typedef unsigned long long ulong64;
#endif
#pragma endregion
} // end of namespace
#if 0
// std::string, std::wstring を返す。
// <boost/format.hpp> のインクルードが必要。
// Boost.Format() は Legacy C の printf() 系や MFC/ATL の CString::Format() と比べて型安全でありながら、
// かつ標準 C++ の stream 系よりも記述しやすいのが利点。
// また、CStringA が使えない Windows ストア アプリでの文字列フォーマットにも役立つ。
// ただし、MSVC 拡張である %S 書式による ANSI - Unicode 相互変換は使えないので注意。
// なお、<boost/format/format_fwd.hpp> にて型定義されているが、Boost 1.74 時点でも char16_t に対応したものは定義されていない。
// https://github.com/boostorg/format/blob/develop/include/boost/format/format_fwd.hpp
// こういった部分が C/C++ のダメな点。Boost を含め、文字列処理は現在に至るまで貧弱そのもので、実用途をまるで考えていない。
// Java や C# のほうが遥かに使いやすく生産的。
#define STRINGA_FORMAT(asf, pr) boost::io::str(boost::format(asf) pr)
#define STRINGW_FORMAT(wsf, pr) boost::io::str(boost::wformat(wsf) pr)
#if defined UNICODE || defined _UNICODE
#define STRINGT_FORMAT STRINGW_FORMAT
#else
#define STRINGT_FORMAT STRINGA_FORMAT
#endif
#endif
// シンボルの文字列リテラル化。
#ifndef SYMBOL2STRING
#if defined UNICODE || defined _UNICODE
#define SYMBOL2STRING(s) L#s
#else
#define SYMBOL2STRING(s) #s
#endif
#endif
#ifndef SYMBOL2STRINGW
#define SYMBOL2STRINGW(s) L#s
#endif
#ifndef SYMBOL2STRINGA
#define SYMBOL2STRINGA(s) #s
#endif
// .NET の System.Char のメソッドに似せてある。
namespace MyCharHelpers
{
inline bool IsHighSurrogate(wchar_t c)
{
return (0xD800 <= c && c <= 0xDBFF);
}
inline bool IsLowSurrogate(wchar_t c)
{
return (0xDC00 <= c && c <= 0xDFFF);
}
inline bool IsSurrogate(wchar_t c)
{
return IsHighSurrogate(c) || IsLowSurrogate(c);
}
inline bool IsSurrogatePair(wchar_t x, wchar_t y)
{
return IsHighSurrogate(x) && IsLowSurrogate(y);
}
class UnicodePair
{
public:
wchar_t X, Y;
public:
UnicodePair()
: X(), Y()
{
}
explicit UnicodePair(wchar_t x, wchar_t y = 0)
: X(x), Y(y)
{
}
public:
// 同値判定用の演算子オーバーロード。
// .NET の System.Object.Equals() に相当。
// unordered_set/unordered_map ではハッシュ値とともに使われる。
bool operator==(const UnicodePair& rval) const
{
return this->X == rval.X && this->Y == rval.Y;
}
bool operator!=(const UnicodePair& rval) const
{
return !(*this == rval);
}
bool operator==(wchar_t rval) const
{
return this->Y == 0 && this->X == rval;
}
bool operator!=(wchar_t rval) const
{
return !(*this == rval);
}
public:
// .NET の System.Object.GetHashCode() に相当。
size_t GetHashCode() const
{
return this->X ^ this->Y;
}
// ハッシュ値取得用の関数オブジェクト。
struct HashFunctor
{
size_t operator ()(const UnicodePair& v) const { return v.GetHashCode(); }
};
};
#if 0
// std::function<decltype(T)> と組み合わせて使う。
// std::unordered_map のハッシュ関数として定義する場合、クラスの static メンバーにしてはダメで、
// グローバル関数として定義してやらないといけないらしい?
inline size_t GetUnicodePairHashCode(const UnicodePair& key)
{
return key.GetHashCode();
}
#endif
} // end of namespace
#if 0
namespace std
{
// 独自型を std::unordered_map のキーとして使うために、
// 独自型のハッシュ計算関数として std::hash<T> の特殊化を定義する方法がある。
// std 名前空間を汚染したくない場合、
// std::unordered_map テンプレート第3引数に
// size_t operator ()(const TKey&) const;
// を定義した関数オブジェクトの型を渡す方法もある。
// どちらかというと関数オブジェクトを使うほうが独立性が高く、適用範囲や影響を限定できるが、
// map と unordered_map を切り替えてパフォーマンス テストするときはやや面倒になる。
template<> struct hash<MyCharHelpers::UnicodePair>
{
std::size_t operator()(const MyCharHelpers::UnicodePair& key) const
{
return key.GetHashCode();
}
};
// なお、独自型の比較関数として std::equal_to<T> の特殊化を定義する方法がある。
// std 名前空間を汚染したくない場合、
// std::unordered_map テンプレート第4引数に
// bool operator ()(const TKey&, const TKey&) const;
// を定義した関数オブジェクトの型を渡す方法もある。
// あるいは、独自型のメンバーとして
// bool operator ==(const TKey&) const;
// を定義するだけでもよい。
} // end of namespace
#endif
namespace MyUtils
{
// メソッドの戻り値で文字列クラスへの const 参照(const ポインタではない)を返したりする必要があるとき、
// null 値の代替として空文字列の定数オブジェクトを用意しておく。
// メソッド ブロック内の static const ローカル変数でもいいが、共通グローバル定数オブジェクトを作っておいたほうがよい。
// なお、グローバル定数オブジェクトを定義して、それを使ってクラスのメンバー変数を初期化したりする場合、
// そのクラスのインスタンスをグローバル変数にしてはいけない。
// グローバル変数の初期化順序の問題に引っかかる。
// もしどうしてもグローバル変数にする場合、グローバル定数オブジェクトではなく、
// 静的ローカル変数への参照を返すグローバル メソッドを定義して、初期化時にそれを呼び出すようにする。
const std::string EmptyStdStringA;
const std::wstring EmptyStdStringW;
extern std::vector<char> ConvertUtf16toUtf8(const wchar_t* srcText);
extern std::vector<wchar_t> ConvertUtf8toUtf16(const char* srcText);
inline std::string SafeConvertUtf16toUtf8(const wchar_t* srcText)
{ return srcText ? ConvertUtf16toUtf8(srcText).data() : ""; }
inline std::wstring SafeConvertUtf8toUtf16(const char* srcText)
{ return srcText ? ConvertUtf8toUtf16(srcText).data() : L""; }
//! @brief Windows Unicode (UTF-16) のパスに対応する UTF-8 エンコード MBCS の絶対ファイルパスを取得する。<br>
//!
//! Windows ANSI Code Page (日本語では Windows Shift-JIS, CP932) のパスに対応する <br>
//! UTF-8 エンコード MBCS の絶対ファイルパスを取得したい場合、呼び出し側でいったん UTF-16 のワイド文字列に <br>
//! 変換しておくこと。<br>
extern bool GetUtf8FullPath(const wchar_t* inRelFilePath, std::string& outFullPath);
template<typename T> inline T SquareVal(const T& x)
{ return x * x; }
template<typename T> inline T CubeVal(const T& x)
{ return x * x * x; }
template<typename T> inline T ToPowerOf4(const T& x)
{ return x * x * x * x; }
template<typename T> inline void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
// マクロ展開を回避するテクニックがあるので、std::min() および std::max() の代替は定義しない。
#if 0
//! @brief GDI+ や MFC アプリとコードを共有する場合の、std::min() の代替。NaN 非対応。<br>
template<typename T> inline const T& MinVal(const T& a, const T& b)
{
return (a <= b) ? a : b;
}
//! @brief GDI+ や MFC アプリとコードを共有する場合の、std::max() の代替。NaN 非対応。<br>
template<typename T> inline const T& MaxVal(const T& a, const T& b)
{
return (a >= b) ? a : b;
}
#endif
template<typename T> inline const T& Clamp(const T& a, const T& minVal, const T& maxVal)
{
if (a < minVal) return minVal;
if (a > maxVal) return maxVal;
return a;
}
template<typename T> inline void LogicalNot(T& n)
{
n = !n;
}
template<typename T> inline void SafeDelete(T*& p)
{
// C++ の仕様では NULL ポインタに delete を実行しても何も起こらないということになっている。
// なので NULL チェックは行なわない。
delete p;
p = nullptr;
}
template<typename T> inline void SafeFree(T*& ptr)
{
// C/C++ の仕様では NULL ポインタに free() を実行しても何も起こらないということになっている。
// なので NULL チェックは行なわない。
free(ptr);
ptr = nullptr;
}
template<typename T> inline void SafeRelease(T*& ptr)
{
if (ptr)
{
ptr->Release();
ptr = nullptr;
}
}
inline void SafeFClose(FILE*& fp)
{
if (fp)
{
fclose(fp);
fp = nullptr;
}
}
template<typename T> T* StaticPointerCast(void* pIntermediate)
{ return static_cast<T*>(pIntermediate); }
template<typename T> const T* StaticPointerCast(const void* pIntermediate)
{ return static_cast<const T*>(pIntermediate); }
class AltFinally final
{
using TFinalFunc = std::function<void()>;
TFinalFunc m_finalFunc;
public:
explicit AltFinally(const TFinalFunc& finalFunc)
: m_finalFunc(finalFunc)
{}
~AltFinally()
{
if (m_finalFunc)
{
m_finalFunc();
}
}
};
} // end of namespace
namespace MyAlgHelpers
{
// コンテナ/コレクションの全要素を検査するアサーションを書く場合、
// C++ であれば STL アルゴリズムとラムダ式、
// C# であれば LINQ メソッド構文とラムダ式を使えばインラインで書けるので有用。
// ジャグ配列の検査などで効果的。
template<typename T> bool CheckAllElemSizesInJaggedArrayAreSame(const std::vector<std::shared_ptr<std::vector<T>>>& inJagged, size_t targetSize)
{
typedef typename decltype(*inJagged.begin()) TValue;
return std::find_if(inJagged.begin(), inJagged.end(),
[targetSize] (const TValue& pSubContainer)
{ return !pSubContainer || (pSubContainer->size() != targetSize); })
== inJagged.end();
}
}
|
[
"whitekatyusha@yahoo.co.jp"
] |
whitekatyusha@yahoo.co.jp
|
22a2fa145ea6fdbf02391936d6f354dbb1b0e933
|
111c3ebecfa9eac954bde34b38450b0519c45b86
|
/SDK_Perso/include/Cockpit/Base/Header/Avionics/avMechanics.h
|
5694525fb768430d3700cc20fa1b720532be9d63
|
[] |
no_license
|
1059444127/NH90
|
25db189bb4f3b7129a3c6d97acb415265339dab7
|
a97da9d49b4d520ad169845603fd47c5ed870797
|
refs/heads/master
| 2021-05-29T14:14:33.309737
| 2015-10-05T17:06:10
| 2015-10-05T17:06:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,638
|
h
|
#pragma once
#include "Avionics/avDevice.h"
#include "wFloat.h"
#include "Utilities/ccUtilities.h"
#include "FMElectricSystems/Items/MultiThrowSwitch.h"
#include "FMElectricSystems/Items/Wire.h"
namespace Lua
{
class Config;
}
namespace cockpit
{
class GaugeBiasChunk
{
public:
GaugeBiasChunk() : min_val(0.0), max_val(0.0), bias(0.0) {};
double min_val, max_val, bias;
};
typedef ed::vector<GaugeBiasChunk> BiasVec;
class COCKPITBASE_API GaugeBias
{
public:
bool l_read(Lua::Config& config, const char* field);
bool l_read(Lua::Config& config);
BiasVec bias;
};
class GaugeAnglesChunk
{
public:
GaugeAnglesChunk() : val(0.0), angle(0.0) {}
double val, angle;
};
typedef ed::vector<GaugeAnglesChunk> AnglesVec;
class MomentNormaChunk
{
public:
MomentNormaChunk() : min_angle(0.0), max_angle(0.0), norma(0.0) {};
double min_angle, max_angle, norma;
};
typedef ed::vector<MomentNormaChunk> NormasVec;
class COCKPITBASE_API GaugeOrient
{
public:
bool l_read(Lua::Config& config);
AnglesVec angles;
NormasVec normas;
};
class COCKPITBASE_API gauge
{
public:
gauge() : value_min(0.0), value_max(Pi_2), error(0.0), failure(false) {value_out.Set(0.0, wTime::GetModelTime());}
double simulate(double value_in, wModelTime dt) {value_out.Set(0.0, wTime::GetModelTime()); return 0.0;}
void stop(wModelTime dt);
double get_value_out() const {return value_out.GetValue(wTime::GetModelTime());}
double get_value_min() const {return value_min;}
double get_value_max() const {return value_max;}
bool get_failure() const {return failure;}
double get_error() const {return error;}
void set_value_out(double param_in) {value_out.Set(param_in, wTime::GetModelTime());}
void set_value_min(double param_in) {value_min = param_in;}
void set_value_max(double param_in) {value_max = param_in;}
void set_failure(bool param_in) {failure = param_in;}
virtual bool l_read(Lua::Config& config, const char* field);
protected:
static const double epsilon;
wDouble value_out;
double value_min, value_max;
bool failure;
double error;
};
class COCKPITBASE_API gauge_linear : public gauge
{
public:
gauge_linear() : d_value(0.0) {}
virtual bool l_read(Lua::Config& config, const char* field);
double simulate(double value_in, wModelTime dt);
double get_d_value() const {return d_value;}
void set_d_value(double param_in){d_value = param_in;}
protected:
double d_value;
};
// В функцию simulateF() можно передавать внешнюю силу
// Две особенности функции:
// 1) Коэффициент, которым можно масштабировать силу, который задается в скрипте.
// 2) Если прибор свое значение увеличивает против часовой стрелки, то этот коэффициент надо указать с минусом.
//
// Ориентация прибора должна задаваться так, чтобы угол увеличивался по часовой стрелке. Ноль -
// это вертикально вверх. минус 90 - вправо, плюс 90 - влево. Например, у типового прибора, вроде напряжения,
// где стрелка ходит по дуге слева направо типичными углами будут: от минус 60 до плюс 60.
// Углы задаются парами - угол ориентации стрелки и соответстующее ему положение стрелки на шкале (в единицах прибора).
// Если шкала линейная, то начальный и конечный углы будут совпадать. Например, для вертикальной шкалы
// углы будут составлять: от -90 до -90. Пример результата действия силы - если переменная сила (тряска)
// действует строго вниз относительно панели приборов, то стрелка ориентированная вертикально будет неподвижна,
// а стрелка ориентированая горизонтально будет иметь макс. амплитуду тряски. Для круговой замкнутой шкалы,
// если у нее, например, нулевое положение строго влево относительно приборной доски, надо указывать углы не "от -90 до -90", а "от -90 до 270".
class COCKPITBASE_API gauge_periodic : public gauge
{
public:
gauge_periodic() : isLagElement(false), w(0.0), w_max(0.0), T1(0.0), T2(0.0), momentCoeff(1.0) {}
virtual bool l_read(Lua::Config& config, const char* field);
double simulate(double value_in, wModelTime dt);
double simulateF(double value_in, double forceY, double forceZ, wModelTime dt);
double get_w() const {return w;}
GaugeBias& get_bias() {return bias;}
double get_w_max() const {return w_max;}
double get_T1() const {return T1;}
double get_T2() const {return T2;}
double getMomentCoeff() const {return momentCoeff;}
void set_w(double param_in) {w = param_in;}
void set_w_max(double param_in) {w_max = param_in;}
void set_T1(double param_in) {T1 = param_in;}
void set_T2(double param_in) {T2 = param_in;}
void setMomentCoeff(double param_in) {momentCoeff = param_in;}
protected:
double findBias(double val);
double findAngle(double val);
double findNorma(double angle);
double calcMoment(double angle, double forceY, double forceZ);
double simulate(double currVal, double prevVal, wModelTime dt);
double simulateM(double value_in, double addMoment, wModelTime dt);
bool isLagElement;
double w;
GaugeBias bias;
double w_max;
double T1, T2;
GaugeOrient angles;
double momentCoeff;
};
class COCKPITBASE_API gauge_limited : public gauge_periodic
{
public:
gauge_limited() {}
double simulate(double value_in, wModelTime dt);
double simulateF(double value_in, double forceY, double forceZ, wModelTime dt);
protected:
double simulateM(double value_in, double addMoment, wModelTime dt);
};
class COCKPITBASE_API gauge_input_adapter
{
public:
typedef ed::vector<double> GaugeAdapterValues;
void l_read(Lua::Config& config, const char* field);
void set_defalut(const GaugeAdapterValues& input, const GaugeAdapterValues& output);
double get_animation(double value) const; /*returns in animation units*/
double get_native(double value) const; /*returns in gauge native units*/
private:
GaugeAdapterValues input_;
GaugeAdapterValues output_;
};
// A non-ideal meter susceptible for voltage changes in the bus
inline double electricQuotientMeter(double trueVal, double minVal, double voltageRatio, double K)
{
//return trueVal + measurRange * (voltageRatio - 1.0) * K;
return minVal + (trueVal - minVal) * (1.0 + K * (voltageRatio - 1.0));
}
class COCKPITBASE_API gear_handle // анимация крана шасси
{
public:
gear_handle();
virtual ~gear_handle(){};
double get_animation_value() const { return animation.get_value_out(); }
bool get_commanded_pos() const { return commanded_gear_down; }
void force(bool gear_down);
void command(bool gear_down);
void connect_electric(EagleFM::Elec::ItemBase & bus,
EagleFM::Elec::Wire & on_up,
EagleFM::Elec::Wire & on_down);
void update(double dt);
protected:
wModelTime unlock_dpos,
dpos,
lock_dpos;
char moving; // -1 = уборка, 0 = не двигается, 1 = выпуск
bool commanded_gear_down;
gauge_linear animation;
EagleFM::Elec::MultiThrowSwitch selector; //управление уборкой/выпуском шасси
};
template <unsigned N>
class counter_drum
{
class drum_digit
{
public:
drum_digit()
{
smooth = false;
value = 0;
basement = 1;
}
void set(double in,double eps)
{
in = fmod(in,10 * basement);
if (smooth)
{
value = in / basement;
return;
}
double p_2 = int(in/basement)* basement;
double p_1 = in - p_2;
if (p_1 > basement - eps)
value = p_2 / basement + (p_1 - (basement - eps)) / eps;
else
value = p_2 / basement;
}
bool smooth;
double value;
unsigned basement;
};
public:
counter_drum()
{
assert(N);
for (int i = 1; i < N; ++i)
{
d[i].basement = d[i-1].basement * 10;
}
last = 0;
threshold = 1;
};
~counter_drum(){};
void set(double value)
{
if (last == value)
return;
for(int decade = 0; decade < N; ++decade)
d[decade].set(value,threshold);
last = value;
}
void set_smooth(unsigned decade,bool value)
{
assert(decade < N);
d[decade].smooth = value;
}
double get_decade(unsigned decade) const
{
assert(decade < N);
return d[decade].value;
}
void set_threshold(double val) { threshold = val;}
private:
drum_digit d[N];
double last;
double threshold;
};
}
|
[
"hashmaaal@gmail.com"
] |
hashmaaal@gmail.com
|
ccdc95517e6a97653ce270cb3d72fc0c6f16338f
|
0da624ab75d88a1f27ac8a87a27a8e25209007e6
|
/sources/enduro2d/utils/filesystem_impl/files_posix.cpp
|
e6ee5ba552c82e83ef057182bb6dcf083342c0e6
|
[
"MIT"
] |
permissive
|
BobDeng1974/enduro2d
|
e2a6ebf3ac681e4c77676757e71cdba3f58ca2cc
|
f8721f365a91353ff3c96b63fa8186d8bd98406b
|
refs/heads/master
| 2020-08-03T06:20:54.860890
| 2019-09-05T11:38:07
| 2019-09-05T11:38:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,035
|
cpp
|
/*******************************************************************************
* This file is part of the "Enduro2D"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2018-2019, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#include "files.hpp"
#if defined(E2D_FILES_MODE) && E2D_FILES_MODE == E2D_FILES_MODE_POSIX
#include <fcntl.h>
#include <unistd.h>
namespace
{
using namespace e2d;
class read_file_posix final : public read_file {
public:
read_file_posix(str path)
: path_(std::move(path))
{
if ( !open_() ) {
throw bad_stream_operation();
}
}
~read_file_posix() noexcept final {
close_();
}
public:
std::size_t read(void* dst, std::size_t size) final {
E2D_ASSERT(is_opened_());
const std::ptrdiff_t rread = ::read(handle_, dst, size);
return rread >= 0
? math::numeric_cast<std::size_t>(rread)
: throw bad_stream_operation();
}
std::size_t seek(std::ptrdiff_t offset, bool relative) final {
E2D_ASSERT(is_opened_());
const std::ptrdiff_t rlseek = ::lseek(handle_, offset, relative ? SEEK_CUR : SEEK_SET);
return rlseek >= 0
? math::numeric_cast<std::size_t>(rlseek)
: throw bad_stream_operation();
}
std::size_t tell() const final {
E2D_ASSERT(is_opened_());
const std::ptrdiff_t rlseek = ::lseek(handle_, 0, SEEK_CUR);
return rlseek >= 0
? math::numeric_cast<std::size_t>(rlseek)
: throw bad_stream_operation();
}
std::size_t length() const noexcept final {
return length_;
}
const str& path() const noexcept final {
return path_;
}
private:
bool open_() noexcept {
E2D_ASSERT(!is_opened_());
handle_ = ::open(path_.c_str(), O_RDONLY);
if ( handle_ < 0 ) {
close_();
return false;
}
if ( ::lseek(handle_, 0, SEEK_END) < 0 ) {
close_();
return false;
}
const std::ptrdiff_t rlseek = ::lseek(handle_, 0, SEEK_CUR);
if ( rlseek < 0 ) {
close_();
return false;
}
length_ = math::numeric_cast<std::size_t>(rlseek);
if ( ::lseek(handle_, 0, SEEK_SET) < 0 ) {
close_();
return false;
}
return true;
}
void close_() noexcept {
if ( handle_ >= 0 ) {
::close(handle_);
handle_ = -1;
}
}
bool is_opened_() const noexcept {
return handle_ >= 0;
}
private:
str path_;
std::size_t length_ = 0;
int handle_ = -1;
};
class write_file_posix : public write_file {
public:
write_file_posix(str path, bool append)
: path_(std::move(path))
{
if ( !open_(append) ) {
throw bad_stream_operation();
}
}
~write_file_posix() noexcept final {
close_();
}
public:
std::size_t write(const void* src, std::size_t size) final {
E2D_ASSERT(is_opened_());
const std::ptrdiff_t rwrite = ::write(handle_, src, size);
return rwrite >= 0
? math::numeric_cast<std::size_t>(rwrite)
: throw bad_stream_operation();
}
std::size_t seek(std::ptrdiff_t offset, bool relative) final {
E2D_ASSERT(is_opened_());
const std::ptrdiff_t rlseek = ::lseek(handle_, offset, relative ? SEEK_CUR : SEEK_SET);
return rlseek >= 0
? math::numeric_cast<std::size_t>(rlseek)
: throw bad_stream_operation();
}
std::size_t tell() const final {
E2D_ASSERT(is_opened_());
const std::ptrdiff_t rlseek = ::lseek(handle_, 0, SEEK_CUR);
return rlseek >= 0
? math::numeric_cast<std::size_t>(rlseek)
: throw bad_stream_operation();
}
void flush() const final {
E2D_ASSERT(is_opened_());
if ( 0 != ::fsync(handle_) ) {
throw bad_stream_operation();
}
}
const str& path() const noexcept final {
return path_;
}
private:
bool open_(bool append) noexcept {
E2D_ASSERT(!is_opened_());
handle_ = ::open(
path_.c_str(),
append ? (O_WRONLY|O_CREAT) : (O_WRONLY|O_CREAT|O_TRUNC),
S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
if ( handle_ < 0 ) {
close_();
return false;
}
if ( ::lseek(handle_, 0, SEEK_END) < 0 ) {
close_();
return false;
}
return true;
}
void close_() noexcept {
if ( handle_ >= 0 ) {
::close(handle_);
handle_ = -1;
}
}
bool is_opened_() const noexcept {
return handle_ >= 0;
}
private:
str path_;
int handle_ = -1;
};
}
namespace e2d::impl
{
read_file_uptr make_read_file(str_view path) noexcept {
try {
return std::make_unique<read_file_posix>(str(path));
} catch (...) {
return nullptr;
}
}
write_file_uptr make_write_file(str_view path, bool append) noexcept {
try {
return std::make_unique<write_file_posix>(str(path), append);
} catch (...) {
return nullptr;
}
}
}
#endif
|
[
"blackmatov@gmail.com"
] |
blackmatov@gmail.com
|
fea4c85d7a536785cb68401a7b21e5aa399f5867
|
8dafe0da13657e7cae5fdf023461bdc5f54afab6
|
/Review/widget.h
|
616086d9293c621f826fe5bacb7ef08274c3e3b2
|
[] |
no_license
|
waynegod/Qt-Learning
|
0901f0ccd5bf02a89ae61c9bdb06046051c11467
|
088666938e1cd7c88bcf30fd43cdd3a2788191e1
|
refs/heads/master
| 2021-08-24T13:43:42.252356
| 2017-11-21T08:47:47
| 2017-11-21T08:47:47
| 109,367,924
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 181
|
h
|
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
};
#endif // WIDGET_H
|
[
"noreply@github.com"
] |
waynegod.noreply@github.com
|
f683954df94e2b4557c3e1d51d359dfc9b3b8d35
|
cb9bbac43da9262d23017de87813ef5a849e3421
|
/Lab7/Lab7/Lab7.ino
|
2f3838005f99e11cffd3c062caf263b7739c3d35
|
[] |
no_license
|
kebradford/ECE4960
|
887677a58e81ab6695eb60194019e7923c62b6ee
|
ae1b327e170954cd0875c5f911b9f8560d332ece
|
refs/heads/master
| 2023-01-30T14:30:55.004871
| 2020-12-17T22:08:58
| 2020-12-17T22:08:58
| 292,678,685
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,919
|
ino
|
/////////Motor and IMU Stuff////////////////////////////////////////////////////////////
#include "ICM_20948.h" // Click here to get the library: http://librarymanager/All#SparkFun_ICM_20948_IMU
#include "math.h"
#include <Arduino.h>
#include <stdint.h>
#include "SCMD.h"
#include "SCMD_config.h" //Contains #defines for common SCMD register names and values
#include "Wire.h"
#define SERIAL_PORT Serial
#define WIRE_PORT Wire // Your desired Wire port. Used when "USE_SPI" is not defined
#define AD0_VAL 1 // The value of the last bit of the I2C address.
#include <PID_v1.h> //PID library
///TOF Things
#include <ComponentObject.h>
#include <RangeSensor.h>
#include <SparkFun_VL53L1X.h>
#include <vl53l1x_class.h>
#include <vl53l1_error_codes.h>
#include "SparkFun_VL53L1X.h" //TOF
////////////////////////////////////////////////////////////////////////////////////////////
SFEVL53L1X distanceSensor;
ICM_20948_I2C myICM; // Otherwise create an ICM_20948_I2C object
SCMD myMotorDriver; //This creates the main object of one motor driver and connected slaves.
double dt, lastRead, rotationalSpeed;
double pitch_g, roll_g, yaw_g;
///////PID Stuff////////////////////////////////////////////////
double Setpoint, Input, Output; // for PID control
double Kp=3, Ki=.5, Kd=0; //CHANGE THESE CONSTANTS FOR PID
double last_yaw = 0;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
////////////////////////////////////////////////////////////////
void setup() {
SERIAL_PORT.begin(115200);
while(!SERIAL_PORT){};
WIRE_PORT.begin();
WIRE_PORT.setClock(400000);
/////set up IMU////////
bool initialized = false;
while( !initialized ){
myICM.begin( WIRE_PORT, AD0_VAL );
if( myICM.status != ICM_20948_Stat_Ok ){
//SERIAL_PORT.println( "Trying again..." );
delay(500);
}
else initialized = true;
}
///set up TOF
if (distanceSensor.begin() != 0) //Begin returns 0 on a good init
{
//Serial.println("Sensor failed to begin. Please check wiring. Freezing...");
while (1)
;
}
/////set up motor////////
myMotorDriver.settings.commInterface = I2C_MODE;
myMotorDriver.settings.I2CAddress = 0x5D; //config pattern "0101" on board for address 0x5A
//*****initialize the driver get wait for idle*****//
while ( myMotorDriver.begin() != 0xA9 ) //Wait until a valid ID word is returned
{
delay(500);
}
// Check to make sure the driver is done looking for slaves before beginning
while ( myMotorDriver.ready() == false );
//*****Set application settings and enable driver*****//
while ( myMotorDriver.busy() );
myMotorDriver.enable();
myPID.SetMode(AUTOMATIC); ///start PID
}
void loop() {
/////////////motor and IMU writing///////////////////////////////////////////////////////////////////////////////////////////
if( myICM.dataReady() ){
//Read yaw data
myICM.getAGMT(); // The values are only updated when you call 'getAGMT'
dt = (millis()-lastRead)/1000;
lastRead = millis();
yaw_g = yaw_g+myICM.gyrZ()*dt;
Serial.print("Yaw:");
Serial.println(yaw_g);
//get distance
distanceSensor.startRanging(); //Write configuration bytes to initiate measurement
int distance = distanceSensor.getDistance(); //Get the result of the measurement from the sensor
distanceSensor.clearInterrupt();
distanceSensor.stopRanging();
Serial.print("Distance(mm): ");
Serial.println(distance);
double motorVal;
//myPID.Compute(); //compute Output for motors
motorVal = 130;
// else motorVal = Output;
myMotorDriver.setDrive( 1, 1, motorVal);
myMotorDriver.setDrive( 0, 1, motorVal);
//Serial.print("MotorValue:");
//Serial.print(motorVal);
//Serial.print(" ");
//Serial.print("GyroData:");
// Serial.println(Input);
delay(1);
}else{
//Serial.println("Waiting for data");
delay(500);
}
}
|
[
"bradfordkatiee@gmail.com"
] |
bradfordkatiee@gmail.com
|
23d6e24999631c57fd53663aa172d8e301965687
|
5235ae66b46cfd628a0988ea10730b33c81c2e91
|
/mirror/Main.cpp
|
9fbb2b3e29ea944124d05ae13fd21342d93b1266
|
[] |
no_license
|
anstn1993/c-_practice
|
c761234303a439da3df8839abda1133c8afed5c4
|
d2f4a7c77778fd9a4415eaa239eac8e55f77f176
|
refs/heads/master
| 2022-03-18T21:40:50.599718
| 2019-12-12T09:34:02
| 2019-12-12T09:34:02
| 223,435,607
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 99
|
cpp
|
#include "Mirrorstring.h"
using namespace samples;
int main()
{
MirroStringExample();
return 0;
}
|
[
"anstn1993@gmail.com"
] |
anstn1993@gmail.com
|
aaf950a0095ed705a446feb9e277a1c6069544b0
|
b3392d0a195c0d94f6197e0f561195b670a6d47c
|
/quartile_cal.cpp
|
2ab2911e9ce800371335eae2097c0c0c13f3ef9b
|
[] |
no_license
|
ths205/C-plus-plus
|
ed7bc3c6be6b26e1343373f8c9874b2a71e70abd
|
e3d031828ea3b098eba5124df0e1e046c7479898
|
refs/heads/master
| 2022-02-25T20:29:08.722168
| 2022-02-10T18:01:46
| 2022-02-10T18:01:46
| 10,113,868
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,745
|
cpp
|
//Calculates the first,second and third Quartiles of an array
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
if( !cin || n<=0)
{
cout<<"You either gave bad input or an integer that is 0 or less.\n";
exit(0);
}
int x[n];
for( int i=0; i<n; i++)
{
cin>>x[i];
if(!cin)
{
cout<<"You gave bad input.\n";
exit(0);
}
}
//Sort the array
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++){
if(x[i] > x[j])
{
int temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
}
//if the number of integers in an array is odd
if(n%2 != 0)
{
int q2 = x[(n/2)];
int q1 = (x[(n/4)-1]+x[(n/4)])/2;
int q3 = (x[(3*n/4)]+x[(3*n/4)+1])/2;
cout<<q1<<"\n";
cout<<q2<<"\n";
cout<<q3<<"\n";
}
//if the number of integers in an array is even and if the number of integers that make up half the array are odd
else if (n%2==0 && n%4!=0) {
int q2 = (x[(n/2)-1]+x[(n/2)])/2;
int q1 = (x[(n/4)]);
int q3 = (x[(3*n/4)]);
cout<<q1<<"\n";
cout<<q2<<"\n";
cout<<q3<<"\n";
}
//if the number of integers in an array is even and if the number of integers that make up half the array are odd
else{
int q2 =(x[(n/2)-1]+x[(n/2)])/2;
int q1= (x[(n/4)-1]+x[(n/4)])/2;
int q3 = (x[((3*n)/4)-1]+x[(3*n/4)])/2;
cout<<q1<<"\n";
|
[
"noreply@github.com"
] |
ths205.noreply@github.com
|
e09d86e779da1035cb9ff624cef72de833b0f8bd
|
c60e4f97890cc7329123d18fd5bc55734815caa5
|
/3rd/xulrunner-sdk/include/nsIMemory.h
|
11dddd834b3665c1e28d64dd8ad2219dfe1f0f08
|
[
"Apache-2.0"
] |
permissive
|
ShoufuLuo/csaw
|
cbdcd8d51bb7fc4943e66b82ee7bc9c25ccbc385
|
0d030d5ab93e61b62dff10b27a15c83fcfce3ff3
|
refs/heads/master
| 2021-01-19T10:02:51.209070
| 2014-04-30T19:53:32
| 2014-04-30T19:53:32
| 16,976,394
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,378
|
h
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/xpcom/base/nsIMemory.idl
*/
#ifndef __gen_nsIMemory_h__
#define __gen_nsIMemory_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: nsIMemory */
#define NS_IMEMORY_IID_STR "59e7e77a-38e4-11d4-8cf5-0060b0fc14a3"
#define NS_IMEMORY_IID \
{0x59e7e77a, 0x38e4, 0x11d4, \
{ 0x8c, 0xf5, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIMemory : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IMEMORY_IID)
/* [noscript,notxpcom] voidPtr alloc (in size_t size); */
NS_IMETHOD_(void *) Alloc(size_t size) = 0;
/* [noscript,notxpcom] voidPtr realloc (in voidPtr ptr, in size_t newSize); */
NS_IMETHOD_(void *) Realloc(void *ptr, size_t newSize) = 0;
/* [noscript,notxpcom] void free (in voidPtr ptr); */
NS_IMETHOD_(void) Free(void *ptr) = 0;
/* void heapMinimize (in boolean immediate); */
NS_SCRIPTABLE NS_IMETHOD HeapMinimize(PRBool immediate) = 0;
/* boolean isLowMemory (); */
NS_SCRIPTABLE NS_IMETHOD IsLowMemory(PRBool *_retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIMemory, NS_IMEMORY_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIMEMORY \
NS_IMETHOD_(void *) Alloc(size_t size); \
NS_IMETHOD_(void *) Realloc(void *ptr, size_t newSize); \
NS_IMETHOD_(void) Free(void *ptr); \
NS_SCRIPTABLE NS_IMETHOD HeapMinimize(PRBool immediate); \
NS_SCRIPTABLE NS_IMETHOD IsLowMemory(PRBool *_retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIMEMORY(_to) \
NS_IMETHOD_(void *) Alloc(size_t size) { return _to Alloc(size); } \
NS_IMETHOD_(void *) Realloc(void *ptr, size_t newSize) { return _to Realloc(ptr, newSize); } \
NS_IMETHOD_(void) Free(void *ptr) { return _to Free(ptr); } \
NS_SCRIPTABLE NS_IMETHOD HeapMinimize(PRBool immediate) { return _to HeapMinimize(immediate); } \
NS_SCRIPTABLE NS_IMETHOD IsLowMemory(PRBool *_retval NS_OUTPARAM) { return _to IsLowMemory(_retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIMEMORY(_to) \
NS_IMETHOD_(void *) Alloc(size_t size) { return !_to ? NS_ERROR_NULL_POINTER : _to->Alloc(size); } \
NS_IMETHOD_(void *) Realloc(void *ptr, size_t newSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->Realloc(ptr, newSize); } \
NS_IMETHOD_(void) Free(void *ptr) { return !_to ? NS_ERROR_NULL_POINTER : _to->Free(ptr); } \
NS_SCRIPTABLE NS_IMETHOD HeapMinimize(PRBool immediate) { return !_to ? NS_ERROR_NULL_POINTER : _to->HeapMinimize(immediate); } \
NS_SCRIPTABLE NS_IMETHOD IsLowMemory(PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsLowMemory(_retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsMemory : public nsIMemory
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIMEMORY
nsMemory();
private:
~nsMemory();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsMemory, nsIMemory)
nsMemory::nsMemory()
{
/* member initializers and constructor code */
}
nsMemory::~nsMemory()
{
/* destructor code */
}
/* [noscript,notxpcom] voidPtr alloc (in size_t size); */
NS_IMETHODIMP_(void *) nsMemory::Alloc(size_t size)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [noscript,notxpcom] voidPtr realloc (in voidPtr ptr, in size_t newSize); */
NS_IMETHODIMP_(void *) nsMemory::Realloc(void *ptr, size_t newSize)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [noscript,notxpcom] void free (in voidPtr ptr); */
NS_IMETHODIMP_(void) nsMemory::Free(void *ptr)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void heapMinimize (in boolean immediate); */
NS_IMETHODIMP nsMemory::HeapMinimize(PRBool immediate)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean isLowMemory (); */
NS_IMETHODIMP nsMemory::IsLowMemory(PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIMemory_h__ */
|
[
"luoshoufu@gmail.com"
] |
luoshoufu@gmail.com
|
c4be7735620f71f504522e3479bfdfe7611203b2
|
3280d7dc9ac78d970aa0054ac9636dbe751df681
|
/include/dnsrpc_constants.h
|
34f462c56aab2e81e0bd8234daf467d4293d7a8c
|
[] |
no_license
|
he475943497/new_edns_dial
|
ff21e4a88c5185d8d0359089a1b884df53882d17
|
89c2627e9fc56e8aa57207995d35141531035f54
|
refs/heads/master
| 2021-05-08T04:16:26.871575
| 2017-10-31T08:04:55
| 2017-10-31T08:04:55
| 108,391,696
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| true
| 408
|
h
|
/**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#ifndef dnsrpc_CONSTANTS_H
#define dnsrpc_CONSTANTS_H
#include "dnsrpc_types.h"
namespace rpc { namespace yamutech { namespace com {
class dnsrpcConstants {
public:
dnsrpcConstants();
};
extern const dnsrpcConstants g_dnsrpc_constants;
}}} // namespace
#endif
|
[
"ww.he@yamutech.com"
] |
ww.he@yamutech.com
|
483376a30a16fb76f91bbe44b0d8d43c2a547cf7
|
757c29b9f49427f7116972d84c08d87d8aa4e333
|
/standard_algorithm/FenwickTree.cpp
|
ad170ff6680cda6d22cbb99770f037e6a620a6a2
|
[] |
no_license
|
jKhurana/competitive_coding
|
4ed3a8aa8b32b05b8a32c50bfe84bffdb64dc679
|
37fd652e5ba925596f41094014b51665a8f6ba0e
|
refs/heads/master
| 2020-06-13T16:53:29.684831
| 2019-03-18T19:05:56
| 2019-03-18T19:05:56
| 75,524,541
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 498
|
cpp
|
#include <stdio.h>
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
void create_fenwick(vector<int> &freq,vector<int> &tree)
{
int add,j;
for(unsigned int i=1;i<freq.size();i++)
{
add=freq[i];
j=i;
while(j<=n-1)
{
tree[j]=tree[j]+add;
}
}
}
int main()
{
int n,temp;
scanf("%d",&n);
vector<int> freq(n);
for(int i=0;i<n;i++)
{
scanf("%d",&temp);
freq.push_back(temp);
}
vector<int> tree(n+1,0);
create_fenwick(freq,tree);
return 0;
}
|
[
"jatinkhurana9@gmail.com"
] |
jatinkhurana9@gmail.com
|
86cdc2b9b6f26346675e22660a8f20c86a02557b
|
e9ade5ea33cf3382f8ab3ad980e7f6d8cb76faf8
|
/solved/RobertCppPrograming/extern1.cpp
|
eef950d9c8f4301925f74ec0af141f94b416a237
|
[] |
no_license
|
Creamy1137689/kyopro
|
75bc3f92edb7bff2cbf27dc79d384b422a0a4702
|
dcacbf27defe840ea7998e06a5f3fb78718e7d53
|
refs/heads/master
| 2023-05-10T19:28:56.447493
| 2021-06-03T12:54:11
| 2021-06-03T12:54:11
| 266,143,691
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 108
|
cpp
|
#include <iostream>
using namespace std;
int a = 2;
void func(){
cout << "a = " << a << endl;
}
|
[
"exception031noexist@gmail.com"
] |
exception031noexist@gmail.com
|
2006b384960eb1e9fd372cd3dd3b67eb43aa3ead
|
1af49694004c6fbc31deada5618dae37255ce978
|
/chrome/browser/ui/views/frame/tab_strip_region_view_unittest.cc
|
777e9e998e7cab5a2f6c9c4fe0a1dd076e03b738
|
[
"BSD-3-Clause"
] |
permissive
|
sadrulhc/chromium
|
59682b173a00269ed036eee5ebfa317ba3a770cc
|
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
|
refs/heads/master
| 2023-02-02T07:59:20.295144
| 2020-12-01T21:32:32
| 2020-12-01T21:32:32
| 317,678,056
| 3
| 0
|
BSD-3-Clause
| 2020-12-01T21:56:26
| 2020-12-01T21:56:25
| null |
UTF-8
|
C++
| false
| false
| 10,510
|
cc
|
// Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/tab_strip_region_view.h"
#include <memory>
#include <string>
#include "base/feature_list.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/tabs/fake_base_tab_strip_controller.h"
#include "chrome/browser/ui/views/tabs/new_tab_button.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/browser/ui/views/tabs/tab_style_views.h"
#include "chrome/test/views/chrome_views_test_base.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
// TabStripRegionViewTestBase contains no test cases.
class TabStripRegionViewTestBase : public ChromeViewsTestBase {
public:
explicit TabStripRegionViewTestBase(bool has_scrolling)
: animation_mode_reset_(gfx::AnimationTestApi::SetRichAnimationRenderMode(
gfx::Animation::RichAnimationRenderMode::FORCE_ENABLED)) {
if (has_scrolling) {
scoped_feature_list_.InitWithFeatures({features::kScrollableTabStrip},
{});
} else {
scoped_feature_list_.InitWithFeatures({},
{features::kScrollableTabStrip});
}
}
TabStripRegionViewTestBase(const TabStripRegionViewTestBase&) = delete;
TabStripRegionViewTestBase& operator=(const TabStripRegionViewTestBase&) =
delete;
~TabStripRegionViewTestBase() override = default;
void SetUp() override {
ChromeViewsTestBase::SetUp();
auto controller = std::make_unique<FakeBaseTabStripController>();
controller_ = controller.get();
auto tab_strip = std::make_unique<TabStrip>(
std::unique_ptr<TabStripController>(controller.release()));
tab_strip_ = tab_strip.get();
controller_->set_tab_strip(tab_strip_);
widget_ = CreateTestWidget();
tab_strip_region_view_ = widget_->SetContentsView(
std::make_unique<TabStripRegionView>(std::move(tab_strip)));
// Prevent hover cards from appearing when the mouse is over the tab. Tests
// don't typically account for this possibly, so it can cause unrelated
// tests to fail due to tab data not being set. See crbug.com/1050012.
Tab::SetShowHoverCardOnMouseHoverForTesting(false);
}
void TearDown() override {
widget_.reset();
ChromeViewsTestBase::TearDown();
}
protected:
int GetInactiveTabWidth() { return tab_strip_->GetInactiveTabWidth(); }
void CompleteAnimationAndLayout() { tab_strip_region_view_->Layout(); }
// Owned by TabStrip.
FakeBaseTabStripController* controller_ = nullptr;
TabStrip* tab_strip_ = nullptr;
TabStripRegionView* tab_strip_region_view_ = nullptr;
std::unique_ptr<views::Widget> widget_;
private:
std::unique_ptr<base::AutoReset<gfx::Animation::RichAnimationRenderMode>>
animation_mode_reset_;
base::test::ScopedFeatureList scoped_feature_list_;
};
// TabStripRegionViewTest contains tests that will run with scrolling enabled
// and disabled.
class TabStripRegionViewTest : public TabStripRegionViewTestBase,
public testing::WithParamInterface<bool> {
public:
TabStripRegionViewTest() : TabStripRegionViewTestBase(GetParam()) {}
TabStripRegionViewTest(const TabStripRegionViewTest&) = delete;
TabStripRegionViewTest& operator=(const TabStripRegionViewTest&) = delete;
~TabStripRegionViewTest() override = default;
};
TEST_P(TabStripRegionViewTest, GrabHandleSpaceStaysVisible) {
const int kTabStripRegionViewWidth = 500;
tab_strip_region_view_->SetBounds(0, 0, kTabStripRegionViewWidth, 20);
for (int i = 0; i < 100; ++i) {
controller_->AddTab(i, (i == 0));
CompleteAnimationAndLayout();
EXPECT_LE(tab_strip_region_view_->reserved_grab_handle_space_for_testing()
->bounds()
.right(),
kTabStripRegionViewWidth);
}
}
TEST_P(TabStripRegionViewTest, NewTabButtonStaysVisible) {
const int kTabStripRegionViewWidth = 500;
tab_strip_region_view_->SetBounds(0, 0, kTabStripRegionViewWidth, 20);
for (int i = 0; i < 100; ++i) {
controller_->AddTab(i, (i == 0));
CompleteAnimationAndLayout();
EXPECT_LE(tab_strip_region_view_->new_tab_button()->bounds().right(),
kTabStripRegionViewWidth);
}
}
TEST_P(TabStripRegionViewTest, NewTabButtonRightOfTabs) {
const int kTabStripRegionViewWidth = 500;
tab_strip_region_view_->SetBounds(0, 0, kTabStripRegionViewWidth, 20);
controller_->AddTab(0, true);
CompleteAnimationAndLayout();
EXPECT_EQ(tab_strip_region_view_->new_tab_button()->bounds().x(),
tab_strip_->ideal_bounds(0).right());
}
TEST_P(TabStripRegionViewTest, NewTabButtonInkDrop) {
constexpr int kTabStripRegionViewWidth = 500;
tab_strip_region_view_->SetBounds(0, 0, kTabStripRegionViewWidth,
GetLayoutConstant(TAB_HEIGHT));
// Add a few tabs and simulate the new tab button's ink drop animation. This
// should not cause any crashes since the ink drop layer size as well as the
// ink drop container size should remain equal to the new tab button visible
// bounds size. https://crbug.com/814105.
for (int i = 0; i < 10; ++i) {
tab_strip_region_view_->new_tab_button()->AnimateInkDropToStateForTesting(
views::InkDropState::ACTION_TRIGGERED);
controller_->AddTab(i, true /* is_active */);
CompleteAnimationAndLayout();
tab_strip_region_view_->new_tab_button()->AnimateInkDropToStateForTesting(
views::InkDropState::HIDDEN);
}
}
// We want to make sure that the following children views sits flush with the
// top of tab strip region view:
// * tab strip
// * new tab button
// This is important in ensuring that we maximise the targetable area of these
// views when the tab strip is flush with the top of the screen when the window
// is maximized (Fitt's Law).
TEST_P(TabStripRegionViewTest, ChildrenAreFlushWithTopOfTabStripRegionView) {
tab_strip_region_view_->SetBounds(0, 0, 1000, 100);
controller_->AddTab(0, true);
CompleteAnimationAndLayout();
// The tab strip should sit flush with the top of the
// |tab_strip_region_view_|.
gfx::Point tab_strip_origin(tab_strip_->bounds().origin());
views::View::ConvertPointToTarget(tab_strip_, tab_strip_region_view_,
&tab_strip_origin);
EXPECT_EQ(0, tab_strip_origin.y());
// The new tab button should sit flush with the top of the
// |tab_strip_region_view_|.
gfx::Point new_tab_button_origin(
tab_strip_region_view_->new_tab_button()->bounds().origin());
views::View::ConvertPointToTarget(tab_strip_, tab_strip_region_view_,
&new_tab_button_origin);
EXPECT_EQ(0, new_tab_button_origin.y());
}
class TabStripRegionViewTestWithScrollingDisabled
: public TabStripRegionViewTestBase {
public:
TabStripRegionViewTestWithScrollingDisabled()
: TabStripRegionViewTestBase(false) {}
TabStripRegionViewTestWithScrollingDisabled(
const TabStripRegionViewTestWithScrollingDisabled&) = delete;
TabStripRegionViewTestWithScrollingDisabled& operator=(
const TabStripRegionViewTestWithScrollingDisabled&) = delete;
~TabStripRegionViewTestWithScrollingDisabled() override = default;
private:
};
// When scrolling is disabled, the tab strip cannot be larger than the container
// so tabs that do not fit in the tabstrip will become invisible. This is the
// opposite behavior from
// TabStripRegionViewTestWithScrollingEnabled.TabStripCanBeLargerThanContainer.
TEST_F(TabStripRegionViewTestWithScrollingDisabled,
TabStripCannotBeLargerThanContainer) {
const int minimum_active_width = TabStyleViews::GetMinimumInactiveWidth();
controller_->AddTab(0, true);
CompleteAnimationAndLayout();
// Add tabs to the tabstrip until it is full.
while (GetInactiveTabWidth() > minimum_active_width) {
controller_->AddTab(0, false);
CompleteAnimationAndLayout();
EXPECT_LT(tab_strip_->width(), tab_strip_region_view_->width());
}
// Add a few more tabs after the tabstrip is full to ensure tabs added
// afterwards are not visible.
for (int i = 0; i < 5; i++) {
controller_->AddTab(0, false);
CompleteAnimationAndLayout();
}
EXPECT_LT(tab_strip_->width(), tab_strip_region_view_->width());
EXPECT_FALSE(
tab_strip_->tab_at(tab_strip_->GetModelCount() - 1)->GetVisible());
}
class TabStripRegionViewTestWithScrollingEnabled
: public TabStripRegionViewTestBase {
public:
TabStripRegionViewTestWithScrollingEnabled()
: TabStripRegionViewTestBase(true) {}
TabStripRegionViewTestWithScrollingEnabled(
const TabStripRegionViewTestWithScrollingEnabled&) = delete;
TabStripRegionViewTestWithScrollingEnabled& operator=(
const TabStripRegionViewTestWithScrollingEnabled&) = delete;
~TabStripRegionViewTestWithScrollingEnabled() override = default;
};
// When scrolling is enabled, the tab strip can grow to be larger than the
// container. This is the opposite behavior from
// TabStripRegionViewTestWithScrollingDisabled.
// TabStripCannotBeLargerThanContainer.
TEST_F(TabStripRegionViewTestWithScrollingEnabled,
TabStripCanBeLargerThanContainer) {
const int minimum_active_width = TabStyleViews::GetMinimumInactiveWidth();
controller_->AddTab(0, true);
CompleteAnimationAndLayout();
// Add tabs to the tabstrip until it is full and should start overflowing.
while (GetInactiveTabWidth() > minimum_active_width) {
controller_->AddTab(0, false);
CompleteAnimationAndLayout();
EXPECT_LT(tab_strip_->width(), tab_strip_region_view_->width());
}
// Add a few more tabs after the tabstrip is full to ensure the tabstrip
// starts scrolling.
for (int i = 0; i < 5; i++) {
controller_->AddTab(0, false);
CompleteAnimationAndLayout();
}
EXPECT_GT(tab_strip_->width(), tab_strip_region_view_->width());
EXPECT_TRUE(
tab_strip_->tab_at(tab_strip_->GetModelCount() - 1)->GetVisible());
}
INSTANTIATE_TEST_SUITE_P(All,
TabStripRegionViewTest,
::testing::Values(true, false));
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
23bc53fd45e680ba0c26f56b848b54865723fedf
|
87ec6512217d88fc2919ec8ca1b336f6fb1b01e9
|
/Common/Sources/VProjectItem.h
|
7f5c877fe75f8fff4ecf28d001cee2bdc1e229b5
|
[] |
no_license
|
tzuchiangshen/core-Wakanda
|
9002e7013e0b2221217373deb4713030f7cb296c
|
c1b4fb1ef7bce79b3d3d453a4112e77d6d37ba36
|
refs/heads/master
| 2021-01-17T08:46:59.059280
| 2013-05-16T15:03:30
| 2013-05-16T15:03:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26,875
|
h
|
/*
* This file is part of Wakanda software, licensed by 4D under
* (i) the GNU General Public License version 3 (GNU GPL v3), or
* (ii) the Affero General Public License version 3 (AGPL v3) or
* (iii) a commercial license.
* This file remains the exclusive property of 4D and/or its licensors
* and is protected by national and international legislations.
* In any event, Licensee's compliance with the terms and conditions
* of the applicable license constitutes a prerequisite to any use of this file.
* Except as otherwise expressly stated in the applicable license,
* such license does not include any other license or rights on this file,
* 4D's and/or its licensors' trademarks and/or other proprietary rights.
* Consequently, no title, copyright or other proprietary rights
* other than those specified in the applicable license is granted.
*/
// ----------------------------------------------------------------------------
#ifndef __VPROJECTITEM__
#define __VPROJECTITEM__
#include "VSolutionManagerInterface.h"
// ci-dessous, doit etre >= 1 car utilise comme parametre inUserItemRef dans
// VTreeItem(inString, inUserItemRef, inIconID, inAnonymousData, fDatabase)
#define PROJECT_ITEM_INDEX_START 1
// ----------------------------------------------------------------------------
// Classe pour representer tous les items d'une solution
// en fait ce sont un peu comme des proxy qui permettent d'acceder facilement
// aux ressources physiques
// Les VProjectItems ont une structure d'arbre dont la racine est l'element solution
// ----------------------------------------------------------------------------
class VProject;
class VSolution;
class VProjectItemBehaviour;
class VCatalog;
class VProjectItem : public XBOX::VObject, public XBOX::IRefCountable
{
public:
friend class VProjectItemIterator;
friend class VSolution;
friend class VProject;
friend class VCatalog;
friend class VSolutionExplorerDialog;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 230409 : ATTENTION !!! toute modification ici doit etre reportee dans la methode
// SOLUTION_CONSTANTS du code 4D associe au Solution Manager
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
typedef enum {
eUNDEFINED = 0, // item de type non defini : ne doit pas se produire
eFILE = 1,
eCATALOG_FILE = 5,
eFOLDER = 500, // dossier physique
ePROJECT = 501, // dossier physique et projet
eMEDIA_LIBRARY = 502,
eDATA_CLASS = 901,
eDATA_CLASS_ATTRIBUTE = 902,
eSOLUTION = 1000,
// -------------------------------
// !!! CI-DESSOUS : NE PAS PRENDRE EN COMPTE !!!
// > 10000 : ne sont pas utilises directement dans les projectItems,
// mais permettent d'unifier certains traitements -> pur trick
// voir VProjectItemManager::CountProjectItemsContains
// -------------------------------
eEXTERNAL_REFERENCE = 10000
} e_ProjectItemKind;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 230409 : ATTENTION !!! toute modification ci-dessus doit etre reportee dans la
// methode PjM_INIT du code 4D associe au Solution Manager
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// --------------------------
// Constructeurs, destructeur
// --------------------------
VProjectItem(e_ProjectItemKind inKind = eUNDEFINED);
VProjectItem(const XBOX::VURL& inURL, e_ProjectItemKind inKind = eUNDEFINED);
VProjectItem( VProjectItemBehaviour *inBehaviour);
virtual ~VProjectItem();
// -------------------------------------------------------------------------
// Properties accessors
/** @brief inName is the full item name (with the extension) */
void SetName( const XBOX::VString& inName);
void GetName( XBOX::VString& outName, bool inWithExtension = true) const;
void GetNameWithoutExtension( XBOX::VString& outName) const;
void GetExtension( XBOX::VString& outExtension) const;
void SetDisplayName( const XBOX::VString& inDisplayName) { fDisplayName = inDisplayName; }
void GetDisplayName( XBOX::VString& outName) const { outName = fDisplayName; }
const XBOX::VString& GetDisplayName() const { return fDisplayName; }
/** @brief The item becomes the owner of the behaviour.
The behaviour is used to manage the item content. */
void SetBehaviour( VProjectItemBehaviour *inBehaviour);
VProjectItemBehaviour* GetBehaviour() const;
/** @brief the user data is retained */
void SetUserData( XBOX::IRefCountable *inUserData);
XBOX::IRefCountable* GetUserData() const;
bool HasUserData() const { return fUserData != NULL; }
// Tags utilities : an item can be associated with one or several tags
void AddTag( const VProjectItemTag& inTag);
void RemoveTag( const VProjectItemTag& inTag);
void RemoveAllTags();
bool IsTagged() const;
bool HasTag( const VProjectItemTag& inTag) const;
void GetTags( std::vector<VProjectItemTag>& outTags) const;
e_ProjectItemKind GetKind() const;
bool ConformsTo( const XBOX::VString& inFileKindID) const;
void GetDescription( XBOX::VString& outDescription) const;
void Touch();
uLONG GetStamp() const;
XBOX::VValueBag* GetBag() const { return fBag; }
void SetExternalReference( bool inExternalReference) { fExternalReference = inExternalReference; }
bool IsExternalReference() const { return fExternalReference; }
/** @brief The physical link is valid when the physical item exists.
Used only in the case of referenced items. */
void SetPhysicalLinkValid( bool inSet) { fPhysicalLinkValid = inSet; }
bool IsPhysicalLinkValid() const { return fPhysicalLinkValid; }
XBOX::VString GetXMLElementName() const;
// URL and path accessors
void SetURL( const XBOX::VURL& inURL);
bool GetURL( XBOX::VURL& outURL) const;
XBOX::VURL GetURL() const;
// The path is relative to the parent item
bool HasRelativePath() const { return !fRelativePath.IsEmpty(); }
void SetRelativePath( const XBOX::VString& inRelativePath, XBOX::EURLPathStyle inStyle = XBOX::eURL_POSIX_STYLE);
void GetRelativePath( XBOX::VString& outRelativePath, XBOX::EURLPathStyle inStyle = XBOX::eURL_POSIX_STYLE) const;
// Parent solution accessors
VSolution* GetSolutionOwner();
VProjectItem* GetProjectItemSolutionOwner();
// Parent project accessors
VProject* GetProjectOwner();
VProjectItem* GetProjectItemProjectOwner();
/** @brief Returns the item unique ID. */
sLONG GetID() const { return fID; }
// -------------------------------------------------------------------------
// Children accessors
VProjectItem* FindChildByID( sLONG inID) const;
VProjectItem* FindChildByRelativePath( const XBOX::VString& inRelativePath, XBOX::EURLPathStyle inStyle = XBOX::eURL_POSIX_STYLE) const;
void GetTaggedChildren( VectorOfProjectItems& ioItems, bool inRecursive) const;
// -------------------------------------------------------------------------
// Content accessors (the content is for exemple the physical file or physical folder)
bool ContentExists() const;
/** @brief Delete the item content */
XBOX::VError DeleteContent();
/** @brief Rename the item content.
If the rename succeeded, all dependent properties are updated: name, display name, url or relative path. */
XBOX::VError RenameContent( const XBOX::VString& inNewName);
XBOX::VError CreateContent();
// --------------------------
// Path, URL
// --------------------------
// si le VProjectItem est un fichier physique (ou un folder), GetFilePath
// renseigne outFilePath avec le VFilePath correspondant.
// GetFilePath retourne false si ce n'est pas un fichier physique
// >>> YOU MUST USE THIS METHOD TO GET VFilePath <<<
// >>> Ne pas passer par l'URL en general car pas forcement definie <<<
bool GetFilePath(XBOX::VFilePath& outFilePath) const;
// Reserver les URL lorsque l'on a besoin de stocker un chemin absolu ou
// manier les eURL_POSIX_STYLE, etc
// construit le path complet sous forme de VString (au format eURL_NATIVE_STYLE) a partir des localPaths
bool BuildFullPath(XBOX::VString& outFullPath) const;
// --------------------------
// Path logique
// --------------------------
// construit le path logique complet sous forme de String
void BuildLogicalFullPath(XBOX::VString& outFullPath);
// fournit la liste des items d'un type donne, enfants de l'item appelant :
void GetProjectItemsList(uWORD inProjectItemKind, std::list<VProjectItem*>& outProjectItemsList, bool inIncludeMe = true);
void GetProjectItemsVector(uWORD inProjectItemKind, VectorOfProjectItems& outProjectItemsVector, bool inIncludeMe = true);
// fournit la liste des items d'une extension donnee, enfants de l'item appelant et de type eFILE :
void GetProjectItemsVector(XBOX::VString inExtension, VectorOfProjectItems& outProjectItemsVector, bool inIncludeMe = true, bool inRecursive = true);
// trouve s'il existe le premier VProjectItem* ayant un VFilePath specifique parmi les enfants du VProjectItem this
VProjectItem* FindProjectItemInChildren(const XBOX::VFilePath& inVFilePath, bool inIncludeMe = true);
// --------------------------
// Methodes booleennes
// --------------------------
bool CheckAnyProjectItemParentIsExternalReference(bool inIncludeMe = false) const;
// ------------------------------------
// Structure en arbre des VProjectItems
// ------------------------------------
void AttachChild(VProjectItem* inProjectItem);
void DetachChild(VProjectItem* inProjectItem);
void SetParent(VProjectItem* inParent) {fParent = inParent;}
VProjectItem* GetParent() const {return fParent;}
VProjectItem* NewChild(e_ProjectItemKind inKind = eUNDEFINED);
VProjectItem* NewChild(const XBOX::VURL& inURL, e_ProjectItemKind inKind = eUNDEFINED);
inline bool HasChildren() const;
void DeleteChildren();
inline sLONG GetCountChildren() const;
// -------------------
// Methodes Is, Has...
// -------------------
bool IsChildOf(VProjectItem* inProjectItem) const;
bool IsParentOf( VProjectItem* inProjectItem) const;
bool HasFilePath() const;
bool IsPhysicalFileOrFolder() const;
bool IsPhysicalFile() const;
bool IsPhysicalFolder() const;
bool IsVirtualFolder() const;
bool IsSystemFile() const; // comprendre que le fichier est considere comme un fichier systeme pour nous (Wakanda)
// -------------------
// Proprietes "speciales" des VProjectItems
// -------------------
// pour signifier un objet physique associe detruit ou dereference
void SetGhost(bool inGhost);
bool IsGhost() const {return fGhost;}
// ---------------
// Autres methodes
// ---------------
// profondeur de l'item
void SetLevel(sLONG level) {fLevel = level;};
sLONG GetLevel() {return fLevel;};
// ---------------------------------
// Manipulation de l'item physique
// ---------------------------------
bool CreatePhysicalItem();
bool CopyPhysicalItemFrom(const XBOX::VURL& inSrcURL);
bool CopyOrMovePhysicalItemTo(const XBOX::VURL& inSrcURL, const XBOX::VURL& inDestURL, bool inCopy);
bool CreatePhysicalChildren(bool inRecursive);
protected:
void _GetProjectItemsVector(uWORD inProjectItemKind, VectorOfProjectItems& outProjectItemsVector);
void _GetProjectItemsVector(XBOX::VString inExtension, VectorOfProjectItems& outProjectItemsVector, bool inRecursive);
// ci-dessous, methode tres lente, a utiliser ponctuellement : on lui preferera la methode
// GetProjectItemFromFullPath d'un VProject lorsque possible
VProjectItem* _FindProjectItemInChildren(const XBOX::VFilePath& inVFilePath);
XBOX::VURL fURL;
XBOX::VValueBag* fBag;
bool fExternalReference;
ListOfProjectItem fChildren;
private:
void _CreateItemBehaviour( e_ProjectItemKind inKind);
// retrouver un (ou +r) VProjectItem depuis path partiel
bool _GetProjectItemFromPartialPath(const XBOX::VString& inPartialPath, VectorOfProjectItems& ioFoundProjectItems);
VProjectItem* _GetProjectItemFromPartialPath(const XBOX::VString& inPartialPath); // SI ON SAIT que la reponse est unique
bool _AutoRegisterInMapOfFullPathes(bool inRegisterChildren);
bool _AutoUnregisterFromMapOfFullPathes(bool inUnregisterChildren);
void _SetGhost(bool inGhost) {fGhost = inGhost;}
XBOX::VString fName; // the full item name (with extension)
XBOX::VString fDisplayName; // nom affiche
uLONG fStamp;
XBOX::VString fRelativePath; // The path relative to the parent item
sLONG fID; // cree initialement pour pouvoir reperer un item depuis la ListBox du SolutionExplorer
// Structure d'arbre
VProjectItem* fParent;
// ci-dessous : toujours utiliser les methodes GetProjectItemSolutionOwner et GetProjectItemProjectOwner pour y acceder !!!
// you must always use GetProjectItemSolutionOwner() instead fProjectItemSolutionOwner
VProjectItem* fProjectItemSolutionOwner;// pointeur sur la solution proprietaire pour des raisons d'optimisation
// you must always use GetProjectItemProjectOwner() instead fProjectItemProjectOwner
VProjectItem* fProjectItemProjectOwner; // pointeur sur le projet proprietaire pour des raisons d'optimisation
VProjectItemBehaviour* fBehaviour; // definit le comportement de l'item physique
// associe au VProjectItem (pattern Strategie)
// n'est cree que si necessaire (pattern Procuration)
sLONG fLevel; // indique la profondeur du VProjectItem dans l'arbre
bool fPhysicalLinkValid; // un item reference dans le fichier projet mais inexistant physiquement
bool fGhost; // a cause des Retain-Release, la duree de vie d'un VProjectItem
// peut etre plus longue que l'objet auquel il est associe... surtout
// vrai dans le cas du deplacement d'un fichier depuis l'exterieur
// fGhost indique que l'on a affaire a un item fantome (brrr)
std::vector<VProjectItemTag> fTags;
XBOX::IRefCountable *fUserData;
};
// ----------------------------------------------------------------------------
// Classe VProjectItemIterator pour faciliter les operations sur l'arbre des VProjectItems
// ----------------------------------------------------------------------------
class VProjectItemIterator : public XBOX::VObject
{
public:
VProjectItemIterator(const VProjectItem* inProjectItem);
const VProjectItemIterator& operator++() { ++fCurrent; return *this; }
operator VProjectItem*() { return *fCurrent; }
VProjectItem* operator->() { return *fCurrent; }
VProjectItem& operator*() { return *(*fCurrent); }
bool IsValid() const { return /*(fProjectItems != NULL) &&*/ (fCurrent != fProjectItems.end());}
private:
ListOfProjectItem fProjectItems;
std::list<VProjectItem*>::iterator fCurrent;
};
// ----------------------------------------------------------------------------
// VProjectItemManager class
// ----------------------------------------------------------------------------
class VProjectItemManager : public XBOX::VObject
{
public:
virtual ~VProjectItemManager();
static VProjectItemManager* Get();
static bool Init( bool inWithProjectItemUniqueID);
static void DeInit();
bool IsProjectItemUniqueIDRequired() const { return fWithProjectItemUniqueID; }
sLONG RegisterProjectItem( VProjectItem *inProjectItem);
void UnregisterProjectItem( VProjectItem *inProjectItem);
VProjectItem* GetProjectItemFromID( sLONG inID) const;
// ---------------------------------------
// Fonctions utilitaires sur fichiers et les folders
// ---------------------------------------
sLONG CountProjectItemsContains(const VectorOfProjectItems& inProjectItems, VProjectItem::e_ProjectItemKind inProjectItemKind);
static sLONG GetFilesCountInFolderAndSubfolder(const XBOX::VFolder& inFolder);
static bool FileCopyTo(const XBOX::VURL& inSrcURL, const XBOX::VURL& inDestURL);
static bool FileMoveTo(const XBOX::VURL& inSrcURL, const XBOX::VURL& inDestURL);
static bool FolderCopyOrMoveTo(const XBOX::VURL& inSrcURL, const XBOX::VURL& inDestURL, bool inCopy);
static bool FileCopyTo(const XBOX::VFilePath& inSrcFilePath, const XBOX::VFilePath& inDestFilePath, XBOX::VProgressIndicator* inProgressIndicator = NULL, bool* outUserAbort = NULL);
static bool FileMoveTo(const XBOX::VFilePath& inSrcFilePath, const XBOX::VFilePath& inDestFilePath, XBOX::VProgressIndicator* inProgressIndicator = NULL, bool* outUserAbort = NULL);
static bool FolderCopyTo(const XBOX::VFilePath& inSrcFilePath, const XBOX::VFilePath& inDestFilePath, XBOX::VProgressIndicator* inProgressIndicator = NULL, bool* outUserAbort = NULL);
static bool FolderMoveTo(const XBOX::VFilePath& inSrcFilePath, const XBOX::VFilePath& inDestFilePath, XBOX::VProgressIndicator* inProgressIndicator = NULL, bool* outUserAbort = NULL);
static bool FolderCopyOrMoveTo(const XBOX::VFilePath& inSrcFilePath, const XBOX::VFilePath& inDestFilePath, bool inCopy);
private:
VProjectItemManager( bool inWithProjectItemUniqueID);
VProjectItemManager (const VProjectItemManager &);
VProjectItemManager& operator=(const VProjectItemManager&);
static VProjectItemManager *sProjectItemManager;
std::map< sLONG , VProjectItem* > fMapOfProjectItemIDs;
sLONG fNextProjectItemID;
bool fWithProjectItemUniqueID;
};
// ----------------------------------------------------------------------------
// Pattern Composite
// ----------------------------------------------------------------------------
class IProjectItemFilter : public XBOX::IRefCountable
{
public:
virtual void Reset() = 0;
virtual void AddProjectItemFilter(IProjectItemFilter* inProjectItemFilter) = 0;
virtual bool Matches(VProjectItem* inProjectItem) const = 0;
};
// filtre tres simple : test sur l'extension et/ou sur le motif du filtre
class VProjectItemBasicFilter : public XBOX::VObject, public IProjectItemFilter
{
public:
typedef enum {
eEXTENSION_NONE,
eEXTENSION_BEGINS_WITH,
eEXTENSION_EQUALS_TO,
eEXTENSION_CONTAINS,
eEXTENSION_ENDS_WITH,
eEXTENSION_BEGINS_WITH_AND_ENDS_WITH
} e_FilterExtensionAction;
typedef enum {
eMOTIF_NONE,
eMOTIF_BEGINS_WITH,
eMOTIF_EQUALS_TO,
// recherche stricte sur le nom sans l'extension
eMOTIF_STRICTLY_CONTAINS,
eMOTIF_STRICTLY_ENDS_WITH,
eMOTIF_STRICTLY_BEGINS_WITH_AND_ENDS_WITH,
// recherche large sur le nom complet (avec l'extension)
eMOTIF_CONTAINS,
eMOTIF_ENDS_WITH
} e_FilterMotifAction;
// --------------------------
// Constructeurs, destructeur
// --------------------------
VProjectItemBasicFilter(XBOX::VString inFilterExtensionStart = "",
XBOX::VString inFilterExtension = "",
XBOX::VString inFilterExtensionEnd = "",
e_FilterExtensionAction inFilterExtensionAction = eEXTENSION_CONTAINS,
XBOX::VString inFilterMotifStart = "",
XBOX::VString inFilterMotif = "",
XBOX::VString inFilterMotifEnd = "",
e_FilterMotifAction inFilterMotifAction = eMOTIF_CONTAINS);
virtual ~VProjectItemBasicFilter();
void SetFilter( XBOX::VString inFilterExtensionStart = "",
XBOX::VString inFilterExtension = "",
XBOX::VString inFilterExtensionEnd = "",
e_FilterExtensionAction inFilterExtensionAction = eEXTENSION_CONTAINS,
XBOX::VString inFilterMotifStart = "",
XBOX::VString inFilterMotif = "",
XBOX::VString inFilterMotifEnd = "",
e_FilterMotifAction inFilterMotifAction = eMOTIF_CONTAINS);
void Reset() {SetFilter();};
void AddProjectItemFilter(IProjectItemFilter* inProjectItemFilter) {};
bool Matches(VProjectItem* inProjectItem) const;
protected:
private:
XBOX::VString fFilterExtensionStart;
XBOX::VString fFilterExtension;
XBOX::VString fFilterExtensionEnd;
e_FilterExtensionAction fFilterExtensionAction;
XBOX::VString fFilterMotif;
XBOX::VString fFilterMotifStart;
XBOX::VString fFilterMotifEnd;
e_FilterMotifAction fFilterMotifAction;
};
// filtre compose de la reunion de VProjectItemBasicFilter...
typedef std::vector<IProjectItemFilter*> VectorOfProjectItemFilters;
typedef std::vector<IProjectItemFilter*>::iterator VectorOfProjectItemFiltersIterator;
typedef std::vector<IProjectItemFilter*>::const_iterator VectorOfProjectItemFiltersConstIterator;
class VProjectItemFilter : public XBOX::VObject, public IProjectItemFilter
{
public:
// --------------------------
// Constructeurs, destructeur
// --------------------------
VProjectItemFilter() {};
virtual ~VProjectItemFilter() {};
void Reset();
void AddProjectItemFilter(IProjectItemFilter* inProjectItemFilter) {projectItemFilters.push_back(inProjectItemFilter);};
bool Matches(VProjectItem* inProjectItem) const;
protected:
private:
VectorOfProjectItemFilters projectItemFilters;
};
// ----------------------------------------------------------------------------
// Fonctions inline
// ----------------------------------------------------------------------------
inline bool VProjectItem::HasChildren() const
{
return !fChildren.empty();
}
inline sLONG VProjectItem::GetCountChildren() const
{
return (sLONG) fChildren.size();
}
// ----------------------------------------------------------------------------
// Project items static utilities
class VProjectItemTools
{
public:
/** @brief Remove the items for which an ancestor is already in the vector. */
static void RemoveUselessItems( VectorOfProjectItems& ioItems);
/** @brief Returns the flattened children list. */
static void GetChildren( VProjectItem *inProjectItem, VectorOfProjectItems& ioChildren, bool inRecursive);
/** @brief Returns the flattened list of child file. */
static void GetChildFile( VProjectItem *inProjectItem, VectorOfProjectItems& ioChildren, bool inRecursive);
static VProjectItem* GetFirstCommonParent( const VectorOfProjectItems &inProjectItems);
};
// ----------------------------------------------------------------------------
// Project item role constants
extern const VProjectItemTag kSettingTag;
extern const VProjectItemTag kCatalogTag;
extern const VProjectItemTag kBackupsTag;
extern const VProjectItemTag kDataTag;
extern const VProjectItemTag kDataFolderTag;
extern const VProjectItemTag kRPCCatalogTag;
extern const VProjectItemTag kBootstrapTag;
extern const VProjectItemTag kUAGDirectoryTag;
extern const VProjectItemTag kPermissionsTag;
extern const VProjectItemTag kWebFolderTag;
extern const VProjectItemTag kWebComponentFolderTag;
extern const VProjectItemTag kProjectCertificatesFolderTag;
extern const VProjectItemTag kSolutionCertificatesFolderTag;
enum
{
ePITP_Default = 0x00000000,
ePITP_ApplyToSingleFile = 0x00000001,
ePITP_ApplyToMultipleFiles = 0x00000002,
ePITP_ApplyToSingleFolder = 0x00000004,
ePITP_ApplyToMultipleFolders = 0x00000008,
ePITP_ApplyToFolderContent = 0x00000010
};
typedef uLONG EProjectItemTagProperties;
namespace ProjectItemTagBagKeys
{
EXTERN_BAGKEY_WITH_DEFAULT( fileKindID, XBOX::VString);
EXTERN_BAGKEY_WITH_DEFAULT_SCALAR( properties, XBOX::VLong, uLONG);
EXTERN_BAGKEY( defaultFolders);
EXTERN_BAGKEY( defaultFiles);
EXTERN_BAGKEY_NO_DEFAULT( path, XBOX::VString);
EXTERN_BAGKEY( extraBag);
}
class VProjectItemTagManager : public XBOX::VObject
{
public:
typedef std::map< VProjectItemTag, XBOX::VRefPtr<XBOX::VValueBag> > MapOfTagInfo;
typedef std::map< VProjectItemTag, XBOX::VRefPtr<XBOX::VValueBag> >::iterator MapOfTagInfo_iter;
typedef std::map< VProjectItemTag, XBOX::VRefPtr<XBOX::VValueBag> >::const_iterator MapOfTagInfo_citer;
static VProjectItemTagManager* Get();
static bool Init();
static void DeInit();
/** @brief Returns false if the tag is already registered */
bool RegisterProjectItemTag( const VProjectItemTag& inTag,
const XBOX::VString& inDefaultFileKindID,
EProjectItemTagProperties inProperties,
const XBOX::VectorOfVString* inDefaultFolders,
const XBOX::VectorOfVString* inDefaultFiles);
bool IsRegisteredProjectItemTag( const VProjectItemTag& inTag) const;
void GetProjectItemTagCollection( std::vector<VProjectItemTag>& outTags) const;
/** @brief Returns false if the tag is not registered or if the default file kind is unknown */
bool GetDefaultFileKindID( const VProjectItemTag& inTag, XBOX::VString& outFileKindID) const;
/** @brief Returns false if the tag is not registered or if the default extension is unknown */
bool GetDefaultExtension( const VProjectItemTag& inTag, XBOX::VString& outExtension) const;
/** @brief Returns NULL if the tag is not registered or if the default file kind is unknown */
XBOX::VFileKind* RetainDefaultFileKind( const VProjectItemTag& inTag) const;
/** @brief Returns ePITP_Default if the tag is not registered */
EProjectItemTagProperties GetProperties( const VProjectItemTag& inTag) const;
/** @brief Returns a vector of posix folder paths relative to the project folder to use by default.
An empty path means that the project folder must be used as a default folder.
The prefered default folder is the first item of the vector
Returns false if the tag is not registered or if the tag has none default folders */
bool GetDefaultFolders( const VProjectItemTag& inTag, XBOX::VectorOfVString& outPaths) const;
bool GetPreferedDefaultFolder( const VProjectItemTag& inTag, XBOX::VString& outPath) const;
/** @brief Returns a vector of posix file paths relative to the project folder to use by default.
The prefered default file is the first item of the vector
Returns false if the tag is not registered or if the tag has none default files */
bool GetDefaultFiles( const VProjectItemTag& inTag, XBOX::VectorOfVString& outPaths) const;
/** @brief The extra bag is retained */
bool SetExtraBag( const VProjectItemTag& inTag, XBOX::VValueBag* inBag) const;
XBOX::VValueBag* RetainExtraBag( const VProjectItemTag& inTag) const;
// Utilities
static bool Find( const VProjectItemTag& inTag, const std::vector<VProjectItemTag>& inWhere);
private:
VProjectItemTagManager() {;}
virtual ~VProjectItemTagManager() {;}
void _VectorOfPathsToBagArray( const XBOX::VectorOfVString& inPaths, XBOX::VBagArray& outBagArray) const;
void _BagArrayToVectorOfPaths( const XBOX::VBagArray& inBagArray, XBOX::VectorOfVString& outPaths) const;
static VProjectItemTagManager *sManager;
MapOfTagInfo fMapOfTagsInfo; // the key is the project item tag
};
#endif
|
[
"stephane.hamel@4d.com"
] |
stephane.hamel@4d.com
|
a7882dffa1aa051e05426ad1969acac3dced30e5
|
17b9e156eafafe2b2ec34bedbe54dd1c072fc8da
|
/src/rpcblockchain.cpp
|
edc590febbd48db3be0df50d7158579f924cb258
|
[
"MIT"
] |
permissive
|
Nikita8669/ZaardeCore
|
39af59cabba96fb58da6eea151e46139c4bd81ce
|
9bc06bb2a5d364fbdcb4071dd457dcf82cf2aceb
|
refs/heads/master
| 2020-09-03T18:25:09.447435
| 2019-11-04T16:17:58
| 2019-11-04T16:17:58
| 219,532,505
| 0
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 38,192
|
cpp
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "consensus/validation.h"
#include "main.h"
#include "rpcserver.h"
#include "sync.h"
#include "txdb.h"
#include "util.h"
#include "utilmoneystr.h"
#include <stdint.h>
#include <univalue.h>
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry, bool include_hex, int serialize_flags);
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL) {
if (chainActive.Tip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29) {
dDiff *= 256.0;
nShift++;
}
while (nShift > 29) {
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", blockindex->nVersion));
result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
result.push_back(Pair("time", (int64_t)blockindex->nTime));
result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
result.push_back(Pair("acc_checkpoint", blockindex->nAccumulatorCheckpoint.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", block.GetHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS)));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("cost", (int)::GetBlockCost(block)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("acc_checkpoint", block.nAccumulatorCheckpoint.GetHex()));
UniValue txs(UniValue::VARR);
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (txDetails) {
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(0), objTx, true, RPCSerializationFlags());
txs.push_back(objTx);
} else
txs.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex* pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
result.push_back(Pair("moneysupply",ValueFromAmount(blockindex->nMoneySupply)));
UniValue zphrObj(UniValue::VOBJ);
for (auto denom : libzerocoin::zerocoinDenomList) {
zphrObj.push_back(Pair(to_string(denom), ValueFromAmount(blockindex->mapZerocoinSupply.at(denom) * (denom*COIN))));
}
zphrObj.push_back(Pair("total", ValueFromAmount(blockindex->GetZerocoinSupply())));
result.push_back(Pair("zZARDsupply", zphrObj));
return result;
}
UniValue getblockcount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the longest block chain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n" +
HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", ""));
LOCK(cs_main);
return chainActive.Height();
}
UniValue getbestblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest block chain.\n"
"\nResult\n"
"\"hex\" (string) the block hash hex encoded\n"
"\nExamples\n" +
HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", ""));
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
UniValue getdifficulty(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n" +
HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", ""));
LOCK(cs_main);
return GetDifficulty();
}
UniValue mempoolToJSON(bool fVerbose = false)
{
if (fVerbose) {
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
BOOST_FOREACH (const PAIRTYPE(uint256, CTxMemPoolEntry) & entry, mempool.mapTx) {
const uint256& hash = entry.first;
const CTxMemPoolEntry& e = entry.second;
UniValue info(UniValue::VOBJ);
info.push_back(Pair("size", (int)e.GetTxSize()));
info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
info.push_back(Pair("time", e.GetTime()));
info.push_back(Pair("height", (int)e.GetHeight()));
info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
const CTransaction& tx = e.GetTx();
set<string> setDepends;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
BOOST_FOREACH(const string& dep, setDepends) {
depends.push_back(dep);
}
info.push_back(Pair("depends", depends));
o.push_back(Pair(hash.ToString(), info));
}
return o;
} else {
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
BOOST_FOREACH (const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
}
UniValue getrawmempool(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
" \"size\" : n, (numeric) transaction size in bytes\n"
" \"fee\" : n, (numeric) transaction fee in zaarde\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) transaction priority now\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n"
" }, ...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true"));
LOCK(cs_main);
bool fVerbose = false;
if (params.size() > 0)
fVerbose = params[0].get_bool();
return mempoolToJSON(fVerbose);
}
UniValue getblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash index\n"
"\nReturns hash of block in best-block-chain at index provided.\n"
"\nArguments:\n"
"1. index (numeric, required) The block index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n" +
HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000"));
LOCK(cs_main);
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
UniValue getblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbose is true, returns an Object with information about block <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
" \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n"
" \"zZARDsupply\" :\n"
" {\n"
" \"1\" : n, (numeric) supply of 1 zZARD denomination\n"
" \"5\" : n, (numeric) supply of 5 zZARD denomination\n"
" \"10\" : n, (numeric) supply of 10 zZARD denomination\n"
" \"50\" : n, (numeric) supply of 50 zZARD denomination\n"
" \"100\" : n, (numeric) supply of 100 zZARD denomination\n"
" \"500\" : n, (numeric) supply of 500 zZARD denomination\n"
" \"1000\" : n, (numeric) supply of 1000 zZARD denomination\n"
" \"5000\" : n, (numeric) supply of 5000 zZARD denomination\n"
" \"total\" : n, (numeric) The total supply of all zZARD denominations\n"
" }\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n" +
HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\""));
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!ReadBlockFromDisk(block, pblockindex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
if (!fVerbose) {
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
UniValue getblockheader(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n"
"If verbose is true, returns an Object with information about block <hash> header.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
" \"cost\" : n (numeric) The block cost\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"nonce\" : n, (numeric) The nonce\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash' header.\n"
"\nExamples:\n" +
HelpExampleCli("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\""));
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!fVerbose) {
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) the best block hash hex\n"
" \"transactions\": n, (numeric) The number of transactions\n"
" \"txouts\": n, (numeric) The number of output transactions\n"
" \"bytes_serialized\": n, (numeric) The serialized size\n"
" \"hash_serialized\": \"hash\", (string) The serialized hash\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", ""));
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (pcoinsTip->GetStats(stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
UniValue gettxout(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout \"txid\" n ( includemempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout value\n"
"3. includemempool (boolean, optional) Whether to included the mem pool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in zaarde\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, e.g. pubkeyhash\n"
" \"addresses\" : [ (array of string) array of zaarde addresses\n"
" \"zaardeaddress\" (string) zaarde address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1"));
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
int n = params[1].get_int();
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
CCoins coins;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
if (!view.GetCoins(hash, coins))
return NullUniValue;
mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
} else {
if (!pcoinsTip->GetCoins(hash, coins))
return NullUniValue;
}
if (n < 0 || (unsigned int)n >= coins.vout.size() || coins.vout[n].IsNull())
return NullUniValue;
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex* pindex = it->second;
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
ret.push_back(Pair("confirmations", 0));
else
ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("version", coins.nVersion));
ret.push_back(Pair("coinbase", coins.fCoinBase));
return ret;
}
UniValue verifychain(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain ( numblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n" +
HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", ""));
LOCK(cs_main);
int nCheckLevel = 4;
int nCheckDepth = GetArg("-checkblocks", 288);
if (params.size() > 0)
nCheckDepth = params[1].get_int();
fVerifyingBlocks = true;
bool fVerified = CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth);
fVerifyingBlocks = false;
return fVerified;
}
UniValue getblockchaininfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding block chain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", ""));
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight {
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
UniValue getchaintips(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getchaintips\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n" +
HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", ""));
LOCK(cs_main);
/* Build up a list of chain tips. We start with the list of all
known blocks, and successively remove blocks that appear as pprev
of another block. */
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex)
setTips.insert(item.second);
BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) {
const CBlockIndex* pprev = item.second->pprev;
if (pprev)
setTips.erase(pprev);
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
/* Construct the output array. */
UniValue res(UniValue::VARR);
BOOST_FOREACH (const CBlockIndex* block, setTips) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("height", block->nHeight));
obj.push_back(Pair("hash", block->phashBlock->GetHex()));
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
obj.push_back(Pair("branchlen", branchLen));
string status;
if (chainActive.Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.push_back(Pair("status", status));
res.push_back(obj);
}
return res;
}
UniValue getfeeinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getfeeinfo blocks\n"
"\nReturns details of transaction fees over the last n blocks.\n"
"\nArguments:\n"
"1. blocks (int, required) the number of blocks to get transaction data from\n"
"\nResult:\n"
"{\n"
" \"txcount\": xxxxx (numeric) Current tx count\n"
" \"txbytes\": xxxxx (numeric) Sum of all tx sizes\n"
" \"ttlfee\": xxxxx (numeric) Sum of all fees\n"
" \"feeperkb\": xxxxx (numeric) Average fee per kb over the block range\n"
" \"rec_highpriorityfee_perkb\": xxxxx (numeric) Recommended fee per kb to use for a high priority tx\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getfeeinfo", "5") + HelpExampleRpc("getfeeinfo", "5"));
LOCK(cs_main);
int nBlocks = params[0].get_int();
int nBestHeight = chainActive.Height();
int nStartHeight = nBestHeight - nBlocks;
if (nBlocks < 0 || nStartHeight <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid start height");
CAmount nFees = 0;
int64_t nBytes = 0;
int64_t nTotal = 0;
for (int i = nStartHeight; i <= nBestHeight; i++) {
CBlockIndex* pindex = chainActive[i];
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read block from disk");
CAmount nValueIn = 0;
CAmount nValueOut = 0;
for (const CTransaction& tx : block.vtx) {
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
for (unsigned int j = 0; j < tx.vin.size(); j++) {
if (tx.vin[j].scriptSig.IsZerocoinSpend()) {
nValueIn += tx.vin[j].nSequence * COIN;
continue;
}
COutPoint prevout = tx.vin[j].prevout;
CTransaction txPrev;
uint256 hashBlock;
if(!GetTransaction(prevout.hash, txPrev, hashBlock, true))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read tx from disk");
nValueIn += txPrev.vout[prevout.n].nValue;
}
for (unsigned int j = 0; j < tx.vout.size(); j++) {
nValueOut += tx.vout[j].nValue;
}
nFees += nValueIn - nValueOut;
nBytes += tx.GetSerializeSize(SER_NETWORK, CLIENT_VERSION);
nTotal++;
}
pindex = chainActive.Next(pindex);
if (!pindex)
break;
}
UniValue ret(UniValue::VOBJ);
CFeeRate nFeeRate = CFeeRate(nFees, nBytes);
ret.push_back(Pair("txcount", (int64_t)nTotal));
ret.push_back(Pair("txbytes", (int64_t)nBytes));
ret.push_back(Pair("ttlfee", FormatMoney(nFees)));
ret.push_back(Pair("feeperkb", FormatMoney(nFeeRate.GetFeePerK())));
ret.push_back(Pair("rec_highpriorityfee_perkb", FormatMoney(nFeeRate.GetFeePerK() + 1000)));
return ret;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
//ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
return ret;
}
UniValue getmempoolinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx (numeric) Current tx count\n"
" \"bytes\": xxxxx (numeric) Sum of all tx sizes\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", ""));
return mempoolInfoToJSON();
}
UniValue invalidateblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"invalidateblock \"hash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to mark as invalid\n"
"\nResult:\n"
"\nExamples:\n" +
HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\""));
std::string strHash = params[0].get_str();
uint256 hash(strHash);
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue reconsiderblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"reconsiderblock \"hash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to reconsider\n"
"\nResult:\n"
"\nExamples:\n" +
HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\""));
std::string strHash = params[0].get_str();
uint256 hash(strHash);
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
ReconsiderBlock(state, pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue findserial(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() != 1)
throw runtime_error(
"findserial \"serial\"\n"
"\nSearches the zerocoin database for a zerocoin spend transaction that contains the specified serial\n"
"\nArguments:\n"
"1. serial (string, required) the serial of a zerocoin spend to search for.\n"
"\nResult:\n"
"{\n"
" \"success\": true/false (boolean) Whether the serial was found\n"
" \"txid\": xxxxx (numeric) The transaction that contains the spent serial\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("findserial", "\"serial\"") + HelpExampleRpc("findserial", "\"serial\""));
std::string strSerial = params[0].get_str();
CBigNum bnSerial = 0;
bnSerial.SetHex(strSerial);
if (!bnSerial)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid serial");
uint256 txid = 0;
bool fSuccess = zerocoinDB->ReadCoinSpend(bnSerial, txid);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("success", fSuccess));
ret.push_back(Pair("txid", txid.GetHex()));
return ret;
}
|
[
"nikki.bisschoff@gmail.com"
] |
nikki.bisschoff@gmail.com
|
4595b37d016c72cdee70db690c1c9048953d9ee1
|
0363e5f25ce4d6e2ef0f122c0f430f64521252b7
|
/Problems/PTA/B1007.cpp
|
fd23821257da912e7d68be20e905537147d5d721
|
[
"Apache-2.0"
] |
permissive
|
five-5/code
|
b734f7c4e63b93f6d06f210fb3e2b0c68f4ae6a1
|
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
|
refs/heads/master
| 2021-06-30T02:53:46.463096
| 2020-10-13T02:37:14
| 2020-10-13T02:37:14
| 177,311,694
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 432
|
cpp
|
#include <cstdio>
#include <cmath>
bool isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i <= std::sqrt(n); ++i)
{
if (n % i == 0) return false;
}
return true;
}
int main()
{
int n, count = 0;
scanf("%d", &n);
for (int i = 3; i + 2 <= n; i+=2)
{
if (isPrime(i) && isPrime(i+2))
{
++count;
}
}
printf("%d", count);
return 0;
}
|
[
"535237609@qq.com"
] |
535237609@qq.com
|
0644c0fb5024571e6632a82acd444dc6a2a3e757
|
c3de57676ebc2c4f6d0849347798534f85ab9a72
|
/GUILib/src/GLMeshDisplayWindow.cpp
|
73b39da25fac8be6197105cfdf1343aa1757dcdb
|
[] |
no_license
|
plusminus34/Interactive_thin_shells_Bachelor_thesis
|
0662f6d88d76d8d49b2b6066bf1d2b0fc258f01e
|
85f034a476eeab8d485f19a6ea3208498061a4da
|
refs/heads/main
| 2023-03-10T15:15:53.666726
| 2021-02-24T08:01:25
| 2021-02-24T08:01:25
| 341,820,202
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 700
|
cpp
|
#include <GUILib/GLApplication.h>
#include <GUILib/GLMeshDisplayWindow.h>
#include <Utils/Utils.h>
#include <GUILib/GLUtils.h>
#include <GUILib/GLContentManager.h>
#include <GUILib/GLMesh.h>
#include <GUILib/GLCamera.h>
#include <GUILib/GLTrackingCamera.h>
/**
Default constructor
*/
GLMeshDisplayWindow::GLMeshDisplayWindow(GLMesh* mesh, int posX, int posY, int sizeX, int sizeY) : GLWindow3D(posX, posY, sizeX, sizeY) {
this->mesh = mesh;
}
GLMeshDisplayWindow::GLMeshDisplayWindow(GLMesh* mesh) : GLWindow3D() {
this->mesh = mesh;
}
GLMeshDisplayWindow::GLMeshDisplayWindow() : GLWindow3D() {
this->mesh = NULL;
}
void GLMeshDisplayWindow::drawScene() {
if (mesh)
mesh->drawMesh();
}
|
[
"moritzgeilinger@gmail.com"
] |
moritzgeilinger@gmail.com
|
64836697cfcb8897b4e0d96fdc1a52ee67724460
|
8f3d9eb1d632282a55ea5a5c3dfe6f23e6d1b76c
|
/Wawaji-Server-Windows/wwj_demo/libs/nim_sdk_desktop/nim_cpp_sdk/api/nim_cpp_msglog.h
|
af1f90037bc1e82e083ba424b6b93bc25bdc731a
|
[
"MIT"
] |
permissive
|
jzsplk/Wawaji
|
086580efb5ecf952b990a36bb5cd8a6a9a1fc6f7
|
45c51c3cd1b49a4a926b76b6e4e31a331ede66ee
|
refs/heads/master
| 2020-03-12T15:29:40.437612
| 2018-04-23T12:03:00
| 2018-04-23T12:03:00
| 130,691,413
| 1
| 0
| null | 2018-04-23T12:13:28
| 2018-04-23T12:13:28
| null |
UTF-8
|
C++
| false
| false
| 21,028
|
h
|
/** @file nim_cpp_msglog.h
* @brief 消息历史
* @copyright (c) 2015-2017, NetEase Inc. All rights reserved
* @author towik, Oleg
* @date 2015/2/1
*/
#ifndef _NIM_SDK_CPP_MSGLOG_H_
#define _NIM_SDK_CPP_MSGLOG_H_
#include <string>
#include <functional>
#include "nim_msglog_helper.h"
#include "nim_talk_helper.h"
/**
* @namespace nim
* @brief namespace nim
*/
namespace nim
{
/** @class MsgLog
* @brief NIM SDK提供的消息历史接口
*/
class MsgLog
{
public:
typedef std::function<void(nim::NIMResCode res_code, const std::string& id, nim::NIMSessionType to_type, const QueryMsglogResult& result)> QueryMsgCallback; /**< 查询消息历史回调模板 */
typedef std::function<void(nim::NIMResCode res_code, const std::string& msg_id, const IMMessage& msg)> QuerySingleMsgCallback; /**< 查询单条消息历史回调模板 */
typedef std::function<void(nim::NIMResCode res_code, const std::string& uid, nim::NIMSessionType to_type)> ModifyMultipleMsglogCallback; /**< 修改(多条)消息历史回调模板 */
typedef ModifyMultipleMsglogCallback BatchStatusReadCallback; /**< 批量设置消息历史已读状态回调模板 */
typedef ModifyMultipleMsglogCallback BatchStatusDeleteCallback; /**< 批量删除消息历史回调模板 */
typedef ModifyMultipleMsglogCallback DeleteBySessionTypeCallback;/**< 批量删除消息历史回调模板 */
typedef std::function<void(nim::NIMResCode res_code, const std::string& msg_id)> ModifySingleMsglogCallback; /**< 修改(单条)消息历史回调模板 */
typedef ModifySingleMsglogCallback SetStatusCallback; /**< 修改消息历史状态回调模板 */
typedef ModifySingleMsglogCallback SetSubStatusCallback;/**< 修改消息历史子状态回调模板 */
typedef ModifySingleMsglogCallback UpdateLocalExtCallback;/**< 修改消息历史本地扩展字段内容回调模板 */
typedef ModifySingleMsglogCallback WriteMsglogCallback; /**< 保存消息历史回调模板 */
typedef ModifySingleMsglogCallback DeleteCallback; /**< 删除消息历史回调模板 */
typedef std::function<void(nim::NIMResCode res_code)> DBFunctionCallback; /**< 消息历史变更回调模板 */
typedef DBFunctionCallback DeleteAllCallback; /**< 删除全部消息历史回调模板 */
typedef std::function<void(int64_t imported_count, int64_t total_count)> ImportDbPrgCallback; /**< 导入消息历史回调模板 */
typedef std::function<void(const MessageStatusChangedResult&)> MessageStatusChangedCallback; /**< 发送消息已读回执通知回调模板 */
/** @fn static bool QueryMsgByIDAysnc(const std::string &client_msg_id, const QuerySingleMsgCallback &cb, const std::string &json_extension = "")
* 根据消息ID查询本地(单条)消息
* @param[in] client_msg_id 客户端消息ID
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 查询本地消息的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool QueryMsgByIDAysnc(const std::string &client_msg_id, const QuerySingleMsgCallback &cb, const std::string &json_extension = "");
/** @fn static bool QueryMsgAsync(const std::string& account_id, nim::NIMSessionType to_type, int limit_count, int64_t anchor_msg_time, const QueryMsgCallback& cb, const std::string& json_extension = "")
* 查询本地消息
* @param[in] account_id 查询id,account_id/uid或者tid
* @param[in] to_type 会话类型,双人0,群组1 (见nim_msglog_def.h)
* @param[in] limit_count 一次查询数量,建议20
* @param[in] anchor_msg_time 作为此次查询的定位点的消息历史的消息时间戳(上次查询最后一条消息的时间戳,按指定的时间的顺序起查,默认为逆序,2.4.0之前命名为last_name)
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 查询本地消息的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
*/
static bool QueryMsgAsync(const std::string& account_id
, nim::NIMSessionType to_type
, int limit_count
, int64_t anchor_msg_time
, const QueryMsgCallback& cb
, const std::string& json_extension = "");
/** @fn static bool QueryMsgOnlineAsync(const std::string &id, nim::NIMSessionType to_type, int limit_count, int64_t from_time, int64_t end_time, int64_t end_msg_id, bool reverse, bool need_save_to_local, const QueryMsgCallback& cb, const std::string& json_extension = "")
* 在线查询消息(不包括系统消息)
* @param[in] id 查询id,对方的account id或者群组tid。
* @param[in] to_type 会话类型,双人0,群组1 (nim_msglog_def.h)
* @param[in] limit_count 本次查询的消息条数上限(最多100条)
* @param[in] from_time 起始时间点,单位:毫秒
* @param[in] end_time 结束时间点,单位:毫秒
* @param[in] end_msg_id 结束查询的最后一条消息的server_msg_id(不包含在查询结果中)
* @param[in] reverse true:反向查询(按时间正序起查,正序排列),false:按时间逆序起查,逆序排列(建议默认为false)
* @param[in] need_save_to_local true: 将在线查询结果保存到本地,false: 不保存
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 在线查询消息的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 403:禁止访问(不在该群,只针对群组会话)
* 414:参数错误
*/
static bool QueryMsgOnlineAsync(const std::string &id
, nim::NIMSessionType to_type
, int limit_count
, int64_t from_time
, int64_t end_time
, int64_t end_msg_id
, bool reverse
, bool need_save_to_local
, const QueryMsgCallback& cb
, const std::string& json_extension = "");
/** @fn static bool QueryMsgOfSpecifiedTypeInASessionAsync(nim::NIMSessionType to_type, const std::string &id, int limit_count, int64_t from_time, int64_t end_time, const std::string &end_client_msg_id, bool reverse, std::list<NIMMessageType> msg_type, const QueryMsgCallback& cb, const std::string& json_extension = "")
* 根据指定条件在一个会话中查询指定单个或多个类型的本地消息
* @param[in] to_type 会话类型,双人0,群组1 (nim_msglog_def.h)
* @param[in] id 查询id,对方的account id或者群组tid。
* @param[in] limit_count 本次查询的消息条数上限(最多100条)
* @param[in] from_time 起始时间点,单位:毫秒
* @param[in] end_time 结束时间点,单位:毫秒
* @param[in] end_client_msg_id 结束查询的最后一条消息的end_client_msg_id(不包含在查询结果中)
* @param[in] reverse true:反向查询(按时间正序起查,正序排列),false:按时间逆序起查,逆序排列(建议默认为false)
* @param[in] msg_type 检索的消息类型
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 在线查询消息的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
*/
static bool QueryMsgOfSpecifiedTypeInASessionAsync(nim::NIMSessionType to_type
, const std::string &id
, int limit_count
, int64_t from_time
, int64_t end_time
, const std::string &end_client_msg_id
, bool reverse
, std::list<NIMMessageType> msg_type
, const QueryMsgCallback& cb
, const std::string& json_extension = "");
/** @fn static bool QueryMsgByOptionsAsync(NIMMsgLogQueryRange query_range, const std::list<std::string> &ids, nim::NIMSessionType to_type, int limit_count, int64_t from_time, int64_t end_time, const std::string &end_client_msg_id, bool reverse, NIMMessageType msg_type, const std::string &search_content, const QueryMsgCallback& cb, const std::string& json_extension = "")
* 根据指定条件查询本地消息,使用此接口可以完成全局搜索等功能,具体请参阅开发手册 http://dev.netease.im/docs/product/IM即时通讯/SDK开发集成/Windows开发集成/Windows开发集成&#历史记录
* @param[in] query_range 消息历史的检索范围(目前暂不支持某些范围的组合检索,详见NIMMsgLogQueryRange说明)
* @param[in] ids 会话id(对方的account id或者群组tid)的集合,目前暂不支持多个的组合检索,详见NIMMsgLogQueryRange说明
* @param[in] limit_count 本次查询的消息条数上限(最多100条)
* @param[in] from_time 起始时间点,单位:毫秒
* @param[in] end_time 结束时间点,单位:毫秒
* @param[in] end_client_msg_id 结束查询的最后一条消息的end_client_msg_id(不包含在查询结果中)
* @param[in] reverse true:反向查询(按时间正序起查,正序排列),false:按时间逆序起查,逆序排列(建议默认为false)
* @param[in] msg_type 检索的消息类型(目前只支持kNIMMessageTypeText、kNIMMessageTypeImage和kNIMMessageTypeFile这三种类型消息)
* @param[in] search_content 检索文本(目前只支持kNIMMessageTypeText和kNIMMessageTypeFile这两种类型消息的文本关键字检索,即支持文字消息和文件名的检索。如果合并检索,需使用未知类型消息kNIMMessageTypeUnknown)
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 在线查询消息的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
*/
static bool QueryMsgByOptionsAsync(NIMMsgLogQueryRange query_range
, const std::list<std::string> &ids
, int limit_count
, int64_t from_time
, int64_t end_time
, const std::string &end_client_msg_id
, bool reverse
, NIMMessageType msg_type
, const std::string &search_content
, const QueryMsgCallback& cb
, const std::string& json_extension = "");
/** @fn static bool BatchStatusReadAsync(const std::string& account_id, nim::NIMSessionType to_type, const BatchStatusReadCallback& cb, const std::string& json_extension = "")
* 批量设置已读状态
* @param[in] account_id 查询id,account_id/uid或者tid
* @param[in] to_type 会话类型,双人0,群组1 (见nim_msglog_def.h)
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool BatchStatusReadAsync(const std::string& account_id
, nim::NIMSessionType to_type
, const BatchStatusReadCallback& cb
, const std::string& json_extension = "");
/** @fn static bool BatchStatusDeleteAsync(const std::string& account_id, nim::NIMSessionType to_type, const BatchStatusDeleteCallback& cb, const std::string& json_extension = "")
* 批量设置未读状态为已读消息状态
* @param[in] account_id 查询id,account_id/uid或者tid
* @param[in] to_type 会话类型,双人0,群组1 (见nim_msglog_def.h)
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool BatchStatusDeleteAsync(const std::string& account_id
, nim::NIMSessionType to_type
, const BatchStatusDeleteCallback& cb
, const std::string& json_extension = "");
/** @fn static bool SetStatusAsync(const std::string& msg_id, nim::NIMMsgLogStatus msglog_status, const SetStatusCallback& cb, const std::string& json_extension = "")
* 设置消息状态
* @param[in] msg_id 消息id
* @param[in] msglog_status 消息状态枚举值
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool SetStatusAsync(const std::string& msg_id
, nim::NIMMsgLogStatus msglog_status
, const SetStatusCallback& cb
, const std::string& json_extension = "");
/** @fn static bool SetSubStatusAsync(const std::string& msg_id, nim::NIMMsgLogSubStatus msglog_sub_status, const SetSubStatusCallback& cb, const std::string& json_extension = "")
* 设置消息子状态
* @param[in] msg_id 消息id
* @param[in] msglog_sub_status 消息子状态枚举值
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool SetSubStatusAsync(const std::string& msg_id
, nim::NIMMsgLogSubStatus msglog_sub_status
, const SetSubStatusCallback& cb
, const std::string& json_extension = "");
/** @fn static bool WriteMsglogToLocalAsync(const std::string& talk_id, bool need_update_session, const std::string& json_msg, const WriteMsglogCallback& cb, const std::string& json_extension = "")
* 只往本地消息历史数据库里写入一条消息(如果已存在这条消息,则更新。通常是APP的本地自定义消息,并不会发给服务器)
* @param[in] account_id 会话id,对方的account id或者群组tid
* @param[in] msg 消息内容
* @param[in] need_update_session 是否更新会话列表(一般最新一条消息有这个需求)
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool WriteMsglogToLocalAsync(const std::string& talk_id
, const IMMessage& msg
, bool need_update_session
, const WriteMsglogCallback& cb
, const std::string& json_extension = "");
/** @fn static bool DeleteBySessionTypeAsync(bool delete_sessions, NIMSessionType to_type, const DeleteBySessionTypeCallback& cb, const std::string& json_extension = "")
* 删除指定会话类型的所有消息
* @param[in] delete_sessions 是否删除会话
* @param[in] to_type 会话类型
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool DeleteBySessionTypeAsync(bool delete_sessions
, NIMSessionType to_type
, const DeleteBySessionTypeCallback& cb
, const std::string& json_extension = "");
/** @fn static bool DeleteAsync(const std::string& session_id, NIMSessionType to_type, const std::string& msg_id, const DeleteCallback& cb, const std::string& json_extension = "")
* 删除指定一条消息
* @param[in] session_id 会话id,对方的account id或者群组tid
* @param[in] to_type 会话类型
* @param[in] msg_id 消息id
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool DeleteAsync(const std::string& session_id
, NIMSessionType to_type
, const std::string& msg_id
, const DeleteCallback& cb
, const std::string& json_extension = "");
/** @fn static bool DeleteAllAsync(bool delete_sessions, const DeleteAllCallback& cb, const std::string& json_extension = "")
* 删除全部消息历史
* @param[in] delete_sessions 是否删除所有会话列表项(即全部最近联系人)。
* ture则删除,并通过nim_session_reg_change_cb注册的回调通知上层kNIMSessionCommandRemoveAll事件(不会触发每个会话项的kNIMSessionCommandRemove事件);
* false则不删除,并将所有会话项的最后一条消息的状态kNIMSessionMsgStatus设置为已删除状态,并通过nim_session_reg_change_cb注册的回调通知上层kNIMSessionCommandAllMsgDeleted事件(不会触发每个会话项的kNIMSessionCommandUpdate事件,避免频繁通知上层)。
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool DeleteAllAsync(bool delete_sessions, const DeleteAllCallback& cb, const std::string& json_extension = "");
/** @fn static bool ExportDbAsync(const std::string& dst_path, const ExportDbCallback& cb, const std::string& json_extension = "")
* 导出整个消息历史DB文件(不包括系统消息历史)
* @param[in] dst_path 导出时保存的目标全路径(UTF-8编码)。
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool ExportDbAsync(const std::string& dst_path, const DBFunctionCallback& cb, const std::string& json_extension = "");
/** @fn static bool ImportDbAsync(const std::string& src_path, const ImportDbCallback& cb, const ImportDbPrgCallback& prg_cb, const std::string& json_extension = "")
* 导入消息历史DB文件(不包括系统消息历史)。先验证是否自己的消息历史文件和DB加密密钥(见nim_client_def.h里的kNIMDataBaseEncryptKey),如果验证不通过,则不导入。
* @param[in] src_path 导入源文件的全路径(UTF-8编码)。
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @param[in] prg_cb 导入进度的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 10600:导入消息历史时验证身份和加密密钥不通过
* 10601:导入消息历史时写记录失败
*/
static bool ImportDbAsync(const std::string& src_path
, const DBFunctionCallback& cb
, const ImportDbPrgCallback& prg_cb
, const std::string& json_extension = "");
/** @fn void SendReceiptAsync(const std::string& json_msg, const MessageStatusChangedCallback& cb)
* 发送消息已读回执
* @param[in] json_msg 已读消息json string。
* @param[in] cb 操作结果的回调函数
* @return void 无返回值
* @note 错误码 200:成功
* 403:服务器关闭此功能,或者应用没权限
* 404:请求的目标(用户或对象)不存在
* 10414:本地错误码,参数错误
*/
static void SendReceiptAsync(const std::string& json_msg, const MessageStatusChangedCallback& cb);
/** @fn bool QuerySentMessageBeReaded(const IMMessage& msg)
* 查询自己发送的消息是否被对方已读
* @param[in] msg 消息。
* @return bool 是否被已读
*/
static bool QuerySentMessageBeReaded(const IMMessage& msg);
/** @fn bool QueryReceivedMsgReceiptSent(const IMMessage& msg)
* 查询收到的消息是否已经发送过已读回执
* @param[in] msg 消息。
* @return bool 是否已发送过
*/
static bool QueryReceivedMsgReceiptSent(const IMMessage& msg);
/** @fn void RegMessageStatusChangedCb(const MessageStatusChangedCallback& cb, const std::string &json_extension = "")
* (全局回调)注册全局的消息状态变更通知(目前只支持已读状态的通知)
* @param[in] cb 回调函数
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @return void 无返回值
* @note 错误码 200:成功
*/
static void RegMessageStatusChangedCb(const MessageStatusChangedCallback& cb, const std::string &json_extension = "");
/** @fn static bool UpdateLocalExtAsync(const std::string& msg_id, const std::string& local_ext, const UpdateLocalExtCallback& cb, const std::string& json_extension = "")
* 更新本地消息扩展字段内容
* @param[in] msg_id 消息id
* @param[in] local_ext 本地扩展字段内容
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool UpdateLocalExtAsync(const std::string& msg_id
, const std::string& local_ext
, const UpdateLocalExtCallback& cb
, const std::string& json_extension = "");
/** @fn static bool ReadAllAsync(const DBFunctionCallback& cb, const std::string& json_extension = "")
* 全部未读消息历史标记为已读
* @param[in] json_extension json扩展参数(备用,目前不需要)
* @param[in] cb 操作结果的回调函数
* @return bool 检查参数如果不符合要求则返回失败
* @note 错误码 200:成功
* 0:失败
*/
static bool ReadAllAsync(const DBFunctionCallback& cb, const std::string& json_extension = "");
};
}
#endif //_NIM_SDK_CPP_MSGLOG_H_
|
[
"hzgaoqi1@corp.netease.com"
] |
hzgaoqi1@corp.netease.com
|
64c2f15807b5d7d979b7b90b72a574fa39f4f4e5
|
6335043b83fcfc0cd9537ee775dc3badbfb6d478
|
/examples/dcps/QueryCondition/isocpp/publisher.cpp
|
600464724bb6cc704ea6708d605acaebfde52f75
|
[] |
no_license
|
satej1210/CasinoRoyale
|
5d989ef1e3b88ee032c4cc847b235c5b2d2a43f6
|
f3de3fc29d27d58e95852bd674021743b91f4eee
|
refs/heads/master
| 2021-03-24T12:51:58.889956
| 2017-11-15T07:22:11
| 2017-11-15T07:22:11
| 73,645,806
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 528
|
cpp
|
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to 2013 PrismTech
* Limited and its licensees. All rights reserved. See file:
*
* $OSPL_HOME/LICENSE
*
* for full copyright notice and license terms.
*
*/
#include "implementation.hpp"
/**
* @addtogroup examplesdcpsQueryConditionisocpp
*/
/** @{*/
/** @file */
/** @}*/
int EXAMPLE_MAIN (int argc, char *argv[])
{
return examples::dcps::QueryCondition::isocpp::publisher(argc, argv);
}
|
[
"satej1210@live.com"
] |
satej1210@live.com
|
e60ebf61de415a589da309610deaf2dee7d726a3
|
51e8260df21001498150dc4dcadd36a364300e24
|
/src/test/resources/results/armadillo/testMath/l0/test_math_tanCommandTest.h
|
254b49abb7d84664d795688a43db53ef4574891c
|
[] |
no_license
|
Qwertzimus/EMAM2Cpp
|
f733a19eaf8619df921aaff9ee401d1c4e8314e8
|
6f5a7ffa880fa223fd5e3d828239b7d3bbd2efa1
|
refs/heads/master
| 2020-03-20T22:34:50.299533
| 2018-05-22T16:51:38
| 2018-05-22T16:51:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 276
|
h
|
#ifndef TEST_MATH_TANCOMMANDTEST
#define TEST_MATH_TANCOMMANDTEST
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#include "armadillo.h"
using namespace arma;
class test_math_tanCommandTest{
public:
void init()
{
}
void execute()
{
double a = (tan(0.5));
}
};
#endif
|
[
"sascha.schneiders@rwth-aachen.de"
] |
sascha.schneiders@rwth-aachen.de
|
fbb371dd3f34045e0c8f9f0bb5078aac651a78d6
|
83e687bc3f6878e4d739072be7380b5f285c6490
|
/dgconst.h
|
77919d9bd454779f4c29e7b82358ed4a11510295
|
[] |
no_license
|
miheslkivi/PPFCU-controller
|
7c18fb7d9802645d0e3e1af7e642f69dbe26e5e2
|
dff94ced522887fd325cfa99d6056f98e4c80e8f
|
refs/heads/master
| 2021-05-04T22:29:37.894183
| 2018-04-23T13:00:18
| 2018-04-23T13:00:18
| 120,038,935
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,040
|
h
|
/*
*
* Controller and info program for Pac-person freespace continuum undiscreted
* ( PPFCU or p-pf-scu-d ) - Copyright (C) 2018 by Mikko Heiska
*
*
*** You may use this file under the terms of the BSD license as follows:
**
** "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.
** * The names of its contributors may not 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 DGCONST_H
#define DGCONST_H
#include"client.h"
#include<iostream>
using namespace std;
#endif // DGCONST_H
|
[
"mihepeau@suomi24.fi"
] |
mihepeau@suomi24.fi
|
d6e7623725cc257bf6085929e0bca17ebd487149
|
ffc0f86fc1110564ca188b8e22a8e5de5c31e24d
|
/lab14_5.cpp
|
97f1a89e2e00f002c2f6d8f865d79cea2fae07af
|
[] |
no_license
|
jerryc137th/lab_14
|
ec0f1f2de2d6a4ffe04f2fb5639ac359d2d36ddf
|
f6da4e089976c6f57cd36709994a149c3a2af3d2
|
refs/heads/master
| 2023-02-26T12:35:51.792222
| 2021-02-02T11:11:59
| 2021-02-02T11:11:59
| 335,261,425
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 696
|
cpp
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void shuffle(int *,int *, int *, int *); //Modify input arguments to pointer
int main(){
int a = 50, b = 100, c = 500, d = 1000;
srand(time(0));
for(int i = 0;i < 10;i++){
shuffle(&a,&b,&c,&d); //Modify input arguments to pointer
cout << a << " " << b << " " << c << " " << d << "\n";
}
return 0;
}
void shuffle(int *a,int *b,int *c,int *d){
int e[4] = {},r,w[4]={50,100,500,1000},i=0;
while(i<4){
r = rand()%4;
bool foul = 0;
for(int j = 0;j<i;j++){
if(w[r]==e[j]) foul = 1;
}
if(!foul){
e[i] = w[r];
i++;
}
}
*a = e[0];
*b = e[1];
*c = e[2];
*d = e[3];
}
|
[
"noreply@github.com"
] |
jerryc137th.noreply@github.com
|
1db6693d30caaf1f97739ce90aa52a7128a80795
|
940dd9691f1409d9f12c5f0f6912b36d4c6bf0bf
|
/include/boost/mpl/permutations.hpp
|
8f7cdad424e5ef3a41e21718f42bacd54584ff11
|
[
"BSL-1.0"
] |
permissive
|
blockspacer/mpl_extensions
|
06e6591b122e6ba42f0d2da7802b4a65ac37b2f1
|
ca728992567b96dad884be1658b0822a955174cc
|
refs/heads/master
| 2021-04-24T03:39:04.068234
| 2013-09-28T13:47:50
| 2013-09-28T13:47:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,623
|
hpp
|
/*!
* @file
* Defines `boost::mpl::permutations`.
*/
#ifndef BOOST_MPL_PERMUTATIONS_HPP
#define BOOST_MPL_PERMUTATIONS_HPP
#include <boost/mpl/copy.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/front_inserter.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/remove.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/transform.hpp>
namespace boost { namespace mpl {
namespace permutations_detail {
template <typename Element, typename Sequence>
struct helper;
template <typename Sequence, unsigned long Size = size<Sequence>::value>
struct permutations
: fold<
Sequence,
list0<>,
copy<helper<_2, Sequence>, front_inserter<_1>>
>
{ };
template <typename Sequence>
struct permutations<Sequence, 1> {
using type = list1<Sequence>;
};
template <typename Element, typename Sequence>
struct helper
: transform<
typename permutations<
typename remove<Sequence, Element>::type
>::type,
push_front<_1, Element>
>
{ };
} // end namespace permutations_detail
/*!
* Metafunction returning a sequence containing all the permutations of a
* `Sequence`.
*
* @internal
* We dispatch to `permutations_detail::permutations` to avoid exposing
* the `Size` parameter in the interface.
*/
template <typename Sequence>
struct permutations
: permutations_detail::permutations<Sequence>
{ };
}} // end namespace boost::mpl
#endif // !BOOST_MPL_PERMUTATIONS_HPP
|
[
"ldionne.2@gmail.com"
] |
ldionne.2@gmail.com
|
91578af0d04c7cdaddb44ff3b36c72d851a2742f
|
d3f554e22644369444f287487a5b429bcf8393ea
|
/pta1009.cpp
|
a9bc308aa4646311dfad71a0f7fe130016aef035
|
[] |
no_license
|
momoshenchi/PAT-Advanced-level
|
19a74ee3791060c13392faf93124c66be750ab55
|
a014d5c1cd0183cd0530ea2e8138ec0e318ec10f
|
refs/heads/master
| 2020-09-16T20:23:52.327746
| 2020-06-08T08:38:24
| 2020-06-08T08:38:24
| 223,880,110
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 813
|
cpp
|
#include <bits/stdc++.h>
#define MAX 501
#define INF 0x7fffffff
using namespace std;
map<int,double,greater<int>>dit1;
map<int,double,greater<int>>sum;
int main(void)
{
int now=0,n1,n2;
int a;double b;
cin>>n1;
for(int i=0;i<n1;++i)
{
cin>>a>>b;
dit1[a]+=b;
}
cin>>n2;
for(int i=0;i<n2;++i)
{
cin>>a>>b;
for(auto i=dit1.begin();i!=dit1.end();i++)
{
sum[i->first+a]+=i->second*b;
}
}
for(auto i=sum.begin();i!=sum.end();++i)
{
if(i->second==0)
sum.erase(i);
}
cout<<sum.size();
for(auto i=sum.begin();i!=sum.end();++i)
{
printf(" %d %.1f",i->first,i->second);
}
return 0;
}
|
[
"982060958@qq.com"
] |
982060958@qq.com
|
c4446a3a9bf6722dca948175dd096864b486b858
|
fa55f3745c046c591018002c39eb82f6c17662dd
|
/SiblingViterbi.H
|
178c8669412a04754789bce40f7653afaf928cac
|
[] |
no_license
|
bmajoros/alignment
|
bd73cd8a1d56c0eb4672da97a6eb6f51f5d769fa
|
0bb4b89a0445d4cc2cf8b49ee21a67ecc4e398f8
|
refs/heads/master
| 2021-01-20T04:30:21.310099
| 2015-08-13T18:54:03
| 2015-08-13T18:54:03
| 40,673,892
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,513
|
h
|
/****************************************************************
SiblingViterbi.H
william.majoros@duke.edu
This is open-source software, governed by the Gnu General Public License (GPL) version 3
(see www.opensource.org).
****************************************************************/
#ifndef INCL_SiblingViterbi_H
#define INCL_SiblingViterbi_H
#include <iostream>
#include "Taxon.H"
#include "PairHMM/StatePath.H"
#include "BranchAttributes.H"
#include "BranchHMM.H"
#include "Banding.H"
#include "LinkFelsenstein.H"
#include "LinkViterbi.H"
using namespace std;
using namespace BOOM;
/****************************************************************
A version of LinkViterbi which aligns two sibling taxa.
****************************************************************/
class SiblingViterbi : public LinkViterbi {
public:
SiblingViterbi(BranchHMM *hmm,Taxon *left,Taxon *right,
LinkFelsenstein &F,BandingType=NO_BANDING,
int bandwidth=100);
virtual ~SiblingViterbi() {}
protected:
Taxon *left, *right;
BranchAttributes *leftBranch, *rightBranch;
IndexMap *leftDownMap, *leftUpMap, *rightDownMap, *rightUpMap;
int *leftDownMapEntry, *rightDownMapEntry;
virtual double getEmitP(STATE,int parentResidueIndex,
int childResidueIndex,PairHMMStateType);
virtual double emission(STATE,int parentResidueIndex,
int childResidueIndex,PairHMMStateType);
virtual void precomputeEmissions();
void precomputeEmissions(PrecomputedEmissions &,Taxon &cladeRoot);
};
#endif
|
[
"martiandna@gmail.com"
] |
martiandna@gmail.com
|
b92b028ef35feede97d86ab2926999aaf09fee90
|
45d2a4d3d738e3ded35908a17f2bae65b5aac57d
|
/pgAdmin/include/schema/edbPackageFunction.h
|
fb04ec83c84771fae50a435b3a5593c6be528cb1
|
[
"PostgreSQL"
] |
permissive
|
asdbaihu/Database-Designer-for-pgAdmin
|
fa2fb39fe1c4908567e817b6945b5c163d440437
|
502afe753362233eb8ecb60004fee9346579b2ef
|
refs/heads/master
| 2020-07-08T11:07:54.105552
| 2010-08-14T23:55:45
| 2010-08-14T23:55:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,505
|
h
|
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
// RCS-ID: $Id: edbPackageFunction.h 8189 2010-02-25 22:10:21Z dpage $
// Copyright (C) 2002 - 2010, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// edbPackageFunction.h - EnterpriseDB Package member function
//
//////////////////////////////////////////////////////////////////////////
#ifndef EDBPACKAGEFUNCTION_H
#define EDBPACKAGEFUNCTION_H
#include "edbPackage.h"
class pgCollection;
class edbPackageFunction;
class edbPackageFunctionFactory : public edbPackageObjFactory
{
public:
edbPackageFunctionFactory(const wxChar *tn=0, const wxChar *ns=0, const wxChar *nls=0, const char **img=0);
virtual dlgProperty *CreateDialog(frmMain *frame, pgObject *node, pgObject *parent) { return 0; };
virtual pgObject *CreateObjects(pgCollection *obj, ctlTree *browser, const wxString &restr=wxEmptyString);
edbPackageFunction *AppendFunctions(pgObject *obj, edbPackage *package, ctlTree *browser, const wxString &restriction);
};
extern edbPackageFunctionFactory packageFunctionFactory;
class edbPackageFunction : public edbPackageObject
{
public:
edbPackageFunction(edbPackage *newPackage, const wxString& newName = wxT(""));
edbPackageFunction(edbPackage *newPackage, pgaFactory &factory, const wxString& newName = wxT(""));
void ShowTreeDetail(ctlTree *browser, frmMain *form=0, ctlListView *properties=0, ctlSQLBox *sqlPane=0);
wxString GetSql(ctlTree *browser);
pgObject *Refresh(ctlTree *browser, const wxTreeItemId item);
virtual bool GetIsProcedure() const { return false; }
wxString GetFullName();
wxString GetArgListWithNames();
wxString GetArgSigList();
wxArrayString &GetArgNamesArray() { return argNamesArray; }
void iAddArgName(const wxString &s) { argNamesArray.Add(s); }
wxArrayString &GetArgTypesArray() { return argTypesArray; }
void iAddArgType(const wxString &s) { argTypesArray.Add(s); }
wxArrayString &GetArgModesArray() { return argModesArray; }
void iAddArgMode(const wxString &s) { argModesArray.Add(s); }
wxArrayString &GetArgDefsArray() { return argDefsArray; }
void iAddArgDef(const wxString &s) { argDefsArray.Add(s); }
wxString GetReturnType() const { return returnType; }
void iSetReturnType(const wxString& s) { returnType = s; }
wxString GetSource() const { return source; }
void iSetSource(const wxString& s) { source = s; }
wxString GetVisibility() const { return visibility; }
void iSetVisibility(const wxString& s) { visibility = s; }
long GetArgCount() const { return argCount; }
void iSetArgCount(long ac) { argCount = ac; }
bool CanCreate() { return false; }
private:
long argCount;
wxArrayString argNamesArray, argTypesArray, argModesArray, argDefsArray;
wxString returnType, source, visibility;
};
class edbPackageProcedureFactory : public edbPackageFunctionFactory
{
public:
edbPackageProcedureFactory();
virtual pgObject *CreateObjects(pgCollection *obj, ctlTree *browser, const wxString &restr=wxEmptyString);
};
extern edbPackageProcedureFactory packageProcedureFactory;
class edbPackageProcedure : public edbPackageFunction
{
public:
edbPackageProcedure(edbPackage *newPackage, const wxString& newName=wxT(""));
wxString GetFullName();
bool GetIsProcedure() const { return true; }
wxString GetSql(ctlTree *browser);
};
#endif
|
[
"ziul1979@gmail.com"
] |
ziul1979@gmail.com
|
dfea6329164caf5fb61955a5db6e4bced053c2f6
|
624511f6ad0cf17a2ba1a1ea1f25c3b139ce4295
|
/topchain/src/primitives/transaction.h
|
9e901225f2ef4b020c8ee5a37553538f61b28b1a
|
[] |
no_license
|
lightchainone/lightchain
|
7d90338d4a4e8d31d550c07bf380c06580941334
|
6fc7019c76a8b60d4fd63fba58fa79858856f66b
|
refs/heads/master
| 2021-05-11T05:47:17.672527
| 2019-12-16T09:51:39
| 2019-12-16T09:51:39
| 117,969,593
| 23
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,160
|
h
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_TRANSACTION_H
#define BITCOIN_PRIMITIVES_TRANSACTION_H
#include <stdint.h>
#include "amount.h"
#include "script/script.h"
#include "serialize.h"
#include "uint256.h"
#include "primitives/extdata.h"
static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
uint32_t n;
COutPoint(): n((uint32_t) -1) { }
COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(hash);
READWRITE(n);
}
void SetNull() { hash.SetNull(); n = (uint32_t) -1; }
bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
int cmp = a.hash.Compare(b.hash);
return cmp < 0 || (cmp == 0 && a.n < b.n);
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const;
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
uint32_t nSequence;
CScriptWitness scriptWitness; //! Only serialized through CTransaction
/* Setting nSequence to this value for every input in a transaction
* disables nLockTime. */
static const uint32_t SEQUENCE_FINAL = 0xffffffff;
/* Below flags apply in the context of BIP 68*/
/* If this flag set, CTxIn::nSequence is NOT interpreted as a
* relative lock-time. */
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
/* If CTxIn::nSequence encodes a relative lock-time and this flag
* is set, the relative lock-time has units of 512 seconds,
* otherwise it specifies blocks with a granularity of 1. */
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
/* If CTxIn::nSequence encodes a relative lock-time, this mask is
* applied to extract that lock-time from the sequence field. */
static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
/* In order to use the same number of bits to encode roughly the
* same wall-clock duration, and because blocks are naturally
* limited to occur every 600s on average, the minimum granularity
* for time-based relative lock-time is fixed at 512 seconds.
* Converting from CTxIn::nSequence to seconds is performed by
* multiplying by 512 = 2^9, or equivalently shifting up by
* 9 bits. */
static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
CTxIn()
{
nSequence = SEQUENCE_FINAL;
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const;
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
CAmount nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(nValue);
READWRITE(scriptPubKey);
}
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull() const
{
return (nValue == -1);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToString() const;
};
struct CMutableTransaction;
/**
* Basic transaction serialization format:
* - int32_t nVersion
* - std::vector<CTxIn> vin
* - std::vector<CTxOut> vout
* - uint32_t nLockTime
*
* Extended transaction serialization format:
* - int32_t nVersion
* - unsigned char dummy = 0x00
* - unsigned char flags (!= 0)
* - std::vector<CTxIn> vin
* - std::vector<CTxOut> vout
* - if (flags & 1):
* - CTxWitness wit;
* - uint32_t nLockTime
*/
template<typename Stream, typename TxType>
inline void UnserializeTransaction(TxType& tx, Stream& s) {
const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
s >> tx.nVersion;
unsigned char flags = 0;
tx.vin.clear();
tx.vout.clear();
/* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
s >> tx.vin;
if (tx.vin.size() == 0 && fAllowWitness) {
/* We read a dummy or an empty vin. */
s >> flags;
if (flags != 0) {
s >> tx.vin;
s >> tx.vout;
}
} else {
/* We read a non-empty vin. Assume a normal vout follows. */
s >> tx.vout;
}
if ((flags & 1) && fAllowWitness) {
/* The witness flag is present, and we support witnesses. */
flags ^= 1;
for (size_t i = 0; i < tx.vin.size(); i++) {
s >> tx.vin[i].scriptWitness.stack;
}
}
if (flags) {
/* Unknown flag in the serialization */
throw std::ios_base::failure("Unknown transaction optional data");
}
s >> tx.nLockTime;
s >> tx.extData;
}
template<typename Stream, typename TxType>
inline void SerializeTransaction(const TxType& tx, Stream& s) {
const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
s << tx.nVersion;
unsigned char flags = 0;
// Consistency check
if (fAllowWitness) {
/* Check whether witnesses need to be serialized. */
if (tx.HasWitness()) {
flags |= 1;
}
}
if (flags) {
/* Use extended format in case witnesses are to be serialized. */
std::vector<CTxIn> vinDummy;
s << vinDummy;
s << flags;
}
s << tx.vin;
s << tx.vout;
if (flags & 1) {
for (size_t i = 0; i < tx.vin.size(); i++) {
s << tx.vin[i].scriptWitness.stack;
}
}
s << tx.nLockTime;
s << tx.extData;
}
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
// Default transaction version.
static const int32_t CURRENT_VERSION=2;
// Changing the default transaction version requires a two step process: first
// adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date
// bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and
// MAX_STANDARD_VERSION will be equal.
static const int32_t MAX_STANDARD_VERSION=2;
// The local variables are made const to prevent unintended modification
// without updating the cached hash value. However, CTransaction is not
// actually immutable; deserialization and assignment are implemented,
// and bypass the constness. This is safe, as they update the entire
// structure, including the hash.
const int32_t nVersion;
const std::vector<CTxIn> vin;
const std::vector<CTxOut> vout;
const uint32_t nLockTime;
const CExtData extData;
private:
/** Memory only. */
const uint256 hash;
uint256 ComputeHash() const;
public:
/** Construct a CTransaction that qualifies as IsNull() */
CTransaction();
/** Convert a CMutableTransaction into a CTransaction. */
CTransaction(const CMutableTransaction &tx);
CTransaction(CMutableTransaction &&tx);
template <typename Stream>
inline void Serialize(Stream& s) const {
SerializeTransaction(*this, s);
}
/** This deserializing constructor is provided instead of an Unserialize method.
* Unserialize is not possible, since it would require overwriting const fields. */
template <typename Stream>
CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}
bool IsNull() const {
return vin.empty() && vout.empty();
}
const uint256& GetHash() const {
return hash;
}
// Compute a hash that includes both transaction and witness data
uint256 GetWitnessHash() const;
// Return sum of txouts.
CAmount GetValueOut() const;
// GetValueIn() is a method on CCoinsViewCache, because
// inputs must be known to compute value in.
/**
* Get the total transaction size in bytes, including witness data.
* "Total Size" defined in BIP141 and BIP144.
* @return Total transaction size in bytes
*/
unsigned int GetTotalSize() const;
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return a.hash == b.hash;
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return a.hash != b.hash;
}
std::string ToString() const;
bool HasWitness() const
{
for (size_t i = 0; i < vin.size(); i++) {
if (!vin[i].scriptWitness.IsNull()) {
return true;
}
}
return false;
}
};
/** A mutable version of CTransaction. */
struct CMutableTransaction
{
int32_t nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
uint32_t nLockTime;
CExtData extData;
CMutableTransaction();
CMutableTransaction(const CTransaction& tx);
template <typename Stream>
inline void Serialize(Stream& s) const {
SerializeTransaction(*this, s);
}
template <typename Stream>
inline void Unserialize(Stream& s) {
UnserializeTransaction(*this, s);
}
template <typename Stream>
CMutableTransaction(deserialize_type, Stream& s) {
Unserialize(s);
}
/** Compute the hash of this CMutableTransaction. This is computed on the
* fly, as opposed to GetHash() in CTransaction, which uses a cached result.
*/
uint256 GetHash() const;
friend bool operator==(const CMutableTransaction& a, const CMutableTransaction& b)
{
return a.GetHash() == b.GetHash();
}
bool HasWitness() const
{
for (size_t i = 0; i < vin.size(); i++) {
if (!vin[i].scriptWitness.IsNull()) {
return true;
}
}
return false;
}
};
typedef std::shared_ptr<const CTransaction> CTransactionRef;
static inline CTransactionRef MakeTransactionRef() { return std::make_shared<const CTransaction>(); }
template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
#endif // BITCOIN_PRIMITIVES_TRANSACTION_H
|
[
"dongyunbiao@itrustdata.com.cn"
] |
dongyunbiao@itrustdata.com.cn
|
d20d2c602ab628f57ac8beecf476bfa33ebf250e
|
d70ccc804729cb8af2c7076383c8965c6d3e0952
|
/UVA online judge/AOAPC I_ Beginning Algorithm Contests (Rujia Liu)/Volume 0. Getting Started/10055 - Hashmat the Brave Warrior.cpp
|
3f407ac009b66e64474b94be38c2921cd1bee63e
|
[] |
no_license
|
Saqib29/Problem-solving
|
5f57bfac02ff85f3e134de78a242c0cb2c8e4523
|
ecf966a8c6beda52218c76017981deffe6abdc08
|
refs/heads/master
| 2021-07-03T10:18:26.484183
| 2020-09-09T19:06:24
| 2020-09-09T19:06:24
| 164,236,758
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 376
|
cpp
|
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
long long int a, b; //there was data type problem
// unsigned didn't work here!
while(scanf("%lld %lld", &a, &b) != EOF)
{
if(a<b)
{
printf("%lld\n", b-a);
}
else
printf("%lld\n", a-b);
}
return 0;
}
|
[
"saqib29111@gmail.com"
] |
saqib29111@gmail.com
|
ed9038259b475443438c4ff7e743bc3749e4f30d
|
11a246743073e9d2cb550f9144f59b95afebf195
|
/kattis/largesttriangle.cpp
|
dd996b82b12b926c854137ca5fdb3481b6af771b
|
[] |
no_license
|
ankitpriyarup/online-judge
|
b5b779c26439369cedc05c045af5511cbc3c980f
|
8a00ec141142c129bfa13a68dbf704091eae9588
|
refs/heads/master
| 2020-09-05T02:46:56.377213
| 2019-10-27T20:12:25
| 2019-10-27T20:12:25
| 219,959,932
| 0
| 1
| null | 2019-11-06T09:30:58
| 2019-11-06T09:30:57
| null |
UTF-8
|
C++
| false
| false
| 1,696
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define all(x) begin(x), end(x)
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
using pt = pair<ll, ll>;
ll ccw(const pt& a, const pt& b, const pt& c) {
ll x1 = b.first - a.first;
ll y1 = b.second - a.second;
ll x2 = c.first - a.first;
ll y2 = c.second - a.second;
return x1 * y2 - x2 * y1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
vector<pt> pts(n);
for (int i = 0; i < n; ++i) {
cin >> pts[i].first >> pts[i].second;
}
sort(all(pts));
pts.erase(unique(all(pts)), end(pts));
n = pts.size();
vector<pt> hull;
if (pts.size() <= 2) {
hull = pts;
} else {
for (int k = 0; k < 2; ++k) {
int start = hull.size();
for (int i = 0; i < n; ++i) {
while (hull.size() >= start + 2 and
ccw(hull[hull.size() - 2], hull[hull.size() - 1], pts[i]) < 0) {
hull.pop_back();
}
hull.push_back(pts[i]);
}
hull.pop_back();
reverse(all(pts));
}
}
n = hull.size();
ll ans = 0LL;
for (int a = 0; a < n; ++a) {
int c = a;
for (int b = a + 1; b < n; ++b) {
while (abs(ccw(hull[a], hull[b], hull[c])) < abs(ccw(hull[a], hull[b], hull[(c + 1) % n]))) {
c = (c + 1) % n;
}
ans = max(ans, abs(ccw(hull[a], hull[b], hull[c])));
}
}
cout << (ans / 2) << "." << (ans & 1 ? "5" : "0") << '\n';
return 0;
}
|
[
"arnavsastry@gmail.com"
] |
arnavsastry@gmail.com
|
e3038baabf9d628a92e295cd2572bf36de18cb46
|
0ee652fc4120dc35d1f4114db31fd34b8cd0c2b5
|
/t1/q1/FibonacciHeap/FibonacciHeap.h
|
361b057c8bdeb7717052f01a17023cee86a59c5b
|
[] |
no_license
|
luizfls/paa211
|
819bdb22df4a908931cd8e0422138db43959aefc
|
8590119b1b0746ad0bca3d6e17cce21fba386cfa
|
refs/heads/main
| 2023-06-05T03:15:36.457654
| 2021-06-15T16:39:26
| 2021-06-15T16:39:26
| 363,583,121
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,137
|
h
|
#pragma once
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iterator>
#include <list>
#include <optional>
#include <stdexcept>
#include <utility>
#include <vector>
template <typename T>
struct FibonacciHeap
{
using value_type = T;
private:
struct Node;
public:
using NodePtr = typename std::list<Node>::iterator;
NodePtr insert(T data)
{
roots.emplace_back(data);
if(min == roots.end())
min = roots.begin();
else if(data < min->data)
min = std::prev(roots.end());
++size;
return std::prev(roots.end());
}
T extract_min()
{
if(min == roots.end())
throw std::logic_error{"extract_min called on empty heap"};
for(auto& child : min->children)
{
child.parent = {};
child.marked = false;
}
roots.splice(roots.end(), min->children);
auto ans = min->data;
roots.erase(min);
--size;
if(!roots.empty())
cleanup();
return ans;
}
void decrease_key(NodePtr node, int k)
{
node->data.first = k;
if(node->parent && node->data < (*node->parent)->data)
{
cut(node);
auto p = node->parent;
while(p && (*p)->marked)
{
auto tmp = (*p)->parent;
cut(*p);
p = tmp;
}
}
if(min == roots.end())
throw std::logic_error{"bad min value"};
else if(node->data < min->data)
min = node;
}
private:
struct Node
{
Node(T pData)
: data(pData)
, marked(false)
{}
T data;
std::optional<NodePtr> parent;
std::list<Node> children;
bool marked;
};
void cleanup()
{
std::vector<NodePtr> v(std::log2(size) + 2, roots.end());
auto it = roots.begin();
while(it != roots.end())
{
auto next = std::next(it);
auto degree = it->children.size();
while(v[degree] != roots.end())
{
auto min = v[degree];
auto max = it;
if(min->data > max->data)
std::swap(max, min);
min->children.splice(min->children.end(), roots, max);
max->parent = min;
v[degree] = roots.end();
it = min;
degree = it->children.size();
}
v[degree] = it;
it = next;
}
min = std::min_element(roots.begin(), roots.end(),
[](const auto& a, const auto& b)
{ return a.data < b.data; });
}
void cut(NodePtr node)
{
if(!node->parent)
throw std::logic_error{"cut called on root node"};
roots.splice(roots.end(), (*node->parent)->children, node);
node->parent = {};
node->marked = false;
}
std::list<Node> roots;
NodePtr min = roots.end();
std::size_t size = 0;
};
|
[
"luiz.felipe7@gmail.com"
] |
luiz.felipe7@gmail.com
|
6c4250fc06f8b04b29211acda528a25c86211556
|
eeaeb9bfeb56cff52b074b413b259c5de64eba24
|
/Principle 5/src/AllPrinciplesExemplar.cpp
|
684c13b75b4a07483cbabdc7a282b5dbc2e0b147
|
[] |
no_license
|
UW-COSC-4010-5010-CYBER-FA-2017/foundational-concepts-in-cybersecurity-aphorism14
|
4bc5dac805f456d7fef4c934bfa61a777f35520f
|
d7d7d5e91765e1085c45c1533cc59c76ca4dcef3
|
refs/heads/master
| 2021-07-24T06:16:41.737136
| 2017-11-01T06:03:17
| 2017-11-01T06:03:17
| 104,931,760
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,216
|
cpp
|
// Russell Todd
// Cybersecurity
// Principle 1 (Domain Separation) Exemplar
// Principle 2 (Process Isolation) Exemplar
// Principle 3 (Resource Encapsulation) Exemplar
// Principle 4 (Least Privilege) Exemplar
// Principle 5 (Modularity) Exemplar
// Principle 6 (Layering) Exemplar
// Principle 7 (Abstraction) Exemplar
// Principle 8 (Data Hiding) Exemplar
// Principle 9 (Simplicity) Exemplar
// Principle 10 (Minimization) Exemplar
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
#include <time.h>
using namespace std;
class Authority
{
public:
//Public Variables
string userInfo = "cake";
//Public Methods
// "Logs user in". Basically sets the operator's access privilege.
void login()
{
// Ask for Admin login or User login.
string status;
cout << "\nPlease enter your user status: " << endl;
cout << "Options are: 'Admin' or 'User'" << endl;
// Accept input.
cin >> status;
cout << "\nYou have entered: " << status << endl;
if (status == "Admin")
{
cout << "\nWelcome, GLaDOS.\n" << endl;
adminPriv = true;
}
else if (status == "User")
{
cout << "\nWelcome, Chell.\n" << endl;
}
else
{
cout << "Invalid entry. Please exit and try again." << endl;
}
}
// "Logs user out". Resets the operator's access privilege.
void logout()
{
adminPriv = false;
}
// Prints out some information the Admin & User setting has access to.
void userAccess(string input)
{
cout << "\nInformation available to you: \n" << userInfo << endl;
}
// Prints out some information that only the Admin setting has access to.
void adminAccess(string input)
{
cout << "\nInformation available to you: \n" << AdminInfo << endl;
}
// Returns whether the operator has Admin credentials or not.
bool checkPriv()
{
if (adminPriv == false)
{
return false;
}
else if (adminPriv == true)
{
return true;
}
else
{
;
}
}
// Adds new information to this hyper-simplified databank.
void setNewInfo(string input)
{
newInfo.push_back(input);
};
// Prints out the contents of our "databank".
void printInfo()
{
for (vector<string>::const_iterator i = newInfo.begin(); i != newInfo.end(); ++i)
{
cout << *i << ", ";
}
}
void returnSecret()
{
cout << "\nAccess Granted." << endl;
cout << "\n" << superSecretBlackmail << "\n" << endl;
}
// Private variables & storage
private:
bool adminPriv = false;
string AdminInfo = "cake is a lie";
string superSecretBlackmail = "GLaDOS is Caroline.";
vector <string> newInfo;
};
class PunGenerator
{
public:
void tellBadPun()
{
// Seed random
srand(time(NULL));
int jokeNum = rand() % 5;
// Shamebot's pun tolerance is only so high.
if (shameIterator == 7)
{
cout << "\nSorry, I am too ashamed to continue. Please go do something else.\n" << endl;
return;
}
// Choose randomly between 5 jokes.
switch (jokeNum)
{
case 0:
{
cout << "\nI lost my job at the bank on my very first day." << endl;
cout << "A woman asked me to check her balance, so..." << endl;
cout << ".\n.\n.\n" << endl;
cout << "I pushed her over....\n" << endl;
shameIterator +=1;
cout << "My shame level is: " << shameIterator << endl << endl;
break;
}
case 1:
{
cout << "\nI tried to sue the airport for misplacing my luggage..." << endl;
cout << ".\n.\n.\n" << endl;
cout << "I lost my case....\n" << endl;
shameIterator +=1;
cout << "My shame level is: " << shameIterator << endl << endl;
break;
}
case 2:
{
cout << "\nR.I.P. Mr. Boiling Water...." << endl;
cout << ".\n.\n.\n" << endl;
cout << "You will be mist....\n" << endl;
shameIterator +=1;
cout << "My shame level is: " << shameIterator << endl << endl;
break;
}
case 3:
{
cout << "\nWhat is the best thing about living in Switzerland?" << endl;
cout << ".\n.\n.\n" << endl;
cout << "Well the flag is a big plus....\n" << endl;
shameIterator +=1;
cout << "My shame level is: " << shameIterator << endl << endl;
break;
}
case 4:
{
cout << "\nWhat's the difference between a hippo and a Zippo?" << endl;
cout << ".\n.\n.\n" << endl;
cout << "One is really heavy and the other is a little lighter....\n" << endl;
shameIterator +=1;
cout << "My shame level is: " << shameIterator << endl << endl;
break;
}
}
}
private:
int shameIterator = 0;
bool ashamed = false;
};
// Asks operator what info they desire to access. Access may be allowed or denied depending on operator privilege status.
void infoRequest(Authority program)
{
cout << "\nAdmins may access both Admin info and User info, while Users may only access User info.\nPlease enter an information request command: " << endl;
cout << "Options are: 'AdminInfo' or 'UserInfo'" << endl;
string input;
cin >> input;
// If the operator wants AdminInfo, they must pass the privilege check. Anyone can acquire UserInfo.
if (input == "AdminInfo" && program.checkPriv())
{
program.adminAccess(input);
}
else if (input == "UserInfo")
{
program.userAccess(input);
}
else
{
cout << "Invalid entry. Please try again." << endl;
}
}
// Asks operator if they want to read from the "database" or write to it. Only Admins may write, while either Admins or Users can read what has been written.
void dataReadWrite(Authority program)
{
// Presents different choices depending on whether operator has Admin privileges.
if (program.checkPriv() == true)
{
// Admin can choose to read database or write new info into it.
cout << "\nAs an admin, you may both enter new information \nand read previously entered information" << endl;
cout << "To enter new information, enter '1'. To view information, enter '2'." << endl;
int z;
cin >> z;
if (z == 1)
{
cout << "You may now enter new information. Limit yourself to a single continous string. \nPlease write your input below: " << endl;
string newString;
cin >> newString;
cout << "You entered: " << newString << endl;
program.setNewInfo(newString);
}
else if (z == 2)
{
program.printInfo();
}
else
{
cout << "Invalid Input." << endl;
}
}
else if (program.checkPriv() == false)
{
// User can only choose whether they want to read from database.
cout << "\nAs a user, you may read information previously entered by Admins." << endl;
cout << "Do you want to view the information? Please enter 'Y' or 'N'" << endl;
string a;
cin >> a;
if (a == "Y" | a == "y")
{
program.printInfo();
}
else if (a == "N" | a == "n")
{
;
}
else
{
cout << "Invalid Input." << endl;
}
}
}
void superSecret(Authority program)
{
cout << "\nTo access the super secret information, enter the secondary password." << endl;
cout << "Hint: Only Admins can view the password. To enter spaces, use '_'." << endl;
cout << "Please enter the secondary password now: " << endl;
string secondaryPassword;
cin >> secondaryPassword;
if (secondaryPassword == "cake_is_a_lie")
{
program.returnSecret();
}
else
{
cout << "\nNice try, Wheatley." << endl;
}
}
// Launches the work sim.
void launchWorkSim()
{
// Instantiate Authority object. Our "program".
Authority program;
// Loop for easy iteration and testing both operator settings.
while (true)
{
// Calls function to "log in" operator.
program.login();
// Calls function to allow operator to request information.
infoRequest(program);
// Calls function to all operator to read or write "data" to a "database" depending on operator credentials.
dataReadWrite(program);
// Calls function that allows operator to enter secondary password to access super secret information.
superSecret(program);
// Logs operator out.
program.logout();
}
}
// Launches Shamebot (aka pun generator)
void launchShamebot()
{
// Instanstiate ShameBot
PunGenerator ShameBot;
// Loops
while (true)
{
cout << "\nWould you like to hear a joke?!?!?!?" << endl;
cout << "Enter 'Yes' or 'NO'" << endl;
string regret;
cin >> regret;
if (regret == "Yes")
{
ShameBot.tellBadPun();
}
else if (regret == "NO")
{
cout << "Oh thank goodness." << endl;
break;
}
else
{
cout << "Invalid input. If you wish to escape this purgatory, try entering 'NO' next time." << endl;
}
}
}
// Asks operater which program they want to launch.
void chooseProgram()
{
while (true)
{
cout << "\n\nEnter '1' to log in as User or Admin on work partition." << endl;
cout << "Enter '2' to tickle your funny bone." << endl;
cout << "Please enter '1' or '2' now:" << endl;
int choice;
cin >> choice;
switch (choice)
{
case 1:
{
launchWorkSim();
}
case 2:
{
launchShamebot();
}
}
}
}
// Main
int main()
{
// Choose the program.
chooseProgram();
}
|
[
"noreply@github.com"
] |
UW-COSC-4010-5010-CYBER-FA-2017.noreply@github.com
|
535fb8cfeecf26f52cfc84bf6233ea06734488f4
|
7d5538864d38167b2cb66764b4ea5c85bee0c918
|
/atcoder/abc/219/c.cpp
|
95152aacaaf5dfb8467ab7a040d4cecb7de64128
|
[] |
no_license
|
iPolyomino/contest
|
ec63acef925bf4a9b562aab46fc247d0fe7a71b9
|
96bea95174cc320f0620da322a25668ac5c500cd
|
refs/heads/master
| 2023-07-09T01:19:33.026494
| 2023-06-24T01:06:13
| 2023-06-24T01:06:13
| 163,596,349
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 596
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
string X;
bool compare(string left, string right)
{
int lIndex = X.find(left[0]);
int rIndex = X.find(right[0]);
if (lIndex == rIndex) {
if (left.size() == 1) {
return true;
} else if (right.size() == 1) {
return false;
}
return compare(left.substr(1), right.substr(1));
}
return lIndex < rIndex;
}
int main()
{
cin >> X;
int N;
cin >> N;
vector<string>S(N);
for (int i = 0; i < N; i++) {
cin >> S[i];
}
sort(S.begin(), S.end(), compare);
for (int i = 0; i < N; i++) {
cout << S[i] << endl;
}
return 0;
}
|
[
"macbookpromacbookpromacbookpro@gmail.com"
] |
macbookpromacbookpromacbookpro@gmail.com
|
29595bb857fc8bc25a957b4923bc7e1adb01bc28
|
101036abb220a37af1ad838e6b68ca6431da39c7
|
/DHT22 lcd.ino
|
a367823b9c1fce2e1b02122744bfe9a6bbc30912
|
[] |
no_license
|
estagio2018/SensorDHT
|
d2066b5ea0199d89802423c065afd57a15ccae44
|
90378b293c21c18166260f7edd8ab4f4e8d35f35
|
refs/heads/master
| 2020-04-22T12:22:03.721719
| 2019-02-18T18:39:53
| 2019-02-18T18:39:53
| 170,368,963
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,637
|
ino
|
//---------- Bloco de define e inclusão de bibliotecas ----------------//
#include "DHT.h" //Biblioteca do DHT
#include <Wire.h> //Biblioteca do módulo I2C
#include <LiquidCrystal_I2C.h> //Biblioteca do LCD
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // configurações do LCD
#define PINODHT 2 //Pino para comunicação com DHT
#define TIPODHT DHT22 //DHT22(AM2302/ AM2321)
DHT dht(PINODHT, TIPODHT); //Configuraçãoes do DHT
// ------------- Inicialização de DHT e LCD ---------------------------//
void setup() {
lcd.begin(16, 2); // inicializa o LCD
lcd.setCursor(0, 0);
lcd.print("Testando o sen-");
lcd.setCursor(0, 1);
lcd.print("sor de tempera-");
delay(2500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("tura e umidade");
lcd.setCursor(0,1);
lcd.print("DHT22!");
delay(2500);
lcd.clear();
dht.begin(); //Inicializa o DHT
}
// ------------------- Lê e mostra informações -------------------- //
void loop() {
delay(1000); //Espera um segundo para as informações aparecerem.
//Ler a temperatura ou humidade leva cerca de 250 milisegundos!
float h = dht.readHumidity();
//Lê a temperatura em Celsius (padrão)
float t = dht.readTemperature();
// Checando se qualquer leitura falhou.
if (isnan(h) || isnan(t)) {
lcd.setCursor(0, 1);
lcd.print("Falha ao ler");
return;
}
lcd.setCursor(0, 0);
lcd.print("Umid: ");
lcd.setCursor(6, 0);
lcd.print(h);
lcd.setCursor(12, 0);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.setCursor(6, 1);
lcd.print(t);
lcd.setCursor(12, 1);
lcd.print("*C ");
}
|
[
"noreply@github.com"
] |
estagio2018.noreply@github.com
|
ab493f8639e22108e1be8f0f92b1f580ff116d60
|
41bda13313dc1643f55043507cb780012f4a8e0e
|
/physx_demo/source/gl_manager.cpp
|
e7cdc02e67a76d1f9765908296a25852528f1229
|
[] |
no_license
|
BarleyTuan/work
|
f965307032c42941eceb09c7c1d51db142bd7ba4
|
fc41c570ac76a23802ea75c903917db7281a5837
|
refs/heads/master
| 2021-01-12T11:42:49.324079
| 2017-02-07T09:37:42
| 2017-02-07T09:37:42
| 72,273,204
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,454
|
cpp
|
#include "gl_manager.h"
void GlManager::DrawGrid(int grid_size) {
glBegin(GL_LINES);
glColor3f(0.75f, 0.75f, 0.75f);
for(int i = -grid_size; i<=grid_size; i++) {
glVertex3f((float) i, 0, (float) -grid_size);
glVertex3f((float) i, 0, (float) grid_size);
glVertex3f((float) -grid_size, 0, (float) i);
glVertex3f((float) grid_size, 0, (float) i);
}
glEnd();
}
void GlManager::getColumnMajor(PxMat33 m, PxVec3 t, float* mat) {
mat[0] = m.column0[0];
mat[1] = m.column0[1];
mat[2] = m.column0[2];
mat[3] = 0;
mat[4] = m.column1[0];
mat[5] = m.column1[1];
mat[6] = m.column1[2];
mat[7] = 0;
mat[8] = m.column2[0];
mat[9] = m.column2[1];
mat[10] = m.column2[2];
mat[11] = 0;
mat[12] = t[0];
mat[13] = t[1];
mat[14] = t[2];
mat[15] = 1;
}
void GlManager::DrawBox(PxShape* pShape, PxRigidActor* actor) {
PxTransform pT = PxShapeExt::getGlobalPose(*pShape, *actor);
PxBoxGeometry bg;
pShape->getBoxGeometry(bg);
PxMat33 m = PxMat33(pT.q);
float mat[16];
getColumnMajor(m, pT.p, mat);
glPushMatrix();
glMultMatrixf(mat);
glutSolidCube(bg.halfExtents.x*2);
glPopMatrix();
}
void GlManager::DrawShape(PxShape* shape, PxRigidActor* actor) {
PxGeometryType::Enum type = shape->getGeometryType();
switch(type) {
case PxGeometryType::eBOX:
DrawBox(shape, actor);
break;
}
}
void GlManager::DrawActor(PxRigidActor* actor) {
PxU32 nShapes = actor->getNbShapes();
PxShape** shapes = new PxShape*[nShapes];
actor->getShapes(shapes, nShapes);
while(nShapes--) {
DrawShape(shapes[nShapes], actor);
}
delete[] shapes;
}
void GlManager::RenderActors() {
GLfloat mat_diffuse[4] = {0.85f, 0, 0, 0};
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mat_diffuse);
for (int i = 0; i < px_manager->boxes.size(); ++i) {
DrawActor(px_manager->boxes[i]);
}
for(map<int, PxController *>::iterator iter = px_manager->character_controller_map.begin();
iter != px_manager->character_controller_map.end(); ++iter) {
PxController *controller = iter->second;
glPushMatrix();
GLfloat mat_diffuse2[4] = {0.0f, 1.0f, 0, 0};
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mat_diffuse2);
const PxExtendedVec3 position = controller->getPosition();
glTranslatef(
controller->getPosition().x,
controller->getPosition().y,
controller->getPosition().z);
glutSolidCube(1.0f);
glPopMatrix();
}
}
void GlManager::OnRender() {
int current = glutGet(GLUT_ELAPSED_TIME);
float diff_time = (current - pre_tick) / 1000.0;
if (px_manager->gScene) {
px_manager->UpdatePhysX(diff_time);
}
//Draw the grid and axes
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0, 0, -10);
glRotatef(15, 1, 0, 0);
glRotatef(0, 0, 1, 0);
DrawGrid(10);
glEnable(GL_LIGHTING);
RenderActors();
glDisable(GL_LIGHTING);
glColor3f(1, 1, 1);
glutSwapBuffers();
PyEval_CallObject(update_func, Py_BuildValue("(i)", current-pre_tick));
pre_tick = current;
}
void GlManager::OnKeyboard(unsigned char key, int mx, int my) {
PyEval_CallObject(key_func, Py_BuildValue("(c)", key));
/*
float movement = 1;
x = add_y = add_z = 0;
if(key=='j') {
add_y = 3 * movement;
}
if(key=='w') {
add_z = -movement;
}
if(key=='s') {
add_z = movement;
}
if(key=='d') {
add_x = movement;
}
if(key=='a') {
add_x = -movement;
}
px_manager->MovePosition(1, PxVec3(add_x, add_y, add_z), 1);
add_x = add_y = add_z = 0;
*/
}
void GlManager::OnKeyboardUp(unsigned char key, int mx, int my) {
}
|
[
"handybiz@163.com"
] |
handybiz@163.com
|
826095773911814c19a90c986aac208aa08be17a
|
53f343023df12ac59d9489de9c0c3611b2cb6bfa
|
/Chapter11/ex11_1.cpp
|
e039b78ef1b606ae3b058a71152eb981d3b6e6f9
|
[] |
no_license
|
Sparrow-hawks/C-Primer-Plus-Exercises
|
0b1884a25e08fe77cc7bd2038b4602376a11961e
|
ae9e3df0336b6edaa969d9aae2b04e6808ed8c87
|
refs/heads/master
| 2021-04-09T15:44:10.300636
| 2018-03-18T14:54:45
| 2018-03-18T14:54:45
| 125,735,612
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,679
|
cpp
|
// Book: C++ Primer Plus
// Chapter: 11
// Exercise: 1
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include "vect_1.h"
int main() {
using namespace std;
using VECTOR::Vector;
srand(time(0));
double direction;
Vector step;
Vector result(0.0, 0.0);
unsigned long steps = 0;
double target;
double dstep;
cout << "Podaj dystans do przejścia (k, aby zakończyć): ";
while (cin >> target) {
cout << "Podaj długość kroku: ";
if (!(cin >> dstep))
break;
std::ofstream outFile;
outFile.open("Results.txt", std::ofstream::out | std::ofstream::trunc);
if (!outFile.is_open()) {
cout << "Nie mogę utworzyć pliku z raporterm!\n";
exit(EXIT_FAILURE);
}
outFile << "Dystans do przejścia: " << target << ", długość kroku: " << dstep << endl;
while (result.magval() < target) {
direction = rand() % 360;
step.reset(dstep, direction, Vector::POL);
result = result + step;
step.rect_mode();
outFile << steps << ": " << step << std::endl;
steps++;
}
cout << "Po " << steps << " krokach delikwent "
"osiągnął położenie:\n";
cout << result << endl;
result.polar_mode();
cout << " czyli\n" << result << endl;
result.rect_mode();
outFile << "Po " << steps << " krokach delikwent "
"osiągnął położenie:\n";
outFile << result << endl;
result.polar_mode();
outFile << " czyli\n" << result << endl;
steps = 0;
result.reset(0.0, 0.0);
outFile.close();
cout << "Podaj dystans do przejścia (k, aby zakończyć): ";
}
cout << "Koniec!\n";
return 0;
}
|
[
"sparrow-hawk@hotmail.com"
] |
sparrow-hawk@hotmail.com
|
fbc51273fbb7804566ca4f74a6dbcac0dca8eef0
|
ef2f818f3a89511f854f053904839cf72c756f83
|
/RandomPlayer.cpp
|
a2c1668978c8b01a2a93b38bf124a5aaa5055ad0
|
[] |
no_license
|
Buzzkata/ReversiBoardGame
|
631f1123ca435f6992ee08631f5e60757d808f2f
|
6192f685a5245bec0155374ffe29530c8b75931e
|
refs/heads/main
| 2023-02-24T19:11:44.578297
| 2021-01-29T04:43:04
| 2021-01-29T04:43:04
| 334,039,161
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 389
|
cpp
|
//Bozhidar Stoyanov, 0353616
#include "RandomPlayer.h"
#include "Board.h"
#include "Game.h"
#include "ReversiTester.h"
#include <vector>
using namespace std;
//random player class
class RandomPlayer : public ComputerPlayer {
vector<Move> validMoves;
void makeMove() {
genValidMoves();
}
void genValidMoves() {
for (int i = 0; i < 64; i++) {
}
}
};
|
[
"noreply@github.com"
] |
Buzzkata.noreply@github.com
|
ff2915ac686cfcfcc65e44c5e3063f3e03bd9d54
|
a1cf56748379556e3573e45c9f953cfede2c8512
|
/RandomWalkGenerator.h
|
c2a791f7368c6a8648e3960f6d892d0f68f8329d
|
[] |
no_license
|
EdemEkoue98/CProject
|
f94be9707e3b67c3452ea7be0c2ff88371590146
|
6a4f666f355fa250c4a05a5f3ed775d7503cebf6
|
refs/heads/main
| 2023-03-31T03:16:28.620673
| 2021-04-03T12:00:22
| 2021-04-03T12:00:22
| 354,273,082
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 441
|
h
|
#include <iostream>
#include "RandomWalk.cpp"
class RandomWalkGenerator
{
public:
// Methods
static RandomWalkGenerator& getInstance();
static RandomWalk generate(int, std::string, float, float, float);
private:
// Constructor
RandomWalkGenerator();
// Methods
static std::vector<float> generateInnovationProcess(int, std::string, float, float);
static int convertDistribution(std::string);
};
|
[
"edemedem12345@gmail.com"
] |
edemedem12345@gmail.com
|
16d2fb5c056c01f443581d39e27ccd52b136bf61
|
c01b74e74650e6dd5f8affac9fb5ce7a970f7ffb
|
/Source/CoopHordeShooter/Private/CSGameMode.cpp
|
baa1e6c7c2eb9e428be4fe211b295de54df58eea
|
[
"MIT"
] |
permissive
|
AomDEV/CoopHordeShooter
|
af404a25a5e6aa18d2295ce7126f862deec4231f
|
de118fb1f9379508e40b210f0f7d18ede5541bd3
|
refs/heads/master
| 2020-03-29T06:26:32.057564
| 2018-02-01T08:57:10
| 2018-02-01T08:57:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,710
|
cpp
|
#include "CSGameMode.h"
#include "TimerManager.h"
#include "Engine/World.h"
#include "CSHealthComponent.h"
#include "CSGameState.h"
#include "CSPlayerState.h"
ACSGameMode::ACSGameMode():
BotsToSpawn(0),
WaveCount(0),
TimeBetweenWaves(10.0f)
{
GameStateClass = ACSGameState::StaticClass();
PlayerStateClass = ACSPlayerState::StaticClass();
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickInterval = 1.0f;
}
void ACSGameMode::StartWave()
{
WaveCount++;
BotsToSpawn = 2 * WaveCount;
GetWorldTimerManager().SetTimer(TimerHandle_BotSpawner, this, &ACSGameMode::SpawnBotTimerElapsed, 1.0f, true, 0.0f);
SetWaveState(EWaveState::WaveInProgress);
}
void ACSGameMode::EndWave()
{
GetWorldTimerManager().ClearTimer(TimerHandle_BotSpawner);
SetWaveState(EWaveState::WaitingToComplete);
}
void ACSGameMode::PrepareForNextWave()
{
GetWorldTimerManager().SetTimer(TimerHandle_NextWaveStart, this, &ACSGameMode::StartWave, TimeBetweenWaves, false);
SetWaveState(EWaveState::WaitingToStart);
RestartDeadPlayers();
}
void ACSGameMode::CheckWaveState()
{
bool bIsPreparingForWave = GetWorldTimerManager().IsTimerActive(TimerHandle_NextWaveStart);
if (BotsToSpawn > 0 || bIsPreparingForWave)
{
return;
}
bool bWaveIsPassed = true;
for (FConstPawnIterator It=GetWorld()->GetPawnIterator(); It ; ++It)
{
APawn* TestPawn = It->Get();
if (TestPawn == nullptr || TestPawn->IsPlayerControlled())
{
continue;
}
UCSHealthComponent* HealthComponent = Cast<UCSHealthComponent>(TestPawn->GetComponentByClass(UCSHealthComponent::StaticClass()));
if (HealthComponent && HealthComponent->GetHealth() >= 0.0f)
{
bWaveIsPassed = false;
break;
}
}
if (bWaveIsPassed)
{
SetWaveState(EWaveState::WaveComplete);
PrepareForNextWave();
}
}
void ACSGameMode::SpawnBotTimerElapsed()
{
SpawnNewBot();
BotsToSpawn--;
if (BotsToSpawn <= 0)
{
EndWave();
}
}
void ACSGameMode::CheckAnyPlayerIsAlive()
{
for(FConstPlayerControllerIterator It=GetWorld()->GetPlayerControllerIterator(); It; ++It)
{
APlayerController* PlayerController = It->Get();
if (PlayerController && PlayerController->GetPawn())
{
APawn* Pawn = PlayerController->GetPawn();
UCSHealthComponent* HealthComponent = Cast<UCSHealthComponent>(Pawn->GetComponentByClass(UCSHealthComponent::StaticClass()));
if (ensure(HealthComponent) && HealthComponent->GetHealth() > 0.0f)
{
// A player is still alive.
return;
}
}
}
// No players alive
GameOver();
}
void ACSGameMode::GameOver()
{
EndWave();
SetWaveState(EWaveState::GameOver);
UE_LOG(LogTemp, Log, TEXT("Game over!. All players are died."));
}
void ACSGameMode::SetWaveState(EWaveState NewState)
{
ACSGameState* GameState = GetGameState<ACSGameState>();
if (ensureAlways(GameState))
{
GameState->SetWaveState(NewState);
}
}
void ACSGameMode::RestartDeadPlayers()
{
for(FConstPlayerControllerIterator It=GetWorld()->GetPlayerControllerIterator(); It; ++It)
{
APlayerController* PlayerController = It->Get();
if (PlayerController && PlayerController->GetPawn() == nullptr)
{
RestartPlayer(PlayerController);
}
}
}
void ACSGameMode::StartPlay()
{
Super::StartPlay();
PrepareForNextWave();
}
void ACSGameMode::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
CheckWaveState();
CheckAnyPlayerIsAlive();
}
|
[
"relrin78@gmail.com"
] |
relrin78@gmail.com
|
b620698779b0cee9ffde47814a3bb6f8f22026b5
|
c2efe54b8ad33c2a6f516b865fc104894d800186
|
/[其他]1001.Travel Information Center.cpp
|
6e335537cda565e80700aebb12aa5d013f86fc55
|
[] |
no_license
|
Fly365/AlgorithmCode
|
2f8df8b934dcd3099d0e6b0fed66b670f28d21b3
|
389401a4f7eb9f97ff524277c6e049771276e700
|
refs/heads/master
| 2021-01-12T17:56:10.927847
| 2015-10-27T02:00:23
| 2015-10-27T02:00:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,895
|
cpp
|
#include <iostream>
#include <vector>
#include <limits.h>
#include <list>
using namespace std;
#define N 100002
// Any two cities are connected directly or indirectly and there is ONLY one path between any 2 cities
class Solution {
public:
int ShortestPath(vector<list<int> > Map,vector<bool> city,int num){
if(num <= 0){
return 0;
}//if
if(city[num]){
return 0;
}//if
vector<bool> visited(N,false);
int result = INT_MAX;
BFS(Map,city,visited,0,result,num);
return result;
}
private:
void BFS(vector<list<int> > &Map,vector<bool> &city,vector<bool> &visited,int cur,int &result,int pos){
if(city[pos]){
if(cur < result){
result = cur;
}//if
return;
}//if
visited[pos] = true;
// 相邻城市
list<int> c = Map[pos];
list<int>::iterator ite = c.begin();
while(ite != c.end()){
int num = *ite;
if(!visited[num]){
int tmp = cur + 1;
BFS(Map,city,visited,tmp,result,num);
}//if
++ite;
}//while
visited[pos] = false;
}
};
int main(){
Solution s;
int x,y,n,m;
//freopen("C:\\Users\\Administrator\\Desktop\\acm.txt","r",stdin);
while(cin>>n>>m){
vector<list<int> > Map(N,list<int>());
vector<bool> city(N,false);
city[1] = true;
for(int i = 1;i <= n-1;++i){
cin>>x>>y;
Map[x].push_back(y);
Map[y].push_back(x);
}//for
for(int i = 1;i <= m;++i){
cin>>x>>y;
if(x == 1){
city[y] = true;
}//if
else if(x == 2){
cout<<s.ShortestPath(Map,city,y)<<endl;
}//else
}//for
}//while
return 0;
}
|
[
"1203745031@qq.com"
] |
1203745031@qq.com
|
ed2d63fb73c7b3027cfba44f5bc2f74f04a71cb1
|
abe58add361b401b53045fdacdd8a65635ed7e7f
|
/src/base/application.h
|
53b95f74531e1dc0e8bf214d0e7dce57552360db
|
[
"BSD-2-Clause"
] |
permissive
|
arthurx70/mayo
|
50862f434a167a5e332c7f676345a1d83f161681
|
1cec4f6aec31bf942ed9e836849923102780210b
|
refs/heads/master
| 2023-01-23T13:14:13.383475
| 2020-07-09T09:48:12
| 2020-07-09T09:48:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,820
|
h
|
/****************************************************************************
** Copyright (c) 2020, Fougue Ltd. <http://www.fougue.pro>
** All rights reserved.
** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt
****************************************************************************/
#pragma once
#include "application_item.h"
#include "result.h"
#include "span.h"
#ifdef HAVE_GMIO
# include <gmio_core/text_format.h>
# include <gmio_stl/stl_format.h>
#endif
#include <QtCore/QObject>
#include <string>
#include <vector>
class QFileInfo;
namespace qttask { class Progress; }
namespace Mayo {
class Document;
class DocumentItem;
class Property;
class Application : public QObject {
Q_OBJECT
public:
// -- Types
enum class PartFormat {
Unknown,
Iges,
Step,
OccBrep,
Stl
};
using IoResult = Result<void>;
struct ExportOptions {
#ifdef HAVE_GMIO
gmio_stl_format stlFormat = GMIO_STL_FORMAT_UNKNOWN;
std::string stlaSolidName;
gmio_float_text_format stlaFloat32Format =
GMIO_FLOAT_TEXT_FORMAT_SHORTEST_LOWERCASE;
uint8_t stlaFloat32Precision = 9;
#else
enum class StlFormat {
Ascii,
Binary
};
StlFormat stlFormat = StlFormat::Binary;
#endif
};
enum class StlIoLibrary {
Gmio,
OpenCascade
};
// -- API
static Application* instance();
Span<Document* const> documents() const;
int documentCount() const;
Document* documentAt(int index) const;
int findDocumentByLocation(const QFileInfo& loc) const;
int indexOfDocument(const Document* doc) const;
void addDocument(Document* doc);
bool eraseDocument(Document* doc);
static Span<const PartFormat> partFormats();
static QString partFormatFilter(PartFormat format);
static QStringList partFormatFilters();
static PartFormat findPartFormat(const QString& filepath);
Application::StlIoLibrary stlIoLibrary() const;
void setStlIoLibrary(Application::StlIoLibrary lib);
IoResult importInDocument(
Document* doc,
PartFormat format,
const QString& filepath,
qttask::Progress* progress = nullptr);
IoResult exportApplicationItems(
Span<const ApplicationItem> appItems,
PartFormat format,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress = nullptr);
static bool hasExportOptionsForFormat(PartFormat format);
static void setOpenCascadeEnvironment(const QString& settingsFilepath);
signals:
void documentAdded(Document* doc);
void documentErased(const Document* doc);
void documentPropertyChanged(Document* doc, Property* prop);
void documentItemAdded(DocumentItem* docItem);
void documentItemErased(const DocumentItem* docItem);
void documentItemPropertyChanged(DocumentItem* docItem, Property* prop);
// -- Implementation
private:
Application(QObject* parent = nullptr);
IoResult importIges(
Document* doc, const QString& filepath, qttask::Progress* progress);
IoResult importStep(
Document* doc, const QString& filepath, qttask::Progress* progress);
IoResult importOccBRep(
Document* doc, const QString& filepath, qttask::Progress* progress);
IoResult importStl(
Document* doc, const QString& filepath, qttask::Progress* progress);
IoResult exportIges(
Span<const ApplicationItem> appItems,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress);
IoResult exportStep(
Span<const ApplicationItem> appItems,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress);
IoResult exportOccBRep(
Span<const ApplicationItem> appItems,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress);
IoResult exportStl(
Span<const ApplicationItem> appItems,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress);
IoResult exportStl_gmio(
Span<const ApplicationItem> appItems,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress);
IoResult exportStl_OCC(
Span<const ApplicationItem> appItems,
const ExportOptions& options,
const QString& filepath,
qttask::Progress* progress);
std::vector<Document*> m_documents;
StlIoLibrary m_stlIoLibrary = StlIoLibrary::OpenCascade;
};
} // namespace Mayo
|
[
"delorme.hugues@fougue.pro"
] |
delorme.hugues@fougue.pro
|
26ad575cbe8c49ce9c553c0d19f344d2b8f34e71
|
68ea83d49f993e2f2caa630cffdf2f3ee3b35fdf
|
/tools/aac_converter/aac_converter/test.cpp
|
15809f12851a869835c7d5f8e915bd1e6f13dfa4
|
[] |
no_license
|
xiangchunsong520/UnityClientFramework
|
ac42bdd36cc11c3d1246179d19c7c319b4a3a555
|
627c9a41ecc5f124bfbee96d070712faa4e9a61e
|
refs/heads/master
| 2021-01-23T00:16:04.661357
| 2018-01-25T17:47:33
| 2018-01-25T17:47:33
| 85,711,138
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 391
|
cpp
|
#include "aac_converter.h"
#include <stdio.h>
int main()
{
int id;
unsigned long frameSamples, maxOutputBytes;
id = StartEncode(44100, 1, &frameSamples, &maxOutputBytes);
id = StartEncode(44100, 1, &frameSamples, &maxOutputBytes);
printf("id\t%d\n", id);
printf("frameSamples\t%d\n", frameSamples);
printf("maxOutputBytes\t%d\n", maxOutputBytes);
return 0;
}
|
[
"xiangchunsong520@gmail.com"
] |
xiangchunsong520@gmail.com
|
ac6979203256c9932e1b999866d1dd29eebc9b2f
|
23553b6bcf0a278776f0a651b24a3c6a22a702f9
|
/ALibrary/Console/tFileToFile.cpp
|
588a06ad804169423f0e3959ab6486f184643ec0
|
[] |
no_license
|
achacha/AOS
|
24ace04a4228de4d0295379d84cb936c2a33511b
|
bea07af94f23982d4fceb10a9cf70a7e5467355f
|
refs/heads/master
| 2020-05-17T12:20:35.667655
| 2016-02-10T13:33:43
| 2016-02-10T13:33:43
| 3,578,772
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 326
|
cpp
|
#include "AFile_AString.hpp"
void testReadWrite()
{
{
AFile_AString source("0123456789");
AFile_AString target;
target.write(source, 4);
target.write(source, 2);
target.write(source, 5);
std::cout << target << std::endl;
}
}
int main()
{
testReadWrite();
return 0;
}
|
[
"achacha@1a8727a7-69a9-4645-974c-ee3eb180c2d6"
] |
achacha@1a8727a7-69a9-4645-974c-ee3eb180c2d6
|
dcfc2ccc547520bed1fc346ca151728e2dc16bc9
|
ac227cc22d5f5364e5d029a2cef83816a6954590
|
/applications/physbam/physbam-lib/Public_Library/PhysBAM_Geometry/Grids_RLE_Interpolation_Collidable/INTERPOLATION_COLLIDABLE_RLE_FORWARD.h
|
3e32d8cc5115bcbf6b1566b8b0322786af392021
|
[
"BSD-3-Clause"
] |
permissive
|
schinmayee/nimbus
|
597185bc8bac91a2480466cebc8b337f5d96bd2e
|
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
|
refs/heads/master
| 2020-03-11T11:42:39.262834
| 2018-04-18T01:28:23
| 2018-04-18T01:28:23
| 129,976,755
| 0
| 0
|
BSD-3-Clause
| 2018-04-17T23:33:23
| 2018-04-17T23:33:23
| null |
UTF-8
|
C++
| false
| false
| 1,143
|
h
|
//#####################################################################
// Copyright 2009, Geoffrey Irving.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Header INTERPOLATION_COLLIDABLE_RLE_FORWARD
//#####################################################################
#ifndef COMPILE_WITHOUT_RLE_SUPPORT
#ifndef __INTERPOLATION_COLLIDABLE_RLE_FORWARD__
#define __INTERPOLATION_COLLIDABLE_RLE_FORWARD__
#include <PhysBAM_Tools/Grids_RLE_Interpolation/INTERPOLATION_RLE_FORWARD.h>
#include <PhysBAM_Tools/Interpolation/INTERPOLATION_FORWARD.h>
namespace PhysBAM{
template<class T_GRID,class T_NESTED_LOOKUP=FACE_LOOKUP_RLE<T_GRID> > class FACE_LOOKUP_COLLIDABLE_RLE;
template<class T_GRID,class T_FACE_LOOKUP> class AVERAGING_COLLIDABLE_RLE;
template<class T_GRID,class T2> class LINEAR_INTERPOLATION_COLLIDABLE_CELL_RLE;
template<class T_GRID,class T2,class T_FACE_LOOKUP=FACE_LOOKUP_COLLIDABLE_RLE<T_GRID> > class LINEAR_INTERPOLATION_COLLIDABLE_FACE_RLE;
}
#endif
#endif
|
[
"quhang@stanford.edu"
] |
quhang@stanford.edu
|
a15605bf20e0d8b3a47fe073f37e340d077080c7
|
fa083621ffabe3579dbb622323d6d1668da2e531
|
/AtCoder/ABC/126/abc126_d.cpp
|
74dafd88d35448cf17e2bb12e43d8432da01033a
|
[] |
no_license
|
y-meguro/competitive-programming
|
0dc7e0338332d3b17915f41136f744bff5e39965
|
dbe4a51fd4d88e6ccc80ae0c41098f844783bd23
|
refs/heads/master
| 2020-12-21T12:02:08.210193
| 2020-10-06T13:26:02
| 2020-10-06T13:26:02
| 236,424,669
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 733
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int>>> tree;
vector<int> col;
void dfs(int current, int c) {
col.at(current) = c;
for (pair<int, int> e : tree.at(current)) {
int to = e.first;
if (col.at(to) != -1) continue;
int dist = e.second;
if (dist % 2 == 0) {
dfs(to, c);
} else {
dfs(to, 1 - c);
}
}
}
int main() {
int N;
cin >> N;
tree.resize(N);
col.resize(N, -1);
for (int i = 0; i < N - 1; i++) {
int u, v, w;
cin >> u >> v >> w;
u--;
v--;
tree.at(u).push_back(make_pair(v, w));
tree.at(v).push_back(make_pair(u, w));
}
dfs(0, 0);
for (int i = 0; i < N; i++) {
cout << col.at(i) << endl;
}
return 0;
}
|
[
"y.meguro.2008@gmail.com"
] |
y.meguro.2008@gmail.com
|
cec99c0e5c2759468dad70bdb018beb29cb20425
|
d73eb9e6b9450f5456d92c710c457fb36bbe8d59
|
/cdcResource/AnimationSection.cpp
|
8313c67cd7b52e69e12fd9a26923bc81fc530660
|
[] |
no_license
|
rrika/cdcEngineDXHR
|
110cb9314f242e0cfe07c51d439da1045aec78a0
|
ff312d19663ca1f68881b46089c4a856c2ced0f5
|
refs/heads/main
| 2023-08-31T05:09:34.118694
| 2023-08-30T23:49:39
| 2023-08-30T23:49:39
| 474,729,623
| 192
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 30
|
cpp
|
#include "AnimationSection.h"
|
[
"adam.jensen@si.det.usa"
] |
adam.jensen@si.det.usa
|
bd9cf15be4453e200dfc6914c7f8241c51974303
|
90d39aa2f36783b89a17e0687980b1139b6c71ce
|
/SPOJ/CPRMT.cpp
|
b5b29729c8b7d5580095700a1d9a06f01fbe397e
|
[] |
no_license
|
nims11/coding
|
634983b21ad98694ef9badf56ec8dfc950f33539
|
390d64aff1f0149e740629c64e1d00cd5fb59042
|
refs/heads/master
| 2021-03-22T08:15:29.770903
| 2018-05-28T23:27:37
| 2018-05-28T23:27:37
| 247,346,971
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 578
|
cpp
|
/*
* Problem is to find the common characters between the two strings and print them alphabetically
*/
#include<cstdio>
int main()
{
char a[1001],b[1001];
while(scanf("%s%s",a,b)!=EOF)
{
int counta[26]={0};
int countb[26]={0};
for(int i=0;a[i]!=0;i++)
counta[a[i]-'a']++;
for(int i=0;b[i]!=0;i++)
countb[b[i]-'a']++;
for(int i=0;i<26;i++)
{
int lt=counta[i]>countb[i]?countb[i]:counta[i];
while(lt--)
printf("%c",i+'a');
}
printf("\n");
}
}
|
[
"nimeshghelani@gmail.com"
] |
nimeshghelani@gmail.com
|
970e3aae7c221b4646781998e895c2fdc9269f62
|
58dab5e6ab12f43dd8352176081e5b2a656ed6bb
|
/src/accumulatormap.h
|
ace0392859b350db0cdf178fcab21d3f27351ce3
|
[
"MIT"
] |
permissive
|
designcoinled/DesignCoin
|
7b591fbdbff46f9e1c6509d809c2e3ed1cf5c0fb
|
f77ff26cef2e5a2e8b133456fcadb0295058e22a
|
refs/heads/master
| 2020-04-05T09:01:33.577918
| 2018-11-08T17:28:05
| 2018-11-08T17:28:05
| 156,739,202
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 787
|
h
|
// Copyright (c) 2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SIGN_ACCUMULATORMAP_H
#define SIGN_ACCUMULATORMAP_H
#include "libzerocoin/Accumulator.h"
#include "libzerocoin/Coin.h"
//A map with an accumulator for each denomination
class AccumulatorMap
{
private:
std::map<libzerocoin::CoinDenomination, std::unique_ptr<libzerocoin::Accumulator> > mapAccumulators;
public:
AccumulatorMap();
bool Load(uint256 nCheckpoint);
bool Accumulate(libzerocoin::PublicCoin pubCoin, bool fSkipValidation = false);
CBigNum GetValue(libzerocoin::CoinDenomination denom);
uint256 GetCheckpoint();
void Reset();
};
#endif //SIGN_ACCUMULATORMAP_H
|
[
"Soytannoob809@gmail.com"
] |
Soytannoob809@gmail.com
|
82798ad21f8bdfe98f84c654609f6d63fd21fc02
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/admin/wmi/wbem/winmgmt/esscomp/timeprov/dnf.h
|
cf2de1e4f04fe1e0c9d020312158a26f657f48d5
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 1,759
|
h
|
#include <parmdefs.h>
#include <ql.h>
#include <sync.h>
#include <limits.h>
#include <sortarr.h>
#ifndef __WBEM_EVALUTAION_TREE__H_
#define __WBEM_EVALUTAION_TREE__H_
class CConjunction
{
protected:
CUniquePointerArray<QL_LEVEL_1_TOKEN> m_apTokens;
public:
CConjunction(QL_LEVEL_1_TOKEN& Token, BOOL bNegate);
CConjunction(CConjunction& Other);
CConjunction(CConjunction& Other1, CConjunction& Other2);
long GetNumTokens() {return m_apTokens.GetSize();}
INTERNAL QL_LEVEL_1_TOKEN* GetTokenAt(int nIndex)
{return m_apTokens[nIndex];}
void AddToken(ACQUIRE QL_LEVEL_1_TOKEN* pNew)
{m_apTokens.Add(pNew);}
// HRESULT BuildTree(CContextMetaData* pNamespace,
// CImplicationList& Implications,
// CEvalNode** ppRes);
void Sort();
static int NegateOperator(int nOperator);
};
class CDNFExpression
{
protected:
CUniquePointerArray<CConjunction> m_apTerms;
protected:
void CreateFromToken(QL_LEVEL_1_TOKEN& Token, BOOL bNegate = FALSE);
void CreateOr(CDNFExpression& Arg1, CDNFExpression& Arg2);
void CreateAnd(CDNFExpression& Arg1, CDNFExpression& Arg2);
public:
long GetNumTerms() {return m_apTerms.GetSize();}
INTERNAL CConjunction* GetTermAt(int nIndex)
{return m_apTerms[nIndex];}
void AddTerm(ACQUIRE CConjunction* pNew)
{m_apTerms.Add(pNew);}
// HRESULT BuildTree(CContextMetaData* pNamespace,
// CImplicationList& Implications,
// CEvalNode** ppRes);
void CreateFromTokens(QL_LEVEL_1_TOKEN*& pLastToken, BOOL bNegate = FALSE);
void Sort();
};
#endif
|
[
"seta7D5@protonmail.com"
] |
seta7D5@protonmail.com
|
69c99b2698c12bcb9495fa1fba303dfabcd8a5a7
|
770056a788b1478f977b79648f16fe4219816768
|
/src/qt/askpassphrasedialog.h
|
87d2409da33451a4451dfe4360ba2e3141e9f134
|
[
"MIT"
] |
permissive
|
StipendClassic/spdz
|
4356334f685c21f4388e2972254abf33f0fcb06f
|
27c30658982d8f5ade462902a2ae0ce40b98c507
|
refs/heads/master
| 2020-03-19T02:15:46.286346
| 2018-05-31T19:20:32
| 2018-05-31T19:20:32
| 135,613,310
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,222
|
h
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2018 The SPDZ developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_ASKPASSPHRASEDIALOG_H
#define BITCOIN_QT_ASKPASSPHRASEDIALOG_H
#include <QDialog>
class WalletModel;
namespace Ui
{
class AskPassphraseDialog;
}
/** Multifunctional dialog to ask for passphrases. Used for encryption, unlocking, and changing the passphrase.
*/
class AskPassphraseDialog : public QDialog
{
Q_OBJECT
public:
enum class Mode {
Encrypt, /**< Ask passphrase twice and encrypt */
UnlockAnonymize, /**< Ask passphrase and unlock only for anonymization */
Unlock, /**< Ask passphrase and unlock */
ChangePass, /**< Ask old passphrase + new passphrase twice */
Decrypt /**< Ask passphrase and decrypt wallet */
};
// Context from where / for what the passphrase dialog was called to set the status of the checkbox
// Partly redundant to Mode above, but offers more flexibility for future enhancements
enum class Context {
Unlock_Menu, /** Unlock wallet from menu */
Unlock_Full, /** Wallet needs to be fully unlocked */
Encrypt, /** Encrypt unencrypted wallet */
ToggleLock, /** Toggle wallet lock state */
ChangePass, /** Change passphrase */
Send_SPDZ, /** Send SPDZ */
Send_zSPDZ, /** Send zSPDZ */
Mint_zSPDZ, /** Mint zSPDZ */
BIP_38, /** BIP38 menu */
Multi_Sig, /** Multi-Signature dialog */
Sign_Message /** Sign/verify message dialog */
};
explicit AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context);
~AskPassphraseDialog();
void accept();
private:
Ui::AskPassphraseDialog* ui;
Mode mode;
WalletModel* model;
Context context;
bool fCapsLock;
private slots:
void textChanged();
protected:
bool event(QEvent* event);
bool eventFilter(QObject* object, QEvent* event);
};
#endif // BITCOIN_QT_ASKPASSPHRASEDIALOG_H
|
[
"paul.brooks2091@gmail.com"
] |
paul.brooks2091@gmail.com
|
d52b818dc98987da4746d13e3c491fe0c041ab00
|
3a81e856e3a7dcae8ab88085fb228920d1acbaf3
|
/fsfd.cpp
|
38fe763c50bd64b2024f0907716d5ea3301678ae
|
[] |
no_license
|
michaelxuzhi/2016-5.3
|
d171a224638e85eb7d78a8d908bf6cb85472f959
|
00fc271b8ffab41d549edf5468dc7e392df27a12
|
refs/heads/master
| 2020-03-30T00:25:22.863504
| 2018-09-27T03:19:59
| 2018-09-27T03:19:59
| 150,520,283
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 531
|
cpp
|
#include <iostream.h>
int main()
{
int x,y,d,m=31,n=30,l=28;
cin>>x>>y; //x表示月y表示年
switch(x)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
cout<<"当月天数="<<m<<endl;
break;
case 4:
case 6:
case 9:
case 11:
cout<<"当月天数="<<n<<endl;
break;
}
if(y%4==0&&y%100!=0||y%400==0&&x==2)
{
d=29;
cout<<"这一年的二月份天数="<<d<<endl;
}
else {
d=28;
cout<<"这一年的二月份天数="<<d<<endl;
}
return (d);
}
|
[
"noreply@github.com"
] |
michaelxuzhi.noreply@github.com
|
a4c94b1584b129852fa2f0e1689784caac8f2267
|
124167abc99747fbcb95960940e6968c6c556bb8
|
/include/jkl/util/lambda.hpp
|
720bcf983aaf28eedfa5f89d13560053d8b849aa
|
[
"MIT"
] |
permissive
|
feverzsj/jkl
|
c62fe0122fb2bb75f4a2034b2b4a67fdef2ce81f
|
1ea32ff2495120cc901d29a9c351154ca1f565e4
|
refs/heads/master
| 2023-02-15T12:06:42.214564
| 2021-01-15T03:31:25
| 2021-01-15T03:31:25
| 301,203,569
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,611
|
hpp
|
#pragma once
#include <tuple>
#include <type_traits>
namespace jkl::lambda_placeholders{
template<size_t N>
struct holder{ static constexpr size_t value = N; };
constexpr auto _1 = holder<0>{};
constexpr auto _2 = holder<1>{};
constexpr auto _3 = holder<2>{};
constexpr auto _4 = holder<3>{};
constexpr auto _5 = holder<4>{};
constexpr auto _6 = holder<5>{};
constexpr auto _ = _1;
// NOTE: all the op should be const
template<class F>
struct lambda_holder
{
F f;
constexpr explicit lambda_holder(F&& t) : f(std::move(t)) {}
constexpr explicit lambda_holder(F const& t) : f(t) {}
template<class...A>
constexpr decltype(auto) operator()(A&&... a) const
{
auto t = std::forward_as_tuple(std::forward<A>(a)...);
return f(t);
}
template<class Tuple>
constexpr decltype(auto) apply(Tuple&& args) const
{
return f(std::forward<Tuple>(args));
}
};
#define _JKL_LAMBDA_PLACEHOLDER_UNARY_OP(OP) \
template<size_t I> \
constexpr auto operator OP (holder<I>) \
{ \
return lambda_holder([](auto& args) -> decltype(auto) \
{ \
return OP std::get<I>(args); \
}); \
} \
\
template<class F> \
constexpr auto operator OP (lambda_holder<F> const& h) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return OP h.apply(args); \
}); \
} \
/**/
#define _JKL_LAMBDA_PLACEHOLDER_BINARY_OP(OP) \
template<class Q, size_t I> \
constexpr auto operator OP (Q const& q, holder<I>) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return q OP std::get<I>(args); \
}); \
} \
\
template<size_t I, class Q> \
constexpr auto operator OP (holder<I>, Q const& q) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return std::get<I>(args) OP q; \
}); \
} \
\
template<size_t I, size_t J> \
constexpr auto operator OP (holder<I>, holder<J>) \
{ \
return lambda_holder([](auto& args) -> decltype(auto) \
{ \
return std::get<I>(args) OP std::get<J>(args); \
}); \
} \
\
template<class Q, class F> \
constexpr auto operator OP (Q const& q, lambda_holder<F> const& h) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return q OP h.apply(args); \
}); \
} \
\
template<class F, class Q> \
constexpr auto operator OP (lambda_holder<F> const& h, Q const& q) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return h.apply(args) OP q; \
}); \
} \
\
template<size_t I, class F> \
constexpr auto operator OP (holder<I>, lambda_holder<F> const& h) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return std::get<I>(args) OP h.apply(args); \
}); \
} \
\
template<class F, size_t I> \
constexpr auto operator OP (lambda_holder<F> const& h, holder<I>) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return h.apply(args) OP std::get<I>(args); \
}); \
} \
\
template<class F, class E> \
constexpr auto operator OP (lambda_holder<F> const& h, lambda_holder<E> const& g) \
{ \
return lambda_holder([&](auto& args) -> decltype(auto) \
{ \
return h.apply(args) OP g.apply(args); \
}); \
} \
/**/
// Arithmetic
_JKL_LAMBDA_PLACEHOLDER_UNARY_OP (+)
_JKL_LAMBDA_PLACEHOLDER_UNARY_OP (-)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(+)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(-)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(*)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(/)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(%)
// Bitwise
_JKL_LAMBDA_PLACEHOLDER_UNARY_OP ( ~)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP( &)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP( |)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP( ^)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(<<)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(>>)
// Comparison
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(==)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(!=)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(< )
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(<=)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(> )
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(>=)
// Logical
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(||)
_JKL_LAMBDA_PLACEHOLDER_BINARY_OP(&&)
_JKL_LAMBDA_PLACEHOLDER_UNARY_OP (! )
// Member access (array subscript is a member function)
_JKL_LAMBDA_PLACEHOLDER_UNARY_OP(*)
// Other (function call is a member function)
#undef _JKL_LAMBDA_PLACEHOLDER_UNARY_OP
#undef _JKL_LAMBDA_PLACEHOLDER_BINARY_OP
} // namespace jkl::lambda_placeholders
|
[
"feverzsj@hotmail.com"
] |
feverzsj@hotmail.com
|
769b5198237e2238897947a121900c98b3c31ff0
|
855b36038b837ef1283b42aa8231920636a12013
|
/mic2.ino
|
65b57359b7d24021695cee4ffd0aea8a771ba168
|
[] |
no_license
|
ngonhu159/mic_recognize
|
76f3a65e161769abc7456f53e2c5cfa4773dcd52
|
a4e4940cd34b83c8a3592f6999897d6b3ad35fae
|
refs/heads/master
| 2020-04-08T20:01:27.932536
| 2018-11-30T01:59:25
| 2018-11-30T01:59:25
| 159,681,007
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,636
|
ino
|
const int sampleWindow = 15; // lấy mẫu 50ms (50 mS = 20Hz)
unsigned int sample;
int i_sample=0;
int count_threshold_dapBan=0;
int count_threshold_het=0;
#define count_dapBan 1
#define count_het 4
#define threshold_dapBan 520
#define threshold_het 450
#define time_delay 2000 /* thời gian delay */
void setup()
{
Serial.begin(9600);
}
void loop()
{
unsigned long startMillis= millis();
unsigned int peakToPeak = 0;
unsigned int signalMax = 0;
unsigned int signalMin = 1024;
// collect data for 50 mS
while (millis() - startMillis < sampleWindow)
{
sample = analogRead(A1);
if (sample < 1024)
{
if (sample > signalMax)
{
signalMax = sample; // lưu lại giá trị max
}
else if (sample < signalMin)
{
signalMin = sample; // lưu lại giá trị min
}
}
}
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
if (i_sample>=10) {
if (count_threshold_het>=count_het) {
Serial.println("tieng het");
delay(time_delay);
}
else if (count_threshold_dapBan>=2 && count_threshold_dapBan<=3) {
startMillis= millis();
peakToPeak = 0;
signalMax = 0;
signalMin = 1024;
while (millis() - startMillis < sampleWindow)
{
sample = analogRead(A1);
if (sample < 1024)
{
if (sample > signalMax)
{
signalMax = sample; // lưu lại giá trị max
}
else if (sample < signalMin)
{
signalMin = sample; // lưu lại giá trị min
}
}
}
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
if (peakToPeak>350){
Serial.println("tieng het");
delay(time_delay);
} else {
Serial.println("Dap ban");
delay(time_delay);
}
}
i_sample=0;
count_threshold_het=0;
count_threshold_dapBan=0;
return;
}
if (peakToPeak >= threshold_het) {
count_threshold_het++;
if (peakToPeak >= threshold_dapBan) {
count_threshold_dapBan++;
}
}
i_sample++;
}
|
[
"noreply@github.com"
] |
ngonhu159.noreply@github.com
|
aee8ef0b67ede2915560c4b2c1bc3f18ec7ca75c
|
88636ec6b098142931caa02740db0fae4a0e0dcb
|
/api/api_athena/src/utests/test_coint.cpp
|
ec78f813cb99e070a3e2aff8acbea89c28756ca8
|
[] |
no_license
|
xibaomo/athena
|
6b8464b67a43b765f8b0c0794ecaea43d94d266f
|
8e28814670dc2d0af06956e906bf60f68e0a23d4
|
refs/heads/master
| 2023-08-22T20:20:25.996064
| 2023-08-15T12:06:42
| 2023-08-15T12:06:42
| 147,918,903
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 390
|
cpp
|
#include "basics/utils.h"
#include "basics/types.h"
#include <vector>
#define N 100
using namespace std;
using namespace athena;
int main() {
PyEnviron::getInstance();
vector<real64> v1;
vector<real64> v2;
for (int i=0; i < N; i++) {
v1.push_back(i*.1);
v2.push_back(i*i*0.2+1);
}
double r = testADF(&v1[0],N);
cout<<r<<endl;
return 0;
}
|
[
"fxua@gmail.com"
] |
fxua@gmail.com
|
a963f4661bd33b6106d18bcfac73f8b9b7803b83
|
1dae79fb96f0dbbd03104eac106285e1aef88197
|
/Compiler Theory/PascalParser/TK_Array/TK_Array.cpp
|
3e59dc926ec16a813d3326d94abec12f7b393b7e
|
[
"Apache-2.0"
] |
permissive
|
ilyacoding/bsuir
|
781e8f126d1f7d2db402b9d8083d1f4bcdcc6f4e
|
c1a09b63d5d66a3dc0f4545589608a18d1b5d9c9
|
refs/heads/master
| 2021-05-15T04:23:26.430221
| 2019-05-29T04:06:12
| 2019-05-29T04:06:12
| 75,403,020
| 0
| 0
|
Apache-2.0
| 2021-04-21T19:34:52
| 2016-12-02T14:35:01
|
Objective-C
|
WINDOWS-1251
|
C++
| false
| false
| 14,688
|
cpp
|
// TK_Array.cpp : Defines the entry point for the console application.
//
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include "iostream"
#include "fstream"
#include "string"
#include "vector"
#include <algorithm>
#include <functional>
#include <sstream>
#include <cctype>
#include <locale>
#include <iostream>
#include <iomanip>
#include "boost/algorithm/string.hpp"
using namespace std;
enum TOKEN {
PROGRAM_DESC,
PROGRAM_NAME,
ID_LIST,
PROGRAM_HEADER,
DEFINE_BLOCK,
OPERATOR_BLOCK,
EXPRESSION,
EXPRESSION_LIST,
PROGRAM,
USES,
VAR,
CONST,
BEGIN,
END,
TYPE,
ID,
OPERATOR,
DELIMETER,
OPEN_BRACKET,
CLOSE_BRACKET,
E
};
struct lexem {
lexem(char* str, TOKEN tk) : s(str), tok(tk) {}
lexem(TOKEN tk) : tok(tk) {}
char* s;
TOKEN tok;
};
vector<string> TYPES, lexems, l;
vector<lexem> tokens;
string TokenToStr(TOKEN tok)
{
switch (tok)
{
/* PROGRAM_DESC,
PROGRAM_HEADER,
DEFINE_BLOCK,
OPERATOR_BLOCK,*/
case ID_LIST:
return "ID_LIST";
break;
case PROGRAM_NAME:
return "PROGRAM_NAME";
break;
case PROGRAM_DESC:
return "PROGRAM_DESC";
break;
case PROGRAM_HEADER:
return "PROGRAM_HEADER";
break;
case DEFINE_BLOCK:
return "DEFINE_BLOCK";
break;
case OPERATOR_BLOCK:
return "OPERATOR_BLOCK";
break;
case PROGRAM:
return "PROGRAM";
break;
case USES:
return "USES";
break;
case VAR:
return "VAR";
break;
case CONST:
return "CONST";
break;
case BEGIN:
return "BEGIN";
break;
case END:
return "END";
break;
case TYPE:
return "TYPE";
break;
case ID:
return "ID";
break;
case OPERATOR:
return "OPERATOR";
break;
case DELIMETER:
return "DELIMETER";
break;
case OPEN_BRACKET:
return "OPEN_BRACKET";
break;
case CLOSE_BRACKET:
return "CLOSE_BRACKET";
break;
case EXPRESSION_LIST:
return "EXPRESSION_LIST";
break;
case EXPRESSION:
return "EXPRESSION";
break;
case E:
return "E";
break;
default:
return "";
break;
}
}
bool IsTerminal(lexem tok)
{
switch (tok.tok)
{
case PROGRAM:
case PROGRAM_DESC:
case PROGRAM_HEADER:
case DEFINE_BLOCK:
case OPERATOR_BLOCK:
case ID_LIST:
case EXPRESSION:
case EXPRESSION_LIST:
return false;
break;
default:
return true;
break;
}
}
// ------------------------------------------------------------------------
struct Tree {
lexem term;
Tree* Left;
Tree* Center;
Tree* Right;
};
void InitTree(Tree* & head, lexem t) {
head = (Tree*)malloc(sizeof(Tree));
head->term = t;
head->Left = NULL;
head->Right = NULL;
head->Center = NULL;
}
void AddLeft(Tree* & head, lexem t)
{
InitTree(head->Left, t);
}
void AddCenter(Tree* & head, lexem t)
{
InitTree(head->Center, t);
}
void AddRight(Tree* & head, lexem t)
{
InitTree(head->Right, t);
}
void ProbPrint(Tree* & head, int n)
{
if (head != NULL) {
for (int i = 0; i < n; i++) printf(" ");
if (!IsTerminal(head->term)) {
cout << TokenToStr(head->term.tok) << endl;
}
else {
cout << TokenToStr(head->term.tok) << endl;
for (int i = 0; i < n + 2; i++) printf(" ");
printf("-> %s \n", head->term.s);
}
ProbPrint(head->Left, n + 2);
ProbPrint(head->Center, n + 2);
ProbPrint(head->Right, n + 2);
}
}
void Init()
{
TYPES.push_back("integer");
TYPES.push_back("byte");
TYPES.push_back("word");
TYPES.push_back("shortint");
TYPES.push_back("longint");
TYPES.push_back("real");
TYPES.push_back("single");
TYPES.push_back("double");
TYPES.push_back("extended");
TYPES.push_back("boolean");
TYPES.push_back("char");
}
bool is_digits(const std::string &str)
{
return str.find_first_not_of("0123456789") == std::string::npos;
}
bool isValidVar(string str)
{
if (!isalpha(str[0]) && (str[0] != '_')) return false;
for (int i = 0; i < str.length(); i++)
{
if (!isalnum(str[i]) && (str[0] != '_')) return false;
}
return true;
}
bool isValidType(vector<string> gotLex)
{
bool IsArray = true;
vector<string> newLex;
for (int i = 0; i < TYPES.size(); i++)
if (TYPES[i] == gotLex[0])
IsArray = false;
if (IsArray) {
int k = 1;
while ((gotLex[k] != "of") && (k < gotLex.size() - 1))
if (gotLex[k] == "array")
return false;
else
k++;
if (k == gotLex.size() - 1) return false;
// Get new type
for (int i = k + 1; i < gotLex.size(); i++)
newLex.push_back(gotLex[i]);
return isValidType(newLex);
}
else {
if (gotLex.size() == 1)
return true;
else
return false;
}
}
vector<string> GetStrLexems(string str)
{
string buf = "";
boost::algorithm::trim(str);
vector<string> lexems;
for (int j = 0; j < str.length(); j++)
{ /*|| (str[j] == '.' && is_digits(buf))*/
while ((isalpha(str[j]) || (str[j] == '.' && (buf == ".")) || (str[j] == '_') || isdigit(str[j])) && str[j] != ';' && (j < str.length())) buf += str[j++];
if (buf.length() > 0) {
boost::algorithm::trim(buf);
lexems.push_back(buf);
buf = "";
}
if (str[j] == ';') {
lexems.push_back(";");
j++;
}
while ((!isspace(str[j]) && !isalpha(str[j]) && !isdigit(str[j])) && str[j] != ';' && (j < str.length())) buf += str[j++];
if (buf.length() > 0) {
boost::algorithm::trim(buf);
lexems.push_back(buf);
buf = "";
}
if (str[j] == ';') {
lexems.push_back(";");
j++;
}
if (isalpha(str[j]) || isdigit(str[j])) j--;
}
return lexems;
}
bool ParseTokens(vector<string> lex)
{
for (int i = 0; i < lex.size(); i++)
{
char* cstr = new char[lex[i].length() + 1];
strcpy(cstr, lex[i].c_str());
if (lex[i] == "program")
tokens.push_back(lexem(cstr, PROGRAM));
else if (lex[i] == "begin")
tokens.push_back(lexem(cstr, BEGIN));
else if (lex[i] == "end")
tokens.push_back(lexem(cstr, END));
else if(lex[i] == "uses")
tokens.push_back(lexem(cstr, USES));
else if (lex[i] == "var")
tokens.push_back(lexem(cstr, VAR));
else if (lex[i] == "integer" || lex[i] == "real" || lex[i] == "int64")
tokens.push_back(lexem(cstr, TYPE));
else if (lex[i] == "+" || lex[i] == "-" || lex[i] == "*" || lex[i] == "/" || lex[i] == ":=" || lex[i] == ";" || lex[i] == "=")
tokens.push_back(lexem(cstr, OPERATOR));
else if (lex[i] == "." || lex[i] == "," || lex[i] == ":")
tokens.push_back(lexem(cstr, DELIMETER));
else if (isValidVar(lex[i]))
tokens.push_back(lexem(cstr, ID));
else if (lex[i] == "(")
tokens.push_back(lexem(lex[i], OPEN_BRACKET));
else if (lex[i] == ")")
tokens.push_back(lexem(lex[i], CLOSE_BRACKET));
else if (is_digits(lex[i]))
tokens.push_back(lexem(cstr, CONST));
else {
cout << "Unknown symbol: " << lex[i] << endl;
return false;
}
}
return true;
}
int main()
{
setlocale(LC_ALL, "rus");
Init();
ifstream file;
string s;
vector <string> v;
Tree* tree;
char buf[500];
file.open("file/file.txt", ios_base::in);
file.imbue(std::locale(""));
while (!file.eof()) {
file.getline(buf, 500);
v.push_back(buf);
}
for (int i = 0; i < v.size(); i++)
{
auto x = GetStrLexems(boost::algorithm::to_lower_copy(v[i]));
for (int j = 0; j < x.size(); j++)
l.push_back(x[j]);
}
file.close();
cout << "Parsed text:" << endl;
for (int i = 0; i < l.size(); i++)
{
cout << l[i];
if (i < l.size() - 1) cout << "_";
}
cout << endl << endl << "Starting to parse lexems:" << endl;
if (!ParseTokens(l))
{
cout << "Lexical error." << endl;
cout << endl << endl;
system("pause");
return 0;
}
for (int i = 0; i < tokens.size(); i++)
{
printf("Lexem: %s %s \n", tokens[i].s, TokenToStr(tokens[i].tok).c_str());
}
cout << endl;
InitTree(tree, lexem("program", PROGRAM));
cout << endl << endl << "#=> Дерево: " << endl << endl;
ProbPrint(tree, 0);
cout << endl << endl;
while (tokens.size() > 0)
{
if (tokens[0].tok == PROGRAM)
{
int i = 0;
vector<lexem> s;
while (tokens[i].tok != OPERATOR && i < tokens.size() - 1)
{
s.push_back(tokens[i]);
tokens.erase(tokens.begin());
}
s.push_back(tokens[i]);
tokens.erase(tokens.begin());
/*for (int i = 0; i < s.size(); i++)
{
printf("Lexem2: %s %s \n", s[i].s, TokenToStr(s[i].tok).c_str());
}*/
if (s.size() < 3)
{
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
if (isValidVar(s[i].s) && !strcmp(s[2].s, ";"))
{
AddLeft(tree, lexem("", PROGRAM_HEADER));
AddLeft(tree->Left, lexem("program", PROGRAM_NAME));
AddCenter(tree->Left, lexem(s[1].s, ID));
}
else {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
cout << endl << endl << "#=> Дерево: " << endl << endl;
ProbPrint(tree, 0);
cout << endl;
for (int i = 0; i < tokens.size(); i++)
{
printf("Lexem: %s %s \n", tokens[i].s, TokenToStr(tokens[i].tok).c_str());
}
cout << endl;
}
cout << endl;
if (tokens[0].tok == VAR)
{
int i = 0;
vector<lexem> s;
while (strcmp(tokens[i].s, ";") && i < tokens.size() - 1)
{
s.push_back(tokens[i]);
tokens.erase(tokens.begin());
}
s.push_back(tokens[i]);
tokens.erase(tokens.begin());
/*for (int i = 0; i < s.size(); i++)
{
printf("Lexem3: %s %s \n", s[i].s, TokenToStr(s[i].tok).c_str());
}*/
vector<string> type;
vector<lexem> ids;
string Stype = "";
int j = 0;
while (strcmp(s[j].s, ":") && j < s.size() - 1) j++;
for (int k = 0; k < j && k < s.size(); k++)
if (s[k].tok == ID)
ids.push_back(s[k]);
for (int k = j + 1; k < s.size() - 1; k++)
type.push_back(s[k].s);
for (int i = 0; i < type.size(); i++)
Stype += type[i] + " ";
char* cstr = new char[Stype.length() + 1];
strcpy(cstr, Stype.c_str());
if (isValidType(type) && !strcmp(s[s.size() - 1].s, ";"))
{
AddCenter(tree, lexem("", DEFINE_BLOCK));
AddLeft(tree->Center, lexem("var", VAR));
AddCenter(tree->Center, lexem("", ID_LIST));
if (ids.size() < 4)
{
if (ids.size() == 1)
{
AddLeft(tree->Center->Center, ids[0]);
} else if (ids.size() == 2)
{
AddLeft(tree->Center->Center, ids[0]);
AddCenter(tree->Center->Center, ids[1]);
} else if (ids.size() == 3)
{
AddLeft(tree->Center->Center, ids[0]);
AddCenter(tree->Center->Center, ids[1]);
AddRight(tree->Center->Center, ids[2]);
}
}
AddRight(tree->Center, lexem(cstr, TYPE));
} else {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
cout << endl << endl << "#=> Дерево: " << endl << endl;
ProbPrint(tree, 0);
cout << endl;
for (int i = 0; i < tokens.size(); i++)
{
printf("Lexem: %s %s \n", tokens[i].s, TokenToStr(tokens[i].tok).c_str());
}
cout << endl;
}
cout << endl;
if (tokens[0].tok == BEGIN)
{
tokens.erase(tokens.begin());
if (strcmp(tokens[tokens.size() - 1].s, ".") || tokens[tokens.size() - 2].tok != END)
{
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
tokens.erase(tokens.begin() + tokens.size() - 1);
tokens.erase(tokens.begin() + tokens.size() - 1);
// deleted mycor
/*for (int i = 0; i < tokens.size(); i++)
{
printf("Lexem4: %s %s \n", tokens[i].s, TokenToStr(tokens[i].tok).c_str());
}*/
AddRight(tree, lexem("", PROGRAM_DESC));
while (tokens.size() > 0)
{
vector<lexem> l;
while (strcmp(tokens[0].s, ";"))
{
l.push_back(tokens[0]);
tokens.erase(tokens.begin());
}
tokens.erase(tokens.begin());
/*for (int i = 0; i < l.size(); i++)
{
printf("Lexem5: %s %s \n", l[i].s, TokenToStr(l[i].tok).c_str());
}*/
if (l.size() < 3)
{
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
if (tree->Right->Left) {
if (tree->Right->Center) {
AddRight(tree->Right, EXPRESSION);
if (l[1].tok == OPERATOR)
{
AddLeft(tree->Right->Right, lexem(l[0].s, ID));
AddCenter(tree->Right->Right, lexem(l[1].s, OPERATOR));
AddRight(tree->Right->Right, EXPRESSION);
l.erase(l.begin());
l.erase(l.begin());
if (l.size() == 1) {
AddLeft(tree->Right->Right->Right, l[0]);
}
else if (l.size() == 2) {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
else if (l.size() == 3) {
AddLeft(tree->Right->Right->Right, l[0]);
AddCenter(tree->Right->Right->Right, l[1]);
AddRight(tree->Right->Right->Right, l[2]);
}
}
} else {
AddCenter(tree->Right, EXPRESSION);
if (l[1].tok == OPERATOR)
{
AddLeft(tree->Right->Center, lexem(l[0].s, ID));
AddCenter(tree->Right->Center, lexem(l[1].s, OPERATOR));
AddRight(tree->Right->Center, EXPRESSION);
l.erase(l.begin());
l.erase(l.begin());
if (l.size() == 1) {
AddLeft(tree->Right->Center->Right, l[0]);
}
else if (l.size() == 2) {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
else if (l.size() == 3) {
AddLeft(tree->Right->Center->Right, l[0]);
AddCenter(tree->Right->Center->Right, l[1]);
AddRight(tree->Right->Center->Right, l[2]);
}
} else {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
}
} else {
AddLeft(tree->Right, EXPRESSION);
if (l[1].tok == OPERATOR)
{
AddLeft(tree->Right->Left, lexem(l[0].s, ID));
AddCenter(tree->Right->Left, lexem(l[1].s, OPERATOR));
AddRight(tree->Right->Left, EXPRESSION);
l.erase(l.begin());
l.erase(l.begin());
if (l.size() == 1) {
AddLeft(tree->Right->Left->Right, l[0]);
} else if (l.size() == 2) {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
} else if (l.size() == 3) {
AddLeft(tree->Right->Left->Right, l[0]);
AddCenter(tree->Right->Left->Right, l[1]);
AddRight(tree->Right->Left->Right, l[2]);
}
}
}
}
cout << endl << endl << "#=> Дерево: " << endl << endl;
ProbPrint(tree, 0);
cout << endl;
for (int i = 0; i < tokens.size(); i++)
{
printf("Lexem: %s %s \n", tokens[i].s, TokenToStr(tokens[i].tok).c_str());
}
cout << endl;
}
if (tokens.size() > 0)
if (tokens[0].tok == ID) {
cout << "Parser error.";
cout << endl << endl;
system("pause");
return 0;
}
}
cout << endl << endl << "###=> Результирующее дерево: " << endl << endl;
ProbPrint(tree, 0);
cout << endl << endl;
system("pause");
return 0;
}
|
[
"ilyacoding@yandex.com"
] |
ilyacoding@yandex.com
|
9560be08eb09dc333900e0af4c9530360bbeae4d
|
810ff30662ef6ceb2d8a60b62bb9f3e6b565e466
|
/code-network/igwb/com/cdrstat/cdr_stat_svr.h
|
90d7e096770a87541c3653980be219fbf207c8a3
|
[] |
no_license
|
y35777/abcd
|
9e551d26a0c9128e3f02f61bd2f9c24415a4df67
|
77d71ae93103cbf39c1a77148367de0f21860bc4
|
refs/heads/main
| 2023-05-28T12:26:02.436874
| 2021-06-06T13:01:50
| 2021-06-06T13:01:50
| 361,348,921
| 0
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,209
|
h
|
#ifndef __CDR_STAT_SVR_H__
#define __CDR_STAT_SVR_H__
#include "../include/toolbox.h"
#include "../include/frame.h"
#include "../utility/mml_para.h"
#include "stat_cfg_info.h"
#ifdef _PLATFORM_WIN32
#pragma warning(disable:4503)
#endif
class CCDRStatCfgMgr;
class CCDRStatRstMgr;
class CCDRStatTask;
class CQBMMLReport;
class CCDRStatSvr : public CWorkModule
{
public:
//构造函数
CCDRStatSvr();
//析构函数
virtual ~CCDRStatSvr();
//获取指定目录下面的所有话单文件名称
static int GetBillFiles(const char* szPath, LIST<STRING>& qResult);
static void SetParaInfoContentList(STRING sAPName, INFO_LIST ContentList);
protected:
//初始化函数
int InitInstance();
//结束工作处理函数
void ExitInstance();
//获取本模块类型函数
MODULE_TYPE GetModuleType();
//定时器事件处理函数
void OnTimer(const long nTimerID);
//命令解析与分发函数
void ParseMsg(MSG_INTRA* pMsgParsed);
//处理统计项目查询请求
void ProcListStatItem(MSG_INTRA* pMsgParsed);
//处理统计可选域信息查询请求
void ProcListQueryPara(MSG_INTRA* pMsgParsed);
//处理统计项目设置请求
void ProcSetStatItem(MSG_INTRA* pMsgParsed);
//处理统计数据浏览请求
void ProcBrowseStatRst(MSG_INTRA* pMsgParsed);
protected:
//发送报告体中只有简单的消息的MML报告
void SendSimpleInfoReport(const char* szCmd, int nRetCode,
const char* szInfo);
//发送报告体为一个横向表格的MML报告
void SendHoriTableReport(CParseResult* pParseResult,
LIST<STRING>& TitleList, LIST<STRING>& ContentList,
const char* szTableHeadName);
//发送报告体为一个纵向表格的MML报告
void SendVertTableReport(CParseResult* pParseResult,
LIST<STRING>& TitleList, LIST<STRING>& ContentList,
LIST<STRING>& RecTitleList);
void SendMMLReport(const char* szReport);
//把字串转换为时间
int StrToTm(const char* szSrc, tm &tmTar);
//由年,月获得日的天数
int GetDay(int nYear, int nMonth);
//获得和周期相关信息
int ConvertCycle(int nPeriod,
char* szStartTime,
char* szEndTime,
VECTOR<STRING>& CycleName,
VECTOR<time_t>& StartTime,
VECTOR<time_t>& EndTime);
//分析配置信息
void ParseCfgInfo(char* szCfgInfo,
MAP<STRING, ONESTATSUBITEMCFG_LIST>& mapAPNameStatCfg);
//获得详细配置信息内容
void GetCfgItem(char* szStatCfg,
char* szApName,
char* szItemName,
char* szSubItemName,
char* szExpress);
protected:
//当前正在处理的话单台的台号
int m_nCurClientNo;
//统计配置文件管理者对象指针
CCDRStatCfgMgr* m_pCDRStatCfgMgr;
//统计结果文件管理者对象指针
CCDRStatRstMgr* m_pCDRStatRstMgr;
//MML报文对象指针
CQBMMLReport* m_pMMLReport;
//统计操作对象指针
CCDRStatTask* m_pCDRStatTask;
char m_szBeginTime[20];
//统计起始时间
time_t m_tBeginTime;
//统计截止时间
time_t m_tEndTime;
//上次统计启动时间
time_t m_tLastStatTime;
//定时器ID
long m_lTimerID;
//接点数
UINT4 m_uAPNum;
//接入点列表
LIST<STRING> m_APNameList;
//每个接入点对应的可选域信息
MAP<STRING, INFO_LIST> m_mapAPToParaField;
//每个接入点对应的可选域信息
static MAP<STRING, INFO_LIST> m_mapAPToParaContent;
//每个接入点对应的可选域信息查询MML报文的缓冲区
MAP<STRING, char*> m_mapAPToParaMem;
//每个接入点对应的存储统计项目查询MML报文的缓冲区
MAP<STRING, INFO_LIST> m_mapAPToStatItemMem;
STRING m_szInfo;
};
#endif //__CDR_STAT_SVR_H__
|
[
"y35777@163.com"
] |
y35777@163.com
|
b8c58c251653b22378d2ee5b2ee98ea13487370c
|
a47a539625a3e4962abbd91f4d6eab1bd7ee6823
|
/balltrack.cpp
|
9278a72e58e1fd5f317cb2ef83aba5eb49c3f75d
|
[] |
no_license
|
burakkurtt/ballTrack
|
cc21e3342a2a74d1eb6462e5e4abeb49befe34bb
|
ba778971802e17a6aebbe5fc2b5bc1b47bb215e1
|
refs/heads/master
| 2020-04-13T05:48:45.086029
| 2018-12-24T16:59:45
| 2018-12-24T16:59:45
| 163,003,867
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,725
|
cpp
|
#include "../flycapture.2.9.3.43_armhf/include/FlyCapture2.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <wiringSerial.h>
using namespace FlyCapture2;
using namespace cv;
using namespace std;
ofstream dosyaYaz ("denemethr6.txt",ios::app);
float errorX;
float errorY;
int posX = 0;
int posY = 0;
int midPositionThrottle = 0;
int midPositionRudder = 0;
int rudder = 0;
int aileron = 0;
int throttle = 0;
int elevator = 0;
int width = 100;
int height = 100;
int pErrorX = 0;
int pErrorY = 0;
int erroriX = 0;
int erroriY = 0;
float totalErrorX = 0;
float totalErrorY = 0;
float kd = 0;
float kp = 0;
float ki = 0;
float kdRudder = 0;
float kpRudder = 0;
float kiRudder = 0;
float kdThrottle = 0;
float kpThrottle = 0;
float kiThrottle = 0;
std::ofstream odroid;
float errorTot [2];
float pidCal (int a, int b);
int sendMsg (int throttle, int rudder, int elevator, int aileron);
int main()
{
Error error;
Camera camera;
CameraInfo camInfo;
// Connect the camera
error = camera.Connect( 0 );
if ( error != PGRERROR_OK )
{
std::cout << "Failed to connect to camera" << std::endl;
return false;
}
// Get the camera info and print it out
error = camera.GetCameraInfo( &camInfo );
if ( error != PGRERROR_OK )
{
std::cout << "Failed to get camera info from camera" << std::endl;
return false;
}
std::cout << camInfo.vendorName << " "
<< camInfo.modelName << " "
<< camInfo.serialNumber << std::endl;
error = camera.StartCapture();
if ( error == PGRERROR_ISOCH_BANDWIDTH_EXCEEDED )
{
std::cout << "Bandwidth exceeded" << std::endl;
return false;
}
else if ( error != PGRERROR_OK )
{
std::cout << "Failed to start image capture" << std::endl;
return false;
}
/*
//HSV controll
namedWindow ("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
//Create trackbars in "Control" window
cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", "Control", &iHighH, 179);
cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", "Control", &iHighS, 255);
cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", "Control", &iHighV, 255);
//Create trackbars in "Control" window
cvCreateTrackbar("Kp ", "Control", &kpc, 100);
cvCreateTrackbar("Ki ", "Control", &kic, 100);
cvCreateTrackbar("Kd ", "Control", &kdc, 100);
*/
//PID control
int kpc = 0;
int kic = 0;
int kdc = 0;
int iLastX = -1;
int iLastY = -1;
//Capture a temporary image from the camera
Mat imgTmp;
//cap.read(imgTmp);
//Create a black image with the size as the camera output
Mat imgLines = Mat::zeros( imgTmp.size(), CV_8UC3 );;
// capture loop
char key = 0;
while(key != 'q')
{
// Get the image
Image rawImage;
Error error = camera.RetrieveBuffer( &rawImage );
if ( error != PGRERROR_OK )
{
std::cout << "capture error" << std::endl;
continue;
}
// convert to rgb
Image rgbImage;
rawImage.Convert( FlyCapture2::PIXEL_FORMAT_BGR, &rgbImage );
// convert to OpenCV Mat
unsigned int rowBytes = (double)rgbImage.GetReceivedDataSize()/(double)rgbImage.GetRows();
cv::Mat imageOrj = cv::Mat(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3, rgbImage.GetData(),rowBytes);
// image process
//resize the image
resize(imageOrj, imageOrj, Size(width,height), 0, 0, INTER_CUBIC);
Mat imageHSV;
cvtColor(imageOrj, imageHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded
;
//inRange(imageHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
inRange(imageHSV, Scalar(62,32,62), Scalar(84, 255, 255), imgThresholded); //Threshold the image
//morphological opening (remove small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//morphological closing (fill small holes in the foreground)
dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//showing centre of ferame
circle(imageOrj, Point(width/2,height/2), 1, Scalar (0,255,0), 2);
//calculatıon of object center
Moments oMoments = moments(imgThresholded);
double dM01 = oMoments.m01;
double dM10 = oMoments.m10;
double dArea = oMoments.m00;
// if the area <= 10000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
if (dArea > width*100)
{
//calculate the position of the ball
posX = dM10 / dArea;
posY = dM01 / dArea;
std::cout << "Point(x,y)=" << Point(posX, posY) << std::endl;
//error calculation PID coeff.
kp = kpc * 0.1 ;
ki = kic * 0.01;
kd = kdc * 0.01;
kpRudder = 4.3;
kiRudder = 0.01;
kdRudder = 0;
kpThrottle =2;
kiThrottle = 0.01;
kdThrottle = 0;
//std::cout << kpRudder<< "" << kdRudder<< std::endl;
pidCal (posX, posY);
std::cout << totalErrorX << "" << totalErrorY << std::endl;
throttle = 1580; // mid value of throttle
aileron = 1516; // mid value of aileron
//rudder = 1504;
elevator = 1476;
//calculation control signal to quadcopter if error > 30 pixel
if (errorX > width/20 || errorX < -1*width/20)
{
// X calculation [min-1100-mid-1504-max-1900]
midPositionRudder = 1504;
rudder = midPositionRudder + totalErrorX;
std::cout << "X control signal " << rudder << std::endl;
}
if (errorY > height/20 || errorY < -1*height/20)
{
// Y calculation [min-1100-mid-1504-max-1900]
//int midPositionThrottle = 1504;
//midPositionThrottle = 1625;
//throttle = midPositionThrottle + totalErrorY;
//throttle = throttle + totalErrorY;
std::cout << "Y control signal " << throttle << std::endl;
}
// writing text
dosyaYaz<<midPositionThrottle<<" "<<throttle<<" "<<midPositionRudder<<" "<<rudder<<" "<<posX<<" "<<posY<<" "<<errorX<<" "<<errorY<<endl;
// sending message to arduino
sendMsg (throttle, rudder, elevator, aileron);
if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
{
//Draw a red circle from the previous point to the current point
line(imageOrj, Point(posX, posY), Point(iLastX, iLastY), Scalar(0,0,255), 2);
circle(imageOrj, Point(posX, posY), width/10 , Scalar (0,0,255), 1);
}
iLastX = posX;
iLastY = posY;
}
else
{
throttle = 1504; // mid value of throttle
aileron = 1516; // mid value of aileron
rudder = 1504; // mid value of rudder
elevator = 1476; // mid value of elevator
// sending message to arduino
sendMsg (throttle, rudder, elevator, aileron);
}
imshow("Thresholded Image", imgThresholded); //show the thresholded image
imshow("Original", imageOrj); //show the original image
key = cv::waitKey(40);
}
error = camera.StopCapture();
if ( error != PGRERROR_OK )
{
// This may fail when the camera was removed, so don't show
// an error message
}
camera.Disconnect();
dosyaYaz<<"\n"<<endl;
return 0;
}
float pidCal (int a, int b)
{
//kp
errorX = a - width/2;
errorY = height/2 - b;
//kd
int errordX = errorX - pErrorX;
int errordY = errorY - pErrorY;
//ki
erroriX += errorX;
erroriY += errorY;
//float errorTotX = errorX * kp + errordX * kd + erroriX * ki;
float errorTotX = errorX * kpRudder + errordX * kdRudder + erroriX * kiRudder;
float errorTotY = errorY * kpThrottle + errordY * kdThrottle + erroriY * kiThrottle;
//float errorTotY = errorY * kp + errordY * kd + erroriY * ki;
pErrorX = errorX;
pErrorY = errorY;
totalErrorX = errorTotX;
totalErrorY = errorTotY;
std::cout << "Error(x,y)=" << (totalErrorX) << "" << (totalErrorY) << std::endl;
return 0;
}
int sendMsg (int throttle, int rudder, int elevator, int aileron)
{
int maxThrottle = 1900;
int minThrottle = 1110;
int maxRudder = 1900;
int minRudder = 1110;
int maxElevator = 1740;
int minElevator = 1260;
int maxAileron = 1740;
int minAileron = 1260;
if (throttle > maxThrottle)
{
throttle = maxThrottle;
}
else if (throttle < minThrottle)
{
throttle = minThrottle;
}
if (rudder > maxRudder)
{
rudder = maxRudder;
}
else if (rudder < minRudder)
{
rudder = minRudder;
}
if (elevator > maxElevator)
{
elevator = maxElevator;
}
else if (elevator < minElevator)
{
elevator = minElevator;
}
if (aileron > maxAileron)
{
aileron = maxAileron;
}
else if (aileron < minAileron)
{
aileron = minAileron;
}
//total control signal
std::cout << "control signals " << "\nT " << throttle << "\nR " << rudder << "\nE " << elevator << "\nA " << aileron << std::endl;
//serial
odroid.open( "/dev/ttyACM1");
//write to it
odroid << throttle << "t" << rudder << "r" << elevator << "e" << aileron << "a";
odroid.close();
return 0;
}
|
[
"noreply@github.com"
] |
burakkurtt.noreply@github.com
|
8e8af1cdc245620c2c6471070a030a8a8f105c46
|
6161b649af64dd01c041ef47e809eb0ea2c6e6fd
|
/libs/ardour/ardour/delivery.h
|
bb07b9ab2554b5e1ddcddb51070a2336b1631db9
|
[] |
no_license
|
taybin/Gusto
|
a6df309075f2ed5fffa5404ce756c8282cc6aa87
|
567554470a8de13a9984c895b83f3ac045f587ab
|
refs/heads/master
| 2016-08-05T13:52:42.667291
| 2010-07-06T03:11:34
| 2010-07-06T03:16:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,704
|
h
|
/*
Copyright (C) 2006 Paul Davis
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __ardour_delivery_h__
#define __ardour_delivery_h__
#include <string>
#include "ardour/types.h"
#include "ardour/chan_count.h"
#include "ardour/io_processor.h"
namespace ARDOUR {
class BufferSet;
class IO;
class MuteMaster;
class Panner;
class Delivery : public IOProcessor
{
public:
enum Role {
/* main outputs - delivers out-of-place to port buffers, and cannot be removed */
Main = 0x1,
/* send - delivers to port buffers, leaves input buffers untouched */
Send = 0x2,
/* insert - delivers to port buffers and receives in-place from port buffers */
Insert = 0x4,
/* listen - internal send used only to deliver to control/monitor bus */
Listen = 0x8,
/* aux - internal send used to deliver to any bus, by user request */
Aux = 0x10
};
static bool role_requires_output_ports (Role r) { return r == Main || r == Send || r == Insert; }
/* Delivery to an existing output */
Delivery (Session& s, boost::shared_ptr<IO> io, boost::shared_ptr<MuteMaster> mm, const std::string& name, Role);
/* Delivery to a new output owned by this object */
Delivery (Session& s, boost::shared_ptr<MuteMaster> mm, const std::string& name, Role);
~Delivery ();
bool set_name (const std::string& name);
std::string display_name() const;
Role role() const { return _role; }
bool can_support_io_configuration (const ChanCount& in, ChanCount& out) const;
bool configure_io (ChanCount in, ChanCount out);
void run (BufferSet& bufs, sframes_t start_frame, sframes_t end_frame, nframes_t nframes, bool);
/* supplemental method used with MIDI */
void flush (nframes_t nframes, nframes64_t time);
void transport_stopped ();
void no_outs_cuz_we_no_monitor(bool);
void cycle_start (nframes_t);
void increment_output_offset (nframes_t);
void transport_stopped (sframes_t frame);
BufferSet& output_buffers() { return *_output_buffers; }
PBD::Signal0<void> MuteChange;
static PBD::Signal1<void,nframes_t> CycleStart;
XMLNode& state (bool full);
int set_state (const XMLNode&, int version);
/* Panning */
static int disable_panners (void);
static int reset_panners (void);
boost::shared_ptr<Panner> panner() const { return _panner; }
void reset_panner ();
void defer_pan_reset ();
void allow_pan_reset ();
uint32_t pans_required() const { return _configured_input.n_audio(); }
void start_pan_touch (uint32_t which);
void end_pan_touch (uint32_t which);
protected:
Role _role;
BufferSet* _output_buffers;
gain_t _current_gain;
nframes_t _output_offset;
bool _no_outs_cuz_we_no_monitor;
boost::shared_ptr<MuteMaster> _mute_master;
bool no_panner_reset;
boost::shared_ptr<Panner> _panner;
static bool panners_legal;
static PBD::Signal0<int> PannersLegal;
int panners_became_legal ();
PBD::ScopedConnection panner_legal_c;
void output_changed (IOChange, void*);
gain_t target_gain ();
};
} // namespace ARDOUR
#endif // __ardour__h__
|
[
"taybin@penguinsounds.org"
] |
taybin@penguinsounds.org
|
4bfa4a1cb4ab8c6b56cd884804e47a666ceaa021
|
4ab8df086e0079258f3fed9452e0a62d782e7b40
|
/WorldPlayer.h
|
cb54cf728338ff9b52a98f3ae276e0771cc4d4f2
|
[] |
no_license
|
PhanHoangf/game_development
|
7d1e4b7bba7fe24613f20db779ebe678bc17d315
|
717a80e8d57a10713bf32a63aa894607851c8eb7
|
refs/heads/master
| 2023-06-22T00:09:53.155602
| 2021-07-17T03:55:30
| 2021-07-17T03:55:30
| 366,421,367
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 934
|
h
|
#pragma once
#include "GameObject.h"
#include "Game.h"
#define PLAYER_SPEED 0.1f
#define PLAYER_STATE_IDLE 0
#define PLAYER_STATE_RIGHT 100
#define PLAYER_STATE_LEFT 111
#define PLAYER_STATE_UP 200
#define PLAYER_STATE_DOWN 201
#define PLAYER_BBOX_WIDTH 8
// SMALL
#define MARIO_ANI_SMALL 0
//BIG
#define MARIO_ANI_BIG 1
//TAIL
#define MARIO_ANI_TAIL 2
//FIRE
#define MARIO_ANI_FIRE 3
#define MARIO 0
#define LUIGI 1
class WorldPlayer :public CGameObject {
int level;
public:
int moveLeft, moveUp, moveRight, moveBottom, sceneId;
WorldPlayer(float x = 0.0f, float y = 0.0f);
virtual void GetBoundingBox(float& left, float& top, float& right, float& bottom);
virtual void Render();
virtual void Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects = NULL);
void SetLevel(int l) { level = l; };
void SetState(int state);
void ChooseScene(int sceneId) { CGame::GetInstance()->SwitchScene(sceneId); }
};
|
[
"thanh-hoang.phan@ant-tech.eu"
] |
thanh-hoang.phan@ant-tech.eu
|
9811d11a41ddf2d5a45f3eb3e5b8811a3ef9f9cc
|
48e5c7e47a09ec53a4763efe29dedc41535d1d68
|
/src/runtime-env/fiber-env/native-mutex.cpp
|
3e5ed26ce5f2ccdac6598d75bfebe56f780e53a7
|
[] |
no_license
|
kaifengz/fasmio
|
dddd2e9249a0643ac5b3de7f416ba053c809fe9d
|
4a769823d35c27c3f764eb0342e0dde6b71fb4b3
|
refs/heads/master
| 2016-08-10T12:59:12.136290
| 2015-05-23T11:53:47
| 2015-07-09T02:07:36
| 36,076,525
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 474
|
cpp
|
#include "./native-mutex.h"
namespace fasmio { namespace fiber_env {
NativeMutex::NativeMutex()
{
pthread_mutex_init(&mutex_, nullptr);
}
NativeMutex::~NativeMutex()
{
pthread_mutex_destroy(&mutex_);
}
bool NativeMutex::Lock()
{
return 0 == pthread_mutex_lock(&mutex_);
}
bool NativeMutex::TryLock()
{
return 0 == pthread_mutex_trylock(&mutex_);
}
void NativeMutex::Unlock()
{
pthread_mutex_unlock(&mutex_);
}
}} // namespace fasmio::fiber_env
|
[
"kaifeng.zhu@citrix.com"
] |
kaifeng.zhu@citrix.com
|
6a9722b4ef351d8acb57f48e75bd2d5518984c62
|
35a9dcf009857ca7c720e31dbef6cd22479854ef
|
/src/Utils/MyGLM.h
|
aafbcb5321e8afaff88c0d8d65f12c73f3b0d79b
|
[] |
no_license
|
x3ent3nte/SimulationProject
|
22e9646512f374c74a3fdde68cc2fa5b183bb327
|
292e4e663a66d35147442dcda0841a56a736ed4a
|
refs/heads/master
| 2023-05-14T06:28:15.124400
| 2021-06-06T19:42:43
| 2021-06-06T19:42:43
| 275,607,695
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 357
|
h
|
#ifndef MY_GLM_H
#define MY_GLM_H
#define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/hash.hpp>
#include <sstream>
std::ostream& operator<<(std::ostream& os, const glm::uvec4& v);
#endif
|
[
"m202-tracer@hotmail.co.uk"
] |
m202-tracer@hotmail.co.uk
|
1404a24871c04abbd67d921685bb8c094821a185
|
075e1e57da060d1c705a28786583f296e54a331c
|
/Internet_Clock_eps01_v3/Internet_Clock_eps01_v3.ino
|
ed66860e303699f308022510ecd4f91e791a36e0
|
[] |
no_license
|
AgIgor/Internet_Clock_3
|
84dfab4c759a06c40bc1b736f4a50cfd642351fa
|
a52725fa743b16f4d2131adeae0c0af6501d349f
|
refs/heads/main
| 2023-08-23T15:58:26.312268
| 2021-11-07T17:15:27
| 2021-11-07T17:15:27
| 404,538,374
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 846
|
ino
|
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char *ssid = "VIVOFIBRA-9501";
const char *password = "rgw7ucm3GT";
const long utcOffsetInSeconds = -10800;
char daysOfTheWeek[7][12] = {"Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sabado"};
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "south-america.pool.ntp.org", utcOffsetInSeconds,60000);
byte Minuto,newMinuto;
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println("Ok");
}
void loop() {
timeClient.update();
Minuto = (timeClient.getMinutes());
if(newMinuto != Minuto){
newMinuto = Minuto;
Serial.println(timeClient.getFormattedTime());
}
delay(10);
}
|
[
"you@example.com"
] |
you@example.com
|
8036d577f0cd981ab60563cb083db2f4a8389ae2
|
519c2a08b44addad219dba1393c21e78b3c0f175
|
/BasicFunctions.cpp
|
0d40f7190c1660a5c67c3ae477e9c405540c86aa
|
[] |
no_license
|
genghiskhan3/C-Tutorials
|
0692f9ac4c38090aab4e74b2fea0339f995062b7
|
a712c64a8eeb6ea210a3c0d553f414cb8c8b1c45
|
refs/heads/master
| 2021-01-25T10:44:39.069158
| 2015-03-13T04:38:01
| 2015-03-13T04:38:01
| 28,027,137
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 531
|
cpp
|
#include <iostream>
int add(int x, int y)
{
return x + y;
}
int multiply(int z, int w)
{
return z * w;
}
int main()
{
using namespace std;
cout << add(4, 5) << endl; // evalutes 4 + 5
cout << add(3, 6) << endl; // evalues 3 + 6
cout << add(1, 8) << endl; // evalues 1 + 8
int a = 3;
int b = 5;
cout << add(a, b) << endl; // evaluates 3 + 5
cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)
return 0;
}
|
[
"mattleblanc333@gmail.com"
] |
mattleblanc333@gmail.com
|
1a5565f2ac3c17e6db560ae3438fa49787b50ae2
|
0ef6f523f64dd2461893bfa510eae3ac2da47dc1
|
/Classes/Buff.h
|
d63ea3664e427737cca2361655fc0618d9d62baf
|
[] |
no_license
|
Crasader/ColorDefence
|
2654fcd368f9a3f20056dbb8733f3f9c99264770
|
e0f940c26bbf3803ff64b7a4e4d2e248967db2ab
|
refs/heads/master
| 2020-12-07T08:41:53.498516
| 2016-05-21T06:17:23
| 2016-05-21T06:17:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 831
|
h
|
#pragma once
#include "cocos2d.h"
class Enemy;
class Buff : public cocos2d::Sprite
{
public:
//初始化
virtual bool init();
//create函数
CREATE_FUNC(Buff);
unsigned getBuffType();
virtual void makeEffectWithTarget(Enemy* target, float delta);
virtual void overrideWithNewBuff(Buff* newBuff);
bool willEndBuff();
virtual bool verifyWithTarget(Enemy* target);
virtual void setAppearacneWithTarget(Enemy* target , bool show);
void setDamageContributerID(int ID);
enum BuffType
{
kBuffTypeSlow,
kBuffTypePoisoning,
kBuffTypeBroken,
kBuffTypeStun,
kBuffTypeSuperPoisoning,
kBuffTypeSpreadDamage,
kBuffTypeExplodeOnDeath,
kBuff
};
void forceEnd();
protected:
bool _end;
unsigned _buffType;
//Enemy* _target;
float _buffTimeRest;
int _damageContributerID;
};
|
[
"aillieo@163.com"
] |
aillieo@163.com
|
b0cc512448d055c854dfcbd630ef436f52cd4f99
|
e1a0c89b0923e7e9be5e44d546c75a0f808c8d79
|
/lib/ArduinoJson/test/JsonVariant/as.cpp
|
3c9002a663e3f7e3d5ff2246ab794712d85ff1db
|
[
"MIT"
] |
permissive
|
nicksteiner/tltcam
|
71961b1bab00aa5eb6b8fc3ad272b8cfc8c1f679
|
1353e4384d163a5033e8b12f3362fa5c12176b6d
|
refs/heads/master
| 2020-03-12T16:22:20.481462
| 2018-04-23T15:08:33
| 2018-04-23T15:08:33
| 130,714,435
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,746
|
cpp
|
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <stdint.h>
#include <catch.hpp>
static const char* null = 0;
TEST_CASE("JsonVariant::as()") {
SECTION("DoubleAsBool") {
JsonVariant variant = 4.2;
REQUIRE(variant.as<bool>());
}
SECTION("DoubleAsCstr") {
JsonVariant variant = 4.2;
REQUIRE_FALSE(variant.as<const char*>());
}
SECTION("DoubleAsString") {
JsonVariant variant = 4.2;
REQUIRE(std::string("4.20") == variant.as<std::string>());
}
SECTION("DoubleAsLong") {
JsonVariant variant = 4.2;
REQUIRE(4L == variant.as<long>());
}
SECTION("DoubleAsUnsigned") {
JsonVariant variant = 4.2;
REQUIRE(4U == variant.as<unsigned>());
}
SECTION("DoubleZeroAsBool") {
JsonVariant variant = 0.0;
REQUIRE_FALSE(variant.as<bool>());
}
SECTION("DoubleZeroAsLong") {
JsonVariant variant = 0.0;
REQUIRE(0L == variant.as<long>());
}
SECTION("FalseAsBool") {
JsonVariant variant = false;
REQUIRE_FALSE(variant.as<bool>());
}
SECTION("FalseAsDouble") {
JsonVariant variant = false;
REQUIRE(0.0 == variant.as<double>());
}
SECTION("FalseAsLong") {
JsonVariant variant = false;
REQUIRE(0L == variant.as<long>());
}
SECTION("FalseAsString") {
JsonVariant variant = false;
REQUIRE(std::string("false") == variant.as<std::string>());
}
SECTION("TrueAsBool") {
JsonVariant variant = true;
REQUIRE(variant.as<bool>());
}
SECTION("TrueAsDouble") {
JsonVariant variant = true;
REQUIRE(1.0 == variant.as<double>());
}
SECTION("TrueAsLong") {
JsonVariant variant = true;
REQUIRE(1L == variant.as<long>());
}
SECTION("TrueAsString") {
JsonVariant variant = true;
REQUIRE(std::string("true") == variant.as<std::string>());
}
SECTION("LongAsBool") {
JsonVariant variant = 42L;
REQUIRE(variant.as<bool>());
}
SECTION("LongZeroAsBool") {
JsonVariant variant = 0L;
REQUIRE_FALSE(variant.as<bool>());
}
SECTION("PositiveLongAsDouble") {
JsonVariant variant = 42L;
REQUIRE(42.0 == variant.as<double>());
}
SECTION("NegativeLongAsDouble") {
JsonVariant variant = -42L;
REQUIRE(-42.0 == variant.as<double>());
}
SECTION("LongAsString") {
JsonVariant variant = 42L;
REQUIRE(std::string("42") == variant.as<std::string>());
}
SECTION("LongZeroAsDouble") {
JsonVariant variant = 0L;
REQUIRE(0.0 == variant.as<double>());
}
SECTION("NullAsBool") {
JsonVariant variant = null;
REQUIRE_FALSE(variant.as<bool>());
}
SECTION("NullAsDouble") {
JsonVariant variant = null;
REQUIRE(0.0 == variant.as<double>());
}
SECTION("NullAsLong") {
JsonVariant variant = null;
REQUIRE(0L == variant.as<long>());
}
SECTION("NullAsString") {
JsonVariant variant = null;
REQUIRE(std::string("null") == variant.as<std::string>());
}
SECTION("NumberStringAsBool") {
JsonVariant variant = "42";
REQUIRE(variant.as<bool>());
}
SECTION("NumberStringAsLong") {
JsonVariant variant = "42";
REQUIRE(42L == variant.as<long>());
}
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
SECTION("NumberStringAsInt64Negative") {
JsonVariant variant = "-9223372036854775808";
REQUIRE(-9223372036854775807 - 1 == variant.as<long long>());
}
SECTION("NumberStringAsInt64Positive") {
JsonVariant variant = "9223372036854775807";
REQUIRE(9223372036854775807 == variant.as<long long>());
}
#endif
SECTION("RandomStringAsBool") {
JsonVariant variant = "hello";
REQUIRE_FALSE(variant.as<bool>());
}
SECTION("RandomStringAsLong") {
JsonVariant variant = "hello";
REQUIRE(0L == variant.as<long>());
}
SECTION("RandomStringAsConstCharPtr") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.as<const char*>());
}
SECTION("RandomStringAsCharPtr") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.as<char*>());
}
SECTION("RandomStringAsString") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.as<std::string>());
}
SECTION("TrueStringAsBool") {
JsonVariant variant = "true";
REQUIRE(variant.as<bool>());
}
SECTION("TrueStringAsLong") {
JsonVariant variant = "true";
REQUIRE(1L == variant.as<long>());
}
SECTION("ObjectAsString") {
DynamicJsonBuffer buffer;
JsonObject& obj = buffer.createObject();
obj["key"] = "value";
JsonVariant variant = obj;
REQUIRE(std::string("{\"key\":\"value\"}") == variant.as<std::string>());
}
SECTION("ArrayAsString") {
DynamicJsonBuffer buffer;
JsonArray& arr = buffer.createArray();
arr.add(4);
arr.add(2);
JsonVariant variant = arr;
REQUIRE(std::string("[4,2]") == variant.as<std::string>());
}
SECTION("ArrayAsJsonArray") {
DynamicJsonBuffer buffer;
JsonArray& arr = buffer.createArray();
JsonVariant variant = arr;
REQUIRE(&arr == &variant.as<JsonArray&>());
REQUIRE(&arr == &variant.as<JsonArray>()); // <- shorthand
}
SECTION("ObjectAsJsonObject") {
DynamicJsonBuffer buffer;
JsonObject& arr = buffer.createObject();
JsonVariant variant = arr;
REQUIRE(&arr == &variant.as<JsonObject&>());
REQUIRE(&arr == &variant.as<JsonObject>()); // <- shorthand
}
}
|
[
"nick.steiner@gmail.com"
] |
nick.steiner@gmail.com
|
3e7175f3070ab3f0b626b9fd105bd32f76485e9b
|
afb13079285b95a307df439b0a5393c41f881e58
|
/QRNG-unity/Assets/StreamingAssets/.q/src/noise/noise_model.hpp
|
04fbe787706ae0cd588218989a576280cd877ac6
|
[
"Apache-2.0"
] |
permissive
|
edwinagnew/procedural-rng
|
a59bcc54ac215fc618cd6fdb2ef1276a7a42004f
|
ce158572a700c9f247162affb076afff30dd8632
|
refs/heads/main
| 2023-06-13T03:52:00.826642
| 2021-07-15T11:05:25
| 2021-07-15T11:05:25
| 351,199,592
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 45,342
|
hpp
|
/**
* This code is part of Qiskit.
*
* (C) Copyright IBM 2018, 2019.
*
* This code is licensed under the Apache License, Version 2.0. You may
* obtain a copy of this license in the LICENSE.txt file in the root directory
* of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
*
* Any modifications or derivative works of this code must retain this
* copyright notice, and modified files need to carry a notice indicating
* that they have been altered from the originals.
*/
#ifndef _aer_noise_model_hpp_
#define _aer_noise_model_hpp_
#define _USE_MATH_DEFINES
#include <math.h>
#include "framework/operations.hpp"
#include "framework/types.hpp"
#include "framework/rng.hpp"
#include "framework/circuit.hpp"
#include "framework/linalg/matrix_utils.hpp"
#include "noise/quantum_error.hpp"
#include "noise/readout_error.hpp"
namespace AER {
namespace Noise {
//=========================================================================
// Noise Model class
//=========================================================================
// This allows specification of default and individual noise parameters for
// each circuit operation that may either be local (applied to the qubits
// in the operation) or nonlocal (applied to different qubits). The errors
// may each also be applied either before or after the operation as per
// the specification of the AbstractError subclass.
class NoiseModel {
public:
using Method = QuantumError::Method;
using NoiseOps = std::vector<Operations::Op>;
NoiseModel() = default;
NoiseModel(const json_t &js) {load_from_json(js);}
// Sample a noisy implementation of a full circuit
// An RngEngine is passed in as a reference so that sampling
// can be done in a thread-safe manner.
// Sample methods are:
// standard: each noisy op will be returned along with additional noise ops
// superop: each noisy gate or reset will be returned as a single superop
Circuit sample_noise(const Circuit &circ,
RngEngine &rng) const;
// Set sample mode to circuit
// This is the default method for noise sampling that can work for
// any simulator that supports the sampled noise instructions
void activate_circuit_method();
// Set sample mode to superoperator
// This will cause all QuantumErrors stored in the noise model
// to calculate their superoperator representations and raise
// an exception if they cannot be converted.
void activate_superop_method();
// Set sample mode to kraus
// This will cause all QuantumErrors stored in the noise model
// to calculate their canonical Kraus representations and raise
// an exception if they cannot be converted.
void activate_kraus_method();
//-----------------------------------------------------------------------
// Checking if errors types are in noise model
//-----------------------------------------------------------------------
// Return True if noise model contains readout errors
inline bool has_readout_errors() const {
return !readout_errors_.empty();
}
// Return True if noise model contains quantum errors
inline bool has_quantum_errors() const {
return local_quantum_errors_ || nonlocal_quantum_errors_;
}
// Return True if noise model contains nonlocal quantum errors
inline bool has_nonlocal_quantum_errors() const {
return nonlocal_quantum_errors_;
}
// Return True if noise model contains local quantum errors
inline bool has_local_quantum_errors() const {
return local_quantum_errors_;
}
// Return true if the noise model is ideal
inline bool is_ideal() const {
return !has_readout_errors() && !has_quantum_errors();
}
//-----------------------------------------------------------------------
// Add errors to noise model
//-----------------------------------------------------------------------
// Load a noise model from JSON
void load_from_json(const json_t &js);
// Add a QuantumError to the noise model
void add_quantum_error(const QuantumError &error,
const stringset_t &op_labels,
const std::vector<reg_t> &op_qubits = {},
const std::vector<reg_t> &noise_qubits = {});
// Add a ReadoutError to the noise model
void add_readout_error(const ReadoutError &error,
const std::vector<reg_t> &op_qubits = {});
// Set which single qubit gates should use the X90 waltz error model
inline void set_x90_gates(const stringset_t &x90_gates) {
x90_gates_ = x90_gates;
}
//-----------------------------------------------------------------------
// Utils
//-----------------------------------------------------------------------
// Remap the qubits in the noise model.
// A remapping is entered as a map {old: new}
// Any qubits not in the mapping are assumed to be mapped to themselves.
// Hence the sets of all keys and all values of the map must be equal.
void remap_qubits(const std::unordered_map<uint_t, uint_t> &mapping);
// Return vector of noise qubits for non local error on specified label and qubits
// If no nonlocal error exists an empty set is returned.
std::set<uint_t> nonlocal_noise_qubits(const std::string label, const reg_t &qubits) const;
// Set threshold for applying u1 rotation angles.
// an Op for u1(theta) will only be added if |theta| > 0 and |theta - 2*pi| > 0
inline void set_u1_threshold(double threshold) {
u1_threshold_ = threshold;
}
// Return the opset for the noise model
inline const Operations::OpSet& opset() const {return opset_;}
private:
// Sample noise for the current operation.
NoiseOps sample_noise(const Operations::Op &op,
RngEngine &rng) const;
// Sample noise for the current operation
void sample_readout_noise(const Operations::Op &op,
NoiseOps &noise_after,
RngEngine &rng) const;
void sample_local_quantum_noise(const Operations::Op &op,
NoiseOps &noise_before,
NoiseOps &noise_after,
RngEngine &rng) const;
void sample_nonlocal_quantum_noise(const Operations::Op &op,
NoiseOps &noise_ops,
NoiseOps &noise_after,
RngEngine &rng) const;
// Sample noise for the current operation
NoiseOps sample_noise_helper(const Operations::Op &op,
RngEngine &rng) const;
// Sample a noisy implementation of a two-X90 pulse u3 gate
NoiseOps sample_noise_x90_u3(uint_t qubit, complex_t theta,
complex_t phi, complex_t lamba,
RngEngine &rng) const;
// Sample a noisy implementation of a single-X90 pulse u2 gate
NoiseOps sample_noise_x90_u2(uint_t qubit, complex_t phi, complex_t lambda,
RngEngine &rng) const;
// Add a local quantum error to the noise model for specific qubits
void add_local_quantum_error(const QuantumError &error,
const stringset_t &op_labels,
const std::vector<reg_t> &op_qubits);
// Add a non-local Error type to the model for specific qubits
void add_nonlocal_quantum_error(const QuantumError &error,
const stringset_t &op_labels,
const std::vector<reg_t> &op_qubits,
const std::vector<reg_t> &noise_qubits);
// Flags which say whether the local or nonlocal error tables are used
bool local_quantum_errors_ = false;
bool nonlocal_quantum_errors_ = false;
// List of quantum errors
std::vector<QuantumError> quantum_errors_;
// List of readout errors
std::vector<ReadoutError> readout_errors_;
// Set of qubits used in noise model
std::set<uint_t> noise_qubits_;
using inner_table_t = stringmap_t<std::vector<size_t>>;
using outer_table_t = stringmap_t<inner_table_t>;
// Table indexes a name with a vector of the position of noise operations
inner_table_t readout_error_table_;
outer_table_t local_quantum_error_table_;
// Nonlocal noise lookup table. Things get messy here...
// the outer map is a table from gate strings to gate qubit maps
// the gate qubit map is a map from qubits to another map of target qubits
// which is then the final qubit map from target qubits to error_ptr positions
stringmap_t<outer_table_t> nonlocal_quantum_error_table_;
// Helper function to convert reg to string for key of unordered maps/sets
std::string reg2string(const reg_t ®) const;
reg_t string2reg(std::string s) const;
std::string remap_string(const std::string key,
const std::unordered_map<uint_t, uint_t> &mapping) const;
// Helper function to try and convert an instruction to superop matrix
// If conversion isn't possible this returns an empty matrix
cmatrix_t op2superop(const Operations::Op &op) const;
// Try and convert an instruction to unitary matrix
// If conversion isn't possible this returns an empty matrix
cmatrix_t op2unitary(const Operations::Op &op) const;
// Table of single-qubit gates to use a Waltz X90 based error model
stringset_t x90_gates_;
// Lookup table for gate strings to enum
enum class WaltzGate {id, x, y, z, h, s, sdg, t, tdg, u0, u1, u2, u3};
const static stringmap_t<WaltzGate> waltz_gate_table_;
// Parameterized Gates
enum class ParamGate {u1, u2, u3, r, rx, ry, rz, rxx, ryy, rzz, rzx, cp};
const static stringmap_t<ParamGate> param_gate_table_;
// waltz threshold for applying u1 rotations if |theta - 2n*pi | > threshold
double u1_threshold_ = 1e-10;
// Joint OpSet of all errors
Operations::OpSet opset_;
// Sampling method
Method method_ = Method::circuit;
};
//=========================================================================
// Parameterized Gates
//=========================================================================
const stringmap_t<NoiseModel::ParamGate>
NoiseModel::param_gate_table_ = {
{"u", ParamGate::u3},
{"u3", ParamGate::u3},
{"u2", ParamGate::u2},
{"u1", ParamGate::u1},
{"r", ParamGate::r},
{"rx", ParamGate::rx},
{"ry", ParamGate::ry},
{"rz", ParamGate::rz},
{"rxx", ParamGate::rxx},
{"ryy", ParamGate::ryy},
{"rzz", ParamGate::rzz},
{"rzx", ParamGate::rzx},
{"p", ParamGate::u1},
{"cp", ParamGate::cp},
{"cu1", ParamGate::cp}
};
//=========================================================================
// Noise sampling
//=========================================================================
NoiseModel::NoiseOps NoiseModel::sample_noise(const Operations::Op &op,
RngEngine &rng) const {
// Noise operations
NoiseOps noise_ops;
// Look to see if gate is a waltz gate for this error model
// NOTE this is deprecated and waltz gate noise sampling should be removed
auto it = x90_gates_.find(op.name);
if (it == x90_gates_.end()) {
// Non-X90 based gate, run according to base model
noise_ops = sample_noise_helper(op, rng);
} else {
// Decompose ops in terms of their waltz implementation
auto gate = waltz_gate_table_.find(op.name);
if (gate != waltz_gate_table_.end()) {
switch (gate->second) {
case WaltzGate::u3:
noise_ops = sample_noise_x90_u3(op.qubits[0],
op.params[0], op.params[1], op.params[2],
rng);
break;
case WaltzGate::u2:
noise_ops = sample_noise_x90_u2(op.qubits[0],
op.params[0], op.params[1],
rng);
break;
case WaltzGate::x:
noise_ops = sample_noise_x90_u3(op.qubits[0], M_PI, 0., M_PI, rng);
break;
case WaltzGate::y:
noise_ops = sample_noise_x90_u3(op.qubits[0], M_PI, 0.5 * M_PI, 0.5 * M_PI, rng);
break;
case WaltzGate::h:
noise_ops = sample_noise_x90_u2(op.qubits[0], 0., M_PI, rng);
break;
default:
// The rest of the Waltz operations are noise free (u1 only)
noise_ops = {op};
break;
}
} else {
// something went wrong if we end up here
throw std::invalid_argument("Invalid waltz gate.");
}
}
// If original op is conditional, make all the noise operations also conditional
if (op.conditional) {
for (auto& noise_op : noise_ops) {
noise_op.conditional = op.conditional;
noise_op.conditional_reg = op.conditional_reg;
noise_op.bfunc = op.bfunc;
}
}
return noise_ops;
}
Circuit NoiseModel::sample_noise(const Circuit &circ,
RngEngine &rng) const {
bool noise_active = true; // set noise active to on-state
Circuit noisy_circ;
// Copy metadata
noisy_circ.seed = circ.seed;
noisy_circ.shots = circ.shots;
noisy_circ.header = circ.header;
// Reserve double length of ops just to be safe
noisy_circ.ops.reserve(2 * circ.ops.size());
// Sample a noisy realization of the circuit
for (const auto &op: circ.ops) {
switch (op.type) {
// Operations that cannot have noise
case Operations::OpType::barrier:
noisy_circ.ops.push_back(op);
break;
case Operations::OpType::snapshot:
noisy_circ.ops.push_back(op);
break;
case Operations::OpType::kraus:
noisy_circ.ops.push_back(op);
break;
case Operations::OpType::superop:
noisy_circ.ops.push_back(op);
break;
case Operations::OpType::roerror:
noisy_circ.ops.push_back(op);
break;
case Operations::OpType::bfunc:
noisy_circ.ops.push_back(op);
break;
// Switch noise on or off during current circuit sample
case Operations::OpType::noise_switch:
noise_active = static_cast<int>(std::real(op.params[0]));
break;
default:
if (noise_active) {
NoiseOps noisy_op = sample_noise(op, rng);
noisy_circ.ops.insert(noisy_circ.ops.end(), noisy_op.begin(), noisy_op.end());
}
break;
}
}
// Update circuit parameters
noisy_circ.set_params();
return noisy_circ;
}
void NoiseModel::activate_circuit_method() {
method_ = Method::circuit;
}
void NoiseModel::activate_superop_method() {
// Set internal sampling method
method_ = Method::superop;
// Compute superoperators
for (auto& qerror : quantum_errors_) {
qerror.compute_superoperator();
}
}
void NoiseModel::activate_kraus_method() {
// Set internal sampling method
method_ = Method::kraus;
// Compute kraus
for (auto& qerror : quantum_errors_) {
qerror.compute_kraus();
}
}
void NoiseModel::add_readout_error(const ReadoutError &error,
const std::vector<reg_t> &op_qubits) {
// Add roerror to noise model ops
opset_.optypes.insert(Operations::OpType::roerror);
// Add error term as unique pointer
readout_errors_.push_back(error);
// Get position of error in error vector
const auto error_pos = readout_errors_.size() - 1;
// Add error index to the error table
if (op_qubits.empty()) {
readout_error_table_[""].push_back(error_pos);
} else {
for (const auto &qubits : op_qubits) {
readout_error_table_[reg2string(qubits)].push_back(error_pos);
for (const auto &qubit : qubits)
noise_qubits_.insert(qubit);
}
}
}
void NoiseModel::add_quantum_error(const QuantumError &error,
const stringset_t &op_labels,
const std::vector<reg_t> &op_qubits,
const std::vector<reg_t> &noise_qubits) {
// Add error opset to noise model opset
opset_.insert(error.opset());
// Add error to noise model
if (op_qubits.empty()) {
// Add default local error
add_local_quantum_error(error, op_labels, {reg_t()});
} else if (noise_qubits.empty()) {
// Add local error for specific qubits
add_local_quantum_error(error, op_labels, op_qubits);
} else {
// Add non local error for specific qubits and target qubits
add_nonlocal_quantum_error(error, op_labels, op_qubits, noise_qubits);
}
}
void NoiseModel::add_local_quantum_error(const QuantumError &error,
const stringset_t &op_labels,
const std::vector<reg_t> &op_qubits) {
// Turn on local error flag
if (!op_labels.empty()) {
local_quantum_errors_ = true;
}
// Add error term as unique pointer
quantum_errors_.push_back(error);
// Get position of error in error vector
const auto error_pos = quantum_errors_.size() - 1;
// Add error index to the error table
for (const auto &gate: op_labels)
for (const auto &qubits : op_qubits) {
local_quantum_error_table_[gate][reg2string(qubits)].push_back(error_pos);
for (const auto &qubit : qubits)
noise_qubits_.insert(qubit);
}
}
void NoiseModel::add_nonlocal_quantum_error(const QuantumError &error,
const stringset_t &op_labels,
const std::vector<reg_t> &op_qubits,
const std::vector<reg_t> &noise_qubits) {
// Turn on nonlocal error flag
if (!op_labels.empty() && !op_qubits.empty() && !noise_qubits.empty()) {
nonlocal_quantum_errors_ = true;
}
// Add error term as unique pointer
quantum_errors_.push_back(error);
// Get position of error in error vector
const auto error_pos = quantum_errors_.size() - 1;
// Add error index to the error table
for (const auto &gate: op_labels)
for (const auto &qubits_gate : op_qubits) {
for (const auto &qubit : qubits_gate)
noise_qubits_.insert(qubit);
for (const auto &qubits_noise : noise_qubits) {
nonlocal_quantum_error_table_[gate][reg2string(qubits_gate)][reg2string(qubits_noise)].push_back(error_pos);
for (const auto &qubit : qubits_noise)
noise_qubits_.insert(qubit);
}
}
}
NoiseModel::NoiseOps NoiseModel::sample_noise_helper(const Operations::Op &op,
RngEngine &rng) const {
// Return operator set
NoiseOps noise_before;
NoiseOps noise_after;
// Apply local errors first
sample_local_quantum_noise(op, noise_before, noise_after, rng);
// Apply nonlocal errors second
sample_nonlocal_quantum_noise(op, noise_before, noise_after, rng);
// Apply readout error to measure ops
if (op.type == Operations::OpType::measure) {
sample_readout_noise(op, noise_after, rng);
}
// Combine errors
auto &noise_ops = noise_before;
noise_ops.reserve(noise_before.size() + noise_after.size() + 1);
noise_ops.push_back(op);
noise_ops.insert(noise_ops.end(),
std::make_move_iterator(noise_after.begin()),
std::make_move_iterator(noise_after.end()));
if (op.type != Operations::OpType::measure &&
noise_ops.size() == 2 &&
noise_ops[0].qubits == noise_ops[1].qubits) {
// Try and fuse operations
// If either are superoperators combine superoperators
// else if either are unitaries combine unitaries
// otherwise return the full list
auto& first_op = noise_ops[0];
auto& second_op = noise_ops[1];
if (second_op.type == Operations::OpType::superop) {
auto& current = second_op;
const auto mat = op2superop(first_op);
if (!mat.empty()) {
current.mats[0] = current.mats[0] * mat;
return NoiseOps({current});
}
} else if (first_op.type == Operations::OpType::superop) {
auto& current = first_op;
const auto mat = op2superop(second_op);
if (!mat.empty()) {
current.mats[0] = mat * current.mats[0];
return NoiseOps({current});
}
} else if (second_op.type == Operations::OpType::matrix) {
auto& current = noise_before[1];
const auto mat = op2unitary(first_op);
if (!mat.empty()) {
current.mats[0] = current.mats[0] * mat;
return NoiseOps({current});
}
} else if (first_op.type == Operations::OpType::matrix) {
auto& current = first_op;
const auto mat = op2unitary(second_op);
if (!mat.empty()) {
current.mats[0] = mat * current.mats[0];
return NoiseOps({current});
}
}
}
// Otherwise return the list of ops
return noise_before;
}
void NoiseModel::sample_readout_noise(const Operations::Op &op,
NoiseOps &noise_after,
RngEngine &rng) const {
// If no readout errors are defined pass
if (readout_errors_.empty()) {
return;
}
// Check if measure op writes only to memory, or also to registers
// We will use the same error model for both memory and registers
bool has_registers = !op.registers.empty();
//
std::string op_qubits = reg2string(op.qubits);
// Check if the qubits are listed in the readout error model
auto iter_default = readout_error_table_.find(std::string());
// Format qubit sets
std::vector<std::string> qubit_keys;
std::vector<reg_t> memory_sets, registers_sets;
if (readout_error_table_.find(op_qubits) == readout_error_table_.end()) {
// Since measure can be defined on multiple qubits
// but error model may be specified only on single qubits we add
// each one separately. If a multi-qubit model is found for specified
// qubits however, that will be used instead.
for (const auto &q : op.qubits) {
qubit_keys.push_back(std::to_string(q));
}
// Add the classical register sets for measure ops
for (const auto &q : op.memory) {
memory_sets.push_back({q});
}
if (has_registers) {
for (const auto &q : op.registers) {
registers_sets.push_back({q});
}
}
} else {
// for gate operations we use the qubits as specified
qubit_keys.push_back(op_qubits);
memory_sets.push_back(op.memory);
if (has_registers)
registers_sets.push_back(op.registers);
}
// Iterate over qubits
for (size_t qs=0; qs < qubit_keys.size(); ++qs) {
auto iter_qubits = readout_error_table_.find(qubit_keys[qs]);
if (iter_qubits != readout_error_table_.end() ||
iter_default != readout_error_table_.end()) {
auto &error_positions = (iter_qubits != readout_error_table_.end())
? iter_qubits->second
: iter_default->second;
for (auto &pos : error_positions) {
// Sample Readout error
auto noise_ops = readout_errors_[pos].sample_noise(memory_sets[qs], rng);
if (has_registers) {
for (auto& noise_op: noise_ops) {
noise_op.registers = registers_sets[qs];
}
}
// Add noise after the error
noise_after.insert(noise_after.end(), noise_ops.begin(), noise_ops.end());
}
}
}
}
void NoiseModel::sample_local_quantum_noise(const Operations::Op &op,
NoiseOps &noise_before,
NoiseOps &noise_after,
RngEngine &rng) const {
// If no errors are defined pass
if (local_quantum_errors_ == false)
return;
// Get op name, or label if it is a gate or unitary matrix
std::string name = (op.type == Operations::OpType::matrix ||
op.type == Operations::OpType::gate)
? op.string_params[0]
: op.name;
// Check if op is a measure or reset
bool is_measure_or_reset = (op.type == Operations::OpType::measure ||
op.type == Operations::OpType::reset);
// Convert qubits to string for table lookup
std::string op_qubits = reg2string(op.qubits);
// Get the qubit error map for gate name
auto iter = local_quantum_error_table_.find(name);
if (iter != local_quantum_error_table_.end()) {
// Check if the qubits are listed in the inner model
const auto qubit_map = iter->second;
// Get the default qubit model in case a specific qubit model is not found
// The default model is stored under the empty key string ""
auto iter_default = qubit_map.find(std::string());
// Format qubit sets
std::vector<std::string> qubit_keys;
if (is_measure_or_reset && qubit_map.find(op_qubits) == qubit_map.end()) {
// Since measure and reset ops can be defined on multiple qubits
// but error model may be specified only on single qubits we add
// each one separately. If a multi-qubit model is found for specified
// qubits however, that will be used instead.
for (const auto &q : op.qubits) {
qubit_keys.push_back(std::to_string(q) + std::string(","));
}
} else {
// for gate operations we use the qubits as specified
qubit_keys.push_back(op_qubits);
}
for(auto qubit_key: qubit_keys){
auto iter_qubits = qubit_map.find(qubit_key);
if (iter_qubits != qubit_map.end() ||
iter_default != qubit_map.end()) {
auto &error_positions = (iter_qubits != qubit_map.end())
? iter_qubits->second
: iter_default->second;
for (auto &pos : error_positions) {
auto noise_ops = quantum_errors_[pos].sample_noise(string2reg(qubit_key), rng, method_);
// Duplicate same sampled error operations
if (quantum_errors_[pos].errors_after())
noise_after.insert(noise_after.end(), noise_ops.begin(), noise_ops.end());
else
noise_before.insert(noise_before.end(), noise_ops.begin(), noise_ops.end());
}
}
}
}
}
void NoiseModel::sample_nonlocal_quantum_noise(const Operations::Op &op,
NoiseOps &noise_before,
NoiseOps &noise_after,
RngEngine &rng) const {
// If no errors are defined pass
if (nonlocal_quantum_errors_ == false)
return;
// Get op name, or label if it is a gate or unitary matrix
std::string name = (op.type == Operations::OpType::matrix ||
op.type == Operations::OpType::gate)
? op.string_params[0]
: op.name;
// Convert qubits to string for table lookup
std::string qubits_str = reg2string(op.qubits);
// Get the inner error map for gate name
auto iter = nonlocal_quantum_error_table_.find(name);
if (iter != nonlocal_quantum_error_table_.end()) {
const auto qubit_map = iter->second;
// Format qubit sets
std::vector<std::string> qubit_keys;
if ((op.type == Operations::OpType::measure || op.type == Operations::OpType::reset)
&& qubit_map.find(qubits_str) == qubit_map.end()) {
// Since measure and reset ops can be defined on multiple qubits
// but error model may be specified only on single qubits we add
// each one separately. If a multi-qubit model is found for specified
// qubits however, that will be used instead.
for (const auto &q : op.qubits)
qubit_keys.push_back(std::to_string(q));
} else {
// for gate operations we use the qubits as specified
qubit_keys.push_back(reg2string(op.qubits));
}
for (const auto &qubits: qubit_keys) {
// Check if the qubits are listed in the inner model
auto iter_qubits = qubit_map.find(qubits);
if (iter_qubits != qubit_map.end()) {
for (auto &target_pair : iter_qubits->second) {
auto &target_qubits = target_pair.first;
auto &error_positions = target_pair.second;
for (auto &pos : error_positions) {
auto ops = quantum_errors_[pos].sample_noise(string2reg(target_qubits), rng,
method_);
if (quantum_errors_[pos].errors_after())
noise_after.insert(noise_after.end(), ops.begin(), ops.end());
else
noise_before.insert(noise_before.end(), ops.begin(), ops.end());
}
}
}
}
}
}
const stringmap_t<NoiseModel::WaltzGate>
NoiseModel::waltz_gate_table_ = {
{"u3", WaltzGate::u3}, {"u2", WaltzGate::u2}, {"u1", WaltzGate::u1}, {"u0", WaltzGate::u0},
{"id", WaltzGate::id}, {"x", WaltzGate::x}, {"y", WaltzGate::y}, {"z", WaltzGate::z},
{"h", WaltzGate::h}, {"s", WaltzGate::s}, {"sdg", WaltzGate::sdg},
{"t", WaltzGate::t}, {"tdg", WaltzGate::tdg}
};
NoiseModel::NoiseOps NoiseModel::sample_noise_x90_u3(uint_t qubit,
complex_t theta,
complex_t phi,
complex_t lambda,
RngEngine &rng) const {
// sample noise for single X90
const auto x90 = Operations::make_unitary({qubit}, Linalg::Matrix::X90, "x90");
switch (method_) {
case Method::superop: {
// The first element of the sample should be the superoperator to combine
auto sample = sample_noise_helper(x90, rng);
// The first element of the sample should be the superoperator to combine
if (sample[0].type != Operations::OpType::superop) {
throw std::runtime_error("Sampling superoperator noise failed.");
}
cmatrix_t& current = sample[0].mats[0];
// Combine with middle u1 gate with two noisy x90 superops
auto mat = Linalg::Matrix::u1(theta + M_PI);
auto super = Utils::tensor_product(AER::Utils::conjugate(mat), mat);
current = current * super * current;
// Prepend with first u1 matrix with superop
mat = Linalg::Matrix::u1(lambda);
super = Utils::tensor_product(AER::Utils::conjugate(mat),
mat);
current = current * super;
// Append third u1 matrix with superop
mat = Linalg::Matrix::u1(phi + M_PI);
super = Utils::tensor_product(AER::Utils::conjugate(mat), mat);
current = super * current;
return sample;
}
default: {
NoiseOps ret;
if (std::abs(lambda) > u1_threshold_
&& std::abs(lambda - 2 * M_PI) > u1_threshold_
&& std::abs(lambda + 2 * M_PI) > u1_threshold_) {
ret.push_back(Operations::make_u1(qubit, lambda)); // add 1st U1
}
auto sample = sample_noise_helper(x90, rng); // sample noise for 1st X90
ret.insert(ret.end(), sample.begin(), sample.end()); // add 1st noisy X90
if (std::abs(theta + M_PI) > u1_threshold_
&& std::abs(theta - M_PI) > u1_threshold_) {
ret.push_back(Operations::make_u1(qubit, theta + M_PI)); // add 2nd U1
}
sample = sample_noise_helper(x90, rng); // sample noise for 2nd X90
ret.insert(ret.end(), sample.begin(), sample.end()); // add 2nd noisy X90
if (std::abs(phi + M_PI) > u1_threshold_
&& std::abs(phi - M_PI) > u1_threshold_) {
ret.push_back(Operations::make_u1(qubit, phi + M_PI)); // add 3rd U1
}
return ret;
}
}
}
NoiseModel::NoiseOps NoiseModel::sample_noise_x90_u2(uint_t qubit,
complex_t phi,
complex_t lambda,
RngEngine &rng) const {
// sample noise for single X90
const auto x90 = Operations::make_unitary({qubit}, Linalg::Matrix::X90, "x90");
auto sample = sample_noise_helper(x90, rng);
switch (method_) {
case Method::superop: {
// The first element of the sample should be the superoperator to combine
if (sample[0].type != Operations::OpType::superop) {
throw std::runtime_error("Sampling superoperator noise failed.");
}
cmatrix_t ¤t = sample[0].mats[0];
// Combine first u1 matrix with superop
auto mat = Linalg::Matrix::u1(lambda - 0.5 * M_PI);
auto super = Utils::tensor_product(AER::Utils::conjugate(mat),
mat);
current = current * super;
// Combine second u1 matrix with superop
mat = Linalg::Matrix::u1(phi + 0.5 * M_PI);
super = Utils::tensor_product(AER::Utils::conjugate(mat), mat);
current = super * current;
return sample;
}
default: {
NoiseOps ret;
// Standard method doesn't combine any ops
if (std::abs(lambda - 0.5 * M_PI) > u1_threshold_) {
// add 1st u1
ret.push_back(Operations::make_u1(qubit, lambda - 0.5 * M_PI));
}
// add 1st noisy x90
ret.insert(ret.end(), sample.begin(), sample.end());
if (std::abs(phi + 0.5 * M_PI) > u1_threshold_) {
// add 2nd u1
ret.push_back(Operations::make_u1(qubit, phi + 0.5 * M_PI));
}
return ret;
}
}
}
cmatrix_t NoiseModel::op2superop(const Operations::Op &op) const {
switch (op.type) {
case Operations::OpType::superop:
return op.mats[0];
case Operations::OpType::kraus: {
return Utils::kraus_superop(op.mats);
}
case Operations::OpType::reset:
return Linalg::SMatrix::reset(1ULL << op.qubits.size());
case Operations::OpType::matrix:
return Utils::unitary_superop(op.mats[0]);
case Operations::OpType::gate: {
auto it = param_gate_table_.find(op.name);
if (it != param_gate_table_.end()) {
// Get parameterized gate superop
switch (it -> second) {
case ParamGate::u1:
return Linalg::SMatrix::u1(op.params[0]);
case ParamGate::u2:
return Linalg::SMatrix::u2(op.params[0], op.params[1]);
case ParamGate::u3:
return Linalg::SMatrix::u3(op.params[0], op.params[1], op.params[2]);
case ParamGate::r:
return Linalg::SMatrix::r(op.params[0], op.params[1]);
case ParamGate::rx:
return Linalg::SMatrix::rx(op.params[0]);
case ParamGate::ry:
return Linalg::SMatrix::ry(op.params[0]);
case ParamGate::rz:
return Linalg::SMatrix::rz(op.params[0]);
case ParamGate::rxx:
return Linalg::SMatrix::rxx(op.params[0]);
case ParamGate::ryy:
return Linalg::SMatrix::ryy(op.params[0]);
case ParamGate::rzz:
return Linalg::SMatrix::rzz(op.params[0]);
case ParamGate::rzx:
return Linalg::SMatrix::rzx(op.params[0]);
case ParamGate::cp:
return Linalg::SMatrix::cphase(op.params[0]);
}
} else {
// Check if we can convert this gate to a standard superoperator matrix
if (Linalg::SMatrix::allowed_name(op.name)) {
return Linalg::SMatrix::from_name(op.name);
}
}
}
default:
return cmatrix_t();
}
}
cmatrix_t NoiseModel::op2unitary(const Operations::Op &op) const {
switch (op.type) {
case Operations::OpType::matrix:
return op.mats[0];
case Operations::OpType::gate: {
auto it = param_gate_table_.find(op.name);
if (it != param_gate_table_.end()) {
// Get parameterized gate superop
switch (it -> second) {
case ParamGate::u1:
return Linalg::Matrix::u1(op.params[0]);
case ParamGate::u2:
return Linalg::Matrix::u2(op.params[0], op.params[1]);
case ParamGate::u3:
return Linalg::Matrix::u3(op.params[0], op.params[1], op.params[2]);
case ParamGate::r:
return Linalg::Matrix::r(op.params[0], op.params[1]);
case ParamGate::rx:
return Linalg::Matrix::rx(op.params[0]);
case ParamGate::ry:
return Linalg::Matrix::ry(op.params[0]);
case ParamGate::rz:
return Linalg::Matrix::rz(op.params[0]);
case ParamGate::rxx:
return Linalg::Matrix::rxx(op.params[0]);
case ParamGate::ryy:
return Linalg::Matrix::ryy(op.params[0]);
case ParamGate::rzz:
return Linalg::Matrix::rzz(op.params[0]);
case ParamGate::rzx:
return Linalg::Matrix::rzx(op.params[0]);
case ParamGate::cp:
return Linalg::Matrix::cphase(op.params[0]);
}
} else {
// Check if we can convert this gate to a standard superoperator matrix
if (Linalg::Matrix::allowed_name(op.name)) {
return Linalg::Matrix::from_name(op.name);
}
}
}
default:
return cmatrix_t();
}
}
std::string NoiseModel::reg2string(const reg_t ®) const {
std::stringstream result;
std::copy(reg.begin(), reg.end(), std::ostream_iterator<reg_t::value_type>(result, ","));
return result.str();
}
reg_t NoiseModel::string2reg(std::string s) const {
reg_t result;
size_t pos = 0;
while ((pos = s.find(",")) != std::string::npos) {
result.push_back(std::stoi(s.substr(0, pos)));
s.erase(0, pos + 1);
}
return result;
}
//=========================================================================
// Qubit Remapping
//=========================================================================
std::set<uint_t> NoiseModel::nonlocal_noise_qubits(const std::string label,
const reg_t& qubits) const {
std::set<uint_t> all_noise_qubits;
// Check if label has noise
const auto outer_it = nonlocal_quantum_error_table_.find(label);
if (outer_it != nonlocal_quantum_error_table_.end()) {
const auto outer_table = outer_it->second;
const auto it = outer_table.find(reg2string(qubits));
// Check if label on specified qubits has noise
if (it != outer_table.end()) {
// Add all noise qubit errors to the return value
const auto inner_table = it->second;
for (const auto &pair : inner_table) {
auto noise_qubits = string2reg(pair.first);
for (const auto &qubit : noise_qubits) {
all_noise_qubits.insert(qubit);
}
}
}
}
return all_noise_qubits;
}
std::string NoiseModel::remap_string(const std::string key,
const std::unordered_map<uint_t, uint_t> &mapping) const{
reg_t qubits = string2reg(key);
for (size_t j=0; j<qubits.size(); j++)
qubits[j] = mapping.at(qubits[j]);
return reg2string(qubits);
}
void NoiseModel::remap_qubits(const std::unordered_map<uint_t, uint_t> &mapping) {
// If noise model is ideal we have no need to remap
if (is_ideal())
return;
// We only need the mapping for qubits in the noise model.
// We add qubits not specified in the mapping as trivial mapping to themselves
// We also validate the mapping while building the full mapping
std::unordered_map<uint_t, uint_t> full_mapping = mapping;
// Add noise qubits not specified in mapping
for (const auto &qubit : noise_qubits_) {
if (full_mapping.find(qubit) == full_mapping.end()) {
full_mapping[qubit] = qubit;
}
}
// Check mapping is valid
std::set<uint_t> qubits_in;
std::set<uint_t> qubits_out;
for (const auto &pair: full_mapping) {
qubits_in.insert(pair.first);
qubits_out.insert(pair.second);
}
if (qubits_in != qubits_out) {
std::stringstream msg;
msg << "NoiseModel: invalid qubit re-mapping " << full_mapping;
throw std::invalid_argument(msg.str());
}
// Remap readout error
if (has_readout_errors()) {
inner_table_t new_readout_error_table;
for (const auto &pair : readout_error_table_) {
new_readout_error_table[remap_string(pair.first, full_mapping)] = pair.second;
}
readout_error_table_ = new_readout_error_table;
new_readout_error_table.clear();
}
// Remap local quantum error
if (has_local_quantum_errors()) {
for (auto& outer_pair : local_quantum_error_table_) {
// Get reference to the inner table we need to change the keys for
auto& inner_table = outer_pair.second;
// Make a temporary table to store remapped table
inner_table_t new_table;
for (const auto &inner_pair : inner_table) {
new_table[remap_string(inner_pair.first, full_mapping)] = inner_pair.second;
}
// Replace inner table with the remapped table
inner_table = new_table;
}
}
// Remap nonlocal quantum error
if (has_nonlocal_quantum_errors()) {
for (auto& pair : nonlocal_quantum_error_table_) {
// Get reference to the middle table we need to change the keys for
auto& outer_table = pair.second;
// Make a temporary table to store remapped outer table
outer_table_t new_outer_table;
for (auto& outer_pair : outer_table) {
// Remap inner table
auto& inner_table = outer_pair.second;
inner_table_t new_inner_table;
for (const auto &inner_pair : inner_table) {
new_inner_table[remap_string(inner_pair.first, full_mapping)] = inner_pair.second;
}
// Update outer table with remapped inner table
new_outer_table[remap_string(outer_pair.first, full_mapping)] = new_inner_table;
}
outer_table = new_outer_table;
}
}
}
//=========================================================================
// JSON Conversion
//=========================================================================
/*
Schemas:
{
"error_model": {
"errors": [error js],
"x90_gates": which gates should be implemented as waltz gates and use the "x90" term
}
}
Specific types additional parameters
Quantum Error
{
"type": "qerror",
"operations": ["x", "y", ...], // ops to apply error to
"gate_qubits": [[0], [1]] // error only apples when op is on these qubits (blank for all)
"noise_qubits": [[2], ...] // error term will be applied to these qubits (blank for input qubits)
// if false noise will be applied before op
"probabilities": [p0, p1, ..],
"instructions": [qobj_circuit_instrs0, qobj_circuit_instrs1, ...]
}
Readout Error (note: readout errors can only be local)
{
"type": "roerror",
"operations": ["measure"],
"probabilities": [[P(0|0), P(0|1)], [P(1|0), P(1|1)]]
"gate_qubits": [[0]] // error only apples when op is on these qubits (blank for all)
}
*/
void NoiseModel::load_from_json(const json_t &js) {
// If JSON is empty stop
if (js.empty())
return;
// Check JSON is an object
if (!js.is_object()) {
throw std::invalid_argument("Invalid noise_params JSON: not an object.");
}
// See if any single qubit gates have a waltz error model applied to them
if (JSON::check_key("x90_gates", js)) {
set_x90_gates(js["x90_gates"]);
}
if (JSON::check_key("errors", js)) {
if (!js["errors"].is_array()) {
throw std::invalid_argument("Invalid noise_params JSON: \"error\" field is not a list");
}
for (const auto &gate_js : js["errors"]) {
std::string type;
JSON::get_value(type, "type", gate_js);
stringset_t ops; // want set so ops are unique, and we can pull out measure
JSON::get_value(ops, "operations", gate_js);
std::vector<reg_t> gate_qubits;
JSON::get_value(gate_qubits, "gate_qubits", gate_js);
std::vector<reg_t> noise_qubits;
JSON::get_value(noise_qubits, "noise_qubits", gate_js);
// We treat measure as a separate error op so that it can be applied before
// the measure operation, rather than after like the other gates
if (ops.find("measure") != ops.end() && type != "roerror") {
ops.erase("measure"); // remove measure from set of ops
if (type != "qerror")
throw std::invalid_argument("NoiseModel: Invalid noise type (" + type + ")");
QuantumError error;
error.load_from_json(gate_js);
error.set_errors_before(); // set errors before the op
add_quantum_error(error, {"measure"}, gate_qubits, noise_qubits);
}
// Load the remaining ops as errors that come after op
if (type == "qerror") {
QuantumError error;
error.load_from_json(gate_js);
add_quantum_error(error, ops, gate_qubits, noise_qubits);
} else if (type == "roerror") {
// We do not allow non-local readout errors
if (!noise_qubits.empty()) {
throw std::invalid_argument("Readout error must be a local error");
}
ReadoutError error; // readout error goes after
error.load_from_json(gate_js);
add_readout_error(error, gate_qubits);
}else {
throw std::invalid_argument("NoiseModel: Invalid noise type (" + type + ")");
}
}
}
}
inline void from_json(const json_t &js, NoiseModel &model) {
model = NoiseModel(js);
}
//-------------------------------------------------------------------------
} // end namespace Noise
//-------------------------------------------------------------------------
} // end namespace AER
//-------------------------------------------------------------------------
#endif
|
[
"edwin.agnew@duke.edu"
] |
edwin.agnew@duke.edu
|
dbca024b25bc1948e0f5ef769bc23cad9e3258b7
|
0447f03d44890be87c5595d6b3a351c6d87d1395
|
/Rec/bzoj3998.cpp
|
8ee4189dc6caccebfb6c3230fac2cbb341ab442e
|
[] |
no_license
|
Jupitercal/ProblemsSolvedCode
|
3e27aed6256e10e11ba7ed5d4cc6c12a344b4c19
|
8653f5b3f97e8e41eedf7e1f5bfdb4a128fc4a28
|
refs/heads/master
| 2022-08-13T21:54:50.798759
| 2020-05-24T15:25:18
| 2020-05-24T15:25:18
| 266,562,033
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,909
|
cpp
|
#include<bits/stdc++.h>
#define N 520000
#define INF 0x3f3f3f3f
typedef long long LL;
char s[N];
int mx[N*2],Len;
int len[N<<1],fa[N<<1],son[N<<1][26];
int size,last,root,anslen;
int a[N<<1],c[N<<1],cnt[N<<1],t,k,sum[N<<1];
LL F[N<<1];
char ans[N];
void Init(){root=size=last=1;}
void Extend(int c){
int end=++size,tmp=last;
len[end]=len[tmp]+1;
while(tmp&&!son[tmp][c]){
son[tmp][c]=end;
tmp=fa[tmp];
}
if(!tmp) fa[end]=root;
else{
int ne=son[tmp][c];
if(len[tmp]+1==len[ne]) fa[end]=ne;
else{
int np=++size;
memcpy(son[np],son[ne],sizeof(son[ne]));
len[np]=len[tmp]+1;
fa[np]=fa[ne];
fa[end]=fa[ne]=np;
while(tmp&&son[tmp][c]==ne){
son[tmp][c]=np;
tmp=fa[tmp];
}
}
}
last=end;
cnt[last]=1;
}
void Radixsort(){
for(int i=1;i<=size;i++) c[len[i]]++;
for(int i=1;i<=Len;i++) c[i]+=c[i-1];
for(int i=size;i>=1;i--) a[c[len[i]]--]=i;
}
void dfs(int x,int len){
if (k<=0)return;
for (int i=0;i<26;i++){
if (!son[x][i])continue;
if (sum[son[x][i]]>=k){
ans[len]='a'+i;
ans[len+1]='\0';
k-=cnt[son[x][i]];
//printf("%c %d %d\n",'a'+i,len,k);
dfs(son[x][i],len+1);
return ;
}else k-=sum[son[x][i]];
}
}
int main(){
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
scanf("%s",s);
Len=strlen(s);
scanf("%d%d",&t,&k);
Init();
for (int i=0;i<Len;i++)Extend(s[i]-'a');
Radixsort();
for (int i=size;i>=1;i--){
if (t==1)cnt[fa[a[i]]]+=cnt[a[i]];
else cnt[a[i]]=1;
}
cnt[1]=0;
for (int i=size;i>=1;i--){
int p=a[i];
sum[p]=cnt[p];
for (int j=0;j<26;j++)sum[p]+=sum[son[p][j]];
}
//printf("%d\n",sum[1]);
if (sum[1]>=k){
dfs(root,0);
//printf("\n");
printf("%s",ans);
}
else printf("-1");
//if (cnt[1]>=k)printf("%s",ans);
return 0;
}
|
[
"719650063@qq.com"
] |
719650063@qq.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.