blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
540baddf25a1bfd01e6d7fa02fd2d9b9f1ea9c33 | e911a874b4feb6bdf275d65c59887047319dc432 | /src/rpc/net.cpp | bfb1c53fab9ea6a12d2f7dd50429423675908b39 | [
"MIT"
] | permissive | ida-pay/idapay-refresh | c34742aa926623847aa792fdc5ba9baa26de8d0b | fa4c24c819ad2c211895930fc1f08a1811a4da65 | refs/heads/master | 2021-07-11T18:45:16.607382 | 2020-07-06T10:45:46 | 2020-07-06T10:45:46 | 161,047,918 | 1 | 4 | MIT | 2020-07-06T10:45:47 | 2018-12-09T14:30:08 | C++ | UTF-8 | C++ | false | false | 26,453 | cpp | // Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpc/server.h"
#include "chainparams.h"
#include "clientversion.h"
#include "validation.h"
#include "net.h"
#include "net_processing.h"
#include "netbase.h"
#include "protocol.h"
#include "sync.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"
#include <boost/foreach.hpp>
#include <univalue.h>
using namespace std;
UniValue getconnectioncount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"\nReturns the number of connections to other nodes.\n"
"\nResult:\n"
"n (numeric) The connection count\n"
"\nExamples:\n"
+ HelpExampleCli("getconnectioncount", "")
+ HelpExampleRpc("getconnectioncount", "")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
return (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
}
UniValue ping(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"ping\n"
"\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
"\nExamples:\n"
+ HelpExampleCli("ping", "")
+ HelpExampleRpc("ping", "")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
// Request that each node send a ping during next message processing pass
g_connman->ForEachNode([](CNode* pnode) {
pnode->fPingQueued = true;
});
return NullUniValue;
}
UniValue getpeerinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"\nReturns data about each connected network node as a json array of objects.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"id\": n, (numeric) Peer index\n"
" \"addr\":\"host:port\", (string) The ip address and port of the peer\n"
" \"addrlocal\":\"ip:port\", (string) local address\n"
" \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
" \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n"
" \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
" \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
" \"bytessent\": n, (numeric) The total bytes sent\n"
" \"bytesrecv\": n, (numeric) The total bytes received\n"
" \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"timeoffset\": ttt, (numeric) The time offset in seconds\n"
" \"pingtime\": n, (numeric) ping time (if available)\n"
" \"minping\": n, (numeric) minimum observed ping time (if any at all)\n"
" \"pingwait\": n, (numeric) ping wait (if non-zero)\n"
" \"version\": v, (numeric) The peer version, such as 7001\n"
" \"subver\": \"/IDAPay Core:x.x.x/\", (string) The string version\n"
" \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n"
" \"startingheight\": n, (numeric) The starting height (block) of the peer\n"
" \"banscore\": n, (numeric) The ban score\n"
" \"synced_headers\": n, (numeric) The last header we have in common with this peer\n"
" \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n"
" \"inflight\": [\n"
" n, (numeric) The heights of blocks we're currently asking from this peer\n"
" ...\n"
" ]\n"
" \"bytessent_per_msg\": {\n"
" \"addr\": n, (numeric) The total bytes sent aggregated by message type\n"
" ...\n"
" }\n"
" \"bytesrecv_per_msg\": {\n"
" \"addr\": n, (numeric) The total bytes received aggregated by message type\n"
" ...\n"
" }\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getpeerinfo", "")
+ HelpExampleRpc("getpeerinfo", "")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
vector<CNodeStats> vstats;
g_connman->GetNodeStats(vstats);
UniValue ret(UniValue::VARR);
BOOST_FOREACH(const CNodeStats& stats, vstats) {
UniValue obj(UniValue::VOBJ);
CNodeStateStats statestats;
bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
obj.push_back(Pair("id", stats.nodeid));
obj.push_back(Pair("addr", stats.addrName));
if (!(stats.addrLocal.empty()))
obj.push_back(Pair("addrlocal", stats.addrLocal));
obj.push_back(Pair("services", strprintf("%016x", stats.nServices)));
obj.push_back(Pair("relaytxes", stats.fRelayTxes));
obj.push_back(Pair("lastsend", stats.nLastSend));
obj.push_back(Pair("lastrecv", stats.nLastRecv));
obj.push_back(Pair("bytessent", stats.nSendBytes));
obj.push_back(Pair("bytesrecv", stats.nRecvBytes));
obj.push_back(Pair("conntime", stats.nTimeConnected));
obj.push_back(Pair("timeoffset", stats.nTimeOffset));
if (stats.dPingTime > 0.0)
obj.push_back(Pair("pingtime", stats.dPingTime));
if (stats.dMinPing < std::numeric_limits<int64_t>::max()/1e6)
obj.push_back(Pair("minping", stats.dMinPing));
if (stats.dPingWait > 0.0)
obj.push_back(Pair("pingwait", stats.dPingWait));
obj.push_back(Pair("version", stats.nVersion));
// Use the sanitized form of subver here, to avoid tricksy remote peers from
// corrupting or modifiying the JSON output by putting special characters in
// their ver message.
obj.push_back(Pair("subver", stats.cleanSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
if (fStateStats) {
obj.push_back(Pair("banscore", statestats.nMisbehavior));
obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
UniValue heights(UniValue::VARR);
BOOST_FOREACH(int height, statestats.vHeightInFlight) {
heights.push_back(height);
}
obj.push_back(Pair("inflight", heights));
}
obj.push_back(Pair("whitelisted", stats.fWhitelisted));
UniValue sendPerMsgCmd(UniValue::VOBJ);
BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapSendBytesPerMsgCmd) {
if (i.second > 0)
sendPerMsgCmd.push_back(Pair(i.first, i.second));
}
obj.push_back(Pair("bytessent_per_msg", sendPerMsgCmd));
UniValue recvPerMsgCmd(UniValue::VOBJ);
BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapRecvBytesPerMsgCmd) {
if (i.second > 0)
recvPerMsgCmd.push_back(Pair(i.first, i.second));
}
obj.push_back(Pair("bytesrecv_per_msg", recvPerMsgCmd));
ret.push_back(obj);
}
return ret;
}
UniValue addnode(const UniValue& params, bool fHelp)
{
string strCommand;
if (params.size() == 2)
strCommand = params[1].get_str();
if (fHelp || params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"addnode \"node\" \"add|remove|onetry\"\n"
"\nAttempts add or remove a node from the addnode list.\n"
"Or try a connection to a node once.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
"2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n"
"\nExamples:\n"
+ HelpExampleCli("addnode", "\"192.168.0.6:19285\" \"onetry\"")
+ HelpExampleRpc("addnode", "\"192.168.0.6:19285\", \"onetry\"")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
string strNode = params[0].get_str();
if (strCommand == "onetry")
{
CAddress addr;
g_connman->OpenNetworkConnection(addr, NULL, strNode.c_str());
return NullUniValue;
}
if (strCommand == "add")
{
if(!g_connman->AddNode(strNode))
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
}
else if(strCommand == "remove")
{
if(!g_connman->RemoveAddedNode(strNode))
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
}
return NullUniValue;
}
UniValue disconnectnode(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"disconnectnode \"node\" \n"
"\nImmediately disconnects from the specified node.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
"\nExamples:\n"
+ HelpExampleCli("disconnectnode", "\"192.168.0.6:19285\"")
+ HelpExampleRpc("disconnectnode", "\"192.168.0.6:19285\"")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
bool ret = g_connman->DisconnectNode(params[0].get_str());
if (!ret)
throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes");
return NullUniValue;
}
UniValue getaddednodeinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getaddednodeinfo dummy ( \"node\" )\n"
"\nReturns information about the given added node, or all added nodes\n"
"(note that onetry addnodes are not listed here)\n"
"\nArguments:\n"
"1. dummy (boolean, required) Kept for historical purposes but ignored\n"
"2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"addednode\" : \"192.168.0.201\", (string) The node ip address or name (as provided to addnode)\n"
" \"connected\" : true|false, (boolean) If connected\n"
" \"addresses\" : [ (list of objects) Only when connected = true\n"
" {\n"
" \"address\" : \"192.168.0.201:19285\", (string) The idapay server IP and port we're connected to\n"
" \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
" }\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddednodeinfo", "true")
+ HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"")
+ HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo();
if (params.size() == 2) {
bool found = false;
for (const AddedNodeInfo& info : vInfo) {
if (info.strAddedNode == params[1].get_str()) {
vInfo.assign(1, info);
found = true;
break;
}
}
if (!found) {
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
}
}
UniValue ret(UniValue::VARR);
for (const AddedNodeInfo& info : vInfo) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("addednode", info.strAddedNode));
obj.push_back(Pair("connected", info.fConnected));
UniValue addresses(UniValue::VARR);
if (info.fConnected) {
UniValue address(UniValue::VOBJ);
address.push_back(Pair("address", info.resolvedAddress.ToString()));
address.push_back(Pair("connected", info.fInbound ? "inbound" : "outbound"));
addresses.push_back(address);
}
obj.push_back(Pair("addresses", addresses));
ret.push_back(obj);
}
return ret;
}
UniValue getnettotals(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getnettotals\n"
"\nReturns information about network traffic, including bytes in, bytes out,\n"
"and current time.\n"
"\nResult:\n"
"{\n"
" \"totalbytesrecv\": n, (numeric) Total bytes received\n"
" \"totalbytessent\": n, (numeric) Total bytes sent\n"
" \"timemillis\": t, (numeric) Total cpu time\n"
" \"uploadtarget\":\n"
" {\n"
" \"timeframe\": n, (numeric) Length of the measuring timeframe in seconds\n"
" \"target\": n, (numeric) Target in bytes\n"
" \"target_reached\": true|false, (boolean) True if target is reached\n"
" \"serve_historical_blocks\": true|false, (boolean) True if serving historical blocks\n"
" \"bytes_left_in_cycle\": t, (numeric) Bytes left in current time cycle\n"
" \"time_left_in_cycle\": t (numeric) Seconds left in current time cycle\n"
" }\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getnettotals", "")
+ HelpExampleRpc("getnettotals", "")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("totalbytesrecv", g_connman->GetTotalBytesRecv()));
obj.push_back(Pair("totalbytessent", g_connman->GetTotalBytesSent()));
obj.push_back(Pair("timemillis", GetTimeMillis()));
UniValue outboundLimit(UniValue::VOBJ);
outboundLimit.push_back(Pair("timeframe", g_connman->GetMaxOutboundTimeframe()));
outboundLimit.push_back(Pair("target", g_connman->GetMaxOutboundTarget()));
outboundLimit.push_back(Pair("target_reached", g_connman->OutboundTargetReached(false)));
outboundLimit.push_back(Pair("serve_historical_blocks", !g_connman->OutboundTargetReached(true)));
outboundLimit.push_back(Pair("bytes_left_in_cycle", g_connman->GetOutboundTargetBytesLeft()));
outboundLimit.push_back(Pair("time_left_in_cycle", g_connman->GetMaxOutboundTimeLeftInCycle()));
obj.push_back(Pair("uploadtarget", outboundLimit));
return obj;
}
static UniValue GetNetworksInfo()
{
UniValue networks(UniValue::VARR);
for(int n=0; n<NET_MAX; ++n)
{
enum Network network = static_cast<enum Network>(n);
if(network == NET_UNROUTABLE)
continue;
proxyType proxy;
UniValue obj(UniValue::VOBJ);
GetProxy(network, proxy);
obj.push_back(Pair("name", GetNetworkName(network)));
obj.push_back(Pair("limited", IsLimited(network)));
obj.push_back(Pair("reachable", IsReachable(network)));
obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string()));
obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials));
networks.push_back(obj);
}
return networks;
}
UniValue getnetworkinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getnetworkinfo\n"
"Returns an object containing various state info regarding P2P networking.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"subversion\": \"/IDAPay Core:x.x.x/\", (string) the server subversion string\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
" \"localrelay\": true|false, (bool) true if transaction relay is requested from peers\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"networkactive\": true|false, (bool) whether p2p networking is enabled\n"
" \"networks\": [ (array) information per network\n"
" {\n"
" \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n"
" \"limited\": true|false, (boolean) is the network limited using -onlynet?\n"
" \"reachable\": true|false, (boolean) is the network reachable?\n"
" \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n"
" }\n"
" ,...\n"
" ],\n"
" \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in " + CURRENCY_UNIT + "/kB\n"
" \"localaddresses\": [ (array) list of local addresses\n"
" {\n"
" \"address\": \"xxxx\", (string) network address\n"
" \"port\": xxx, (numeric) network port\n"
" \"score\": xxx (numeric) relative score\n"
" }\n"
" ,...\n"
" ]\n"
" \"warnings\": \"...\" (string) any network warnings (such as alert messages) \n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getnetworkinfo", "")
+ HelpExampleRpc("getnetworkinfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("subversion", strSubVersion));
obj.push_back(Pair("protocolversion",PROTOCOL_VERSION));
if(g_connman)
obj.push_back(Pair("localservices", strprintf("%016x", g_connman->GetLocalServices())));
obj.push_back(Pair("localrelay", fRelayTxes));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
if (g_connman) {
obj.push_back(Pair("networkactive", g_connman->GetNetworkActive()));
obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
}
obj.push_back(Pair("networks", GetNetworksInfo()));
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
UniValue localAddresses(UniValue::VARR);
{
LOCK(cs_mapLocalHost);
BOOST_FOREACH(const PAIRTYPE(CNetAddr, LocalServiceInfo) &item, mapLocalHost)
{
UniValue rec(UniValue::VOBJ);
rec.push_back(Pair("address", item.first.ToString()));
rec.push_back(Pair("port", item.second.nPort));
rec.push_back(Pair("score", item.second.nScore));
localAddresses.push_back(rec);
}
}
obj.push_back(Pair("localaddresses", localAddresses));
obj.push_back(Pair("warnings", GetWarnings("statusbar")));
return obj;
}
UniValue setban(const UniValue& params, bool fHelp)
{
string strCommand;
if (params.size() >= 2)
strCommand = params[1].get_str();
if (fHelp || params.size() < 2 ||
(strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"setban \"ip(/netmask)\" \"add|remove\" (bantime) (absolute)\n"
"\nAttempts add or remove a IP/Subnet from the banned list.\n"
"\nArguments:\n"
"1. \"ip(/netmask)\" (string, required) The IP/Subnet (see getpeerinfo for nodes ip) with a optional netmask (default is /32 = single ip)\n"
"2. \"command\" (string, required) 'add' to add a IP/Subnet to the list, 'remove' to remove a IP/Subnet from the list\n"
"3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the ip is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n"
"4. \"absolute\" (boolean, optional) If set, the bantime must be a absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
"\nExamples:\n"
+ HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400")
+ HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"")
+ HelpExampleRpc("setban", "\"192.168.0.6\", \"add\" 86400")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
CSubNet subNet;
CNetAddr netAddr;
bool isSubnet = false;
if (params[0].get_str().find("/") != string::npos)
isSubnet = true;
if (!isSubnet) {
CNetAddr resolved;
LookupHost(params[0].get_str().c_str(), resolved, false);
netAddr = resolved;
}
else
LookupSubNet(params[0].get_str().c_str(), subNet);
if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Invalid IP/Subnet");
if (strCommand == "add")
{
if (isSubnet ? g_connman->IsBanned(subNet) : g_connman->IsBanned(netAddr))
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
int64_t banTime = 0; //use standard bantime if not specified
if (params.size() >= 3 && !params[2].isNull())
banTime = params[2].get_int64();
bool absolute = false;
if (params.size() == 4 && params[3].isTrue())
absolute = true;
isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute);
}
else if(strCommand == "remove")
{
if (!( isSubnet ? g_connman->Unban(subNet) : g_connman->Unban(netAddr) ))
throw JSONRPCError(RPC_MISC_ERROR, "Error: Unban failed");
}
return NullUniValue;
}
UniValue listbanned(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listbanned\n"
"\nList all banned IPs/Subnets.\n"
"\nExamples:\n"
+ HelpExampleCli("listbanned", "")
+ HelpExampleRpc("listbanned", "")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
banmap_t banMap;
g_connman->GetBanned(banMap);
UniValue bannedAddresses(UniValue::VARR);
for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++)
{
CBanEntry banEntry = (*it).second;
UniValue rec(UniValue::VOBJ);
rec.push_back(Pair("address", (*it).first.ToString()));
rec.push_back(Pair("banned_until", banEntry.nBanUntil));
rec.push_back(Pair("ban_created", banEntry.nCreateTime));
rec.push_back(Pair("ban_reason", banEntry.banReasonToString()));
bannedAddresses.push_back(rec);
}
return bannedAddresses;
}
UniValue clearbanned(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"clearbanned\n"
"\nClear all banned IPs.\n"
"\nExamples:\n"
+ HelpExampleCli("clearbanned", "")
+ HelpExampleRpc("clearbanned", "")
);
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
g_connman->ClearBanned();
return NullUniValue;
}
UniValue setnetworkactive(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1) {
throw runtime_error(
"setnetworkactive true|false\n"
"Disable/enable all p2p network activity."
);
}
if (!g_connman) {
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
}
g_connman->SetNetworkActive(params[0].get_bool());
return g_connman->GetNetworkActive();
}
| [
"[email protected]"
] | |
78ff070017ec8fb2e8d6f511e0a13a2087f58d6e | b909c2b9958448671e6440069f2b057e8fd12126 | /최소 스패닝 트리/1922.cpp | a7f3d7f15bf9fb7af7852d051b944beccba295c7 | [] | no_license | sunjungAn/C-study | 0c4dba0737edafa00fa1438fb11a38320a00fbaa | 8d66a51baee95e7299a8c03c529fea86591188e7 | refs/heads/master | 2022-12-04T07:14:33.618898 | 2020-08-20T15:16:09 | 2020-08-20T15:16:09 | 278,672,402 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,659 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int v, e;
int parent[10002]; //부모를 저장할 리스트
int rank[10002]; //랭크는 다 0으로 초기화
typedef struct edge {
int v1, v2, w, visit=0;
}edge;
vector<edge> vlist;
bool compare(edge a, edge b) //가중치를 기준으로 정렬
{
if (a.w > b.w)
return false;
if (a.w == b.w) {
if (a.v1 > b.v1)
return false;
}
else return true;
}
void input(void)
{
int v1, v2, w;
edge edg;
for (int i = 0; i < e; i++)
{
cin >> v1 >> v2 >> w;
edg.v1 = v1; edg.v2 = v2; edg.w = w;
vlist.push_back(edg);
}
sort(vlist.begin(), vlist.end(), compare); // 가중치를 기준으로 정렬
}
int find(int v)
{
if (parent[v] == v) //값과 부모가 같으면 그냥 그대로 값 리턴
return v;
else
return find(parent[v]); // 아니면 부모로 find호출
}
void union_(int v1, int v2) { //union find계산 순서
int x, y;
x = find(v1);
y = find(v2);
if (x < y) //더 작은 값이 부모가 된다. +랭크 계산에서는 랭크에다 +1씩해줌
parent[y] = x;
else
parent[x] = y;
}
int main(void)
{
cin >> v >> e;
int answer = 0;
for (int i = 1; i <= v; i++)
{
parent[i] = i; //부모 배열 초기화
}
input();
for (int i = 0; i < vlist.size(); i++) //일단은 모든 간선을 다 돈다
{
if (find(vlist[i].v1) != find(vlist[i].v2) && vlist[i].visit==0) // 부모가 같으면 사이클 발생 --> 다음으로 작은 가중치를 가진 간선으로 넘어감
{
vlist[i].visit = 1;
union_(vlist[i].v1, vlist[i].v2);
answer += vlist[i].w; //길이 증가
}
}
cout << answer << '\n';
return 0;
} | [
"[email protected]"
] | |
d83696545f645cfe95046a523030845cd925ab1d | 3047545349bf224a182b2c33bf1f110aef1ce9b6 | /Transims60/Converge_Service/Get_Trip_Gap.cpp | a731f934f9d772667b4803808fe5869d14fe52bd | [] | no_license | qingswu/Transim | 585afe71d9666557cff53f6683cf54348294954c | f182d1639a4db612dd7b43a379a3fa344c2de9ea | refs/heads/master | 2021-01-10T21:04:50.576267 | 2015-04-08T19:07:28 | 2015-04-08T19:07:28 | 35,232,171 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,071 | cpp | //*********************************************************
// Get_Trip_Gap.cpp - process trip gap data
//*********************************************************
#include "Converge_Service.hpp"
//---------------------------------------------------------
// Get_Trip_Gap
//---------------------------------------------------------
double Converge_Service::Get_Trip_Gap (void)
{
int i, num, period;
double diff, imp, sum_diff, total, gap;
bool gap_flag;
Trip_Gap_Map_Itr itr;
Gap_Sum gap_sum;
Doubles period_diff, period_sum;
num = 0;
sum_diff = total = gap = 0.0;
memset (&gap_sum, '\0', sizeof (gap_sum));
gap_flag = (trip_gap_flag || trip_report_flag);
if (gap_flag) {
num = dat->sum_periods.Num_Periods ();
period_diff.assign (num, 0);
period_sum.assign (num, 0);
}
//---- process each trip ----
if (memory_flag) {
Gap_Data_Itr gap_itr;
for (gap_itr = gap_data_array.begin (); gap_itr != gap_data_array.end (); gap_itr++) {
total += imp = gap_itr->current;
sum_diff += diff = abs (imp - gap_itr->previous);
gap_itr->previous = gap_itr->current;
gap_itr->current = 0;
if (trip_report_flag) {
gap_sum.count++;
gap_sum.abs_diff += diff;
gap_sum.diff_sq += diff * diff;
gap_sum.current += imp;
if (imp > 0) {
gap = diff / imp;
if (gap > gap_sum.max_gap) gap_sum.max_gap = gap;
}
}
if (gap_flag) {
period = dat->sum_periods.Period (gap_itr->time);
if (period >= 0) {
period_diff [period] += diff;
period_sum [period] += imp;
}
}
}
} else {
for (i=0; i < num_parts; i++) {
Trip_Gap_Map *trip_gap_map_ptr = trip_gap_map_array [i];
for (itr = trip_gap_map_ptr->begin (); itr != trip_gap_map_ptr->end (); itr++) {
total += imp = itr->second.current;
sum_diff += diff = abs (imp - itr->second.previous);
itr->second.previous = itr->second.current;
itr->second.current = 0;
if (trip_report_flag) {
gap_sum.count++;
gap_sum.abs_diff += diff;
gap_sum.diff_sq += diff * diff;
gap_sum.current += imp;
if (imp > 0) {
gap = diff / imp;
if (gap > gap_sum.max_gap) gap_sum.max_gap = gap;
}
}
if (gap_flag) {
period = dat->sum_periods.Period (itr->second.time);
if (period >= 0) {
period_diff [period] += diff;
period_sum [period] += imp;
}
}
}
}
}
//---- process the iteration data ----
if (total > 0) {
gap = sum_diff / total;
} else if (sum_diff > 0) {
gap = 1.0;
} else {
gap = 0.0;
}
//---- write the trip gap file ----
if (gap_flag) {
for (i=0; i < num; i++) {
imp = period_sum [i];
diff = period_diff [i];
if (imp > 0) {
diff = diff / imp;
} else if (diff > 0) {
diff = 1.0;
} else {
diff = 0.0;
}
Write_Trip_Gap (diff);
}
Write_Trip_Gap (gap, true);
if (trip_report_flag) {
trip_gap_array.push_back (gap_sum);
}
}
return (gap);
}
| [
"davidroden@7728d46c-9721-0410-b1ea-f014b4b56054"
] | davidroden@7728d46c-9721-0410-b1ea-f014b4b56054 |
3f0e431f043c62cde3f44d8021f5d16e498d8880 | 2e59275322981cf8662fe6de525eb747a0a21371 | /project_1/DFA.cpp | 78224cf0771fdb7b45fcfc206da32523f9425b09 | [] | no_license | colesteaks/EECS_665 | e72e62f3c5b94beac1a8ce625bd55dd55f77a368 | 7b7a2b61ac88c80be1fe90e0e435e8f7752b28f0 | refs/heads/master | 2021-06-08T20:27:29.353025 | 2016-12-02T01:18:24 | 2016-12-02T01:18:53 | 66,558,895 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | cpp | #include "DFA.h"
using namespace std;
DFA::DFA() {
this->startStates = {};
this->finalStates = {};
this->inputs = {};
this->totalStates = -1;
this->states = {};
}
DFA::~DFA() {}
//Checks to see if a set of NFA states is already in the DFA asa state
int DFA::checkDFA(unordered_set<int> set) {
int id;
for(auto itr = this->states.begin(); itr != this->states.end(); ++itr) {
unordered_set<int> test = itr->second->nStates;
unordered_set<int> diff;
std::set_difference(set.begin(), set.end(), test.begin(), test.end(),std::inserter(diff, diff.begin()));
if(diff.empty()) {
return itr->first;
}
}
return -1;
}
//checks to see if the DState should be included in final states.
bool DFA::isFinal(unordered_set<int> dstates, unordered_set<int> nfinals) {
for (auto ns = dstates.begin(); ns != dstates.end(); ++ns) {
int sfind = *ns;
if(nfinals.find(sfind) != nfinals.end()) {
return true;
}
}
return false;
}
| [
"[email protected]"
] | |
9139c8e568f11f45af61c5982ba34f6ed78ce132 | e86308ccdbfa05b1bd1738179e989ccfb35b950c | /ui/viewgroup.h | f009802cb6fff6c946f4123d8c220851db8bebdf | [
"MIT",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | kryan-supan/native | 97a205ec3dfbbd0f9e17fd794c15db69c6c6ba85 | a7b92d63d6a51f41b3fe8c89fee0bd5f85b8f4a6 | refs/heads/master | 2021-01-17T05:44:41.421957 | 2013-07-15T22:25:08 | 2013-07-15T22:25:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,091 | h | #pragma once
#include "base/logging.h"
#include "ui/view.h"
#include "math/geom2d.h"
#include "input/gesture_detector.h"
namespace UI {
struct NeighborResult {
NeighborResult() : view(0), score(0) {}
NeighborResult(View *v, float s) : view(v), score(s) {}
View *view;
float score;
};
class ViewGroup : public View {
public:
ViewGroup(LayoutParams *layoutParams = 0) : View(layoutParams), hasDropShadow_(false) {}
virtual ~ViewGroup();
// Pass through external events to children.
virtual void Key(const KeyInput &input);
virtual void Touch(const TouchInput &input);
// By default, a container will layout to its own bounds.
virtual void Measure(const UIContext &dc, MeasureSpec horiz, MeasureSpec vert) = 0;
virtual void Layout() = 0;
virtual void Update(const InputState &input_state);
virtual void Draw(UIContext &dc);
// These should be unused.
virtual float GetContentWidth() const { return 0.0f; }
virtual float GetContentHeight() const { return 0.0f; }
// Takes ownership! DO NOT add a view to multiple parents!
template <class T>
T *Add(T *view) { views_.push_back(view); return view; }
virtual bool SetFocus();
virtual bool SubviewFocused(View *view);
// Assumes that layout has taken place.
NeighborResult FindNeighbor(View *view, FocusDirection direction, NeighborResult best);
virtual bool CanBeFocused() const { return false; }
virtual bool IsViewGroup() const { return true; }
virtual void SetBG(const Drawable &bg) { bg_ = bg; }
virtual void Clear();
View *GetViewByIndex(int index) { return views_[index]; }
void SetHasDropShadow(bool has) { hasDropShadow_ = has; }
protected:
std::vector<View *> views_;
Drawable bg_;
bool hasDropShadow_;
};
// A frame layout contains a single child view (normally).
// It simply centers the child view.
class FrameLayout : public ViewGroup {
public:
void Measure(const UIContext &dc, MeasureSpec horiz, MeasureSpec vert);
void Layout();
};
enum {
NONE = -1,
};
class AnchorLayoutParams : public LayoutParams {
public:
AnchorLayoutParams(Size w, Size h, float l, float t, float r, float b)
: LayoutParams(w, h, LP_ANCHOR), left(l), top(t), right(r), bottom(b) {
}
AnchorLayoutParams(float l, float t, float r, float b)
: LayoutParams(WRAP_CONTENT, WRAP_CONTENT, LP_ANCHOR), left(l), top(t), right(r), bottom(b) {}
// These are not bounds, but distances from the container edges.
// Set to NONE to not attach this edge to the container.
float left, top, right, bottom;
};
class AnchorLayout : public ViewGroup {
public:
AnchorLayout(LayoutParams *layoutParams = 0) : ViewGroup(layoutParams) {}
void Measure(const UIContext &dc, MeasureSpec horiz, MeasureSpec vert);
void Layout();
};
class LinearLayoutParams : public LayoutParams {
public:
LinearLayoutParams()
: LayoutParams(LP_LINEAR), weight(0.0f), gravity(G_TOPLEFT), hasMargins_(false) {}
explicit LinearLayoutParams(float wgt, Gravity grav = G_TOPLEFT)
: LayoutParams(LP_LINEAR), weight(wgt), gravity(grav), hasMargins_(false) {}
LinearLayoutParams(float wgt, const Margins &mgn)
: LayoutParams(LP_LINEAR), weight(wgt), gravity(G_TOPLEFT), margins(mgn), hasMargins_(true) {}
LinearLayoutParams(Size w, Size h, float wgt = 0.0f, Gravity grav = G_TOPLEFT)
: LayoutParams(w, h, LP_LINEAR), weight(wgt), gravity(grav), hasMargins_(false) {}
LinearLayoutParams(Size w, Size h, float wgt, Gravity grav, const Margins &mgn)
: LayoutParams(w, h, LP_LINEAR), weight(wgt), gravity(grav), margins(mgn), hasMargins_(true) {}
LinearLayoutParams(Size w, Size h, const Margins &mgn)
: LayoutParams(w, h, LP_LINEAR), weight(0.0f), gravity(G_TOPLEFT), margins(mgn), hasMargins_(true) {}
LinearLayoutParams(const Margins &mgn)
: LayoutParams(WRAP_CONTENT, WRAP_CONTENT, LP_LINEAR), weight(0.0f), gravity(G_TOPLEFT), margins(mgn), hasMargins_(true) {}
float weight;
Gravity gravity;
Margins margins;
bool HasMargins() const { return hasMargins_; }
private:
bool hasMargins_;
};
class LinearLayout : public ViewGroup {
public:
LinearLayout(Orientation orientation, LayoutParams *layoutParams = 0)
: ViewGroup(layoutParams), orientation_(orientation), defaultMargins_(0), spacing_(10) {}
void Measure(const UIContext &dc, MeasureSpec horiz, MeasureSpec vert);
void Layout();
private:
Orientation orientation_;
Margins defaultMargins_;
float spacing_;
};
// GridLayout is a little different from the Android layout. This one has fixed size
// rows and columns. Items are not allowed to deviate from the set sizes.
// Initially, only horizontal layout is supported.
struct GridLayoutSettings {
GridLayoutSettings() : orientation(ORIENT_HORIZONTAL), columnWidth(100), rowHeight(50), spacing(5), fillCells(false) {}
GridLayoutSettings(int colW, int colH, int spac = 5) : orientation(ORIENT_HORIZONTAL), columnWidth(colW), rowHeight(colH), spacing(spac), fillCells(false) {}
Orientation orientation;
int columnWidth;
int rowHeight;
int spacing;
bool fillCells;
};
class GridLayout : public ViewGroup {
public:
GridLayout(GridLayoutSettings settings, LayoutParams *layoutParams = 0)
: ViewGroup(layoutParams), settings_(settings) {
if (settings.orientation != ORIENT_HORIZONTAL)
ELOG("GridLayout: Vertical layouts not yet supported");
}
void Measure(const UIContext &dc, MeasureSpec horiz, MeasureSpec vert);
void Layout();
private:
GridLayoutSettings settings_;
};
// A scrollview usually contains just a single child - a linear layout or similar.
class ScrollView : public ViewGroup {
public:
ScrollView(Orientation orientation, LayoutParams *layoutParams = 0) :
ViewGroup(layoutParams),
orientation_(orientation),
scrollPos_(0),
scrollStart_(0),
scrollMax_(0),
scrollTarget_(0),
scrollToTarget_(false) {}
void Measure(const UIContext &dc, MeasureSpec horiz, MeasureSpec vert);
void Layout();
void Key(const KeyInput &input);
void Touch(const TouchInput &input);
void Draw(UIContext &dc);
void ScrollTo(float newScrollPos);
void ScrollRelative(float distance);
void Update(const InputState &input_state);
// Override so that we can scroll to the active one after moving the focus.
virtual bool SubviewFocused(View *view);
private:
void ClampScrollPos(float &pos);
GestureDetector gesture_;
Orientation orientation_;
float scrollPos_;
float scrollStart_;
float scrollMax_;
float scrollTarget_;
bool scrollToTarget_;
};
class ViewPager : public ScrollView {
public:
};
class ChoiceStrip : public LinearLayout {
public:
ChoiceStrip(Orientation orientation, LayoutParams *layoutParams = 0)
: LinearLayout(orientation, layoutParams), selected_(0) {}
void AddChoice(const std::string &title);
int GetSelection() const { return selected_; }
void SetSelection(int sel);
Event OnChoice;
private:
EventReturn OnChoiceClick(EventParams &e);
int selected_;
};
class TabHolder : public LinearLayout {
public:
TabHolder(Orientation orientation, float stripSize, LayoutParams *layoutParams = 0)
: LinearLayout(Opposite(orientation), layoutParams),
orientation_(orientation), stripSize_(stripSize), currentTab_(0) {
tabStrip_ = new ChoiceStrip(orientation, new LinearLayoutParams(stripSize, WRAP_CONTENT));
Add(tabStrip_);
tabStrip_->OnChoice.Handle(this, &TabHolder::OnTabClick);
}
template <class T>
T *AddTab(const std::string &title, T *tabContents) {
tabContents->ReplaceLayoutParams(new LinearLayoutParams(1.0f));
tabs_.push_back(tabContents);
tabStrip_->AddChoice(title);
Add(tabContents);
if (tabs_.size() > 1)
tabContents->SetVisibility(V_GONE);
return tabContents;
}
void SetCurrentTab(int tab) {
tabs_[currentTab_]->SetVisibility(V_GONE);
currentTab_ = tab;
tabs_[currentTab_]->SetVisibility(V_VISIBLE);
}
private:
EventReturn OnTabClick(EventParams &e);
ChoiceStrip *tabStrip_;
Orientation orientation_;
float stripSize_;
int currentTab_;
std::vector<View *> tabs_;
};
// Yes, this feels a bit Java-ish...
class ListAdaptor {
public:
virtual ~ListAdaptor() {}
virtual View *CreateItemView(int index) = 0;
virtual int GetNumItems() = 0;
virtual bool AddEventCallback(View *view, std::function<EventReturn(EventParams&)> callback) { return false; }
virtual std::string GetTitle(int index) { return ""; }
virtual void SetSelected(int sel) { }
virtual int GetSelected() { return -1; }
};
class ChoiceListAdaptor : public ListAdaptor {
public:
ChoiceListAdaptor(const char *items[], int numItems) : items_(items), numItems_(numItems) {}
virtual View *CreateItemView(int index);
virtual int GetNumItems() { return numItems_; }
virtual bool AddEventCallback(View *view, std::function<EventReturn(EventParams&)> callback);
private:
const char **items_;
int numItems_;
};
// The "selected" item is what was previously selected (optional). This items will be drawn differently.
class StringVectorListAdaptor : public ListAdaptor {
public:
StringVectorListAdaptor() : selected_(-1) {}
StringVectorListAdaptor(const std::vector<std::string> &items, int selected = -1) : items_(items), selected_(selected) {}
virtual View *CreateItemView(int index);
virtual int GetNumItems() { return (int)items_.size(); }
virtual bool AddEventCallback(View *view, std::function<EventReturn(EventParams&)> callback);
void SetSelected(int sel) { selected_ = sel; }
virtual std::string GetTitle(int index) { return items_[index]; }
virtual int GetSelected() { return selected_; }
private:
std::vector<std::string> items_;
int selected_;
};
// A list view is a scroll view with autogenerated items.
// In the future, it might be smart and load/unload items as they go, but currently not.
class ListView : public ScrollView {
public:
ListView(ListAdaptor *a, LayoutParams *layoutParams = 0);
int GetSelected() { return adaptor_->GetSelected(); }
Event OnChoice;
private:
void CreateAllItems();
EventReturn OnItemCallback(int num, EventParams &e);
ListAdaptor *adaptor_;
LinearLayout *linLayout_;
};
void LayoutViewHierarchy(const UIContext &dc, ViewGroup *root);
void UpdateViewHierarchy(const InputState &input_state, ViewGroup *root);
} // namespace UI
| [
"[email protected]"
] | |
8b6bb8c58e1006e33b2ab364e9ae77d3201147c3 | 97aa1181a8305fab0cfc635954c92880460ba189 | /c10/test/util/typeid_test.cpp | 65e93c569169a4bc74cd56b250a786204b73ae8a | [
"BSD-2-Clause"
] | permissive | zhujiang73/pytorch_mingw | 64973a4ef29cc10b96e5d3f8d294ad2a721ccacb | b0134a0acc937f875b7c4b5f3cef6529711ad336 | refs/heads/master | 2022-11-05T12:10:59.045925 | 2020-08-22T12:10:32 | 2020-08-22T12:10:32 | 123,688,924 | 8 | 4 | NOASSERTION | 2022-10-17T12:30:52 | 2018-03-03T12:15:16 | C++ | UTF-8 | C++ | false | false | 4,449 | cpp | #include <c10/util/typeid.h>
#include <gtest/gtest.h>
using std::string;
namespace caffe2 {
namespace {
class TypeMetaTestFoo {};
class TypeMetaTestBar {};
}
CAFFE_KNOWN_TYPE(TypeMetaTestFoo);
CAFFE_KNOWN_TYPE(TypeMetaTestBar);
namespace {
TEST(TypeMetaTest, TypeMetaStatic) {
EXPECT_EQ(TypeMeta::ItemSize<int>(), sizeof(int));
EXPECT_EQ(TypeMeta::ItemSize<float>(), sizeof(float));
EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestFoo>(), sizeof(TypeMetaTestFoo));
EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestBar>(), sizeof(TypeMetaTestBar));
EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<float>());
EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<TypeMetaTestFoo>());
EXPECT_NE(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestBar>());
EXPECT_EQ(TypeMeta::Id<int>(), TypeMeta::Id<int>());
EXPECT_EQ(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestFoo>());
}
TEST(TypeMetaTest, Names) {
TypeMeta null_meta;
EXPECT_EQ("nullptr (uninitialized)", null_meta.name());
TypeMeta int_meta = TypeMeta::Make<int>();
EXPECT_EQ("int", int_meta.name());
TypeMeta string_meta = TypeMeta::Make<string>();
EXPECT_TRUE(c10::string_view::npos != string_meta.name().find("string"));
}
TEST(TypeMetaTest, TypeMeta) {
TypeMeta int_meta = TypeMeta::Make<int>();
TypeMeta float_meta = TypeMeta::Make<float>();
TypeMeta foo_meta = TypeMeta::Make<TypeMetaTestFoo>();
TypeMeta bar_meta = TypeMeta::Make<TypeMetaTestBar>();
TypeMeta another_int_meta = TypeMeta::Make<int>();
TypeMeta another_foo_meta = TypeMeta::Make<TypeMetaTestFoo>();
EXPECT_EQ(int_meta, another_int_meta);
EXPECT_EQ(foo_meta, another_foo_meta);
EXPECT_NE(int_meta, float_meta);
EXPECT_NE(int_meta, foo_meta);
EXPECT_NE(foo_meta, bar_meta);
EXPECT_TRUE(int_meta.Match<int>());
EXPECT_TRUE(foo_meta.Match<TypeMetaTestFoo>());
EXPECT_FALSE(int_meta.Match<float>());
EXPECT_FALSE(int_meta.Match<TypeMetaTestFoo>());
EXPECT_FALSE(foo_meta.Match<int>());
EXPECT_FALSE(foo_meta.Match<TypeMetaTestBar>());
EXPECT_EQ(int_meta.id(), TypeMeta::Id<int>());
EXPECT_EQ(float_meta.id(), TypeMeta::Id<float>());
EXPECT_EQ(foo_meta.id(), TypeMeta::Id<TypeMetaTestFoo>());
EXPECT_EQ(bar_meta.id(), TypeMeta::Id<TypeMetaTestBar>());
EXPECT_EQ(int_meta.itemsize(), TypeMeta::ItemSize<int>());
EXPECT_EQ(float_meta.itemsize(), TypeMeta::ItemSize<float>());
EXPECT_EQ(foo_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestFoo>());
EXPECT_EQ(bar_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestBar>());
EXPECT_EQ(int_meta.name(), "int");
EXPECT_EQ(float_meta.name(), "float");
EXPECT_NE(foo_meta.name().find("TypeMetaTestFoo"), c10::string_view::npos);
EXPECT_NE(bar_meta.name().find("TypeMetaTestBar"), c10::string_view::npos);
}
class ClassAllowAssignment {
public:
ClassAllowAssignment() : x(42) {}
ClassAllowAssignment(const ClassAllowAssignment& src) : x(src.x) {}
ClassAllowAssignment& operator=(const ClassAllowAssignment& src) = default;
int x;
};
class ClassNoAssignment {
public:
ClassNoAssignment() : x(42) {}
ClassNoAssignment(const ClassNoAssignment& src) = delete;
ClassNoAssignment& operator=(const ClassNoAssignment& src) = delete;
int x;
};
}
CAFFE_KNOWN_TYPE(ClassAllowAssignment);
CAFFE_KNOWN_TYPE(ClassNoAssignment);
namespace {
TEST(TypeMetaTest, CtorDtorAndCopy) {
TypeMeta fundamental_meta = TypeMeta::Make<int>();
EXPECT_EQ(fundamental_meta.placementNew(), nullptr);
EXPECT_EQ(fundamental_meta.placementDelete(), nullptr);
EXPECT_EQ(fundamental_meta.copy(), nullptr);
TypeMeta meta_a = TypeMeta::Make<ClassAllowAssignment>();
EXPECT_TRUE(meta_a.placementNew() != nullptr);
EXPECT_TRUE(meta_a.placementDelete() != nullptr);
EXPECT_TRUE(meta_a.copy() != nullptr);
ClassAllowAssignment src;
src.x = 10;
ClassAllowAssignment dst;
EXPECT_EQ(dst.x, 42);
meta_a.copy()(&src, &dst, 1);
EXPECT_EQ(dst.x, 10);
TypeMeta meta_b = TypeMeta::Make<ClassNoAssignment>();
EXPECT_TRUE(meta_b.placementNew() != nullptr);
EXPECT_TRUE(meta_b.placementDelete() != nullptr);
#ifndef __clang__
// gtest seems to have some problem with function pointers and
// clang right now... Disabling it.
// TODO: figure out the real cause.
EXPECT_EQ(meta_b.copy(), &(detail::_CopyNotAllowed<ClassNoAssignment>));
#endif
}
TEST(TypeMetaTest, Float16IsNotUint16) {
EXPECT_NE(TypeMeta::Id<uint16_t>(), TypeMeta::Id<at::Half>());
}
} // namespace
} // namespace caffe2
| [
"[email protected]"
] | |
f01021e74cec747e76b19f235b3ef4432b3204e9 | 9f25ac38773b5ccdc0247c9d43948d50e60ab97a | /third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.cc | e2b05dad4d9d9d076d1fc7d9fde6c6b0d17c1844 | [
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | liang0/chromium | e206553170eab7b4ac643ef7edc8cc57d4c74342 | 7a028876adcc46c7f7079f894a810ea1f511c3a7 | refs/heads/main | 2023-03-25T05:49:21.688462 | 2021-04-28T06:07:52 | 2021-04-28T06:07:52 | 362,370,889 | 1 | 0 | BSD-3-Clause | 2021-04-28T07:04:42 | 2021-04-28T07:04:41 | null | UTF-8 | C++ | false | false | 1,971 | cc | // Copyright 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 "third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_replaced.h"
namespace blink {
NGReplacedLayoutAlgorithm::NGReplacedLayoutAlgorithm(
const NGLayoutAlgorithmParams& params)
: NGLayoutAlgorithm(params),
// TODO(dgrogan): Use something from NGLayoutInputNode instead of
// accessing LayoutBox directly.
natural_size_(PhysicalSize(Node().GetLayoutBox()->IntrinsicSize())
.ConvertToLogical(Style().GetWritingMode())) {}
const NGLayoutResult* NGReplacedLayoutAlgorithm::Layout() {
DCHECK(!BreakToken() || BreakToken()->IsBreakBefore());
// Set this as a legacy root so that legacy painters are used.
container_builder_.SetIsLegacyLayoutRoot();
// TODO(dgrogan): |natural_size_.block_size| is frequently not the correct
// intrinsic block size. Move |ComputeIntrinsicBlockSizeForAspectRatioElement|
// from NGFlexLayoutAlgorithm to ng_length_utils and call it here.
LayoutUnit intrinsic_block_size = natural_size_.block_size;
container_builder_.SetIntrinsicBlockSize(intrinsic_block_size +
BorderPadding().BlockSum());
return container_builder_.ToBoxFragment();
}
// TODO(dgrogan): |natural_size_.inline_size| is frequently not the correct
// intrinsic inline size. Move NGFlexLayoutAlgorithm's
// |ComputeIntrinsicInlineSizeForAspectRatioElement| to here.
MinMaxSizesResult NGReplacedLayoutAlgorithm::ComputeMinMaxSizes(
const MinMaxSizesFloatInput&) const {
MinMaxSizes sizes({natural_size_.inline_size, natural_size_.inline_size});
sizes += BorderScrollbarPadding().InlineSum();
return {sizes, false};
}
} // namespace blink
| [
"[email protected]"
] | |
382118eb00e86d29416082dc116bf257a184a92e | 0f78c98050b62158e600f5a9f5b8503f3d951fa2 | /Source/Header/MyListCtrl.h | a9f5f12cc4cd1a96170e366d31b769a24900b99a | [] | no_license | NoMatterU/yddsspace | 811420ac8ca62bd574977d449a1a16367ad297d3 | e8a2710f3a999fd8646caa206481e8cf4a132b27 | refs/heads/master | 2020-07-06T16:54:30.287678 | 2019-09-05T12:59:14 | 2019-09-05T12:59:14 | 203,084,279 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,316 | h | #pragma once
#include "ListEdit.h"
#include "ImgListVector.h"
#pragma comment(lib, "Lib/ImgListVector.lib")
// CMyListCtrl
class CMyListCtrl : public CListCtrl
{
DECLARE_DYNAMIC(CMyListCtrl)
public:
CMyListCtrl();
virtual ~CMyListCtrl();
void SetpImgList(CImageList *pImgList);
CImageList *GetpImgList();
void SetpImgVector(ImgListVector *pImgVector);
ImgListVector *GetpImgVector();
void SetListCount(int ListIndex);
BOOL AddListItem(CString ImgPath);
BOOL DeleteListItem(int ListIndex, CString ImgName);
BOOL Create(DWORD dwStyle, const RECT &rect, CWnd *pParentWnd, UINT uID);
protected:
DECLARE_MESSAGE_MAP()
private:
CListEdit *m_pEdit;
CImageList *m_pImgList;
ImgListVector *m_pImgVector;
int m_ListIndex;
int m_Item;
int m_Subitem;
CRect m_EditRect;
public:
afx_msg void OnNMSetfocusList(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnNMDblclkList(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg LRESULT EditReturnFocus(WPARAM wParam, LPARAM lParam);
protected:
BOOL ChangeItemPos(int PrePos, int LaterPos);
public:
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
};
| [
"[email protected]"
] | |
7d7c50a322dad92486c2ad21466def734605e54e | 9f88366f38ca7e74dc7d6a12be927f154d15f528 | /684A.cpp | 90c717155ff9b93df63747b488122cda7265f5d4 | [] | no_license | shreyas-mante/Codeforces | 6b6d038065ab5439e5d45d8ff88d2ae9d5fc6965 | fb8c3609c2410c55626201a0980b21645d27a591 | refs/heads/main | 2023-07-15T01:32:45.987702 | 2021-08-26T09:20:53 | 2021-08-26T09:20:53 | 363,723,401 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll t;
cin>>t;
while(t--)
{
ll n,c0,c1,h;
cin>>n>>c0>>c1>>h;
string s;
cin>>s;
ll cnt0 = 0;
ll cnt1 = 0;
for(ll i=0;i<n;i++)
{
if(s[i]=='1')
{
cnt1++;
}
if(s[i]=='0')
{
cnt0++;
}
}
ll a1 , a2 ,a3;
a1 = cnt1*c1 + cnt0*c0;
a2 = h*cnt1 + n*c0;
a3 = h*cnt0 + n*c1;
ll res = min(a1,a2);
ll res1 = min(res,a3);
cout<<res1<<endl;
}
}
| [
"[email protected]"
] | |
a38fca30c7d45363e7dd01f058fd46471063bb8f | 58391c7d7dd4dd208d7c42554593d0809cd51261 | /src/Symbol.hpp | 530ff1a465993c3c4da72c9538891f3dab6c6191 | [] | no_license | DldFw/ecbrates | 88ed599ba95bfd1c6c32c0f3202d64a126d0cf50 | 752b5d77a0d21d464835404abbdad53585ac51e2 | refs/heads/master | 2022-01-09T09:36:55.886040 | 2019-01-08T20:47:58 | 2019-01-08T20:47:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | hpp | #pragma once
#include <string>
#include <vector>
namespace MO
{
/* Using special char traits is nice - the string behaves like case insensitive,
* however each time we compare strings we pay for this convenience.
* On my machine performing 100k request for some set of latest data took
* 3.3s when using Case_Insensitive_Char_Traits
* vs
* 2.9s when using plain std::string and uppercasing strings passed to Ecb::Get*.
*
* I leave the code here commented out with this comment
* to be able to test it quickly again if needs to be.
struct Case_Insensitive_Char_Traits : public std::char_traits<char>
{
static char to_upper(char ch) { return std::toupper((unsigned char)ch); }
static bool eq(char c1, char c2) { return to_upper(c1) == to_upper(c2); }
static bool lt(char c1, char c2) { return to_upper(c1) < to_upper(c2); }
static int compare(const char *s1, const char *s2, size_t n)
{
while (n-- != 0)
{
if (to_upper(*s1) < to_upper(*s2))
return -1;
if (to_upper(*s1) > to_upper(*s2))
return 1;
++s1;
++s2;
}
return 0;
}
static const char *find(const char *s, int n, char a)
{
auto const ua(to_upper(a));
while (n-- != 0)
{
if (to_upper(*s) == ua)
return s;
s++;
}
return nullptr;
}
};
using Symbol = std::basic_string<char, Case_Insensitive_Char_Traits>;
*/
using Symbol = std::string;
using Symbols = std::vector<Symbol>;
static const Symbol DEFAULT_CURRENCY{"EUR"};
} // namespace MO
| [
"[email protected]"
] | |
f4e3a08ce8e1fee60427d2a66acaede07af81974 | 62079b7030745570e21c59f61bf2ad6597a7976f | /Essentail Training for C programming/2017.10.16/pg2201.cpp | fd38239e797921f3b63b434b3e2bf712415371f5 | [] | no_license | XC-Team/c-program-code | 42f38c492e6dd2611ca29bef7be447118b22d450 | a8672c73bb5f5ec46e928a86e11f1bd23ecbb201 | refs/heads/master | 2022-12-22T23:31:08.823404 | 2020-09-25T05:07:05 | 2020-09-25T05:07:05 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 221 | cpp | #include<stdio.h>
int main(void)
{
int a, b, max;
printf("请输入两个数a,b(以逗号分隔):");
scanf("%d,%d", &a, &b);
max = (a > b ? a : b);
printf("max = %d", max);
printf("\n");
return 0;
}
| [
"[email protected]"
] | |
0adbe1c1ecad41427f5564ec6913a8c7310e82a8 | 7eaf3490a9565541cddcaab2ef5fa6d268148421 | /src/util.h | c06451c65aaa262bceb41e06b1fa35faa0b9b12e | [
"MIT"
] | permissive | xccdev/cobaltcash | 1c6eb12cf8f32af41601831582d1d2500b913c81 | 4045738b1d340b2cccbe96ffcc3a610db06dfc50 | refs/heads/master | 2020-03-23T08:14:02.107718 | 2018-07-21T05:07:54 | 2018-07-21T05:07:54 | 141,315,416 | 0 | 1 | MIT | 2018-07-21T05:07:54 | 2018-07-17T16:24:49 | C++ | UTF-8 | C++ | false | false | 7,521 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Server/client environment: argument handling, config file parsing,
* logging, thread wrappers
*/
#ifndef BITCOIN_UTIL_H
#define BITCOIN_UTIL_H
#if defined(HAVE_CONFIG_H)
#include "config/cobaltcash-config.h"
#endif
#include "compat.h"
#include "tinyformat.h"
#include "utiltime.h"
#include <exception>
#include <map>
#include <stdint.h>
#include <string>
#include <vector>
#include <boost/filesystem/path.hpp>
#include <boost/thread/exceptions.hpp>
//Cobalt Cash only features
extern bool fMasterNode;
extern bool fLiteMode;
extern bool fEnableSwiftTX;
extern int nSwiftTXDepth;
extern int64_t enforceMasternodePaymentsTime;
extern std::string strMasterNodeAddr;
extern int keysLoaded;
extern bool fSucessfullyLoaded;
extern std::string strBudgetMode;
extern std::map<std::string, std::string> mapArgs;
extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
extern bool fDebug;
extern bool fPrintToConsole;
extern bool fPrintToDebugLog;
extern bool fServer;
extern std::string strMiscWarning;
extern bool fLogTimestamps;
extern bool fLogIPs;
extern volatile bool fReopenDebugLog;
void SetupEnvironment();
/** Return true if log accepts specified category */
bool LogAcceptCategory(const char* category);
/** Send a string to the log output */
int LogPrintStr(const std::string& str);
#define LogPrintf(...) LogPrint(NULL, __VA_ARGS__)
/**
* When we switch to C++11, this can be switched to variadic templates instead
* of this macro-based construction (see tinyformat.h).
*/
#define MAKE_ERROR_AND_LOG_FUNC(n) \
/** Print to debug.log if -debug=category switch is given OR category is NULL. */ \
template <TINYFORMAT_ARGTYPES(n)> \
static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \
{ \
if (!LogAcceptCategory(category)) return 0; \
return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \
} \
/** Log error and return false */ \
template <TINYFORMAT_ARGTYPES(n)> \
static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \
{ \
LogPrintStr(std::string("ERROR: ") + tfm::format(format, TINYFORMAT_PASSARGS(n)) + "\n"); \
return false; \
}
TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC)
/**
* Zero-arg versions of logging and error, these are not covered by
* TINYFORMAT_FOREACH_ARGNUM
*/
static inline int LogPrint(const char* category, const char* format)
{
if (!LogAcceptCategory(category)) return 0;
return LogPrintStr(format);
}
static inline bool error(const char* format)
{
LogPrintStr(std::string("ERROR: ") + format + "\n");
return false;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread);
void ParseParameters(int argc, const char* const argv[]);
void FileCommit(FILE* fileout);
bool TruncateFile(FILE* file, unsigned int length);
int RaiseFileDescriptorLimit(int nMinFD);
void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length);
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
bool TryCreateDirectory(const boost::filesystem::path& p);
boost::filesystem::path GetDefaultDataDir();
const boost::filesystem::path& GetDataDir(bool fNetSpecific = true);
boost::filesystem::path GetConfigFile();
boost::filesystem::path GetMasternodeConfigFile();
#ifndef WIN32
boost::filesystem::path GetPidFile();
void CreatePidFile(const boost::filesystem::path& path, pid_t pid);
#endif
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif
boost::filesystem::path GetTempPath();
void ShrinkDebugFile();
void runCommand(std::string strCommand);
inline bool IsSwitchChar(char c)
{
#ifdef WIN32
return c == '-' || c == '/';
#else
return c == '-';
#endif
}
/**
* Return string argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. "1")
* @return command-line argument or default value
*/
std::string GetArg(const std::string& strArg, const std::string& strDefault);
/**
* Return integer argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. 1)
* @return command-line argument (0 if invalid number) or default value
*/
int64_t GetArg(const std::string& strArg, int64_t nDefault);
/**
* Return boolean argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (true or false)
* @return command-line argument or default value
*/
bool GetBoolArg(const std::string& strArg, bool fDefault);
/**
* Set an argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param strValue Value (e.g. "1")
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetArg(const std::string& strArg, const std::string& strValue);
/**
* Set a boolean argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param fValue Value (e.g. false)
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetBoolArg(const std::string& strArg, bool fValue);
/**
* Format a string to be used as group of options in help messages
*
* @param message Group name (e.g. "RPC server options:")
* @return the formatted string
*/
std::string HelpMessageGroup(const std::string& message);
/**
* Format a string to be used as option description in help messages
*
* @param option Option message (e.g. "-rpcuser=<user>")
* @param message Option description (e.g. "Username for JSON-RPC connections")
* @return the formatted string
*/
std::string HelpMessageOpt(const std::string& option, const std::string& message);
void SetThreadPriority(int nPriority);
void RenameThread(const char* name);
/**
* .. and a wrapper that just calls func once
*/
template <typename Callable>
void TraceThread(const char* name, Callable func)
{
std::string s = strprintf("cobaltcash-%s", name);
RenameThread(s.c_str());
try {
LogPrintf("%s thread start\n", name);
func();
LogPrintf("%s thread exit\n", name);
} catch (boost::thread_interrupted) {
LogPrintf("%s thread interrupt\n", name);
throw;
} catch (std::exception& e) {
PrintExceptionContinue(&e, name);
throw;
} catch (...) {
PrintExceptionContinue(NULL, name);
throw;
}
}
#endif // BITCOIN_UTIL_H
| [
"[email protected]"
] | |
b0863dfe9761ad8348e45fd2a9f418cb9b6a566d | 2413d71a07074043233874f114c303a9d1df7705 | /动态规划/樱花.cpp | 673c006d81a7bf962b54980b8a40e07e74bb4050 | [] | no_license | ferapontqiezi/AlgorithmDesign | fe21ccc5983c9622e4e6200209f0124b4360eeb4 | cdeefa760f1c55fa32ebc4a0f034fcbfa1da0ac1 | refs/heads/master | 2023-08-26T18:29:07.171850 | 2021-11-12T05:20:14 | 2021-11-12T05:20:14 | 421,362,539 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | #include<cstdio>
#include<algorithm>
using namespace std;
int nx, ny, ex, ey, n, f[1010];
int a[10005], b[10005], c[10005];
int cnt = 0, co[1000005], v[1000005];//尽可能开大,不要把空间开爆了
int main() {
scanf("%d:%d %d:%d%d", &nx, &ny, &ex, &ey, &n);
int t = (ex * 60 + ey) - (nx * 60 + ny);
for(int i = 1; i <= n; ++ i) {
scanf("%d%d%d", &a[i], &b[i], &c[i]);
if(!c[i]) c[i] = 999999;
int at = a[i], bt = b[i], ct = c[i];
for(int j = 1; j <= ct; j <<= 1) {
co[++cnt] = j*at, v[cnt] = j*bt;
ct -= j;
}
if(c) co[++cnt] = at*ct, v[cnt] = bt*ct;
//二进制优化,拆分
}
for(int i = 1; i <= cnt; ++ i) {//考虑每个拆出来的物品
for(int j = t; j >= co[i]; -- j)//01背包板子
f[j] = max(f[j], f[j - co[i]] + v[i]);
}
printf("%d", f[t]);
return 0;
} | [
"[email protected]"
] | |
a8cea3a1989a514be88a9d95b10fcd982e5c2142 | b67ab5f64c4f562bfce5d871c75821d85aa45733 | /src/core/enumerate.hpp | 805aae0acd66109b5651782a8655c162b129ac36 | [] | no_license | aamshukov/algorithms | ba20e29c886d80942b347fcf9662f84316aa28f5 | cc248526544a559fc82b235c40747206e809b802 | refs/heads/master | 2023-04-07T07:59:03.319751 | 2023-03-28T23:02:05 | 2023-03-28T23:02:05 | 195,858,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,511 | hpp | //..............................
// UI Lab Inc. Arthur Amshukov .
//..............................
#ifndef __ENUMERATE_H__
#define __ENUMERATE_H__
#pragma once
BEGIN_NAMESPACE(algorithms)
template <typename T>
struct enumerate_wrapper
{
using iterator_type = std::conditional_t<std::is_const_v<T>, typename T::const_iterator, typename T::iterator>;
using pointer_type = std::conditional_t<std::is_const_v<T>, typename T::const_pointer, typename T::pointer>;
using reference_type = std::conditional_t<std::is_const_v<T>, typename T::const_reference, typename T::reference>;
T& container;
constexpr enumerate_wrapper(T& c) : container(c)
{
}
struct enumerate_wrapper_iter
{
std::size_t index;
iterator_type value;
bool operator != (const iterator_type& other) const
{
return value != other;
}
enumerate_wrapper_iter& operator ++ ()
{
++index;
++value;
return *this;
}
constexpr std::pair<size_t, reference_type> operator * ()
{
return std::pair<size_t, reference_type>{index, *value};
}
};
constexpr enumerate_wrapper_iter begin()
{
return { 0, std::begin(container) };
}
constexpr iterator_type end()
{
return std::end(container);
}
};
template <typename T>
constexpr auto enumerate(T& c)
{
return enumerate_wrapper<T>(c);
}
END_NAMESPACE
#endif // __ENUMERATE_H__
| [
"[email protected]"
] | |
df8fadb692783252b1f810a09cb4e5e2b1f51c4e | a194511dea15e82780072fb88dad81b17e24919f | /libs/habutil/habit/HLoggerWidget.h | 2884e15ff7c6ad88d6e767f4e6a82d937645b40b | [] | no_license | djsperka/habit2-src | 3056b07c664f2cbc1e32874cdf442b13a511b205 | a35117864de3c8cff55ff05d7b20fcc479e4ee8c | refs/heads/master | 2023-01-07T19:56:59.382117 | 2023-01-06T00:23:50 | 2023-01-06T00:23:50 | 157,589,849 | 0 | 0 | null | 2023-01-05T22:00:14 | 2018-11-14T18:03:09 | C++ | UTF-8 | C++ | false | false | 443 | h | /*
* HLoggerWidget.h
*
* Created on: Jun 6, 2018
* Author: dan
*/
#ifndef LIBS_HABUTIL_HABIT_HLOGGERWIDGET_H_
#define LIBS_HABUTIL_HABIT_HLOGGERWIDGET_H_
#include <QtWidgets/qplaintextedit.h>
class HLoggerWidget: public QPlainTextEdit {
Q_OBJECT
public:
HLoggerWidget(QWidget *parent = NULL);
virtual ~HLoggerWidget();
public slots:
void appendMessage(const QString&);
};
#endif /* LIBS_HABUTIL_HABIT_HLOGGERWIDGET_H_ */
| [
"[email protected]"
] | |
30423ffe7e0abf60011f8c22241965b9e7a27bdd | 6cf257a0febcd24234777b44c68191e824662715 | /src/hls_lfcd_lds_driver/include/hls_lfcd_lds_driver/lfcd_laser.h | 82daed3fecee2c4adf6ddefe7b0789c1c6b83291 | [
"BSD-3-Clause"
] | permissive | levanson1998/ros_mbrb_pi | 6126e6a0e4fb9c65744503d8f371f09fe156d20f | eb6dd66a570e501d292cdffc21d65008795a98b5 | refs/heads/main | 2023-02-19T13:45:15.876617 | 2021-01-21T03:57:10 | 2021-01-21T03:57:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,429 | h | /*******************************************************************************
* Copyright (c) 2016, Hitachi-LG Data Storage
* Copyright (c) 2017, ROBOTIS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
/* Authors: SP Kong, JH Yang */
/* maintainer: Pyo */
#include <string>
#include <sensor_msgs/LaserScan.h>
#include <boost/asio.hpp>
#include <boost/array.hpp>
namespace hls_lfcd_lds
{
class LFCDLaser
{
public:
uint16_t rpms; ///< @brief RPMS derived from the rpm bytes in an LFCD packet
/**
* @brief Constructs a new LFCDLaser attached to the given serial port
* @param port The string for the serial port device to attempt to connect to, e.g. "/dev/ttyUSB0"
* @param baud_rate The baud rate to open the serial port at.
* @param io Boost ASIO IO Service to use when creating the serial port object
*/
LFCDLaser(const std::string& port, uint32_t baud_rate, boost::asio::io_service& io);
/**
* @brief Default destructor
*/
~LFCDLaser();
/**
* @brief Poll the laser to get a new scan. Blocks until a complete new scan is received or close is called.
* @param scan LaserScan message pointer to fill in with the scan. The caller is responsible for filling in the ROS timestamp and frame_id
*/
void poll(sensor_msgs::LaserScan::Ptr scan);
/**
* @brief Close the driver down and prevent the polling loop from advancing
*/
void close() { shutting_down_ = true; }
private:
std::string port_; ///< @brief The serial port the driver is attached to
uint32_t baud_rate_; ///< @brief The baud rate for the serial connection
bool shutting_down_; ///< @brief Flag for whether the driver is supposed to be shutting down or not
boost::asio::io_service m_ioService;
boost::asio::serial_port serial_; ///< @brief Actual serial port object for reading/writing to the LFCD Laser Scanner
uint16_t motor_speed_; ///< @brief current motor speed as reported by the LFCD.
};
}
| [
"[email protected]"
] | |
46d4ca1349c84d61d30c77cdf0e9b2026e020e8f | 802007d9aaa09ee69d3c9a423733987aedb64b31 | /code_C++/Usine.cpp | a3db20dbbefeb4b259147f2bd5f13c66d1219b6d | [] | no_license | BASARANOMO/Renault-operations-research-project | b04c8fee60d3ff16e189ec65da5202e3b5b46834 | 8575afa1f162c7b98ac969fdd79f2ee3a7b8ecd8 | refs/heads/main | 2023-02-16T23:52:00.268274 | 2021-01-14T10:35:33 | 2021-01-14T10:35:33 | 312,566,174 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 64 | cpp | #include "Usine.h"
Usine::Usine()
{
id = -1;
vertexId = -1;
} | [
"[email protected]"
] | |
8ff9882f0930025ebf5e27a11b51f81b58326ded | d6fcbc713b0e720be2cf96abfca5abfdda33279e | /DragonCore/src/Platform/SFML/Graphics/SfmlTexture.cpp | 16f5e7eb676027d11301165e137397b8bb7190e4 | [] | no_license | dylanwijnen1/DragonEngine | b72ed0f4c95802319862b65999ba769e384a1115 | 9ee3d248882a6c0d309b173e2198b8bb2b4ca784 | refs/heads/master | 2020-05-30T01:32:26.071862 | 2020-03-12T05:03:49 | 2020-03-12T05:03:49 | 189,479,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | cpp | #include "SfmlTexture.h"
#include <SFML/Graphics/Texture.hpp>
namespace dragon
{
SfmlTexture::~SfmlTexture()
{
delete m_pTexture;
m_pTexture = nullptr;
}
bool SfmlTexture::LoadFromFile(const char* filename)
{
m_pTexture = new sf::Texture();
if (!m_pTexture->loadFromFile(filename))
{
Destroy();
return false;
}
return true;
}
bool SfmlTexture::LoadFromMemory(const dragon::Byte* pData, size_t size)
{
m_pTexture = new sf::Texture();
if (!m_pTexture->loadFromMemory((void*)pData, size))
{
Destroy();
return false;
}
return true;
}
void SfmlTexture::Destroy()
{
delete m_pTexture;
m_pTexture = nullptr;
}
Vector2f SfmlTexture::GetSize() const
{
dragon::Vector2f size = { 0.f, 0.f };
if (m_pTexture)
{
sf::Vector2u texSize = m_pTexture->getSize();
size.x = (float)texSize.x;
size.y = (float)texSize.y;
}
return size;
}
} | [
"[email protected]"
] | |
f1fc3ac01f3083edcf3ce288f07f0883307e65a6 | d1ed4185904c093bda093a28fa6dd5de3e5695f9 | /src/common/test/test_term_match.cpp | 2069dba2ec7ac1ef6e69a9232c7ffca2090df7f3 | [
"MIT"
] | permissive | datavetaren/epilog | 7c31fc89f9428a5f14edf0eabf4550aa13ad7d99 | 7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820 | refs/heads/master | 2023-07-23T22:57:41.040136 | 2021-08-26T10:45:07 | 2021-08-26T10:45:07 | 371,300,487 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,172 | cpp | #include <common/term.hpp>
#include <common/term_match.hpp>
using namespace epilog::common;
#include <type_traits>
static void header( const std::string &str )
{
std::cout << "\n";
std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n";
std::cout << "\n";
}
static void test_simple_match()
{
header("test_simple_match");
// Construct
term_env env;
term t = env.new_term( con_cell(",", 2),
{con_cell("foo",0),
env.new_term(con_cell(",",2),
{int_cell(42),
env.new_term(con_cell(",",2),
{con_cell("baz",0),
con_cell("xyz",0)}
)}
)});
pattern pat(env);
term out;
int64_t ival = 0;
for (int i = 0; i < 10; i++) {
auto p = pat.str( con_cell(",",2),
pat.con("foo",0),
pat.str(con_cell(",",2),
pat.any_int(ival),
pat.any(out)));
bool r = p(env, t);
std::cout << "Matching: " << r << ": ";
if (r) {
std::cout << env.to_string(out) << " int=" << ival << std::endl;
} else {
std::cout << "Fail!" << std::endl;
}
assert(r);
}
}
int main(int argc, char *argv[] )
{
test_simple_match();
return 0;
}
| [
"[email protected]"
] | |
03209a742616d6a242742b8ce2f17cabdab8c90d | 0058bd180ba394f55b7cd33b6722ea7a63e359e6 | /commonj/sdo/ParserErrorSetter.cpp | c50f9cd0050811b21360b3b41b3fbd7e74a38a59 | [
"LicenseRef-scancode-generic-cla"
] | no_license | vex75/SCA_SDO-1.2.4_compile_fix | b66574b9dc37a052a6bea52776040d57cd1adf39 | c7dfa793722eda7cda18d9851a48e7d06ea4eb34 | refs/heads/master | 2021-01-13T16:59:07.044353 | 2016-12-22T15:06:19 | 2016-12-22T15:06:19 | 77,153,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,417 | cpp | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* $Rev: 452786 $ $Date: 2007/08/24 15:20:21 $ */
// ParserErrorSetter.cpp: class allowing parser to push errors back.
//
//////////////////////////////////////////////////////////////////////
#include "commonj/sdo/ParserErrorSetter.h"
namespace commonj
{
namespace sdo
{
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
ParserErrorSetter::~ParserErrorSetter()
{
}
} // End - namespace sdo
} // End - namespace commonj
| [
"[email protected]"
] | |
37b9651cfa25dbc536c176c24fa90d12012280b2 | 788c1404e18d6e11c0e179b8f52bb50d05dbf99c | /v1/Query/Range.cpp | f601288c4225009e8e62a2c82da9a516ce6d4ece | [] | no_license | helloyichu/PRESS | 08b4fad52bfcb77fa444bf94aae4778b9e357b07 | 5bbc3c5d827ecc44078bf6107fdebccc5bafa616 | refs/heads/master | 2021-01-18T03:40:03.092228 | 2015-01-18T03:43:45 | 2015-01-18T03:43:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 21,284 | cpp | /**
核心程序,进行MMTC的SPATIAl部分的压缩的程序
*/
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <time.h>
#include "define2.h"
#include "file.h"
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#define MAXN 95000000
using namespace std;
ofstream fout("E:\\TC\\OUTPUT.TXT");
int nodeInRegion[2000000],edgeInRegion[2000000];
//double latMax2 = 47.30329376225394, latMin2 = 46.83389173208538;
//double longMax2 = -121.827392578125, longMin2 = -121.9557373046875;
double latMax2 = 47.86523461231467, latMin2 = 47.427622733649606;
double longMax2 = -122.213037109375, longMin2 = -122.43576049804688;
union Int2Binary {
int value;
unsigned char data[4];
};
union Int2Binary int2Binary;
union Double2Binary {
double value;
unsigned char data[8];
};
union Double2Binary double2Binary;
void writeInt(FILE* file, int value) {
int2Binary.value = value;
fwrite(int2Binary.data,sizeof(unsigned char), 4,file);
}
int readInt(FILE* file) {
//unsigned char buf[4];
if (fread(int2Binary.data,sizeof(unsigned char), 4,file) < 4) return -1;
return int2Binary.value;
}
void writeDouble(FILE* file, double value) {
double2Binary.value = value;
fwrite(double2Binary.data,sizeof(unsigned char), 8,file);
}
double readDouble(FILE* file) {
if (fread(double2Binary.data,sizeof(unsigned char), 8,file) < 8) return -1;
return double2Binary.value;
}
//============
int nodeIndex[1000000][2]; //0:文件 1:偏移
int spSize; //到多少个点有最短路
int spPre[1000000]; //每个点的上一条边,-1表示不存在
int path[100000]; //记录原始SPATIAL路径
int ansSize; //压缩后实体个数
int ansList[10000]; //压缩后的轨迹,测试解压用
int SPNUM[40000];
int** SPLINK;/*-1表示两点间不连通*/
int MAP[2000000];
int save[10000];
//计算几何
/**
* Get Distance between two points
*/
double circleDistance(double lat1,double long1,double lat2,double long2)
{
double deltaLat=lat1-lat2;
double deltaLong=(long2-long1)*cos(lat1 * PI180);
return LENGTH_PER_RAD*sqrt(deltaLat*deltaLat+deltaLong*deltaLong);
}
/**
*description:计算球面一点到一条路径的距离
*param: double double 点坐标 int 边标号 double* 最近点距离边的前端点距离 double* 道路长度
*return:地球面距离,单位米
*/
double nodeToEdgeDistanceAndNodeSide(double nodeX,double nodeY,int edgeId,double *sideLen,double *roadLen){
int i,j;
double tmpSideLen=0,tmpRoadLen=0;
double result=1e80,tmp=0;
for (i=edgeStart[edgeId];i<edgeStart[edgeId+1];++i){
double x=coordNet[i << 1],y=coordNet[(i << 1)+1],x2=coordNet[(i << 1)+2],y2=coordNet[(i << 1)+3];
double dist=circleDistance(x,y,nodeX,nodeY);
if (dist<result){
result=dist;
tmpSideLen=tmp;
}
if (i<edgeStart[edgeId+1]-1) {
double vecX1=x2-x,vecY1=y2-y,
vecX2=nodeX-x,vecY2=nodeY-y,
vecX3=nodeX-x2,vecY3=nodeY-y2;
if (vecX1*vecX2+vecY1*vecY2>0 && -vecX1*vecX3-vecY1*vecY3>0 && (vecX1!=0 || vecY1!=0)){
double rate=((nodeX-x2)*vecX1+(nodeY-y2)*vecY1)/(-vecX1*vecX1-vecY1*vecY1);
double nearX=rate*x+(1-rate)*x2,nearY=rate*y+(1-rate)*y2;
double dist=circleDistance(nearX,nearY,nodeX,nodeY);
if (dist<result){
result=dist;
tmpSideLen=tmp+circleDistance(x,y,nearX,nearY);
}
}
tmpRoadLen+=circleDistance(x,y,x2,y2);
}
tmp+=circleDistance(x,y,x2,y2);
}
*sideLen=tmpSideLen;
*roadLen=tmpRoadLen;
return result;
}
//两路口间路径长度
double pathLen(int node1, int node2) {/*两点之间的最短距离*/
//printf("\n%d %d\n",node1,node2);
double res = 0, sideLen,roadLen;
int count = 0;
while (node2!=node1) {
save[count] = SPLINK[node1][node2];
if (save[count] == -1) break;
node2 = thisSide[save[count]];
++count;
}
int i;
for (i = count-1; i >=0; --i) {
nodeToEdgeDistanceAndNodeSide(0,0,save[i],&sideLen,&roadLen);
res += roadLen;
}
return res;
}
//两路口间mbr
void edgeMBR(int edgeId, double* x1, double* x2, double* y1, double* y2) {
int i,j;
double minX = 1e100, minY = 1e100, maxX = -1e100, maxY = -1e100;
for (i=edgeStart[edgeId];i<edgeStart[edgeId+1];++i){
double x=coordNet[i << 1],y=coordNet[(i << 1)+1],x2=coordNet[(i << 1)+2],y2=coordNet[(i << 1)+3];
if (x > maxX) maxX = x;
if (x < minX) minX = x;
if (x2 > maxX) maxX = x2;
if (x2 < minX) minX = x2;
if (y > maxY) maxY = y;
if (y < minY) minY = y;
if (y2 > maxY) maxY = y2;
if (y2 < minY) minY = y2;
}
*x1 = minX;
*x2 = maxX;
*y1 = minY;
*y2 = maxY;
}
void pathMBR(int node1, int node2, double* x1, double* x2, double* y1, double* y2) {
//printf("\n%d %d\n",node1,node2);
double mx1, mx2, my1, my2;
double res = 0, sideLen,roadLen;
double minX = 1e100, minY = 1e100, maxX = -1e100, maxY = -1e100;
int count = 0;
while (node2!=node1) {
save[count] = SPLINK[node1][node2];
if (save[count] == -1) break;
node2 = thisSide[save[count]];
++count;
}
int i;
for (i = count-1; i >=0; --i) {
edgeMBR(save[i], &mx1, &mx2, &my1, &my2);
if (mx1 < minX) minX = mx1;
if (mx2 > maxX) maxX = mx2;
if (my1 < minY) minY = my1;
if (my2 > maxY) maxY = my2;
}
*x1 = minX;
*x2 = maxX;
*y1 = minY;
*y2 = maxY;
}
void loadSPAll2() {
int t;
int s;
int f;
int c = 0;
//memset(SPLINK,255,sizeof(SPLINK));
//SPLINK = (int**)malloc(40000*sizeof(int));
SPLINK = new int*[30000];
for (t = 0; t < 30000; ++t) {
SPLINK[t] = new int[30000];
}
for (t = 0; t < 30000; ++t)
for (s = 0; s < 30000; ++s)
SPLINK[t][s] = -1;
char fileName[100]="../ShortestPath/SP00.txt";
//////
for (f = 0; f < 21; ++f) {
//--
//cout << f << endl;
fileName[18] = (f / 10) + 48;
fileName[19] = (f % 10) + 48;
cout << fileName << endl;
//--
//printf("%d %s\n",nodeId,fileName);
FILE* file = fopen(fileName,"rb");
//点数
int number = readInt(file);
int j;
for (j = 0; j < number; ++j) {
//id
int id = readInt(file);
//MAP[id] = c;
//个数
int many = readInt(file);
int i;
//memset(spPre,255,sizeof(spPre));
for (i = 0; i < many; ++i){
int q = readInt(file);
SPLINK[id][q] = readInt(file);
}
//++c;
}
//fseek(file,nodeIndex[nodeId][1],0);
//spSize = readInt(file);
fclose(file);
}
}
int* son/*节点孩子编号*/, *righting/*右兄弟编号*/, *value/*路段编号*/, counting, *father/*父节点标号*/, *father2/*最远祖先标号,根的直接孩子存的是本身编号*/, *L, *R, *F, *map/*-1代表不是叶子节点*/, *rvsmap, *fail, depth;
double *trielen/*trie树上记录的距离*/,*mbr1,*mbr2,*mbr3,*mbr4/*xxyy*/;
int e = 0,p,q;
int halfRoot;/*哈夫曼树根节点编号,L[i]=i节点左孩子编号,R[i]=i节点右孩子编号,F[i]=i节点父亲编号,map[i]=trie树节点编号j,rvsmap[j]=哈夫曼树i节点*/
double tmpDist[100000], tmpTime[100000];
char spCode[100000];
pair<double,double> query(int T, string code, int spNumber) {
double d;
int s,e;
if(tmpTime[0] > T || tmpTime[spNumber-1] < T)
return make_pair(-1,-1);
for(int i = 0;i < spNumber;i++) {
if(tmpTime[i] > T) {
s = i-1;
e = i;
d = tmpDist[s] + (tmpDist[e]-tmpDist[s])/(tmpTime[e]-tmpTime[s])*(T-tmpTime[s]);
break;
}
}
int count = 0;
int c = halfRoot;
double curD = 0.0;
double lastD = 0.0;
bool mark = 0;
int last;//上一段最后节点
int trieNum;
int trieTarget;
int result = -1;
int final_s,final_t;
for(int i = 0;i < code.length();i++) {
int cur = code[i]-'0';
if(cur == 0)
c = L[c];
else
c = R[c];
if(map[c] != -1) {
// cout << curD << endl;
// cout << map[c] << endl;
if(mark == 0) {
curD = trielen[map[c]];
mark = 1;
last = other[value[map[c]]];
count++;
}
else {
lastD = curD;
curD += pathLen(last,thisSide[value[father2[map[c]]]]);
// cout << lastD << "\t" << curD << "\t 1"<< endl;
count++;
if(curD > d) {
/*落在两段边之间的最短路径上*/
final_s = last;
final_t = thisSide[value[father2[map[c]]]];
result = 0;
break;
}
lastD = curD;
curD += trielen[map[c]];
// cout << lastD << "\t" << curD << "\t 2" << endl;
count++;
if(curD > d) {
/*落在trie树保存的链上*/
result = 1;
trieTarget = map[c];
break;
}
last = other[value[map[c]]];
}
c = halfRoot;
}
}
if(count <= 2)
return make_pair(-1,-1);
if(curD <= d) {
return make_pair(coordNode[last*2],coordNode[last*2+1]);
}
// cout << result << endl;
if(result == 0) {
/*在final_s,final_t之间的最短路径上*/
int final_e;
int curs,cure;
double endD;
while(curD > d) {
final_e = SPLINK[final_s][final_t];
curs = thisSide[final_e];
cure = other[final_e];
endD = curD;
curD -= pathLen(curs,cure);
}
double x1 = coordNode[curs*2];
double y1 = coordNode[curs*2+1];
double x2 = coordNode[cure*2];
double y2 = coordNode[cure*2+1];
pair<double, double> re = make_pair((d-curD)/(endD-curD)*(x2-x1)+x1,(d-curD)/(endD-curD)*(y2-y1)+y1);
return re;
}
else if(result == 1) {
while(lastD+trielen[father[trieTarget]] > d) {
trieTarget = father[trieTarget];
//cout << lastD <<"\t" << trielen[father[trieTarget]] << endl;
}
if(lastD + trielen[father[trieTarget]] + pathLen(other[value[father[trieTarget]]],thisSide[value[trieTarget]]) > d) {
/*在other[value[father[trieTarget]]],thisSide[trieTarget]之间*/
// cout << 3 << endl;
final_t = thisSide[value[trieTarget]];
// cout << final_s << "\t" << final_t << endl;
if(pathLen(final_s,final_t) < 1e-3 || final_s == final_t)
return make_pair(coordNode[final_s*2],coordNode[final_s*2+1]);
int final_e;
int curs,cure;
double endD;
int cc = 0;
while(curD >= d) {
cc++;
// system("pause");
final_e = SPLINK[final_s][final_t];
if(final_e == -1)
return make_pair(-1,-1);
final_t = thisSide[final_e];
curs = thisSide[final_e];
cure = other[final_e];
endD = curD;
curD -= pathLen(curs,cure);
// cout << final_e << endl;
// cout << curs << " " << cure << endl;
// cout << curD << endl;
}
double x1 = coordNode[curs*2];
double y1 = coordNode[curs*2+1];
double x2 = coordNode[cure*2];
double y2 = coordNode[cure*2+1];
pair<double, double> re = make_pair((d-curD)/(endD-curD)*(x2-x1)+x1,(d-curD)/(endD-curD)*(y2-y1)+y1);
return re;
}
else {
/*sonTarget边上*/
double startD = lastD + trielen[trieTarget] + pathLen(other[value[trieTarget]],thisSide[value[trieTarget]]);
double endD = lastD + trielen[trieTarget];
double len = endD-startD;
double x1 = coordNode[thisSide[value[trieTarget]]*2];
double y1 = coordNode[thisSide[value[trieTarget]]*2+1];
double x2 = coordNode[other[value[trieTarget]]*2];
double y2 = coordNode[other[value[trieTarget]]*2+1];
pair<double, double> re = make_pair((d-startD)/(endD-startD)*(x2-x1)+x1,(d-startD)/(endD-startD)*(y2-y1)+y1);
return re;
}
}
}
double dis(double x1,double y1,double x2,double y2,double x,double y) {
if(x > x2) {
if(y > y2)
return (x-x2)*(x-x2)+(y-y2)*(y-y2);
if(y < y1)
return (x-x2)*(x-x2)+(y1-y)*(y1-y);
return (x-x2)*(x-x2);
}
if(x < x1) {
if(y > y2)
return (x1-x)*(x1-x)+(y-y2)*(y-y2);
if(y < y1)
return (x1-x)*(x1-x)+(y1-y)*(y1-y);
return (x1-x)*(x1-x);
}
if(y > y2)
return (y-y2)*(y-y2);
if(y < y1)
return (y1-y)*(y1-y);
return 0.0;
}
int queryWhenAt(string code, double x, double y, int spNumber) {
int count = 0;
int c = halfRoot;
double curD = 0.0;
bool mark = 0;
int last;//上一段最后节点
double mindis = 1e10;
double tdis;
int trieNum;
int trieTarget;
int result = -1;
int final_s,final_t;
int inSP = -1;
for(int i = 0;i < code.length();i++) {
int cur = code[i]-'0';
if(cur == 0)
c = L[c];
else
c = R[c];
if(map[c] != -1) {
if(mark == 0) {
if(mbr1[map[c]] <= x && mbr2[map[c]] >= x && mbr3[map[c]] <= y && mbr4[map[c]] >= y) {
trieTarget = map[c];
result = 0;
break;
}
mindis = dis(mbr1[map[c]],mbr3[map[c]],mbr2[map[c]],mbr4[map[c]],x,y);
curD = trielen[map[c]];
last = other[value[map[c]]];
mark = 1;
}
else {
int endP = thisSide[value[father2[map[c]]]];
double cx1,cy1,cx2,cy2;
pathMBR(last,endP,&cx1,&cx2,&cy1,&cy2);
if(cx1 <= x && cx2 >= x && cy1 <= y && cy2 >= y) {
// cout << 1 << endl;
result = 1;
final_s = last;
final_t = endP;
break;
}
tdis = dis(cx1,cy1,cx2,cy2,x,y);
if(mindis > tdis) {
result = 1;
final_s = last;
final_t = endP;
mindis = tdis;
}
curD += pathLen(last,endP);
if(mbr1[map[c]] <= x && mbr2[map[c]] >= x && mbr3[map[c]] <= y && mbr4[map[c]] >= y) {
// cout << 2 << endl;
trieTarget = map[c];
result = 0;
break;
}
tdis = dis(mbr1[map[c]],mbr3[map[c]],mbr2[map[c]],mbr4[map[c]],x,y);
if(mindis > tdis) {
result = 0;
trieTarget = map[c];
mindis = tdis;
}
curD += trielen[map[c]];
last = other[value[map[c]]];
}
c = halfRoot;
}
}
//cout << result << endl;
if(result == 1) {
//在final_s和final_t的最短路径上
curD += pathLen(final_s,final_t);
double x1,x2,y1,y2;
mindis = 1e10;
int ts,tt;
double td;
int curE;
while(thisSide[curE] != final_s) {
curE = SPLINK[final_s][final_t];
pathMBR(thisSide[curE],other[curE],&x1,&x2,&y1,&y2);
tdis = dis(x1,y1,x2,y2,x,y);
curD -= pathLen(thisSide[curE],other[curE]);
if(tdis < mindis) {
ts = thisSide[curE];
tt = other[curE];
mindis = tdis;
td = curD;
}
final_t = thisSide[curE];
// cout << final_t << "\t" << final_s << endl;
//system("pause");
}
curD = td;
//cout << result << "\t" << trieTarget << endl;
}
// 在final_s,final_t之间的边上,final_s距离为curD
for(int i = 0;i < spNumber;i++) {
if(tmpDist[i] > curD) {
return tmpTime[i-1] + (curD-tmpDist[i-1])/(tmpDist[i]-tmpDist[i-1]) * (tmpTime[i]-tmpTime[i-1]);
}
}
}
#define TIME1 13102826
#define TIME2 13122826
double RANGE[5][4] = {
{1.182,103.62,1.31074,103.802},
{1.39658,103.924,1.52533,104.106},
{1.39658,103.62,1.52533,103.802},
{1.182,103.924,1.31074,104.106},
{1.28929,103.772,1.41804,103.954}
};
bool MBRmixed(double x1,double x2,double y1,double y2,double qx1,double qx2,double qy1,double qy2) {
if(x1 > qx2 || x2 < qx1 || y1 > qy2 || y2 < qy1)
return 0;
return 1;
}
bool cross(double x11,double y11,double x12,double y12,double x21,double y21,double x22,double y22) {
double Ex1 = x11-x21;
double Ey1 = y11-y21;
double Ex2 = x22-x21;
double Ey2 = y22-y21;
double Ex3 = x12-x21;
double Ey3 = y12-y21;
if((Ex2*Ey1-Ex1*Ey2)*(Ex2*Ey3-Ey2*Ex3) >= 0)
return 0;
Ex1 = -Ex1;
Ey1 = -Ey1;
Ex2 = x12-x11;
Ey2 = y12-y11;
Ex3 = x22-x11;
Ey3 = y22-y11;
if((Ex2*Ey1-Ex1*Ey2)*(Ex2*Ey3-Ey2*Ex3) >= 0)
return 0;
return 1;
}
bool crossMBR(double lx1,double ly1,double lx2,double ly2,double x1,double y1,double x2,double y2) {
if(lx1 < x2 && lx1 > x1 && ly1 < y2 && ly1 > y1)
return 1;
if(cross(lx1,ly1,lx2,ly2,x1,y1,x1,y2))
return 1;
if(cross(lx1,ly1,lx2,ly2,x1,y1,x2,y1))
return 1;
if(cross(lx1,ly1,lx2,ly2,x2,y1,x2,y2))
return 1;
if(cross(lx1,ly1,lx2,ly2,x1,y2,x2,y2))
return 1;
return 0;
}
bool crossEdge(int edgeID,double x1,double y1,double x2,double y2) {
for (int i=edgeStart[edgeID];i<edgeStart[edgeID+1];++i){
double lx1=coordNet[i << 1],ly1=coordNet[(i << 1)+1],lx2=coordNet[(i << 1)+2],ly2=coordNet[(i << 1)+3];
if(crossMBR(lx1,ly1,lx2,ly2,x1,y1,x2,y2) == 1)
return 1;
}
return 0;
}
int spatialNumber;
int rangeQuery(int startT, int endT, double qx1,double qy1, double qx2,double qy2, int spNumber) {
int s,e;
double d1,d2;
if(tmpTime[0] > TIME2 || tmpTime[spNumber-1] < TIME1)
return 0;
for(int i = 0;i < spNumber;i++) {
if(tmpTime[i] > TIME1) {
s = i-1;
e = i;
d1 = tmpDist[s] + (tmpDist[e]-tmpDist[s])/(tmpTime[e]-tmpTime[s])*(TIME1-tmpTime[s]);
}
if(tmpTime[i] > TIME2) {
s = i-1;
e = i;
d2 = tmpDist[s] + (tmpDist[e]-tmpDist[s])/(tmpTime[e]-tmpTime[s])*(TIME2-tmpTime[s]);
break;
}
}
double dist = 0;
double sideLen, roadLen;
for (int i = 0; i < spatialNumber; ++i) {
if (dist > d2) break;
nodeToEdgeDistanceAndNodeSide(0,0,path[i],&sideLen,&roadLen);
if (dist + roadLen <= d1) {
dist += roadLen; continue;
}
if (crossEdge(path[i],qx1,qy1,qx2,qy2)) return 1;
}
return 0;
}
int main(int argc, char *argv[]) {
//Load Road Network from File
char sss[20] = "";
//读入路网
loadData(sss);
//===============
int nodeUseful = 0;
int i;
//============Part 1 用最短路压缩轨迹=====================
//全内存载入最短路
//最短路表
loadSPAll2();
//读入Trie
FILE* fp = fopen("./suffix_03.txt","r");
son = (int*)malloc(MAXN*sizeof(int));
righting = (int*)malloc(MAXN*sizeof(int));
value = (int*)malloc(MAXN*sizeof(int));
father = (int*)malloc(MAXN*sizeof(int));
father2 = (int*)malloc(MAXN*sizeof(int));
mbr1 = (double*)malloc(MAXN*sizeof(double));
mbr2 = (double*)malloc(MAXN*sizeof(double));
mbr3 = (double*)malloc(MAXN*sizeof(double));
mbr4 = (double*)malloc(MAXN*sizeof(double));
trielen = (double*)malloc(MAXN*sizeof(double));
fail = (int*)malloc(MAXN*sizeof(int));
map = (int*)malloc(MAXN*sizeof(int));
rvsmap = (int*)malloc(MAXN*sizeof(int));
L = (int*)malloc(MAXN*sizeof(int));
R = (int*)malloc(MAXN*sizeof(int));
F = (int*)malloc(MAXN*sizeof(int));
fscanf(fp,"%d",&e);
for (int i = 0; i <= e; ++i)
fscanf(fp,"%d%d%d%d%d",&son[i],&righting[i],&father[i],&value[i],&counting);
fclose(fp);
for (int i = 1; i <=e; ++i)
if (father[i] == 0) father2[i] = i;
else
father2[i] = father2[father[i]];
//读入failure function
fp = fopen("./ac_03.txt","r");
for (int i = 0; i <=e; ++i)
fscanf(fp,"%d%d",&fail[i],&depth);
fclose(fp);
//Halfman树编码
fp = fopen("./halfman_03.txt","r");
// Huffman Root
fscanf(fp,"%d",&halfRoot);
for (int i = 0; i <= halfRoot; ++i) {
int id;
fscanf(fp,"%d",&id);
fscanf(fp,"%d%d%d",&L[id],&R[id],&map[id]);
if (L[id] > -1) F[L[id]] = id;
if (R[id] > -1) F[R[id]] = id;
rvsmap[map[id]] = id;
}
fclose(fp);
//Len & MBR
fp = fopen("./LenMBR.txt","r");
for (int i = 0; i <=e; ++i)
fscanf(fp,"%lf%lf%lf%lf%lf",&trielen[i],&mbr1[i],&mbr2[i],&mbr3[i],&mbr4[i]);
fclose(fp);
//读入Spatial & Temporal 然后处理
long ttr = clock();
fp =fopen(argv[1],"rb"); //Temporal文件
FILE* spatial = fopen("./DBTrajectory_Spatial_005.txt","rb");
readInt(spatial);
//cout << 1 << endl;
FILE* q = fopen("./WhenAt.txt","r");
int queryNumber;
fscanf(q,"%d",&queryNumber);
int tjNumber = readInt(fp);
int kk;
//fscanf(spatial,"%d\n",&kk);
int qcount = 0;
int pNumber;
//cout << 1 << endl;
FILE* oup = fopen(argv[2],"w");
for(int j = 0;j < queryNumber;j++) {
double qx,qy;
int qNumber;
//fscanf(q,"%d %lf %lf",&qNumber,&qx, &qy);
//while(qcount <= qNumber) {
//cout << qcount << "\t" << qNumber << endl;
spatialNumber = readInt(spatial);
for (int u = 0; u < spatialNumber; ++u) path[u] = readInt(spatial);
//qcount ++;
pNumber = readInt(fp);
for(int i = 0;i < pNumber;i++) {
tmpDist[i] = readInt(fp);
tmpTime[i] = readInt(fp);
}
//if(j == 1052)
/*cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[0][0],RANGE[0][1],RANGE[0][2],RANGE[0][3],pNumber) << endl;
cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[1][0],RANGE[1][1],RANGE[1][2],RANGE[1][3],pNumber) << endl;
cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[2][0],RANGE[2][1],RANGE[2][2],RANGE[2][3],pNumber) << endl;
cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[3][0],RANGE[3][1],RANGE[3][2],RANGE[3][3],pNumber) << endl;
cout << j<< "\t" << rangeQuery(spCode,TIME1,TIME2,RANGE[4][0],RANGE[4][1],RANGE[4][2],RANGE[4][3],pNumber) << endl;
*/
fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[0][0],RANGE[0][1],RANGE[0][2],RANGE[0][3],pNumber));
fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[1][0],RANGE[1][1],RANGE[1][2],RANGE[1][3],pNumber));
fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[2][0],RANGE[2][1],RANGE[2][2],RANGE[2][3],pNumber));
fprintf(oup,"%d",rangeQuery(TIME1,TIME2,RANGE[3][0],RANGE[3][1],RANGE[3][2],RANGE[3][3],pNumber));
fprintf(oup,"%d\n",rangeQuery(TIME1,TIME2,RANGE[4][0],RANGE[4][1],RANGE[4][2],RANGE[4][3],pNumber));
//system("pause");
}
fclose(oup);
fclose(fp);
fclose(spatial);
FILE* fff = fopen("yao.txt","a+");
fprintf(fff,"%ld\n",clock()-ttr);
fclose(fff);
//system("pause");
return 0;
}
| [
"[email protected]"
] | |
d06b0cdce1beee0a9bdcee238a279dbe98749a67 | 7ddef2c1950de659c6a0f37412310f0b34a8f27e | /tools/Call.h | c5d3b64d350771e0d71f8ff602c4baffdf1f927b | [] | no_license | cmguo/just-base-util | 85b72ce6c95c71b16844fac5a42617517904a269 | 92051179f55e40f56128a633b7b0de96d844f209 | refs/heads/master | 2022-11-19T19:22:10.799610 | 2017-12-07T02:15:00 | 2017-12-07T02:15:50 | 280,883,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | h | // Call.h
#ifndef _UTIL_TOOLS_CALL_H_
#define _UTIL_TOOLS_CALL_H_
namespace util
{
namespace tools
{
struct Call
{
template <
typename Func,
typename Arg1
>
Call(
Func func,
Arg1 arg1)
{
func(arg1);
}
template <
typename Func,
typename Arg1,
typename Arg2
>
Call(
Func func,
Arg1 arg1,
Arg2 arg2)
{
func(arg1, arg2);
}
template <
typename Func,
typename Arg1,
typename Arg2,
typename Arg3
>
Call(
Func func,
Arg1 arg1,
Arg2 arg2,
Arg3 arg3)
{
func(arg1, arg2, arg3);
}
};
} // namespace tools
} // namespace util
#endif // _UTIL_TOOLS_CALL_H_
| [
"[email protected]"
] | |
d6004dc0de7a8fcc5b483f7f1dd71e7e3ffcf72b | d89ab622dde1d9374e17346ecce8f7a60b8d094f | /dinic_algo.cpp | ecfbaf7b0b4c51cc2687473fba9a5981fcf36b11 | [] | no_license | lokesh999/prongrams_C- | a1af8919eaacff269dd05d2cfcb47fdf3bfb8361 | 8c26e442db95c51da7bf7f0499d43ac21c5dd2a5 | refs/heads/master | 2020-04-28T02:31:30.562171 | 2019-03-11T01:44:18 | 2019-03-11T01:44:18 | 174,901,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,674 | cpp | #include<bits/stdc++.h>
using namespace std;
struct edge {
int a, b, f, c;
};
const int inf = 1000 * 1000 * 1000;
const int MAXN = 1050;
int n, m;
vector <edge> e;
int pt[MAXN]; // very important performance trick
vector <int> g[MAXN];
long long flow = 0;
queue <int> q;
int d[MAXN];
int lim;
int s, t;
void add_edge(int a, int b, int c) {
edge ed;
//keep edges in vector: e[ind] - direct edge, e[ind ^ 1] - back edge
ed.a = a; ed.b = b; ed.f = 0; ed.c = c;
g[a].push_back(e.size());
e.push_back(ed);
ed.a = b; ed.b = a; ed.f = c; ed.c = c;
g[b].push_back(e.size());
e.push_back(ed);
}
bool bfs() {
for (int i = s; i <= t; i++)
d[i] = inf;
d[s] = 0;
q.push(s);
while (!q.empty() && d[t] == inf) {
int cur = q.front(); q.pop();
for (size_t i = 0; i < g[cur].size(); i++) {
int id = g[cur][i];
int to = e[id].b;
//printf("cur = %d id = %d a = %d b = %d f = %d c = %d\n", cur, id, e[id].a, e[id].b, e[id].f, e[id].c);
if (d[to] == inf && e[id].c - e[id].f >= lim) {
d[to] = d[cur] + 1;
q.push(to);
}
}
}
while (!q.empty())
q.pop();
return d[t] != inf;
}
bool dfs(int v, int flow) {
if (flow == 0)
return false;
if (v == t) {
//cout << v << endl;
return true;
}
for (; pt[v] < g[v].size(); pt[v]++) {
int id = g[v][pt[v]];
int to = e[id].b;
//printf("v = %d id = %d a = %d b = %d f = %d c = %d\n", v, id, e[id].a, e[id].b, e[id].f, e[id].c);
if (d[to] == d[v] + 1 && e[id].c - e[id].f >= flow) {
int pushed = dfs(to, flow);
if (pushed) {
e[id].f += flow;
e[id ^ 1].f -= flow;
return true;
}
}
}
return false;
}
void dinic() {
for (lim = (1 << 30); lim >= 1;) {
if (!bfs()) {
lim >>= 1;
continue;
}
for (int i = s; i <= t; i++)
pt[i] = 0;
int pushed;
while (pushed = dfs(s, lim)) {
flow = flow + lim;
}
//cout << flow << endl;
}
}
int main() {
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
scanf("%d %d", &n, &m);
s = 1; t = n;
for (int i = 1; i <= m; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
add_edge(a, b, c);
}
dinic();
cout << flow << endl;
return 0;
}
| [
"[email protected]"
] | |
d3f610bf11c9860aa9ca340ec67b5ad11fe0cd02 | ae92d68c5e4de0d8ac59364931412e19add414f5 | /Topic15/Task2/Task2.cpp | c0dc162386bf8ac4d76e5a079faa30cbff342828 | [] | no_license | nataliiageryk/cpp_fundamentals | 72914919357d7a97ff726cf1b96e62797514d4a0 | 6ddc70812892641231457bbba22764fa9ee62bcb | refs/heads/master | 2021-01-25T04:08:43.475487 | 2014-05-13T08:59:34 | 2014-05-13T08:59:34 | 16,540,847 | 1 | 0 | null | 2014-02-21T13:21:38 | 2014-02-05T09:53:21 | C++ | UTF-8 | C++ | false | false | 1,203 | cpp | #include <iostream>
#include <cmath> // or math.h, unix users may need -lm flag
#include "exc_mean.h"
// function prototypes
double hmean(double a, double b);
double gmean(double a, double b);
int main()
{
using std::cout;
using std::cin;
using std::endl;
double x, y, z;
cout << "Enter two numbers: ";
while (cin >> x >> y)
{
try { // start of try block
z = hmean(x,y);
cout << "Harmonic mean of " << x << " and " << y
<< " is " << z << endl;
cout << "Geometric mean of " << x << " and " << y
<< " is " << gmean(x,y) << endl;
cout << "Enter next set of numbers <q to quit>: ";
}// end of try block
catch (bad_hmean & bg) // start of catch block
{
cout << bg.what();
cout << "Try again.\n";
continue;
}
catch (bad_gmean & hg)
{
cout << hg.what();
cout << "Sorry, you don't get to play any more.\n";
break;
} // end of catch block
catch(std::exception & he)
{
cout << he.what();
break;
}
}
cout << "Bye!\n";
return 0;
}
double hmean(double a, double b)
{
if (a == -b)
throw bad_hmean();
return 2.0 * a * b / (a + b);
}
double gmean(double a, double b)
{
if (a < 0 || b < 0)
throw bad_gmean();
return std::sqrt(a * b);
} | [
"[email protected]"
] | |
2f485626be692035ddbc04e5459f21f0f6b18a3d | f1d0ea36f07c2ef126dec93208bd025aa78eceb7 | /Zen/Enterprise/Database/src/I_FilterClause.cpp | b28028b5781292c585942a122dcf7e70ed945043 | [] | no_license | SgtFlame/indiezen | b7d6f87143b2f33abf977095755b6af77e9e7dab | 5513d5a05dc1425591ab7b9ba1b16d11b6a74354 | refs/heads/master | 2020-05-17T23:57:21.063997 | 2016-09-05T15:28:28 | 2016-09-05T15:28:28 | 33,279,102 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,839 | cpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Enterprise Framework
//
// Copyright (C) 2001 - 2008 Tony Richards
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Tony Richards [email protected]
// Matthew Gray [email protected]
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "../I_FilterClause.hpp"
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Database {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
I_FilterClause::I_FilterClause()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
I_FilterClause::~I_FilterClause()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Database
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| [
"mgray@wintermute"
] | mgray@wintermute |
54672465c9dca88a0ed4a714b409b9b2d75bae52 | 099eea67daa4fc80e002280e2dd4588efc04b7ce | /Desktop/gesture-control/GestureControlledHomeApplianceV1.2.ino | e77488f75746aafd19e70489f8106726b6f891c7 | [] | no_license | Ashish-Sharma-1999/Arduino-Gesture-Based-Automation | 7ec2ca80b10cf8397189c8bc0e992555c98a9170 | c5a88240c24f5a9ead365a76d1fd12e7a9be6ec5 | refs/heads/master | 2022-12-22T19:44:53.590550 | 2018-10-13T15:59:33 | 2018-10-13T15:59:33 | 296,229,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,433 | ino |
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
MPU6050 mpu;
// Unccomment if you are using an Arduino-Style Board
#define ARDUINO_BOARD
#define LED_PIN 13 // (Galileo/Arduino is 13)
#define SETPIN 5
#define WIFIPIN 7
#define LIMIT 5
#define THUMB A0
/*#define INDEXFINGER A1
#define MIDDLEFINGER A2
#define RINGFINGER A3
#define SHORTFINGER A6*/
#define ENGAGESTA 8
#define ADDMODESTA 6
#define FOUNDSTA 9
int yy,pp,rr;
byte index=0;
//defination of clas object
class object{
int y,p,r; //yaw,pitch,role
static int yawlimit;
static int pchlimit;
public:
byte onoff; //true if on
object(){ //constructor
y=0;
p=0;
r=0;
onoff=0;
}
void assign(object* obj,float ypr[3],int ind){ //set object
y=ypr[0];
p=ypr[2];
for(int i=0;i<ind;i++){
yy=abs(y-obj[i].y);
if(yy>180){
yy=360-yy;
}
Serial.println(yy);
if(yy<yawlimit){
if(yy>LIMIT)
yawlimit=yy;
else{
pp=abs(p-obj[i].p);
if(pp<pchlimit && pp>LIMIT){
pchlimit=pp;
}
}
}
}
}
boolean compare(float ypr[3]){ //comapare ypr and returns true if within limit
pp=ypr[2]-p;
yy=ypr[0]-y;
if(yy>-yawlimit && yy<yawlimit){
if(pp>-pchlimit && pp<pchlimit)
return true;
else
return false;
}
else
return false;
}
};
int object::yawlimit=90;
int object::pchlimit=45;
// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
boolean engaged=false; // not engaged initally
boolean found=false; // if true finger command will be read
boolean addmode=true; //add mode is initially on to add objects
//boolean adprestate=false,adpasstate=false; //to store present and past state of ADDPIN
boolean stprestate=false,stpasstate=false; //to store present and past state of SETPIN
boolean wifi=true; //wifi will be on
boolean sendRequest=false; //to check request is checked or not
int objectno=0;
boolean thumb=false,indexfinger=false,middlefinger=false,ringfinger=false,shortfinger=false;
VectorFloat gravity; // [x, y, z] gravity vector
Quaternion q; // [w, x, y, z] quaternion container
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
object obj[4];
byte i=0,j=0;
int k=0,f=10;
int fingerSelector=0;
String request="ash";
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
// ================================================================
// === INITIAL SETUP ===
// ================================================================
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(SETPIN, INPUT);
pinMode(WIFIPIN,OUTPUT);
pinMode(THUMB,INPUT);
/*pinMode(INDEXFINGER,INPUT);
pinMode(MIDDLEFINGER,INPUT);
pinMode(RINGFINGER,INPUT);
pinMode(SHORTFINGER,INPUT);*/
pinMode(ADDMODESTA,OUTPUT);
pinMode(ENGAGESTA,OUTPUT);
pinMode(FOUNDSTA,OUTPUT);
digitalWrite(WIFIPIN,HIGH);
digitalWrite(ENGAGESTA,HIGH);
digitalWrite(ADDMODESTA,HIGH);
digitalWrite(FOUNDSTA,HIGH);
delay(4000);
digitalWrite(ENGAGESTA,LOW);
digitalWrite(ADDMODESTA,LOW);
digitalWrite(FOUNDSTA,LOW);
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
// int TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
Serial.begin(115200); //for transfering data to wifi module
// initialize MPU-6050
mpu.initialize();
// verify connection
if(!(mpu.testConnection())){
digitalWrite(LED_PIN,HIGH);
delay(2000);
digitalWrite(LED_PIN,LOW);
}
// load and configure the DMP
devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
attachInterrupt(digitalPinToInterrupt(3), dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
}
while (!digitalRead(SETPIN)==HIGH);
}
// ================================================================
// === MAIN PROGRAM LOOP ===
// ================================================================
void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;
// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize);
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
}
// otherwise, check for DMP data ready interrupt (this should happen frequently)
else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
ypr[0]=ypr[0]*57.3248; //converting to degrees
ypr[1]=ypr[1]*57.3248;
ypr[2]=ypr[2]*57.3248;
/*Serial.print(ypr[0]);
Serial.print("\t");
Serial.print(ypr[1]);
Serial.print("\t");
Serial.println(ypr[2]);*/
if(addmode){ //used to add new object
digitalWrite(ADDMODESTA,HIGH);
stprestate=digitalRead(SETPIN);
if(stpasstate && !stprestate){
if(analogRead(THUMB)<=300){
obj[index].assign(obj,ypr,index);
objectno=index;
digitalWrite(ENGAGESTA,HIGH);
for(int a=0;a<10;a++){
Serial.print(request + (objectno+1) + "sta2" + "\r");
}
delay(1000);
sendRequest=true;
index++;
digitalWrite(ENGAGESTA,LOW);
f=10;
}
else
addmode=false; //new object cant be added
}
stpasstate=stprestate; //to remember the past state
}
else { //used to check whethere any object is pointed or not
digitalWrite(ADDMODESTA,LOW);
if(!found){ //if no object found then find an object
digitalWrite(FOUNDSTA,LOW);
if(engaged){ //is setup pin is pressed engaged will be true and objects will be compared
digitalWrite(WIFIPIN,HIGH);
for(i=0;i<=index;i++){
if(obj[i].compare(ypr)){
found=true; //flag is set when object is found
objectno=i;
sendRequest=true;
f=5;
break; //once an object is found no further comparision will take place
}
}
}
}
if(engaged)
digitalWrite(ENGAGESTA,HIGH); //led to show engaged status //engaged
else
digitalWrite(ENGAGESTA,LOW); //not engaged
if(found && engaged){
digitalWrite(FOUNDSTA,HIGH); //once object is found and engaed is on further processing will be done
((analogRead(THUMB)>=300) ? thumb=true: thumb=false); //checks flex sensor value
if(thumb) {
(obj[objectno].onoff ? obj[objectno].onoff=0 : obj[objectno].onoff=1); //once object is turned on or off
engaged=false; //engaged is turned off
f=10; //how many times send request
}
}
else{
found=false; //no object is engaged
}
stprestate=digitalRead(SETPIN);
if(stprestate && (!stpasstate)) //if setpin alter its state then engaged is altered
engaged=!engaged; //from high to low
stpasstate=stprestate;
}
if(index>=4) //maximum objects are added
addmode=false; //no further addition can take place
if(f){ //index for sending request
Serial.print(request+(objectno+1)+"sta"+((obj[objectno].onoff)+1)+"\r");
f--;
}
}
digitalWrite(WIFIPIN,HIGH);
}
| [
"[email protected]"
] | |
539fc9bf914316cad6a929d878176fa1842d94f4 | a7f3b2d71915854808c76536a6213c14900d601d | /Arduino/src/edge-impulse-sdk/tensorflow/lite/micro/micro_time.cpp | 350a8a2dc92f7f04d89649ee5555c58b653ba1da | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | vishwasnavada/Smart_Collar | ce98188bdf8408fd1075151b5ee5100ee7242e64 | e5cfffc8eec5bc3bd87705d54f05c863b79d3c72 | refs/heads/main | 2023-01-05T10:07:08.689772 | 2020-11-01T12:42:17 | 2020-11-01T12:42:17 | 308,138,219 | 0 | 0 | MIT | 2020-10-31T12:49:34 | 2020-10-28T20:52:36 | null | UTF-8 | C++ | false | false | 2,066 | cpp | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Reference implementation of timer functions. Platforms are not required to
// implement these timer methods, but they are required to enable profiling.
// On platforms that have a POSIX stack or C library, it can be written using
// methods from <sys/time.h> or clock() from <time.h>.
// To add an equivalent function for your own platform, create your own
// implementation file, and place it in a subfolder with named after the OS
// you're targeting. For example, see the Cortex M bare metal version in
// tensorflow/lite/micro/bluepill/micro_time.cc or the mbed one on
// tensorflow/lite/micro/mbed/micro_time.cc.
#include "edge-impulse-sdk/tensorflow/lite/micro/micro_time.h"
namespace tflite {
// Reference implementation of the ticks_per_second() function that's required
// for a platform to support Tensorflow Lite for Microcontrollers profiling.
// This returns 0 by default because timing is an optional feature that builds
// without errors on platforms that do not need it.
int32_t ticks_per_second() { return 0; }
// Reference implementation of the GetCurrentTimeTicks() function that's
// required for a platform to support Tensorflow Lite for Microcontrollers
// profiling. This returns 0 by default because timing is an optional feature
// that builds without errors on platforms that do not need it.
int32_t GetCurrentTimeTicks() { return 0; }
} // namespace tflite
| [
"[email protected]"
] | |
c5a22736fb29965f7f268b3b674f1771ca995b98 | af84d68aa2e830427fd3720977138cdffb04f521 | /FractalDrawer.cpp | ba70816c3181204653518a765984c8a321ea825c | [] | no_license | YuliaFeldman/FractalsDrawer | e1c859eacaf8cd9c4317b8caaebe2be8aeaa97f8 | 440103976cd7d455069cb6a6af7652de5599138a | refs/heads/main | 2023-01-08T19:01:26.872850 | 2020-11-15T08:53:38 | 2020-11-15T08:53:38 | 312,992,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,185 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include "Fractal.h"
const int NUMBER_OF_TYPES = 3;
const int MAX_DIM = 6;
const int MIN_DIM = 1;
/**
* Main function of FractalDrawer program
* @param argc number of arguments
* @param argv arguments
* @return 0 when success
*/
int main(int argc, char** argv)
{
if(argc != 2)
{
std::cerr << "Usage: FractalDrawer <file path>\n";
return EXIT_FAILURE;
}
std::ifstream inputFile;
inputFile.open(argv[1]);
// if file doesn't exist or doesn't open
if(!inputFile.is_open()) //note: the school solution only prints error when file doesn't exist
{
std::cerr << "Invalid input\n";
return EXIT_FAILURE;
}
inputFile.clear();
if(inputFile.peek() == std::ifstream::traits_type::eof()) //if file is empty
{
inputFile.close();
return EXIT_FAILURE;
}
inputFile.clear();
std::string line;
int type, dim;
unsigned long i;
std::vector<std::string> input;
std::vector<Fractal*> fractals;
while(std::getline(inputFile, line))
{
input.push_back(line);
}
inputFile.close();
unsigned long numOfLines = input.size();
if(input[0].empty() && numOfLines == 1)
{
std::cerr << "Invalid input\n";
return EXIT_FAILURE;
}
for(i = 0; i < numOfLines; i++)
{
if(input[i].empty()
|| input[i].find(' ') != std::string::npos
|| input[i].find('\t') != std::string::npos
|| input[i].length() != 3
|| input[i].find(',') != 1
|| input[i].at(0) <= '0' || input[i].at(0) - '0' > NUMBER_OF_TYPES
|| input[i].at(2) - '0' < MIN_DIM || input[i].at(2) - '0' > MAX_DIM)
{
std::cerr << "Invalid input\n";
return EXIT_FAILURE;
}
type = input[i].at(0) - '0';
dim = input[i].at(2) - '0';
if(type == 1)
{
fractals.push_back(new SierpinskiCarpet(dim));
}
else if(type == 2)
{
fractals.push_back(new SierpinskiSieve(dim));
}
else
{
fractals.push_back(new CantorDust(dim));
}
}
//drawing all fractals from input file in a reverse order
while(!fractals.empty())
{
Fractal *fractal = fractals.back();
fractal->draw();
std::cout << std::endl;
delete(fractal);
fractals.pop_back();
}
inputFile.close();
return 0;
} | [
"[email protected]"
] | |
84e0c2c541c7cf90bd2adc5f132390c92b94889e | 42d981b9ac42ad12577865115228b3744aad6e6b | /bachelors/year2/ArchECM/5/LAB5.CPP | 619233b52c02710554207c542cbd5a22da71a21c | [] | no_license | Witalia008/university_courses | bcd7683ac3abbfb8f5474c0d114ed01cbc15eab6 | 8bdfb3b5f8ce44680dde530e4eabc28141013bd0 | refs/heads/main | 2023-04-11T11:16:59.444067 | 2021-04-01T01:31:02 | 2021-04-01T01:31:02 | 350,045,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | #include <conio.h>
#include <stdio.h>
#include <bios.h>
int main()
{
char data[512] = "";
int M, N, K;
printf("Input side number: ");
scanf("%d", &K);
printf("Input sector number: ");
scanf("%d", &N);
printf("Input track number: ");
scanf("%d", &M);
int res = biosdisk(2, 0, K, M, N, 1, data);
if (res != 0)
{
printf("Error: %x\n", res);
getch();
return 0;
}
int i;
for (i = 0; i < 512; i++)
{
printf("%c ", data[i]);
}
getch();
return 0;
} | [
"[email protected]"
] | |
8256fb631df8051c9b9c62ab0d63ccddcd1d222f | a88f569aeb5888d990adf009377c14cea691b09d | /src/Math/Matrix.inl | ccdf82ce310dc4e75744319e8806dce946d876bb | [] | no_license | tgjones/aether-cpp | d1de28d0c8400eb06f01d9a12e9a29ff1dd83b07 | 1cfe9c4905c2623fbcd18a2144e0690291824a43 | refs/heads/master | 2020-05-25T09:41:28.428328 | 2012-05-11T02:46:51 | 2012-05-11T02:46:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,712 | inl | template <typename Derived, int Order>
Derived
MatrixBase<Derived, Order>::identity()
{
Derived r;
for (int i = 0; i < Order; i++)
for (int j = 0; j < Order; j++)
r(i, j) = (i == j) ? 1 : 0;
return r;
}
template <typename Derived, unsigned Order>
MatrixBase<Derived, Order - 1> getMinor(MatrixBase<Derived, Order> src, int row, int col)
{
// Keep track of which col and row are being copied to dest
int colCount = 0, rowCount = 0;
MatrixBase<Derived, Order - 1> dest;
for (int i = 0; i < Order; i++)
{
if (i != row)
{
colCount = 0;
for (int j = 0; j < Order; j++)
{
if (j != col)
{
dest(rowCount, colCount) = src(i, j);
colCount++;
}
}
rowCount++;
}
}
return dest;
}
template <typename Derived, unsigned Order>
class MatrixDeterminantHelper
{
public:
static double calculateDeterminant(MatrixBase<Derived, Order> mat)
{
// The determinant value
float det = 0.0f;
// Allocate the cofactor matrix
Matrix<Order - 1> minor;
for (int i = 0; i < Order; i++)
{
// Get minor of element (0, i)
auto minor = getMinor<Derived, Order>(mat, 0, i);
// If this is an odd-numbered row, negate the value.
float factor = (i % 2 == 1) ? -1.0f : 1.0f;
// Recursion!
det += factor * mat(0, i) * MatrixDeterminantHelper<Derived, Order - 1>::calculateDeterminant(minor);
}
return det;
}
};
// Template specialization
template <typename Derived>
class MatrixDeterminantHelper<Derived, 1>
{
public:
static double calculateDeterminant(MatrixBase<Derived, 1> mat)
{
return mat(0, 0);
}
};
template <typename Derived, int Order>
Derived
MatrixBase<Derived, Order>::invert(const Derived& m)
{
// Get the determinant of a
float det = 1.0f / MatrixDeterminantHelper<Derived, Order>::calculateDeterminant(m);
Derived result;
for (int j = 0; j < Order; j++)
for (int i = 0; i < Order; i++)
{
auto minor = getMinor<Derived, Order>(m, j, i);
result(i, j) = det * MatrixDeterminantHelper<Derived, Order - 1>::calculateDeterminant(minor);
if ((i + j) % 2 == 1)
result(i, j) = -result(i, j);
}
return result;
}
template <typename Derived, int Order>
MatrixBase<Derived, Order>::MatrixBase()
{
for (int i = 0; i < Order; i++)
for (int j = 0; j < Order; j++)
at(i, j) = 0;
}
template <typename Derived, int Order>
bool
MatrixBase<Derived, Order>::approximatelyEquals(const Derived &rhs) const
{
const float EPSILON = 0.0001f;
for (int i = 0; i < Order; i++)
for (int j = 0; j < Order; j++)
if (fabs(at(i, j) - rhs(i, j)) > EPSILON)
return false;
return true;
}
template <typename Derived, int Order>
Derived
MatrixBase<Derived, Order>::operator*(const Derived& rhs) const
{
Derived r;
for (int i = 0; i < Order; i++)
for (int j = 0; j < Order; j++)
for (int k = 0; k < Order; k++)
r(i, j) += at(i, k) * rhs(k, j);
return r;
}
template <typename Derived, int Order>
bool
MatrixBase<Derived, Order>::operator==(const Derived& rhs) const
{
for (int i = 0; i < Order; i++)
for (int j = 0; j < Order; j++)
if (at(i, j) != rhs(i, j))
return false;
return true;
}
template <typename Derived, int Order>
float
MatrixBase<Derived, Order>::operator()(const int i, const int j) const
{
return m[(i * Order) + j];
}
template <typename Derived, int Order>
float&
MatrixBase<Derived, Order>::operator()(const int i, const int j)
{
return m[(i * Order) + j];
}
template <typename Derived, int Order>
float
MatrixBase<Derived, Order>::at(const int i, const int j) const
{
return (*this)(i, j);
}
template <typename Derived, int Order>
float&
MatrixBase<Derived, Order>::at(const int i, const int j)
{
return (*this)(i, j);
}
| [
"[email protected]"
] | |
ab327e98e290e74dcbcb491c1a8884f7497a3b3a | ba1f77bea85efa1bf9de89c17b4940728ae3db52 | /Activation.h | 0a84a2e97cba14d3f424f9f629f584427659d0af | [] | no_license | andrewbo29/feedforward_network | 3b93a43f7efeb21b52fddc56149f7e774d495d7f | 267cd97f35149855818240e1e3f3164fa71eca1a | refs/heads/master | 2021-01-18T21:11:10.840803 | 2016-06-03T11:06:23 | 2016-06-03T11:06:23 | 52,079,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | //
// Created by boyarov on 21.04.16.
//
#ifndef FEEDFORWARD_NETWORK_ACTIVATION_H
#define FEEDFORWARD_NETWORK_ACTIVATION_H
class Activation {
public:
Activation() = default;
virtual double forward(double x) { return 0; };
virtual double backward() { return 0; };
virtual ~Activation() = default;
protected:
double s;
};
#endif //FEEDFORWARD_NETWORK_ACTIVATION_H
| [
"[email protected]"
] | |
b2a0b834779fd721b1cd9b14cb82c5bb01ac449b | ac816b2154a04678ebd0b347b314d510fdca6280 | /table/two_level_iterator.h | 06dcc9a9641ec2ae4f0319a263ff15aa9296c346 | [] | no_license | plutolove/leveldb | f75a18ac502e70e3889c01130f35bc327ef7b653 | 117a148d976659adc0d4d14f25a8054ef86e54a5 | refs/heads/master | 2020-09-06T05:32:33.558738 | 2019-03-22T09:27:13 | 2019-03-22T09:27:13 | 67,226,482 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef STORAGE_LEVELDB_TABLE_TWO_LEVEL_ITERATOR_H_
#define STORAGE_LEVELDB_TABLE_TWO_LEVEL_ITERATOR_H_
#include "leveldb/iterator.h"
namespace leveldb {
struct ReadOptions;
// Return a new two level iterator. A two-level iterator contains an
// index iterator whose values point to a sequence of blocks where
// each block is itself a sequence of key,value pairs. The returned
// two-level iterator yields the concatenation of all key/value pairs
// in the sequence of blocks. Takes ownership of "index_iter" and
// will delete it when no longer needed.
//
// Uses a supplied function to convert an index_iter value into
// an iterator over the contents of the corresponding block.
extern Iterator *NewTwoLevelIterator(
Iterator *index_iter,
Iterator *(*block_function)(
void *arg,
const ReadOptions &options,
const Slice &index_value),
void *arg,
const ReadOptions &options);
} // namespace leveldb
#endif // STORAGE_LEVELDB_TABLE_TWO_LEVEL_ITERATOR_H_
| [
"[email protected]"
] | |
a71adbfeaca6df0788100fc0135bb00810778494 | f98d74ba8fe3cd25cdc3bb7aa4529013a22e1441 | /Isaac/Client58/BlackFly.cpp | 7b6c07c9966e8f8e4a975d00a9b62e0870422af4 | [] | no_license | Jisean/IsaacProjectBackup | 939933516d309c0e7ee179d72dacf945edf7b903 | 4368da54189e8c7969bc8cfd42f8d00fc7d9b88b | refs/heads/master | 2021-05-13T17:28:24.041874 | 2018-01-09T15:38:06 | 2018-01-09T15:38:06 | 116,823,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,215 | cpp | #include "StdAfx.h"
#include "BlackFly.h"
CBlackFly::CBlackFly(void)
{
}
CBlackFly::~CBlackFly(void)
{
}
HRESULT CBlackFly::Initialize(void)
{
fHp = 3.f;
m_wstrObjKey = L"BlackFly";
m_wstrStateKey = L"Left";
m_dwState = MS_STAND;
m_dwPrevState = MS_STAND;
m_tFrame = FRAME(0.f, 100.f, 2.f);
m_tInfo.vSize = D3DXVECTOR3(38.f,30.f,0.f);
m_fSpeed = 0.3f;
m_RenderType = R_WORLDOBJ;
return S_OK;
}
int CBlackFly::Progress(void)
{
if(m_bIsDead == true)
return 0;
FrameMove();
CMonster::WorldMatrix();
return 0;
}
void CBlackFly::Render(void)
{
CMonster::Render();
}
void CBlackFly::Release(void)
{
}
void CBlackFly::FrameMove(void)
{
if(m_dwState != m_dwPrevState)
{
switch(m_dwState)
{
case MS_STAND:
m_wstrStateKey = L"Left";
m_tFrame = FRAME(0.f, 100.f, 2.f);
break;
case MS_LEFT:
m_wstrStateKey = L"Left";
m_tFrame = FRAME(0.f, 100.f, 2.f);
break;
case MS_RIGHT:
m_wstrStateKey = L"Right";
m_tFrame = FRAME(0.f, 100.f, 2.f);
break;
}
m_dwPrevState = m_dwState;
}
m_tFrame.fFrame += m_tFrame.fCount * GET_TIME;
if(m_tFrame.fFrame > m_tFrame.fMax)
{
if(m_dwState != MS_STAND)
{
m_dwState = MS_STAND;
}
m_tFrame.fFrame = 0.f;
}
} | [
"[email protected]"
] | |
a65f70baa57fd3ccdd2b0bb6a875630284dbd717 | 551d70674c26b4e46eda660e8138167334e4352e | /queue.cpp | c5fff2a2cfa4902c9fe82afbe5078b15ad4be46c | [] | no_license | gsauarv/Queue | 7a45e8d263d446d5583878f2b43807e43a25be91 | 9f986792d0d0ae860b47d73e6d6561c4fcd08aad | refs/heads/master | 2020-09-26T11:09:59.467320 | 2019-12-06T03:59:33 | 2019-12-06T03:59:33 | 226,242,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | cpp | #include<iostream>
#define size 100
using namespace std;
int a[size];
int front=-1;
int rear =-1;
void enqueue(int value)
{
if(rear==size-1)
{
cout<<"\n"<<"Queue OverFlow";
}
else
{
if(front==-1)
front++;
rear++;
a[rear]=value;
}
}
void dequeue()
{
if(front==-1)
{
cout<<"\n"<<"Queue Overflow";
}
else
{
front++;
cout<<"Value Dequeued";
}
}
void Front()
{
if(front==-1)
{
cout<<"Queue Underflow";
}
cout<<"\n"<<"Front Items is " << a[front];
}
void display(int a[])
{
int i;
for(i=front;i<=rear;i++)
{
cout<<a[i];
}
}
int main()
{
int i,ch,value,loop=0;
cout<<"Enter Choice";
do{
cout<<"\n 1:Enqueue \n 2:Dequeue \n 3:Display Front \n 4: Display \n 5:Exit\n";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter value for enqueue\n";
cin>>value;
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
Front();
break;
case 4:
display(a);
break;
case 5:
break;
default:
cout<<"--Invalid Input--";
}
cout<<"\n"<<"\n\nDo You Want to Continue ! Enter 1 ! Exit: Enter 0\n";
cin>>loop;
}while(loop==1);
}
| [
"[email protected]"
] | |
b8335307cd047168a292d0ea9274ffda5f875fc5 | 3efc50ba20499cc9948473ee9ed2ccfce257d79a | /data/code-jam/files/2994486_PowerIVQ_5751500831719424_0_extracted_r1.cpp | 504754efd81e590098e1e1833da43f7ac281f8ca | [] | no_license | arthurherbout/crypto_code_detection | 7e10ed03238278690d2d9acaa90fab73e52bab86 | 3c9ff8a4b2e4d341a069956a6259bf9f731adfc0 | refs/heads/master | 2020-07-29T15:34:31.380731 | 2019-12-20T13:52:39 | 2019-12-20T13:52:39 | 209,857,592 | 9 | 4 | null | 2019-12-20T13:52:42 | 2019-09-20T18:35:35 | C | UTF-8 | C++ | false | false | 1,284 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int solve(vector<string> &ipt, int sz)
{
vector<int> pt(sz);
int ret = 0;
while (true)
{
if (ipt[0].length() == pt[0])
{
for (int i=1; i<sz; i++)
if (ipt[i].length() != pt[i]) return -1;
return ret;
}
char now = ipt[0][pt[0]];
vector<int> lens(sz);
for (int i=0; i<sz; i++)
{
if (ipt[i][pt[i]] != now) return -1;
while (pt[i]<ipt[i].length() && ipt[i][pt[i]] == now)
{
pt[i]++;
lens[i]++;
}
//cout<<i<<" "<<now<<" "<<pt[i]<<" "<<lens[i]<<endl;
}
sort(lens.begin(), lens.end());
for (int i=0; i<sz; i++) ret += abs(lens[i] - lens[sz/2]);
}
}
int main()
{
int t;
cin>>t;
for (int i=1; i<=t; i++)
{
int size;
cin>>size;
vector<string> ipt(size);
for (int j=0; j<size; j++) cin>>ipt[j];
cout<<"Case #"<<i<<": ";
int ans = solve(ipt, size);
if (ans==-1) cout<<"Fegla Won\n"; else cout<<ans<<"\n";
}
} | [
"[email protected]"
] | |
1aee1a3c8cb4371fb3c51d76d1f2a514e8e17141 | 584fb69896f39590bbf43e3d4221dbbeb07b5a5d | /source/LibFgBase/src/FgClusterImpl.hpp | 71def08a05f4615f24b2f85dc4c17ed94a3bdea5 | [
"MIT"
] | permissive | leo92613/FaceGenBaseLibrary | d94bf9f67cc2bc95e05b368945b5a6cdb58e24b7 | 97c9a80a232dc10281d8fc52c11f1b6d0b17552a | refs/heads/master | 2022-03-15T04:44:31.948009 | 2019-11-28T13:21:55 | 2019-11-28T13:21:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,845 | hpp | //
// Copyright (c) 2019 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
// Implementation file to be included in OS-specific libraries
#include <boost/asio.hpp>
#include "FgCluster.hpp"
#include "FgDiagnostics.hpp"
#include "FgOut.hpp"
using namespace boost::asio;
namespace Fg {
// TCP provides a full duplex stream but no mechanism for discrete messages (although each direction of
// the stream can be closed separately) so we do our own 'framing' of messsages using a size-block format
// in the functions below:
static
void
sendFrame(ip::tcp::socket & sock,String const & msg)
{
boost::system::error_code err;
size_t msgSz = msg.size();
write(sock,buffer(&msgSz,8),err);
FGASSERT(!err);
write(sock,buffer(msg.data(),msgSz),err);
FGASSERT(!err);
}
// Returns 'false' if connection closed by sender
static
bool
recvFrame(ip::tcp::socket & sock,String & msg)
{
boost::system::error_code err;
size_t msgSz,
szRead;
// 'read' makes repeated use of sock::read_some (== receive) to read the requested amount:
szRead = read(sock,buffer(&msgSz,8),err);
if (err == error::eof)
return false;
FGASSERT(!err);
FGASSERT(szRead == 8);
FGASSERT(msgSz <= 0x02000000); // < 32MB sanity check
msg.resize(msgSz);
szRead = read(sock,buffer(&msg[0],msgSz),err);
if (err == error::eof)
return false;
FGASSERT(!err);
FGASSERT(szRead == msgSz);
return true;
}
// The worker can receive and send messages in the same thread as the dispatcher won't send
// another message until it receives its response:
void
fgClustWorker(FgFnStr2Str handler,uint16 port)
{
io_service ios; // Initialize networking functionality
ip::tcp::endpoint ep(ip::tcp::v4(),port);
ip::tcp::acceptor acc(ios,ep);
ip::tcp::socket sock(ios);
acc.accept(sock);
boost::system::error_code err;
for (;;) {
String msg;
if (!recvFrame(sock,msg)) // Can block for a long time
return; // Connection closed, terminate
String resp = handler(msg); // Can take a long time before returning
sendFrame(sock,resp);
}
}
// If an exception is thrown, store it's details in the message:
void
recvFrameThread(ip::tcp::socket & sock,String & msg)
{
bool connectionOpen = true;
try {
connectionOpen = recvFrame(sock,msg);
}
catch(FgException const & e) {
msg = e.tr_message();
}
catch(std::exception const & e) {
msg = String("Standard library exception\n")+e.what();
}
catch(...) {
msg = "Unknown exception type";
}
if (!connectionOpen)
msg = "Worker closed connection";
}
struct FgClustDispatcherImpl : FgClustDispatcher
{
typedef std::unique_ptr<ip::tcp::socket> SockPtr;
io_service ios;
Svec<SockPtr> sockPtrs;
FgClustDispatcherImpl(Strings const & hosts,String const & port)
{
sockPtrs.reserve(hosts.size());
for (size_t hh=0; hh<hosts.size(); ++hh) {
ip::tcp::resolver res(ios);
ip::tcp::resolver::query query(ip::tcp::v4(),hosts[hh],port);
ip::tcp::resolver::iterator iter(res.resolve(query));
sockPtrs.emplace_back(std::unique_ptr<ip::tcp::socket>(new ip::tcp::socket(ios)));
boost::system::error_code err;
connect(*sockPtrs[hh],iter,err);
if (err)
fgThrow("Cluster dispatch connect failed",hosts[hh]);
}
}
virtual
size_t numMachines() const
{return sockPtrs.size(); }
virtual
void
batchProcess(Strings const & msgsSend,Strings & msgsRecv) const
{
FGASSERT(msgsSend.size() == sockPtrs.size());
msgsRecv.resize(msgsSend.size());
// Start the receive threads before sending in case of long send and short return times.
// Since workers will finish in different times, we cannot receive sequentially (not just due to
// inefficiencies but also because input buffers could overflow) so each send is a thread:
Svec<std::thread> recvThreads;
recvThreads.reserve(msgsSend.size());
for (size_t mm=0; mm<msgsSend.size(); ++mm)
recvThreads.push_back(std::thread(recvFrameThread,
std::ref(*sockPtrs[mm]),
std::ref(msgsRecv[mm])));
// Since there's only one physical ethernet cable and recipients are close by we just send each
// message sequentially. A possible future optimization would be to make this asynchronous with some
// number of threads (via asio):
for (size_t mm=0; mm<msgsSend.size(); ++mm)
sendFrame(*sockPtrs[mm],msgsSend[mm]);
for (size_t mm=0; mm<recvThreads.size(); ++mm)
recvThreads[mm].join();
// Check for errors within the receive threads;
static String hdrSer = "\26\0\\0\0\0\0\0\0serialization::archive"; // Character literals in octal
for (size_t mm=0; mm<msgsRecv.size(); ++mm)
if (!fgBeginsWith(msgsRecv[mm],hdrSer))
fgThrow("Cluster worker "+toString(mm),msgsRecv[mm]);
}
};
std::shared_ptr<FgClustDispatcher>
fgClustDispatcher(Strings const & hostnames,uint16 port)
{
return std::make_shared<FgClustDispatcherImpl>(hostnames,toString(port));
}
}
// */
| [
"[email protected]"
] | |
c113ef16bac5b16a8074590f1325efdccdc4c51c | a13e7993275058dceae188f2101ad0750501b704 | /2021/299. Bulls and Cows.cpp | 56de608bb436a2387fb3b31bd7951a9263acf678 | [] | no_license | yangjufo/LeetCode | f8cf8d76e5f1e78cbc053707af8bf4df7a5d1940 | 15a4ab7ce0b92b0a774ddae0841a57974450eb79 | refs/heads/master | 2023-09-01T01:52:49.036101 | 2023-08-31T00:23:19 | 2023-08-31T00:23:19 | 126,698,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | cpp | class Solution {
public:
string getHint(string secret, string guess) {
vector<int> countS(10, 0), countG(10, 0);
int bulls = 0;
for (int i = 0; i < secret.size(); i++) {
if (secret[i] == guess[i]) {
bulls++;
} else {
countS[secret[i] - '0']++;
countG[guess[i] - '0']++;
}
}
int cows = 0;
for (int i = 0; i < 10; i++) {
cows += min(countS[i], countG[i]);
}
return to_string(bulls) + "A" + to_string(cows) + "B";
}
}; | [
"[email protected]"
] | |
1f0b22dcb72e585c6c4d8b5528e0a0214546db5a | a1b5fa19a2980641a0e08d0a5caddef6b9a7533f | /libcaf_io/caf/io/handle.hpp | bfa1238e7c7891a37a7faee6cbde1b16319d7dbb | [
"BSL-1.0"
] | permissive | subailong/actor-framework | ef0fa46919f8add887dd1a0b13962fff36d428bb | d9e99842449752ec777beca1c21aff1c45a5008b | refs/heads/master | 2021-01-18T00:00:33.761745 | 2015-04-13T15:16:29 | 2015-04-13T15:16:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,678 | hpp | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_DETAIL_HANDLE_HPP
#define CAF_DETAIL_HANDLE_HPP
#include <cstdint>
#include "caf/detail/comparable.hpp"
namespace caf {
/**
* Base class for IO handles such as `accept_handle` or `connection_handle`.
*/
template <class Subtype, int64_t InvalidId = -1>
class handle : detail::comparable<Subtype> {
public:
constexpr handle() : m_id{InvalidId} {
// nop
}
handle(const Subtype& other) {
m_id = other.id();
}
handle(const handle& other) = default;
Subtype& operator=(const handle& other) {
m_id = other.id();
return *static_cast<Subtype*>(this);
}
/**
* Returns the unique identifier of this handle.
*/
int64_t id() const {
return m_id;
}
/**
* Sets the unique identifier of this handle.
*/
void set_id(int64_t value) {
m_id = value;
}
int64_t compare(const Subtype& other) const {
return m_id - other.id();
}
bool invalid() const {
return m_id == InvalidId;
}
void set_invalid() {
set_id(InvalidId);
}
static Subtype from_int(int64_t id) {
return {id};
}
protected:
handle(int64_t handle_id) : m_id{handle_id} {
// nop
}
private:
int64_t m_id;
};
} // namespace caf
#endif // CAF_DETAIL_HANDLE_HPP
| [
"[email protected]"
] | |
3deed88acb806764363286ba0abe906cc032e69d | 76f115f0110fd13703043dd221b006a68b8c934f | /libraries/marekburiak-ILI9341_due-37936e8/examples/utftDemo/utftDemo.ino | fab822d16d0b6743c474e73e8ba6f847779c385f | [] | no_license | benco/digital-recorder | f5e714528099b8ba9ed510a2e1be6579a30b6849 | b26dc629c62345eedb9d594a17559fdb8dd1eda1 | refs/heads/master | 2016-09-05T11:18:40.961360 | 2015-04-15T12:49:15 | 2015-04-15T12:49:15 | 30,207,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,279 | ino | // UTFT Demo ported to ILI9341_due library by TFTLCDCyg
// Based on Demo 320x240 Serial of UTFT library
// UTFT-web: http://www.henningkarlsen.com/electronics
#include <SPI.h>
// ILI9341_due NEW lib by Marek Buriak http://marekburiak.github.io/ILI9341_due/
#include <ILI9341_due_gText.h>
#include <ILI9341_due.h>
#include "fonts\Arial14.h"
//#include "Streaming.h"
// For the Adafruit shield, these are the default.
#define TFT_DC 9
#define TFT_CS 10
// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
ILI9341_due tft = ILI9341_due(TFT_CS, TFT_DC);
ILI9341_due_gText t1(&tft);
char textBuff[20];
// Color set
#define BLACK 0x0000
#define RED 0xF800
#define GREEN 0x07E0
//#define BLUE 0x001F
#define BLUE 0x102E
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define ORANGE 0xFD20
#define GREENYELLOW 0xAFE5
#define DARKGREEN 0x03E0
#define WHITE 0xFFFF
uint16_t color;
uint16_t colorFONDO=BLACK;
void setup()
{
randomSeed(analogRead(0));
// TFT 2.2" SPI
Serial.begin(9600);
tft.begin();
tft.setRotation(iliRotation270);
tft.fillScreen(colorFONDO);
t1.defineArea(0, 0, 320, 240);
t1.selectFont(Arial14);
}
void ILI9341duenodelay()
{
int buf[318];
int x, x2;
int y, y2;
int r;
tft.fillScreen(colorFONDO);
int timeinit= millis();
//ILI9341due NEW
tft.fillRect(0, 0, 320, 15,RED);
t1.setFontColor(WHITE, RED);
t1.drawString("* ILI9341_due UTFT 240x320 Demo *", 47,0);
tft.fillRect(0, 226, 320, 240,tft.color565(64, 64, 64));
t1.setFontColor(YELLOW, tft.color565(64, 64, 64));
t1.drawString("<http://electronics.henningkarlsen.com>", gTextAlignBottomCenter,227);
//ILI9341due NEW
tft.drawRect(0, 15, 320, 211,BLUE);
//ILI9341due NEW
// Draw crosshairs
tft.drawLine(159, 15, 159, 224,BLUE);
tft.drawLine(1, 119, 318, 119,BLUE);
for (int i=9; i<310; i+=10)
tft.drawLine(i, 117, i, 121,BLUE);
for (int i=19; i<220; i+=10)
tft.drawLine(157, i, 161, i, BLUE);
// Draw sin-, cos- and tan-lines
t1.setFontColor(CYAN, BLACK);
t1.drawString("Sin", 5,17);
for (int i=1; i<318; i++)
{
tft.drawPixel(i,119+(sin(((i*1.13)*3.14)/180)*95),CYAN);
}
t1.setFontColor(RED, BLACK);
t1.drawString("Cos", 5,29);
for (int i=1; i<318; i++)
{
tft.drawPixel(i,119+(cos(((i*1.13)*3.14)/180)*95),RED);
}
t1.setFontColor(YELLOW, BLACK);
t1.drawString("Tan", 5,41);
for (int i=1; i<318; i++)
{
tft.drawPixel(i,119+(tan(((i*1.13)*3.14)/180)),YELLOW);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
tft.drawLine(159, 16, 159, 224,BLUE);
tft.drawLine(1, 119, 318, 119,BLUE);
// Draw a moving sinewave
x=1;
for (int i=1; i<(318*20); i++)
{
x++;
if (x==319)
x=1;
if (i>319)
{
if ((x==159)||(buf[x-1]==119))
color = BLUE;
else
color = BLACK;
tft.drawPixel(x,buf[x-1],color);
}
y=119+(sin(((i*1.1)*3.14)/180)*(90-(i / 100)));
tft.drawPixel(x,y,CYAN);
buf[x-1]=y;
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some filled rectangles
for (int i=1; i<6; i++)
{
switch (i)
{
case 1:
color = MAGENTA;
break;
case 2:
color = RED;
break;
case 3:
color = GREEN;
break;
case 4:
color = BLUE;
break;
case 5:
color = YELLOW;
break;
}
tft.fillRect(70+(i*20), 30+(i*20), 60, 60,color);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some filled, rounded rectangles
for (int i=1; i<6; i++)
{
switch (i)
{
case 1:
color = MAGENTA;
break;
case 2:
color = RED;
break;
case 3:
color = GREEN;
break;
case 4:
color = BLUE;
break;
case 5:
color = YELLOW;
break;
}
tft.fillRoundRect(190-(i*20), 30+(i*20), 60, 60,3,color);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some filled circles
for (int i=1; i<6; i++)
{
switch (i)
{
case 1:
color = MAGENTA;
break;
case 2:
color = RED;
break;
case 3:
color = GREEN;
break;
case 4:
color = BLUE;
break;
case 5:
color = YELLOW;
break;
}
tft.fillCircle(100+(i*20),60+(i*20), 30, color);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some lines in a pattern
for (int i=17; i<222; i+=5)
{
tft.drawLine(1, i, (i*1.44)-10, 224, RED);
}
for (int i=222; i>17; i-=5)
{
tft.drawLine(318, i, (i*1.44)-11, 15,RED);
}
for (int i=222; i>17; i-=5)
{
tft.drawLine(1, i, 331-(i*1.44), 15, CYAN);
}
for (int i=17; i<222; i+=5)
{
tft.drawLine(318, i, 330-(i*1.44), 223, CYAN);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some random circles
for (int i=0; i<100; i++)
{
color = tft.color565(random(255), random(255), random(255));
x=32+random(256);
y=45+random(146);
r=random(30);
tft.drawCircle(x, y, r, color);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some random rectangles
for (int i=0; i<100; i++)
{
color = tft.color565(random(255), random(255), random(255));
x=2 + random(165);
y=16+ random(100);
x2=random(165);
y2=random(115);
tft.drawRect(x, y, x2, y2, color);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
// Draw some random rounded rectangles
for (int i=0; i<100; i++)
{
color = tft.color565(random(255), random(255), random(255));
x=2+random(165);
y=16+random(100);
x2=random(165);
y2=random(115);
tft.drawRoundRect(x, y, x2, y2,3,color);
}
// delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
for (int i=0; i<100; i++)
{
color = tft.color565(random(255), random(255), random(255));
x=2+random(316);
y=16+random(209);
x2=2+random(316);
y2=16+random(209);
tft.drawLine(x, y, x2, y2, color);
}
//delay(2000);
//ILI9341due NEW
tft.fillRect(1,16,318,209,BLACK);
for (int i=0; i<10000; i++)
{
color = tft.color565(random(255), random(255), random(255));
tft.drawPixel(2+random(316), 16+random(209), color);
}
int timetest = millis() -timeinit;
//delay(2000);
//ILI9341due NEW
tft.fillRect(0,0,320,240,BLUE);
tft.fillRoundRect(80, 70, 159, 99,3,RED);
t1.setFontColor(WHITE, RED);
t1.drawString("That's it!", 130,93);
t1.drawString("Restarting in a", 117, 119);
t1.drawString("few seconds...", 117, 132);
t1.setFontColor(WHITE, BLUE);
t1.drawString("Runtime: (msecs)", 112, 210);
sprintf(textBuff, "%d", timetest);
t1.drawString(textBuff, 146, 225);
}
void loop()
{
ILI9341duenodelay();
delay(5000);
}
| [
"[email protected]"
] | |
70a581f30de12229640673549063c928d65e7688 | 4980348eda8918cfccc1857f7f1e56eecc08345f | /Source/Decoda/libs/wxWidgets/include/wx/html/helpdata.h | fcd54d780183ceb3343d740e975bfec257f0f6a8 | [
"MIT"
] | permissive | KoSukeWork/BabeLua | 2d3163a118985676fd621baafa7457d1f6b66044 | 0904f8ba15174fcfe88d75e37349c4f4f15403ef | refs/heads/master | 2023-01-24T12:14:03.548957 | 2020-12-07T11:13:09 | 2020-12-07T11:13:09 | 319,252,369 | 0 | 1 | MIT | 2020-12-07T08:28:27 | 2020-12-07T08:28:26 | null | UTF-8 | C++ | false | false | 9,199 | h | /////////////////////////////////////////////////////////////////////////////
// Name: helpdata.h
// Purpose: wxHtmlHelpData
// Notes: Based on htmlhelp.cpp, implementing a monolithic
// HTML Help controller class, by Vaclav Slavik
// Author: Harm van der Heijden and Vaclav Slavik
// RCS-ID: $Id: helpdata.h 53135 2008-04-12 02:31:04Z VZ $
// Copyright: (c) Harm van der Heijden and Vaclav Slavik
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_HELPDATA_H_
#define _WX_HELPDATA_H_
#include "wx/defs.h"
#if wxUSE_HTML
#include "wx/object.h"
#include "wx/string.h"
#include "wx/filesys.h"
#include "wx/dynarray.h"
#include "wx/font.h"
class WXDLLIMPEXP_FWD_HTML wxHtmlHelpData;
//--------------------------------------------------------------------------------
// helper classes & structs
//--------------------------------------------------------------------------------
class WXDLLIMPEXP_HTML wxHtmlBookRecord
{
public:
wxHtmlBookRecord(const wxString& bookfile, const wxString& basepath,
const wxString& title, const wxString& start)
{
m_BookFile = bookfile;
m_BasePath = basepath;
m_Title = title;
m_Start = start;
// for debugging, give the contents index obvious default values
m_ContentsStart = m_ContentsEnd = -1;
}
wxString GetBookFile() const { return m_BookFile; }
wxString GetTitle() const { return m_Title; }
wxString GetStart() const { return m_Start; }
wxString GetBasePath() const { return m_BasePath; }
/* SetContentsRange: store in the bookrecord where in the index/contents lists the
* book's records are stored. This to facilitate searching in a specific book.
* This code will have to be revised when loading/removing books becomes dynamic.
* (as opposed to appending only)
* Note that storing index range is pointless, because the index is alphab. sorted. */
void SetContentsRange(int start, int end) { m_ContentsStart = start; m_ContentsEnd = end; }
int GetContentsStart() const { return m_ContentsStart; }
int GetContentsEnd() const { return m_ContentsEnd; }
void SetTitle(const wxString& title) { m_Title = title; }
void SetBasePath(const wxString& path) { m_BasePath = path; }
void SetStart(const wxString& start) { m_Start = start; }
// returns full filename of page (which is part of the book),
// i.e. with book's basePath prepended. If page is already absolute
// path, basePath is _not_ prepended.
wxString GetFullPath(const wxString &page) const;
protected:
wxString m_BookFile;
wxString m_BasePath;
wxString m_Title;
wxString m_Start;
int m_ContentsStart;
int m_ContentsEnd;
};
WX_DECLARE_USER_EXPORTED_OBJARRAY(wxHtmlBookRecord, wxHtmlBookRecArray,
WXDLLIMPEXP_HTML);
struct WXDLLIMPEXP_HTML wxHtmlHelpDataItem
{
wxHtmlHelpDataItem() : level(0), parent(NULL), id(wxID_ANY), book(NULL) {}
int level;
wxHtmlHelpDataItem *parent;
int id;
wxString name;
wxString page;
wxHtmlBookRecord *book;
// returns full filename of m_Page, i.e. with book's basePath prepended
wxString GetFullPath() const { return book->GetFullPath(page); }
// returns item indented with spaces if it has level>1:
wxString GetIndentedName() const;
};
WX_DECLARE_USER_EXPORTED_OBJARRAY(wxHtmlHelpDataItem, wxHtmlHelpDataItems,
WXDLLIMPEXP_HTML);
#if WXWIN_COMPATIBILITY_2_4
// old interface to contents and index:
struct wxHtmlContentsItem
{
wxHtmlContentsItem();
wxHtmlContentsItem(const wxHtmlHelpDataItem& d);
wxHtmlContentsItem& operator=(const wxHtmlContentsItem& d);
~wxHtmlContentsItem();
int m_Level;
int m_ID;
wxChar *m_Name;
wxChar *m_Page;
wxHtmlBookRecord *m_Book;
// returns full filename of m_Page, i.e. with book's basePath prepended
wxString GetFullPath() const { return m_Book->GetFullPath(m_Page); }
private:
bool m_autofree;
};
#endif
//------------------------------------------------------------------------------
// wxHtmlSearchEngine
// This class takes input streams and scans them for occurence
// of keyword(s)
//------------------------------------------------------------------------------
class WXDLLIMPEXP_HTML wxHtmlSearchEngine : public wxObject
{
public:
wxHtmlSearchEngine() : wxObject() {}
virtual ~wxHtmlSearchEngine() {}
// Sets the keyword we will be searching for
virtual void LookFor(const wxString& keyword, bool case_sensitive, bool whole_words_only);
// Scans the stream for the keyword.
// Returns true if the stream contains keyword, fALSE otherwise
virtual bool Scan(const wxFSFile& file);
private:
wxString m_Keyword;
bool m_CaseSensitive;
bool m_WholeWords;
DECLARE_NO_COPY_CLASS(wxHtmlSearchEngine)
};
// State information of a search action. I'd have preferred to make this a
// nested class inside wxHtmlHelpData, but that's against coding standards :-(
// Never construct this class yourself, obtain a copy from
// wxHtmlHelpData::PrepareKeywordSearch(const wxString& key)
class WXDLLIMPEXP_HTML wxHtmlSearchStatus
{
public:
// constructor; supply wxHtmlHelpData ptr, the keyword and (optionally) the
// title of the book to search. By default, all books are searched.
wxHtmlSearchStatus(wxHtmlHelpData* base, const wxString& keyword,
bool case_sensitive, bool whole_words_only,
const wxString& book = wxEmptyString);
bool Search(); // do the next iteration
bool IsActive() { return m_Active; }
int GetCurIndex() { return m_CurIndex; }
int GetMaxIndex() { return m_MaxIndex; }
const wxString& GetName() { return m_Name; }
const wxHtmlHelpDataItem *GetCurItem() const { return m_CurItem; }
#if WXWIN_COMPATIBILITY_2_4
wxDEPRECATED( wxHtmlContentsItem* GetContentsItem() );
#endif
private:
wxHtmlHelpData* m_Data;
wxHtmlSearchEngine m_Engine;
wxString m_Keyword, m_Name;
wxString m_LastPage;
wxHtmlHelpDataItem* m_CurItem;
bool m_Active; // search is not finished
int m_CurIndex; // where we are now
int m_MaxIndex; // number of files we search
// For progress bar: 100*curindex/maxindex = % complete
DECLARE_NO_COPY_CLASS(wxHtmlSearchStatus)
};
class WXDLLIMPEXP_HTML wxHtmlHelpData : public wxObject
{
DECLARE_DYNAMIC_CLASS(wxHtmlHelpData)
friend class wxHtmlSearchStatus;
public:
wxHtmlHelpData();
virtual ~wxHtmlHelpData();
// Sets directory where temporary files are stored.
// These temp files are index & contents file in binary (much faster to read)
// form. These files are NOT deleted on program's exit.
void SetTempDir(const wxString& path);
// Adds new book. 'book' is location of .htb file (stands for "html book").
// See documentation for details on its format.
// Returns success.
bool AddBook(const wxString& book);
bool AddBookParam(const wxFSFile& bookfile,
wxFontEncoding encoding,
const wxString& title, const wxString& contfile,
const wxString& indexfile = wxEmptyString,
const wxString& deftopic = wxEmptyString,
const wxString& path = wxEmptyString);
// Some accessing stuff:
// returns URL of page on basis of (file)name
wxString FindPageByName(const wxString& page);
// returns URL of page on basis of MS id
wxString FindPageById(int id);
const wxHtmlBookRecArray& GetBookRecArray() const { return m_bookRecords; }
const wxHtmlHelpDataItems& GetContentsArray() const { return m_contents; }
const wxHtmlHelpDataItems& GetIndexArray() const { return m_index; }
#if WXWIN_COMPATIBILITY_2_4
// deprecated interface, new interface is arrays-based (see above)
wxDEPRECATED( wxHtmlContentsItem* GetContents() );
wxDEPRECATED( int GetContentsCnt() );
wxDEPRECATED( wxHtmlContentsItem* GetIndex() );
wxDEPRECATED( int GetIndexCnt() );
#endif
protected:
wxString m_tempPath;
// each book has one record in this array:
wxHtmlBookRecArray m_bookRecords;
wxHtmlHelpDataItems m_contents; // list of all available books and pages
wxHtmlHelpDataItems m_index; // list of index itesm
#if WXWIN_COMPATIBILITY_2_4
// deprecated data structures, set only if GetContents(), GetIndex()
// called
wxHtmlContentsItem* m_cacheContents;
wxHtmlContentsItem* m_cacheIndex;
private:
void CleanCompatibilityData();
#endif
protected:
// Imports .hhp files (MS HTML Help Workshop)
bool LoadMSProject(wxHtmlBookRecord *book, wxFileSystem& fsys,
const wxString& indexfile, const wxString& contentsfile);
// Reads binary book
bool LoadCachedBook(wxHtmlBookRecord *book, wxInputStream *f);
// Writes binary book
bool SaveCachedBook(wxHtmlBookRecord *book, wxOutputStream *f);
DECLARE_NO_COPY_CLASS(wxHtmlHelpData)
};
#endif
#endif
| [
"[email protected]"
] | |
f74afdb1e74cfe2f218298e841c3db6d76256e07 | e571e187fb7cf617b74226b73dcd236e77f4343e | /src/irc.cpp | dce5e92ef087faf64b34bd1b33c1a996d39d4211 | [
"MIT"
] | permissive | arielshad/Phoenixcoin | d2e4cd6ef6e2bcd3c942ceda9c795d02c84afaa9 | 3f224acab0df765e97ad643b35d2cd6b81d38f79 | refs/heads/master | 2021-04-28T19:34:24.818968 | 2018-01-15T08:40:06 | 2018-01-15T08:40:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,968 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013-2014 Phoenixcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file LICENCE or http://www.opensource.org/licenses/mit-license.php
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
while(1)
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
while(1)
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
while(1)
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
// Make this thread recognisable as the IRC seeding thread
RenameThread("pxc-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
/* Dont advertise on IRC if we don't allow incoming connections */
if (mapArgs.count("-connect") || fNoListen)
return;
if (!GetBoolArg("-irc", false))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
while(!fShutdown) {
SOCKET hSocket;
CService addrConnect("irc.lfnet.org", 6667, true);
if(!ConnectSocket(addrConnect, hSocket)) {
addrConnect = CService("pelican.heliacal.net", 6667, true);
if(!ConnectSocket(addrConnect, hSocket)) {
addrConnect = CService("giraffe.heliacal.net", 6667, true);
if(!ConnectSocket(addrConnect, hSocket)) {
printf("IRC connect failed!\n");
nErrorWait = nErrorWait * 11 / 10;
if(Wait(nErrorWait += 60)) continue;
else return;
}
}
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
if (GetLocal(addrLocal, &addrIPv4))
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%u", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
if (addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #phoenixcoinTEST3\r");
Send(hSocket, "WHO #phoenixcoinTEST3\r");
} else {
// randomly join #phoenixcoin00-#phoenixcoin09
// int channel_number = GetRandInt(10);
// use one channel for now
int channel_number = 0;
Send(hSocket, strprintf("JOIN #phoenixcoin%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #phoenixcoin%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :[email protected] JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
bool fAddStatus = false;
if(fBerkeleyAddrDB)
fAddStatus = AddAddress(addr, 51 * 60);
else
fAddStatus = addrman.Add(addr, addrConnect, 51 * 60);
if(fAddStatus)
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
| [
"[email protected]"
] | |
b7cad59e7ee11b06fe75c6810020ed9006ec5bc8 | 3cd1e6cff03461acf5edc1d25f253f1a0af383d0 | /lib/Target/MSP430/MSP430ISelLowering.h | d8ad02fca40394c6e30f054a103ac05bde97866e | [
"NCSA"
] | permissive | Quantum-Platinum-Cloud/llvmCore | aacb91b619df609f1baf91df966e31a15bda31cc | 06636e2aa0be8e24b9c3ed903480bdd49471ee5d | refs/heads/main | 2023-08-23T17:42:51.782394 | 2013-10-29T00:03:36 | 2021-10-06T05:26:44 | 589,028,216 | 1 | 0 | NOASSERTION | 2023-01-14T20:31:25 | 2023-01-14T20:31:24 | null | UTF-8 | C++ | false | false | 7,302 | h | //===-- MSP430ISelLowering.h - MSP430 DAG Lowering Interface ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interfaces that MSP430 uses to lower LLVM code into a
// selection DAG.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TARGET_MSP430_ISELLOWERING_H
#define LLVM_TARGET_MSP430_ISELLOWERING_H
#include "MSP430.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/Target/TargetLowering.h"
namespace llvm {
namespace MSP430ISD {
enum {
FIRST_NUMBER = ISD::BUILTIN_OP_END,
/// Return with a flag operand. Operand 0 is the chain operand.
RET_FLAG,
/// Same as RET_FLAG, but used for returning from ISRs.
RETI_FLAG,
/// Y = R{R,L}A X, rotate right (left) arithmetically
RRA, RLA,
/// Y = RRC X, rotate right via carry
RRC,
/// CALL - These operations represent an abstract call
/// instruction, which includes a bunch of information.
CALL,
/// Wrapper - A wrapper node for TargetConstantPool, TargetExternalSymbol,
/// and TargetGlobalAddress.
Wrapper,
/// CMP - Compare instruction.
CMP,
/// SetCC - Operand 0 is condition code, and operand 1 is the flag
/// operand produced by a CMP instruction.
SETCC,
/// MSP430 conditional branches. Operand 0 is the chain operand, operand 1
/// is the block to branch if condition is true, operand 2 is the
/// condition code, and operand 3 is the flag operand produced by a CMP
/// instruction.
BR_CC,
/// SELECT_CC - Operand 0 and operand 1 are selection variable, operand 3
/// is condition code and operand 4 is flag operand.
SELECT_CC,
/// SHL, SRA, SRL - Non-constant shifts.
SHL, SRA, SRL
};
}
class MSP430Subtarget;
class MSP430TargetMachine;
class MSP430TargetLowering : public TargetLowering {
public:
explicit MSP430TargetLowering(MSP430TargetMachine &TM);
virtual MVT getShiftAmountTy(EVT LHSTy) const { return MVT::i8; }
/// LowerOperation - Provide custom lowering hooks for some operations.
virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
/// getTargetNodeName - This method returns the name of a target specific
/// DAG node.
virtual const char *getTargetNodeName(unsigned Opcode) const;
SDValue LowerShifts(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerSETCC(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerSIGN_EXTEND(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const;
SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
SDValue getReturnAddressFrameIndex(SelectionDAG &DAG) const;
TargetLowering::ConstraintType
getConstraintType(const std::string &Constraint) const;
std::pair<unsigned, const TargetRegisterClass*>
getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const;
/// isTruncateFree - Return true if it's free to truncate a value of type
/// Ty1 to type Ty2. e.g. On msp430 it's free to truncate a i16 value in
/// register R15W to i8 by referencing its sub-register R15B.
virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
virtual bool isTruncateFree(EVT VT1, EVT VT2) const;
/// isZExtFree - Return true if any actual instruction that defines a value
/// of type Ty1 implicit zero-extends the value to Ty2 in the result
/// register. This does not necessarily include registers defined in unknown
/// ways, such as incoming arguments, or copies from unknown virtual
/// registers. Also, if isTruncateFree(Ty2, Ty1) is true, this does not
/// necessarily apply to truncate instructions. e.g. on msp430, all
/// instructions that define 8-bit values implicit zero-extend the result
/// out to 16 bits.
virtual bool isZExtFree(Type *Ty1, Type *Ty2) const;
virtual bool isZExtFree(EVT VT1, EVT VT2) const;
MachineBasicBlock* EmitInstrWithCustomInserter(MachineInstr *MI,
MachineBasicBlock *BB) const;
MachineBasicBlock* EmitShiftInstr(MachineInstr *MI,
MachineBasicBlock *BB) const;
private:
SDValue LowerCCCCallTo(SDValue Chain, SDValue Callee,
CallingConv::ID CallConv, bool isVarArg,
bool isTailCall,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const;
SDValue LowerCCCArguments(SDValue Chain,
CallingConv::ID CallConv,
bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl,
SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const;
SDValue LowerCallResult(SDValue Chain, SDValue InFlag,
CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const;
virtual SDValue
LowerFormalArguments(SDValue Chain,
CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const;
virtual SDValue
LowerCall(TargetLowering::CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const;
virtual SDValue
LowerReturn(SDValue Chain,
CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
DebugLoc dl, SelectionDAG &DAG) const;
virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op,
SDValue &Base,
SDValue &Offset,
ISD::MemIndexedMode &AM,
SelectionDAG &DAG) const;
const MSP430Subtarget &Subtarget;
const TargetData *TD;
};
} // namespace llvm
#endif // LLVM_TARGET_MSP430_ISELLOWERING_H
| [
"[email protected]"
] | |
d7b17ba663b221791ec1588262d2bee301c9c5fd | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_repos_function_567_mutt-1.4.2.3.cpp | 3e6936d519449a22cb47b1e90767874895971f31 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | void fgetconv_close (FGETCONV **_fc)
{
struct fgetconv_s *fc = (struct fgetconv_s *) *_fc;
if (fc->cd != (iconv_t)-1)
iconv_close (fc->cd);
safe_free ((void **) _fc);
} | [
"[email protected]"
] | |
925fb2b15f1a31c8f1be2fc6beea316085050b1f | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /eflo/include/alibabacloud/eflo/model/AssociateVpdCidrBlockResult.h | 09ce18de7e8f8e33dd9a487b1bf18037aec4ecc0 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,569 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_EFLO_MODEL_ASSOCIATEVPDCIDRBLOCKRESULT_H_
#define ALIBABACLOUD_EFLO_MODEL_ASSOCIATEVPDCIDRBLOCKRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/eflo/EfloExport.h>
namespace AlibabaCloud
{
namespace Eflo
{
namespace Model
{
class ALIBABACLOUD_EFLO_EXPORT AssociateVpdCidrBlockResult : public ServiceResult
{
public:
struct Content
{
std::string vpdId;
};
AssociateVpdCidrBlockResult();
explicit AssociateVpdCidrBlockResult(const std::string &payload);
~AssociateVpdCidrBlockResult();
std::string getMessage()const;
Content getContent()const;
int getCode()const;
protected:
void parse(const std::string &payload);
private:
std::string message_;
Content content_;
int code_;
};
}
}
}
#endif // !ALIBABACLOUD_EFLO_MODEL_ASSOCIATEVPDCIDRBLOCKRESULT_H_ | [
"[email protected]"
] | |
838efefab38b9b4e4e5bc944a806f24fb4bcec4c | 67ce8ff142f87980dba3e1338dabe11af50c5366 | /opencv/src/opencv/modules/dnn/src/layers/crop_and_resize_layer.cpp | 08cf1a47aabfd68cef2bf2e0bb1b13243f5b5a83 | [
"Apache-2.0"
] | permissive | checksummaster/depthmovie | 794ff1c5a99715df4ea81abd4198e8e4e68cc484 | b0f1c233afdaeaaa5546e793a3e4d34c4977ca10 | refs/heads/master | 2023-04-19T01:45:06.237313 | 2021-04-30T20:34:16 | 2021-04-30T20:34:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,882 | cpp | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
// Copyright (C) 2018, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
#include "../precomp.hpp"
#include "../ie_ngraph.hpp"
#include "layers_common.hpp"
#ifdef HAVE_CUDA
#include "../cuda4dnn/primitives/crop_and_resize.hpp"
using namespace cv::dnn::cuda4dnn;
#endif
namespace cv { namespace dnn {
class CropAndResizeLayerImpl CV_FINAL : public CropAndResizeLayer
{
public:
CropAndResizeLayerImpl(const LayerParams& params)
{
setParamsFrom(params);
CV_Assert_N(params.has("width"), params.has("height"));
outWidth = params.get<float>("width");
outHeight = params.get<float>("height");
}
virtual bool supportBackend(int backendId) CV_OVERRIDE
{
return backendId == DNN_BACKEND_OPENCV
|| backendId == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH
|| backendId == DNN_BACKEND_CUDA
;
}
bool getMemoryShapes(const std::vector<MatShape> &inputs,
const int requiredOutputs,
std::vector<MatShape> &outputs,
std::vector<MatShape> &internals) const CV_OVERRIDE
{
CV_Assert_N(inputs.size() == 2, inputs[0].size() == 4);
if (inputs[0][0] != 1)
CV_Error(Error::StsNotImplemented, "");
outputs.resize(1, MatShape(4));
outputs[0][0] = inputs[1][2]; // Number of bounding boxes.
outputs[0][1] = inputs[0][1]; // Number of channels.
outputs[0][2] = outHeight;
outputs[0][3] = outWidth;
return false;
}
void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
{
CV_TRACE_FUNCTION();
CV_TRACE_ARG_VALUE(name, "name", name.c_str());
if (inputs_arr.depth() == CV_16S)
{
forward_fallback(inputs_arr, outputs_arr, internals_arr);
return;
}
std::vector<Mat> inputs, outputs;
inputs_arr.getMatVector(inputs);
outputs_arr.getMatVector(outputs);
Mat& inp = inputs[0];
Mat& out = outputs[0];
Mat boxes = inputs[1].reshape(1, inputs[1].total() / 7);
const int numChannels = inp.size[1];
const int inpHeight = inp.size[2];
const int inpWidth = inp.size[3];
const int inpSpatialSize = inpHeight * inpWidth;
const int outSpatialSize = outHeight * outWidth;
CV_Assert_N(inp.isContinuous(), out.isContinuous());
for (int b = 0; b < boxes.rows; ++b)
{
float* outDataBox = out.ptr<float>(b);
float left = boxes.at<float>(b, 3);
float top = boxes.at<float>(b, 4);
float right = boxes.at<float>(b, 5);
float bottom = boxes.at<float>(b, 6);
float boxWidth = right - left;
float boxHeight = bottom - top;
float heightScale = boxHeight * static_cast<float>(inpHeight - 1) / (outHeight - 1);
float widthScale = boxWidth * static_cast<float>(inpWidth - 1) / (outWidth - 1);
for (int y = 0; y < outHeight; ++y)
{
float input_y = top * (inpHeight - 1) + y * heightScale;
int y0 = static_cast<int>(input_y);
const float* inpData_row0 = inp.ptr<float>(0, 0, y0);
const float* inpData_row1 = (y0 + 1 < inpHeight) ? (inpData_row0 + inpWidth) : inpData_row0;
for (int x = 0; x < outWidth; ++x)
{
float input_x = left * (inpWidth - 1) + x * widthScale;
int x0 = static_cast<int>(input_x);
int x1 = std::min(x0 + 1, inpWidth - 1);
float* outData = outDataBox + y * outWidth + x;
const float* inpData_row0_c = inpData_row0;
const float* inpData_row1_c = inpData_row1;
for (int c = 0; c < numChannels; ++c)
{
*outData = inpData_row0_c[x0] +
(input_y - y0) * (inpData_row1_c[x0] - inpData_row0_c[x0]) +
(input_x - x0) * (inpData_row0_c[x1] - inpData_row0_c[x0] +
(input_y - y0) * (inpData_row1_c[x1] - inpData_row0_c[x1] - inpData_row1_c[x0] + inpData_row0_c[x0]));
inpData_row0_c += inpSpatialSize;
inpData_row1_c += inpSpatialSize;
outData += outSpatialSize;
}
}
}
}
if (boxes.rows < out.size[0])
{
// left = top = right = bottom = 0
std::vector<cv::Range> dstRanges(4, Range::all());
dstRanges[0] = Range(boxes.rows, out.size[0]);
out(dstRanges).setTo(inp.ptr<float>(0, 0, 0)[0]);
}
}
#ifdef HAVE_DNN_NGRAPH
virtual Ptr<BackendNode> initNgraph(const std::vector<Ptr<BackendWrapper> >& inputs,
const std::vector<Ptr<BackendNode> >& nodes) CV_OVERRIDE
{
// Slice second input: from 1x1xNx7 to 1x1xNx5
auto input = nodes[0].dynamicCast<InfEngineNgraphNode>()->node;
auto rois = nodes[1].dynamicCast<InfEngineNgraphNode>()->node;
std::vector<size_t> dims = rois->get_shape(), offsets(4, 0);
offsets[3] = 2;
dims[3] = 7;
auto lower_bounds = std::make_shared<ngraph::op::Constant>(ngraph::element::i64,
ngraph::Shape{offsets.size()}, offsets.data());
auto upper_bounds = std::make_shared<ngraph::op::Constant>(ngraph::element::i64,
ngraph::Shape{dims.size()}, dims.data());
auto strides = std::make_shared<ngraph::op::Constant>(ngraph::element::i64,
ngraph::Shape{dims.size()}, std::vector<int64_t>((int64_t)dims.size(), 1));
auto slice = std::make_shared<ngraph::op::v1::StridedSlice>(rois,
lower_bounds, upper_bounds, strides, std::vector<int64_t>{}, std::vector<int64_t>{});
// Reshape rois from 4D to 2D
std::vector<size_t> shapeData = {dims[2], 5};
auto shape = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{2}, shapeData.data());
auto reshape = std::make_shared<ngraph::op::v1::Reshape>(slice, shape, true);
auto roiPooling =
std::make_shared<ngraph::op::v0::ROIPooling>(input, reshape,
ngraph::Shape{(size_t)outHeight, (size_t)outWidth},
1.0f, "bilinear");
return Ptr<BackendNode>(new InfEngineNgraphNode(roiPooling));
}
#endif // HAVE_DNN_NGRAPH
#ifdef HAVE_CUDA
Ptr<BackendNode> initCUDA(
void *context_,
const std::vector<Ptr<BackendWrapper>>& inputs,
const std::vector<Ptr<BackendWrapper>>& outputs
) override
{
auto context = reinterpret_cast<csl::CSLContext*>(context_);
return make_cuda_node<cuda4dnn::CropAndResizeOp>(preferableTarget, std::move(context->stream));
}
#endif
private:
int outWidth, outHeight;
};
Ptr<Layer> CropAndResizeLayer::create(const LayerParams& params)
{
return Ptr<CropAndResizeLayer>(new CropAndResizeLayerImpl(params));
}
} // namespace dnn
} // namespace cv
| [
"[email protected]"
] | |
f31753962883c4d859e70c55868ea6f88e6b19c7 | f4d47239db040bd5a3842ae92e9b3e65a9df0d87 | /calibration_common/include/calibration_common/objects/with_points.h | a0fd2f76750b9b0693a6d72f1974172f03cc9900 | [
"BSD-2-Clause"
] | permissive | iaslab-unipd/calibration_toolkit | b3931aa3e6d29af1273e8253a10e5f5e2d7bd9b0 | ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212 | refs/heads/indigo | 2022-01-20T06:04:20.972129 | 2016-01-07T11:33:11 | 2016-01-07T11:33:11 | 15,998,666 | 27 | 16 | BSD-3-Clause | 2022-01-10T14:08:31 | 2014-01-17T12:02:29 | C++ | UTF-8 | C++ | false | false | 2,095 | h | /*
* Copyright (c) 2015-, Filippo Basso <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder(s) nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef UNIPD_CALIBRATION_CALIBRATION_COMMON_OBJECTS_WITH_POINTS_H_
#define UNIPD_CALIBRATION_CALIBRATION_COMMON_OBJECTS_WITH_POINTS_H_
#include <calibration_common/base/eigen_cloud.h>
namespace unipd
{
namespace calib
{
struct WithPoints
{
virtual
~WithPoints ()
{
// Do nothing
}
virtual const Cloud3 &
points () const = 0;
};
} // namespace calib
} // namespace unipd
#endif // UNIPD_CALIBRATION_CALIBRATION_COMMON_OBJECTS_WITH_POINTS_H_
| [
"[email protected]"
] | |
0e3b58ea763478030ab5f64f0a4526586418e697 | 04e5b6df2ee3bcfb7005d8ec91aab8e380333ac4 | /clang_codecompletion/llvm/DebugInfo/GSYM/FunctionInfo.h | 552337f543901e569ee1ba1ed3a3bbead6a68414 | [
"MIT"
] | permissive | ColdGrub1384/Pyto | 64e2a593957fd640907f0e4698d430ea7754a73e | 7557485a733dd7e17ba0366b92794931bdb39975 | refs/heads/main | 2023-08-01T03:48:35.694832 | 2022-07-20T14:38:45 | 2022-07-20T14:38:45 | 148,944,721 | 884 | 157 | MIT | 2023-02-26T21:34:04 | 2018-09-15T22:29:07 | C | UTF-8 | C++ | false | false | 8,597 | h | //===- FunctionInfo.h -------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_DEBUGINFO_GSYM_FUNCTIONINFO_H
#define LLVM_DEBUGINFO_GSYM_FUNCTIONINFO_H
#include "llvm/ADT/Optional.h"
#include "llvm/DebugInfo/GSYM/InlineInfo.h"
#include "llvm/DebugInfo/GSYM/LineTable.h"
#include "llvm/DebugInfo/GSYM/LookupResult.h"
#include "llvm/DebugInfo/GSYM/Range.h"
#include "llvm/DebugInfo/GSYM/StringTable.h"
#include <cstdint>
#include <tuple>
namespace llvm {
class raw_ostream;
namespace gsym {
class GsymReader;
/// Function information in GSYM files encodes information for one contiguous
/// address range. If a function has discontiguous address ranges, they will
/// need to be encoded using multiple FunctionInfo objects.
///
/// ENCODING
///
/// The function information gets the function start address as an argument
/// to the FunctionInfo::decode(...) function. This information is calculated
/// from the GSYM header and an address offset from the GSYM address offsets
/// table. The encoded FunctionInfo information must be aligned to a 4 byte
/// boundary.
///
/// The encoded data for a FunctionInfo starts with fixed data that all
/// function info objects have:
///
/// ENCODING NAME DESCRIPTION
/// ========= =========== ====================================================
/// uint32_t Size The size in bytes of this function.
/// uint32_t Name The string table offset of the function name.
///
/// The optional data in a FunctionInfo object follows this fixed information
/// and consists of a stream of tuples that consist of:
///
/// ENCODING NAME DESCRIPTION
/// ========= =========== ====================================================
/// uint32_t InfoType An "InfoType" enumeration that describes the type
/// of optional data that is encoded.
/// uint32_t InfoLength The size in bytes of the encoded data that
/// immediately follows this length if this value is
/// greater than zero.
/// uint8_t[] InfoData Encoded bytes that represent the data for the
/// "InfoType". These bytes are only present if
/// "InfoLength" is greater than zero.
///
/// The "InfoType" is an enumeration:
///
/// enum InfoType {
/// EndOfList = 0u,
/// LineTableInfo = 1u,
/// InlineInfo = 2u
/// };
///
/// This stream of tuples is terminated by a "InfoType" whose value is
/// InfoType::EndOfList and a zero for "InfoLength". This signifies the end of
/// the optional information list. This format allows us to add new optional
/// information data to a FunctionInfo object over time and allows older
/// clients to still parse the format and skip over any data that they don't
/// understand or want to parse.
///
/// So the function information encoding essientially looks like:
///
/// struct {
/// uint32_t Size;
/// uint32_t Name;
/// struct {
/// uint32_t InfoType;
/// uint32_t InfoLength;
/// uint8_t InfoData[InfoLength];
/// }[N];
/// }
///
/// Where "N" is the number of tuples.
struct FunctionInfo {
AddressRange Range;
uint32_t Name; ///< String table offset in the string table.
llvm::Optional<LineTable> OptLineTable;
llvm::Optional<InlineInfo> Inline;
FunctionInfo(uint64_t Addr = 0, uint64_t Size = 0, uint32_t N = 0)
: Range(Addr, Addr + Size), Name(N) {}
/// Query if a FunctionInfo has rich debug info.
///
/// \returns A bool that indicates if this object has something else than
/// range and name. When converting information from a symbol table and from
/// debug info, we might end up with multiple FunctionInfo objects for the
/// same range and we need to be able to tell which one is the better object
/// to use.
bool hasRichInfo() const {
return OptLineTable.hasValue() || Inline.hasValue();
}
/// Query if a FunctionInfo object is valid.
///
/// Address and size can be zero and there can be no line entries for a
/// symbol so the only indication this entry is valid is if the name is
/// not zero. This can happen when extracting information from symbol
/// tables that do not encode symbol sizes. In that case only the
/// address and name will be filled in.
///
/// \returns A boolean indicating if this FunctionInfo is valid.
bool isValid() const {
return Name != 0;
}
/// Decode an object from a binary data stream.
///
/// \param Data The binary stream to read the data from. This object must
/// have the data for the object starting at offset zero. The data
/// can contain more data than needed.
///
/// \param BaseAddr The FunctionInfo's start address and will be used as the
/// base address when decoding any contained information like the line table
/// and the inline info.
///
/// \returns An FunctionInfo or an error describing the issue that was
/// encountered during decoding.
static llvm::Expected<FunctionInfo> decode(DataExtractor &Data,
uint64_t BaseAddr);
/// Encode this object into FileWriter stream.
///
/// \param O The binary stream to write the data to at the current file
/// position.
///
/// \returns An error object that indicates failure or the offset of the
/// function info that was successfully written into the stream.
llvm::Expected<uint64_t> encode(FileWriter &O) const;
/// Lookup an address within a FunctionInfo object's data stream.
///
/// Instead of decoding an entire FunctionInfo object when doing lookups,
/// we can decode only the information we need from the FunctionInfo's data
/// for the specific address. The lookup result information is returned as
/// a LookupResult.
///
/// \param Data The binary stream to read the data from. This object must
/// have the data for the object starting at offset zero. The data
/// can contain more data than needed.
///
/// \param GR The GSYM reader that contains the string and file table that
/// will be used to fill in information in the returned result.
///
/// \param FuncAddr The function start address decoded from the GsymReader.
///
/// \param Addr The address to lookup.
///
/// \returns An LookupResult or an error describing the issue that was
/// encountered during decoding. An error should only be returned if the
/// address is not contained in the FunctionInfo or if the data is corrupted.
static llvm::Expected<LookupResult> lookup(DataExtractor &Data,
const GsymReader &GR,
uint64_t FuncAddr,
uint64_t Addr);
uint64_t startAddress() const { return Range.Start; }
uint64_t endAddress() const { return Range.End; }
uint64_t size() const { return Range.size(); }
void setStartAddress(uint64_t Addr) { Range.Start = Addr; }
void setEndAddress(uint64_t Addr) { Range.End = Addr; }
void setSize(uint64_t Size) { Range.End = Range.Start + Size; }
void clear() {
Range = {0, 0};
Name = 0;
OptLineTable = None;
Inline = None;
}
};
inline bool operator==(const FunctionInfo &LHS, const FunctionInfo &RHS) {
return LHS.Range == RHS.Range && LHS.Name == RHS.Name &&
LHS.OptLineTable == RHS.OptLineTable && LHS.Inline == RHS.Inline;
}
inline bool operator!=(const FunctionInfo &LHS, const FunctionInfo &RHS) {
return !(LHS == RHS);
}
/// This sorting will order things consistently by address range first, but then
/// followed by inlining being valid and line tables. We might end up with a
/// FunctionInfo from debug info that will have the same range as one from the
/// symbol table, but we want to quickly be able to sort and use the best version
/// when creating the final GSYM file.
inline bool operator<(const FunctionInfo &LHS, const FunctionInfo &RHS) {
// First sort by address range
if (LHS.Range != RHS.Range)
return LHS.Range < RHS.Range;
// Then sort by inline
if (LHS.Inline.hasValue() != RHS.Inline.hasValue())
return RHS.Inline.hasValue();
return LHS.OptLineTable < RHS.OptLineTable;
}
raw_ostream &operator<<(raw_ostream &OS, const FunctionInfo &R);
} // namespace gsym
} // namespace llvm
#endif // LLVM_DEBUGINFO_GSYM_FUNCTIONINFO_H
| [
"[email protected]"
] | |
498364e2cb923a7e3b57d26378eca0a5634165bc | 93ee0186c389f7e57a6f97188049b79e91cde5b1 | /others/InversionCount/InversionCount/main.cpp | 0f70b53dcc96dda6f2692b784cff8127dd051238 | [] | no_license | BessieChen/Algorithms | e737c6a3a1152d6b3986d4504b292f7bc31b806b | 14ff4e4b53b3e23d2aebde14b8c92ef4fc7b9e27 | refs/heads/master | 2021-02-07T23:41:58.302326 | 2020-03-01T04:40:31 | 2020-03-01T04:40:31 | 244,088,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | cpp | //
// main.cpp
// InversionCount
//
// Created by 陈贝茜 on 2019/7/1.
// Copyright © 2019 Bessie Chen. All rights reserved.
//
#include <iostream>
#include "TestHelper.h"
#include "InverseCount.h"
using namespace std;
int main() {
int n = 1000000;
// 测试1: 测试随机数组
cout<<"Test Inversion Count for Random Array, n = "<<n<<" :"<<endl;
int* arr = TestHelper::generateRandomArray(n, 0, n);
cout<<inverseCount(arr, n)<<endl<<endl;
delete[] arr;
// 测试2: 测试完全有序的数组
// 结果应该为0
cout<<"Test Inversion Count for Ordered Array, n = "<<n<<" :"<<endl;
arr = TestHelper::generateOrderedArray(n);
cout<<inverseCount(arr, n)<<endl<<endl;
delete[] arr;
// 测试3: 测试完全逆序的数组
// 结果应改为 N*(N-1)/2
cout<<"Test Inversion Count for Inversed Array, n = "<<n<<" :"<<endl;
arr = TestHelper::generateInversedArray(n);
cout<<inverseCount(arr, n)<<endl;
delete[] arr;
return 0;
}
| [
"[email protected]"
] | |
c05c10701e1418d4e0473513614ad57b9b37a54a | 09bdb299a70cc773cfaa1a2c814d39df05aa8656 | /TeapotAD/TeapotAD/scenediffuse.h | 2c97c423c467ca0a14b3a24b287d2deb26d3d2d5 | [] | no_license | imat2908/lighting-Xeltania | 82e9183c309ede7376591ef2b21cfcb747cd1491 | 45c1e455e9f59947996cd3437a14b57ab9ed9e74 | refs/heads/master | 2022-04-09T23:12:16.751262 | 2020-03-25T11:07:10 | 2020-03-25T11:07:10 | 248,068,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | h | #ifndef SCENEDIFFUSE_H
#define SCENEDIFFUSE_H
#include "gl_core_4_3.hpp"
#include <glfw3.h>
#include "scene.h"
#include "glslprogram.h"
#include "vboteapot.h"
#include "vboplane.h"
#include <glm.hpp>
using glm::mat4;
namespace imat2908
{
class SceneDiffuse : public Scene
{
private:
GLSLProgram prog;
int width, height;
VBOTeapot *teapot; //Teapot VBO
VBOPlane *plane; //Plane VBO
mat4 model; //Model matrix
void setMatrices(QuatCamera camera); //Set the camera matrices
void compileAndLinkShader(); //Compile and link the shader
public:
SceneDiffuse(); //Constructor
void setLightParams(QuatCamera camera); //Setup the lighting
void initScene(QuatCamera camera); //Initialise the scene
void update( float t); //Update the scene
void render(QuatCamera camera); //Render the scene
void resize(QuatCamera camera, int, int); //Resize
};
}
#endif // SCENEDIFFUSE_H
| [
"[email protected]"
] | |
db54602639a03f88443400d20207ee8016b0b0e5 | 296baf47d116a1ac101e2461ac003e39a11588ef | /1022.cpp | c412a5313d66e24b7122825c4412e34536babe6f | [] | no_license | AnaRaquelCP/URI-solutions | 46e658060b425e84bf90ddee5db982e5346114da | af42cfd251d16f5af5757af88bdc44ae9859790f | refs/heads/master | 2020-05-02T03:42:29.654656 | 2015-08-22T15:31:22 | 2015-08-22T15:31:22 | 41,211,937 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cpp | #include <iostream>
#include <cmath>
using namespace std;
int mdc(int a, int b) {
if (b == 0)
return a;
return mdc(b, a % b);
}
class Racional {
int num;
int den;
char sinal;
public:
Racional() { sinal = ' '; }
Racional(int n, int d) {
num = n;
den = d;
sinal = ' ';
}
static Racional soma(Racional n1, Racional n2) {
Racional res;
res.num = n1.num * n2.den + n2.num * n1.den;
res.den = n1.den * n2.den;
return res;
}
static Racional sub(Racional n1, Racional n2) {
Racional res;
res.num = n1.num * n2.den - n2.num * n1.den;
res.den = n1.den * n2.den;
if(res.num < 0 || res.den < 0) {
res.num = abs(res.num);
res.den = abs(res.den);
res.sinal = '-';
}
return res;
}
static Racional mult(Racional n1, Racional n2) {
Racional res;
res.num = n1.num * n2.num;
res.den = n1.den * n2.den;
return res;
}
static Racional div(Racional n1, Racional n2) {
Racional res;
res.num = n1.num * n2.den;
res.den = n2.num * n1.den;
return res;
}
void simplifica() {
int x = mdc(num, den);
num /= x;
den /= x;
}
void imprimi() {
if(sinal != ' ')
cout << sinal << num << "/" << den;
else
cout << num << "/" << den;
}
};
void operacao(Racional n1, Racional n2, char op) {
Racional res;
switch(op) {
case '+':
res = Racional::soma(n1, n2);
break;
case '-':
res = Racional::sub(n1, n2);
break;
case '*':
res = Racional::mult(n1, n2);
break;
case '/':
res = Racional::div(n1, n2);
break;
}
res.imprimi(); cout << " = ";
res.simplifica();
res.imprimi(); cout << endl;
}
int main(){
int qtd, n, d;
char aux, op;
cin >> qtd;
while(qtd){
cin >> n;
cin >> aux;
cin >> d;
Racional n1(n,d);
cin >> op;
cin >> n;
cin >> aux;
cin >> d;
Racional n2(n,d);
operacao(n1, n2, op);
qtd--;
}
}
| [
"[email protected]"
] | |
049fdab3ef5e730abacb96c578a8a9be0a63d587 | 38c10c01007624cd2056884f25e0d6ab85442194 | /content/child/child_resource_message_filter.h | 2a92fcc5fb8e0e10fc2bd0f1713a8ce511a0c00e | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 1,932 | h | // Copyright 2013 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 CONTENT_CHILD_CHILD_RESOURCE_MESSAGE_FILTER_H_
#define CONTENT_CHILD_CHILD_RESOURCE_MESSAGE_FILTER_H_
#include "base/memory/ref_counted.h"
#include "ipc/message_filter.h"
namespace base {
class SingleThreadTaskRunner;
}
namespace content {
class ResourceDispatcher;
// Supplies ResourceDispatcher with timestamps for some resource messages.
//
// Background: ResourceDispatcher converts browser process time to child
// process time. This is done to achieve coherent timeline. Conversion is
// a linear transformation such that given browser process time range is
// mapped to corresponding child process time range. Timestamps for child
// process time range should be taken by IO thread when resource messages
// arrive. Otherwise, timestamps may be affected by long rendering / JS task.
//
// When specific message is processed by this filter, new task charged
// with timestamp is posted to main thread. This task is processed just before
// resource message and invokes ResourceDispatcher::set_io_timestamp.
class ChildResourceMessageFilter : public IPC::MessageFilter {
public:
explicit ChildResourceMessageFilter(ResourceDispatcher* resource_dispatcher);
// IPC::MessageFilter implementation.
bool OnMessageReceived(const IPC::Message& message) override;
void SetMainThreadTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner) {
main_thread_task_runner_ = main_thread_task_runner;
}
private:
~ChildResourceMessageFilter() override;
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
ResourceDispatcher* resource_dispatcher_;
DISALLOW_COPY_AND_ASSIGN(ChildResourceMessageFilter);
};
} // namespace content
#endif // CONTENT_CHILD_CHILD_RESOURCE_MESSAGE_FILTER_H_
| [
"[email protected]"
] | |
b5e8844bd17f21225dde42ad6538c804c0f52202 | 032013d17b506b2eb732a535b9e42df148d9a75d | /src/plugins/azoth/plugins/murm/vkconnection.h | 1f300b90cbebf0d8cb7b59df982e6b3cd96e53dc | [
"BSL-1.0"
] | permissive | zhao07/leechcraft | 55bb64d6eab590a69d92585150ae1af3d32ee342 | 4100c5bf3a260b8bc041c14902e2f7b74da638a3 | refs/heads/master | 2021-01-22T11:59:18.782462 | 2014-04-01T14:04:10 | 2014-04-01T14:04:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,297 | h | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#pragma once
#include <functional>
#include <QObject>
#include <QHash>
#include <QVariantList>
#include <QVariantMap>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/azoth/iclentry.h>
#include "structures.h"
namespace LeechCraft
{
namespace Util
{
class QueueManager;
namespace SvcAuth
{
class VkAuthManager;
}
}
namespace Azoth
{
namespace Murm
{
class LongPollManager;
class Logger;
class VkConnection : public QObject
{
Q_OBJECT
LeechCraft::Util::SvcAuth::VkAuthManager * const AuthMgr_;
const ICoreProxy_ptr Proxy_;
Logger& Logger_;
QByteArray LastCookies_;
public:
typedef QMap<QString, QString> UrlParams_t;
class PreparedCall_f
{
std::function<QNetworkReply* (QString, UrlParams_t)> Call_;
UrlParams_t Params_;
public:
PreparedCall_f () = default;
template<typename T>
PreparedCall_f (T c)
: Call_ (c)
{
}
QNetworkReply* operator() (const QString& key) const
{
return Call_ (key, Params_);
}
void ClearParams ()
{
Params_.clear ();
}
void AddParam (const QPair<QString, QString>& pair)
{
Params_ [pair.first] = pair.second;
}
};
private:
QList<PreparedCall_f> PreparedCalls_;
LeechCraft::Util::QueueManager *CallQueue_;
typedef QList<QPair<QNetworkReply*, PreparedCall_f>> RunningCalls_t;
RunningCalls_t RunningCalls_;
EntryStatus Status_;
EntryStatus CurrentStatus_;
LongPollManager *LPManager_;
public:
typedef std::function<void (QHash<int, QString>)> GeoSetter_f;
typedef std::function<void (QList<PhotoInfo>)> PhotoInfoSetter_f;
typedef std::function<void (FullMessageInfo)> MessageInfoSetter_f;
private:
QHash<int, std::function<void (QVariantList)>> Dispatcher_;
QHash<QNetworkReply*, std::function<void (qulonglong)>> MsgReply2Setter_;
QHash<QNetworkReply*, GeoSetter_f> CountryReply2Setter_;
QHash<QNetworkReply*, MessageInfoSetter_f> Reply2MessageSetter_;
QHash<QNetworkReply*, PhotoInfoSetter_f> Reply2PhotoSetter_;
QHash<QNetworkReply*, QString> Reply2ListName_;
QHash<QNetworkReply*, ChatInfo> Reply2ChatInfo_;
struct ChatRemoveInfo
{
qulonglong Chat_;
qulonglong User_;
};
QHash<QNetworkReply*, ChatRemoveInfo> Reply2ChatRemoveInfo_;
QHash<QString, PreparedCall_f> CaptchaId2Call_;
int APIErrorCount_ = 0;
bool ShouldRerunPrepared_ = false;
bool MarkingOnline_ = false;
QTimer * const MarkOnlineTimer_;
public:
enum class MessageType
{
Dialog,
Chat
};
VkConnection (const QString&, const QByteArray&, ICoreProxy_ptr, Logger&);
const QByteArray& GetCookies () const;
void RerequestFriends ();
void SendMessage (qulonglong to,
const QString& body,
std::function<void (qulonglong)> idSetter,
MessageType type);
void SendTyping (qulonglong to);
void MarkAsRead (const QList<qulonglong>&);
void RequestGeoIds (const QList<int>&, GeoSetter_f, GeoIdType);
void GetUserInfo (const QList<qulonglong>& ids);
void GetMessageInfo (qulonglong id, MessageInfoSetter_f setter);
void GetPhotoInfos (const QStringList& ids, PhotoInfoSetter_f setter);
void AddFriendList (const QString&, const QList<qulonglong>&);
void ModifyFriendList (const ListInfo&, const QList<qulonglong>&);
void SetNRIList (const QList<qulonglong>&);
void CreateChat (const QString&, const QList<qulonglong>&);
void RequestChatInfo (qulonglong);
void AddChatUser (qulonglong chat, qulonglong user);
void RemoveChatUser (qulonglong chat, qulonglong user);
void SetChatTitle (qulonglong, const QString&);
void SetStatus (QString);
void SetStatus (const EntryStatus&, bool updateString);
EntryStatus GetStatus () const;
void SetMarkingOnlineEnabled (bool);
void QueueRequest (PreparedCall_f);
static void AddParams (QUrl&, const UrlParams_t&);
void HandleCaptcha (const QString& cid, const QString& value);
private:
void PushFriendsRequest ();
RunningCalls_t::const_iterator FindRunning (QNetworkReply*) const;
RunningCalls_t::iterator FindRunning (QNetworkReply*);
void RescheduleRequest (QNetworkReply*);
bool CheckFinishedReply (QNetworkReply*);
bool CheckReplyData (const QVariant&, QNetworkReply*);
public slots:
void reauth ();
private slots:
void rerunPrepared ();
void callWithKey (const QString&);
void handleReplyDestroyed ();
void markOnline ();
void handleListening ();
void handlePollError ();
void handlePollStopped ();
void handlePollData (const QVariantMap&);
void handleFriendListAdded ();
void handleGotSelfInfo ();
void handleGotFriendLists ();
void handleGotFriends ();
void handleGotNRI ();
void handleGotUserInfo ();
void handleGotUnreadMessages ();
void handleChatCreated ();
void handleChatInfo ();
void handleChatUserRemoved ();
void handleMessageSent ();
void handleCountriesFetched ();
void handleMessageInfoFetched ();
void handlePhotoInfosFetched ();
void handleScopeSettingsChanged ();
void saveCookies (const QByteArray&);
signals:
void statusChanged (EntryStatus);
void cookiesChanged ();
void stoppedPolling ();
void gotSelfInfo (const UserInfo&);
void gotLists (const QList<ListInfo>&);
void addedLists (const QList<ListInfo>&);
void gotUsers (const QList<UserInfo>&);
void gotNRIList (const QList<qulonglong>&);
void gotMessage (const MessageInfo&);
void gotTypingNotification (qulonglong uid);
void gotChatInfo (const ChatInfo&);
void chatUserRemoved (qulonglong, qulonglong);
void userStateChanged (qulonglong uid, bool online);
void mucChanged (qulonglong);
void captchaNeeded (const QString& sid, const QUrl& url);
};
}
}
}
| [
"[email protected]"
] | |
aa817438ef1e2c76c8970b5dd954f8a7feaf087a | e3e333bfc10b1b1a06ffb0df2e6cdc417b4c3a34 | /catalog.cpp | 12a77a192ff3c438e1df9347e1c6f5552ba3e7d7 | [] | no_license | hasbro17/DB-P5-FrontEndDBUtilities | 20c39105b4d5bbc2f54410bd3fe7e060f7ceda16 | 5ece5d25b5cbcf747f035e6af8906d7c6e584576 | refs/heads/master | 2020-06-05T20:34:28.404060 | 2014-12-10T15:55:20 | 2014-12-10T15:55:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,966 | cpp | #include "catalog.h"
RelCatalog::RelCatalog(Status &status) :
HeapFile(RELCATNAME, status)
{
// nothing should be needed here
}
const Status RelCatalog::getInfo(const string & relation, RelDesc &record)
{
if (relation.empty())
return BADCATPARM;
Status status;
Record rec;
RID rid;
//Open up a HeapFileScan on our relCatalog file RELCATNAME
HeapFileScan *scan = new HeapFileScan(RELCATNAME, status);
if(status!=OK)
{
printf("MyError: Cannot open HeapFileScan(RELCATNAME) in getInfo\n");
return status;
}
//initiate a startScan for this relation
status=scan->startScan(0, MAXNAME, STRING, relation.data(), EQ);
if(status!=OK)
{
printf("MyError: Cannot initiate startScan in getInfo\n");
return status;
}
//do a scan next to get even one match.
status=scan->scanNext(rid);
if(status==FILEEOF)//should only be EOF
return RELNOTFOUND;
else if(status!=OK)
{
printf("MyError: Something wrong while scanNext() in getInfo\n");
return status;
}
//get record from RID
status=scan->getRecord(rec);
if(status!=OK)
{
printf("MyError: Problem in getRecord after valid scanNext in getInfo\n");
return status;
}
//memcopy the dbrecord data into the return param Reldesc record
memcpy(&record, rec.data, rec.length);
scan->endScan();
delete scan;
return OK;
}
const Status RelCatalog::addInfo(RelDesc & record)
{
RID rid;
InsertFileScan* ifs;
Status status;
Record rec;
ifs= new InsertFileScan(RELCATNAME, status);
if(status!=OK)
{
printf("MyError: Could not open InsertFileScan on relcatalog in addInfo\n");
return status;
}
//create a record to insert in ifs
rec.data=&record;
rec.length=sizeof(RelDesc);//sizeof(RelDesc);//FIXME:Check if this is correct.
//insert the record
status=ifs->insertRecord(rec, rid);
if(status!=OK)
{
printf("MyError: Could not insertRecord in relcatalog in addInfo\n");
return status;
}
delete ifs;
return OK;
}
const Status RelCatalog::removeInfo(const string & relation)
{
Status status;
RID rid;
HeapFileScan* scan;
if (relation.empty()) return BADCATPARM;
//Open up a HeapFileScan on our relCatalog file RELCATNAME
scan = new HeapFileScan(RELCATNAME, status);
if(status!=OK)
{
printf("MyError: Cannot open HeapFileScan(RELCATNAME) in removeInfo\n");
return status;
}
//initiate a startScan for this relation
status=scan->startScan(0, MAXNAME, STRING, relation.data(), EQ);
if(status!=OK)
{
printf("MyError: Cannot initiate startScan in removeInfo\n");
return status;
}
//do a scan next to get even one match.
status=scan->scanNext(rid);
if(status==FILEEOF)//should only be EOF
return RELNOTFOUND;
else if(status!=OK)
{
printf("MyError: Something wrong while scanNext() in removeInfo\n");
return status;
}
//delete the record that was saved in curRec from scanNext
status=scan->deleteRecord();
if(status!=OK)
{
printf("MyError: Something wrong while deleteRecord() in removeInfo\n");
return status;
}
scan->endScan();
delete scan;
return OK;
}
RelCatalog::~RelCatalog()
{
// nothing should be needed here
}
AttrCatalog::AttrCatalog(Status &status) :
HeapFile(ATTRCATNAME, status)
{
// nothing should be needed here
}
const Status AttrCatalog::getInfo(const string & relation,
const string & attrName,
AttrDesc &record)
{
Status status;
RID rid;
Record rec;
HeapFileScan* scan;
if (relation.empty() || attrName.empty()) return BADCATPARM;
//Open up a HeapFileScan on our relCatalog file RELCATNAME
scan = new HeapFileScan(ATTRCATNAME, status);
if(status!=OK)
{
printf("MyError: Cannot open HeapFileScan(ATTRCATNAME) in getInfo\n");
return status;
}
//initiate a startScan for this relation
status=scan->startScan(0, MAXNAME, STRING, relation.data(), EQ);
if(status!=OK)
{
printf("MyError: Cannot initiate startScan in AttrCat::getInfo()\n");
return status;
}
//scan for all records with the relation name
while(status!=FILEEOF)
{
status=scan->scanNext(rid);
if(status!=OK && status!=FILEEOF)
{
printf("MyError: Something wrong while scanNext() in AttrCat::getInfo()\n");
return status;
}
if(status==OK)//rec found
{
//get record from RID
status=scan->getRecord(rec);
if(status!=OK)
{
printf("MyError: Problem in getRecord after valid scanNext in AttrCat::getInfo()\n");
return status;
}
//memcopy the dbrecord data into the return param AttrDesc record
memcpy(&record, rec.data, rec.length);
//check if the record attrName matches the given attrName
if(strcmp(record.attrName, attrName.c_str())==0)
{
scan->endScan();
delete scan;
return OK;
}
}
}
//End of file so attr not found
scan->endScan();
delete scan;
return ATTRNOTFOUND;
}
const Status AttrCatalog::addInfo(AttrDesc & record)
{
RID rid;
InsertFileScan* ifs;
Status status;
Record rec;
ifs= new InsertFileScan(ATTRCATNAME, status);
if(status!=OK)
{
printf("MyError: Could not open InsertFileScan on attrcatalog in addInfo\n");
return status;
}
//create a record to insert in ifs
rec.data=&record;
rec.length=sizeof(AttrDesc);//FIXME:Check if this is correct.
//insert the record
status=ifs->insertRecord(rec, rid);
if(status!=OK)
{
printf("MyError: Could not insertRecord in attrcatalog in addInfo\n");
return status;
}
delete ifs;
return OK;
}
const Status AttrCatalog::removeInfo(const string & relation,
const string & attrName)
{
Status status;
Record rec;
RID rid;
AttrDesc record;
HeapFileScan* scan;
if (relation.empty() || attrName.empty()) return BADCATPARM;
//Open up a HeapFileScan on our relCatalog file RELCATNAME
scan = new HeapFileScan(ATTRCATNAME, status);
if(status!=OK)
{
printf("MyError: Cannot open HeapFileScan(ATTRCATNAME) in removeInfo\n");
return status;
}
//initiate a startScan for this relation
status=scan->startScan(0, MAXNAME, STRING, relation.data(), EQ);
if(status!=OK)
{
printf("MyError: Cannot initiate startScan in AttrCat::removeInfo()\n");
return status;
}
//scan for all records with the relation name
while(status!=FILEEOF)
{
status=scan->scanNext(rid);
if(status!=OK && status!=FILEEOF)
{
printf("MyError: Something wrong while scanNext() in AttrCat::removeInfo()\n");
return status;
}
if(status==OK)//rec found
{
//get record from RID
status=scan->getRecord(rec);
if(status!=OK)
{
printf("MyError: Problem in getRecord after valid scanNext in AttrCat::removeInfo()\n");
return status;
}
//memcopy the dbrecord data into the return param AttrDesc record
memcpy(&record, rec.data, rec.length);
//check if the record attrName matches the given attrName
if(strcmp(record.attrName, attrName.c_str())==0)
{
//delete the record that was saved in curRec from scanNext
status=scan->deleteRecord();
if(status!=OK)
{
printf("MyError: Something wrong while deleteRecord() in removeInfo\n");
return status;
}
}
}
}
return OK;//FIXME:What if attribute not found
}
const Status AttrCatalog::getRelInfo(const string & relation,
int &attrCnt,
AttrDesc *&attrs)
{
Status status;
RID rid;
Record rec;
AttrDesc record;
HeapFileScan* scan;
if (relation.empty()) return BADCATPARM;
//Open up a HeapFileScan on our relCatalog file RELCATNAME
scan = new HeapFileScan(ATTRCATNAME, status);
if(status!=OK)
{
printf("MyError: Cannot open HeapFileScan(ATTRCATNAME) in AttrCat::getRelInfo\n");
return status;
}
//initiate a startScan for this relation
status=scan->startScan(0, MAXNAME, STRING, relation.data(), EQ);
if(status!=OK)
{
printf("MyError: Cannot initiate startScan in AttrCat::getRelInfo()\n");
return status;
}
attrCnt=0;
std::vector<AttrDesc> relationMatch;//vector to hold all matches
//scan for all records with the relation name
while(status!=FILEEOF)
{
status=scan->scanNext(rid);
if(status!=OK && status!=FILEEOF)
{
printf("MyError: Something wrong while scanNext() in getRelInfo\n");
return status;
}
if(status==OK)//rec found
{
//get record from RID
status=scan->getRecord(rec);
if(status!=OK)
{
printf("MyError: Problem in getRecord after valid scanNext in getRelInfo\n");
return status;
}
//memcopy the dbrecord data into the return param AttrDesc record
memcpy(&record, rec.data, rec.length);
relationMatch.push_back(record);//add to vector
attrCnt++;
}
}
scan->endScan();
delete scan;
if(attrCnt>0)
{
attrs= new AttrDesc[attrCnt];//might throw exception
for(int i=0; i<attrCnt; i++)
attrs[i]=relationMatch[i];
return OK;
}
else
return ATTRNOTFOUND;
}
AttrCatalog::~AttrCatalog()
{
// nothing should be needed here
}
| [
"[email protected]"
] | |
08232d4e9ea84b480e68b008b848651d3168c2cc | e53074d668e8eea241e2afa5aa42890bedb78cd9 | /Project1/Project1/Source/Engine/GraphicsSystem/Enumerations/BlendFactor.h | 0367a2484ab0a9d8278869d38b83e3f418083a10 | [] | no_license | ReU1107/Project1 | 9f1e2ab128744c321f56219679cdb2a33072dd9f | dfae75c51981c29a5a578b1e754524476d1a6809 | refs/heads/master | 2020-12-26T19:13:20.864694 | 2020-10-29T11:51:13 | 2020-10-29T11:51:13 | 237,610,628 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 823 | h | #pragma once
#include <cstdint>
namespace Engine
{
namespace GraphicsSystem
{
enum class BlendFactor : uint8_t
{
Zero, // (0,0,0,0)
One, // (1,1,1,1)
SourceColor, // (Sr,Sg,Sb,Sa)
InverseSourceColor, // (1-Sr,1-Sg,1-Sb,1-Sa)
SourceAlpha, // (Sa,Sa,Sa,Sa)
InverseSourceAlpha, // (1-Sa,1-Sa,1-Sa,1-Sa)
DestinationColor, // (Dr,Dg,Db,Da)
InverseDestinationColor, // (1-Dr,1-Dg,1-Db,1-Da)
DestinationAlpha, // (Da,Da,Da,Da)
InverseDestinationAlpha, // (1-Da,1-Da,1-Da,1-Da)
SourceAlphaSaturate, // (f、f、f、1)f = min(Sa、1-Da)
PresetFactor, //
InversePresetFactor, //
// よくわからん
//D3D12_BLEND_SRC1_COLOR = 16,
//D3D12_BLEND_INV_SRC1_COLOR = 17,
//D3D12_BLEND_SRC1_ALPHA = 18,
//D3D12_BLEND_INV_SRC1_ALPHA = 19
};
}
} | [
"[email protected]"
] | |
16d90c5d45aeafa2cbb6995a37c91b658e7703e0 | 211fcb30d2c0068d88074c646258b31e008fd32b | /AtCoder/abc/abc029/c.cpp | d5055906a028051881f278b5bec5fdb5c8692176 | [] | no_license | makecir/competitive-programming | 2f9ae58284b37fab9aed872653518089951ff7fd | be6c7eff4baf07dd19b50eb756ec0d5dc5ec3ebf | refs/heads/master | 2021-06-11T08:10:17.375410 | 2021-04-13T11:59:17 | 2021-04-13T11:59:17 | 155,111,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,604 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll=long long;
using vb=vector<bool>;
using vvb=vector<vb>;
using vd=vector<double>;
using vvd=vector<vd>;
using vi=vector<int>;
using vvi=vector<vi>;
using vl=vector<ll>;
using vvl=vector<vl>;
using pll=pair<ll,ll>;
using tll=tuple<ll,ll>;
using vs=vector<string>;
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define rep(i,n) range(i,0,n)
#define rrep(i,n) for(int i=(n)-1;i>=0;i--)
#define range(i,a,n) for(int i=(a);i<(n);i++)
#define LINF ((ll)1ll<<60)
#define INF ((int)1<<30)
#define EPS (1e-9)
#define MOD (1000000007ll)
#define fcout(a) cout<<setprecision(a)<<fixed
#define fs first
#define sc second
#define PI (3.1415926535897932384)
int dx[]={1,0,-1,0,1,-1,-1,1},dy[]={0,1,0,-1,1,1,-1,-1};
template<class S,class T>ostream&operator<<(ostream&os,pair<S,T>p){os<<"["<<p.first<<", "<<p.second<<"]";return os;};
template<class S>auto&operator<<(ostream&os,vector<S>t){bool a=1; for(auto s:t){os<<(a?"":" ")<<s; a=0;} return os;}
template<class T> void chmax(T &a, const T &b){if(a<b)a=b;}
template<class T> void chmin(T &a, const T &b){if(a>b)a=b;}
void YN(bool b){cout<<(b?"YES":"NO")<<endl;}
void Yn(bool b){cout<<(b?"Yes":"No")<<endl;}
void yn(bool b){cout<<(b?"yes":"no")<<endl;}
class compare {
public:
bool operator()(tuple<ll, ll> a, tuple<ll, ll> b) {
return (get<1>(a) > get<1>(b));
}
};
int n;
void rec(string s){
if(s.size()==n)cout<<s<<"\n";
else{
rec(s+"a");
rec(s+"b");
rec(s+"c");
}
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
cin>>n;
rec("");
}
| [
"[email protected]"
] | |
ee314adc625320f5d9816b1570c675c1fe31b614 | 47f89380f778b6ee8311678e48970ea710e8c1a8 | /atask/Repair.h | 6b911bd6b6c802d679fbd160e8cb3032f8f21c47 | [] | no_license | hoijui/E323AI | f53a0fb388b67557fc92f38835343a85ef01135a | c4fcac72b77cff352350326c01ecab2d0ba9b388 | refs/heads/master | 2021-01-17T23:26:30.279240 | 2010-12-17T00:35:34 | 2010-12-17T00:35:34 | 358,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | h | #ifndef E323_TASKREPAIR_H
#define E323_TASKREPAIR_H
#include "../ATask.h"
class UnitType;
struct RepairTask: public ATask {
RepairTask(AIClasses* _ai): ATask(_ai) { t = TASK_REPAIR; }
RepairTask(AIClasses* _ai, int target, CGroup& group);
/* build type to string */
static std::map<buildType, std::string> buildStr;
bool repairing;
int target;
/* overloaded */
void onUpdate();
/* overloaded */
bool onValidate();
/* overloaded */
void toStream(std::ostream& out) const;
/* overloaded */
void onUnitDestroyed(int uid, int attacker);
};
#endif
| [
"[email protected]"
] | |
231582750cadc766ad8c216064ceeac3216d9988 | cccfb7be281ca89f8682c144eac0d5d5559b2deb | /chromeos/services/libassistant/grpc/external_services/action_service.cc | d30a2edfc1111459877079213385a3ea975c7d8a | [
"BSD-3-Clause"
] | permissive | SREERAGI18/chromium | 172b23d07568a4e3873983bf49b37adc92453dd0 | fd8a8914ca0183f0add65ae55f04e287543c7d4a | refs/heads/master | 2023-08-27T17:45:48.928019 | 2021-11-11T22:24:28 | 2021-11-11T22:24:28 | 428,659,250 | 1 | 0 | BSD-3-Clause | 2021-11-16T13:08:14 | 2021-11-16T13:08:14 | null | UTF-8 | C++ | false | false | 10,260 | cc | // Copyright 2021 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 "chromeos/services/libassistant/grpc/external_services/action_service.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "chromeos/assistant/internal/grpc_transport/request_utils.h"
#include "chromeos/assistant/internal/internal_constants.h"
#include "chromeos/services/libassistant/callback_utils.h"
#include "chromeos/services/libassistant/grpc/external_services/action_args.h"
#include "chromeos/services/libassistant/grpc/grpc_libassistant_client.h"
namespace chromeos {
namespace libassistant {
namespace {
std::string GetActionId(const ::assistant::api::HandleActionRequest* request) {
return request->conversation_id() + ":" +
base::NumberToString(request->interaction_id());
}
} // namespace
ActionService::ActionService(::grpc::ServerBuilder* server_builder,
GrpcLibassistantClient* libassistant_client,
const std::string& assistant_service_address)
: AsyncServiceDriver(server_builder),
libassistant_client_(libassistant_client),
assistant_service_address_(assistant_service_address) {
DCHECK(server_builder);
DCHECK(libassistant_client_);
server_builder_->RegisterService(&service_);
}
ActionService::~ActionService() = default;
void ActionService::RegisterActionModule(
assistant_client::ActionModule* action_module) {
DCHECK(!action_module_);
action_module_ = action_module;
StartRegistration();
}
void ActionService::StartRegistration() {
::assistant::api::RegisterActionModuleRequest request;
for (const auto& action : action_module_->GetSupportedActions()) {
PopulateRegisterActionModuleRequest(action, &request);
}
auto* action_handler = request.mutable_action_handler();
action_handler->set_server_address(assistant_service_address_);
action_handler->set_service_name(assistant::kActionServiceName);
action_handler->set_handler_method(assistant::kHandleActionMethodName);
auto* context_provider = request.mutable_context_provider();
context_provider->set_server_address(assistant_service_address_);
context_provider->set_service_name(assistant::kActionServiceName);
context_provider->set_handler_method(assistant::kGetContextMethodName);
constexpr int kMaxRegisterRetry = 3;
constexpr int kRegisterTimeoutInMs = 2000;
StateConfig config;
config.max_retries = kMaxRegisterRetry;
config.timeout_in_ms = kRegisterTimeoutInMs;
libassistant_client_->CallServiceMethod(
request,
base::BindOnce(&ActionService::OnRegistrationDone,
weak_factory_.GetWeakPtr()),
std::move(config));
}
void ActionService::OnRegistrationDone(
const ::grpc::Status& status,
const ::assistant::api::RegisterActionModuleResponse& response) {
if (!status.ok()) {
LOG(ERROR) << "Registration failed with status: " << status.error_code()
<< " and message: " << status.error_message();
return;
}
bool has_failure = false;
for (const auto& result : response.register_result()) {
DVLOG(3) << "Client op <" << result.first
<< "> registration status = " << result.second;
if (result.second !=
::assistant::api::RegisterActionModuleResponse_Status_SUCCESS) {
has_failure = true;
}
}
if (has_failure) {
LOG(ERROR) << "Registration failed.";
}
}
void ActionService::OnHandleActionRequest(
grpc::ServerContext* context,
const ::assistant::api::HandleActionRequest* request,
base::OnceCallback<void(const grpc::Status&,
const ::assistant::api::HandleActionResponse&)>
done) {
DCHECK(request);
if (!request->has_conversation_id() || !request->has_interaction_id()) {
LOG(ERROR) << "Received invalid HandleActionRequest.";
::assistant::api::HandleActionResponse response;
std::move(done).Run(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
"HandleActionRequest missing arguments."),
response);
return;
}
assistant_client::ActionModule::Action* action = PrepareAction(request);
if (!action) {
// TODO: Set the proper operation status in response.
// If the status is not OK, it will ignore the response and generate
// `Result::Error` and send to server.
LOG(ERROR) << "PrepareAction returns nullptr.";
::assistant::api::HandleActionResponse response;
std::move(done).Run(grpc::Status::OK, response);
return;
}
DVLOG(3) << "Received request: operation=" << request->operation()
<< ", client_op_name=" << request->client_op_name();
switch (request->operation()) {
case ::assistant::api::HandleActionRequest_Operation_PREPARE: {
::assistant::api::HandleActionResponse response;
std::move(done).Run(grpc::Status::OK, response);
return;
}
case ::assistant::api::HandleActionRequest_Operation_EXECUTE: {
const std::string& action_id = GetActionId(request);
action->Execute(ToStdFunction(base::BindOnce(
&ActionService::OnActionDone, weak_factory_.GetWeakPtr(),
std::move(done), action_id)));
return;
}
case ::assistant::api::HandleActionRequest_Operation_INTERRUPT: {
// TODO: Add interrupt logic.
const std::string& action_id = GetActionId(request);
DVLOG(2) << "Action is interrupted, id: " << action_id;
return;
}
case ::assistant::api::HandleActionRequest_Operation_TERMINATE: {
const std::string& action_id = GetActionId(request);
const auto action_iter = alive_actions_.find(action_id);
if (action_iter != alive_actions_.end()) {
DVLOG(3) << "Destroyed action without execution, id: " << action_id
<< ", name: " << action_iter->second.first;
alive_actions_.erase(action_id);
} else {
LOG(ERROR)
<< "The action with id: " << action_id
<< " doesn't exist in |alive_actions_|. This should never happen.";
}
return;
}
}
}
assistant_client::ActionModule::Action* ActionService::PrepareAction(
const ::assistant::api::HandleActionRequest* request) {
const std::string& action_id = GetActionId(request);
const auto action_iter = alive_actions_.find(action_id);
// Try to retrieve the action from the alive actions. This is for retrieving
// the action that has prepare phase for execute operation or the action is
// executing for interrupt operation.
if (action_iter != alive_actions_.end()) {
return action_iter->second.second.get();
}
// Never try to create a new action if the operation is interrupting or
// terminating.
if (request->operation() ==
::assistant::api::HandleActionRequest_Operation_INTERRUPT ||
request->operation() ==
::assistant::api::HandleActionRequest_Operation_TERMINATE) {
return nullptr;
}
if (!request->has_client_op_name()) {
LOG(ERROR) << "Failed to create the action because of no client op name in "
"the request.";
return nullptr;
}
const std::string& action_name = request->client_op_name();
// ActionModule returns the raw pointer of a new action and transfers
// the ownership. The raw pointer is used to cross the ABI boundaries.
auto* action =
action_module_->CreateAction(action_name, ActionArgs(*request));
if (!action) {
LOG(ERROR) << "Action module failed to create action : " << action_name;
return nullptr;
}
alive_actions_.insert(
{action_id, std::make_pair(action_name, base::WrapUnique(action))});
return action;
}
void ActionService::OnActionDone(
base::OnceCallback<void(const grpc::Status&,
const ::assistant::api::HandleActionResponse&)>
done,
const std::string& action_id,
const assistant_client::ActionModule::Result& result) {
::assistant::api::HandleActionResponse response;
PopulateHandleActionResponse(result, &response);
const auto action_iter = alive_actions_.find(action_id);
if (action_iter != alive_actions_.end()) {
DVLOG(3) << "Finished executing action with id: " << action_id
<< " and name: " << action_iter->second.first;
alive_actions_.erase(action_id);
} else {
LOG(ERROR)
<< "The action with id: " << action_id
<< " doesn't exist in |alive_actions_|. This should never happen.";
}
std::move(done).Run(grpc::Status::OK, response);
}
void ActionService::OnGetActionServiceContextRequest(
grpc::ServerContext* context,
const ::assistant::api::GetActionServiceContextRequest* request,
base::OnceCallback<
void(const grpc::Status&,
const ::assistant::api::GetActionServiceContextResponse&)> done) {
DVLOG(3) << "Getting service context.";
::assistant::api::GetActionServiceContextResponse response;
PopulateGetActionServiceContextResponse(*action_module_, &response);
std::move(done).Run(grpc::Status::OK, response);
}
void ActionService::StartCQ(::grpc::ServerCompletionQueue* cq) {
action_handler_driver_ = std::make_unique<
RpcMethodDriver<::assistant::api::HandleActionRequest,
::assistant::api::HandleActionResponse>>(
cq,
base::BindRepeating(
&::assistant::api::ActionService::AsyncService::RequestHandleAction,
async_service_weak_factory_.GetWeakPtr()),
base::BindRepeating(&ActionService::OnHandleActionRequest,
weak_factory_.GetWeakPtr()));
service_context_driver_ = std::make_unique<
RpcMethodDriver<::assistant::api::GetActionServiceContextRequest,
::assistant::api::GetActionServiceContextResponse>>(
cq,
base::BindRepeating(&::assistant::api::ActionService::AsyncService::
RequestGetActionServiceContext,
async_service_weak_factory_.GetWeakPtr()),
base::BindRepeating(&ActionService::OnGetActionServiceContextRequest,
weak_factory_.GetWeakPtr()));
}
} // namespace libassistant
} // namespace chromeos
| [
"[email protected]"
] | |
262c7efc13479617ceea9cf978b24a3c15b10776 | 2e3f7d511efc89fa54c99545ce5e0bcbe9456974 | /apps/jpegresize/lib_pers_mc/src_model/JpegDecode.h | fb70509745990492826b323e2ac38fc872496e55 | [
"BSD-3-Clause"
] | permissive | PacificBiosciences/OpenHT | a3aab4ddf01c9339899531d737de4ee38a35bd2e | 63898397de4d303ba514d88b621cc91367ffe2a6 | refs/heads/master | 2021-06-03T19:43:09.920841 | 2020-09-24T14:32:52 | 2020-09-24T14:32:52 | 33,895,564 | 1 | 1 | null | 2015-04-13T21:39:54 | 2015-04-13T21:39:53 | null | UTF-8 | C++ | false | false | 3,608 | h | /* Copyright (c) 2015 Convey Computer Corporation
*
* This file is part of the OpenHT jpegscale application.
*
* Use and distribution licensed under the BSD 3-clause license.
* See the LICENSE file for the complete license text.
*/
#pragma once
#include <stdint.h>
#include <assert.h>
#include <queue>
using namespace std;
#include "JpegCommon.h"
#include "JobInfo.h"
#include "MyInt.h"
#include "JpegDecMsg.h"
void jpegDecode( JobInfo * pJobInfo, queue<JpegDecMsg> &jpegDecMsgQue );
extern int cycles;
class HuffDec {
public:
HuffDec( JobInfo const * pJobInfo, uint16_t rstIdx )
: m_pJobInfo(pJobInfo)
{
m_pInPtr = pJobInfo->m_dec.m_pRstBase + pJobInfo->m_dec.m_rstInfo[rstIdx].m_offset;
m_curCi = 0;
m_bitsLeft = 0;
m_bitsZero = 0;
for (int i = 0; i < 4; i+=1)
m_lastDcValue[i] = 0;
}
void setCompId( my_uint2 ci ) {
m_curCi = ci;
}
int getCompId() { return (int) m_curCi; }
// get next huffman decoded value
my_uint8 getNext(bool bDc) {
JobDht const * pDht;
if (bDc)
pDht = &m_pJobInfo->m_dec.m_dcDht[ m_pJobInfo->m_dec.m_dcp[m_curCi].m_dcDhtId];
else
pDht = &m_pJobInfo->m_dec.m_acDht[ m_pJobInfo->m_dec.m_dcp[m_curCi].m_acDhtId];
fillBits();
// first clock of decode (usually only clock)
cycles += 1;
my_uint8 t1 = peekBits(HUFF_LOOKAHEAD);
my_uint12 t2 = pDht->m_dhtTbls[t1].m_lookup;
my_uint5 nb = (t2 >> HUFF_LOOKAHEAD) & 0xf;
my_uint8 s1 = t2 & ((1 << HUFF_LOOKAHEAD) - 1);
my_uint8 s2 = 0;
if (nb > HUFF_LOOKAHEAD) {
assert(nb == HUFF_LOOKAHEAD+1);
my_int18 t3 = (uint64_t)getBits(HUFF_LOOKAHEAD+1);
// a clock per iteration
while (t3 > (my_int21)pDht->m_dhtTbls[nb].m_maxCode) {
cycles += 1; // for performance monitoring (not in HW)
t3 = (t3 << 1) | getBits(1);
nb = nb + 1;
}
// last clock
cycles += 1;
my_uint8 codeIdx = (my_uint8)(t3 + pDht->m_dhtTbls[nb].m_valOffset);
s2 = pDht->m_dhtTbls[ codeIdx ].m_huffCode;
} else
// first clock when needed
dropBits(nb);
return nb > HUFF_LOOKAHEAD ? s2 : s1;
}
my_int16 huffExtendDc(my_uint11 r, my_uint5 s)
{
bool rIsNeg = (r & (1Ull << (s-1))) != 0;
my_int16 t = rIsNeg ? 0 : ((-1 << s) + 1);
return (int64_t)(r + t);
}
my_int16 huffExtendAc(my_uint10 r, my_uint4 s)
{
bool rIsNeg = (r & (1Ull << (s-1))) != 0;
my_int16 t = rIsNeg ? 0 : ((-1 << s) + 1);
return (int64_t)(r + t);
}
void fillBits()
{
while (m_bitsLeft < 16) {
bool bSkipZero = false;
if (m_pInPtr[0] == 0xFF) {
if (m_pInPtr[1] != 0x00) {
// fill with zero
m_bitBuffer <<= 8;
m_bitsLeft += 8;
m_bitsZero += 8;
continue;
}
bSkipZero = true;
}
m_bitBuffer = (m_bitBuffer << 8) | *m_pInPtr++;
if (bSkipZero)
m_pInPtr++;
m_bitsLeft += 8;
}
}
int peekBits(int nb)
{
return (m_bitBuffer >> (m_bitsLeft - (nb))) & ((1<<nb)-1);
}
void dropBits(my_uint5 nb)
{
assert(nb <= 8);
assert(m_bitsLeft - m_bitsZero >= nb);
m_bitsLeft = m_bitsLeft - nb;
}
my_uint16 getBits(my_uint5 nb)
{
assert(nb <= 16);
assert(m_bitsLeft - m_bitsZero >= nb);
int bits = (m_bitBuffer >> (m_bitsLeft - (nb))) & ((1<<nb)-1);
m_bitsLeft = m_bitsLeft - nb;
return bits;
}
int16_t & getLastDcValueRef() { return m_lastDcValue[m_curCi]; }
void checkEndOfScan() {
assert( m_pInPtr[0] == 0xFF && (m_pInPtr[1] == 0xD9 || (m_pInPtr[1] >= 0xD0 && m_pInPtr[1] <= 0xD7)));
};
private:
JobInfo const * m_pJobInfo;
uint8_t * m_pInPtr;
uint32_t m_bitBuffer;
my_uint6 m_bitsLeft; // allows a 32 bit buffer
uint8_t m_bitsZero;
uint64_t m_curCi : 2;
int16_t m_lastDcValue[4];
};
| [
"[email protected]"
] | |
ceb4c5fb9d40bd582334173faf1a395f7925cbd1 | d79408a9616a8ff8ac9375b9fffaa45ae6698fd5 | /src/qt/clientmodel.cpp | ceaefc49bf2359a7306fc37a5285b790af4569a6 | [
"MIT"
] | permissive | Schepses/nero | 6c77f5df6afd36a6ebcb14af1d8257d918d7bda7 | 7ec5e3a6c7f1c75f5ec15b1f4d0bcb9cdc0ec9b0 | refs/heads/master | 2020-03-07T13:43:18.425050 | 2018-03-28T12:27:27 | 2018-03-28T12:27:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,779 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Nero Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientmodel.h"
#include "bantablemodel.h"
#include "guiconstants.h"
#include "peertablemodel.h"
#include "alert.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "validation.h"
#include "net.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "util.h"
#include "masternodeman.h"
#include "masternode-sync.h"
#include "privatesend.h"
#include <stdint.h>
#include <QDebug>
#include <QTimer>
class CBlockIndex;
static const int64_t nClientStartupTime = GetTime();
static int64_t nLastHeaderTipUpdateNotification = 0;
static int64_t nLastBlockTipUpdateNotification = 0;
ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
QObject(parent),
optionsModel(optionsModel),
peerTableModel(0),
cachedMasternodeCountString(""),
banTableModel(0),
pollTimer(0)
{
cachedBestHeaderHeight = -1;
cachedBestHeaderTime = -1;
peerTableModel = new PeerTableModel(this);
banTableModel = new BanTableModel(this);
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
pollTimer->start(MODEL_UPDATE_DELAY);
pollMnTimer = new QTimer(this);
connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer()));
// no need to update as frequent as data for balances/txes/blocks
pollMnTimer->start(MODEL_UPDATE_DELAY * 4);
subscribeToCoreSignals();
}
ClientModel::~ClientModel()
{
unsubscribeFromCoreSignals();
}
int ClientModel::getNumConnections(unsigned int flags) const
{
CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE;
if(flags == CONNECTIONS_IN)
connections = CConnman::CONNECTIONS_IN;
else if (flags == CONNECTIONS_OUT)
connections = CConnman::CONNECTIONS_OUT;
else if (flags == CONNECTIONS_ALL)
connections = CConnman::CONNECTIONS_ALL;
if(g_connman)
return g_connman->GetNodeCount(connections);
return 0;
}
QString ClientModel::getMasternodeCountString() const
{
// return tr("Total: %1 (PS compatible: %2 / Enabled: %3) (IPv4: %4, IPv6: %5, TOR: %6)").arg(QString::number((int)mnodeman.size()))
return tr("Total: %1 (PS compatible: %2 / Enabled: %3)")
.arg(QString::number((int)mnodeman.size()))
.arg(QString::number((int)mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)))
.arg(QString::number((int)mnodeman.CountEnabled()));
// .arg(QString::number((int)mnodeman.CountByIP(NET_IPV4)))
// .arg(QString::number((int)mnodeman.CountByIP(NET_IPV6)))
// .arg(QString::number((int)mnodeman.CountByIP(NET_TOR)));
}
int ClientModel::getNumBlocks() const
{
LOCK(cs_main);
return chainActive.Height();
}
int ClientModel::getHeaderTipHeight() const
{
if (cachedBestHeaderHeight == -1) {
// make sure we initially populate the cache via a cs_main lock
// otherwise we need to wait for a tip update
LOCK(cs_main);
if (pindexBestHeader) {
cachedBestHeaderHeight = pindexBestHeader->nHeight;
cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
}
}
return cachedBestHeaderHeight;
}
int64_t ClientModel::getHeaderTipTime() const
{
if (cachedBestHeaderTime == -1) {
LOCK(cs_main);
if (pindexBestHeader) {
cachedBestHeaderHeight = pindexBestHeader->nHeight;
cachedBestHeaderTime = pindexBestHeader->GetBlockTime();
}
}
return cachedBestHeaderTime;
}
quint64 ClientModel::getTotalBytesRecv() const
{
if(!g_connman)
return 0;
return g_connman->GetTotalBytesRecv();
}
quint64 ClientModel::getTotalBytesSent() const
{
if(!g_connman)
return 0;
return g_connman->GetTotalBytesSent();
}
QDateTime ClientModel::getLastBlockDate() const
{
LOCK(cs_main);
if (chainActive.Tip())
return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime());
return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network
}
long ClientModel::getMempoolSize() const
{
return mempool.size();
}
size_t ClientModel::getMempoolDynamicUsage() const
{
return mempool.DynamicMemoryUsage();
}
double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const
{
CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn);
if (!tip)
{
LOCK(cs_main);
tip = chainActive.Tip();
}
return Checkpoints::GuessVerificationProgress(Params().Checkpoints(), tip);
}
void ClientModel::updateTimer()
{
// no locking required at this point
// the following calls will acquire the required lock
Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage());
Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}
void ClientModel::updateMnTimer()
{
QString newMasternodeCountString = getMasternodeCountString();
if (cachedMasternodeCountString != newMasternodeCountString)
{
cachedMasternodeCountString = newMasternodeCountString;
Q_EMIT strMasternodesChanged(cachedMasternodeCountString);
}
}
void ClientModel::updateNumConnections(int numConnections)
{
Q_EMIT numConnectionsChanged(numConnections);
}
void ClientModel::updateNetworkActive(bool networkActive)
{
Q_EMIT networkActiveChanged(networkActive);
}
void ClientModel::updateAlert(const QString &hash, int status)
{
// Show error message notification for new alert
if(status == CT_NEW)
{
uint256 hash_256;
hash_256.SetHex(hash.toStdString());
CAlert alert = CAlert::getAlertByHash(hash_256);
if(!alert.IsNull())
{
Q_EMIT message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR);
}
}
Q_EMIT alertsChanged(getStatusBarWarnings());
}
bool ClientModel::inInitialBlockDownload() const
{
return IsInitialBlockDownload();
}
enum BlockSource ClientModel::getBlockSource() const
{
if (fReindex)
return BLOCK_SOURCE_REINDEX;
else if (fImporting)
return BLOCK_SOURCE_DISK;
else if (getNumConnections() > 0)
return BLOCK_SOURCE_NETWORK;
return BLOCK_SOURCE_NONE;
}
void ClientModel::setNetworkActive(bool active)
{
if (g_connman) {
g_connman->SetNetworkActive(active);
}
}
bool ClientModel::getNetworkActive() const
{
if (g_connman) {
return g_connman->GetNetworkActive();
}
return false;
}
QString ClientModel::getStatusBarWarnings() const
{
return QString::fromStdString(GetWarnings("gui"));
}
OptionsModel *ClientModel::getOptionsModel()
{
return optionsModel;
}
PeerTableModel *ClientModel::getPeerTableModel()
{
return peerTableModel;
}
BanTableModel *ClientModel::getBanTableModel()
{
return banTableModel;
}
QString ClientModel::formatFullVersion() const
{
return QString::fromStdString(FormatFullVersion());
}
QString ClientModel::formatSubVersion() const
{
return QString::fromStdString(strSubVersion);
}
bool ClientModel::isReleaseVersion() const
{
return CLIENT_VERSION_IS_RELEASE;
}
QString ClientModel::clientName() const
{
return QString::fromStdString(CLIENT_NAME);
}
QString ClientModel::formatClientStartupTime() const
{
return QDateTime::fromTime_t(nClientStartupTime).toString();
}
QString ClientModel::dataDir() const
{
return QString::fromStdString(GetDataDir().string());
}
void ClientModel::updateBanlist()
{
banTableModel->refresh();
}
// Handlers for core signals
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
{
// emits signal "showProgress"
QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(title)),
Q_ARG(int, nProgress));
}
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
// Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections);
QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
Q_ARG(int, newNumConnections));
}
static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
{
QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection,
Q_ARG(bool, networkActive));
}
static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
qDebug() << "NotifyAlertChanged: " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status);
QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(hash.GetHex())),
Q_ARG(int, status));
}
static void BannedListChanged(ClientModel *clientmodel)
{
qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}
static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader)
{
// lock free async UI updates in case we have a new block tip
// during initial sync, only update the UI if the last update
// was > 250ms (MODEL_UPDATE_DELAY) ago
int64_t now = 0;
if (initialSync)
now = GetTimeMillis();
int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification;
if (fHeader) {
// cache best headers time and height to reduce future cs_main locks
clientmodel->cachedBestHeaderHeight = pIndex->nHeight;
clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime();
}
// if we are in-sync, update the UI regardless of last update time
if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) {
//pass a async signal to the UI thread
QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
Q_ARG(int, pIndex->nHeight),
Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())),
Q_ARG(double, clientmodel->getVerificationProgress(pIndex)),
Q_ARG(bool, fHeader));
nLastUpdateNotification = now;
}
}
static void NotifyAdditionalDataSyncProgressChanged(ClientModel *clientmodel, double nSyncProgress)
{
QMetaObject::invokeMethod(clientmodel, "additionalDataSyncProgressChanged", Qt::QueuedConnection,
Q_ARG(double, nSyncProgress));
}
void ClientModel::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1));
uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false));
uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true));
uiInterface.NotifyAdditionalDataSyncProgressChanged.connect(boost::bind(NotifyAdditionalDataSyncProgressChanged, this, _1));
}
void ClientModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1));
uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false));
uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true));
uiInterface.NotifyAdditionalDataSyncProgressChanged.disconnect(boost::bind(NotifyAdditionalDataSyncProgressChanged, this, _1));
}
| [
"[email protected]"
] | |
652c2b1be0cb1737728345017668f5db711d4a9b | 8ecc0311feb77802ece89f12153f79192897a729 | /LeetCode_Cpp/leetcode_cpp/数组/1502_判断能否形成等差数列.cpp | 1e7dd3c8d58654e498cd04cb8682568eb7531920 | [] | no_license | zhxiongfei/leetcode-Cpp | 3ce4026ba5d92d1a092d18a6ed2c2e3103d4246d | 3972c1b4d1cc61ab0fbe97f4102ac831e1f7103d | refs/heads/master | 2023-02-28T12:08:42.377794 | 2021-02-05T09:22:05 | 2021-02-05T09:22:05 | 277,428,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | cpp | //
// 1502_判断能否形成等差数列.cpp
// leetcode_cpp
//
// Created by 飞熊 on 2020/7/17.
// Copyright © 2020 飞熊. All rights reserved.
//
#include <stdio.h>
#include "vector"
using namespace std;
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
sort(arr.begin(), arr.end());
int diff = arr[1] - arr[0];
for (int i = 2; i < arr.size(); i ++) {
if (diff != arr[i] - arr[i - 1]) return false;
}
return true;
}
};
| [
"[email protected]"
] | |
cff21d607261d1f1e7e44a2922034e7278ac3d06 | a291084d56ad29a280a12830415fba2a87de8000 | /546A - Soldier and Bananas.cpp | 1fe1d7782d3af9f0362c72751ff757e1c913ff8a | [] | no_license | amanmj/CodeForces | 9ccbd3d5d5a3e593ed6688ce7813471ad0fc1c46 | 0c37add4406aebf0ffddc09fd82014e9b0c3e01b | refs/heads/master | 2021-01-21T22:26:18.986110 | 2016-06-05T06:11:19 | 2016-06-05T06:11:19 | 48,799,046 | 0 | 0 | null | 2015-12-30T12:09:31 | 2015-12-30T12:09:31 | null | UTF-8 | C++ | false | false | 269 | cpp | #include<stdio.h>
#include<iostream>
int main(void)
{
long long int n,k,w;
std::cin>>n>>k>>w;
long long int ans;
ans=(w*(w+1))/2;
ans*=n;
ans-=k;
if(ans<=0)
printf("0");
else
std::cout<<ans;
return 0;
} | [
"[email protected]"
] | |
127f694fa013f2080051dac7833657798b7cfc75 | 602e0f4bae605f59d23688cab5ad10c21fc5a34f | /MyToolKit/NumericalRecipes/examples/xellf.cpp | 3ffe929e488a72ce85c4b0adf11802fda68ca994 | [] | no_license | yanbcxf/cpp | d7f26056d51f85254ae1dd2c4e8e459cfefb2fb6 | e059b02e7f1509918bbc346c555d42e8d06f4b8f | refs/heads/master | 2023-08-04T04:40:43.475657 | 2023-08-01T14:03:44 | 2023-08-01T14:03:44 | 172,408,660 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,236 | cpp | #include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include "nr.h"
using namespace std;
// Driver for routine ellf
int main(void)
{
const DP FAC=3.141592653589793238/180.0;
string txt;
int i,nval;
DP ak,alpha,phi,val;
ifstream fp("fncval.dat");
if (fp.fail())
NR::nrerror("Data file fncval.dat not found");
getline(fp,txt);
while (txt.find("Legendre Elliptic Integral First Kind")) {
getline(fp,txt);
if (fp.eof()) NR::nrerror("Data not found in fncval.dat");
}
fp >> nval;
getline(fp,txt);
cout << endl << "Legendre Elliptic Integral First Kind" << endl;
cout << setw(11) << "phi" << setw(20) << "sin(alpha)";
cout << setw(14) << "actual" << setw(19) << "ellf(phi,ak)";
cout << endl << endl;
cout << scientific << setprecision(6);
for (i=0;i<nval;i++) {
fp >> phi >> alpha >> val;
alpha=alpha*FAC;
ak=sin(alpha);
phi=phi*FAC;
cout << setw(16) << phi << setw(16) << ak;
cout << setw(16) << val << setw(16) << NR::ellf(phi,ak) << endl;
}
return 0;
}
| [
"[email protected]"
] | |
117565fb677d3ce2ced2b2405919b16226a44f8b | 466791528d608f092de2a179e0cac60c7d27d4cd | /libraries/core/database/database.hpp | bbd19df4cee6e19c8df77a05114f09174474fc26 | [
"Unlicense"
] | permissive | PhilipMourdjis/cmake-object-libraries | 11f03cd44c87bbabff401bab726d4f889be6d73a | 8634f5722fb4e9e36431c71f95314c7c83986a0d | refs/heads/master | 2021-11-10T15:30:58.259477 | 2021-10-28T15:16:18 | 2021-10-28T15:16:18 | 184,545,434 | 0 | 0 | null | 2019-05-02T08:20:18 | 2019-05-02T08:20:17 | null | UTF-8 | C++ | false | false | 148 | hpp | #include <string>
namespace core::database
{
void printString(const std::string& someString);
int returnNumberTwo();
} // namespace core::database | [
"[email protected]"
] | |
9a3caf28f046a5e14b6e81909fac04928976f58a | dd5356457879b9edf8c982a412e0068f94da697d | /SDK/RoCo_WBP_KeyboardBackButton_classes.hpp | 3144156bfaee6e5c5c14a8477172c45257bbb6de | [] | no_license | ALEHACKsp/RoCo-SDK | 5ee6567294674b6933dcd0acda720f64712ccdbf | 3a9e37be3a48bc0a10aa9e4111865c996f3b5680 | refs/heads/master | 2023-05-14T16:54:49.296847 | 2021-06-08T20:09:37 | 2021-06-08T20:09:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,795 | hpp | #pragma once
// Rogue Company (0.60) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "RoCo_WBP_KeyboardBackButton_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass WBP_KeyboardBackButton.WBP_KeyboardBackButton_C
// 0x0020 (0x0258 - 0x0238)
class UWBP_KeyboardBackButton_C : public UUserWidget
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0238(0x0008) (CPF_ZeroConstructor, CPF_Transient, CPF_DuplicateTransient)
class UButton* BackButton; // 0x0240(0x0008) (CPF_BlueprintVisible, CPF_ExportObject, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData, CPF_RepSkip, CPF_NoDestructor, CPF_PersistentInstance, CPF_HasGetValueTypeHash)
struct FScriptMulticastDelegate OnBackButtonClicked; // 0x0248(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_BlueprintAssignable, CPF_BlueprintCallable)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("WidgetBlueprintGeneratedClass WBP_KeyboardBackButton.WBP_KeyboardBackButton_C");
return ptr;
}
void BndEvt__Button_253_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature();
void BndEvt__BackButton_K2Node_ComponentBoundEvent_1_OnButtonHoverEvent__DelegateSignature();
void ExecuteUbergraph_WBP_KeyboardBackButton(int EntryPoint);
void OnBackButtonClicked__DelegateSignature();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
0e05b2413593fdd11e62c9f583c6756e5926ab97 | c3f18073dac4767129e28dece885dc95525c1f53 | /LeetCode/Tag/Hash-Table/cpp/705.design-hashset.cpp | 270031420342937aff8c9c4f16e37d6e3f9fc026 | [
"MIT"
] | permissive | sunnysetia93/competitive-coding-problems | 670ffe1ec90bfee0302f0b023c09e80bf5547e96 | e8fad1a27a9e4df8b4138486a52bef044586c066 | refs/heads/master | 2023-08-09T04:31:24.027037 | 2023-07-24T12:39:46 | 2023-07-24T12:39:46 | 89,518,943 | 20 | 22 | MIT | 2023-07-24T12:39:48 | 2017-04-26T19:29:18 | JavaScript | UTF-8 | C++ | false | false | 942 | cpp | class MyHashSet {
vector<vector<bool>> bucket;
public:
/** Initialize your data structure here. */
MyHashSet() {
bucket.resize(1001, vector<bool>());
}
void add(int key) {
int keyHash = key / 1000;
if (bucket[keyHash].empty()) bucket[keyHash].resize(1000, false);
bucket[keyHash][key % 1000] = true;
}
void remove(int key) {
int keyHash = key / 1000;
if (bucket[keyHash].empty()) return;
bucket[keyHash][key % 1000] = false;
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
int keyHash = key / 1000;
if (bucket[keyHash].empty()) return false;
return bucket[keyHash][key % 1000];
}
};
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet* obj = new MyHashSet();
* obj->add(key);
* obj->remove(key);
* bool param_3 = obj->contains(key);
*/ | [
"[email protected]"
] | |
63a44738d3935a6895c0fe695b00b6a11e54480d | 35321390460c43a8003f8b613ce20b3c733ee6ed | /cpp_bomberman/map/AI.cpp | d65fa7539bfb8d41a3d881105de36048ef6a1819 | [] | no_license | Vypz/Global-project | 39540c59bc316b1cd23a9e7777e853c42a02c3bc | 72aa8c00d5934d542aa9484501cb5d6ae3f49829 | refs/heads/master | 2023-09-02T05:09:35.173690 | 2021-09-22T15:01:34 | 2021-09-22T15:01:34 | 197,783,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,130 | cpp | //
// AI.cpp for in /home/mar_j/rendu/cpp_bomberman/map
//
// Made by julien martini
// Login <[email protected]>
//
// Started on Wed Jun 4 15:21:38 2014 julien martini
// Last update Sun Jun 15 18:59:52 2014 virgile prideaux
//
#include "AI.hh"
AI::AI(int x, int y)
: Character(x, y, true), _x(0), _y(0), _bomb(false), _init(false)
{}
AI::~AI()
{}
void AI::initMap(Map& map)
{
int i;
i = 0;
this->_map.resize(map.size());
for (std::vector<Line>::iterator it = _map.begin(); it != _map.end(); ++it)
(*it).resize(map[i++].size(), static_cast<int>(AI::NOTHING));
}
void AI::refreshMap(Map& map)
{
std::list<AElement*>::iterator it;
std::map<AElement::Type, AI::Type> type;
type[AElement::NOTHING] = AI::NOTHING;
type[AElement::BOMB] = AI::BOMB;
type[AElement::CHARACTER] = AI::PLAYER;
type[AElement::BONUS] = AI::BONUS;
type[AElement::WALL] = AI::WALL;
type[AElement::EXPLOSION] = AI::EXPLODE;
for (int y = 0; y != static_cast<int>(this->_map.size()); y += 1)
for (int x = 0; x != static_cast<int>(this->_map[y].size()); x += 1)
this->_map[y][x] = AI::NOTHING;
for (int y = 0; y != static_cast<int>(this->_map.size()); y += 1)
for (int x = 0; x != static_cast<int>(this->_map[y].size()); x += 1)
for (it = map[y][x].begin(); it != map[y][x].end(); ++it)
{
this->_map[y][x] |= type[(*it)->getType()];
if ((*it)->getType() == AElement::BOMB)
{
for (int i = 0; i <= dynamic_cast<Bomb*>(*it)->getScope(); i += 1)
{
if ((x - i) > 0)
this->_map[y][x - i] |= AI::EXPLODE;
if ((x + i) < static_cast<int>(_map[y].size()))
this->_map[y][x + i] |= AI::EXPLODE;
if ((y - i) > 0)
this->_map[y - i][x] |= AI::EXPLODE;
if ((y + i) < static_cast<int>(_map.size()))
this->_map[y + i][x] |= AI::EXPLODE;
}
}
else if ((*it)->getType() == AElement::WALL)
{
if (dynamic_cast<Wall*>(*it)->isDestroyable() == true)
this->_map[y][x] = AI::DBLOCK;
else
this->_map[y][x] = AI::WALL;
}
}
_map[this->_posX][this->_posY] &= ~AI::PLAYER;
}
int AI::findSafeArea(float x, float y, int iter)
{
int up;
int down;
int left;
int right;
if (iter >= MAX_ITER ||
((this->_map[x][y] & AI::BOMB) && iter != 0) ||
(this->_map[x][y] & AI::WALL) ||
(this->_map[x][y] & AI::DBLOCK))
return (MAX_ITER + 1);
else if (!(this->_map[x][y] & AI::EXPLODE) &&
!(this->_map[x][y] & AI::BOMB))
return (0);
else
{
up = findSafeArea(x - 1, y, iter + 1);
right = findSafeArea(x, y + 1, iter + 1);
down = findSafeArea(x + 1, y, iter + 1);
left = findSafeArea(x, y - 1, iter + 1);
if (up <= down && up <= left && up <= right)
{
this->_x = -1;
this->_y = 0;
return (up + 1);
}
if (right <= up && right <= down && right <= left)
{
this->_x = 0;
this->_y = 1;
return (right + 1);
}
if (down <= up && down <= left && down <= right)
{
this->_x = 1;
this->_y = 0;
return (down + 1);
}
if (left <= up && left <= right && left <= down)
{
this->_x = 0;
this->_y = -1;
return (left + 1);
}
}
return (MAX_ITER + 1);
}
int AI::searchObject(int x, int y, int iter, AI::Type object)
{
int up;
int right;
int left;
int down;
if (iter >= MAX_ITER ||
(this->_map[x][y] & AI::BOMB) ||
(this->_map[x][y] & AI::WALL) ||
(this->_map[x][y] & AI::EXPLODE))
return (MAX_ITER + 1);
else if ((this->_map[x][y] & object))
return (0);
else
{
up = searchObject(x - 1, y, iter + 1, object);
right = searchObject(x, y + 1, iter + 1, object);
down = searchObject(x + 1, y, iter + 1, object);
left = searchObject(x, y - 1, iter + 1, object);
if (up <= down && up <= left && up <= right)
{
this->_x = -1;
this->_y = 0;
return (up + 1);
}
if (right <= up && right <= down && right <= left)
{
this->_x = 0;
this->_y = 1;
return (right + 1);
}
if (down <= up && down <= left && down <= right)
{
this->_x = 1;
this->_y = 0;
return (down + 1);
}
if (left <= up && left <= right && left <= down)
{
this->_x = 0;
this->_y = -1;
return (left + 1);
}
}
return (MAX_ITER + 1);
}
bool AI::isDangerous()
{
int i;
for (i = 0; i <= this->getBombScope(); i++)
{
if ((_map[this->_posX + i][this->_posY] & AI::WALL) ||
(_map[this->_posX + i][this->_posY] & AI::BOMB))
i = this->getBombScope() + 1;
else if ((_map[this->_posX + i][this->_posY] & AI::EXPLODE))
return (false);
}
for (i = 0; i <= this->getBombScope(); i++)
{
if ((_map[this->_posX][this->_posY - i] & AI::WALL) ||
(_map[this->_posX][this->_posY - i] & AI::BOMB))
i = this->getBombScope() + 1;
else if ((_map[this->_posX][this->_posY - i] & AI::EXPLODE))
return (false);
}
for (i = 0; i <= this->getBombScope(); i++)
{
if ((_map[this->_posX - i][this->_posY] & AI::WALL) ||
(_map[this->_posX - i][this->_posY] & AI::BOMB))
i = this->getBombScope() + 1;
else if ((_map[this->_posX - i][this->_posY] & AI::EXPLODE))
return (false);
}
for (i = 0; i <= this->getBombScope(); i++)
{
if ((_map[this->_posX][this->_posY + i] & AI::WALL) ||
(_map[this->_posX][this->_posY + i] & AI::BOMB))
i = this->getBombScope() + 1;
else if ((_map[this->_posX][this->_posY - i] & AI::EXPLODE))
return (false);
}
return (true);
}
bool AI::iCanBomb()
{
int i;
bool ret;
ret = false;
for (i = 0; i <= this->getBombScope() && ret != true; i++)
{
if ((_map[this->_posX + i][this->_posY] & AI::DBLOCK) ||
(_map[this->_posX + i][this->_posY] & AI::PLAYER))
ret = true;
else if ((_map[this->_posX + i][this->_posY] & AI::WALL) ||
(_map[this->_posX + i][this->_posY] & AI::BOMB))
i = this->getBombScope() + 1;
}
for (i = 0; i <= this->getBombScope() && ret != true; i++)
{
if ((_map[this->_posX - i][this->_posY] & AI::DBLOCK) ||
(_map[this->_posX - i][this->_posY] & AI::PLAYER))
ret = true;
else if ((_map[this->_posX - i][this->_posY] & AI::WALL) ||
(_map[this->_posX - i][this->_posY] & AI::BOMB))
i = this->getBombScope() + 1;
}
for (i = 0; i <= this->getBombScope() && ret != true; i++)
{
if ((_map[this->_posX][this->_posY + i] & AI::DBLOCK) ||
(_map[this->_posX][this->_posY + i] & AI::PLAYER))
ret = true;
else if ((_map[this->_posX][this->_posY + i] & AI::WALL) ||
(_map[this->_posX][this->_posY + i] & AI::BOMB))
i = this->getBombScope() + 1;
}
for (i = 0; i <= this->getBombScope() && ret != true; i++)
{
if ((_map[this->_posX][this->_posY - i] & AI::DBLOCK) ||
(_map[this->_posX][this->_posY - i] & AI::PLAYER))
ret = true;
else if ((_map[this->_posX][this->_posY - i] & AI::WALL) ||
(_map[this->_posX][this->_posY - i] & AI::BOMB))
i = this->getBombScope() + 1;
}
return (ret);
}
void AI::randomMove()
{
int pileFace;
srand(getuid() * getgid() * getpid() * time(0));
pileFace = (rand() % 4);
if (pileFace == 0 &&
!(_map[this->_posX + 1][this->_posY] & AI::WALL) &&
!(_map[this->_posX + 1][this->_posY] & AI::EXPLODE))
this->_x = 1;
if (pileFace == 1 &&
!(_map[this->_posX][this->_posY - 1] & AI::WALL) &&
!(_map[this->_posX][this->_posY - 1] & AI::EXPLODE))
this->_y = -1;
if (pileFace == 2 &&
!(_map[this->_posX - 1][this->_posY] & AI::WALL) &&
!(_map[this->_posX - 1][this->_posY] & AI::EXPLODE))
this->_x = -1;
if (pileFace == 3 &&
!(_map[this->_posX][this->_posY + 1] & AI::WALL) &&
!(_map[this->_posX][this->_posY + 1] & AI::EXPLODE))
this->_y = 1;
}
void AI::scan()
{
this->_x = 0;
this->_y = 0;
if ((_map[this->_posX][this->_posY] & AI::EXPLODE) ||
(_map[this->_posX][this->_posY] & AI::BOMB))
{
if (this->findSafeArea(this->_posX, this->_posY, 0) > MAX_ITER)
randomMove();
}
else
{
if (this->searchObject(this->_posX, this->_posY, 0, AI::BONUS) > MAX_ITER || this->_map[this->_posX + this->_x][this->_posY + this->_y] == AI::DBLOCK)
{
this->_x = 0;
this->_y = 0;
if (isDangerous() == true &&
iCanBomb() == true && this->_canPutBomb() == true)
this->_bomb = true;
else
{
if (this->searchObject(this->_posX, this->_posY, 0, AI::PLAYER) > MAX_ITER)
{
this->_x = 0;
this->_y = 0;
if (this->searchObject(this->_posX, this->_posY, 0, AI::DBLOCK) > MAX_ITER)
{
this->_x = 0;
this->_y = 0;
randomMove();
}
}
}
if (this->_map[this->_posX + this->_x][this->_posY + this->_y] == AI::DBLOCK)
{
this->_x = 0;
this->_y = 0;
}
}
}
}
void AI::sendInput(float& x, float& y, Map &map)
{
this->_x = 0;
this->_y = 0;
if (this->_init == false)
{
this->_init = true;
this->initMap(map);
}
this->refreshMap(map);
this->scan();
x = this->_x;
y = this->_y;
}
bool AI::getBomb() const
{
return (this->_bomb);
}
void AI::setBomb(bool set)
{
this->_bomb = set;
}
| [
"[email protected]"
] | |
03b4efbfdc3f6a5e115b296b4866d73a5d948799 | 85371e644ed7597d8ef50f3b3af7effeeb1f1d7d | /2. ImageRectification2/2steps_remove_distortion/stdafx.cpp | 4f95b594e5548a1b7d81672d2332ac7cebdd8a0a | [] | no_license | enoch-lee/Computer-Geometry-Experiment | 76986cd951c911e0951f7cb85c613cfb7ac78354 | d83b110d36afccec20b3ff45f1a792e5987b3271 | refs/heads/master | 2021-07-10T15:04:09.626770 | 2017-10-10T04:16:31 | 2017-10-10T04:16:31 | 104,299,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | // stdafx.cpp : source file that includes just the standard includes
// HW1_2step_remove_distortion.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
4f857b20b28f4cffd6db23e75f28ec9004f751c1 | 695d24f3778e942b534eeb890f901e9139b774ca | /mapperview.h | 706f15c4eee0abb42c512386b725e834c3442c9b | [] | no_license | mdirks/mygui | a94d0c5d1301417525fc902a854e256693bdcc3c | 5b6df7d32e8807cc08512179e539b8902be787b7 | refs/heads/master | 2021-05-09T10:22:58.755543 | 2018-02-04T12:17:19 | 2018-02-04T12:17:19 | 118,960,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | //
// C++ Interface: mapperview
//
// Description:
//
//
// Author: Marcus Dirks <[email protected]>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef MAPPERVIEW_H
#define MAPPERVIEW_H
#include <mapping/abstractmapper.h>
#include <QListWidget>
#include <QDialog>
/**
@author Marcus Dirks <[email protected]>
*/
class MapperView : public QListWidget
{
public:
MapperView(QWidget *parent=0, QStringList classList=QStringList());
~MapperView();
AbstractMapper* getSelectedMapper();
};
class MapperViewItem : public QListWidgetItem
{
public:
MapperViewItem(AbstractMapper *mapper, MapperView *parent);
AbstractMapper* getMapper();
private:
AbstractMapper *mapper;
};
#endif
class MapperDialog : public QDialog
{
public:
MapperDialog(QWidget *parent=0L, QStringList classList=QStringList());
AbstractMapper* getSelectedMapper();
static AbstractMapper* chooseMapper(QStringList classList=QStringList());
private:
MapperView *mapperView;
};
| [
"[email protected]"
] | |
2e293d94e4f40fcf4ce97b39ba781fcc623d985a | 05281e151cc7663c3faec9706498f159723efd18 | /Resources.cpp | 58c2951596f051dc30a91f66be1e1e9120e56196 | [] | no_license | ezh/ENikiBENiki | 843781503ce45d16e7d7497c46aff980883360e4 | 7e1346785feea786272ba3a769b5c788e9f3572d | refs/heads/master | 2016-09-06T19:53:16.784322 | 2010-08-30T07:56:58 | 2010-08-30T07:56:58 | 721,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,182 | cpp | /***************************************************************************
* Copyright (C) 2010 Alexey Aksenov, Alexx Fomichew *
* Alexey Aksenov (ezh at ezh.msk.ru) software, firmware *
* Alexx Fomichew (axx at fomichi.ru) hardware *
* *
* This file is part of ENikiBENiki *
* *
* ENikiBENiki is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* ENikiBENiki 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 ENikiBENiki. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
/*
* idea of wrapper based on source code of Matthias Braun <[email protected]>
*/
#include <ptlib.h>
#include "physfs.h"
#include "Resources.h"
#define new PNEW
Resources::Resources(PString & _resourceExt) : resourceExt(_resourceExt) {
}
Resources::~Resources() {
}
bool Resources::Open(PString & argv0, PString & application) {
if(!PHYSFS_init(argv0.GetPointer())) {
PError << "failure while initialising physfs: " << PHYSFS_getLastError() << endl;
return PFalse;
} else {
PTRACE(5, "successful initialize physfs");
}
const char* basedir = PHYSFS_getBaseDir();
const char* userdir = PHYSFS_getUserDir();
const char* dirsep = PHYSFS_getDirSeparator();
char* writedir = new char[strlen(userdir) + application.GetLength() + 2];
sprintf(writedir, "%s.%s", userdir, application.GetPointer());
PTRACE(5, "physfs base directory: " << basedir);
PTRACE(5, "physfs user directory: " << userdir);
PTRACE(5, "physfs write directory: " << writedir);
if(!PHYSFS_setWriteDir(writedir)) {
// try to create the directory...
char* mkdir = new char[application.GetLength()+2];
sprintf(mkdir, ".%s", application.GetPointer());
if(!PHYSFS_setWriteDir(userdir) || ! PHYSFS_mkdir(mkdir)) {
delete[] writedir;
delete[] mkdir;
PError << "failed creating configuration directory: '" << writedir << "': " << PHYSFS_getLastError() << endl;
return PFalse;
}
delete[] mkdir;
if (!PHYSFS_setWriteDir(writedir)) {
PError << "couldn't set configuration directory to '" << writedir << "': " << PHYSFS_getLastError() << endl;
return PFalse;
}
}
PHYSFS_addToSearchPath(writedir, 0);
PHYSFS_addToSearchPath(basedir, 1);
delete[] writedir;
/* Root out archives, and add them to search path... */
if (resourceExt != NULL) {
char **rc = PHYSFS_enumerateFiles("/");
char **i;
size_t extlen = strlen(resourceExt);
char *ext;
for (i = rc; *i != NULL; i++) {
size_t l = strlen(*i);
if ((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
ext = (*i) + (l - extlen);
if (strcasecmp(ext, resourceExt) == 0) {
PTRACE(5, "Add resource '" << *i << "' to search path");
const char *d = PHYSFS_getRealDir(*i);
char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
sprintf(str, "%s%s%s", d, dirsep, *i);
addToSearchPath(str, 1);
delete[] str;
};
};
};
PHYSFS_freeList(rc);
}
return PTrue;
}
bool Resources::Close() {
PHYSFS_deinit();
return PTrue;
}
bool Resources::addToSearchPath(const char* directory, bool append) {
if(!PHYSFS_addToSearchPath(directory, append)) {
PError << "Couldn't add '" << directory << "' to searchpath: " << PHYSFS_getLastError() << endl;
return PFalse;
};
return PTrue;
}
bool Resources::removeFromSearchPath(const char* directory) {
if(!PHYSFS_removeFromSearchPath(directory)) {
PError << "Couldn't remove '" << directory << "' from searchpath: " << PHYSFS_getLastError() << endl;
return PFalse;
};
return PTrue;
}
const char* Resources::getRealDir(const char* filename) {
return PHYSFS_getRealDir(filename);
}
std::string Resources::getRealName(const char* filename) {
const char* dir = PHYSFS_getRealDir(filename);
if (dir == 0) {
PError << "no such path '" << filename << "'" << endl;
return NULL;
};
std::string realname = dir;
realname += PHYSFS_getDirSeparator();
realname += filename;
return realname;
}
std::string Resources::getRealWriteName(const char* filename) {
const char* dir = PHYSFS_getWriteDir();
if (dir == 0) {
PError << "no writedir defined" << endl;
return NULL;
}
std::string realname = dir;
realname += PHYSFS_getDirSeparator();
realname += filename;
return realname;
}
char** Resources::enumerateFiles(const char* directory) {
return PHYSFS_enumerateFiles(directory);
}
void Resources::freeList(char** list) {
PHYSFS_freeList(list);
}
ResourceWO * Resources::RetrieveWrite(PString & filename) {
PHYSFS_file* file = PHYSFS_openWrite(filename);
if(!file) {
PError << "couldn't open file '" << filename << "' for writing: " << PHYSFS_getLastError() << endl;
return NULL;
};
return new ResourceWO(file);
}
ResourceRO * Resources::RetrieveRead(PString & filename) {
PHYSFS_file* file = PHYSFS_openRead(filename);
if(!file) {
const int fn_length = filename.GetLength()+1;
char fn[4096];
memcpy(fn, filename.GetPointer(), fn_length); // includes \0;
char * folder_sep = strrchr(fn, '/');
char * fn_start = fn;
char ** filelist = 0;
if ( folder_sep ) {
*folder_sep = 0;
filelist = enumerateFiles(fn);
*folder_sep = '/';
fn_start = folder_sep+1;
} else {
filelist = enumerateFiles(".");
folder_sep = fn;
};
if (filelist) {
for(char** curfile = filelist; *curfile != 0; curfile++) {
if ( strcasecmp(*curfile, fn_start) == 0 ) {
memcpy(fn_start, *curfile, fn_length-(folder_sep-fn));
file = PHYSFS_openRead(fn);
break;
};
};
freeList(filelist);
};
if (!file) {
PError << "couldn't open file '" << filename << "' for reading: " << PHYSFS_getLastError() << endl;
return NULL;
};
};
return new ResourceRO(file);
}
ResourceWO * Resources::RetrieveAppend(PString & filename) {
PHYSFS_file* file = PHYSFS_openAppend(filename);
if(!file) {
PError << "couldn't open file '" << filename << "' for writing(append): %s" << PHYSFS_getLastError() << endl;
return NULL;
};
return new ResourceWO(file);
}
bool Resources::mkdir(const char* directory) {
if(!PHYSFS_mkdir(directory)) {
PError << "couldn't create directory '" << directory << "': " << PHYSFS_getLastError() << endl;
return PFalse;
};
return PTrue;
}
bool Resources::remove(const char* filename) {
if(!PHYSFS_delete(filename)) {
PError << "couldn't remove file '" << filename << "': " << PHYSFS_getLastError() << endl;
return PFalse;
};
return PTrue;
}
bool Resources::exists(const char* filename) {
return PHYSFS_exists(filename);
}
bool Resources::isDirectory(const char* filename) {
return PHYSFS_isDirectory(filename);
}
bool Resources::isSymbolicLink(const char* filename) {
return PHYSFS_isSymbolicLink(filename);
}
int64_t Resources::getLastModTime(const char* filename) {
int64_t modtime = PHYSFS_getLastModTime(filename);
if (modtime < 0) {
PError << "couldn't determine modification time of '" << filename << "': " << PHYSFS_getLastError() << endl;
return NULL;
};
return modtime;
}
SDL_Surface * Resources::LoadImage(PString & imageName) {
PTRACE(4, "load image '" << imageName << "' from resources");
SDL_Surface * imageSurface = 0;
ResourceRO * imageFile = RetrieveRead(imageName);
if (!imageFile)
return NULL;
SDL_RWops * rw = imageFile->GetSDLRWOps();
if (!rw)
return NULL;
imageSurface = SDL_LoadBMP_RW(rw, 0);
PTRACE(4, "image width: " << imageSurface->w << ", image height: " << imageSurface->h);
return imageSurface;
}
SDL_Surface * Resources::LoadImageOptimized(PString & imageName) {
SDL_Surface * imageSurface = 0;
SDL_Surface * optimizedSurface = 0;
imageSurface = LoadImage(imageName);
if (!imageSurface)
return NULL;
//Create an optimized image
optimizedSurface = SDL_DisplayFormat(imageSurface);
//Free the old surface
SDL_FreeSurface(imageSurface);
return optimizedSurface;
}
bool Resources::LoadTextFile(PString & fileName, PStringArray & textBuffer) {
PTRACE(4, "load textfile '" << fileName << "' from resources");
bool result;
ResourceRO * textFile = RetrieveRead(fileName);
result = textFile->readText(textBuffer);
delete textFile;
return result;
}
//int * ResFile::loadFile(char *fileName, int *fileSize) {
/* PHYSFS_file *compFile;
PHYSFS_sint64 fileLength;
int *levelInMem = NULL;
char tempFilename[MAX_STRING_SIZE];
if (NO == fileSystemReady) {
SDL_SetError("PHYSFS system has not been initialised.");
return NULL;
}
// Get a handle to the file
compFile = PHYSFS_openRead(fileName);
if (NULL == compFile) {
strcpy(tempFilename, "");
strcpy(tempFilename, dataDirectory);
strcat(tempFilename, fileName);
compFile = PHYSFS_openRead(fileName);
if (NULL == compFile)
return NULL;
}
// Get it's size
fileLength = PHYSFS_fileLength(compFile);
if (-1 == fileLength) {
//CON_Out (mainConsole, "Unable to determine file length for [ %s ]", fileName);
return NULL;
}
// Pass the filesize back
*fileSize = (int)fileLength;
// conPrint (true, "Size of [ %s ] is [ %i ]", fileName, fileLength);
if (NULL != levelInMem)
free(levelInMem);
levelInMem = (int *)malloc((int)fileLength);
int returnCode = (int)PHYSFS_read(compFile, (void *)levelInMem, (PHYSFS_uint32)fileLength, 1);
if (-1 == returnCode) {
return NULL;
};
PHYSFS_close(compFile);
return (int *)levelInMem;*/
// return 0;
//}
| [
"[email protected]"
] | |
ba9281141a42416d8ed17d2fca3e69cbd99991fd | c7300b157b6b01761949dc742f45c16ed5723956 | /ScMedia/include/MediaSdk.h | 3ef15d3c7a4c7b68ae8ea1d9bc6229d9d14b6cb2 | [] | no_license | chxj1980/SimpleCpp | 64f3fe2272bae90e6202ac55f7cc8ad296bfdd23 | 5134f996421721cfde73d0c76890894a0a1462bf | refs/heads/master | 2021-09-07T20:13:40.289732 | 2018-02-28T10:51:20 | 2018-02-28T10:51:20 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,083 | h | // 下列 ifdef 块是创建使从 DLL 导出更简单的
// 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 VIVSMEDIABOX_EXPORTS
// 符号编译的。在使用此 DLL 的
// 任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将
// VIVSMEDIABOX_API 函数视为是从 DLL 导入的,而此 DLL 则将用此宏定义的
// 符号视为是被导出的。
#ifndef MEDIA_SDK_H
#define MEDIA_SDK_H
#ifdef WIN32
#ifdef VIVSMEDIABOX_EXPORTS
#define MEDIASDK_API __declspec(dllexport)
#else
#define MEDIASDK_API __declspec(dllimport)
#endif
#else
#define MEDIASDK_API
#define __stdcall
#endif
#ifndef WIN32
#define debug printf
unsigned long timeGetTime();
#endif
//#define OS_WIN
// 此类是从 VivsMediaBox.dll 导出的
class MEDIASDK_API CVivsMediaBox {
public:
CVivsMediaBox(void);
// TODO: 在此添加您的方法。
};
extern MEDIASDK_API int nVivsMediaBox;
MEDIASDK_API int fnVivsMediaBox(void);
MEDIASDK_API int Vmb_Ret2Err(int nRet);
MEDIASDK_API int Vmb_Err2Ret(int nErr);
#endif
| [
"[email protected]"
] | |
56295d761ef06ad03730ea62e8f4ad8f9a594e03 | 032013d17b506b2eb732a535b9e42df148d9a75d | /src/plugins/monocle/plugins/dik/dik.h | 671bc84ae1fda7e7dfc69362e34c35759bf2a02a | [
"BSL-1.0"
] | permissive | zhao07/leechcraft | 55bb64d6eab590a69d92585150ae1af3d32ee342 | 4100c5bf3a260b8bc041c14902e2f7b74da638a3 | refs/heads/master | 2021-01-22T11:59:18.782462 | 2014-04-01T14:04:10 | 2014-04-01T14:04:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,394 | h | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#pragma once
#include <QObject>
#include <interfaces/iinfo.h>
#include <interfaces/iplugin2.h>
#include <interfaces/monocle/ibackendplugin.h>
namespace LeechCraft
{
namespace Monocle
{
namespace Dik
{
class Plugin : public QObject
, public IInfo
, public IPlugin2
, public IBackendPlugin
{
Q_OBJECT
Q_INTERFACES (IInfo IPlugin2 LeechCraft::Monocle::IBackendPlugin)
public:
void Init (ICoreProxy_ptr);
void SecondInit ();
QByteArray GetUniqueID () const;
void Release ();
QString GetName () const;
QString GetInfo () const;
QIcon GetIcon () const;
QSet<QByteArray> GetPluginClasses () const;
bool CanLoadDocument (const QString&);
IDocument_ptr LoadDocument (const QString&);
};
}
}
}
| [
"[email protected]"
] | |
544ad9dcc7b47967edeafd009175045b11cb651a | 3b4c44ec1104a1b6eeb432c5b270cfd1e661a4fe | /example/vl/sift.h | cb5358fa739dcd57ed367bfea600bdb49e70ce0a | [] | no_license | chensh236/ComputerVisionImageStich | 76d9b49ff3d78c7801bdb67a1c3181cd85a1acd1 | c350157d1995c173e99814272b953080360b7062 | refs/heads/master | 2020-04-08T06:21:08.258636 | 2018-11-27T09:30:59 | 2018-11-27T09:30:59 | 159,093,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,534 | h | #ifndef VL_SIFT_H
#define VL_SIFT_H
#include <stdio.h>
#include <iostream>
#include "generic.h"
using namespace std;
/** @brief SIFT filter pixel type */
typedef float vl_sift_pix ;
/** ------------------------------------------------------------------
** @brief SIFT filter keypoint
**
** This structure represent a keypoint as extracted by the SIFT
** filter ::VlSiftFilt.
**/
typedef struct _VlSiftKeypoint
{
int o ; /**< o coordinate (octave). */
int ix ; /**< Integer unnormalized x coordinate. */
int iy ; /**< Integer unnormalized y coordinate. */
int is ; /**< Integer s coordinate. */
float x ; /**< x coordinate. */
float y ; /**< y coordinate. */
float s ; /**< s coordinate. */
float sigma ; /**< scale. */
} VlSiftKeypoint ;
/** ------------------------------------------------------------------
** @brief SIFT filter
**
** This filter implements the SIFT detector and descriptor.
**/
typedef struct _VlSiftFilt
{
double sigman ; /**< nominal image smoothing. */
double sigma0 ; /**< smoothing of pyramid base. */
double sigmak ; /**< k-smoothing */
double dsigma0 ; /**< delta-smoothing. */
int width ; /**< image width. */
int height ; /**< image height. */
int O ; /**< number of octaves. */
int S ; /**< number of levels per octave. */
int o_min ; /**< minimum octave index. */
int s_min ; /**< minimum level index. */
int s_max ; /**< maximum level index. */
int o_cur ; /**< current octave. */
vl_sift_pix *temp ; /**< temporary pixel buffer. */
vl_sift_pix *octave ; /**< current GSS data. */
vl_sift_pix *dog ; /**< current DoG data. */
int octave_width ; /**< current octave width. */
int octave_height ; /**< current octave height. */
vl_sift_pix *gaussFilter ; /**< current Gaussian filter */
double gaussFilterSigma ; /**< current Gaussian filter std */
vl_size gaussFilterWidth ; /**< current Gaussian filter width */
VlSiftKeypoint* keys ;/**< detected keypoints. */
int nkeys ; /**< number of detected keypoints. */
int keys_res ; /**< size of the keys buffer. */
double peak_thresh ; /**< peak threshold. */
double edge_thresh ; /**< edge threshold. */
double norm_thresh ; /**< norm threshold. */
double magnif ; /**< magnification factor. */
double windowSize ; /**< size of Gaussian window (in spatial bins) */
vl_sift_pix *grad ; /**< GSS gradient data. */
int grad_o ; /**< GSS gradient data octave. */
} VlSiftFilt ;
/** @name Create and destroy
** @{
**/
VL_EXPORT
VlSiftFilt* vl_sift_new (int width, int height,
int noctaves, int nlevels,
int o_min) ;
VL_EXPORT
void vl_sift_delete (VlSiftFilt *f) ;
/** @} */
/** @name Process data
** @{
**/
VL_EXPORT
int vl_sift_process_first_octave (VlSiftFilt *f,
vl_sift_pix const *im) ;
VL_EXPORT
int vl_sift_process_next_octave (VlSiftFilt *f) ;
VL_EXPORT
void vl_sift_detect (VlSiftFilt *f) ;
VL_EXPORT
int vl_sift_calc_keypoint_orientations (VlSiftFilt *f,
double angles [4],
VlSiftKeypoint const*k);
VL_EXPORT
void vl_sift_calc_keypoint_descriptor (VlSiftFilt *f,
vl_sift_pix *descr,
VlSiftKeypoint const* k,
double angle) ;
VL_EXPORT
void vl_sift_calc_raw_descriptor (VlSiftFilt const *f,
vl_sift_pix const* image,
vl_sift_pix *descr,
int widht, int height,
double x, double y,
double s, double angle0) ;
VL_EXPORT
void vl_sift_keypoint_init (VlSiftFilt const *f,
VlSiftKeypoint *k,
double x,
double y,
double sigma) ;
/** @} */
/** @name Retrieve data and parameters
** @{
**/
VL_INLINE int vl_sift_get_octave_index (VlSiftFilt const *f) ;
VL_INLINE int vl_sift_get_noctaves (VlSiftFilt const *f) ;
VL_INLINE int vl_sift_get_octave_first (VlSiftFilt const *f) ;
VL_INLINE int vl_sift_get_octave_width (VlSiftFilt const *f) ;
VL_INLINE int vl_sift_get_octave_height (VlSiftFilt const *f) ;
VL_INLINE int vl_sift_get_nlevels (VlSiftFilt const *f) ;
VL_INLINE int vl_sift_get_nkeypoints (VlSiftFilt const *f) ;
VL_INLINE double vl_sift_get_peak_thresh (VlSiftFilt const *f) ;
VL_INLINE double vl_sift_get_edge_thresh (VlSiftFilt const *f) ;
VL_INLINE double vl_sift_get_norm_thresh (VlSiftFilt const *f) ;
VL_INLINE double vl_sift_get_magnif (VlSiftFilt const *f) ;
VL_INLINE double vl_sift_get_window_size (VlSiftFilt const *f) ;
VL_INLINE vl_sift_pix *vl_sift_get_octave (VlSiftFilt const *f, int s) ;
VL_INLINE VlSiftKeypoint const *vl_sift_get_keypoints (VlSiftFilt const *f) ;
/** @} */
/** @name Set parameters
** @{
**/
VL_INLINE void vl_sift_set_peak_thresh (VlSiftFilt *f, double t) ;
VL_INLINE void vl_sift_set_edge_thresh (VlSiftFilt *f, double t) ;
VL_INLINE void vl_sift_set_norm_thresh (VlSiftFilt *f, double t) ;
VL_INLINE void vl_sift_set_magnif (VlSiftFilt *f, double m) ;
VL_INLINE void vl_sift_set_window_size (VlSiftFilt *f, double m) ;
/** @} */
/* -------------------------------------------------------------------
* Inline functions implementation
* ---------------------------------------------------------------- */
/** ------------------------------------------------------------------
** @brief Get current octave index.
** @param f SIFT filter.
** @return index of the current octave.
**/
VL_INLINE int
vl_sift_get_octave_index (VlSiftFilt const *f)
{
return f-> o_cur ;
}
/** ------------------------------------------------------------------
** @brief Get number of octaves.
** @param f SIFT filter.
** @return number of octaves.
**/
VL_INLINE int
vl_sift_get_noctaves (VlSiftFilt const *f)
{
return f-> O ;
}
/**-------------------------------------------------------------------
** @brief Get first octave.
** @param f SIFT filter.
** @return index of the first octave.
**/
VL_INLINE int
vl_sift_get_octave_first (VlSiftFilt const *f)
{
return f-> o_min ;
}
/** ------------------------------------------------------------------
** @brief Get current octave width
** @param f SIFT filter.
** @return current octave width.
**/
VL_INLINE int
vl_sift_get_octave_width (VlSiftFilt const *f)
{
return f-> octave_width ;
}
/** ------------------------------------------------------------------
** @brief Get current octave height
** @param f SIFT filter.
** @return current octave height.
**/
VL_INLINE int
vl_sift_get_octave_height (VlSiftFilt const *f)
{
return f-> octave_height ;
}
/** ------------------------------------------------------------------
** @brief Get current octave data
** @param f SIFT filter.
** @param s level index.
**
** The level index @a s ranges in the interval <tt>s_min = -1</tt>
** and <tt> s_max = S + 2</tt>, where @c S is the number of levels
** per octave.
**
** @return pointer to the octave data for level @a s.
**/
VL_INLINE vl_sift_pix *
vl_sift_get_octave (VlSiftFilt const *f, int s)
{
int w = vl_sift_get_octave_width (f) ;
int h = vl_sift_get_octave_height (f) ;
return f->octave + w * h * (s - f->s_min) ;
}
/** ------------------------------------------------------------------
** @brief Get number of levels per octave
** @param f SIFT filter.
** @return number of leves per octave.
**/
VL_INLINE int
vl_sift_get_nlevels (VlSiftFilt const *f)
{
return f-> S ;
}
/** ------------------------------------------------------------------
** @brief Get number of keypoints.
** @param f SIFT filter.
** @return number of keypoints.
**/
VL_INLINE int
vl_sift_get_nkeypoints (VlSiftFilt const *f)
{
return f-> nkeys ;
}
/** ------------------------------------------------------------------
** @brief Get keypoints.
** @param f SIFT filter.
** @return pointer to the keypoints list.
**/
VL_INLINE VlSiftKeypoint const *
vl_sift_get_keypoints (VlSiftFilt const *f)
{
return f-> keys ;
}
/** ------------------------------------------------------------------
** @brief Get peaks treashold
** @param f SIFT filter.
** @return threshold ;
**/
VL_INLINE double
vl_sift_get_peak_thresh (VlSiftFilt const *f)
{
return f -> peak_thresh ;
}
/** ------------------------------------------------------------------
** @brief Get edges threshold
** @param f SIFT filter.
** @return threshold.
**/
VL_INLINE double
vl_sift_get_edge_thresh (VlSiftFilt const *f)
{
return f -> edge_thresh ;
}
/** ------------------------------------------------------------------
** @brief Get norm threshold
** @param f SIFT filter.
** @return threshold.
**/
VL_INLINE double
vl_sift_get_norm_thresh (VlSiftFilt const *f)
{
return f -> norm_thresh ;
}
/** ------------------------------------------------------------------
** @brief Get the magnification factor
** @param f SIFT filter.
** @return magnification factor.
**/
VL_INLINE double
vl_sift_get_magnif (VlSiftFilt const *f)
{
return f -> magnif ;
}
/** ------------------------------------------------------------------
** @brief Get the Gaussian window size.
** @param f SIFT filter.
** @return standard deviation of the Gaussian window (in spatial bin units).
**/
VL_INLINE double
vl_sift_get_window_size (VlSiftFilt const *f)
{
return f -> windowSize ;
}
/** ------------------------------------------------------------------
** @brief Set peaks threshold
** @param f SIFT filter.
** @param t threshold.
**/
VL_INLINE void
vl_sift_set_peak_thresh (VlSiftFilt *f, double t)
{
f -> peak_thresh = t ;
}
/** ------------------------------------------------------------------
** @brief Set edges threshold
** @param f SIFT filter.
** @param t threshold.
**/
VL_INLINE void
vl_sift_set_edge_thresh (VlSiftFilt *f, double t)
{
f -> edge_thresh = t ;
}
/** ------------------------------------------------------------------
** @brief Set norm threshold
** @param f SIFT filter.
** @param t threshold.
**/
VL_INLINE void
vl_sift_set_norm_thresh (VlSiftFilt *f, double t)
{
f -> norm_thresh = t ;
}
/** ------------------------------------------------------------------
** @brief Set the magnification factor
** @param f SIFT filter.
** @param m magnification factor.
**/
VL_INLINE void
vl_sift_set_magnif (VlSiftFilt *f, double m)
{
f -> magnif = m ;
}
/** ------------------------------------------------------------------
** @brief Set the Gaussian window size
** @param f SIFT filter.
** @param x Gaussian window size (in units of spatial bin).
**
** This is the parameter @f$ \hat \sigma_{\text{win}} @f$ of
** the standard SIFT descriptor @ref sift-tech-descriptor-std.
**/
VL_INLINE void
vl_sift_set_window_size (VlSiftFilt *f, double x)
{
f -> windowSize = x ;
}
/* VL_SIFT_H */
#endif
| [
"[email protected]"
] | |
dca335e62736e36adb2ef4817c4a5d57a6e6a3de | ed4389138e32c59b86908ff8e6ed056fe898152d | /src/pubkey.cpp | e92890765df9d6818c2cc9510eab15c6c5e524e8 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sphinxcoin/sphinx-old | 3728c34048d0585f4c3932034e3ce424313e6488 | 589464539ef66e8ce3a6173bb755a83a1cb296fa | refs/heads/master | 2020-03-26T04:47:28.786704 | 2018-09-19T15:03:15 | 2018-09-19T15:03:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,202 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pubkey.h"
#include "script/script.h"
#include <secp256k1.h>
#include <secp256k1_recovery.h>
namespace
{
/* Global secp256k1_context object used for verification. */
secp256k1_context* secp256k1_context_verify = NULL;
}
/** This function is taken from the libsecp256k1 distribution and implements
* DER parsing for ECDSA signatures, while supporting an arbitrary subset of
* format violations.
*
* Supported violations include negative integers, excessive padding, garbage
* at the end, and overly long length descriptors. This is safe to use in
* Sphinxcoin because since the activation of BIP66, signatures are verified to be
* strict DER before being passed to this module, and we know it supports all
* violations present in the blockchain before that point.
*/
static int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) {
size_t rpos, rlen, spos, slen;
size_t pos = 0;
size_t lenbyte;
unsigned char tmpsig[64] = {0};
int overflow = 0;
/* Hack to initialize sig with a correctly-parsed but invalid signature. */
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
/* Sequence tag byte */
if (pos == inputlen || input[pos] != 0x30) {
return 0;
}
pos++;
/* Sequence length bytes */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
pos += lenbyte;
}
/* Integer tag byte for R */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for R */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
if (lenbyte >= sizeof(size_t)) {
return 0;
}
rlen = 0;
while (lenbyte > 0) {
rlen = (rlen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
rlen = lenbyte;
}
if (rlen > inputlen - pos) {
return 0;
}
rpos = pos;
pos += rlen;
/* Integer tag byte for S */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for S */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (pos + lenbyte > inputlen) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
if (lenbyte >= sizeof(size_t)) {
return 0;
}
slen = 0;
while (lenbyte > 0) {
slen = (slen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
slen = lenbyte;
}
if (slen > inputlen - pos) {
return 0;
}
spos = pos;
pos += slen;
/* Ignore leading zeroes in R */
while (rlen > 0 && input[rpos] == 0) {
rlen--;
rpos++;
}
/* Copy R value */
if (rlen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
}
/* Ignore leading zeroes in S */
while (slen > 0 && input[spos] == 0) {
slen--;
spos++;
}
/* Copy S value */
if (slen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 64 - slen, input + spos, slen);
}
if (!overflow) {
overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
if (overflow) {
/* Overwrite the result again with a correctly-parsed but invalid
signature if parsing failed. */
memset(tmpsig, 0, 64);
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
return 1;
}
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
secp256k1_pubkey pubkey;
secp256k1_ecdsa_signature sig;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) {
return false;
}
if (vchSig.size() == 0) {
return false;
}
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, &vchSig[0], vchSig.size())) {
return false;
}
/* libsecp256k1's ECDSA verification requires lower-S signatures, which have
* not historically been enforced in Sphinxcoin, so normalize them first. */
secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, &sig, &sig);
return secp256k1_ecdsa_verify(secp256k1_context_verify, &sig, hash.begin(), &pubkey);
}
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.size() != 65)
return false;
int recid = (vchSig[0] - 27) & 3;
bool fComp = ((vchSig[0] - 27) & 4) != 0;
secp256k1_pubkey pubkey;
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_verify, &sig, &vchSig[1], recid)) {
return false;
}
if (!secp256k1_ecdsa_recover(secp256k1_context_verify, &pubkey, &sig, hash.begin())) {
return false;
}
unsigned char pub[65];
size_t publen = 65;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid())
return false;
secp256k1_pubkey pubkey;
return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size());
}
bool CPubKey::Decompress() {
if (!IsValid())
return false;
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) {
return false;
}
unsigned char pub[65];
size_t publen = 65;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
assert(IsValid());
assert((nChild >> 31) == 0);
assert(begin() + 33 == end());
unsigned char out[64];
BIP32Hash(cc, nChild, *begin(), begin()+1, out);
memcpy(ccChild, out+32, 32);
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, &(*this)[0], size())) {
return false;
}
if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_verify, &pubkey, out)) {
return false;
}
unsigned char pub[33];
size_t publen = 33;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, SECP256K1_EC_COMPRESSED);
pubkeyChild.Set(pub, pub + publen);
return true;
}
void CExtPubKey::Encode(unsigned char code[74]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
memcpy(code+9, vchChainCode, 32);
assert(pubkey.size() == 33);
memcpy(code+41, pubkey.begin(), 33);
}
void CExtPubKey::Decode(const unsigned char code[74]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(vchChainCode, code+9, 32);
pubkey.Set(code+41, code+74);
}
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = nChild;
return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode);
}
/* static */ bool CPubKey::CheckLowS(const std::vector<unsigned char>& vchSig) {
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, &vchSig[0], vchSig.size())) {
return false;
}
return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, NULL, &sig));
}
/* static */ int ECCVerifyHandle::refcount = 0;
ECCVerifyHandle::ECCVerifyHandle()
{
if (refcount == 0) {
assert(secp256k1_context_verify == NULL);
secp256k1_context_verify = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
assert(secp256k1_context_verify != NULL);
}
refcount++;
}
ECCVerifyHandle::~ECCVerifyHandle()
{
refcount--;
if (refcount == 0) {
assert(secp256k1_context_verify != NULL);
secp256k1_context_destroy(secp256k1_context_verify);
secp256k1_context_verify = NULL;
}
}
| [
"[email protected]"
] | |
490a029aa3da706c0d07533ccc8749160154bb04 | ff0d14df1484fbbd37cc8aa5fbb7629670ffa445 | /Tutorials/EB/MacProj/initEB.cpp | 2d5c867892610ed74b559f83be025cf36bd14909 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ghweber/amrex | c4c56cc69a519318f78c511f20a6c63f6b064ea7 | 165e36b28cdd5d9ab0448346a3bd8c2a8e7357f3 | refs/heads/master | 2020-05-07T00:58:49.935338 | 2019-04-09T01:35:17 | 2019-04-09T01:35:17 | 180,254,174 | 0 | 0 | NOASSERTION | 2019-04-09T00:32:43 | 2019-04-09T00:32:43 | null | UTF-8 | C++ | false | false | 170 | cpp | #include <AMReX_ParmParse.H>
#include <AMReX_EB2_IF.H>
#include "initEB.H"
using namespace amrex;
void initEB (const Geometry& geom)
{
EB2::Build(geom, 0, 30);
}
| [
"[email protected]"
] | |
4b00579881096920e5bd47c9a5cbbfe38761164a | 2d98b85b551a53ca74f40db5a8bbb4a81d94f308 | /pr1id314/src/item.cc | 12e70e8c05b98c78dff26468fbd19c5df4dd6d2f | [] | no_license | djuber/MCS-360 | 6528dca02669b0cbedb59f4288c1efe70bace986 | 93a54088101f189709d914b807dc5516a2115d86 | refs/heads/master | 2016-09-16T11:33:13.672712 | 2011-12-03T19:41:49 | 2011-12-03T19:41:49 | 2,905,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,103 | cc | /** @file item.cc
@author Daniel Uber
@brief Item::supplier modifiers using lookup table.
*/
#include "item.h"
#include "project1.h"
#include "dollar.h"
#include <string>
#include <iostream>
#include <cstring>
/** generate an empty new Item */
Item::Item()
{
currentMonth = INVALID;
name = "*";
code = "*";
onHand = -1;
target= -1;
cost.whole=-1;
cost.cents=0;
price.whole=-1;
price.cents=0;
itemSupplier.code=-1;
itemSupplier.name="*";
shelfLife=-1;
avgVolume=-1.0;
currentSales=-1.0;
}
/** supplier modifier
@param c is supplier code
supplier name is provided from lookup table
*/
void Item::supplier(int c) {
itemSupplier.code = c;
itemSupplier.name = SupplierNameFromCode(c);
return;
}
/** supplier modifier
@param n is supplier name
supplier code is provided by lookup table
*/
void Item::supplier(std::string n){
itemSupplier.name = n;
itemSupplier.code = SupplierCodeFromName(n);
}
/** generate a string representation of item and insert it into
an ostream.
*/
std::ostream& operator<<(std::ostream& os, Item& item){
os<<"_ITEM_ "
<<" _MONTH_ " << printMonth(item.current_month())
<<" _NAME_ " << item.Name()
<<" _CODE_ " << item.Code()
<<" _ONHAND_ " << item.inStock()
<<" _TARGET_ " << item.desired()
<<" _COST_ " << item.Cost().print()
<<" _PRICE_ " << item.Price().print()
<<" _ITEM_SUPPLIER_ " << item.supplierCode() <<' '
<< item.supplierName()
<<" _SHELF_LIFE_ " << item.ShelfLife()
<<" _AVGVOLUME_ " << item.volume()
<<" _CURRENT_SALES_ " << item.sales().print()
<< std::endl;
return os;
}
/** extract Item from istream (with newline.)
really this only will work when the input was provided from
ostream operator<<, i.e., it's really unlikely that this would work
for hand edited files.
*/
std::istream& operator>>(std::istream& is, Item& item){
std::string s,a;
int d;
Dollar dol;
is>>s;
if(!strcmp(s.c_str(), "_ITEM_")){
is>>s;
is>>s;
item.current_month(readMonth(s));
is>>s;
is>>s;
while(strcmp(s.c_str(),"_CODE_")){
a+=' '+s;
is>>s;
}
item.Name(a);
is>>s;
item.Code(s);
is>>s;
is>>d;
item.inStock(d);
is>>s;
is>>d;
item.desired(d);
is>>s;
is>>dol;
item.Cost(dol);
is>>s;
is>>dol;
item.Price(dol);
is>>s;
is>>d;
is>>s;
Supplier x;
x.code=d;
x.name=s;
is>>s;
while(strcmp(s.c_str(),"_SHELF_LIFE_")){
x.name+=' '+s;
is>>s;
}
item.supplier(x);
is>>d;
item.ShelfLife(d);
is>>s;
is>>d;
item.volume(d);
is>>s;
is>>dol;
item.sales(dol);
is.ignore(1,'\n');
} else {
// not an item record, return buffered input to stream
for(size_t i=0; i<s.length();i++)
is.putback(s[s.length() - 1 -i]);
// signal a problem with fail
std::ios_base::iostate state = std::ios_base::failbit;
is.setstate(state);
}
return is;
}
| [
"[email protected]"
] | |
9b1d88c86db956660ab390caafe5ee66a24ae873 | a0e1fc02eb3154aaad33c58979c24314a02aed4b | /qt/lab3/mainwindow.h | f95560b228c05bcdc6d570ef627a05d0a3cbde00 | [] | no_license | antuan1996/univer-2year- | 76bdb5c27280bdc53cb8625461a5d2af53cfb54c | e8df98a212e93271234f835757462bb9dc8bb904 | refs/heads/master | 2021-01-10T13:52:27.160566 | 2017-02-25T06:12:36 | 2017-02-25T06:12:36 | 44,915,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void get_val();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"[email protected]"
] | |
b10a9f07c593389596f763d2044979b0da3d1af0 | 1145a4f5335d8cf966f9fa5a93df8fbdd8ff9fe4 | /src/test/prevector_tests.cpp | 525c1b87f7a36901a4db7af69c1dfb01d54742ce | [
"MIT"
] | permissive | RapidsOfficial/Rapids | 40a6a143eef9628c2fbe8c436012a2a0621df093 | cddbdb9514834357dfe49bb037e069f300be144b | refs/heads/4.0 | 2022-12-26T12:15:34.511952 | 2022-12-13T20:16:02 | 2022-12-13T20:16:02 | 180,844,322 | 74 | 29 | MIT | 2022-12-13T20:16:03 | 2019-04-11T17:29:29 | C++ | UTF-8 | C++ | false | false | 7,534 | cpp | // Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <vector>
#include "prevector.h"
#include "random.h"
#include "serialize.h"
#include "streams.h"
#include "test/test_pivx.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)
template<unsigned int N, typename T>
class prevector_tester {
typedef std::vector<T> realtype;
realtype real_vector;
realtype real_vector_alt;
typedef prevector<N, T> pretype;
pretype pre_vector;
pretype pre_vector_alt;
typedef typename pretype::size_type Size;
void test() {
const pretype& const_pre_vector = pre_vector;
BOOST_CHECK_EQUAL(real_vector.size(), pre_vector.size());
BOOST_CHECK_EQUAL(real_vector.empty(), pre_vector.empty());
for (Size s = 0; s < real_vector.size(); s++) {
BOOST_CHECK(real_vector[s] == pre_vector[s]);
BOOST_CHECK(&(pre_vector[s]) == &(pre_vector.begin()[s]));
BOOST_CHECK(&(pre_vector[s]) == &*(pre_vector.begin() + s));
BOOST_CHECK(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));
}
// BOOST_CHECK(realtype(pre_vector) == real_vector);
BOOST_CHECK(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
BOOST_CHECK(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
size_t pos = 0;
for (const T& v : pre_vector) {
BOOST_CHECK(v == real_vector[pos++]);
}
pos = 0;
for (const T& v : const_pre_vector) {
BOOST_CHECK(v == real_vector[pos++]);
}
CDataStream ss1(SER_DISK, 0);
CDataStream ss2(SER_DISK, 0);
ss1 << real_vector;
ss2 << pre_vector;
BOOST_CHECK_EQUAL(ss1.size(), ss2.size());
for (Size s = 0; s < ss1.size(); s++) {
BOOST_CHECK_EQUAL(ss1[s], ss2[s]);
}
}
public:
void resize(Size s) {
real_vector.resize(s);
BOOST_CHECK_EQUAL(real_vector.size(), s);
pre_vector.resize(s);
BOOST_CHECK_EQUAL(pre_vector.size(), s);
test();
}
void reserve(Size s) {
real_vector.reserve(s);
BOOST_CHECK(real_vector.capacity() >= s);
pre_vector.reserve(s);
BOOST_CHECK(pre_vector.capacity() >= s);
test();
}
void insert(Size position, const T& value) {
real_vector.insert(real_vector.begin() + position, value);
pre_vector.insert(pre_vector.begin() + position, value);
test();
}
void insert(Size position, Size count, const T& value) {
real_vector.insert(real_vector.begin() + position, count, value);
pre_vector.insert(pre_vector.begin() + position, count, value);
test();
}
template<typename I>
void insert_range(Size position, I first, I last) {
real_vector.insert(real_vector.begin() + position, first, last);
pre_vector.insert(pre_vector.begin() + position, first, last);
test();
}
void erase(Size position) {
real_vector.erase(real_vector.begin() + position);
pre_vector.erase(pre_vector.begin() + position);
test();
}
void erase(Size first, Size last) {
real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);
pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);
test();
}
void update(Size pos, const T& value) {
real_vector[pos] = value;
pre_vector[pos] = value;
test();
}
void push_back(const T& value) {
real_vector.push_back(value);
pre_vector.push_back(value);
test();
}
void pop_back() {
real_vector.pop_back();
pre_vector.pop_back();
test();
}
void clear() {
real_vector.clear();
pre_vector.clear();
}
void assign(Size n, const T& value) {
real_vector.assign(n, value);
pre_vector.assign(n, value);
}
Size size() {
return real_vector.size();
}
Size capacity() {
return pre_vector.capacity();
}
void shrink_to_fit() {
pre_vector.shrink_to_fit();
test();
}
void swap() {
real_vector.swap(real_vector_alt);
pre_vector.swap(pre_vector_alt);
test();
}
void move() {
real_vector = std::move(real_vector_alt);
real_vector_alt.clear();
pre_vector = std::move(pre_vector_alt);
pre_vector_alt.clear();
}
void copy() {
real_vector = real_vector_alt;
pre_vector = pre_vector_alt;
}
};
BOOST_AUTO_TEST_CASE(PrevectorTestInt)
{
for (int j = 0; j < 64; j++) {
prevector_tester<8, int> test;
for (int i = 0; i < 2048; i++) {
int r = InsecureRand32();
if ((r % 4) == 0) {
test.insert(InsecureRand32() % (test.size() + 1), InsecureRand32());
}
if (test.size() > 0 && ((r >> 2) % 4) == 1) {
test.erase(InsecureRand32() % test.size());
}
if (((r >> 4) % 8) == 2) {
int new_size = std::max<int>(0, std::min<int>(30, test.size() + (InsecureRand32() % 5) - 2));
test.resize(new_size);
}
if (((r >> 7) % 8) == 3) {
test.insert(InsecureRand32() % (test.size() + 1), 1 + (InsecureRand32() % 2), InsecureRand32());
}
if (((r >> 10) % 8) == 4) {
int del = std::min<int>(test.size(), 1 + (InsecureRand32() % 2));
int beg = InsecureRand32() % (test.size() + 1 - del);
test.erase(beg, beg + del);
}
if (((r >> 13) % 16) == 5) {
test.push_back(InsecureRand32());
}
if (test.size() > 0 && ((r >> 17) % 16) == 6) {
test.pop_back();
}
if (((r >> 21) % 32) == 7) {
int values[4];
int num = 1 + (InsecureRand32() % 4);
for (int i = 0; i < num; i++) {
values[i] = InsecureRand32();
}
test.insert_range(InsecureRand32() % (test.size() + 1), values, values + num);
}
if (((r >> 26) % 32) == 8) {
int del = std::min<int>(test.size(), 1 + (InsecureRand32() % 4));
int beg = InsecureRand32() % (test.size() + 1 - del);
test.erase(beg, beg + del);
}
r = InsecureRand32();
if (r % 32 == 9) {
test.reserve(InsecureRand32() % 32);
}
if ((r >> 5) % 64 == 10) {
test.shrink_to_fit();
}
if (test.size() > 0) {
test.update(InsecureRand32() % test.size(), InsecureRand32());
}
if (((r >> 11) % 1024) == 11) {
test.clear();
}
if (((r >> 21) % 512) == 12) {
test.assign(InsecureRand32() % 32, InsecureRand32());
}
if (((r >> 15) % 8) == 3) {
test.swap();
}
if (((r >> 15) % 16) == 8) {
test.copy();
}
if (((r >> 15) % 32) == 18) {
test.move();
}
}
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
be5f71f5158f44462fb302e9954d37f4541363db | c1970ee06cb34a6c670cf26bdde2bbbe38abaa66 | /libiec61131parser/runtime/tree/pattern/ParseTreePatternMatcher.cpp | 3c61b937ee133096cc615beeed8b8247af0475a5 | [] | no_license | aeon32/speedometer_qml | 79b00364c40260c70088610099fc20c26e69e567 | 36a971fbc5b77c9e166573140adbcbc848dcea04 | refs/heads/master | 2023-06-02T02:24:27.380346 | 2021-06-15T14:43:29 | 2021-06-15T14:43:29 | 157,600,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,662 | cpp | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "tree/pattern/ParseTreePattern.h"
#include "tree/pattern/ParseTreeMatch.h"
#include "tree/TerminalNode.h"
#include "CommonTokenStream.h"
#include "ParserInterpreter.h"
#include "tree/pattern/TokenTagToken.h"
#include "ParserRuleContext.h"
#include "tree/pattern/RuleTagToken.h"
#include "tree/pattern/TagChunk.h"
#include "atn/ATN.h"
#include "Lexer.h"
#include "BailErrorStrategy.h"
#include "ListTokenSource.h"
#include "tree/pattern/TextChunk.h"
#include "ANTLRInputStream.h"
#include "support/Arrays.h"
#include "Exceptions.h"
#include "support/StringUtils.h"
#include "support/CPPUtils.h"
#include "tree/pattern/ParseTreePatternMatcher.h"
using namespace antlr4;
using namespace antlr4::tree;
using namespace antlr4::tree::pattern;
using namespace antlrcpp;
ParseTreePatternMatcher::CannotInvokeStartRule::CannotInvokeStartRule(const RuntimeException &e) : RuntimeException(e.what()) {
}
ParseTreePatternMatcher::CannotInvokeStartRule::~CannotInvokeStartRule() {
}
ParseTreePatternMatcher::StartRuleDoesNotConsumeFullPattern::~StartRuleDoesNotConsumeFullPattern() {
}
ParseTreePatternMatcher::ParseTreePatternMatcher(Lexer *lexer, Parser *parser) : _lexer(lexer), _parser(parser) {
InitializeInstanceFields();
}
ParseTreePatternMatcher::~ParseTreePatternMatcher() {
}
void ParseTreePatternMatcher::setDelimiters(const std::string &start, const std::string &stop, const std::string &escapeLeft) {
if (start.empty()) {
throw IllegalArgumentException("start cannot be null or empty");
}
if (stop.empty()) {
throw IllegalArgumentException("stop cannot be null or empty");
}
_start = start;
_stop = stop;
_escape = escapeLeft;
}
bool ParseTreePatternMatcher::matches(ParseTree *tree, const std::string &pattern, int patternRuleIndex) {
ParseTreePattern p = compile(pattern, patternRuleIndex);
return matches(tree, p);
}
bool ParseTreePatternMatcher::matches(ParseTree *tree, const ParseTreePattern &pattern) {
std::map<std::string, std::vector<ParseTree *>> labels;
ParseTree *mismatchedNode = matchImpl(tree, pattern.getPatternTree(), labels);
return mismatchedNode == nullptr;
}
ParseTreeMatch ParseTreePatternMatcher::match(ParseTree *tree, const std::string &pattern, int patternRuleIndex) {
ParseTreePattern p = compile(pattern, patternRuleIndex);
return match(tree, p);
}
ParseTreeMatch ParseTreePatternMatcher::match(ParseTree *tree, const ParseTreePattern &pattern) {
std::map<std::string, std::vector<ParseTree *>> labels;
tree::ParseTree *mismatchedNode = matchImpl(tree, pattern.getPatternTree(), labels);
return ParseTreeMatch(tree, pattern, labels, mismatchedNode);
}
ParseTreePattern ParseTreePatternMatcher::compile(const std::string &pattern, int patternRuleIndex) {
ListTokenSource tokenSrc(tokenize(pattern));
CommonTokenStream tokens(&tokenSrc);
ParserInterpreter parserInterp(_parser->getGrammarFileName(), _parser->getVocabulary(),
_parser->getRuleNames(), _parser->getATNWithBypassAlts(), &tokens);
ParserRuleContext *tree = nullptr;
try {
parserInterp.setErrorHandler(std::make_shared<BailErrorStrategy>());
tree = parserInterp.parse(patternRuleIndex);
} catch (ParseCancellationException &e) {
#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026
// rethrow_if_nested is not available before VS 2015.
throw e;
#else
std::rethrow_if_nested(e); // Unwrap the nested exception.
#endif
} catch (RecognitionException &re) {
throw re;
#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026
} catch (std::exception &e) {
// throw_with_nested is not available before VS 2015.
throw e;
#else
} catch (std::exception & /*e*/) {
std::nested_exception exc;
std::throw_with_nested(exc); // Wrap any other exception. We should however probably use one of the ANTLR exceptions here.
#endif
}
// Make sure tree pattern compilation checks for a complete parse
if (tokens.LA(1) != Token::EOF) {
throw StartRuleDoesNotConsumeFullPattern();
}
return ParseTreePattern(this, pattern, patternRuleIndex, tree);
}
Lexer* ParseTreePatternMatcher::getLexer() {
return _lexer;
}
Parser* ParseTreePatternMatcher::getParser() {
return _parser;
}
ParseTree* ParseTreePatternMatcher::matchImpl(ParseTree *tree, ParseTree *patternTree,
std::map<std::string, std::vector<ParseTree *>> &labels) {
if (tree == nullptr) {
throw IllegalArgumentException("tree cannot be nul");
}
if (patternTree == nullptr) {
throw IllegalArgumentException("patternTree cannot be nul");
}
// x and <ID>, x and y, or x and x; or could be mismatched types
if (is<TerminalNode *>(tree) && is<TerminalNode *>(patternTree)) {
TerminalNode *t1 = dynamic_cast<TerminalNode *>(tree);
TerminalNode *t2 = dynamic_cast<TerminalNode *>(patternTree);
ParseTree *mismatchedNode = nullptr;
// both are tokens and they have same type
if (t1->getSymbol()->getType() == t2->getSymbol()->getType()) {
if (is<TokenTagToken *>(t2->getSymbol())) { // x and <ID>
TokenTagToken *tokenTagToken = dynamic_cast<TokenTagToken *>(t2->getSymbol());
// track label->list-of-nodes for both token name and label (if any)
labels[tokenTagToken->getTokenName()].push_back(tree);
if (tokenTagToken->getLabel() != "") {
labels[tokenTagToken->getLabel()].push_back(tree);
}
} else if (t1->getText() == t2->getText()) {
// x and x
} else {
// x and y
if (mismatchedNode == nullptr) {
mismatchedNode = t1;
}
}
} else {
if (mismatchedNode == nullptr) {
mismatchedNode = t1;
}
}
return mismatchedNode;
}
if (is<ParserRuleContext *>(tree) && is<ParserRuleContext *>(patternTree)) {
ParserRuleContext *r1 = dynamic_cast<ParserRuleContext *>(tree);
ParserRuleContext *r2 = dynamic_cast<ParserRuleContext *>(patternTree);
ParseTree *mismatchedNode = nullptr;
// (expr ...) and <expr>
RuleTagToken *ruleTagToken = getRuleTagToken(r2);
if (ruleTagToken != nullptr) {
//ParseTreeMatch *m = nullptr; // unused?
if (r1->getRuleIndex() == r2->getRuleIndex()) {
// track label->list-of-nodes for both rule name and label (if any)
labels[ruleTagToken->getRuleName()].push_back(tree);
if (ruleTagToken->getLabel() != "") {
labels[ruleTagToken->getLabel()].push_back(tree);
}
} else {
if (!mismatchedNode) {
mismatchedNode = r1;
}
}
return mismatchedNode;
}
// (expr ...) and (expr ...)
if (r1->children.size() != r2->children.size()) {
if (mismatchedNode == nullptr) {
mismatchedNode = r1;
}
return mismatchedNode;
}
std::size_t n = r1->children.size();
for (size_t i = 0; i < n; i++) {
ParseTree *childMatch = matchImpl(r1->children[i], patternTree->children[i], labels);
if (childMatch) {
return childMatch;
}
}
return mismatchedNode;
}
// if nodes aren't both tokens or both rule nodes, can't match
return tree;
}
RuleTagToken* ParseTreePatternMatcher::getRuleTagToken(ParseTree *t) {
if (t->children.size() == 1 && is<TerminalNode *>(t->children[0])) {
TerminalNode *c = dynamic_cast<TerminalNode *>(t->children[0]);
if (is<RuleTagToken *>(c->getSymbol())) {
return dynamic_cast<RuleTagToken *>(c->getSymbol());
}
}
return nullptr;
}
std::vector<std::unique_ptr<Token>> ParseTreePatternMatcher::tokenize(const std::string &pattern) {
// split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)
std::vector<Chunk> chunks = split(pattern);
// create token stream from text and tags
std::vector<std::unique_ptr<Token>> tokens;
for (auto chunk : chunks) {
if (is<TagChunk *>(&chunk)) {
TagChunk &tagChunk = (TagChunk&)chunk;
// add special rule token or conjure up new token from name
if (isupper(tagChunk.getTag()[0])) {
size_t ttype = _parser->getTokenType(tagChunk.getTag());
if (ttype == Token::INVALID_TYPE) {
throw IllegalArgumentException("Unknown token " + tagChunk.getTag() + " in pattern: " + pattern);
}
tokens.emplace_back(new TokenTagToken(tagChunk.getTag(), (int)ttype, tagChunk.getLabel()));
} else if (islower(tagChunk.getTag()[0])) {
size_t ruleIndex = _parser->getRuleIndex(tagChunk.getTag());
if (ruleIndex == INVALID_INDEX) {
throw IllegalArgumentException("Unknown rule " + tagChunk.getTag() + " in pattern: " + pattern);
}
size_t ruleImaginaryTokenType = _parser->getATNWithBypassAlts().ruleToTokenType[ruleIndex];
tokens.emplace_back(new RuleTagToken(tagChunk.getTag(), ruleImaginaryTokenType, tagChunk.getLabel()));
} else {
throw IllegalArgumentException("invalid tag: " + tagChunk.getTag() + " in pattern: " + pattern);
}
} else {
TextChunk &textChunk = (TextChunk&)chunk;
ANTLRInputStream input(textChunk.getText());
_lexer->setInputStream(&input);
std::unique_ptr<Token> t(_lexer->nextToken());
while (t->getType() != Token::EOF) {
tokens.push_back(std::move(t));
t = _lexer->nextToken();
}
_lexer->setInputStream(nullptr);
}
}
return tokens;
}
std::vector<Chunk> ParseTreePatternMatcher::split(const std::string &pattern) {
size_t p = 0;
size_t n = pattern.length();
std::vector<Chunk> chunks;
// find all start and stop indexes first, then collect
std::vector<size_t> starts;
std::vector<size_t> stops;
while (p < n) {
if (p == pattern.find(_escape + _start,p)) {
p += _escape.length() + _start.length();
} else if (p == pattern.find(_escape + _stop,p)) {
p += _escape.length() + _stop.length();
} else if (p == pattern.find(_start,p)) {
starts.push_back(p);
p += _start.length();
} else if (p == pattern.find(_stop,p)) {
stops.push_back(p);
p += _stop.length();
} else {
p++;
}
}
if (starts.size() > stops.size()) {
throw IllegalArgumentException("unterminated tag in pattern: " + pattern);
}
if (starts.size() < stops.size()) {
throw IllegalArgumentException("missing start tag in pattern: " + pattern);
}
size_t ntags = starts.size();
for (size_t i = 0; i < ntags; i++) {
if (starts[i] >= stops[i]) {
throw IllegalArgumentException("tag delimiters out of order in pattern: " + pattern);
}
}
// collect into chunks now
if (ntags == 0) {
std::string text = pattern.substr(0, n);
chunks.push_back(TextChunk(text));
}
if (ntags > 0 && starts[0] > 0) { // copy text up to first tag into chunks
std::string text = pattern.substr(0, starts[0]);
chunks.push_back(TextChunk(text));
}
for (size_t i = 0; i < ntags; i++) {
// copy inside of <tag>
std::string tag = pattern.substr(starts[i] + _start.length(), stops[i] - (starts[i] + _start.length()));
std::string ruleOrToken = tag;
std::string label = "";
size_t colon = tag.find(':');
if (colon != std::string::npos) {
label = tag.substr(0,colon);
ruleOrToken = tag.substr(colon + 1, tag.length() - (colon + 1));
}
chunks.push_back(TagChunk(label, ruleOrToken));
if (i + 1 < ntags) {
// copy from end of <tag> to start of next
std::string text = pattern.substr(stops[i] + _stop.length(), starts[i + 1] - (stops[i] + _stop.length()));
chunks.push_back(TextChunk(text));
}
}
if (ntags > 0) {
size_t afterLastTag = stops[ntags - 1] + _stop.length();
if (afterLastTag < n) { // copy text from end of last tag to end
std::string text = pattern.substr(afterLastTag, n - afterLastTag);
chunks.push_back(TextChunk(text));
}
}
// strip out all backslashes from text chunks but not tags
for (size_t i = 0; i < chunks.size(); i++) {
Chunk &c = chunks[i];
if (is<TextChunk *>(&c)) {
TextChunk &tc = (TextChunk&)c;
std::string unescaped = tc.getText();
unescaped.erase(std::remove(unescaped.begin(), unescaped.end(), '\\'), unescaped.end());
if (unescaped.length() < tc.getText().length()) {
chunks[i] = TextChunk(unescaped);
}
}
}
return chunks;
}
void ParseTreePatternMatcher::InitializeInstanceFields() {
_start = "<";
_stop = ">";
_escape = "\\";
}
| [
"[email protected]"
] | |
a0e05d3fb31c57aa8587f7636df3c969789d3fe9 | 3f8f433d15411ddf586fd3dae8b7ed1036cb2ff5 | /Classes/Hero/liyuanba.h | c573ec6a89d2ab66947004bda6fb1f42fc7b8982 | [] | no_license | jj918160/dame-01 | 80d2c6028647f3d5f6beff4792c08f5f9147f25b | 8bef9e56d267cbb6894862b6b605e4024e803598 | refs/heads/master | 2021-01-10T09:10:29.346792 | 2015-09-23T12:30:05 | 2015-09-23T12:30:05 | 42,991,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | h | //
// liyuanba.h
// animate_homework
//
// Created by mac on 15-8-5.
//
//
#ifndef __animate_homework__liyuanba__
#define __animate_homework__liyuanba__
#include <stdio.h>
#include "zhaoyun.h"
class liyuanba:public zhaoyun{
public:
CREATE_FUNC(liyuanba);
virtual bool init();
virtual void loading_animation();
virtual void update(float dt);
virtual void attack_update(float dt);
virtual void level_up();//升级调用,主要控制成长
};
#endif /* defined(__animate_homework__liyuanba__) */
| [
"[email protected]"
] | |
49923ab513a39156e15a824531255dcf2459d590 | fbbbc190890e1658effdf406618574bdd84b21e3 | /Solutions/Set6_The_Death_Eaters.cpp | e925088152c82926c2bb94372a19bf0ceef0d3fc | [] | no_license | acm-svnit/Summer_challenge2021 | c869b54b83c03d5fdb4c2a4a7053a9e892a3d61c | d6701821746306057176e36a05b7819cb54322e6 | refs/heads/master | 2023-05-31T13:49:39.550137 | 2021-07-01T04:11:04 | 2021-07-01T04:11:04 | 381,662,987 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 920 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
typedef pair<int,int> pp;
const int N=2e5+7;
void solve(){
int n;
cin>>n;
int a[n];
queue<int> q;
for(int i=0;i<n;i++){
cin>>a[i];
q.push(a[i]);
}
queue<int> pq;
int ans=0;
while(n>1){
bool flag=0;
int last=-1;
while(q.size()){
if(q.front()<last){
flag=1;
}
else pq.push(q.front());
last=q.front();
q.pop();
}
while(pq.size()) q.push(pq.front()),pq.pop();
if(!flag) break;
ans++;
}
cout<<ans<<"\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t=1;
while(t--)
solve();
return 0;
}
| [
"[email protected]"
] | |
89b8e27f9ae9a2e72f0943d1c0a7bfe2722b6520 | 35b00918620e6ca14410afc33ba61b72ec96b63a | /include/const_array_impl.hpp | 3aec34c65c058590f066ca92869378cfb3666c4e | [
"MIT"
] | permissive | mirandaconrado/multidimensional-array | 88dd95e39c61ac2fca60c2c8a0aeb628f78e6153 | 8f570806ead01937cfdf9726e3389478ee3803da | refs/heads/master | 2021-01-10T21:43:06.575002 | 2014-10-29T11:19:07 | 2014-10-29T11:19:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,562 | hpp | #ifndef __MULTIDIMENSIONAL_ARRAY__CONST_ARRAY_IMPL_HPP__
#define __MULTIDIMENSIONAL_ARRAY__CONST_ARRAY_IMPL_HPP__
#include "const_array.hpp"
namespace MultidimensionalArray {
template <class T>
ConstArray<T>::ConstArray():
values_(nullptr),
deallocate_on_destruction_(false) { }
template <class T>
ConstArray<T>::ConstArray(ConstArray const& other):
size_(other.size_),
values_(other.values_),
deallocate_on_destruction_(false) { }
template <class T>
ConstArray<T>::ConstArray(ConstArray&& other):
size_(std::move(other.size_)),
values_(std::move(other.values_)),
deallocate_on_destruction_(std::move(other.deallocate_on_destruction_)) {
other.values_ = nullptr;
}
template <class T>
ConstArray<T>::ConstArray(Array<T> const& other):
size_(other.size_),
values_(other.values_),
deallocate_on_destruction_(false) { }
template <class T>
ConstArray<T>::ConstArray(Array<T>&& other):
size_(std::move(other.size_)),
values_(std::move(other.values_)),
deallocate_on_destruction_(std::move(other.deallocate_on_destruction_)) {
other.values_ = nullptr;
}
template <class T>
ConstArray<T>::ConstArray(Size const& size):
ConstArray() {
size_ = size;
}
template <class T>
ConstArray<T>::ConstArray(Size const& size, T const* ptr,
bool responsible_for_deleting):
ConstArray(size) {
values_ = ptr;
deallocate_on_destruction_ = responsible_for_deleting;
}
template <class T>
ConstArray<T>::~ConstArray() {
cleanup();
}
template <class T>
void ConstArray<T>::swap(ConstArray& other) {
Size temp1 = std::move(other.size_);
other.size_ = size_;
size_ = std::move(temp1);
T const* temp2 = other.values_;
other.values_ = values_;
values_ = temp2;
bool temp3 = other.deallocate_on_destruction_;
other.deallocate_on_destruction_ = deallocate_on_destruction_;
deallocate_on_destruction_ = temp3;
}
template <class T>
void ConstArray<T>::swap(ConstArray&& other) {
Size temp1 = std::move(other.size_);
other.size_ = size_;
size_ = std::move(temp1);
T const* temp2 = other.values_;
other.values_ = values_;
values_ = temp2;
bool temp3 = other.deallocate_on_destruction_;
other.deallocate_on_destruction_ = deallocate_on_destruction_;
deallocate_on_destruction_ = temp3;
}
template <class T>
ConstView<T> ConstArray<T>::view() {
return ConstView<T>(*this);
}
template <class T>
bool ConstArray<T>::resize(Size const& size) {
if (size.total_size() != total_size())
return false;
size_ = size;
return true;
}
template <class T>
void ConstArray<T>::set_pointer(T const* ptr, bool responsible_for_deleting) {
if (values_ != nullptr && deallocate_on_destruction_) {
delete[] values_;
values_ = nullptr;
}
values_ = ptr;
deallocate_on_destruction_ = responsible_for_deleting;
}
template <class T>
template <class... Args>
T const& ConstArray<T>::operator()(Args const&... args) const {
assert(values_ != nullptr);
return values_[size_.get_position_variadic(args...)];
}
template <class T>
T const& ConstArray<T>::get(Size::SizeType const& index) const {
assert(values_ != nullptr);
return values_[size_.get_position(index)];
}
template <class T>
void ConstArray<T>::cleanup() {
if (values_ != nullptr && deallocate_on_destruction_) {
delete[] values_;
values_ = nullptr;
}
size_ = Size();
}
};
#endif
| [
"[email protected]"
] | |
c618ed0b1b92b3382cb7cf64bca5f8a4d623c8a0 | 8fc3cf44ec1e7fcb0282faa4568f11a09736f7de | /cusparse/rwr/LightSpMV/PageRankCuda-v1.0.1/cusp/graph/detail/maximal_independent_set.inl | da21ad7178967033059e26e46af68cdfc67e11e4 | [] | no_license | hisashi-ito/cuda | 362ec1416ec4e69235cc577de397ded67c62b55b | d63e6c354d1f45df6cb919fc7817d8d72a73d0ae | refs/heads/master | 2021-04-12T04:46:14.381290 | 2018-10-14T10:30:20 | 2018-10-14T10:30:20 | 126,021,847 | 0 | 0 | null | 2018-05-17T08:31:03 | 2018-03-20T13:28:47 | C++ | UTF-8 | C++ | false | false | 3,559 | inl | /*
* Copyright 2008-2014 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.
*/
#include <cusp/exception.h>
#include <cusp/coo_matrix.h>
#include <cusp/csr_matrix.h>
#include <cusp/graph/detail/dispatch/maximal_independent_set.h>
#include <thrust/fill.h>
namespace cusp
{
namespace graph
{
namespace detail
{
//////////////////
// General Path //
//////////////////
template <typename Matrix, typename Array>
size_t maximal_independent_set(const Matrix& A, Array& stencil, size_t k,
cusp::coo_format, cusp::device_memory)
{
typedef typename Matrix::index_type IndexType;
typedef typename Matrix::value_type ValueType;
return cusp::graph::detail::dispatch::maximal_independent_set(A, stencil, k, typename Matrix::memory_space());
}
template <typename Matrix, typename Array,
typename Format>
size_t maximal_independent_set(const Matrix& A, Array& stencil, size_t k,
Format, cusp::device_memory)
{
typedef typename Matrix::index_type IndexType;
typedef typename Matrix::value_type ValueType;
// convert matrix to COO format and compute on the device
cusp::coo_matrix<IndexType,ValueType,cusp::device_memory> A_coo(A);
return cusp::graph::detail::dispatch::maximal_independent_set(A_coo, stencil, k, typename Matrix::memory_space());
}
template <typename Matrix, typename Array>
size_t maximal_independent_set(const Matrix& A, Array& stencil, size_t k,
cusp::csr_format, cusp::host_memory)
{
typedef typename Matrix::index_type IndexType;
typedef typename Matrix::value_type ValueType;
return cusp::graph::detail::dispatch::maximal_independent_set(A, stencil, k, typename Matrix::memory_space());
}
template <typename Matrix, typename Array,
typename Format>
size_t maximal_independent_set(const Matrix& A, Array& stencil, size_t k,
Format, cusp::host_memory)
{
typedef typename Matrix::index_type IndexType;
typedef typename Matrix::value_type ValueType;
// convert matrix to CSR format and compute on the host
cusp::csr_matrix<IndexType,ValueType,cusp::host_memory> A_csr(A);
return cusp::graph::detail::dispatch::maximal_independent_set(A_csr, stencil, k, typename Matrix::memory_space());
}
} // end namespace detail
/////////////////
// Entry Point //
/////////////////
template <typename Matrix, typename Array>
size_t maximal_independent_set(const Matrix& A, Array& stencil, size_t k)
{
CUSP_PROFILE_SCOPED();
if(A.num_rows != A.num_cols)
throw cusp::invalid_input_exception("matrix must be square");
if (k == 0)
{
stencil.resize(A.num_rows);
thrust::fill(stencil.begin(), stencil.end(), typename Array::value_type(1));
return stencil.size();
}
else
{
return cusp::graph::detail::maximal_independent_set(A, stencil, k, typename Matrix::format(), typename Matrix::memory_space());
}
}
} // end namespace graph
} // end namespace cusp
| [
"[email protected]"
] | |
36bebd934e2f01efa0c1bf2ea9ed3f3148e9a1a2 | 0863f22aaf519dafa168cfb67033fa9b9e5066a6 | /structure.cpp | 085e877865368a6b637f28185070381253e30aa0 | [] | no_license | anirudhasj441/CPP-Programing | 3f132a755f91a51f42d98aaa6850eca7c16ba703 | 6d99836161f8594aa6baf96c75f6330aa3547805 | refs/heads/master | 2020-09-14T15:54:15.456236 | 2019-11-21T13:02:01 | 2019-11-21T13:02:01 | 223,175,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | cpp | #include<iostream>
using namespace std;
struct employee{
private:
int id;
string name;
float salary;
public:
void input(int id,string name,float salary){
this->id = id;
this->name = name;
this->salary = salary;
}
void display(){
cout<<"\nid:"<<id<<"\nname:"<<name<<"\nsalary:"<<salary;
}
};
int main(){
// employee anirudha = {1,"Anirudha",15000};
// employee sushil;
// sushil.id = 2;
// sushil.name = "Sushil";
// sushil.salary = 20000;
int id;string name;float salary;
cout<<"id = ";
cin>>id;
cout<<"name = ";
cin>>name;
cout<<"salary = ";
cin>>salary;
employee vinay;
vinay.input(id,name,salary);
vinay.display();
} | [
"[email protected]"
] | |
3606ef9d365f149bab12095634b1405d6e43fe15 | 4714fe324a0e2fc3be490395054e83eb27bd8090 | /tests/profile.cpp | 0debdb22e5c1832d9f2a71607767f3c7c8cd607c | [
"MIT"
] | permissive | CLPopescu-1999-02/lfpAlloc | 996e49c22811e07bdf3a829a06392e594b753beb | f911baa7f621b8a792e06c16c1ffed07334571fc | refs/heads/master | 2020-03-31T04:32:47.100635 | 2015-03-21T06:53:30 | 2015-03-21T06:53:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,671 | cpp |
#include <lfpAlloc/Allocator.hpp>
#include <list>
#include <algorithm>
#include <chrono>
#include <iostream>
using lfpAlloc::lfpAllocator;
namespace utils {
template <typename Func>
void multiRun(Func fun, int thread_count) {
std::vector<std::thread> threads;
for (int i = 0; i < thread_count; ++i) {
threads.emplace_back(fun);
}
for (auto& thread : threads) {
thread.join();
}
}
template <typename T>
std::chrono::milliseconds asMS(const T& time) {
return std::chrono::duration_cast<std::chrono::milliseconds>(time);
}
template <typename Func, typename... Ts>
std::chrono::milliseconds timeCall(Func func, Ts&&... args) {
auto start = std::chrono::system_clock::now();
func(args...);
auto end = std::chrono::system_clock::now();
return asMS(end - start);
}
std::size_t random_uint(std::size_t lower, std::size_t upper) {
static std::default_random_engine e{};
std::uniform_int_distribution<std::size_t> d{lower, upper - 1};
return d(e);
}
} // End utils
template <typename T>
void addRemovePredicatableBody(T& list, int size = 4e5) {
for (int s = 0; s < size; ++s) {
list.push_back(s);
}
int count = 0;
for (auto iter = list.begin(); iter != list.end(); ++iter, ++count) {
if (count % 3 == 0) {
iter = list.erase(iter);
}
}
}
template <typename T>
void addRemoveRandomBody(T& list, int size = 4e3) {
for (int s = 0; s < size; ++s) {
list.push_back(s);
}
while (list.size() > static_cast<std::size_t>(size / 2)) {
auto pos = list.begin();
std::advance(pos, utils::random_uint(0, list.size()));
list.erase(pos);
}
}
void lfpAddRemovePredicatable(int thread_count) {
std::vector<std::thread> threads;
lfpAllocator<int> alloc;
auto fun = [&alloc] {
std::list<int, lfpAllocator<int>> list(alloc);
addRemovePredicatableBody(list);
};
utils::multiRun(fun, thread_count);
}
void stdAddRemovePredictable(int thread_count) {
auto fun = [] {
std::list<int> list;
addRemovePredicatableBody(list);
};
utils::multiRun(fun, thread_count);
}
void lfpAddRemoveRandom(int thread_count) {
std::vector<std::thread> threads;
lfpAllocator<int> alloc;
auto fun = [&alloc] {
std::list<int, lfpAllocator<int>> list(alloc);
addRemoveRandomBody(list);
};
utils::multiRun(fun, thread_count);
}
void stdAddRemoveRandom(int thread_count) {
auto fun = [] {
std::list<int> list;
addRemoveRandomBody(list);
};
utils::multiRun(fun, thread_count);
}
int main() {
std::chrono::milliseconds time;
std::cout << "Profile - Add/Remove Random" << std::endl;
for (int i = 1; i <= 32; i <<= 1) {
std::cout << " Using " << i << " threads " << std::endl;
time = utils::timeCall(lfpAddRemoveRandom, i);
std::cout << " LFP Allocator time (ms): " << time.count()
<< std::endl;
time = utils::timeCall(stdAddRemoveRandom, i);
std::cout << " std Allocator time (ms): " << time.count()
<< std::endl;
}
std::cout << "Profile - Add/Remove Predictable" << std::endl;
for (int i = 1; i <= 32; i <<= 1) {
std::cout << " Using " << i << " threads " << std::endl;
time = utils::timeCall(lfpAddRemovePredicatable, i);
std::cout << " LFP Allocator time (ms): " << time.count()
<< std::endl;
time = utils::timeCall(stdAddRemovePredictable, i);
std::cout << " std Allocator time (ms): " << time.count()
<< std::endl;
}
}
| [
"[email protected]"
] | |
2fddaa517e6c9e21ae99fd446f1c68da2fc4aea2 | 68378ddb7462a2c0cf07a7e5b0783227bfaea324 | /server-code/src/service/ai_service/message_handle/AIMessageHandle.cpp | 1363b5b634c2d16e072d05ef3a5b7ef16c78c57d | [] | no_license | blockspacer/mmo-server | 7e973a9509230025373c196b3b3d0a6ca078fec4 | 9b170f9e9307ee8c2b6d191d99f7e2c35a84626c | refs/heads/master | 2022-12-07T04:18:20.870326 | 2020-08-28T02:44:05 | 2020-08-28T02:44:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,562 | cpp | #include "AIActor.h"
#include "AIActorManager.h"
#include "AIMessageHandler.h"
#include "AIMonster.h"
#include "AIPhase.h"
#include "AIPlayer.h"
#include "AIScene.h"
#include "AISceneManagr.h"
#include "AIService.h"
#include "NetMSGProcess.h"
#include "msg/world_service.pb.h"
#include "msg/zone_service.pb.h"
#include "server_msg/server_side.pb.h"
ON_MSG(CAIService, SC_AOI_NEW) {}
ON_MSG(CAIService, SC_AOI_REMOVE) {}
ON_MSG(CAIService, SC_AOI_UPDATE)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK_FMT(pActor, "actorid:{}", msg.actor_id());
CHECK(pActor->GetCurrentScene());
CHECK(pActor->GetCurrentScene()->GetMapID() == msg.mapid());
pActor->SetPos(Vector2(msg.posx(), msg.posy()));
pActor->UpdateViewList();
LOGAIDEBUG(true, pActor->GetID(),
"Actor:{} MoveTo {} {:.2f}, {:.2f}",
pActor->GetID(),
pActor->GetCurrentScene()->GetMapID(),
pActor->GetPosX(),
pActor->GetPosY());
__LEAVE_FUNCTION
}
ON_MSG(CAIService, SC_ATTRIB_CHANGE)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
for(int32_t i = 0; i < msg.datalist_size(); i++)
{
const auto& data = msg.datalist(i);
pActor->SetProperty(data.actype(), data.val());
}
__LEAVE_FUNCTION
}
ON_MSG(CAIService, SC_CASTSKILL)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
pActor->OnCastSkill(msg.skill_id());
__LEAVE_FUNCTION
}
ON_MSG(CAIService, SC_SKILL_STUN)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
pActor->OnCastSkillFinish(msg.stun_ms());
__LEAVE_FUNCTION
}
ON_MSG(CAIService, SC_SKILL_BREAK)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
pActor->OnCastSkillFinish(0);
__LEAVE_FUNCTION
}
ON_MSG(CAIService, SC_DAMAGE)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
pActor->OnUnderAttack(msg.attacker_id(), msg.damage());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, SceneCreate)
{
__ENTER_FUNCTION
AISceneManager()->CreateScene(msg.scene_id());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, PhaseCreate)
{
__ENTER_FUNCTION
CAIScene* pScene = AISceneManager()->QueryScene(msg.scene_id());
CHECK(pScene);
pScene->CreatePhase(msg.scene_id(), msg.phase_id());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, PhaseDestory)
{
__ENTER_FUNCTION
CAIScene* pScene = AISceneManager()->QueryScene(msg.scene_id());
CHECK(pScene);
pScene->DestoryPhase(msg.phase_id());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, ActiveGen)
{
__ENTER_FUNCTION
CAIPhase* pScene = AISceneManager()->QueryPhase(msg.scene_id());
CHECK(pScene);
pScene->GetMonsterGen().ActiveGen(msg.gen_id(), msg.active());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, MonsterGenOnce)
{
__ENTER_FUNCTION
CAIPhase* pScene = AISceneManager()->QueryPhase(msg.scene_id());
CHECK(pScene);
pScene->GetMonsterGen().GenOnce(msg.gen_id(), msg.phase_id());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, KillGen)
{
__ENTER_FUNCTION
CAIPhase* pScene = AISceneManager()->QueryPhase(msg.scene_id());
CHECK(pScene);
pScene->GetMonsterGen().KillGen(msg.gen_id());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, ActorCreate)
{
__ENTER_FUNCTION
CAIPhase* pScene = AISceneManager()->QueryPhase(msg.scene_id());
CHECK(pScene);
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());;
CHECK(pActor == nullptr);
switch(msg.actortype())
{
case ACT_MONSTER:
{
pActor = CAIMonster::CreateNew(msg);
}
break;
case ACT_PLAYER:
{
pActor = CAIPlayer::CreateNew(msg);
LOGDEBUG("Create AIPlayer id:{} ptr:{:p}", pActor->GetID(), (void*)pActor);
}
break;
case ACT_PET:
{
}
break;
case ACT_NPC:
{
}
break;
}
if(pActor)
{
pScene->EnterMap(pActor, msg.posx(), msg.posy(), msg.face());
AIActorManager()->AddActor(pActor);
pActor->OnBorn();
}
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, ActorDestory)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
LOGDEBUG("ActorDestory id:{} ptr:{:p}", pActor->GetID(), (void*)pActor);
if(msg.dead())
{
pActor->OnDead();
}
if(pActor->GetCurrentScene())
pActor->GetCurrentScene()->LeaveMap(pActor);
AIActorManager()->DelActor(pActor);
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, ActorCastSkill_Fail)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
pActor->OnCastSkillFinish();
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, ActorSetHide)
{
__ENTER_FUNCTION
CAIActor* pActor = AIActorManager()->QueryActor(msg.actor_id());
CHECK(pActor);
pActor->SetHideCoude(msg.hide_count());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, SyncTaskPhase)
{
__ENTER_FUNCTION
auto pActor = AIActorManager()->QueryActor(msg.player_id());
CHECK(pActor);
CAIPlayer* pPlayer = pActor->CastTo<CAIPlayer>();
CHECK(pPlayer);
pPlayer->ClearTaskPhase();
for(int32_t i = 0; i < msg.task_phase_id_size(); i++)
{
pPlayer->AddTaskPhase(msg.task_phase_id(i));
}
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, AddTaskPhase)
{
__ENTER_FUNCTION
auto pActor = AIActorManager()->QueryActor(msg.player_id());
CHECK(pActor);
CAIPlayer* pPlayer = pActor->CastTo<CAIPlayer>();
CHECK(pPlayer);
pPlayer->AddTaskPhase(msg.task_phase_id());
__LEAVE_FUNCTION
}
ON_SERVERMSG(CAIService, RemoveTaskPhase)
{
__ENTER_FUNCTION
auto pActor = AIActorManager()->QueryActor(msg.player_id());
CHECK(pActor);
CAIPlayer* pPlayer = pActor->CastTo<CAIPlayer>();
CHECK(pPlayer);
pPlayer->RemoveTaskPhase(msg.task_phase_id());
__LEAVE_FUNCTION
}
void AIServiceMessageHandlerRegister()
{
auto pNetMsgProcess = AIService()->GetNetMsgProcess();
for(const auto& [k, v]: MsgProcRegCenter<CAIService>::instance().m_MsgProc)
{
pNetMsgProcess->Register(k, std::get<0>(v), std::get<1>(v));
}
}
| [
"[email protected]"
] | |
b9fd8ce7cfc282d2784bf7d5dbc1be181c52566e | 7a14bd4b3b0c406bb46fa82fb208a09de85f6cc2 | /tools/src_old/ReadSim2.h | 8f0485c8edac76c2ae3b3ac15a991124ad4c1f18 | [] | no_license | jhwang7628/TurbulentHead | e7d6fb0788c6d9750edd94e79de5615e83fc67e8 | ecbcb987e318c3809056e6df2296170476c8cb1e | refs/heads/master | 2021-01-16T18:31:43.341197 | 2014-11-27T16:18:01 | 2014-11-27T16:18:01 | 24,374,813 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | h | #ifndef READSIM2_H
#define READSIM2_H
#include "Vector3.h"
#include <vector>
#include <string>
#include <iostream>
#include "ReadSim.h"
void ReadSim2(std::vector<vertexData> & data);
#endif
| [
"[email protected]"
] | |
3153855aee6f27ef94238f3ed41a9fb3a12266c8 | cda9509f551346a07ba311237cd0110e4e369d89 | /Sphere.cpp | 09b3bb0136abb8b1f97c8a1d65fb928d75013b0a | [] | no_license | Ailsa98/Amusement_Park_Ride | 8cc0cb732d623458bad4cabe66aa197b71e6b1c6 | c10a1e8270ed2cceeb05b6341cae30e3a30bd89e | refs/heads/master | 2023-07-13T06:08:18.616808 | 2021-08-23T20:36:53 | 2021-08-23T20:36:53 | 399,240,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,339 | cpp | #include <iostream>
#include <fstream>
#include <map>
#include <tuple>
#include <numeric>
#ifndef GL_PRIMITIVE_RESTART_FIXED_INDEX
#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0xFFFFFF
#endif
#include "Sphere.h"
Sphere::Sphere(){
int i, j;
std::vector<GLfloat> vertices;
std::vector<GLuint> indices;
std::vector<GLfloat> normals;
int indicator = 0;
for (i = 0; i <= stackCount; i++) {
double lat0 = glm::pi<double>() * (-0.5 + (double)(i - 1) / stackCount);
double z0 = sin(lat0);
double zr0 = cos(lat0);
double lat1 = glm::pi<double>() * (-0.5 + (double)i / stackCount);
double z1 = sin(lat1);
double zr1 = cos(lat1);
for (j = 0; j <= sectorCount; j++) {
double lng = 2 * glm::pi<double>() * (double)(j - 1) / sectorCount;
double lng1 = 2 * glm::pi<double>() * (double)(j) / sectorCount;
double x1 = cos(lng1);
double y1 = sin(lng1);
double x = cos(lng);
double y = sin(lng);
vertices.push_back(x * zr1);
vertices.push_back(y * zr1);
vertices.push_back(z1);
indices.push_back(indicator);
indicator++;
vertices.push_back(x * zr0);
vertices.push_back(y * zr0);
vertices.push_back(z0);
indices.push_back(indicator);
indicator++;
vertices.push_back(x1 * zr0);
vertices.push_back(y1 * zr0);
vertices.push_back(z0);
indices.push_back(indicator);
indicator++;
vertices.push_back(x1 * zr0);
vertices.push_back(y1 * zr0);
vertices.push_back(z0);
indices.push_back(indicator);
indicator++;
vertices.push_back(x1 * zr1);
vertices.push_back(y1 * zr1);
vertices.push_back(z1);
indices.push_back(indicator);
indicator++;
vertices.push_back(x * zr1);
vertices.push_back(y * zr1);
vertices.push_back(z1);
indices.push_back(indicator);
indicator++;
float x_avg = ((x * zr1) + (x * zr0) + (x1 * zr0) + (x1 * zr1));
float y_avg = ((y * zr1) + (y * zr0) + (y1 * zr0) + (y1 * zr1));
float z_avg = (2 * z0 + 2 * z1);
glm::vec3 avg = glm::normalize(glm::vec3(x_avg, y_avg, z_avg));
normals.push_back(avg.x);
normals.push_back(avg.y);
normals.push_back(avg.z);
normals.push_back(avg.x);
normals.push_back(avg.y);
normals.push_back(avg.z);
normals.push_back(avg.x);
normals.push_back(avg.y);
normals.push_back(avg.z);
normals.push_back(avg.x);
normals.push_back(avg.y);
normals.push_back(avg.z);
normals.push_back(avg.x);
normals.push_back(avg.y);
normals.push_back(avg.z);
normals.push_back(avg.x);
normals.push_back(avg.y);
normals.push_back(avg.z);
}
indices.push_back(GL_PRIMITIVE_RESTART_FIXED_INDEX);
}
model = glm::mat4(1);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO1);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GLfloat), &vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
glGenBuffers(1, &VBO2);
glBindBuffer(GL_ARRAY_BUFFER, VBO2);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(GLfloat), &normals[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
numsToDraw = indices.size();
}
Sphere::~Sphere() {
// Delete the VBO, VAO and EBO.
glDeleteBuffers(1, &VBO1);
glDeleteBuffers(1, &VBO2);
glDeleteBuffers(1, &EBO);
glDeleteVertexArrays(1, &VAO);
}
void Sphere::draw(const GLuint shader, glm::mat4 C) {
newModel = C * model;
glUseProgram(refShader);
glUniform1i(glGetUniformLocation(refShader, "Skybox"), 0);
glUniformMatrix4fv(glGetUniformLocation(refShader, "model"), 1, GL_FALSE, glm::value_ptr(newModel));
//glDisable(GL_CULL_FACE);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glBindVertexArray(VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glPatchParameteri(GL_PATCH_VERTICES, 4);
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(GL_PRIMITIVE_RESTART_FIXED_INDEX);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glDrawElements(GL_TRIANGLES, numsToDraw, GL_UNSIGNED_INT, NULL);
//glDisable(GL_CULL_FACE);
glUseProgram(0);
glBindVertexArray(0);
}
void Sphere::spin(float deg) {
// Update the model matrix by multiplying a rotation matrix
model = glm::rotate(glm::radians(deg), glm::vec3(0.0f, 1.0f, 0.0f)) * model;
}
| [
"[email protected]"
] | |
9a17935df70db339566bab6a721f55ad3ec95fa2 | e9ba632ed099dc670a87273af5ce513de6744030 | /EngineProject/src/Engine/Material.cpp | 9ebba72168cb646f5b6b7de0448727e0c219323e | [] | no_license | doddzy39/OpenGLEngine | 614ba8499b59d0c834a91ec8a84bf9530f2f4c5a | a0141647a8f678e9ad43bcadd933cae997a48958 | refs/heads/master | 2016-09-03T06:39:35.309507 | 2015-05-18T01:22:16 | 2015-05-18T01:22:16 | 30,573,282 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,217 | cpp | #include "Material.h"
#include "gl_core_4_4.h"
#include <GLFW/glfw3.h>
#include <glm/gtc/type_ptr.hpp>
#include "MaterialHandler.h"
void Material::SetAsActiveMaterial()
{
glUseProgram(m_iShaderID);
glUniform4fv(m_iDiffuseShaderLocation, 1, glm::value_ptr(diffuse));
glUniform4fv(m_iAmbientShaderLocation, 1, glm::value_ptr(ambient));
glUniform4fv(m_iSpecularShaderLocation, 1, glm::value_ptr(specular));
glUniform4fv(m_iemissiveShaderLocation, 1, glm::value_ptr(emissive));
//Next we need to bind the correct textures
for(auto it = m_textureMap.begin();it != m_textureMap.end();++it)
{
if(it->second > 0)
{
glActiveTexture(GL_TEXTURE0 + it->first);
if (it->first != CUBE)
{
glBindTexture(GL_TEXTURE_2D, it->second);
}
else
{
glBindTexture(GL_TEXTURE_CUBE_MAP, it->second);
}
}
}
}
void Material::SetShader( unsigned int a_uiShaderID )
{
m_iShaderID = a_uiShaderID;
m_iDiffuseShaderLocation = glGetUniformLocation(m_iShaderID, "diffuseMaterial");
m_iAmbientShaderLocation = glGetUniformLocation(m_iShaderID, "ambientMaterial");
m_iSpecularShaderLocation = glGetUniformLocation(m_iShaderID, "specularMaterial");
m_iemissiveShaderLocation = glGetUniformLocation(m_iShaderID, "emmisiveMaterial");
m_iModelMatrixShaderLocation = glGetUniformLocation(m_iShaderID, "Model");
m_iViewMatrixShaderLocation = glGetUniformLocation(m_iShaderID, "View");
m_iProjectionMatrixShaderLocation = glGetUniformLocation(m_iShaderID, "Projection");
MaterialHandler::Get()->ConfigureOpenGLTextureSlots(m_iShaderID);
}
void Material::SetShaderModelMatrix( glm::mat4& a_rModelMatrix )
{
glUseProgram(m_iShaderID);
glUniformMatrix4fv(m_iModelMatrixShaderLocation, 1, false, glm::value_ptr(a_rModelMatrix));
}
void Material::SetShaderProjectionMatrix( glm::mat4& a_rProjectionMatrix )
{
glUseProgram(m_iShaderID);
glUniformMatrix4fv(m_iProjectionMatrixShaderLocation, 1, false, glm::value_ptr(a_rProjectionMatrix));
}
void Material::SetShaderViewMatrix( glm::mat4& a_rViewMatrix )
{
glUseProgram(m_iShaderID);
glUniformMatrix4fv(m_iViewMatrixShaderLocation, 1, false, glm::value_ptr(a_rViewMatrix));
}
| [
"[email protected]"
] | |
d75158722cbb245bfe647a659579074ef34cebaf | dca653bb975528bd1b8ab2547f6ef4f48e15b7b7 | /tags/wxPy-2.9.0.1/src/common/mimecmn.cpp | 1121e348a7f1fc0623568271a8d409850610fbec | [] | no_license | czxxjtu/wxPython-1 | 51ca2f62ff6c01722e50742d1813f4be378c0517 | 6a7473c258ea4105f44e31d140ea5c0ae6bc46d8 | refs/heads/master | 2021-01-15T12:09:59.328778 | 2015-01-05T20:55:10 | 2015-01-05T20:55:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,808 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: src/common/mimecmn.cpp
// Purpose: classes and functions to manage MIME types
// Author: Vadim Zeitlin
// Modified by:
// Chris Elliott ([email protected]) 5 Dec 00: write support for Win32
// Created: 23.09.98
// RCS-ID: $Id$
// Copyright: (c) 1998 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence (part of wxExtra library)
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_MIMETYPE
#include "wx/mimetype.h"
#ifndef WX_PRECOMP
#include "wx/dynarray.h"
#include "wx/string.h"
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/module.h"
#include "wx/crt.h"
#endif //WX_PRECOMP
#include "wx/file.h"
#include "wx/iconloc.h"
#include "wx/confbase.h"
// other standard headers
#include <ctype.h>
// implementation classes:
#if defined(__WXMSW__)
#include "wx/msw/mimetype.h"
#elif ( defined(__WXMAC__) && wxOSX_USE_CARBON )
#include "wx/osx/mimetype.h"
#elif defined(__WXPM__) || defined (__EMX__)
#include "wx/os2/mimetype.h"
#undef __UNIX__
#elif defined(__DOS__)
#include "wx/msdos/mimetype.h"
#else // Unix
#include "wx/unix/mimetype.h"
#endif
// ============================================================================
// common classes
// ============================================================================
// ----------------------------------------------------------------------------
// wxMimeTypeCommands
// ----------------------------------------------------------------------------
void
wxMimeTypeCommands::AddOrReplaceVerb(const wxString& verb, const wxString& cmd)
{
int n = m_verbs.Index(verb, false /* ignore case */);
if ( n == wxNOT_FOUND )
{
m_verbs.Add(verb);
m_commands.Add(cmd);
}
else
{
m_commands[n] = cmd;
}
}
wxString
wxMimeTypeCommands::GetCommandForVerb(const wxString& verb, size_t *idx) const
{
wxString s;
int n = m_verbs.Index(verb);
if ( n != wxNOT_FOUND )
{
s = m_commands[(size_t)n];
if ( idx )
*idx = n;
}
else if ( idx )
{
// different from any valid index
*idx = (size_t)-1;
}
return s;
}
wxString wxMimeTypeCommands::GetVerbCmd(size_t n) const
{
return m_verbs[n] + wxT('=') + m_commands[n];
}
// ----------------------------------------------------------------------------
// wxFileTypeInfo
// ----------------------------------------------------------------------------
void wxFileTypeInfo::DoVarArgInit(const wxString& mimeType,
const wxString& openCmd,
const wxString& printCmd,
const wxString& desc,
va_list argptr)
{
m_mimeType = mimeType;
m_openCmd = openCmd;
m_printCmd = printCmd;
m_desc = desc;
for ( ;; )
{
// icc gives this warning in its own va_arg() macro, argh
#ifdef __INTELC__
#pragma warning(push)
#pragma warning(disable: 1684)
#endif
wxArgNormalizedString ext(WX_VA_ARG_STRING(argptr));
#ifdef __INTELC__
#pragma warning(pop)
#endif
if ( !ext )
{
// NULL terminates the list
break;
}
m_exts.Add(ext.GetString());
}
}
void wxFileTypeInfo::VarArgInit(const wxString *mimeType,
const wxString *openCmd,
const wxString *printCmd,
const wxString *desc,
...)
{
va_list argptr;
va_start(argptr, desc);
DoVarArgInit(*mimeType, *openCmd, *printCmd, *desc, argptr);
va_end(argptr);
}
wxFileTypeInfo::wxFileTypeInfo(const wxArrayString& sArray)
{
m_mimeType = sArray [0u];
m_openCmd = sArray [1u];
m_printCmd = sArray [2u];
m_desc = sArray [3u];
size_t count = sArray.GetCount();
for ( size_t i = 4; i < count; i++ )
{
m_exts.Add(sArray[i]);
}
}
#include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo)
// ============================================================================
// implementation of the wrapper classes
// ============================================================================
// ----------------------------------------------------------------------------
// wxFileType
// ----------------------------------------------------------------------------
/* static */
wxString wxFileType::ExpandCommand(const wxString& command,
const wxFileType::MessageParameters& params)
{
bool hasFilename = false;
wxString str;
for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
if ( *pc == wxT('%') ) {
switch ( *++pc ) {
case wxT('s'):
// '%s' expands into file name (quoted because it might
// contain spaces) - except if there are already quotes
// there because otherwise some programs may get confused
// by double double quotes
#if 0
if ( *(pc - 2) == wxT('"') )
str << params.GetFileName();
else
str << wxT('"') << params.GetFileName() << wxT('"');
#endif
str << params.GetFileName();
hasFilename = true;
break;
case wxT('t'):
// '%t' expands into MIME type (quote it too just to be
// consistent)
str << wxT('\'') << params.GetMimeType() << wxT('\'');
break;
case wxT('{'):
{
const wxChar *pEnd = wxStrchr(pc, wxT('}'));
if ( pEnd == NULL ) {
wxString mimetype;
wxLogWarning(_("Unmatched '{' in an entry for mime type %s."),
params.GetMimeType().c_str());
str << wxT("%{");
}
else {
wxString param(pc + 1, pEnd - pc - 1);
str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
pc = pEnd;
}
}
break;
case wxT('n'):
case wxT('F'):
// TODO %n is the number of parts, %F is an array containing
// the names of temp files these parts were written to
// and their mime types.
break;
default:
wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
*pc, command.c_str());
str << *pc;
}
}
else {
str << *pc;
}
}
// metamail(1) man page states that if the mailcap entry doesn't have '%s'
// the program will accept the data on stdin so normally we should append
// "< %s" to the end of the command in such case, but not all commands
// behave like this, in particular a common test is 'test -n "$DISPLAY"'
// and appending "< %s" to this command makes the test fail... I don't
// know of the correct solution, try to guess what we have to do.
// test now carried out on reading file so test should never get here
if ( !hasFilename && !str.empty()
#ifdef __UNIX__
&& !str.StartsWith(_T("test "))
#endif // Unix
) {
str << wxT(" < '") << params.GetFileName() << wxT('\'');
}
return str;
}
wxFileType::wxFileType(const wxFileTypeInfo& info)
{
m_info = &info;
m_impl = NULL;
}
wxFileType::wxFileType()
{
m_info = NULL;
m_impl = new wxFileTypeImpl;
}
wxFileType::~wxFileType()
{
if ( m_impl )
delete m_impl;
}
bool wxFileType::GetExtensions(wxArrayString& extensions)
{
if ( m_info )
{
extensions = m_info->GetExtensions();
return true;
}
return m_impl->GetExtensions(extensions);
}
bool wxFileType::GetMimeType(wxString *mimeType) const
{
wxCHECK_MSG( mimeType, false, _T("invalid parameter in GetMimeType") );
if ( m_info )
{
*mimeType = m_info->GetMimeType();
return true;
}
return m_impl->GetMimeType(mimeType);
}
bool wxFileType::GetMimeTypes(wxArrayString& mimeTypes) const
{
if ( m_info )
{
mimeTypes.Clear();
mimeTypes.Add(m_info->GetMimeType());
return true;
}
return m_impl->GetMimeTypes(mimeTypes);
}
bool wxFileType::GetIcon(wxIconLocation *iconLoc) const
{
if ( m_info )
{
if ( iconLoc )
{
iconLoc->SetFileName(m_info->GetIconFile());
#ifdef __WXMSW__
iconLoc->SetIndex(m_info->GetIconIndex());
#endif // __WXMSW__
}
return true;
}
return m_impl->GetIcon(iconLoc);
}
bool
wxFileType::GetIcon(wxIconLocation *iconloc,
const MessageParameters& params) const
{
if ( !GetIcon(iconloc) )
{
return false;
}
// we may have "%s" in the icon location string, at least under Windows, so
// expand this
if ( iconloc )
{
iconloc->SetFileName(ExpandCommand(iconloc->GetFileName(), params));
}
return true;
}
bool wxFileType::GetDescription(wxString *desc) const
{
wxCHECK_MSG( desc, false, _T("invalid parameter in GetDescription") );
if ( m_info )
{
*desc = m_info->GetDescription();
return true;
}
return m_impl->GetDescription(desc);
}
bool
wxFileType::GetOpenCommand(wxString *openCmd,
const wxFileType::MessageParameters& params) const
{
wxCHECK_MSG( openCmd, false, _T("invalid parameter in GetOpenCommand") );
if ( m_info )
{
*openCmd = ExpandCommand(m_info->GetOpenCommand(), params);
return true;
}
return m_impl->GetOpenCommand(openCmd, params);
}
wxString wxFileType::GetOpenCommand(const wxString& filename) const
{
wxString cmd;
if ( !GetOpenCommand(&cmd, filename) )
{
// return empty string to indicate an error
cmd.clear();
}
return cmd;
}
bool
wxFileType::GetPrintCommand(wxString *printCmd,
const wxFileType::MessageParameters& params) const
{
wxCHECK_MSG( printCmd, false, _T("invalid parameter in GetPrintCommand") );
if ( m_info )
{
*printCmd = ExpandCommand(m_info->GetPrintCommand(), params);
return true;
}
return m_impl->GetPrintCommand(printCmd, params);
}
size_t wxFileType::GetAllCommands(wxArrayString *verbs,
wxArrayString *commands,
const wxFileType::MessageParameters& params) const
{
if ( verbs )
verbs->Clear();
if ( commands )
commands->Clear();
#if defined (__WXMSW__) || defined(__UNIX__)
return m_impl->GetAllCommands(verbs, commands, params);
#else // !__WXMSW__ || Unix
// we don't know how to retrieve all commands, so just try the 2 we know
// about
size_t count = 0;
wxString cmd;
if ( GetOpenCommand(&cmd, params) )
{
if ( verbs )
verbs->Add(_T("Open"));
if ( commands )
commands->Add(cmd);
count++;
}
if ( GetPrintCommand(&cmd, params) )
{
if ( verbs )
verbs->Add(_T("Print"));
if ( commands )
commands->Add(cmd);
count++;
}
return count;
#endif // __WXMSW__/| __UNIX__
}
bool wxFileType::Unassociate()
{
#if defined(__WXMSW__)
return m_impl->Unassociate();
#elif defined(__UNIX__)
return m_impl->Unassociate(this);
#else
wxFAIL_MSG( _T("not implemented") ); // TODO
return false;
#endif
}
bool wxFileType::SetCommand(const wxString& cmd,
const wxString& verb,
bool overwriteprompt)
{
#if defined (__WXMSW__) || defined(__UNIX__)
return m_impl->SetCommand(cmd, verb, overwriteprompt);
#else
wxUnusedVar(cmd);
wxUnusedVar(verb);
wxUnusedVar(overwriteprompt);
wxFAIL_MSG(_T("not implemented"));
return false;
#endif
}
bool wxFileType::SetDefaultIcon(const wxString& cmd, int index)
{
wxString sTmp = cmd;
#ifdef __WXMSW__
// VZ: should we do this?
// chris elliott : only makes sense in MS windows
if ( sTmp.empty() )
GetOpenCommand(&sTmp, wxFileType::MessageParameters(wxEmptyString, wxEmptyString));
#endif
wxCHECK_MSG( !sTmp.empty(), false, _T("need the icon file") );
#if defined (__WXMSW__) || defined(__UNIX__)
return m_impl->SetDefaultIcon (cmd, index);
#else
wxUnusedVar(index);
wxFAIL_MSG(_T("not implemented"));
return false;
#endif
}
// ----------------------------------------------------------------------------
// wxMimeTypesManagerFactory
// ----------------------------------------------------------------------------
wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::m_factory = NULL;
/* static */
void wxMimeTypesManagerFactory::Set(wxMimeTypesManagerFactory *factory)
{
delete m_factory;
m_factory = factory;
}
/* static */
wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::Get()
{
if ( !m_factory )
m_factory = new wxMimeTypesManagerFactory;
return m_factory;
}
wxMimeTypesManagerImpl *wxMimeTypesManagerFactory::CreateMimeTypesManagerImpl()
{
return new wxMimeTypesManagerImpl;
}
// ----------------------------------------------------------------------------
// wxMimeTypesManager
// ----------------------------------------------------------------------------
void wxMimeTypesManager::EnsureImpl()
{
if ( !m_impl )
m_impl = wxMimeTypesManagerFactory::Get()->CreateMimeTypesManagerImpl();
}
bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
const wxString& wildcard)
{
wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
wxT("first MIME type can't contain wildcards") );
// all comparaisons are case insensitive (2nd arg of IsSameAs() is false)
if ( wildcard.BeforeFirst(wxT('/')).
IsSameAs(mimeType.BeforeFirst(wxT('/')), false) )
{
wxString strSubtype = wildcard.AfterFirst(wxT('/'));
if ( strSubtype == wxT("*") ||
strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), false) )
{
// matches (either exactly or it's a wildcard)
return true;
}
}
return false;
}
wxMimeTypesManager::wxMimeTypesManager()
{
m_impl = NULL;
}
wxMimeTypesManager::~wxMimeTypesManager()
{
if ( m_impl )
delete m_impl;
}
bool wxMimeTypesManager::Unassociate(wxFileType *ft)
{
EnsureImpl();
#if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
return m_impl->Unassociate(ft);
#else
return ft->Unassociate();
#endif
}
wxFileType *
wxMimeTypesManager::Associate(const wxFileTypeInfo& ftInfo)
{
EnsureImpl();
#if defined(__WXMSW__) || defined(__UNIX__)
return m_impl->Associate(ftInfo);
#else // other platforms
wxUnusedVar(ftInfo);
wxFAIL_MSG( _T("not implemented") ); // TODO
return NULL;
#endif // platforms
}
wxFileType *
wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
{
EnsureImpl();
wxString::const_iterator i = ext.begin();
const wxString::const_iterator end = ext.end();
wxString extWithoutDot;
if ( i != end && *i == '.' )
extWithoutDot.assign(++i, ext.end());
else
extWithoutDot = ext;
wxCHECK_MSG( !ext.empty(), NULL, _T("extension can't be empty") );
wxFileType *ft = m_impl->GetFileTypeFromExtension(extWithoutDot);
if ( !ft ) {
// check the fallbacks
//
// TODO linear search is potentially slow, perhaps we should use a
// sorted array?
size_t count = m_fallbacks.GetCount();
for ( size_t n = 0; n < count; n++ ) {
if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
ft = new wxFileType(m_fallbacks[n]);
break;
}
}
}
return ft;
}
wxFileType *
wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
{
EnsureImpl();
wxFileType *ft = m_impl->GetFileTypeFromMimeType(mimeType);
if ( !ft ) {
// check the fallbacks
//
// TODO linear search is potentially slow, perhaps we should use a
// sorted array?
size_t count = m_fallbacks.GetCount();
for ( size_t n = 0; n < count; n++ ) {
if ( wxMimeTypesManager::IsOfType(mimeType,
m_fallbacks[n].GetMimeType()) ) {
ft = new wxFileType(m_fallbacks[n]);
break;
}
}
}
return ft;
}
void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
{
EnsureImpl();
for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
AddFallback(*ft);
}
}
size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
{
EnsureImpl();
size_t countAll = m_impl->EnumAllFileTypes(mimetypes);
// add the fallback filetypes
size_t count = m_fallbacks.GetCount();
for ( size_t n = 0; n < count; n++ ) {
if ( mimetypes.Index(m_fallbacks[n].GetMimeType()) == wxNOT_FOUND ) {
mimetypes.Add(m_fallbacks[n].GetMimeType());
countAll++;
}
}
return countAll;
}
void wxMimeTypesManager::Initialize(int mcapStyle,
const wxString& sExtraDir)
{
#if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
EnsureImpl();
m_impl->Initialize(mcapStyle, sExtraDir);
#else
(void)mcapStyle;
(void)sExtraDir;
#endif // Unix
}
// and this function clears all the data from the manager
void wxMimeTypesManager::ClearData()
{
#if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
EnsureImpl();
m_impl->ClearData();
#endif // Unix
}
// ----------------------------------------------------------------------------
// global data and wxMimeTypeCmnModule
// ----------------------------------------------------------------------------
// private object
static wxMimeTypesManager gs_mimeTypesManager;
// and public pointer
wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
class wxMimeTypeCmnModule: public wxModule
{
public:
wxMimeTypeCmnModule() : wxModule() { }
virtual bool OnInit() { return true; }
virtual void OnExit()
{
wxMimeTypesManagerFactory::Set(NULL);
if ( gs_mimeTypesManager.m_impl != NULL )
{
delete gs_mimeTypesManager.m_impl;
gs_mimeTypesManager.m_impl = NULL;
gs_mimeTypesManager.m_fallbacks.Clear();
}
}
DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
};
IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)
#endif // wxUSE_MIMETYPE
| [
"RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775"
] | RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 |
02e89f9e580c34eb2e12a6bbf57dc889c3a8a7ad | 5eb6dbceda5e7a4dd9c483930288ae60b2aff3ab | /quickunionunionfind.h | 1e1638dd09fbe07a6c7e6b227d6b7848aa42afc6 | [] | no_license | vancha/HexMinimax | e46be06332a04dbcc77d17f22b657362b328e235 | cbbd24915e3a23f5de2a0c5eca8fec8790bf2459 | refs/heads/master | 2021-01-11T21:06:55.659402 | 2017-01-20T19:04:02 | 2017-01-20T19:04:02 | 79,245,711 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 520 | h | #ifndef QUICKUNIONUNIONFIND_H
#define QUICKUNIONUNIONFIND_H
#include <vector>
using namespace std;
class QuickUnionUnionFind
{
private:
vector<int> id;//array of indexes
vector<int> sz;//only used to count number of elements in tree(prevent tall trees)
int Qroot(int i);
public:
bool Qconnected(int p, int q);//are p and q in the same set?
void Qunion(int p, int q);//merge sets containing p and q
QuickUnionUnionFind(int N);
void disconnectCell(int p);
};
#endif // QUICKUNIONUNIONFIND_H
| [
"[email protected]"
] | |
6f020d54ea1816227efe04dc877406fd30cdd747 | 2111c552355a578e7c2f125a7226453df7d095be | /kClistMatrix.cpp | f5546ba8f3aaa53c642a1a1b61a15b052bfc180d | [] | no_license | CaitlinKennedy/k-clique-matrix | ede2d58b1f3e2751cbacbc8316f0d71b5f380b3e | 3dd17ed053e3bb4ca87de7134f8f88044558725d | refs/heads/master | 2020-03-16T04:41:09.082713 | 2018-06-02T15:52:01 | 2018-06-02T15:52:01 | 132,516,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,890 | cpp | /*
Info:
Feel free to use these lines as you wish.
This program iterates over all k-cliques. It is highly scallable.
To compile:
"gcc kClistDens.c -O9 -o kClistDens -fopenmp".
To execute:
"./kClistDens p k edgelist.txt".
"edgelist.txt" should contain the graph: one edge on each line separated by a space.
k is the size of the k-cliques
p is the number of threads
Will print the number of k-cliques and the density of the found kclique densest.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <omp.h>
#include <unordered_map>
#include <vector>
#define NLINKS 100000000 //maximum number of edges for memory allocation, will increase if needed
class Clique_Matrix {
public:
Clique_Matrix(unsigned);
unsigned vector_length;
std::vector<std::unordered_map<unsigned, int64_t>> clique_mat;
void add_edge(unsigned, unsigned);
void add_edge_weight(unsigned, unsigned, unsigned);
};
Clique_Matrix::Clique_Matrix(unsigned number_of_nodes) {
vector_length = number_of_nodes;
clique_mat = std::vector<std::unordered_map<unsigned, int64_t>>(number_of_nodes);
};
void Clique_Matrix::add_edge(unsigned p, unsigned q) {
clique_mat[p][q]++;
}
void Clique_Matrix::add_edge_weight(unsigned p, unsigned q, unsigned w) {
clique_mat[p][q] += w;
}
typedef struct {
unsigned s;
unsigned t;
} edge;
typedef struct {
unsigned node;
unsigned deg;
} nodedeg ;
typedef struct {
unsigned n;//number of nodes
unsigned e;//number of edges
edge *edges;//list of edges
unsigned *rank;//ranking of the nodes according to degeneracy ordering
//unsigned *map;//oldID newID correspondance NOT USED IN THIS VERSION
unsigned *node_map; //map from new id to old id
} edgelist;
typedef struct {
unsigned n;
unsigned e;
edge *edges;//ading this again here: TO IMPROVE
unsigned *cd;//cumulative degree: (starts with 0) length=n+1
unsigned *adj;//truncated list of neighbors
unsigned core;//core value of the graph
} graph;
typedef struct {
unsigned *n;//n[l]: number of nodes in G_l
unsigned **d;//d[l]: degrees of G_l
unsigned *adj;//truncated list of neighbors
unsigned char *lab;//lab[i] label of node i
unsigned **nodes;//sub[l]: nodes in G_l
unsigned core;
} subgraph;
void free_graph(graph *g){
free(g->cd);
free(g->adj);
free(g);
}
void free_subgraph(subgraph *sg, unsigned char k){
unsigned char i;
free(sg->n);
for (i=1;i<k;i++){
free(sg->d[i]);
free(sg->nodes[i]);
}
free(sg->d);
free(sg->nodes);
free(sg->lab);
free(sg->adj);
free(sg);
}
//Compute the maximum of three unsigned integers.
inline unsigned int max3(unsigned int a,unsigned int b,unsigned int c){
a=(a>b) ? a : b;
return (a>c) ? a : c;
}
edgelist* readedgelist(char* input){
unsigned e1=NLINKS;
edgelist *el=(edgelist*)malloc(sizeof(edgelist));
FILE *file;
el->n=0;
el->e=0;
file=fopen(input,"r");
el->edges=(edge*)malloc(e1*sizeof(edge));
unsigned w = 1;
unsigned s = 1;
unsigned t = 1;
fscanf(file, "%u %u %u", &s, &t, &w);
while (fscanf(file,"%u %u %u", &s, &t, &w)==3) {//Add one edge
if (s < t) {
(el->edges[el->e].s) = s;
(el->edges[el->e].t) = t;
el->n=max3(el->n,el->edges[el->e].s,el->edges[el->e].t);
el->e++;
if (el->e==e1) {
e1+=NLINKS;
el->edges=(edge*)realloc(el->edges,e1*sizeof(edge));
}
}
}
fclose(file);
el->n++;
el->edges=(edge*)realloc(el->edges,el->e*sizeof(edge));
el->node_map=(unsigned*)malloc((el->n)*sizeof(unsigned));
return el;
}
void relabel(edgelist *el){
// for (int m=0; m<el->n; m++) {
// printf("node: %u rank: %u\n", m, el->rank[m]);
// }
unsigned i, source, target, tmp;
el->n=0;
//FILE* file=fopen("debug.txt","w");
for (i=0;i<el->e;i++) {
source=el->rank[el->edges[i].s];
target=el->rank[el->edges[i].t];
// printf("old src: %u new src: %u\n", el->edges[i].s, source );
// printf("old t: %u new t: %u\n", el->edges[i].t, target );
el->node_map[source] = el->edges[i].s;
el->node_map[target] = el->edges[i].t;
if (source<target){
tmp=source;
source=target;
target=tmp;
}
if (source+1>el->n){
el->n=source+1;
}
el->edges[i].s=source;
el->edges[i].t=target;
//fprintf(file,"%u %u\n",source,target);
}
//fclose(file);
}
///// CORE ordering /////////////////////
typedef struct {
unsigned key;
unsigned value;
} keyvalue;
typedef struct {
unsigned n_max; // max number of nodes.
unsigned n; // number of nodes.
unsigned *pt; // pointers to nodes.
keyvalue *kv; // nodes.
} bheap;
bheap *construct(unsigned n_max){
unsigned i;
bheap *heap=(bheap*)malloc(sizeof(bheap));
heap->n_max=n_max;
heap->n=0;
heap->pt=(unsigned *)malloc(n_max*sizeof(unsigned));
for (i=0;i<n_max;i++) heap->pt[i]=-1;
heap->kv=(keyvalue*)malloc(n_max*sizeof(keyvalue));
return heap;
}
void swap(bheap *heap,unsigned i, unsigned j) {
keyvalue kv_tmp=heap->kv[i];
unsigned pt_tmp=heap->pt[kv_tmp.key];
heap->pt[heap->kv[i].key]=heap->pt[heap->kv[j].key];
heap->kv[i]=heap->kv[j];
heap->pt[heap->kv[j].key]=pt_tmp;
heap->kv[j]=kv_tmp;
}
void bubble_up(bheap *heap,unsigned i) {
unsigned j=(i-1)/2;
while (i>0) {
if (heap->kv[j].value>heap->kv[i].value) {
swap(heap,i,j);
i=j;
j=(i-1)/2;
}
else break;
}
}
void bubble_down(bheap *heap) {
unsigned i=0,j1=1,j2=2,j;
while (j1<heap->n) {
j=( (j2<heap->n) && (heap->kv[j2].value<heap->kv[j1].value) ) ? j2 : j1 ;
if (heap->kv[j].value < heap->kv[i].value) {
swap(heap,i,j);
i=j;
j1=2*i+1;
j2=j1+1;
continue;
}
break;
}
}
void insert(bheap *heap,keyvalue kv){
heap->pt[kv.key]=(heap->n)++;
heap->kv[heap->n-1]=kv;
bubble_up(heap,heap->n-1);
}
void update(bheap *heap,unsigned key){
unsigned i=heap->pt[key];
if (i!=-1){
((heap->kv[i]).value)--;
bubble_up(heap,i);
}
}
keyvalue popmin(bheap *heap){
keyvalue min=heap->kv[0];
heap->pt[min.key]=-1;
heap->kv[0]=heap->kv[--(heap->n)];
heap->pt[heap->kv[0].key]=0;
bubble_down(heap);
return min;
}
//Building the heap structure with (key,value)=(node,degree) for each node
bheap* mkheap(unsigned n,unsigned *v){
unsigned i;
keyvalue kv;
bheap* heap=construct(n);
for (i=0;i<n;i++){
kv.key=i;
kv.value=v[i];
insert(heap,kv);
}
return heap;
}
void freeheap(bheap *heap){
free(heap->pt);
free(heap->kv);
free(heap);
}
//computing degeneracy ordering and core value
void ord_core(edgelist* el){
unsigned i,j,r=0,n=el->n,e=el->e;
keyvalue kv;
bheap *heap;
unsigned *d0=(unsigned*)calloc(el->n,sizeof(unsigned));
unsigned *cd0=(unsigned *)malloc((el->n+1)*sizeof(unsigned));
unsigned *adj0=(unsigned *)malloc(2*el->e*sizeof(unsigned));
for (i=0;i<e;i++) {
d0[el->edges[i].s]++;
d0[el->edges[i].t]++;
}
cd0[0]=0;
for (i=1;i<n+1;i++) {
cd0[i]=cd0[i-1]+d0[i-1];
d0[i-1]=0;
}
for (i=0;i<e;i++) {
adj0[ cd0[el->edges[i].s] + d0[ el->edges[i].s ]++ ]=el->edges[i].t;
adj0[ cd0[el->edges[i].t] + d0[ el->edges[i].t ]++ ]=el->edges[i].s;
}
heap=mkheap(n,d0);
el->rank=(unsigned *)malloc(n*sizeof(unsigned));
for (i=0;i<n;i++){
kv=popmin(heap);
el->rank[kv.key]=n-(++r);
for (j=cd0[kv.key];j<cd0[kv.key+1];j++){
update(heap,adj0[j]);
}
}
freeheap(heap);
free(d0);
free(cd0);
free(adj0);
}
//////////////////////////
//Building the special graph
graph* mkgraph(edgelist *el){
unsigned i,max;
unsigned *d;
graph* g=(graph*)malloc(sizeof(graph));
d=(unsigned *)calloc(el->n,sizeof(unsigned));
for (i=0;i<el->e;i++) {
d[el->edges[i].s]++;
}
g->cd=(unsigned *)malloc((el->n+1)*sizeof(unsigned));
g->cd[0]=0;
max=0;
for (i=1;i<el->n+1;i++) {
g->cd[i]=g->cd[i-1]+d[i-1];
max=(max>d[i-1])?max:d[i-1];
d[i-1]=0;
}
//printf("core value (max truncated degree) = %u\n",max);
g->adj=(unsigned *)malloc(el->e*sizeof(unsigned));
for (i=0;i<el->e;i++) {
g->adj[ g->cd[el->edges[i].s] + d[ el->edges[i].s ]++ ]=el->edges[i].t;
}
free(d);
g->core=max;
g->n=el->n;
free(el->rank);
g->edges=el->edges;
g->e=el->e;
//free(el);
// printf("el2=%u\n",el->e);
return g;
}
subgraph* allocsub(graph *g,unsigned char k){
unsigned i;
subgraph* sg=(subgraph *)malloc(sizeof(subgraph));
sg->n=(unsigned *)calloc(k,sizeof(unsigned));
sg->d=(unsigned **)malloc(k*sizeof(unsigned*));
sg->nodes=(unsigned **)malloc(k*sizeof(unsigned*));
for (i=1;i<k;i++){/////////
sg->d[i]=(unsigned *)malloc(g->core*sizeof(unsigned));
sg->nodes[i]=(unsigned *)malloc(g->core*sizeof(unsigned));
}
sg->lab=(unsigned char *)calloc(g->core,sizeof(unsigned char));
sg->adj=(unsigned *)malloc(g->core*g->core*sizeof(unsigned));
sg->core=g->core;
return sg;
}
unsigned *old=NULL,*newN=NULL;//to improve
#pragma omp threadprivate(newN,old)
void mksub(graph* g,edge ed,subgraph* sg,unsigned char k){
unsigned i,j,l,x,y;
unsigned u=ed.s,v=ed.t;
if (old==NULL){
newN=(unsigned *)malloc(g->n*sizeof(unsigned));
old=(unsigned *)malloc(g->core*sizeof(unsigned));
for (i=0;i<g->n;i++){
newN[i]=-1;
}
}
for (i=0;i<sg->n[k-1];i++){
sg->lab[i]=0;
}
for (i=g->cd[v];i<g->cd[v+1];i++){
newN[g->adj[i]]=-2;
}
j=0;
for (i=g->cd[u];i<g->cd[u+1];i++){
x=g->adj[i];
if (newN[x]==-2){
newN[x]=j;
old[j]=x;
sg->lab[j]=k-2;
sg->nodes[k-2][j]=j;
sg->d[k-2][j]=0;//new degrees
j++;
}
}
sg->n[k-2]=j;
for (i=0;i<sg->n[k-2];i++){//reodering adjacency list and computing new degrees
x=old[i];
for (l=g->cd[x];l<g->cd[x+1];l++){
y=g->adj[l];
j=newN[y];
if (j<-2){
sg->adj[sg->core*i+sg->d[k-2][i]++]=j;
}
}
}
for (i=g->cd[v];i<g->cd[v+1];i++){
newN[g->adj[i]]=-1;
}
}
unsigned long long *ckdeg_p,*ckdeg;
unsigned * ck_buf;
unsigned *ck_p;
Clique_Matrix * ck_m;
Clique_Matrix *clique_matrix;
int pos;
#pragma omp threadprivate(ck_m, ckdeg_p,ck_p,ck_buf,pos)
//after the threads are done, combine individual clique matrices to overall one
void combine_to_global_matrix() {
#pragma omp critical (mat)
for (int p = 0; p < ck_m->vector_length; p++) {//vector iterator
for (std::pair<unsigned, int64_t> element : ck_m->clique_mat[p]) {//map iterator
clique_matrix->clique_mat[p][element.first]+= element.second;
}
}
}
//empty a thread's clique buffer into matrix
void add_to_thread_matrix() {
int i = 0;
while (i < pos) { //<pos
int k = 0;
while (ck_buf[k + i] != -1) {
k++;
}
for (int p = 0; p < k; p++) { //while not "/"
for(int q=p+1;q<k;q++) {
ck_m->add_edge(ck_buf[i+p], ck_buf[i+q]);
ck_m->add_edge(ck_buf[i+q], ck_buf[i+p]);
}
}
i += k + 1;
}
}
//add a clique of size k to the buffer for the thread, when buffer has less than kmax space, empty
void add_clique_to_buf(unsigned k, unsigned kmax, unsigned * clique) {
for (int i = 0; i < k; i++) {
ck_buf[pos] = clique[i];
pos++;
}
ck_buf[pos] = -1;
pos++;
//
if (pos >= 10000*kmax - kmax) {
add_to_thread_matrix();
pos=0;
}
}
//allocate all the thread and global variables
void allocglobal(graph *g,unsigned k, unsigned number_of_nodes){
#pragma omp parallel
{
ck_p=(unsigned *)calloc(k,sizeof(unsigned));
ckdeg_p=(unsigned long long *)calloc(g->n,sizeof(unsigned long long));
ck_buf=(unsigned *)calloc(10000*k, sizeof(unsigned));
pos = 0;
ck_m = new Clique_Matrix(number_of_nodes);
}
ckdeg=(unsigned long long *)calloc(g->n,sizeof(unsigned long long));
clique_matrix = new Clique_Matrix(number_of_nodes);
}
void kclique_thread(unsigned char kmax, unsigned char l, subgraph *sg, unsigned long long *n, unsigned * node_map, int sumC) {
unsigned i,j,k,end,u,v,w;
//edges
if (kmax==2 || (sumC && kmax-l == 2)){
ckdeg_p[ck_p[kmax - 2]]++;
ckdeg_p[ck_p[kmax - 1]]++;
(*n)++;
unsigned kclique[2] = {node_map[ck_p[kmax-2]], node_map[ck_p[kmax-1]]};
add_clique_to_buf(2, kmax, kclique);
if (kmax==2) {return;}
}
//3 clique
if (kmax==3 || (sumC && kmax-l == 2)){//if max is 3 or special cases for sum
for(i=0; i<sg->n[l]; i++){//list all nodes
ckdeg_p[old[sg->nodes[l][i]]]++;
ckdeg_p[ck_p[kmax - 2]]++;
ckdeg_p[ck_p[kmax - 1]]++;
(*n)++;//listing here!!!
unsigned kclique[3] = {node_map[ck_p[kmax - 1]], node_map[ck_p[kmax - 2]], node_map[old[sg->nodes[l][i]]]};
add_clique_to_buf(3, kmax, kclique);
}
if (kmax==3) {return;}
}
//k-clique
if(l==2){
for(i=0; i<sg->n[2]; i++){//list all edges
u=sg->nodes[2][i];
end=u*sg->core+sg->d[2][u];
for (j=u*sg->core;j<end;j++) {
unsigned * kclique = (unsigned *)malloc(kmax*sizeof(unsigned));
int count = 0;
kclique[count] = node_map[old[u]];
count++;
kclique[count]= node_map[old[sg->adj[j]]];
count++;
ckdeg_p[old[sg->adj[j]]]++;
ckdeg_p[old[u]]++;
for (l=2;l<kmax;l++){//ok to use l here :)
ckdeg_p[ck_p[l]]++;
kclique[count] = node_map[ck_p[l]];
count++;
}
(*n)++;//listing here!!
add_clique_to_buf(kmax, kmax, kclique);
}
}
return;
}
//not a tracked clique, or a lower order clique for sum
for(i=0; i<sg->n[l]; i++){
u=sg->nodes[l][i];
ck_p[l-1]=old[u];
//printf("%u %u\n",i,u);
sg->n[l-1]=0;
end=u*sg->core+sg->d[l][u];
for (j=u*sg->core;j<end;j++){//relabeling nodes and forming U'.
if (sumC) {
unsigned * kclique = (unsigned *)malloc((kmax-l+2)*sizeof(unsigned));
int count = 0;
kclique[count] = node_map[old[u]];
count++;
kclique[count]= node_map[old[sg->adj[j]]];
count++;
ckdeg_p[old[sg->adj[j]]]++;
ckdeg_p[old[u]]++;
for (int m=0; m<kmax -l;m++){
ckdeg_p[ck_p[count + m]]++;
kclique[count + m] = node_map[ck_p[l + m]];
}
(*n)++;//listing here!!!
add_clique_to_buf(kmax - l + 2, kmax, kclique);
}
v=sg->adj[j];
if (sg->lab[v]==l){
sg->lab[v]=l-1;
sg->nodes[l-1][sg->n[l-1]++]=v;
sg->d[l-1][v]=0;//new degrees
}
}
for (j=0;j<sg->n[l-1];j++){//reodering adjacency list and computing new degrees
v=sg->nodes[l-1][j];
end=sg->core*v+sg->d[l][v];
for (k=sg->core*v;k<end;k++){
w=sg->adj[k];
if (sg->lab[w]==l-1){
sg->d[l-1][v]++;
}
else{
sg->adj[k--]=sg->adj[--end];
sg->adj[end]=w;
}
}
}
kclique_thread(kmax,l-1, sg, n, node_map, sumC);
for (j=0;j<sg->n[l-1];j++){//restoring labels
v=sg->nodes[l-1][j];
sg->lab[v]=l;
}
}
}
unsigned long long kclique_main(unsigned char k, graph *g, unsigned * node_map, int sumC) {
unsigned i;
unsigned long long n=0;
subgraph *sg;
#pragma omp parallel private(sg,i) reduction(+:n)
{
sg=allocsub(g,k);
#pragma omp for schedule(dynamic, 1) nowait
for(i=0; i<g->e; i++){
ck_p[k-1]=g->edges[i].s;
ck_p[k-2]=g->edges[i].t;
if (k!=2) {
mksub(g,g->edges[i],sg,k);
}
kclique_thread(k,k-2, sg, &n,node_map, sumC);
}
add_to_thread_matrix();
pos=0;
combine_to_global_matrix();
free_subgraph(sg,k);
#pragma omp single
{
bzero(ckdeg,g->n*sizeof(unsigned long long));
}
#pragma omp barrier //is it necessary???
#pragma omp critical
{
for(i=0; i<g->n; i++){
ckdeg[i]+=ckdeg_p[i];
}
bzero(ckdeg_p,g->n*sizeof(unsigned long long));
}
}
return n;
}
int main(int argc,char** argv){
edgelist* el;
graph* g;
int sumC = 0;
unsigned char k;
if (argv[2][strlen(argv[2]) - 1] == '+') {
sumC = 1;
argv[2][strlen(argv[2]) -1] = '\0';
k=atoi(argv[2]);
}
else {
k=atoi(argv[2]);
}
unsigned long long nck;
unsigned test = 0;
if (argc > 4) {
test = 1;
}
omp_set_num_threads(atoi(argv[1]));
time_t t0,t1,t2;
t1=time(NULL);
t0=t1;
if (!test) {
printf("Reading edgelist from file %s\n",argv[3]);
}
el=readedgelist(argv[3]);
if (!test) {
printf("Number of nodes = %u\n",el->n);
printf("Number of edges = %u\n",el->e);
}
unsigned number_of_nodes = el->n;
t2=time(NULL);
if (!test) {
printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));
}
if (!test) {
printf("Building the graph structure\n");
}
ord_core(el);
relabel(el);
g=mkgraph(el);
if (!test) {
printf("Number of nodes (degree > 0) = %u\n",g->n);
}
t2=time(NULL);
if (!test) {
printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));
}
t1=t2;
allocglobal(g,k,number_of_nodes);//allocataing global variables
nck=kclique_main(k, g, el->node_map, sumC);
if (!test && sumC){
printf("Number of all cliques up to %u: %llu\n",k,nck);
}
if (!test && !sumC){
printf("Number of %u-cliques: %llu\n",k,nck);
}
unsigned long long r=0,r2=0;
free_graph(g);
t2=time(NULL);
t1=t2;
//iterate through clique_matrix to print
for (int p = 0; p < clique_matrix->vector_length; p++) {//vector iterator
for (std::pair<unsigned, int64_t> element : clique_matrix->clique_mat[p]) {
printf("%u %u %ld\n", p, element.first, element.second);
}
}
if (!test) {
printf("- Overall time = %ldh%ldm%lds\n",(t2-t0)/3600,((t2-t0)%3600)/60,((t2-t0)%60));
}
return 0;
}
| [
"[email protected]"
] | |
1f64590aeb5261cfd4aa34d6156a42c65c23f298 | f59ed9cff747b62a412aa1fd3868226541475a43 | /soft_rm/Rum/Duplicate.hpp | 4a40765016ceb3e8bbfe214e670df9c7704db5d4 | [] | no_license | waszak/Masspixel-generator | 64bf09443f67eba75bfe0be5c31f379de5d573e7 | 7db39bb63107a3bbcaf1435afe217727342b9d96 | refs/heads/main | 2021-06-02T12:27:49.691255 | 2014-03-18T16:57:24 | 2014-03-18T16:57:24 | 17,873,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | hpp | #ifndef __OBJECT_DUPLICATE_HPP__
#define __OBJECT_DUPLICATE_HPP__
#include "IObject.hpp"
class Duplicate : public IObject
{
public:
Duplicate(const IObject * obj, Vector3D m)
{
mObj = obj;
mMod = m;
REPU(i,3) mHalfMod[i] = m[i] * -0.5;
mHalfMod[3] = 0;
}
private:
virtual double dist(const Point4D& point) const
{
return mObj->Distance( vf::mod_nolast(point,mMod) + mHalfMod);
}
const IObject* mObj;
Vector3D mMod;
Vector4D mHalfMod;
};
#endif //__OBJECT_DUPLICATE_HPP__//
| [
"[email protected]"
] | |
775e4f75b436d29201394755839519fe2e61bbc0 | a3c2b8e59db2761a68cd81431ef0f43b07629e7f | /Source/GameEngine/Graphic/ScreenElement.h | 6013417109302795a47de2c004a0be23b73831aa | [] | no_license | enriquegr84/GameEngineTutorial | 13eeae4b8c65cf94254c4cb7f879f52614fed185 | dd6507839a34746dc9b25d28c879f180c62eaab8 | refs/heads/master | 2021-08-23T09:35:28.257239 | 2021-08-06T16:52:38 | 2021-08-06T16:52:38 | 83,200,106 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,572 | h | //========================================================================
// GameView.h : Defines the GameView class of the GameEngine application
//
// Part of the GameEngine Application
//
// GameEngine is the sample application that encapsulates much of the source code
// discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David
// "Rez" Graham, published by Charles River Media.
// ISBN-10: 1133776574 | ISBN-13: 978-1133776574
//
// If this source code has found it's way to you, and you think it has helped you
// in any way, do the authors a favor and buy a new copy of the book - there are
// detailed explanations in it that compliment this code well. Buy a copy at Amazon.com
// by clicking here:
// http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller=
//
// There's a companion web site at http://www.mcshaffry.com/GameCode/
//
// The source code is managed and maintained through Google Code:
// http://code.google.com/p/GameEngine/
//
// (c) Copyright 2012 Michael L. McShaffry and David Graham
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser GPL v3
// as published by the Free Software Foundation.
//
// 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
// http://www.gnu.org/licenses/lgpl-3.0.txt for more details.
//
// You should have received a copy of the GNU Lesser GPL v3
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//========================================================================
#ifndef SCREENELEMENT_H
#define SCREENELEMENT_H
#include "GameEngineStd.h"
#include "Application/System/EventSystem.h"
/*
A screen element is anything that draws and accepts input. It could be anything from a UI
to your rendered 3D world. Screen elements can be hierarchical, for example, a dialog box
can have buttons attached to it. Screen elements in various configurations create the user
interface for the game, such as a menu, inventory screen. Some run on top of the main game
screen, but others might completely overlay the main view and even pause the game. In
addition to acting as a container for controls, screens parse user input messages from the
application layer and translate them into game messages.
The BaseScreenElement interface shows that a screen knows how to restore itself when it
needs to be rebuilt, how to render itself when it's time to draw, how it should be ordered
in the master draw list, and whether it is visible. The OnMsgProc() method accepts messages
from the application layer, but translates them into a structure to simplify the call signature
of anything that will accept these messages.
*/
class BaseScreenElement
{
public:
virtual bool OnInit() = 0;
virtual bool OnRestore() = 0;
virtual bool OnLostDevice() = 0;
virtual bool OnRender(double time, float elapsedTime) = 0;
virtual void OnUpdate(unsigned int timeMs, unsigned long deltaMs) = 0;
virtual int GetZOrder() const = 0;
virtual void SetZOrder(int const zOrder) = 0;
virtual bool IsVisible() = 0;
virtual void SetVisible(bool visible) = 0;
virtual bool OnMsgProc(const Event& event) = 0;
virtual ~BaseScreenElement() { };
virtual bool const operator <(BaseScreenElement const &other)
{ return GetZOrder() < other.GetZOrder(); }
};
#endif | [
"[email protected]"
] | |
d51800ce7fc4857207ce369b36efa5217151f5c8 | 202b0730d9e103b2233f4a1c344c9eb63fb40f77 | /src/cali/DebugInfo.h | 9d8070468465b6dab657d1665fa6d1148855bcda | [] | no_license | ziab/cali | 2b22b4e9ed4268fcda2a4e12a2f040d6ccb34fc4 | 9bf9eff319e7210089ee69932668d0f432394cac | refs/heads/master | 2021-06-15T01:09:44.413120 | 2021-02-23T05:32:59 | 2021-02-23T05:32:59 | 146,534,277 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | h | #pragma once
#include <unordered_map>
#include <mutex>
#include <SpriteFont.h>
#include <IvRenderer.h>
#include "Renderable.h"
namespace cali
{
class debug_info : public renderable
{
static debug_info* m_debug_info;
static const float m_scaling;
std::unordered_map<const wchar_t*, float> m_strings;
mutable std::mutex m_mutex;
std::unique_ptr<DirectX::SpriteBatch> m_sprite_batch;
std::unique_ptr<DirectX::SpriteFont> m_sprite_font;
debug_info() {}
~debug_info() {}
public:
static debug_info& get_debug_info();
void initialize(IvRenderer & renderer);
void set_debug_string(const wchar_t* param, float value);
virtual void update(float dt);
virtual void render(IvRenderer& renderer);
};
} | [
"[email protected]"
] | |
32bb15596dfdd893d7609bec1b774e0851dcb8b5 | 451ab1e84ae56931352f38ef2ea82d4c14a17497 | /cocos2d/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp | 4cfc46e0346ea697309bc0e736cb46b7e32d284e | [
"MIT"
] | permissive | denghe/xxlib_cocos_cpp | 64b5c02b2525e6f8f27efcc0daa2855e90388063 | d4e9c6f0e59c3db01a6791622188576089df5afe | refs/heads/master | 2021-06-27T21:33:54.024283 | 2020-09-26T07:03:17 | 2020-09-26T07:03:17 | 154,665,907 | 6 | 3 | null | 2019-05-23T14:21:14 | 2018-10-25T12:19:53 | C++ | UTF-8 | C++ | false | false | 5,062 | cpp | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "editor-support/cocosbuilder/CCLabelTTFLoader.h"
using namespace cocos2d;
#define PROPERTY_COLOR "color"
#define PROPERTY_OPACITY "opacity"
#define PROPERTY_BLENDFUNC "blendFunc"
#define PROPERTY_FONTNAME "fontName"
#define PROPERTY_FONTSIZE "fontSize"
#define PROPERTY_HORIZONTALALIGNMENT "horizontalAlignment"
#define PROPERTY_VERTICALALIGNMENT "verticalAlignment"
#define PROPERTY_STRING "string"
#define PROPERTY_DIMENSIONS "dimensions"
namespace cocosbuilder {
void LabelTTFLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_COLOR) == 0) {
((Label *)pNode)->setColor(pColor3B);
} else {
NodeLoader::onHandlePropTypeColor3(pNode, pParent, pPropertyName, pColor3B, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_OPACITY) == 0) {
((Label *)pNode)->setOpacity(pByte);
} else {
NodeLoader::onHandlePropTypeByte(pNode, pParent, pPropertyName, pByte, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_BLENDFUNC) == 0) {
((Label *)pNode)->setBlendFunc(pBlendFunc);
} else {
NodeLoader::onHandlePropTypeBlendFunc(pNode, pParent, pPropertyName, pBlendFunc, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeFontTTF(Node * pNode, Node * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_FONTNAME) == 0) {
((Label *)pNode)->setSystemFontName(pFontTTF);
} else {
NodeLoader::onHandlePropTypeFontTTF(pNode, pParent, pPropertyName, pFontTTF, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeText(Node * pNode, Node * pParent, const char * pPropertyName, const char * pText, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_STRING) == 0) {
((Label *)pNode)->setString(pText);
} else {
NodeLoader::onHandlePropTypeText(pNode, pParent, pPropertyName, pText, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeFloatScale(Node * pNode, Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_FONTSIZE) == 0) {
((Label *)pNode)->setSystemFontSize(pFloatScale);
} else {
NodeLoader::onHandlePropTypeFloatScale(pNode, pParent, pPropertyName, pFloatScale, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_HORIZONTALALIGNMENT) == 0) {
((Label *)pNode)->setHorizontalAlignment(TextHAlignment(pIntegerLabeled));
} else if(strcmp(pPropertyName, PROPERTY_VERTICALALIGNMENT) == 0) {
((Label *)pNode)->setVerticalAlignment(TextVAlignment(pIntegerLabeled));
} else {
NodeLoader::onHandlePropTypeFloatScale(pNode, pParent, pPropertyName, pIntegerLabeled, ccbReader);
}
}
void LabelTTFLoader::onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size size, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_DIMENSIONS) == 0) {
((Label *)pNode)->setDimensions(size.width,size.height);
} else {
NodeLoader::onHandlePropTypeSize(pNode, pParent, pPropertyName, size, ccbReader);
}
}
}
| [
"[email protected]"
] | |
18d1b66d4a478791b7ebc4d2fb82e4aa7f494e61 | cc9aa1ccfe8b6a42c26d5c053e00c4a74ac6310e | /tests/05-texcube/texcube.cpp | e860890c11a6ba6c8a43929fc3642fbf3a87a2d5 | [
"MIT"
] | permissive | kochol/ariyana | 7bc5f8a8ce0bef97b347dbc23c8f894b7925fdd3 | 8c950f065f0240ebf1d5c716dee00578f0218c69 | refs/heads/master | 2022-07-27T14:45:53.912554 | 2022-07-06T13:10:30 | 2022-07-06T13:10:30 | 187,961,918 | 83 | 3 | MIT | 2021-11-06T17:58:39 | 2019-05-22T04:19:03 | C++ | UTF-8 | C++ | false | false | 1,793 | cpp | #include "gfx/gfx.hpp"
#include "gfx/Application.hpp"
#include "en/World.hpp"
#include "3d/RenderSystem.hpp"
#include "3d/SceneSystem.hpp"
#include "3d/Camera.hpp"
#include "3d/BoxShape.hpp"
#include "fs_local/FileSystemLocal.hpp"
#include "io/FileSystem.hpp"
class TexCubeApp : public ari::Application
{
public:
~TexCubeApp() = default;
ari::gfx::GfxSetup* GetGfxSetup() override
{
return &m_setup;
}
void OnInit() override
{
// Add systems
m_world.AddSystem(&m_renderer);
m_world.AddSystem(&m_scene_mgr);
ari::io::RegisterFileSystem("file", &m_file_system_local);
// Create entity and add box and camera
ari::en::EntityHandle entity = m_world.CreateEntity();
auto camera = m_world.CreateComponent<ari::en::Camera, ari::en::Node3D>();
camera.Component->Position.x = 3.f;
camera.Component->Position.y = 3.f;
camera.Component->Position.z = 3.f;
camera.Component->Target.z = 0.0f;
m_world.AddDerivedComponent<ari::en::Camera, ari::en::Node3D>(entity, camera);
auto box = m_world.CreateComponent<ari::en::BoxShape, ari::en::Node3D>();
box.Component->Texture = ari::gfx::LoadTexture("res:baboon.png");
m_pBox = box.Component;
m_world.AddDerivedComponent<ari::en::BoxShape, ari::en::Node3D>(entity, box);
}
void OnFrame(float _elapsedTime) override
{
m_pBox->Rotation.x += 0.3f * _elapsedTime;
m_pBox->Rotation.y += 0.3f * _elapsedTime;
m_world.Update(_elapsedTime);
}
void OnCleanup() override
{
}
void OnEvent(ari_event* event, ari::io::WindowHandle _window) override
{
}
private:
ari::gfx::GfxSetup m_setup;
ari::en::World m_world;
ari::en::RenderSystem m_renderer;
ari::en::SceneSystem m_scene_mgr;
ari::io::FileSystemLocal m_file_system_local;
ari::en::BoxShape * m_pBox = nullptr;
};
ARI_MAIN(TexCubeApp)
| [
"[email protected]"
] | |
e11c54252f4042ccf94ed58768423cce85c3a0b7 | 9e99ab6f88c2b947afa010d657cc8b12dec2cd94 | /benchmark/benchmark_academic/crossproduct_backend/benchmark_crossproduct_4th_backend.cpp | 46739e73f0d10cb270c1921f372c4bbcbdd1c97b | [
"MIT"
] | permissive | jxi24/Fastor | b89c7dfd6d80e893cedfa20918169db52546a251 | fbaa8053ad258791a3352addf1e08e28a459c3a1 | refs/heads/master | 2022-04-18T02:28:22.984687 | 2020-04-22T18:20:44 | 2020-04-22T18:20:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,029 | cpp | #include <Fastor/Fastor.h>
using namespace Fastor;
#define NITER 10000UL
template<typename T, size_t N>
inline void crossproduct_scalar(const T *FASTOR_RESTRICT a, const T *FASTOR_RESTRICT b, T *FASTOR_RESTRICT out) {
constexpr T levi_civita[27] = { 0., 0., 0., 0., 0., -1., 0., 1., 0., 0., 0., 1., 0., 0.,
0., -1., 0., 0., 0., -1., 0., 1., 0., 0., 0., 0., 0.};
constexpr size_t size = N;
for (size_t i=0; i<N; ++i)
for (size_t j=0; j<N; ++j)
for (size_t k=0; k<N; ++k)
for (size_t I=0; I<N; ++I)
for (size_t J=0; J<N; ++J)
for (size_t K=0; K<N; ++K)
for (size_t p=0; p<N; ++p)
for (size_t P=0; P<N; ++P)
for (size_t q=0; q<N; ++q)
for (size_t Q=0; Q<N; ++Q)
out[p*size*size*size*size*size+P*size*size*size*size+i*size*size*size+I*size*size+q*size+Q] += \
levi_civita[i*size*size+j*size+k]*levi_civita[I*size*size+J*size+K]*\
a[p*size*size*size+P*size*size+j*size+J]*b[k*size*size*size+K*size*size+q*size+Q];
}
template<typename T, size_t N>
void iterate_over_scalar(const T *FASTOR_RESTRICT a, const T *FASTOR_RESTRICT b, T *FASTOR_RESTRICT out) {
size_t iter = 0;
for (; iter<NITER; ++iter) {
crossproduct_scalar<T,N>(a,b,out);
unused(a); unused(b); unused(out);
// further hack for gcc, seemingly doesn't hurt performance of _crossproduct
out[1] += out[2];
}
}
template<typename T, size_t N>
void iterate_over_fastor(const T *FASTOR_RESTRICT a, const T *FASTOR_RESTRICT b, T *FASTOR_RESTRICT out) {
size_t iter = 0;
for (; iter<NITER; ++iter) {
_crossproduct<T,N,N,N,N,N,N,N,N>(a,b,out);
unused(a); unused(b); unused(out);
// // further hack for gcc, seemingly doesn't hurt performance of _crossproduct
out[1] += out[2];
}
}
template<typename T, size_t M, size_t N, size_t P, size_t Q>
void run() {
T *a = static_cast<T*>(_mm_malloc(sizeof(T) * M*N*P*Q, 32));
T *b = static_cast<T*>(_mm_malloc(sizeof(T) * M*N*P*Q, 32));
T *out = static_cast<T*>(_mm_malloc(sizeof(T) * M*N*P*Q * 9, 32));
std::iota(a,a+M*N*P*Q,0);
std::iota(b,b+M*N*P*Q,0);
double time0, time1;
std::tie(time0,std::ignore) = rtimeit(static_cast<void (*)(const T*, const T*, T*)>(&iterate_over_scalar<T,N>),a,b,out);
std::tie(time1,std::ignore) = rtimeit(static_cast<void (*)(const T*, const T*, T*)>(&iterate_over_fastor<T,N>),a,b,out);
print(time0,time1);
print("\n");
_mm_free(a);
_mm_free(b);
_mm_free(out);
}
int main() {
print("Single precision benchmark");
run<float,3,3,3,3>();
print("Double precision benchmark");
run<double,3,3,3,3>();
return 0;
} | [
"[email protected]"
] | |
e508b5344b188f9992a5f85cfeb2a639ca78579f | 3b3e5db80d59e7db216801b220e27c7f194d8e65 | /ch_13/exercises_1316.cpp | 1d374bbd5c25f9366aa2c7dd18ddeb03acd2da0d | [] | no_license | teirm/cpp_primer | f93e8296f9582a2738691155c77e01ce0eef50d8 | 29af7f91a1256050a23817f2716d5a95c49baea8 | refs/heads/master | 2021-01-13T03:24:58.887260 | 2017-07-02T16:45:03 | 2017-07-02T16:45:03 | 77,570,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | /* Exercises 13.1.6 */
#include <string>
#include <iostream>
using namespace std;
class Employee {
public:
Employee(string s):name(s), myId(++id) { cout << "Basic Constructor" << endl;}
Employee(Employee &e):name(e.name), myId(++id) { cout << "Copy constructor" << endl; }
Employee& operator=(Employee &e);
int getId() { return this->myId; }
private:
string name;
int myId;
static int id;
};
// Need to init the static variable
int Employee::id = 0;
Employee& Employee::operator=(Employee &e)
{
cout << "In = " << endl;
this->name = e.name;
this->myId = e.myId;
return *this;
}
int main()
{
Employee head("Bob");
Employee vice(head);
Employee fish("doggos");
fish = head;
cout << "Head id: " << head.getId() << endl;
cout << "Vice id: " << vice.getId() << endl;
cout << "Fish id: " << fish.getId() << endl;
return 0;
}
| [
"[email protected]"
] | |
28e03907b4e137f95295feca6d615faefd8d6271 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5662291475300352_0/C++/gabrielinelus/main.cpp | b50a8897da4849ed40b23cebb6e14f182e4fc10b | [] | 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 | UTF-8 | C++ | false | false | 797 | cpp | #include <cstdio>
#include <algorithm>
#define eps 0.0001
using namespace std;
int N;
double t1,t2,d1,d2;
int Solve()
{
scanf("%d",&N);
long long a,b,c;
if(N == 1)
return 0;
scanf("%lld%lld%lld",&a,&b,&c);
t1 = c;
d1 = a;
scanf("%lld%lld%lld",&a,&b,&c);
t2 = c;
d2 = a;
if(d1 > d2)
{
swap(t1,t2);
swap(d1,d2);
}
t1 = t1 * (360.0-d1*1.0)/360.0;
t2 = t2*(360 + 360 - d2*1.0)/360.0;
if(t1 + eps < t2)
return 0;
return 1;
}
int main()
{
freopen("C.in","r",stdin);
freopen("C.out","w",stdout);
int tst;
scanf("%d",&tst);
for(int i = 1; i <= tst; ++i)
{
printf("Case #%d: %d\n",i,Solve());
}
return 0;
}
| [
"[email protected]"
] | |
7c53f2eefe7b44eef62ada0529d5a074c9ce676d | f3a52a8832519729d65c5c3c436db2000217703c | /Source/FSD/Public/FriendlyHealthComponent.h | d6c80fb69bab8b2501c07c9ce474870cd34a015a | [] | no_license | NicolasAubinet/virtual-rock-galactic | 50be56c6548cfd44b3187cb41e4e03847b2093e7 | e82ce900f1f88c7db0abdb1d69c2de31650ca628 | refs/heads/main | 2023-07-22T08:04:59.552029 | 2023-07-15T08:16:22 | 2023-07-15T08:16:22 | 425,605,229 | 22 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | h | #pragma once
#include "CoreMinimal.h"
#include "HealthComponent.h"
#include "FriendlyHealthComponent.generated.h"
class UParticleSystem;
UCLASS(Blueprintable, ClassGroup=Custom, meta=(BlueprintSpawnableComponent))
class UFriendlyHealthComponent : public UHealthComponent {
GENERATED_BODY()
public:
protected:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float MaxHealth;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float FriendlyFireModifier;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float NeutralDamageModifier;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float BigHitDamageModifier;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float BigHitDamageReductionThreshold;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
UParticleSystem* GenericImpactParticles;
public:
UFriendlyHealthComponent();
//UFUNCTION(BlueprintCallable, BlueprintPure)
float GetMaxHealth() const;
};
| [
"[email protected]"
] |
Subsets and Splits