hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dd79134f524c1814c3c0b766e319640d6e358297 | 3,301 | cpp | C++ | libraries/ArduinoJson/test/JsonArray/add.cpp | tarontop/IRmqtt | 5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8 | [
"MIT"
] | null | null | null | libraries/ArduinoJson/test/JsonArray/add.cpp | tarontop/IRmqtt | 5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8 | [
"MIT"
] | 1 | 2020-01-09T07:07:44.000Z | 2020-01-09T07:07:44.000Z | libraries/ArduinoJson/test/JsonArray/add.cpp | tarontop/IRmqtt | 5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8 | [
"MIT"
] | null | null | null | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("JsonArray::add()") {
DynamicJsonDocument doc;
JsonArray _array = doc.to<JsonArray>();
SECTION("int") {
_array.add(123);
REQUIRE(123 == _array[0].as<int>());
REQUIRE(_array[0].is<int>());
REQUIRE(_array[0].is<double>());
}
SECTION("double") {
_array.add(123.45);
REQUIRE(123.45 == _array[0].as<double>());
REQUIRE(_array[0].is<double>());
REQUIRE_FALSE(_array[0].is<bool>());
}
SECTION("bool") {
_array.add(true);
REQUIRE(true == _array[0].as<bool>());
REQUIRE(_array[0].is<bool>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("const char*") {
const char* str = "hello";
_array.add(str);
REQUIRE(str == _array[0].as<std::string>());
REQUIRE(_array[0].is<const char*>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("nested array") {
DynamicJsonDocument doc2;
JsonArray arr = doc2.to<JsonArray>();
_array.add(arr);
REQUIRE(arr == _array[0].as<JsonArray>());
REQUIRE(_array[0].is<JsonArray>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("nested object") {
DynamicJsonDocument doc2;
JsonObject obj = doc2.to<JsonObject>();
_array.add(obj);
REQUIRE(obj == _array[0].as<JsonObject>());
REQUIRE(_array[0].is<JsonObject>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("array subscript") {
const char* str = "hello";
DynamicJsonDocument doc2;
JsonArray arr = doc2.to<JsonArray>();
arr.add(str);
_array.add(arr[0]);
REQUIRE(str == _array[0]);
}
SECTION("object subscript") {
const char* str = "hello";
DynamicJsonDocument doc2;
JsonObject obj = doc2.to<JsonObject>();
obj["x"] = str;
_array.add(obj["x"]);
REQUIRE(str == _array[0]);
}
SECTION("should not duplicate const char*") {
_array.add("world");
const size_t expectedSize = JSON_ARRAY_SIZE(1);
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate char*") {
_array.add(const_cast<char*>("world"));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6;
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate std::string") {
_array.add(std::string("world"));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6;
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should not duplicate serialized(const char*)") {
_array.add(serialized("{}"));
const size_t expectedSize = JSON_ARRAY_SIZE(1);
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate serialized(char*)") {
_array.add(serialized(const_cast<char*>("{}")));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 2;
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate serialized(std::string)") {
_array.add(serialized(std::string("{}")));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 2;
REQUIRE(expectedSize == doc.memoryUsage());
}
SECTION("should duplicate serialized(std::string)") {
_array.add(serialized(std::string("\0XX", 3)));
const size_t expectedSize = JSON_ARRAY_SIZE(1) + 3;
REQUIRE(expectedSize == doc.memoryUsage());
}
}
| 25.992126 | 59 | 0.633141 | tarontop |
dd7ff997434a60045ef2756e488b922394b5f920 | 2,285 | cc | C++ | cc_mocks/socket.cc | piskorzj/node-packet-socket | 151d985dced6fbbd3619e46572b9a6006a689d7a | [
"MIT"
] | 7 | 2017-02-28T14:07:10.000Z | 2019-10-08T18:49:42.000Z | cc_mocks/socket.cc | piskorzj/node-packet-socket | 151d985dced6fbbd3619e46572b9a6006a689d7a | [
"MIT"
] | 2 | 2017-04-02T12:24:00.000Z | 2017-06-08T23:03:00.000Z | cc_mocks/socket.cc | piskorzj/node-packet-socket | 151d985dced6fbbd3619e46572b9a6006a689d7a | [
"MIT"
] | null | null | null | #include "CppUTestExt/MockSupport.h"
#include "socket.hh"
#include <stdexcept>
Socket::Socket(const char * device) {
mock().actualCall("socket_constructor")
.withStringParameter("device", device);
if(!mock().returnBoolValueOrDefault(true)) {
throw std::runtime_error("forced creation failure");
}
}
Socket::~Socket() {}
int Socket::get_descriptor(void) {
return mock().actualCall("get_descriptor").returnIntValue();
}
int Socket::send_message(const unsigned char *destination_address,
const char *message, int message_length) {
mock().actualCall("send_message")
.withMemoryBufferParameter("destination_address", destination_address, ETHER_ADDR_LEN)
.withMemoryBufferParameter("message", (const unsigned char*)message, message_length)
.withIntParameter("message_length", message_length);
int return_value = mock().returnIntValueOrDefault(6);
if(return_value == -1) {
throw std::runtime_error("forced send_message failure");
}
return return_value;
}
int Socket::receive_message(unsigned char *source_address,
unsigned char *destination_address,
char *buffer, int buffer_size) {
mock().actualCall("receive_message")
.withOutputParameter("source_address", source_address)
.withOutputParameter("destination_address", destination_address)
.withOutputParameter("buffer", buffer)
.withIntParameter("buffer_size", buffer_size);
int return_value = mock().returnIntValueOrDefault(6);
if(return_value == -1) {
throw std::runtime_error("forced receive_message failure");
}
return return_value;
}
void Socket::add_membership(Socket::MembershipType type,
const unsigned char *multicast_address) {
mock().actualCall("add_membership")
.withIntParameter("type", type)
.withMemoryBufferParameter("multicast_address", multicast_address, ETHER_ADDR_LEN);
if(!mock().returnBoolValueOrDefault(true)) {
throw std::runtime_error("forced add_membership failure");
}
}
void Socket::drop_membership(Socket::MembershipType type,
const unsigned char *multicast_address) {
mock().actualCall("drop_membership")
.withIntParameter("type", type)
.withMemoryBufferParameter("multicast_address", multicast_address, ETHER_ADDR_LEN);
if(!mock().returnBoolValueOrDefault(true)) {
throw std::runtime_error("forced drop_membership failure");
}
}
| 34.621212 | 89 | 0.76849 | piskorzj |
dd832ab319ce4878ad080464c4635919732aee27 | 1,687 | hpp | C++ | jsonrpc/serverMgr.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | null | null | null | jsonrpc/serverMgr.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | null | null | null | jsonrpc/serverMgr.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | 2 | 2019-12-26T13:54:29.000Z | 2020-10-31T10:19:13.000Z | /*
* serverMgr.hpp
*
* Created on: Oct 8, 2015
* Author: romeo
*/
#ifndef INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_
#define INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_
#include "flexibity/jsonrpc/jsonRpcSerial.hpp"
#include "flexibity/jsonrpc/jsonRpcWebsocketClient.hpp"
#include "flexibity/genericMgr.hpp"
namespace Flexibity{
class serverMgr:
public genericMgr<jsonRpcTransport::sPtr>{
public:
static constexpr const char* uriOption = "uri";
static constexpr const char* nameOption = "name";
static constexpr const char* serialPrefix = "serial://";
static constexpr const char* wsPrefix = "ws://";
static constexpr const char* wssPrefix = "wss://";
serverMgr(const Json::Value& cfg, serialPortMgr::sPtr pm){
ILOG_INIT();
populateItems(cfg, [&](const Json::Value& iCfg){
return serverFactory(iCfg, pm);
});
}
static jsonRpcTransport::sPtr serverFactory(const Json::Value& iCfg, serialPortMgr::sPtr pm){
string uri = iCfg[uriOption].asString();
string name = iCfg[nameOption].asString();
//setInstanceName(name);
auto resource = getResource(uri, serialPrefix);
if (resource.length() > 0) {
auto srv = make_shared<jsonRpcSerial>(pm, resource);
srv->setInstanceName(name);
return srv;
}
resource = getResource(uri, wsPrefix);
if (resource.length() > 0) {
return make_shared<jsonRpcWebsocketClient>(iCfg);
}
//TODO: wss scheme
return make_shared<jsonRpcTransport>();
}
static const string getResource(const string& uri, const string& prefix){
auto pos = uri.find(prefix);
if(pos == 0){
return string(uri, prefix.length());
}
return "";
}
};
}
#endif /* INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ */
| 23.109589 | 94 | 0.713693 | flexibity-team |
dd8497defaf062ee6fc3a88753ba4c155c430632 | 717 | hpp | C++ | include/SerialFiller/Crc16Ccitt1021.hpp | gbmhunter/SerialFiller | d678acbf6d29de7042d48c6be8ecef556bb6d857 | [
"MIT"
] | 9 | 2019-04-01T16:27:15.000Z | 2022-03-14T19:45:34.000Z | include/SerialFiller/Crc16Ccitt1021.hpp | gbmhunter/SerialFiller | d678acbf6d29de7042d48c6be8ecef556bb6d857 | [
"MIT"
] | 12 | 2017-06-18T05:06:36.000Z | 2018-01-30T21:55:39.000Z | include/SerialFiller/Crc16Ccitt1021.hpp | mbedded-ninja/SerialFiller | d678acbf6d29de7042d48c6be8ecef556bb6d857 | [
"MIT"
] | 3 | 2019-09-07T16:56:57.000Z | 2022-02-08T03:25:28.000Z | ///
/// \file Crc16Ccitt1021.hpp
/// \author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja)
/// \edited n/a
/// \created 2017-06-10
/// \last-modified 2018-01-25
/// \brief Contains the Crc16Ccitt1021 class.
/// \details
/// See README.rst in root dir for more info.
#ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
#define MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
// Local includes
#include "SerialFiller/SerialFiller.hpp"
namespace mn {
namespace SerialFiller {
class Crc16Ccitt1021 {
public:
static uint16_t Calc(ByteArray data);
};
} // namespace SerialFiller
} // namespace mn
#endif // #ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_ | 24.724138 | 72 | 0.680614 | gbmhunter |
dd849dbe0685f69864b08ab75120ea54905c2858 | 2,024 | cpp | C++ | DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Minimum Cost of ropes
=====================
There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost.
Example 1:
Input:
n = 4
arr[] = {4, 3, 2, 6}
Output:
29
Explanation:
For example if we are given 4
ropes of lengths 4, 3, 2 and 6. We can
connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3.
Now we have three ropes of lengths 4, 6
and 5.
2) Now connect ropes of lengths 4 and 5.
Now we have two ropes of lengths 6 and 9.
3) Finally connect the two ropes and all
ropes have connected.
Total cost for connecting all ropes is 5
+ 9 + 15 = 29. This is the optimized cost
for connecting ropes. Other ways of
connecting ropes would always have same
or more cost. For example, if we connect
4 and 6 first (we get three strings of 3,
2 and 10), then connect 10 and 3 (we get
two strings of 13 and 2). Finally we
connect 13 and 2. Total cost in this way
is 10 + 13 + 15 = 38.
Example 2:
Input:
n = 5
arr[] = {4, 2, 7, 6, 9}
Output:
62
Explanation:
First, connect ropes 4 and 2, which makes
the array {6,7,6,9}. Next, add ropes 6 and
6, which results in {12,7,9}. Then, add 7
and 9, which makes the array {12,16}. And
finally add these two which gives {28}.
Hence, the total cost is 6 + 12 + 16 +
28 = 62.
Your Task:
You don't need to read input or print anything. Your task isto complete the function minCost() which takes 2 arguments and returns the minimum cost.
Expected Time Complexity : O(nlogn)
Expected Auxilliary Space : O(n)
Constraints:
1 ≤ N ≤ 100000
1 ≤ arr[i] ≤ 106
*/
long long minCost(long long arr[], long long n)
{
priority_queue<long long, vector<long long>, greater<long long>> pq;
long long cost = 0;
for (int i = 0; i < n; ++i)
pq.push(arr[i]);
while (pq.size() > 1)
{
auto a = pq.top();
pq.pop();
auto b = pq.top();
pq.pop();
cost += (a + b);
pq.push(a + b);
}
return cost;
} | 25.948718 | 207 | 0.676877 | Akshad7829 |
dd8ef8e0c9f40df27ada5889ed871b1821998a93 | 12,579 | cpp | C++ | experiments/rmi_lookup.cpp | alhuan/analysis-rmi | be787ee9a02e04210d41af51c8a053f6dea575e9 | [
"Apache-2.0"
] | 9 | 2021-07-01T17:00:42.000Z | 2022-03-23T09:21:17.000Z | experiments/rmi_lookup.cpp | alhuan/analysis-rmi | be787ee9a02e04210d41af51c8a053f6dea575e9 | [
"Apache-2.0"
] | 1 | 2021-07-20T13:39:27.000Z | 2021-07-20T13:39:27.000Z | experiments/rmi_lookup.cpp | alhuan/analysis-rmi | be787ee9a02e04210d41af51c8a053f6dea575e9 | [
"Apache-2.0"
] | 1 | 2022-01-25T16:39:34.000Z | 2022-01-25T16:39:34.000Z | #include <chrono>
#include <random>
#include "argparse/argparse.hpp"
#include "rmi/models.hpp"
#include "rmi/rmi.hpp"
#include "rmi/util/fn.hpp"
#include "rmi/util/search.hpp"
using key_type = uint64_t;
using namespace std::chrono;
std::size_t s_glob; ///< global size_t variable
/**
* Measures lookup times of @p samples on a given @p Rmi and writes results to `std::cout`.
* @tparam Key key type
* @tparam Rmi RMI type
* @tparam Search search type
* @param keys on which the RMI is built
* @param n_models number of models in the second layer of the RMI
* @param samples for which the lookup time is measured
* @param n_reps number of repetitions
* @param dataset_name name of the dataset
* @param layer1 model type of the first layer
* @param layer2 model type of the second layer
* @param bound_type used by the RMI
* @param search used by the RMI for correction prediction errors
*/
template<typename Key, typename Rmi, typename Search>
void experiment(const std::vector<key_type> &keys,
const std::size_t n_models,
const std::vector<key_type> &samples,
const std::size_t n_reps,
const std::string dataset_name,
const std::string layer1,
const std::string layer2,
const std::string bound_type,
const std::string search)
{
using rmi_type = Rmi;
auto search_fn = Search();
// Build RMI.
rmi_type rmi(keys, n_models);
// Perform n_reps runs.
for (std::size_t rep = 0; rep != n_reps; ++rep) {
// Lookup time.
std::size_t lookup_accu = 0;
auto start = steady_clock::now();
for (std::size_t i = 0; i != samples.size(); ++i) {
auto key = samples.at(i);
auto range = rmi.search(key);
auto pos = search_fn(keys.begin() + range.lo, keys.begin() + range.hi, keys.begin() + range.pos, key);
lookup_accu += std::distance(keys.begin(), pos);
}
auto stop = steady_clock::now();
auto lookup_time = duration_cast<nanoseconds>(stop - start).count();
s_glob = lookup_accu;
// Report results.
// Dataset
std::cout << dataset_name << ','
<< keys.size() << ','
// Index
<< layer1 << ','
<< layer2 << ','
<< n_models << ','
<< bound_type << ','
<< search << ','
<< rmi.size_in_bytes() << ','
// Experiment
<< rep << ','
<< samples.size() << ','
// Results
<< lookup_time << ','
// Checksums
<< lookup_accu << std::endl;
} // reps
}
/**
* @brief experiment function pointer
*/
typedef void (*exp_fn_ptr)(const std::vector<key_type>&,
const std::size_t,
const std::vector<key_type>&,
const std::size_t,
const std::string,
const std::string,
const std::string,
const std::string,
const std::string);
/**
* RMI configuration that holds the string representation of model types of layer 1 and layer 2, error bound type, and
* search algorithm.
*/
struct Config {
std::string layer1;
std::string layer2;
std::string bound_type;
std::string search;
};
/**
* Comparator class for @p Config objects.
*/
struct ConfigCompare {
bool operator() (const Config &lhs, const Config &rhs) const {
if (lhs.layer1 != rhs.layer1) return lhs.layer1 < rhs.layer1;
if (lhs.layer2 != rhs.layer2) return lhs.layer2 < rhs.layer2;
if (lhs.bound_type != rhs.bound_type) return lhs.bound_type < rhs.bound_type;
return lhs.search < rhs.search;
}
};
#define ENTRIES(L1, L2, LT1, LT2) \
{ {#L1, #L2, "none", "binary"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, BinarySearch> }, \
{ {#L1, #L2, "labs", "binary"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, BinarySearch> }, \
{ {#L1, #L2, "lind", "binary"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, BinarySearch> }, \
{ {#L1, #L2, "gabs", "binary"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, BinarySearch> }, \
{ {#L1, #L2, "gind", "binary"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, BinarySearch> }, \
{ {#L1, #L2, "none", "model_biased_binary"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \
{ {#L1, #L2, "labs", "model_biased_binary"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \
{ {#L1, #L2, "lind", "model_biased_binary"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \
{ {#L1, #L2, "gabs", "model_biased_binary"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \
{ {#L1, #L2, "gind", "model_biased_binary"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \
{ {#L1, #L2, "none", "linear"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, LinearSearch> }, \
{ {#L1, #L2, "labs", "linear"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, LinearSearch> }, \
{ {#L1, #L2, "lind", "linear"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, LinearSearch> }, \
{ {#L1, #L2, "gabs", "linear"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, LinearSearch> }, \
{ {#L1, #L2, "gind", "linear"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, LinearSearch> }, \
{ {#L1, #L2, "none", "model_biased_linear"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \
{ {#L1, #L2, "labs", "model_biased_linear"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \
{ {#L1, #L2, "lind", "model_biased_linear"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \
{ {#L1, #L2, "gabs", "model_biased_linear"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \
{ {#L1, #L2, "gind", "model_biased_linear"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \
{ {#L1, #L2, "none", "exponential"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ExponentialSearch> }, \
{ {#L1, #L2, "labs", "exponential"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ExponentialSearch> }, \
{ {#L1, #L2, "lind", "exponential"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ExponentialSearch> }, \
{ {#L1, #L2, "gabs", "exponential"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ExponentialSearch> }, \
{ {#L1, #L2, "gind", "exponential"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ExponentialSearch> }, \
{ {#L1, #L2, "none", "model_biased_exponential"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \
{ {#L1, #L2, "labs", "model_biased_exponential"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \
{ {#L1, #L2, "lind", "model_biased_exponential"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \
{ {#L1, #L2, "gabs", "model_biased_exponential"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \
{ {#L1, #L2, "gind", "model_biased_exponential"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \
static std::map<Config, exp_fn_ptr, ConfigCompare> exp_map {
ENTRIES(linear_regression, linear_regression, rmi::LinearRegression, rmi::LinearRegression)
ENTRIES(linear_regression, linear_spline, rmi::LinearRegression, rmi::LinearSpline)
ENTRIES(linear_spline, linear_regression, rmi::LinearSpline, rmi::LinearRegression)
ENTRIES(linear_spline, linear_spline, rmi::LinearSpline, rmi::LinearSpline)
ENTRIES(cubic_spline, linear_regression, rmi::CubicSpline, rmi::LinearRegression)
ENTRIES(cubic_spline, linear_spline, rmi::CubicSpline, rmi::LinearSpline)
ENTRIES(radix, linear_regression, rmi::Radix<key_type>, rmi::LinearRegression)
ENTRIES(radix, linear_spline, rmi::Radix<key_type>, rmi::LinearSpline)
}; ///< Map that assigns an experiment function pointer to RMI configurations.
#undef ENTRIES
/**
* Triggers measurement of lookup times for an RMI configuration provided via command line arguments.
* @param argc arguments counter
* @param argv arguments vector
*/
int main(int argc, char *argv[])
{
// Initialize argument parser.
argparse::ArgumentParser program(argv[0], "0.1");
// Define arguments.
program.add_argument("filename")
.help("path to binary file containing uin64_t keys");
program.add_argument("layer1")
.help("layer1 model type, either linear_regression, linear_spline, cubic_spline, or radix.");
program.add_argument("layer2")
.help("layer2 model type, either linear_regression, linear_spline, or cubic_spline.");
program.add_argument("n_models")
.help("number of models on layer2, power of two is recommended.")
.action([](const std::string &s) { return std::stoul(s); });
program.add_argument("bound_type")
.help("type of error bounds used, either none, labs, lind, gabs, or gind.");
program.add_argument("search")
.help("search algorithm for error correction, either binary, model_biased_binary, exponential, model_biased_exponential, linear, or model_biased_linear.");
program.add_argument("-n", "--n_reps")
.help("number of experiment repetitions")
.default_value(std::size_t(3))
.action([](const std::string &s) { return std::stoul(s); });
program.add_argument("-s", "--n_samples")
.help("number of sampled lookup keys")
.default_value(std::size_t(1'000'000))
.action([](const std::string &s) { return std::stoul(s); });
program.add_argument("--header")
.help("output csv header")
.default_value(false)
.implicit_value(true);
// Parse arguments.
try {
program.parse_args(argc, argv);
}
catch (const std::runtime_error &err) {
std::cout << err.what() << '\n' << program;
exit(EXIT_FAILURE);
}
// Read arguments.
const auto filename = program.get<std::string>("filename");
const auto dataset_name = split(filename, '/').back();
const auto layer1 = program.get<std::string>("layer1");
const auto layer2 = program.get<std::string>("layer2");
const auto n_models = program.get<std::size_t>("n_models");
const auto bound_type = program.get<std::string>("bound_type");
const auto search = program.get<std::string>("search");
const auto n_reps = program.get<std::size_t>("-n");
const auto n_samples = program.get<std::size_t>("-s");
// Load keys.
auto keys = load_data<key_type>(filename);
// Sample keys.
uint64_t seed = 42;
std::mt19937 gen(seed);
std::uniform_int_distribution<> distrib(0, keys.size() - 1);
std::vector<key_type> samples;
samples.reserve(n_samples);
for (std::size_t i = 0; i != n_samples; ++i)
samples.push_back(keys[distrib(gen)]);
// Lookup experiment.
Config config{layer1, layer2, bound_type, search};
if (exp_map.find(config) == exp_map.end()) {
std::cerr << "Error: " << layer1 << ',' << layer2 << ',' << bound_type << ',' << search << " is not a valid RMI configuration." << std::endl;
exit(EXIT_FAILURE);
}
exp_fn_ptr exp_fn = exp_map[config];
// Output header.
if (program["--header"] == true)
std::cout << "dataset,"
<< "n_keys,"
<< "layer1,"
<< "layer2,"
<< "n_models,"
<< "bounds,"
<< "search,"
<< "size_in_bytes,"
<< "rep,"
<< "n_samples,"
<< "lookup_time,"
<< "lookup_accu,"
<< std::endl;
// Run experiment.
(*exp_fn)(keys, n_models, samples, n_reps, dataset_name, layer1, layer2, bound_type, search);
exit(EXIT_SUCCESS);
}
| 45.908759 | 163 | 0.608156 | alhuan |
dd9a19698deae1729c3f357c3c054c787efda000 | 2,605 | hpp | C++ | Source/ReplicantHook/ReplicantHook.hpp | Asiern/ReplicantHook | 63cbfd361d738dc37177c8fcf6e2657dc20bd9aa | [
"MIT"
] | 11 | 2021-04-25T15:29:29.000Z | 2022-02-27T09:49:54.000Z | Source/ReplicantHook/ReplicantHook.hpp | Asiern/ReplicantHook | 63cbfd361d738dc37177c8fcf6e2657dc20bd9aa | [
"MIT"
] | 6 | 2021-04-26T07:39:52.000Z | 2021-10-06T14:12:09.000Z | Source/ReplicantHook/ReplicantHook.hpp | Asiern/ReplicantHook | 63cbfd361d738dc37177c8fcf6e2657dc20bd9aa | [
"MIT"
] | 1 | 2021-08-28T22:13:50.000Z | 2021-08-28T22:13:50.000Z | #pragma once
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
#include "Offsets.hpp"
#include <map>
class ReplicantHook
{
private:
DWORD _pID;
uintptr_t _baseAddress;
uintptr_t actorPlayable;
bool _hooked;
offsets _offsets;
int _version;
std::map<std::string, uintptr_t> _inventory;
int gold;
std::string zone;
std::string name;
int health;
float magic;
int level;
double playtime;
float x;
float y;
float z;
DWORD _getProcessID(void);
uintptr_t _getModuleBaseAddress(DWORD procId, const wchar_t* modName);
void _hook(void);
void _unHook(void);
void _patch(BYTE* destination, BYTE* src, unsigned int size);
template <typename T>
T readMemory(uintptr_t address);
template <typename T>
void writeMemory(uintptr_t address, T value);
std::string readMemoryString(uintptr_t address);
void writeMemoryString(uintptr_t address, std::string value);
void loadInventory();
uintptr_t getItemAddress(std::string name);
public:
ReplicantHook(int version);
~ReplicantHook();
DWORD getProcessID(void);
uintptr_t getBaseAddress(void);
void start(void);
void stop(void);
void hookStatus(void);
void update();
//Getters
bool isHooked(void);
int getGold();
std::string getZone();
std::string getName();
int getHealth();
float getMagic();
int getLevel();
double getPlaytime();
float getX();
float getY();
float getZ();
//Setters
void setGold(int value);
void setZone(std::string value);
void setName(std::string value);
void setHealth(int value);
void setMagic(float value);
void setLevel(int value);
void setPlaytime(double value);
void setX(float value);
void setY(float value);
void setZ(float value);
void setPosition(float x, float y, float z);
//Cheats
void InfiniteHealth(bool enabled);
void InfiniteMagic(bool enabled);
//Models
void setActorModel(std::string model);
std::string getActorModel();
//Inventory
std::map<std::string, uintptr_t> getInventory(void);
int addItem(std::string name, int quantity);
int removeItem(std::string name);
};
template<typename T>
inline T ReplicantHook::readMemory(uintptr_t address)
{
T value;
HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, this->_pID);
ReadProcessMemory(pHandle, (LPCVOID)(address), &value, sizeof(value), NULL);
CloseHandle(pHandle); //Close handle to prevent memory leaks
return value;
}
template<typename T>
inline void ReplicantHook::writeMemory(uintptr_t address, T value)
{
HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, NULL, this->_pID);
WriteProcessMemory(pHandle, (LPVOID)(address), &value, sizeof(value), NULL);
CloseHandle(pHandle);
}
| 23.053097 | 77 | 0.74357 | Asiern |
dda483d94ce9cfa55a437bb7b8b995b0db566d45 | 358 | hpp | C++ | src/engineModules/eFont.hpp | psjuan97/JamEngine | 20d98e6f3e962a518cc519fecd90205a52aba249 | [
"MIT"
] | 3 | 2019-09-30T08:23:03.000Z | 2020-07-18T09:09:56.000Z | src/engineModules/eFont.hpp | psjuan97/JamEngine | 20d98e6f3e962a518cc519fecd90205a52aba249 | [
"MIT"
] | 1 | 2019-09-28T14:17:05.000Z | 2019-09-28T14:17:05.000Z | src/engineModules/eFont.hpp | psjuan97/JamEngine | 20d98e6f3e962a518cc519fecd90205a52aba249 | [
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <SDL2/SDL_ttf.h>
/////////
/// TODO
/// liberar la fuente en el destructor
class eFont{
public:
eFont(const char* str, int size);
~eFont();
inline TTF_Font* getSDLFont() const {
return sdl_font;
};
private:
TTF_Font* sdl_font = nullptr;
}; | 16.272727 | 45 | 0.539106 | psjuan97 |
dda5c67804d14f06cabfc9360bcb4c7d47d84892 | 286 | hpp | C++ | astronomy/solar_system_fingerprints.hpp | madman2003/Principia | c757f840f5278ca3480799cee297238697868283 | [
"MIT"
] | null | null | null | astronomy/solar_system_fingerprints.hpp | madman2003/Principia | c757f840f5278ca3480799cee297238697868283 | [
"MIT"
] | null | null | null | astronomy/solar_system_fingerprints.hpp | madman2003/Principia | c757f840f5278ca3480799cee297238697868283 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
namespace principia {
namespace astronomy {
constexpr std::uint64_t KSPStockSystemFingerprint = 0x54B6323B3376D6F3;
constexpr std::uint64_t KSPStabilizedSystemFingerprint = 0xB57B58F9CF757C62;
} // namespace astronomy
} // namespace principia
| 22 | 76 | 0.793706 | madman2003 |
ddb127e79811d14f6a32686dfbc2d5d990d73fbc | 15,108 | cpp | C++ | frontends/common/resolveReferences/resolveReferences.cpp | pierce-m/p4c | afe96cf5a658f7bf5e1b95a044c241d9afb13dc6 | [
"Apache-2.0"
] | null | null | null | frontends/common/resolveReferences/resolveReferences.cpp | pierce-m/p4c | afe96cf5a658f7bf5e1b95a044c241d9afb13dc6 | [
"Apache-2.0"
] | null | null | null | frontends/common/resolveReferences/resolveReferences.cpp | pierce-m/p4c | afe96cf5a658f7bf5e1b95a044c241d9afb13dc6 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "resolveReferences.h"
#include <sstream>
namespace P4 {
std::vector<const IR::IDeclaration*>*
ResolutionContext::resolve(IR::ID name, P4::ResolutionType type, bool previousOnly) const {
static std::vector<const IR::IDeclaration*> empty;
std::vector<const IR::INamespace*> toTry;
toTry = stack;
toTry.insert(toTry.end(), globals.begin(), globals.end());
for (auto it = toTry.rbegin(); it != toTry.rend(); ++it) {
const IR::INamespace* current = *it;
LOG2("Trying to resolve in " << current->toString());
if (current->is<IR::IGeneralNamespace>()) {
auto gen = current->to<IR::IGeneralNamespace>();
Util::Enumerator<const IR::IDeclaration*>* decls = gen->getDeclsByName(name);
switch (type) {
case P4::ResolutionType::Any:
break;
case P4::ResolutionType::Type: {
std::function<bool(const IR::IDeclaration*)> kindFilter =
[](const IR::IDeclaration* d) {
return d->is<IR::Type>();
};
decls = decls->where(kindFilter);
break;
}
case P4::ResolutionType::TypeVariable: {
std::function<bool(const IR::IDeclaration*)> kindFilter =
[](const IR::IDeclaration* d) {
return d->is<IR::Type_Var>(); };
decls = decls->where(kindFilter);
break;
}
default:
BUG("Unexpected enumeration value %1%", static_cast<int>(type));
}
if (previousOnly) {
std::function<bool(const IR::IDeclaration*)> locationFilter =
[name](const IR::IDeclaration* d) {
Util::SourceInfo nsi = name.srcInfo;
Util::SourceInfo dsi = d->getNode()->srcInfo;
bool before = dsi <= nsi;
LOG2("\tPosition test:" << dsi << "<=" << nsi << "=" << before);
return before;
};
decls = decls->where(locationFilter);
}
auto vector = decls->toVector();
if (!vector->empty()) {
LOG2("Resolved in " << current->getNode());
return vector;
} else {
continue;
}
} else {
auto simple = current->to<IR::ISimpleNamespace>();
auto decl = simple->getDeclByName(name);
if (decl == nullptr)
continue;
switch (type) {
case P4::ResolutionType::Any:
break;
case P4::ResolutionType::Type: {
if (!decl->is<IR::Type>())
continue;
break;
}
case P4::ResolutionType::TypeVariable: {
if (!decl->is<IR::Type_Var>())
continue;
break;
}
default:
BUG("Unexpected enumeration value %1%", static_cast<int>(type));
}
if (previousOnly) {
Util::SourceInfo nsi = name.srcInfo;
Util::SourceInfo dsi = decl->getNode()->srcInfo;
bool before = dsi <= nsi;
LOG2("\tPosition test:" << dsi << "<=" << nsi << "=" << before);
if (!before)
continue;
}
LOG2("Resolved in " << current->getNode());
auto result = new std::vector<const IR::IDeclaration*>();
result->push_back(decl);
return result;
}
}
return ∅
}
void ResolutionContext::done() {
pop(rootNamespace);
if (!stack.empty())
BUG("ResolutionContext::stack not empty");
}
const IR::IDeclaration*
ResolutionContext::resolveUnique(IR::ID name,
P4::ResolutionType type,
bool previousOnly) const {
auto decls = resolve(name, type, previousOnly);
if (decls->empty()) {
::error("Could not find declaration for %1%", name);
return nullptr;
}
if (decls->size() > 1) {
::error("Multiple matching declarations for %1%", name);
for (auto a : *decls)
::error("Candidate: %1%", a);
return nullptr;
}
return decls->at(0);
}
void ResolutionContext::dbprint(std::ostream& out) const {
out << "Context stack[" << stack.size() << "]" << std::endl;
for (auto it = stack.begin(); it != stack.end(); it++) {
const IR::INamespace* ns = *it;
const IR::Node* node = ns->getNode();
node->dbprint(out);
out << std::endl;
}
out << "Globals[" << stack.size() << "]" << std::endl;
for (auto it = globals.begin(); it != globals.end(); it++) {
const IR::INamespace* ns = *it;
const IR::Node* node = ns->getNode();
node->dbprint(out);
out << std::endl;
}
out << "----------" << std::endl;
}
/////////////////////////////////////////////////////
ResolveReferences::ResolveReferences(ReferenceMap* refMap,
bool checkShadow) :
refMap(refMap),
context(nullptr),
rootNamespace(nullptr),
anyOrder(false),
checkShadow(checkShadow) {
CHECK_NULL(refMap);
setName("ResolveReferences");
visitDagOnce = false;
}
void ResolveReferences::addToContext(const IR::INamespace* ns) {
LOG1("Adding to context " << ns);
if (context == nullptr)
BUG("No resolution context; did not start at P4Program?");
context->push(ns);
}
void ResolveReferences::addToGlobals(const IR::INamespace* ns) {
if (context == nullptr)
BUG("No resolution context; did not start at P4Program?");
context->addGlobal(ns);
}
void ResolveReferences::removeFromContext(const IR::INamespace* ns) {
LOG1("Removing from context " << ns);
if (context == nullptr)
BUG("No resolution context; did not start at P4Program?");
context->pop(ns);
}
ResolutionContext*
ResolveReferences::resolvePathPrefix(const IR::PathPrefix* prefix) const {
ResolutionContext* result = context;
if (prefix == nullptr)
return result;
if (prefix->absolute)
result = new ResolutionContext(rootNamespace);
for (IR::ID id : prefix->components) {
const IR::IDeclaration* decl = result->resolveUnique(id, ResolutionType::Any, !anyOrder);
if (decl == nullptr)
return nullptr;
const IR::Node* node = decl->getNode();
if (!node->is<IR::INamespace>()) {
::error("%1%: %2% is not a namespace", prefix, decl);
return nullptr;
}
result = new ResolutionContext(node->to<IR::INamespace>());
}
return result;
}
void ResolveReferences::resolvePath(const IR::Path* path, bool isType) const {
LOG1("Resolving " << path << " " << (isType ? "as type" : "as identifier"));
ResolutionContext* ctx = resolvePathPrefix(path->prefix);
ResolutionType k = isType ? ResolutionType::Type : ResolutionType::Any;
if (resolveForward.empty())
BUG("Empty resolveForward");
bool allowForward = resolveForward.back();
const IR::IDeclaration* decl = ctx->resolveUnique(path->name, k, !allowForward);
if (decl == nullptr) {
refMap->usedName(path->name.name);
return;
}
refMap->setDeclaration(path, decl);
}
void ResolveReferences::checkShadowing(const IR::INamespace*ns) const {
if (!checkShadow) return;
auto e = ns->getDeclarations();
while (e->moveNext()) {
const IR::IDeclaration* decl = e->getCurrent();
const IR::Node* node = decl->getNode();
auto prev = context->resolve(decl->getName(), ResolutionType::Any, !anyOrder);
if (prev->empty()) continue;
for (auto p : *prev) {
const IR::Node* pnode = p->getNode();
if (pnode == node) continue;
if (pnode->is<IR::Type_Method>() && node->is<IR::Type_Method>()) {
auto md = node->to<IR::Type_Method>();
auto mp = pnode->to<IR::Type_Method>();
if (md->parameters->size() != mp->parameters->size())
continue;
}
::warning("%1% shadows %2%", decl->getName(), p->getName());
}
}
}
Visitor::profile_t ResolveReferences::init_apply(const IR::Node* node) {
anyOrder = refMap->isV1();
if (!refMap->checkMap(node))
refMap->clear();
return Inspector::init_apply(node);
}
void ResolveReferences::end_apply(const IR::Node* node) {
refMap->updateMap(node);
}
/////////////////// visitor methods ////////////////////////
// visitor should be invoked here
bool ResolveReferences::preorder(const IR::P4Program* program) {
if (refMap->checkMap(program))
return false;
if (!resolveForward.empty())
BUG("Expected empty resolvePath");
resolveForward.push_back(anyOrder);
if (rootNamespace != nullptr)
BUG("Root namespace already set");
rootNamespace = program;
context = new ResolutionContext(rootNamespace);
return true;
}
void ResolveReferences::postorder(const IR::P4Program*) {
rootNamespace = nullptr;
context->done();
resolveForward.pop_back();
if (!resolveForward.empty())
BUG("Expected empty resolvePath");
context = nullptr;
LOG1("Reference map " << refMap);
}
bool ResolveReferences::preorder(const IR::PathExpression* path) {
resolvePath(path->path, false); return true; }
bool ResolveReferences::preorder(const IR::Type_Name* type) {
resolvePath(type->path, true); return true; }
bool ResolveReferences::preorder(const IR::P4Control *c) {
refMap->usedName(c->name.name);
addToContext(c);
addToContext(c->type->typeParameters);
addToContext(c->type->applyParams);
addToContext(c->constructorParams);
return true;
}
void ResolveReferences::postorder(const IR::P4Control *c) {
removeFromContext(c->constructorParams);
removeFromContext(c->type->applyParams);
removeFromContext(c->type->typeParameters);
removeFromContext(c);
checkShadowing(c);
}
bool ResolveReferences::preorder(const IR::P4Parser *c) {
refMap->usedName(c->name.name);
addToContext(c);
addToContext(c->type->typeParameters);
addToContext(c->type->applyParams);
addToContext(c->constructorParams);
return true;
}
void ResolveReferences::postorder(const IR::P4Parser *c) {
removeFromContext(c->constructorParams);
removeFromContext(c->type->applyParams);
removeFromContext(c->type->typeParameters);
removeFromContext(c);
checkShadowing(c);
}
bool ResolveReferences::preorder(const IR::Function* function) {
refMap->usedName(function->name.name);
addToContext(function->type->parameters);
return true;
}
void ResolveReferences::postorder(const IR::Function* function) {
removeFromContext(function->type->parameters);
}
bool ResolveReferences::preorder(const IR::P4Table* t) {
refMap->usedName(t->name.name);
addToContext(t->parameters);
return true;
}
void ResolveReferences::postorder(const IR::P4Table* t) {
removeFromContext(t->parameters);
}
bool ResolveReferences::preorder(const IR::TableProperties *p) {
addToContext(p);
return true;
}
void ResolveReferences::postorder(const IR::TableProperties *p) {
removeFromContext(p);
}
bool ResolveReferences::preorder(const IR::P4Action *c) {
refMap->usedName(c->name.name);
addToContext(c);
addToContext(c->parameters);
return true;
}
void ResolveReferences::postorder(const IR::P4Action *c) {
removeFromContext(c->parameters);
removeFromContext(c);
checkShadowing(c);
}
bool ResolveReferences::preorder(const IR::Type_Method *t) {
// Function return values in generic functions may depend on the type arguments:
// T f<T>()
// where T is declared *after* its first use
resolveForward.push_back(true);
if (t->typeParameters != nullptr)
addToContext(t->typeParameters);
addToContext(t->parameters);
return true;
}
void ResolveReferences::postorder(const IR::Type_Method *t) {
removeFromContext(t->parameters);
if (t->typeParameters != nullptr)
removeFromContext(t->typeParameters);
resolveForward.pop_back();
}
bool ResolveReferences::preorder(const IR::Type_Extern *t) {
refMap->usedName(t->name.name);
addToContext(t->typeParameters); return true; }
void ResolveReferences::postorder(const IR::Type_Extern *t) {
removeFromContext(t->typeParameters); }
bool ResolveReferences::preorder(const IR::ParserState *s) {
refMap->usedName(s->name.name);
// State references may be resolved forward
resolveForward.push_back(true);
addToContext(s);
return true;
}
void ResolveReferences::postorder(const IR::ParserState *s) {
removeFromContext(s);
resolveForward.pop_back();
checkShadowing(s);
}
bool ResolveReferences::preorder(const IR::Declaration_Errors *d) {
addToGlobals(d); return true; }
bool ResolveReferences::preorder(const IR::Declaration_MatchKind *d) {
addToGlobals(d); return true; }
bool ResolveReferences::preorder(const IR::Type_ArchBlock *t) {
resolveForward.push_back(anyOrder);
addToContext(t->typeParameters);
return true;
}
void ResolveReferences::postorder(const IR::Type_ArchBlock *t) {
refMap->usedName(t->name.name);
removeFromContext(t->typeParameters);
resolveForward.pop_back();
}
bool ResolveReferences::preorder(const IR::Type_StructLike *t)
{ refMap->usedName(t->name.name); addToContext(t); return true; }
void ResolveReferences::postorder(const IR::Type_StructLike *t)
{ removeFromContext(t); }
bool ResolveReferences::preorder(const IR::BlockStatement *b)
{ addToContext(b); return true; }
void ResolveReferences::postorder(const IR::BlockStatement *b)
{ removeFromContext(b); checkShadowing(b); }
bool ResolveReferences::preorder(const IR::Declaration_Instance *decl) {
refMap->usedName(decl->name.name);
if (decl->initializer != nullptr)
addToContext(decl->initializer);
return true;
}
void ResolveReferences::postorder(const IR::Declaration_Instance *decl) {
if (decl->initializer != nullptr)
removeFromContext(decl->initializer);
}
#undef PROCESS_NAMESPACE
} // namespace P4
| 32.560345 | 97 | 0.60458 | pierce-m |
ddb19031941d6712f7139733b6aaeda26c2f1e09 | 1,552 | cpp | C++ | Depth_Estimation_Pipeline/app/driver.cpp | jasonpilbrough/Mesh-Based-Depth-Estimation | fe82eab3b064c3fa6a543fa83f626e7d948d2335 | [
"MIT"
] | null | null | null | Depth_Estimation_Pipeline/app/driver.cpp | jasonpilbrough/Mesh-Based-Depth-Estimation | fe82eab3b064c3fa6a543fa83f626e7d948d2335 | [
"MIT"
] | null | null | null | Depth_Estimation_Pipeline/app/driver.cpp | jasonpilbrough/Mesh-Based-Depth-Estimation | fe82eab3b064c3fa6a543fa83f626e7d948d2335 | [
"MIT"
] | null | null | null | #include "pipeline.h"
//#include "colourmap.h"
//#include <opencv2/viz.hpp>
int main(int argc, char* argv[])
{
// ######### EuRoC #########
//std::string dataset_path_left = "data/EuRoC/MH1/cam0/data/%10d.png";
//std::string dataset_path_right = "data/EuRoC/MH1/cam1/data/%10d.png";
// ######### ETH3D #########
std::string dataset_path_left = "data/ETH3D/delivery_area/cam4_brighter/%10d.png";
std::string dataset_path_right = "data/ETH3D/delivery_area/cam5_brighter/%10d.png";
std::string dataset_path_gnd = "data/ETH3D/delivery_area/gnd/%10d.png";
// ######### OXFORD ######### (This is actually MVSEC)
//std::string dataset_path_left = "data/Oxford/indoor_flying1/cam0/%10d.png";
//std::string dataset_path_right = "data/Oxford/indoor_flying1/cam1/%10d.png";
//std::string dataset_path_gnd = "data/Oxford/indoor_flying1/gnd/%10d.png";
sandbox::Pipeline p(dataset_path_left,dataset_path_right,dataset_path_gnd);
p.run();
return 0;
}
// ######### KITTI #########
//std::string dataset_path_left = "data/KITTI/2011_09_26_drive_0002_sync/image_00/data/%10d.png";
//std::string dataset_path_right = "data/KITTI/2011_09_26_drive_0002_sync/image_01/data/%10d.png";
//std::string dataset_path_left = "data/KITTI/data_stereo_flow/image_00/%10d.png";
//std::string dataset_path_right = "data/KITTI/data_stereo_flow/image_01/%10d.png";
//std::string dataset_path_gnd = "data/KITTI/data_stereo_flow/disp_noc/%10d.png";
//sandbox::Pipeline p(dataset_path_left,dataset_path_right);
| 36.093023 | 98 | 0.691366 | jasonpilbrough |
ddb1bc6b58aa8666fe1bd5ef983591fbeb7c216d | 1,181 | cpp | C++ | test/ext/std/integral_constant/bug_datatype_inheritance.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | 2 | 2015-05-07T14:29:13.000Z | 2015-07-04T10:59:46.000Z | test/ext/std/integral_constant/bug_datatype_inheritance.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | test/ext/std/integral_constant/bug_datatype_inheritance.cpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | /*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/ext/std/integral_constant.hpp>
#include <boost/hana/core/datatype.hpp>
#include <type_traits>
using namespace boost::hana;
struct inherit_simple : std::integral_constant<int, 3> { };
struct inherit_no_default : std::integral_constant<int, 3> {
inherit_no_default() = delete;
};
struct incomplete;
struct empty { };
struct non_pod { virtual ~non_pod() { } };
int main() {
static_assert(std::is_same<datatype_t<inherit_simple>, StdIntegralConstant>{}, "");
static_assert(std::is_same<datatype_t<inherit_no_default>, StdIntegralConstant>{}, "");
static_assert(std::is_same<datatype_t<std::is_pointer<int*>>, StdIntegralConstant>{}, "");
static_assert(!std::is_same<datatype_t<incomplete>, StdIntegralConstant>{}, "");
static_assert(!std::is_same<datatype_t<empty>, StdIntegralConstant>{}, "");
static_assert(!std::is_same<datatype_t<non_pod>, StdIntegralConstant>{}, "");
static_assert(!std::is_same<datatype_t<void>, StdIntegralConstant>{}, "");
}
| 34.735294 | 94 | 0.730737 | rbock |
ddb25dd6ff068f1ee904f061f903794d46277de1 | 878 | cpp | C++ | examples/test.cpp | EBoespflug/multi_array | 61ce2540bf5e4c3c9b7266ae5958eaad433481a4 | [
"CC0-1.0"
] | null | null | null | examples/test.cpp | EBoespflug/multi_array | 61ce2540bf5e4c3c9b7266ae5958eaad433481a4 | [
"CC0-1.0"
] | null | null | null | examples/test.cpp | EBoespflug/multi_array | 61ce2540bf5e4c3c9b7266ae5958eaad433481a4 | [
"CC0-1.0"
] | null | null | null | #include "../multi_array.hpp"
#include <iostream>
#include <numeric>
template<typename Container>
void print(Container c)
{
std::cout << c.size() << '\n';
for(auto&& v : c)
std::cout << v << ' ';
std::cout << '\n';
}
int main()
{
eb::multi_array<int, 3, 2, 2> arr1{0};
eb::multi_array<int, 3, 2, 2> arr2{0};
std::iota(arr1.begin(), arr1.end(), 1);
print(arr1);
print(arr2);
arr2(0, 0, 0) = 0;
arr2(0, 0, 1) = 1;
arr2(0, 1, 0) = 2;
arr2(0, 1, 1) = 3;
arr2(1, 0, 0) = 4;
arr2(1, 0, 1) = 5;
arr2(1, 1, 0) = 6;
arr2(1, 1, 1) = 7;
arr2(2, 0, 0) = 8;
arr2(2, 0, 1) = 9;
arr2(2, 1, 0) = 10;
arr2(2, 1, 1) = 11;
for(auto& i : arr1)
--i;
print(arr1);
print(arr2);
if(arr1 == arr2)
std::cout << "Equals !\n";
else
std::cout << "Not equals !\n";
}
| 17.918367 | 43 | 0.458998 | EBoespflug |
ddb4b869c05f3c26a91225833baa2ebffa91a990 | 2,823 | cc | C++ | cc/whocc-scan-titers.cc | acorg/acmacs-whocc | af508bd4651ffb565cd4cf771200540918b1b2bd | [
"MIT"
] | null | null | null | cc/whocc-scan-titers.cc | acorg/acmacs-whocc | af508bd4651ffb565cd4cf771200540918b1b2bd | [
"MIT"
] | null | null | null | cc/whocc-scan-titers.cc | acorg/acmacs-whocc | af508bd4651ffb565cd4cf771200540918b1b2bd | [
"MIT"
] | null | null | null | #include <string>
#include "acmacs-base/argv.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-chart-2/factory-import.hh"
// ----------------------------------------------------------------------
void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files);
void scan_titers(const fs::path& filename, std::set<acmacs::chart::Titer>& titers);
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
argument<str> source_dir{*this, arg_name{"source-dir"}, mandatory};
};
int main(int argc, const char* argv[])
{
int exit_code = 0;
try {
Options opt(argc, argv);
std::vector<fs::path> ace_files;
find_ace_files(fs::path(*opt.source_dir), ace_files);
fmt::print("Total .ace files found: {}\n", ace_files.size());
std::set<acmacs::chart::Titer> titers;
for (const auto& filename : ace_files)
scan_titers(filename, titers);
fmt::print("{}\n", titers);
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 1;
}
return exit_code;
}
// ----------------------------------------------------------------------
void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files)
{
if (!fs::is_directory(source_dir))
throw std::runtime_error(source_dir.string() + " is not a directory");
for (const auto& dirent: fs::directory_iterator(source_dir)) {
if (fs::is_directory(dirent.status()))
find_ace_files(dirent.path(), ace_files);
else if (is_regular_file(dirent.status()) && dirent.path().extension().string() == ".ace")
ace_files.push_back(dirent.path());
}
} // find_ace_files
// ----------------------------------------------------------------------
void scan_titers(const fs::path& filename, std::set<acmacs::chart::Titer>& titers)
{
auto chart = acmacs::chart::import_from_file(filename, acmacs::chart::Verify::None, report_time::no);
auto chart_titers = chart->titers();
const auto number_of_antigens = chart_titers->number_of_antigens(), number_of_sera = chart_titers->number_of_sera();
for (size_t antigen_no = 0; antigen_no < number_of_antigens; ++antigen_no) {
for (size_t serum_no = 0; serum_no < number_of_sera; ++serum_no) {
titers.insert(chart_titers->titer(antigen_no, serum_no));
}
}
} // scan_titers
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 36.662338 | 129 | 0.569607 | acorg |
ddb8c1a668ae4b09afe226003e27e8d7b3fb0006 | 34,652 | cpp | C++ | Gunz/xpsupport/xpcrt.cpp | WhyWolfie/Repack-Aren | 4839db138a502ca4cfac8c2a8c950f1b59064955 | [
"FSFAP"
] | null | null | null | Gunz/xpsupport/xpcrt.cpp | WhyWolfie/Repack-Aren | 4839db138a502ca4cfac8c2a8c950f1b59064955 | [
"FSFAP"
] | null | null | null | Gunz/xpsupport/xpcrt.cpp | WhyWolfie/Repack-Aren | 4839db138a502ca4cfac8c2a8c950f1b59064955 | [
"FSFAP"
] | null | null | null | /* Copyright (c) 2012 Mike Ryan
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. */
// XPSupport CRT Wrappers
// Written by Mike Ryan (aka Ted.)
// http://tedwvc.wordpress.com
// see also http://connect.microsoft.com/VisualStudio/feedback/details/690617/
// Version history
// 2012-03-11 1.0 initial release
// 2012-03-13 1.01 Added msvcp110 stuff (InitializeCriticalSectionEx, CreateSymbolicLink(A/W)
// 2012-03-15 1.02 (MFC updates)
// 2012-03-15 1.03 Added fix for ConCRT runtime resource manager initialization (so std::thread can now be used)
// 2012-03-15 1.04 (MFC updates)
// 2012-03-29 1.05 added wrapper for EnumSystemLocalesEx
// 2012-05-05 1.06 added wrapper for GetLogicalProcessorInformation (allows unofficial XP SP2 support) - thanks to Michael Chourdakis for this implementation
// 2012-05-09 1.07 added wrapper for InitOnceExecuteOnce
// 2012-05-26 1.08 added XP/2003 x64 edition support (in xpcrtwrap64.asm)
// - thanks to Antony Vennard (https://vennard.org.uk) for testing and correcting several errors in my initial test x64 release
// 2012-05-27 1.09 fixed non-Unicode (MBCS) builds (thanks to Latency for suggesting and helping with this fix)
// 2012-06-28 1.10 added support for Vista threadpooling functions (added to pre-RTM version of CRT), added MIT license
#include "stdafx.h"
#ifndef _UNICODE
#include <io.h>
#include <stdio.h>
#endif
// we'll be using ntdll.dll so pull in a reference here
#pragma comment (lib, "ntdll.lib")
static BOOL IsVista = ((BYTE)::GetVersion() >= 6);
// GetTickCount64 implementation for XP (32 bit)
// IMPORTANT NOTE: this is the only undocumented part of the solution - if you're uncomfortable with this part,
// please substitute it with an alternative of your choice!
// For XP, we will use some undocumented features of Windows to emulate GetTickCount64
// see also: http://uninformed.org/index.cgi?v=7&a=2&p=12 for formula explanation and the offset used below
#define CONST_SCALING_FACTOR 78
// see #include "winternl.h" in SDK headers for documented parts of these structures and enums
// NOTE: only tested on XP 32 bit OS. 64 bit structures may differ!!
// expanded from Microsoft's winternl.h - documented as size 48
typedef struct _SYSTEM_TIMEOFDAY_INFORMATION {
LARGE_INTEGER TimeOfBoot;
BYTE unused[40];
} SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION;
// copied from Microsoft's winternl.h
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemTimeOfDayInformation = 3,
} SYSTEM_INFORMATION_CLASS;
extern "C" __kernel_entry LONG NTAPI NtQuerySystemInformation ( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation,
IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL);
extern "C" __kernel_entry LONG NTAPI NtQuerySystemTime (OUT PLARGE_INTEGER SystemTime);
static ULONGLONG UndocumentedGetTickCount64ImplementationForXP32()
{
static ULONGLONG StartTimeOfServer = static_cast<ULONGLONG>(-1);
if (StartTimeOfServer == -1) {
// undocumented - before using, please see comment above
SYSTEM_TIMEOFDAY_INFORMATION timeofDayInfo = {0};
// see http://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx
NtQuerySystemInformation (SystemTimeOfDayInformation, &timeofDayInfo, sizeof(timeofDayInfo), 0);
StartTimeOfServer = timeofDayInfo.TimeOfBoot.QuadPart;
}
// NtQuerySystemTime documented by Microsoft
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms724512(v=vs.85).aspx
LARGE_INTEGER now;
NtQuerySystemTime( &now );
return (ULONGLONG)(((now.QuadPart - StartTimeOfServer) / 10000.0) + CONST_SCALING_FACTOR);
}
typedef ULONGLONG (WINAPI *pGetTickCount64)(void);
extern "C" ULONGLONG WINAPI AfxGetTickCount64(void)
{
static pGetTickCount64 GetTickCount64_p = NULL;
if (IsVista) { // Vista or higher
if (!GetTickCount64_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetTickCount64_p = (pGetTickCount64) GetProcAddress(mod, "GetTickCount64");
}
return GetTickCount64_p();
} else
return UndocumentedGetTickCount64ImplementationForXP32(); // see above
}
// the following two functions wrap LCIDToLocaleName/LocaleNameToLCID
// we wrap them here so several locale name based APIs can convert back and forth to LCIDs on XP (which doesn't support LCIDs)
// Note: this requires the use of NLSDL.DLL which ships with Internet Explorer 7 or later
// if you really need to support XP3 + IE6 then please use the redistributable download available here:
// http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=25241
// the above installs nlsdl to the windows system32 folder
// or alternatively, modify the functions below to use MLANG instead (older technology but should work for the most part)
// see: http://qualapps.blogspot.com/2011/10/convert-locale-name-to-lcid-in-c.html for an MLANG implementation
typedef int (WINAPI *pLCIDToLocaleName)(__in LCID Locale, __out_opt LPWSTR lpName, int cchName,__in DWORD dwFlags);
int WINAPI AfxLCIDToLocaleName( __in LCID Locale, __out_opt LPWSTR lpName, int cchName,__in DWORD dwFlags )
{
static pLCIDToLocaleName LCIDToLocaleName_p = NULL ;
LCID lcid = GetUserDefaultLCID() ;
if( LCIDToLocaleName_p == NULL ){
HMODULE mod = NULL ;
if( IsVista ){ // for Vista and up
mod = GetModuleHandle( _T( "KERNEL32.dll" ) ) ;
if( mod ){
LCIDToLocaleName_p = ( pLCIDToLocaleName ) GetProcAddress( mod, "LCIDToLocaleName" ) ;
}
}
else{ // for XP and below - only support nlsdl.dll in system32 folder (comes with IE7 or nlsdl redist)
TCHAR systempath[_MAX_PATH];
GetSystemDirectory(systempath , _countof(systempath));
TCHAR FullPath[_MAX_PATH] ;
wsprintf(FullPath, _T( "%s\\%s" ) , systempath,_T( "nlsdl.dll" ) ) ;
if (_taccess(FullPath, 00) == 0)
mod = LoadLibrary( FullPath ) ;
if( mod ){
LCIDToLocaleName_p = ( pLCIDToLocaleName ) GetProcAddress( mod, "DownlevelLCIDToLocaleName" ) ;
}
}
}
if( LCIDToLocaleName_p ){ // call function
lcid = LCIDToLocaleName_p( Locale, lpName, cchName, dwFlags ) ;
}
return lcid ;
}
typedef LCID (WINAPI *pLocaleNameToLCID)(__in LPCWSTR lpName,__in DWORD dwFlags);
LCID WINAPI AfxLocaleNameToLCID( __in LPCWSTR lpName, __in DWORD dwFlags )
{
static pLocaleNameToLCID LocaleNameToLCID_p = NULL ;
LCID lcid = GetUserDefaultLCID() ;
if( LocaleNameToLCID_p == NULL ){
HMODULE mod = NULL ;
if( IsVista ){ // for Vista and up
mod = GetModuleHandle( _T( "KERNEL32.dll" ) ) ;
if( mod ){
LocaleNameToLCID_p = ( pLocaleNameToLCID ) GetProcAddress( mod, "LocaleNameToLCID" ) ;
}
}
else{ // for XP and below - only support nlsdl.dll in system32 folder (comes with IE7)
TCHAR systempath[_MAX_PATH] = {0};
GetSystemDirectory(systempath , _countof(systempath));
TCHAR FullPath[_MAX_PATH] = {0};
wsprintf(FullPath, _T( "%s\\%s" ) , systempath,_T( "nlsdl.dll" ) ) ;
if (_taccess(FullPath, 00) == 0)
mod = LoadLibrary( FullPath ) ;
if( mod ){
LocaleNameToLCID_p = ( pLocaleNameToLCID ) GetProcAddress( mod, "DownlevelLocaleNameToLCID" ) ;
}
}
}
if( LocaleNameToLCID_p ){ // call function
lcid = LocaleNameToLCID_p( lpName, dwFlags ) ;
}
return lcid ;
}
typedef BOOL (WINAPI *pIsValidLocaleName)(LPCWSTR lpLocaleName);
extern "C" BOOL WINAPI AfxIsValidLocaleName(_In_ LPCWSTR lpLocaleName)
{
static pIsValidLocaleName IsValidLocaleName_p = NULL;
if (IsVista) { // Vista or higher
if (!IsValidLocaleName_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
IsValidLocaleName_p = (pIsValidLocaleName) GetProcAddress(mod, "IsValidLocaleName");
}
return IsValidLocaleName_p(lpLocaleName);
} else {
LCID lcid = 0;
if (lpLocaleName)
lcid = AfxLocaleNameToLCID(lpLocaleName, 0);
else
return TRUE; // assume valid
return IsValidLocale(lcid, 0);
}
}
typedef int (WINAPI *pLCMapStringEx)( LPCWSTR lpLocaleName, DWORD dwMapFlags, LPCWSTR lpSrcStr,
int cchSrc, LPWSTR lpDestStr, int cchDest,
LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM sortHandle );
extern "C" int WINAPI AfxLCMapStringEx( LPCWSTR lpLocaleName, DWORD dwMapFlags, LPCWSTR lpSrcStr,
int cchSrc, LPWSTR lpDestStr, int cchDest,
LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM sortHandle )
{
static pLCMapStringEx LCMapStringEx_p = NULL;
if (IsVista) { // Vista or higher
if (!LCMapStringEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
LCMapStringEx_p = (pLCMapStringEx) GetProcAddress(mod, "LCMapStringEx");
}
return LCMapStringEx_p(lpLocaleName, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest,
lpVersionInformation, lpReserved, sortHandle);
} else {
LCID lcid = 0;
if (lpLocaleName)
lcid = AfxLocaleNameToLCID(lpLocaleName, 0);
else
lcid = GetUserDefaultLCID();
return LCMapStringW(lcid, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest);
}
}
typedef int (WINAPI *pCompareStringEx)( LPCWSTR lpLocaleName, DWORD dwCmpFlags, LPCWSTR lpString1,
int cchCount1, LPCWSTR lpString2, int cchCount2,
LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM lParam );
extern "C" int WINAPI AfxCompareStringEx( LPCWSTR lpLocaleName, DWORD dwCmpFlags, LPCWSTR lpString1,
int cchCount1, LPCWSTR lpString2, int cchCount2,
LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM lParam )
{
static pCompareStringEx CompareStringEx_p = NULL;
if (IsVista) { // Vista or higher
if (!CompareStringEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CompareStringEx_p = (pCompareStringEx) GetProcAddress(mod, "CompareStringEx");
}
return CompareStringEx_p(lpLocaleName, dwCmpFlags, lpString1, cchCount1, lpString2, cchCount2,
lpVersionInformation, lpReserved, lParam);
} else {
LCID lcid = 0;
if (lpLocaleName)
lcid = AfxLocaleNameToLCID(lpLocaleName, 0);
else
lcid = GetUserDefaultLCID();
return CompareStringW(lcid, dwCmpFlags,lpString1, cchCount1, lpString2, cchCount2);
}
}
typedef int (WINAPI *pGetLocaleInfoEx)(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData);
extern "C" int WINAPI AfxGetLocaleInfoEx(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData)
{
static pGetLocaleInfoEx GetLocaleInfoEx_p = NULL;
if (IsVista) { // Vista or higher
if (!GetLocaleInfoEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetLocaleInfoEx_p = (pGetLocaleInfoEx) GetProcAddress(mod, "GetLocaleInfoEx");
}
return GetLocaleInfoEx_p(lpLocaleName, LCType, lpLCData, cchData);
} else {
LCID lcid = 0;
if (lpLocaleName)
lcid = AfxLocaleNameToLCID(lpLocaleName, 0);
else
lcid = GetUserDefaultLCID();
return GetLocaleInfoW(lcid, LCType, lpLCData, cchData);
}
}
typedef int (WINAPI *pGetUserDefaultLocaleName)( __out LPWSTR lpLocaleName, __in int cchLocaleName);
extern "C" int WINAPI AfxGetUserDefaultLocaleName( __out LPWSTR lpLocaleName, __in int cchLocaleName)
{
static pGetUserDefaultLocaleName GetUserDefaultLocaleName_p = NULL;
if (IsVista) { // Vista or higher
if (!GetUserDefaultLocaleName_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetUserDefaultLocaleName_p = (pGetUserDefaultLocaleName) GetProcAddress(mod, "GetUserDefaultLocaleName");
}
return GetUserDefaultLocaleName_p(lpLocaleName, cchLocaleName);
} else {
LCID lcid = GetUserDefaultLCID();
return AfxLCIDToLocaleName(lcid, lpLocaleName, cchLocaleName, 0);
}
}
typedef BOOL (WINAPI *pEnumSystemLocalesEx)(__in LOCALE_ENUMPROCEX lpLocaleEnumProcEx,__in DWORD dwFlags, __in LPARAM lParam, __in_opt LPVOID lpReserved);
LOCALE_ENUMPROCEX pLocaleEnumProcEx = 0;
BOOL CALLBACK EnumLocalesProcWrapper (LPWSTR lpLocaleString)
{
LCID localeID = 0;
wchar_t localeName[100] = {0};
swscanf_s( lpLocaleString, L"%x", &localeID );
AfxLCIDToLocaleName(localeID, localeName, _countof(localeName), 0);
return pLocaleEnumProcEx(localeName, 0, 0);
}
extern "C" BOOL WINAPI AfxEnumSystemLocalesEx(__in LOCALE_ENUMPROCEX lpLocaleEnumProcEx,__in DWORD dwFlags, __in LPARAM lParam, __in_opt LPVOID lpReserved)
{
static pEnumSystemLocalesEx EnumSystemLocalesEx_p = NULL;
if (IsVista) { // Vista or higher
if (!EnumSystemLocalesEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
EnumSystemLocalesEx_p = (pEnumSystemLocalesEx) GetProcAddress(mod, "EnumSystemLocalesEx");
}
return EnumSystemLocalesEx_p(lpLocaleEnumProcEx, dwFlags, lParam, lpReserved);
} else {
// fallback to EnumSystemLocales on XP
// not even close to being thread-safe (left as exercise for reader)
pLocaleEnumProcEx = lpLocaleEnumProcEx; // global variable
return EnumSystemLocalesW(EnumLocalesProcWrapper, LCID_INSTALLED);
}
}
// FLS functions - idea borrowed from VC9 and below's CRT source code (this is how they handle it)
typedef DWORD (WINAPI *pFlsAlloc) (IN PFLS_CALLBACK_FUNCTION lpCallback OPTIONAL);
typedef PVOID (WINAPI *pFlsGetValue) (IN DWORD dwFlsIndex);
typedef BOOL (WINAPI *pFlsSetValue) (IN DWORD dwFlsIndex,IN PVOID lpFlsData);
typedef BOOL (WINAPI *pFlsFree) ( IN DWORD dwFlsIndex);
pFlsAlloc gpFlsAlloc = NULL;
pFlsGetValue gpFlsGetValue = NULL;
pFlsSetValue gpFlsSetValue = NULL;
pFlsFree gpFlsFree = NULL;
DWORD WINAPI __noParamTlsAlloc( PFLS_CALLBACK_FUNCTION )
{
return TlsAlloc();
}
static BOOL FlsInited = FALSE;
void FlsInit() {
HINSTANCE hKernel32 = GetModuleHandle(_T("kernel32.dll"));
if (hKernel32) {
gpFlsAlloc = (pFlsAlloc)GetProcAddress(hKernel32, "FlsAlloc");
if (gpFlsAlloc) { // if first one is missing don't bother with the others.
gpFlsGetValue = (pFlsGetValue)GetProcAddress(hKernel32,"FlsGetValue");
gpFlsSetValue = (pFlsSetValue)GetProcAddress(hKernel32, "FlsSetValue");
gpFlsFree = (pFlsFree)GetProcAddress(hKernel32, "FlsFree");
}
}
if (!gpFlsAlloc) {
gpFlsAlloc = (pFlsAlloc)__noParamTlsAlloc;
gpFlsGetValue = (pFlsGetValue)TlsGetValue;
gpFlsSetValue = (pFlsSetValue)TlsSetValue;
gpFlsFree = (pFlsFree)TlsFree;
}
FlsInited = TRUE;
}
extern "C" DWORD WINAPI AfxFlsAlloc(__in PFLS_CALLBACK_FUNCTION lpCallback)
{
// this function is called by CRT before any globals are initialized so we have to call the initialization of the function pointers here
if (!FlsInited) FlsInit();
return gpFlsAlloc(lpCallback);
}
extern "C" PVOID WINAPI AfxFlsGetValue( __in DWORD dwFlsIndex)
{
return gpFlsGetValue(dwFlsIndex);
}
extern "C" BOOL WINAPI AfxFlsSetValue(__in DWORD dwFlsIndex, __in_opt PVOID lpFlsData)
{
return gpFlsSetValue(dwFlsIndex, lpFlsData);
}
extern "C" BOOL WINAPI AfxFlsFree(__in DWORD dwFlsIndex)
{
return gpFlsFree(dwFlsIndex);
}
// miscellaneous functions
// this helper function copied from http://www.scss.tcd.ie/Jeremy.Jones/GetCurrentProcessorNumberXP.htm
DWORD GetCurrentProcessorNumberXP(void)
{
#ifndef _WIN64
_asm {mov eax, 1}
_asm {cpuid}
_asm {shr ebx, 24}
_asm {mov eax, ebx}
#else
return 0;
#endif
}
typedef DWORD (WINAPI *pGetCurrentProcessorNumber)(void);
extern "C" DWORD WINAPI AfxGetCurrentProcessorNumber()
{
static pGetCurrentProcessorNumber GetCurrentProcessorNumber_p = NULL;
static BOOL looked = FALSE;
// native version of this function available on Vista and Server 2003
if (!looked && !GetCurrentProcessorNumber_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetCurrentProcessorNumber_p = (pGetCurrentProcessorNumber) GetProcAddress(mod, "GetCurrentProcessorNumber");
else
looked = TRUE;
}
if (GetCurrentProcessorNumber_p)
return GetCurrentProcessorNumber_p();
else
return GetCurrentProcessorNumberXP();
}
typedef void (WINAPI *pFlushProcessWriteBuffers)(void);
extern "C" void WINAPI AfxFlushProcessWriteBuffers()
{
static pFlushProcessWriteBuffers FlushProcessWriteBuffers_p = NULL;
if (IsVista) { // Vista or higher
if (!FlushProcessWriteBuffers_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
FlushProcessWriteBuffers_p = (pFlushProcessWriteBuffers) GetProcAddress(mod, "FlushProcessWriteBuffers");
}
if (FlushProcessWriteBuffers_p)
FlushProcessWriteBuffers_p();
}
// no implementation for XP
}
typedef HANDLE (WINAPI *pCreateSemaphoreExW)(__in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,__in LONG lInitialCount,
__in LONG lMaximumCount, __in_opt LPCWSTR lpName, __reserved DWORD dwFlags, __in DWORD dwDesiredAccess);
extern "C" HANDLE WINAPI AfxCreateSemaphoreExW(__in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,__in LONG lInitialCount,
__in LONG lMaximumCount, __in_opt LPCWSTR lpName, __reserved DWORD dwFlags, __in DWORD dwDesiredAccess)
{
static pCreateSemaphoreExW CreateSemaphoreExW_p = NULL;
if (IsVista) { // Vista or higher
if (!CreateSemaphoreExW_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CreateSemaphoreExW_p = (pCreateSemaphoreExW) GetProcAddress(mod, "CreateSemaphoreExW");
}
return CreateSemaphoreExW_p(lpSemaphoreAttributes,lInitialCount,lMaximumCount, lpName, dwFlags, dwDesiredAccess);
} else {
// XP can't support last two parameters of CreateSemaphoreExW
return CreateSemaphoreW(lpSemaphoreAttributes,lInitialCount,lMaximumCount, lpName);
}
}
typedef int (WINAPI *pGetTimeFormatEx)(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpTime,
__in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpTimeStr, __in int cchTime);
extern "C" int WINAPI AfxGetTimeFormatEx(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpTime,
__in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpTimeStr, __in int cchTime)
{
static pGetTimeFormatEx GetTimeFormatEx_p = NULL;
if (IsVista) { // Vista or higher
if (!GetTimeFormatEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetTimeFormatEx_p = (pGetTimeFormatEx) GetProcAddress(mod, "GetTimeFormatEx");
}
return GetTimeFormatEx_p(lpLocaleName, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime);
} else {
LCID lcid = 0;
if (lpLocaleName)
lcid = AfxLocaleNameToLCID(lpLocaleName, 0);
else
lcid = GetUserDefaultLCID();
return GetTimeFormatW(lcid, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime);
}
}
typedef int (WINAPI *pGetDateFormatEx)(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpDate,
__in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpDateStr, __in int cchDate, __in_opt LPCWSTR lpCalendar);
extern "C" int WINAPI AfxGetDateFormatEx(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpDate,
__in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpDateStr, __in int cchDate, __in_opt LPCWSTR lpCalendar)
{
static pGetDateFormatEx GetDateFormatEx_p = NULL;
if (IsVista) { // Vista or higher
if (!GetDateFormatEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetDateFormatEx_p = (pGetDateFormatEx) GetProcAddress(mod, "GetDateFormatEx");
}
return GetDateFormatEx_p(lpLocaleName, dwFlags, lpDate, lpFormat, lpDateStr, cchDate, lpCalendar);
} else {
LCID lcid = 0;
if (lpLocaleName)
lcid = AfxLocaleNameToLCID(lpLocaleName, 0);
else
lcid = GetUserDefaultLCID();
return GetDateFormatW(lcid, dwFlags, lpDate, lpFormat, lpDateStr, cchDate);
}
}
typedef BOOL (WINAPI *pSetThreadStackGuarantee)(__inout PULONG StackSizeInBytes);
// available on Vista, XPx64, Server 2003 with SP1 but not XP x86
extern "C" BOOL WINAPI AfxSetThreadStackGuarantee(__inout PULONG StackSizeInBytes)
{
static pSetThreadStackGuarantee SetThreadStackGuarantee_p = NULL;
static BOOL looked = FALSE;
if (!looked && !SetThreadStackGuarantee_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
SetThreadStackGuarantee_p = (pSetThreadStackGuarantee) GetProcAddress(mod, "SetThreadStackGuarantee");
else
looked = TRUE;
}
if (SetThreadStackGuarantee_p)
return SetThreadStackGuarantee_p(StackSizeInBytes);
else
{
// for XP we only need to support stack size query (if you pass in 0 as the stack size) - see _resetstkoflw in CRT source
// not completed - left as an exercise to reader
if (StackSizeInBytes && *StackSizeInBytes == 0) {
*StackSizeInBytes = 0;
return 1;
}
}
return 0;
}
// STL stuff
typedef BOOL (WINAPI *pInitializeCriticalSectionEx)(__out LPCRITICAL_SECTION lpCriticalSection, __in DWORD dwSpinCount, __in DWORD Flags);
extern "C" BOOL WINAPI AfxInitializeCriticalSectionEx(__out LPCRITICAL_SECTION lpCriticalSection, __in DWORD dwSpinCount, __in DWORD Flags)
{
static pInitializeCriticalSectionEx InitializeCriticalSectionEx_p = NULL;
if (IsVista) { // Vista or higher
if (!InitializeCriticalSectionEx_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
InitializeCriticalSectionEx_p = (pInitializeCriticalSectionEx) GetProcAddress(mod, "InitializeCriticalSectionEx");
}
return InitializeCriticalSectionEx_p(lpCriticalSection, dwSpinCount, Flags);
}
// on XP we'll just use InitializeCriticalSection for now
InitializeCriticalSection(lpCriticalSection);
return TRUE;
}
typedef BOOLEAN (WINAPI *pCreateSymbolicLinkA)(__in LPSTR lpSymlinkFileName, __in LPSTR lpTargetFileName, __in DWORD dwFlags);
extern "C" BOOLEAN WINAPI AfxCreateSymbolicLinkA(__in LPSTR lpSymlinkFileName, __in LPSTR lpTargetFileName, __in DWORD dwFlags)
{
static pCreateSymbolicLinkA CreateSymbolicLinkA_p = NULL;
if (IsVista) { // Vista or higher
if (!CreateSymbolicLinkA_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CreateSymbolicLinkA_p = (pCreateSymbolicLinkA) GetProcAddress(mod, "CreateSymbolicLinkA");
}
return CreateSymbolicLinkA_p(lpSymlinkFileName, lpTargetFileName, dwFlags);
}
return 0;
}
typedef BOOLEAN (WINAPI *pCreateSymbolicLinkW)(__in LPWSTR lpSymlinkFileName, __in LPWSTR lpTargetFileName, __in DWORD dwFlags);
extern "C" BOOLEAN WINAPI AfxCreateSymbolicLinkW(__in LPWSTR lpSymlinkFileName, __in LPWSTR lpTargetFileName, __in DWORD dwFlags)
{
static pCreateSymbolicLinkW CreateSymbolicLinkW_p = NULL;
if (IsVista) { // Vista or higher
if (!CreateSymbolicLinkW_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CreateSymbolicLinkW_p = (pCreateSymbolicLinkW) GetProcAddress(mod, "CreateSymbolicLinkW");
}
return CreateSymbolicLinkW_p(lpSymlinkFileName, lpTargetFileName, dwFlags);
}
return 0;
}
// GetLogicalProcessorInformationXP implementation provided by Michael Chourdakis of TurboIRC.COM
BOOL GetLogicalProcessorInformationXP(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer,__inout PDWORD dwLength)
{
if (!dwLength)
return 0;
if (*dwLength < sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
*dwLength = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
return FALSE;
}
if (Buffer == 0)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
SYSTEM_LOGICAL_PROCESSOR_INFORMATION& g1 = Buffer[0];
g1.ProcessorMask = 0x1;
g1.Relationship = RelationProcessorCore;
g1.ProcessorCore.Flags = 0;
*dwLength = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
SetLastError(0);
return TRUE;
}
typedef BOOL (WINAPI *pGetLogicalProcessorInformation)(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, __inout PDWORD ReturnLength);
// GetLogicalProcessorInformation available on XP SP3 and above but not XP SP2
extern "C" BOOL WINAPI AfxGetLogicalProcessorInformation(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, __inout PDWORD ReturnLength)
{
static pGetLogicalProcessorInformation GetLogicalProcessorInformation_p = NULL;
static BOOL looked = FALSE;
if (!looked && !GetLogicalProcessorInformation_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetLogicalProcessorInformation_p = (pGetLogicalProcessorInformation) GetProcAddress(mod, "GetLogicalProcessorInformation");
else
looked = TRUE;
}
if (GetLogicalProcessorInformation_p)
return GetLogicalProcessorInformation_p(Buffer, ReturnLength);
else
return GetLogicalProcessorInformationXP(Buffer, ReturnLength);
}
// not thread-safe - may not even be correct
BOOL WINAPI InitOnceExecuteOnceXP(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context)
{
BOOL ret = TRUE;
static BOOL calledOnce = FALSE;
if (!calledOnce) {
ret = InitFn(InitOnce, Parameter, Context);
calledOnce = TRUE;
}
return ret;
}
typedef BOOL (WINAPI *pInitOnceExecuteOnce)(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context);
extern "C" BOOL WINAPI AfxInitOnceExecuteOnce(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context)
{
static pInitOnceExecuteOnce InitOnceExecuteOnce_p = NULL;
if (IsVista) { // Vista or higher
if (!InitOnceExecuteOnce_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
InitOnceExecuteOnce_p = (pInitOnceExecuteOnce) GetProcAddress(mod, "InitOnceExecuteOnce");
}
return InitOnceExecuteOnce_p(InitOnce, InitFn, Parameter, Context);
} else
return InitOnceExecuteOnceXP(InitOnce, InitFn, Parameter, Context);
}
// RTM added 8 new Vista+ APIs:
//
// CloseThreadpoolTimer
// CloseThreadpoolWait
// CreateThreadpoolTimer
// CreateThreadpoolWait
// FreeLibraryWhenCallbackReturns
// SetThreadpoolTimer
// SetThreadpoolWait
// WaitForThreadpoolTimerCallbacks
typedef VOID (WINAPI *pCloseThreadpoolTimer)(__inout PTP_TIMER pti);
extern "C" VOID WINAPI AfxCloseThreadpoolTimer(__inout PTP_TIMER pti)
{
static pCloseThreadpoolTimer CloseThreadpoolTimer_p = NULL;
if (IsVista) { // Vista or higher
if (!CloseThreadpoolTimer_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CloseThreadpoolTimer_p = (pCloseThreadpoolTimer) GetProcAddress(mod, "CloseThreadpoolTimer");
}
CloseThreadpoolTimer_p(pti);
}
return;
}
typedef VOID (WINAPI *pCloseThreadpoolWait)(__inout PTP_WAIT pwa);
extern "C" VOID WINAPI AfxCloseThreadpoolWait(__inout PTP_WAIT pwa)
{
static pCloseThreadpoolWait CloseThreadpoolWait_p = NULL;
if (IsVista) { // Vista or higher
if (!CloseThreadpoolWait_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CloseThreadpoolWait_p = (pCloseThreadpoolWait) GetProcAddress(mod, "CloseThreadpoolWait");
}
CloseThreadpoolWait_p(pwa);
}
return;
}
typedef PTP_TIMER (WINAPI *pCreateThreadpoolTimer)(__in PTP_TIMER_CALLBACK pfnti, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe);
extern "C" PTP_TIMER WINAPI AfxCreateThreadpoolTimer(__in PTP_TIMER_CALLBACK pfnti, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe)
{
static pCreateThreadpoolTimer CreateThreadpoolTimer_p = NULL;
if (IsVista) { // Vista or higher
if (!CreateThreadpoolTimer_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CreateThreadpoolTimer_p = (pCreateThreadpoolTimer) GetProcAddress(mod, "CreateThreadpoolTimer");
}
return CreateThreadpoolTimer_p(pfnti, pv, pcbe);
}
return 0;
}
typedef PTP_WAIT (WINAPI *pCreateThreadpoolWait)(__in PTP_WAIT_CALLBACK pfnwa, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe);
extern "C" PTP_WAIT WINAPI AfxCreateThreadpoolWait(__in PTP_WAIT_CALLBACK pfnwa, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe)
{
static pCreateThreadpoolWait CreateThreadpoolWait_p = NULL;
if (IsVista) { // Vista or higher
if (!CreateThreadpoolWait_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
CreateThreadpoolWait_p = (pCreateThreadpoolWait) GetProcAddress(mod, "CreateThreadpoolWait");
}
return CreateThreadpoolWait_p(pfnwa, pv, pcbe);
}
return 0;
}
typedef VOID (WINAPI *pFreeLibraryWhenCallbackReturns)(__inout PTP_CALLBACK_INSTANCE pci, __in HMODULE mod);
extern "C" VOID WINAPI AfxFreeLibraryWhenCallbackReturns(__inout PTP_CALLBACK_INSTANCE pci, __in HMODULE mod)
{
static pFreeLibraryWhenCallbackReturns FreeLibraryWhenCallbackReturns_p = NULL;
if (IsVista) { // Vista or higher
if (!FreeLibraryWhenCallbackReturns_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
FreeLibraryWhenCallbackReturns_p = (pFreeLibraryWhenCallbackReturns) GetProcAddress(mod, "FreeLibraryWhenCallbackReturns");
}
FreeLibraryWhenCallbackReturns_p(pci, mod);
}
return;
}
typedef VOID (WINAPI *pSetThreadpoolTimer)(__inout PTP_TIMER pti, __in_opt PFILETIME pftDueTime, __in DWORD msPeriod, __in_opt DWORD msWindowLength);
extern "C" VOID WINAPI AfxSetThreadpoolTimer(__inout PTP_TIMER pti, __in_opt PFILETIME pftDueTime, __in DWORD msPeriod, __in_opt DWORD msWindowLength)
{
static pSetThreadpoolTimer SetThreadpoolTimer_p = NULL;
if (IsVista) { // Vista or higher
if (!SetThreadpoolTimer_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
SetThreadpoolTimer_p = (pSetThreadpoolTimer) GetProcAddress(mod, "SetThreadpoolTimer");
}
SetThreadpoolTimer_p(pti, pftDueTime, msPeriod, msWindowLength);
}
return;
}
typedef VOID (WINAPI *pSetThreadpoolWait)(__inout PTP_WAIT pwa, __in_opt HANDLE h, __in_opt PFILETIME pftTimeout);
extern "C" VOID WINAPI AfxSetThreadpoolWait(__inout PTP_WAIT pwa, __in_opt HANDLE h, __in_opt PFILETIME pftTimeout)
{
static pSetThreadpoolWait SetThreadpoolWait_p = NULL;
if (IsVista) { // Vista or higher
if (!SetThreadpoolWait_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
SetThreadpoolWait_p = (pSetThreadpoolWait) GetProcAddress(mod, "SetThreadpoolWait");
}
SetThreadpoolWait_p(pwa, h, pftTimeout);
}
return;
}
typedef VOID (WINAPI *pWaitForThreadpoolTimerCallbacks)(__inout PTP_TIMER pti, __in BOOL fCancelPendingCallbacks);
extern "C" VOID WINAPI AfxWaitForThreadpoolTimerCallbacks(__inout PTP_TIMER pti, __in BOOL fCancelPendingCallbacks)
{
static pWaitForThreadpoolTimerCallbacks WaitForThreadpoolTimerCallbacks_p = NULL;
if (IsVista) { // Vista or higher
if (!WaitForThreadpoolTimerCallbacks_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
WaitForThreadpoolTimerCallbacks_p = (pWaitForThreadpoolTimerCallbacks) GetProcAddress(mod, "WaitForThreadpoolTimerCallbacks");
}
WaitForThreadpoolTimerCallbacks_p(pti, fCancelPendingCallbacks);
}
return;
}
// need to hook GetVersionEx for concrt runtime to initialized correctly
// uses some globals (probably not thread-safe)
typedef BOOL (WINAPI *pGetVersionExW)(__inout LPOSVERSIONINFO lpVersionInfo);
static BOOL fakeVersion = FALSE;
extern "C" BOOL WINAPI AfxGetVersionExW(__inout LPOSVERSIONINFO lpVersionInfo)
{
static pGetVersionExW GetVersionExW_p = NULL;
BOOL retVal = FALSE;
if (!GetVersionExW_p) {
HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL"));
if (mod)
GetVersionExW_p = (pGetVersionExW) GetProcAddress(mod, "GetVersionExW");
}
if (GetVersionExW_p)
retVal = GetVersionExW_p(lpVersionInfo);
if (!IsVista && fakeVersion) { // XP and lower - trick ConCRT into thinking that it's Vista
lpVersionInfo->dwMajorVersion = 6;
lpVersionInfo->dwMinorVersion = 0;
}
return retVal;
}
#if !defined(_DEBUG) || !defined(_MFC_VER) || _MSC_FULL_VER >= 170050503
// sorry this workaround only works in release builds of MFC until Microsoft fixes this bug in VC11
// http://connect.microsoft.com/VisualStudio/feedback/details/630105/
#include <concrt.h>
#if _MSC_FULL_VER >= 170050623 // pre-RTM
// The following code accesses some private ConCRT data and is necessary because of the new threadpool support written
// for Vista only should not be called on XP so we need to switch the Resource Manager's version back to XP after sucessfully
// initializing it.
class VersionSetterHack;
#include <concrtrm.h>
namespace Concurrency
{
namespace details
{
class ResourceManager : public Concurrency::IResourceManager
{
friend class VersionSetterHack;
private:
static IResourceManager::OSVersion s_version;
public:
static ResourceManager* CreateSingleton();
};
}
}
class VersionSetterHack {
public:
VersionSetterHack() {
// s_version has private linkage: accessing private member using friend hack
Concurrency::details::ResourceManager::s_version = Concurrency::details::ResourceManager::OSVersion::XP;
}
};
#endif
void InitializeConCRT()
{
fakeVersion = TRUE;
// the following function loads the resource manager using a temporary fake version (Vista) by hacking GetVersionEx
Concurrency::details::_GetConcurrency();
#if _MSC_FULL_VER >= 170050623 // pre-RTM
if (!IsVista) {
// this needs to be done before setting back to XP because of an assertion checking for Vista
Concurrency::details::ResourceManager::CreateSingleton();
// On XP OS reset version back to XP so ConCRT fallbacks will be used instead of Vista threadpooling functions
VersionSetterHack versionSet;
}
#endif
fakeVersion = FALSE;
}
class ForceConCRTInit
{
public:
ForceConCRTInit() { InitializeConCRT(); }
};
// this gets called before main() so allows ConCRT Resource Manager to be initialized early
ForceConCRTInit init;
#endif
| 34.791165 | 157 | 0.75303 | WhyWolfie |
ddb931107eeba6b3642942bac5d454e2310eb50f | 2,248 | cpp | C++ | src/Context.cpp | santa01/frank-luna-dx11 | 57172ca245f7933116ad8ab1974a1ff95c6a4f4c | [
"MIT"
] | null | null | null | src/Context.cpp | santa01/frank-luna-dx11 | 57172ca245f7933116ad8ab1974a1ff95c6a4f4c | [
"MIT"
] | null | null | null | src/Context.cpp | santa01/frank-luna-dx11 | 57172ca245f7933116ad8ab1974a1ff95c6a4f4c | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 Pavlo Lavrenenko
*
* 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 "Context.h"
#include "Application.h"
#include <chrono>
Context::Context(Application& application, const ContextParams& params)
: m_Application(application)
, m_Params(params)
{
m_Window.reset(new Window(*this));
m_Device.reset(new DX11Device(*this));
}
const ContextParams& Context::GetParams() const
{
return m_Params;
}
Window& Context::GetWindow() const
{
return *m_Window;
}
DX11Device& Context::GetDevice() const
{
return *m_Device;
}
float Context::GetFrameTime() const
{
return m_FrameTime;
}
void Context::Run()
{
m_Application.Start(*this);
while (!m_Terminate)
{
auto frameBegin = std::chrono::high_resolution_clock::now();
m_Device->Begin(*this);
m_Window->Update(*this);
m_Application.Update(*this);
m_Device->End(*this);
auto frameEnd = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> frameDuration = frameEnd - frameBegin;
m_FrameTime = frameDuration.count();
}
m_Application.Shutdown(*this);
}
void Context::Terminate()
{
m_Terminate = true;
}
| 27.084337 | 81 | 0.711744 | santa01 |
ddba5cf6d9aad6ae6bad3b4345ffd496eb24dd05 | 1,259 | cpp | C++ | 11497/11497.cpp | retroinspect/my-first-ps | 89c583cd7207b32465c9616b032dd1c3f1f54438 | [
"Apache-2.0"
] | null | null | null | 11497/11497.cpp | retroinspect/my-first-ps | 89c583cd7207b32465c9616b032dd1c3f1f54438 | [
"Apache-2.0"
] | null | null | null | 11497/11497.cpp | retroinspect/my-first-ps | 89c583cd7207b32465c9616b032dd1c3f1f54438 | [
"Apache-2.0"
] | null | null | null | // 통나무 건너뛰기
#include <iostream>
#include <string>
#include <vector>
#include <cassert>
#include <cmath>
#include <algorithm>
#include <list>
using namespace std;
vector<int> input;
int N;
int logJumping()
{
sort(input.begin(), input.end());
list<int> reorder;
for (int i=0; i<N; i++)
{
int e = input[i];
if (i%2 == 0) reorder.push_back(e);
else reorder.push_front(e);
}
int maxDiff = -1;
for (list<int>::iterator iter = reorder.begin(); iter != reorder.end(); iter++)
{
list<int>::iterator tmpIt = iter; tmpIt++;
int num1 = *iter;
int num2 = (tmpIt == reorder.end()) ? reorder.front() : *tmpIt;
int tmp = abs(num1-num2);
if (tmp > maxDiff) maxDiff = tmp;
}
return maxDiff;
}
int main()
{
string tmpString;
cin >> tmpString;
int T = stoi(tmpString);
vector<int> answers;
for (int i=0; i<T; i++)
{
cin >> tmpString;
N = stoi(tmpString);
for (int j=0; j<N; j++)
{
cin >> tmpString;
int num = stoi(tmpString);
input.push_back(num);
}
int answer = logJumping();
answers.push_back(answer);
input.clear();
}
for (vector<int>::iterator iter=answers.begin(); iter != answers.end(); iter++)
{
cout << *iter << endl;
}
return 0;
} | 17.985714 | 81 | 0.58062 | retroinspect |
ddc43cf6da150fb602bef9745593a4c071d4c933 | 30,276 | cpp | C++ | Javelin/Assembler/arm64/Assembler.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | 10 | 2016-04-06T01:24:00.000Z | 2021-11-16T10:16:51.000Z | Javelin/Assembler/arm64/Assembler.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | 1 | 2016-05-06T05:38:58.000Z | 2016-05-09T16:42:43.000Z | Javelin/Assembler/arm64/Assembler.cpp | jthlim/JavelinPattern | 8add264f88ac620de109ddf797f7431779bbd9ea | [
"BSD-3-Clause"
] | null | null | null | //============================================================================
#if defined(__arm64__)
//============================================================================
#include "Javelin/Assembler/arm64/Assembler.h"
#include "Javelin/Assembler/JitMemoryManager.h"
#include <algorithm>
#include <stdint.h>
//============================================================================
#if DEBUG
#define USE_GOTO_LABELS 0
#else
#define USE_GOTO_LABELS 1
#endif
#define USE_OPTIMIZED_APPEND_INSTRUCTION_DATA 1
//============================================================================
using namespace Javelin;
using namespace Javelin::arm64Assembler;
//============================================================================
static int64_t cls(int64_t v)
{
int64_t result;
asm("cls %0, %1" : "=r"(result) : "r"(v));
return result;
}
//============================================================================
SegmentAssembler::SegmentAssembler(JitMemoryManager &aMemoryManager)
: memoryManager(aMemoryManager)
{
buildData.Reserve(8192);
}
//============================================================================
#if USE_OPTIMIZED_APPEND_INSTRUCTION_DATA
__attribute__((naked))
void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize,
const uint8_t *s,
uint32_t referenceAndDataLength,
uint32_t labelData)
{
// Define JIT_OFFSETOF to avoid compiler warnings on offsetof()
#define JIT_OFFSETOF(t,f) (size_t(&((t*)64)->f) - 64)
asm volatile(".global __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj");
// Update numberOfLabels, numberOfForwardLabelReferences
asm volatile("ldp w6, w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.numberOfLabels)));
asm volatile("add w6, w6, w4, uxtb");
asm volatile("add w7, w7, w4, lsr #8");
asm volatile("stp w6, w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.numberOfLabels)));
asm volatile("b __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj");
// Definition of AppendInstructionData(blockByteCodeSize, s);
asm volatile(".global __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKh");
asm volatile("__ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKh:");
asm volatile("mov w3, %0" : : "i"(sizeof(AppendAssemblyReference)));
// Definition for AppendInstructionData(blockByteCodeSize, s, referenceAndDataLength);
asm volatile("__ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj:");
// Update byteCodeSize
asm volatile("ldr w5, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.byteCodeSize)));
asm volatile("add w5, w5, w1");
asm volatile("str w5, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.byteCodeSize)));
// buildData.Append, x5 = offset, x6 = capacity.
asm volatile("ldp w5, w6, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData)));
asm volatile("add w7, w5, w3");
asm volatile("cmp w7, w6");
asm volatile("b.hi 1f");
asm volatile("str w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData)));
asm volatile("ldr x0, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data)));
asm volatile("add x0, x0, x5");
// Write referenceSize and assemblerData
asm volatile("stp x2, x3, [x0]");
asm volatile("ret");
asm volatile("1:");
// Update offset and capacity
asm volatile("add w1, w7, w7");
asm volatile("stp w7, w1, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData)));
// Update data (inline of JitVectorBase::ExpandAndAppend
asm volatile("stp x2, lr, [sp, #-48]!");
asm volatile("stp x0, x3, [sp, #16]");
asm volatile("str x5, [sp, #32]");
asm volatile("ldr x0, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data)));
asm volatile("bl _realloc");
asm volatile("ldr x5, [sp, #32]");
asm volatile("ldp x7, x3, [sp, #16]");
asm volatile("ldp x2, lr, [sp], #48");
asm volatile("str x0, [x7, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data)));
asm volatile("add x0, x0, x5");
// Write referenceSize and assemblerData
asm volatile("stp x2, x3, [x0]");
asm volatile("ret");
}
void* (SegmentAssembler::*volatile reference0)(uint32_t, const uint8_t*, uint32_t, uint32_t);
//void* (SegmentAssembler::*volatile reference1)(uint32_t, const uint8_t*, uint32_t);
//void (SegmentAssembler::*volatile reference2)(uint32_t, const uint8_t*);
__attribute__((constructor)) static void EnsureLinkage()
{
reference0 = &SegmentAssembler::AppendInstructionData;
// reference1 = &SegmentAssembler::AppendInstructionData;
// reference2 = &SegmentAssembler::AppendInstructionData;
}
#else
void SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s)
{
AppendInstructionData(blockByteCodeSize, s, sizeof(AppendAssemblyReference), 0);
}
void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize,
const uint8_t *s,
uint32_t referenceAndDataLength)
{
return AppendInstructionData(blockByteCodeSize, s, referenceAndDataLength, 0);
}
void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize,
const uint8_t *s,
uint32_t referenceAndDataLength,
uint32_t labelData)
{
aggregateData.byteCodeSize += blockByteCodeSize;
ProcessLabelData(labelData);
AppendAssemblyReference *reference = (AppendAssemblyReference*) buildData.Append(referenceAndDataLength);
reference->referenceSize = referenceAndDataLength;
reference->assemblerData = s;
return reference;
}
void SegmentAssembler::ProcessLabelData(uint32_t labelData)
{
int numberOfLabels = labelData & 0xff;
int numberOfForwardLabelReferences = labelData >> 8;
aggregateData.numberOfLabels += numberOfLabels;
aggregateData.numberOfForwardLabelReferences += numberOfForwardLabelReferences;
}
#endif
void* SegmentAssembler::AppendData(uint32_t byteSize)
{
static constexpr ActionType appendDataActions[2] =
{
ActionType::DataBlock,
ActionType::Return,
};
static_assert(sizeof(AppendByteReference) == 16, "Expected AppendByteReference to be 16 bytes");
uint32_t allocationSize = (sizeof(AppendByteReference) + byteSize + 7) & -8;
AppendByteReference *reference = (AppendByteReference*) AppendInstructionData(byteSize,
(const uint8_t*) &appendDataActions,
allocationSize);
reference->dataSize = byteSize;
return reference + 1;
}
void SegmentAssembler::AppendDataPointer(const void *data, uint32_t byteSize)
{
static constexpr ActionType appendDataActions[2] =
{
ActionType::DataPointer,
ActionType::Return,
};
AppendDataPointerReference *reference =
(AppendDataPointerReference*) AppendInstructionData(byteSize,
(const uint8_t*) &appendDataActions,
sizeof(AppendDataPointerReference));
reference->dataSize = byteSize;
reference->pData = (const uint8_t*) data;
}
//============================================================================
__attribute__((always_inline)) int32_t SegmentAssembler::ReadSigned16(const uint8_t* &s)
{
int16_t result;
memcpy(&result, s, sizeof(result));
s += sizeof(result);
return result;
}
__attribute__((always_inline)) uint32_t SegmentAssembler::ReadUnsigned16(const uint8_t* &s)
{
uint16_t result;
memcpy(&result, s, sizeof(result));
s += sizeof(result);
return result;
}
__attribute__((always_inline)) uint32_t SegmentAssembler::ReadUnsigned32(const uint8_t* &s)
{
uint32_t result;
memcpy(&result, s, sizeof(result));
s += sizeof(result);
return result;
}
uint32_t SegmentAssembler::LogicalOpcodeValue(uint64_t v)
{
BitMaskEncodeResult result = EncodeBitMask(v);
assert(result.size != 0 && "Unable to encode logical immediate");
uint32_t opcodeValue = result.rotate << 16;
if(result.size == 64) opcodeValue |= 1 << 22;
uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f;
opcodeValue |= imms << 10;
return opcodeValue;
}
void SegmentAssembler::Patch(uint8_t *p, RelEncoding encoding, int64_t delta)
{
switch(encoding)
{
case RelEncoding::Rel26:
{
uint32_t opcode;
memcpy(&opcode, p, 4);
assert((delta & 3) == 0);
delta = opcode + (delta >> 2);
opcode = (opcode & ~0x3ffffff) | (delta & 0x3ffffff);
memcpy(p, &opcode, 4);
}
break;
case RelEncoding::Rel19Offset5:
{
uint32_t opcode;
memcpy(&opcode, p, 4);
assert((delta & 3) == 0);
delta = opcode + (uint32_t(delta) << 3);
opcode = (opcode & ~0xffffe0) | (delta & 0xffffe0);
memcpy(p, &opcode, 4);
}
break;
case RelEncoding::Adrp:
{
uint64_t current = uint64_t(p) >> 12;
uint64_t target = uint64_t(p + delta) >> 12;
delta = target - current;
}
[[fallthrough]];
case RelEncoding::Rel21HiLo:
{
// struct Opcode
// {
// uint32_t _dummy0 : 5;
// uint32_t offsetHi : 19;
// uint32_t _dummy24 : 5;
// uint32_t offsetLo : 2;
// uint32_t _dummy31 : 1;
// };
//
// Opcode opcode;
// memcpy(&opcode, p, 4);
//
// uint32_t rel = (opcode.offsetHi << 2) | opcode.offsetLo;
// rel += delta;
// opcode.offsetLo = rel;
// opcode.offsetHi = rel >> 2;
// memcpy(p, &opcode, 4);
// The compiler does a poor job with the above code. It generates a
// constant that is hoisted all the way to the start of
// GenerateByteCode, which becomes overhead for every single call.
// Attempts to use uint32_t with appropriate shift and masking still do
// not result in the desired generated code.
// -> Manually code it. It is both shorter and has less register pressure.
uint32_t opcode;
memcpy(&opcode, p, 4);
uint32_t rel;
asm volatile("sbfx %w1, %w0, #3, #21 \n\t"
"bfxil %w1, %w0, #29, #2 \n\t"
"add %w1, %w1, %w2 \n\t"
"bfi %w0, %w1, #29, #2 \n\t"
"lsr %w1, %w1, #2 \n\t"
"bfi %w0, %w1, #5, #19 \n\t"
: "+r"(opcode), "=&r"(rel)
: "r"(delta));
memcpy(p, &opcode, 4);
}
break;
case RelEncoding::Rel14Offset5:
{
uint32_t opcode;
memcpy(&opcode, p, 4);
delta = opcode + (uint32_t(delta) << 3);
opcode = (opcode & ~0x7ffe0) | (delta & 0x7ffe0);
memcpy(p, &opcode, 4);
}
break;
case RelEncoding::Imm12:
{
uint32_t opcode;
memcpy(&opcode, p, 4);
uint32_t rel = (opcode >> 10) & 0xfff;
if(int64_t(p) + delta == 0) rel = int32_t(delta);
else rel += (int64_t(p) + delta);
opcode = (opcode & ~0x3ffc00) | ((rel << 10) & 0x3ffc00);
memcpy(p, &opcode, 4);
}
break;
case RelEncoding::Rel64:
{
int64_t rel;
memcpy(&rel, p, 8);
rel += delta;
memcpy(p, &rel, 8);
}
break;
default:
__builtin_unreachable();
}
}
//============================================================================
void SegmentAssembler::ProcessByteCode()
{
programStart = (uint8_t*) memoryManager.Allocate(aggregateData.byteCodeSize+4); // +4 is because some actions assume extra buffer.
uint8_t *programEnd = GenerateByteCode(programStart);
// Shrink allocation
memoryManager.EndWrite(programStart);
codeSize = uint32_t(programEnd - programStart);
assert(codeSize <= aggregateData.byteCodeSize);
memoryManager.Shrink(programStart, codeSize);
}
/**
* There is a lot of function call overhead in GenerateBytecode() because a call to memcpy
* requires the compiler to preserve all registers.
* InlineMemcpy means that no external calls are made, and the compiler can make more use
* of scracth registers.
*/
__attribute__((always_inline))
static void InlineMemcpyAndAdvancePointers(uint8_t* &dest, const uint8_t* &source, uint64_t dataSize)
{
int64_t scratch;
asm volatile(" tst %1, #3 \n\t"
" b.eq 2f \n\t"
"1: \n\t"
" ldrb %w0, [%3], #1 \n\t"
" strb %w0, [%2], #1 \n\t"
" sub %1, %1, #1 \n\t"
" tst %1, #3 \n\t"
" b.ne 1b \n\t"
"2: \n\t"
" tbz %1, #2, 1f \n\t"
" ldr %w0, [%3], #4 \n\t"
" str %w0, [%2], #4 \n\t"
" sub %1, %1, #4 \n\t"
"1: \n\t"
" tbz %1, #3, 1f \n\t"
" ldr %0, [%3], #8 \n\t"
" str %0, [%2], #8 \n\t"
" sub %1, %1, #8 \n\t"
"1: \n\t"
" tbz %1, #4, 1f \n\t"
" ldr q0, [%3], #16 \n\t"
" str q0, [%2], #16 \n\t"
" sub %1, %1, #16 \n\t"
"1: \n\t"
" cbz %1, 2f \n\t"
"1: \n\t"
" ldp q0, q1, [%3], #32 \n\t"
" stp q0, q1, [%2], #32 \n\t"
" subs %1, %1, #32 \n\t"
" b.ne 1b \n\t"
"2: \n\t"
: "=&r"(scratch), "+r"(dataSize), "+r"(dest), "+r"(source)
:
: "v0", "v1", "memory");
}
#if USE_GOTO_LABELS
#define CASE(x) x
#define CONTINUE1(x) do { const uint8_t* pAction = s+x; void *jumpTarget = jumpOffsets[*pAction];
#define CONTINUE2 assert(s == pAction); ++s; goto *jumpTarget; } while(0)
#define CONTINUE goto *jumpOffsets[*s++]
#else
#define CASE(x) case ActionType::x
#define CONTINUE1(x) { const uint8_t* pAction = s+x;
#define CONTINUE2 assert(s == pAction); continue; }
#define CONTINUE continue
#endif
uint8_t *SegmentAssembler::GenerateByteCode(__restrict uint8_t* p)
{
#if USE_GOTO_LABELS
static constexpr void *jumpOffsets[] =
{
#define TAG(x) &&x,
#include "ActionTypeTags.h"
#undef TAG
};
#endif
const AppendAssemblyReference *blockData = (AppendAssemblyReference*) buildData.begin();
const AppendAssemblyReference *const blockDataEnd = (AppendAssemblyReference*) buildData.end();
const __restrict uint8_t* s = blockData->assemblerData;
#if !USE_GOTO_LABELS
uint32_t opcodeValue;
for(;;)
{
#endif
#if USE_GOTO_LABELS
CONTINUE;
#else
switch((ActionType) *s++)
#endif
{
CASE(Return):
blockData = blockData->GetNext();
if(blockData == blockDataEnd) return p;
s = blockData->assemblerData;
CONTINUE;
CASE(Literal4): CONTINUE1(4); memcpy(p, s, 4); p += 4; s += 4; CONTINUE2;
CASE(Literal8): CONTINUE1(8); memcpy(p, s, 8); p += 8; s += 8; CONTINUE2;
CASE(Literal12): CONTINUE1(12); memcpy(p, s, 16); p += 12; s += 12; CONTINUE2;
CASE(Literal16): CONTINUE1(16); memcpy(p, s, 16); p += 16; s += 16; CONTINUE2;
CASE(Literal20): CONTINUE1(20); memcpy(p, s, 20); p += 20; s += 20; CONTINUE2;
CASE(Literal24): CONTINUE1(24); memcpy(p, s, 24); p += 24; s += 24; CONTINUE2;
CASE(Literal28): CONTINUE1(28); memcpy(p, s, 32); p += 28; s += 28; CONTINUE2;
CASE(Literal32): CONTINUE1(32); memcpy(p, s, 32); p += 32; s += 32; CONTINUE2;
CASE(LiteralBlock):
{
uint32_t length = ReadUnsigned16(s);
InlineMemcpyAndAdvancePointers(p, s, length);
CONTINUE;
}
CASE(Align):
{
CONTINUE1(1);
uint8_t alignmentM1 = *s++;
while(size_t(p) & 3) *p++ = 0;
while(size_t(p) & alignmentM1)
{
const uint32_t opcode = 0xd503201f;
memcpy(p, &opcode, 4);
p += 4;
}
CONTINUE2;
}
CASE(Unalign):
{
CONTINUE1(1);
uint8_t alignmentM1 = *s++;
assert(alignmentM1 > 3);
if(((size_t) p & alignmentM1) == 0)
{
const uint32_t opcode = 0xd503201f;
memcpy(p, &opcode, 4);
p += 4;
}
CONTINUE2;
}
CASE(Jump):
s += *s + 1;
CONTINUE;
#if USE_GOTO_LABELS
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
uint32_t opcodeValue;
#pragma clang diagnostic pop
#endif
#ifndef NDEBUG
// Masked, unsigned and signed all have the same implementation in release mode,
// If asserts are enabled, build 3 separate versions, where unsigned and signed
// check the bounds of the provided expression.
CASE(MaskedPatchB1Opcode):
{
int bitMask = *s++;
int bitOffset = *s++;
int valueShift = *s++;
uint8_t value = ReadB1ExpressionValue(s, blockData);
opcodeValue = ((value >> valueShift) & bitMask) << bitOffset;
goto ProcessPatchOpcode;
}
CASE(UnsignedPatchB1Opcode):
{
int bitMask = *s++;
int bitOffset = *s++;
int valueShift = *s++;
uint8_t value = ReadB1ExpressionValue(s, blockData);
assert((value & ((1<<valueShift)-1)) == 0);
assert((value & ~bitMask) == 0);
opcodeValue = value >> valueShift << bitOffset;
goto ProcessPatchOpcode;
}
#else
CASE(MaskedPatchB1Opcode):
CASE(UnsignedPatchB1Opcode):
#endif
CASE(SignedPatchB1Opcode):
{
int bitMask = *s++;
int bitOffset = *s++;
int valueShift = *s++;
int32_t value = ReadB1ExpressionValue(s, blockData);
assert((value & ((1<<valueShift)-1)) == 0);
value >>= valueShift;
assert((value & ~bitMask) == 0 || (value | bitMask) == -1);
opcodeValue = (value & bitMask) << bitOffset;
goto ProcessPatchOpcode;
}
#ifndef NDEBUG
CASE(MaskedPatchB2Opcode):
{
int numberOfBits = *s++;
int bitOffset = *s++;
int valueShift = *s++;
int32_t value = ReadB2ExpressionValue(s, blockData);
value >>= valueShift;
uint32_t mask = (1 << numberOfBits) - 1;
opcodeValue = (value & mask) << bitOffset;
goto ProcessPatchOpcode;
}
#else
CASE(MaskedPatchB2Opcode):
#endif
CASE(SignedPatchB2Opcode):
{
int numberOfBits = *s++;
int bitOffset = *s++;
int valueShift = *s++;
int32_t value = ReadB2ExpressionValue(s, blockData);
assert((value & ((1<<valueShift)-1)) == 0);
value >>= valueShift;
assert(value >> numberOfBits == 0 || value >> numberOfBits == -1);
uint32_t mask = (1 << numberOfBits) - 1;
opcodeValue = (value & mask) << bitOffset;
goto ProcessPatchOpcode;
}
#ifndef NDEBUG
CASE(MaskedPatchB4Opcode):
{
int numberOfBits = *s++;
int bitOffset = *s++;
int valueShift = *s++;
int32_t value = ReadB4ExpressionValue(s, blockData);
value >>= valueShift;
uint32_t mask = (1 << numberOfBits) - 1;
opcodeValue = (value & mask) << bitOffset;
goto ProcessPatchOpcode;
}
#else
CASE(MaskedPatchB4Opcode):
#endif
CASE(SignedPatchB4Opcode):
{
int numberOfBits = *s++;
int bitOffset = *s++;
int valueShift = *s++;
int32_t value = ReadB4ExpressionValue(s, blockData);
assert((value & ((1<<valueShift)-1)) == 0);
value >>= valueShift;
assert(value >> numberOfBits == 0 || value >> numberOfBits == -1);
uint32_t mask = (1 << numberOfBits) - 1;
opcodeValue = (value & mask) << bitOffset;
goto ProcessPatchOpcode;
}
CASE(UnsignedPatchB2Opcode):
{
int numberOfBits = *s++;
int bitOffset = *s++;
int valueShift = *s++;
uint16_t value = ReadB2ExpressionValue(s, blockData);
assert((value & ((1<<valueShift)-1)) == 0);
assert(value >> (numberOfBits + valueShift) == 0);
(void) numberOfBits;
opcodeValue = value >> valueShift << bitOffset;
goto ProcessPatchOpcode;
}
CASE(UnsignedPatchB4Opcode):
{
int numberOfBits = *s++;
int bitOffset = *s++;
int valueShift = *s++;
uint32_t value = ReadB4ExpressionValue(s, blockData);
assert((value & ((1<<valueShift)-1)) == 0);
value >>= valueShift;
assert(value >> numberOfBits == 0);
(void) numberOfBits;
opcodeValue = value << bitOffset;
goto ProcessPatchOpcode;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
{
uint64_t v;
#pragma clang diagnostic pop
CASE(LogicalImmediatePatchB4Opcode):
{
uint32_t value = ReadB4ExpressionValue(s, blockData);
v = (uint64_t(value)<<32) | value;
goto ProcessPatchLogical;
}
CASE(LogicalImmediatePatchB8Opcode):
v = ReadB8ExpressionValue(s, blockData);
ProcessPatchLogical:
opcodeValue = LogicalOpcodeValue(v);
goto ProcessPatchOpcode;
}
CASE(RepeatPatchOpcode):
ProcessPatchOpcode:
{
int offset = ReadSigned16(s);
uint32_t opcode;
memcpy(&opcode, p+offset, 4);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconditional-uninitialized"
opcode |= opcodeValue;
#pragma clang diagnostic pop
memcpy(p+offset, &opcode, 4);
CONTINUE;
}
#if USE_GOTO_LABELS
}
#endif
CASE(B1Expression):
*p++ = ReadB1ExpressionValue(s, blockData);
CONTINUE;
CASE(B2Expression):
{
int16_t v = ReadB2ExpressionValue(s, blockData);
memcpy(p, &v, sizeof(v));
p += sizeof(v);
CONTINUE;
}
CASE(B4Expression):
{
int32_t v = ReadB4ExpressionValue(s, blockData);
memcpy(p, &v, sizeof(v));
p += sizeof(v);
CONTINUE;
}
CASE(B8Expression):
{
int64_t v = ReadB8ExpressionValue(s, blockData);
memcpy(p, &v, sizeof(v));
p += sizeof(v);
CONTINUE;
}
CASE(DataBlock):
{
uint32_t dataSize = ((const AppendByteReference*) blockData)->dataSize;
const uint8_t *expressionData = (const uint8_t*) blockData + sizeof(AppendByteReference);
InlineMemcpyAndAdvancePointers(p, expressionData, dataSize);
CONTINUE;
}
CASE(DataPointer):
{
uint32_t dataSize = ((const AppendDataPointerReference*) blockData)->dataSize;
const uint8_t *pData = ((const AppendDataPointerReference*) blockData)->pData;
InlineMemcpyAndAdvancePointers(p, pData, dataSize);
CONTINUE;
}
{ // Scope block for v
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
uint64_t v;
#pragma clang diagnostic pop
CASE(Imm0B1Condition):
v = ReadB1ExpressionValue(s, blockData);
goto ProcessImm0Condition;
CASE(Imm0B2Condition):
v = ReadB2ExpressionValue(s, blockData);
goto ProcessImm0Condition;
CASE(Imm0B4Condition):
v = ReadB4ExpressionValue(s, blockData);
goto ProcessImm0Condition;
CASE(Imm0B8Condition):
v = ReadB8ExpressionValue(s, blockData);
ProcessImm0Condition:
asm volatile("; This comment prevents the compiler from expanding code inappropriately.");
uint32_t offset = *s++;
if(v != 0) s += offset;
CONTINUE;
}
CASE(Delta21Condition):
{
// ADR has 21 bits
int64_t v = ReadB8ExpressionValue(s, blockData);
uint32_t offset = *s++;
int64_t currentP = int64_t(p);
int64_t delta = v - currentP;
if(cls(delta) < 64-21) s += offset;
CONTINUE;
}
CASE(Delta26x4Condition):
{
// Direct branches have 26 bits, representing delta*4
int64_t v = ReadB8ExpressionValue(s, blockData);
uint32_t offset = *s++;
int64_t currentP = int64_t(p);
int64_t delta = v - currentP;
if((delta & 3) != 0
|| cls(delta) < 64-26-2) s += offset;
CONTINUE;
}
CASE(AdrpCondition):
{
// ADRP has 21 bits
uint64_t v = ReadB8ExpressionValue(s, blockData);
uint32_t offset = *s++;
uint64_t currentP = uint64_t(p);
int64_t delta = (v >> 12) - (currentP >> 12);
if(cls(delta) < 64-21) s += offset;
CONTINUE;
}
{ // Scope block for labelId
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
uint32_t labelId;
#pragma clang diagnostic pop
CASE(Label):
labelId = ReadUnsigned32(s);
goto ProcessLabel;
CASE(ExpressionLabel):
labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData));
ProcessLabel:
asm volatile("; This comment prevents the compiler from expanding code inappropriately.");
// Insert into map.
labels.Set(labelId, p);
JitForwardReferenceMapLookupResult result = unresolvedLabels.Find(labelId);
if(result.reference)
{
JitForwardReferenceData *data = result.reference;
JitForwardReferenceData *last;
do
{
Patch(data->p, (RelEncoding) data->data, (intptr_t) p - (intptr_t) data->p);
last = data;
data = data->next;
} while(data);
unresolvedLabels.Remove(result, last);
}
CONTINUE;
}
{ // Scope block for encoding, labelId
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
uint32_t labelId;
const uint8_t *target;
#pragma clang diagnostic pop
CASE(PatchExpression):
target = (const uint8_t*) ReadB8ExpressionValue(s, blockData);
goto ProcessBackwardTarget;
CASE(PatchExpressionLabel):
labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData));
goto ProcessPatchLabel;
CASE(PatchLabel):
labelId = ReadUnsigned32(s);
ProcessPatchLabel:
target = (const uint8_t*) labels.GetIfExists(labelId);
if(target == nullptr) goto ProcessForwardLabel;
else goto ProcessBackwardTarget;
CASE(PatchLabelForward):
labelId = ReadUnsigned32(s);
goto ProcessForwardLabel;
CASE(PatchExpressionLabelForward):
labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData));
ProcessForwardLabel:
{
JitForwardReferenceData *refData = unresolvedLabels.Add(labelId);
RelEncoding encoding = (RelEncoding) *s++;
uint8_t *patchAddress = p + ReadSigned16(s);
refData->data = (uint32_t) encoding;
refData->p = patchAddress;
}
CONTINUE;
CASE(PatchLabelBackward):
labelId = ReadUnsigned32(s);
goto ProcessBackwardLabel;
CASE(PatchExpressionLabelBackward):
labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData));
ProcessBackwardLabel:
target = (uint8_t*) labels.Get(labelId);
ProcessBackwardTarget:
RelEncoding encoding = (RelEncoding) *s++;
uint8_t *patchAddress = p + ReadSigned16(s);
int64_t delta = target - patchAddress;
Patch(patchAddress, encoding, delta);
}
CONTINUE; // Continue outside variable scope produces better register allocations
CASE(PatchAbsoluteAddress):
{
int offset = ReadSigned16(s);
uint64_t v;
memcpy(&v, p + offset, 8);
v += (uint64_t) p + offset;
memcpy(p + offset, &v, 8);
CONTINUE;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
{
uint32_t opcode;
uint64_t value;
uint64_t notValue;
uint64_t logicalValue;
#pragma clang diagnostic pop
CASE(MovReg32Expression):
opcode = *s++;
value = (uint32_t) ReadB4ExpressionValue(s, blockData);
notValue = ~uint32_t(value);
logicalValue = value | (value << 32);
goto ProcessMovExpression;
CASE(MovReg64Expression):
opcode = *s++ | 0x80000000;
value = ReadB8ExpressionValue(s, blockData);
notValue = ~value;
logicalValue = value;
ProcessMovExpression:
if((value & 0xffffffffffff0000) == 0) opcode |= 0x52800000 | (value << 5);
else if((value & 0xffffffff0000ffff) == 0) opcode |= 0x52a00000 | (value >> 11);
else if((notValue & 0xffffffffffff0000) == 0) opcode |= 0x12800000 | (notValue << 5);
else if((notValue & 0xffffffff0000ffff) == 0) opcode |= 0x12a00000 | (notValue >> 11);
else if((value & 0xffff0000ffffffff) == 0) opcode |= 0x52c00000 | (value >> 27);
else if((value & 0x0000ffffffffffff) == 0) opcode |= 0x52e00000 | (value >> 43);
else if((notValue & 0xffff0000ffffffff) == 0) opcode |= 0x12c00000 | (notValue >> 27);
else if((notValue & 0x0000ffffffffffff) == 0) opcode |= 0x12e00000 | (notValue >> 43);
else
{
BitMaskEncodeResult result = EncodeBitMask(logicalValue);
assert(result.size != 0 && "Unable to encode logical immediate");
if(result.size == 64) opcode |= 1 << 22;
uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f;
opcode |= 0x320003e0 | (result.rotate << 16) | (imms << 10);
}
memcpy(p, &opcode, 4);
p += 4;
}
CONTINUE;
#if !USE_GOTO_LABELS
default:
assert(!"Unhandled opcode");
#endif
}
#if !USE_GOTO_LABELS
}
#endif
}
//============================================================================
int8_t SegmentAssembler::ReadB1ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference)
{
const uint8_t *expressionData = (const uint8_t*) reference;
uint32_t offset = ReadUnsigned16(s);
return expressionData[offset];
}
int32_t SegmentAssembler::ReadB2ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference)
{
const uint8_t *expressionData = (const uint8_t*) reference;
uint32_t offset = ReadUnsigned16(s);
int16_t result;
memcpy(&result, expressionData + offset, sizeof(result));
return result;
}
int32_t SegmentAssembler::ReadB4ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference)
{
const uint8_t *expressionData = (const uint8_t*) reference;
uint32_t offset = ReadUnsigned16(s);
int32_t result;
memcpy(&result, expressionData + offset, sizeof(result));
return result;
}
int64_t SegmentAssembler::ReadB8ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference)
{
const uint8_t *expressionData = (const uint8_t*) reference;
uint32_t offset = ReadUnsigned16(s);
int64_t result;
memcpy(&result, expressionData + offset, sizeof(result));
return result;
}
//============================================================================
bool SegmentAssembler::IsValidBitmask64(uint64_t value)
{
return EncodeBitMask(value).size != 0;
}
//============================================================================
#pragma mark - Assembler
//============================================================================
Assembler::Assembler(JitMemoryManager *codeSegmentMemoryManager,
JitMemoryManager *dataSegmentMemoryManager)
: SegmentAssembler(*codeSegmentMemoryManager)
{
if(dataSegmentMemoryManager)
{
hasDataSegment = true;
new(&dataSegment) SegmentAssembler(*dataSegmentMemoryManager);
}
}
Assembler::~Assembler()
{
if(hasDataSegment) dataSegment.~SegmentAssembler();
}
__attribute__((flatten))
void* Assembler::Build()
{
if(hasDataSegment)
{
uint32_t numberOfLabels = aggregateData.numberOfLabels + dataSegment.aggregateData.numberOfLabels;
uint32_t numberOfForwardLabelReferences = aggregateData.numberOfForwardLabelReferences + dataSegment.aggregateData.numberOfForwardLabelReferences;
labels.Reserve(numberOfLabels);
unresolvedLabels.Reserve(numberOfForwardLabelReferences);
dataSegment.labels.StartUseBacking(labels);
dataSegment.unresolvedLabels.StartUseBacking(unresolvedLabels);
dataSegment.ProcessByteCode();
dataSegment.labels.StopUseBacking(labels);
dataSegment.unresolvedLabels.StopUseBacking(unresolvedLabels);
}
else
{
labels.Reserve(aggregateData.numberOfLabels);
unresolvedLabels.Reserve(aggregateData.numberOfForwardLabelReferences);
}
ProcessByteCode();
assert(!unresolvedLabels.HasData() && "Not all references have been resolved");
return programStart;
}
//============================================================================
#endif // defined(__arm64__)
//============================================================================
| 30.862385 | 148 | 0.647113 | jthlim |
ddd09e71ba385f83682379de1e163d780b5bbfbb | 515 | cpp | C++ | solved/o-q/odd-sum/odd.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/o-q/odd-sum/odd.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/o-q/odd-sum/odd.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <cstdio>
int a, b;
int sum(int lo, int hi)
{
if (lo < 1) lo = 1;
if (lo > hi) return 0;
if (lo == hi) return lo;
return (hi*(hi+1) - (lo-1)*lo)/2;
}
int solve()
{
int x = a % 2 == 0 ? a / 2 : (a - 1) / 2;
int y = b % 2 == 0 ? b / 2 - 1 : (b - 1) / 2;
return sum(x, y)*2 + y - x + 1;
}
int main()
{
int T;
scanf("%d", &T);
int ncase = 0;
while (T--) {
scanf("%d%d", &a, &b);
printf("Case %d: %d\n", ++ncase, solve());
}
return 0;
}
| 15.147059 | 50 | 0.4 | abuasifkhan |
ddd40ffa25cb716b4e26db8746e71abad6f85a73 | 3,167 | cpp | C++ | sniper/pico/Response.cpp | rtbtech/libsniper | 0828df9da74f8ed11a1273c61c15dfb5816c3c1e | [
"Apache-2.0"
] | 9 | 2020-05-08T21:17:12.000Z | 2021-06-04T18:38:35.000Z | sniper/pico/Response.cpp | rtbtech/libsniper | 0828df9da74f8ed11a1273c61c15dfb5816c3c1e | [
"Apache-2.0"
] | null | null | null | sniper/pico/Response.cpp | rtbtech/libsniper | 0828df9da74f8ed11a1273c61c15dfb5816c3c1e | [
"Apache-2.0"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
/*
* Copyright (c) 2018 - 2019, MetaHash, Oleg Romanenko (oleg@romanenko.ro)
*
* 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 <sniper/pico/picohttpparser.h>
#include <sniper/strings/ascii_case.h>
#include <sniper/strings/atoi.h>
#include "Response.h"
namespace sniper::pico {
void Response::clear() noexcept
{
status = -1;
header_size = 0;
content_length = 0;
keep_alive = false;
headers.clear();
}
ParseResult Response::parse(char* data, size_t size) noexcept
{
if (!data || !size)
return ParseResult::Err;
if (size < 5)
return ParseResult::Partial;
struct phr_header pico_headers[MAX_HEADERS];
size_t num_headers = sizeof(pico_headers) / sizeof(headers[0]);
int pico_minor_version = -1;
const char* msg = nullptr;
size_t msg_len = 0;
int ssize =
phr_parse_response(data, size, &pico_minor_version, &status, &msg, &msg_len, pico_headers, &num_headers, 0);
if (ssize > 0) {
header_size = ssize;
if (pico_minor_version == 1)
keep_alive = true;
bool content_length_found = false;
bool connection_found = false;
for (unsigned i = 0; i < num_headers; i++) {
strings::to_lower_ascii(const_cast<char*>(pico_headers[i].name), pico_headers[i].name_len);
strings::to_lower_ascii(const_cast<char*>(pico_headers[i].value), pico_headers[i].value_len);
string_view key(pico_headers[i].name, pico_headers[i].name_len);
string_view val(pico_headers[i].value, pico_headers[i].value_len);
// content-length
if (!content_length_found && key == "content-length") {
content_length_found = true;
if (auto len = strings::fast_atoi64(val); len)
content_length = *len;
else
return ParseResult::Err;
}
// connection
if (!connection_found && key == "connection") {
connection_found = true;
if (pico_minor_version == 0 && val == "keep-alive")
keep_alive = true;
else if (val == "close")
keep_alive = false;
}
headers.emplace_back(key, val);
}
return ParseResult::Complete;
}
else if (ssize == -2) {
return ParseResult::Partial;
}
else {
return ParseResult::Err;
}
}
} // namespace sniper::pico
| 30.747573 | 116 | 0.616672 | rtbtech |
ddd4d5ab025307843be0b62229c0d85036cf370d | 582 | cpp | C++ | Notes_Week2/multipleInput.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | Notes_Week2/multipleInput.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | Notes_Week2/multipleInput.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | /*********************************************************************
** Author: Wei-Chien Hsu
** Date: 04/09/18
** Description: Asks the user enters width and height, and output
the Area.
*********************************************************************/
#include <iostream>
using namespace std;
int main() {
float width, height;
int area;
cout << "Please enters the width and height (in float): " << endl;
cin >> width >> height;
area = static_cast<int>(width * height);
cout << "The area is : " << area << endl;
return 0;
} | 27.714286 | 70 | 0.450172 | WeiChienHsu |
dddafcbbe3971a518cafdb18249ca33a8ffe9536 | 1,668 | cc | C++ | src/sockio.cc | SanczoPL/QtServer | c8350e920cadc215ad306592460cc16031eefff9 | [
"MIT"
] | null | null | null | src/sockio.cc | SanczoPL/QtServer | c8350e920cadc215ad306592460cc16031eefff9 | [
"MIT"
] | null | null | null | src/sockio.cc | SanczoPL/QtServer | c8350e920cadc215ad306592460cc16031eefff9 | [
"MIT"
] | null | null | null | #include "../include/sockio.h"
SockIO::SockIO(QTcpSocket* a_socket, QObject* parent)
: QObject(parent)
, m_socket{ a_socket }
{
connect(m_socket, &QTcpSocket::readyRead, this, &SockIO::onReadyRead);
}
bool SockIO::hasMessages()
{
return !m_messageQueue.isEmpty();
}
Message SockIO::nextMessage()
{
if (!hasMessages()) qFatal("No mesages in queue!");
Message const MESSAGE{ m_messageQueue[0] };
m_messageQueue.pop_front();
return MESSAGE;
}
bool SockIO::sendMessage(Message const& a_message)
{
Logger->trace("SockIO::sendMessage()");
if (m_socket->write(a_message.rawData()) < 0) {
Logger->warn("Failed to send message to host", m_socket->peerAddress().toString().toStdString());
return false;
}
return true;
}
void SockIO::onReadyRead()
{
m_bufer += m_socket->readAll();
Logger->trace("Recived data from ip:{}, bufSize:{}", m_socket->peerAddress().toString().toStdString(), m_bufer.size());
Logger->trace("while({} >= {})", m_bufer.size() ,static_cast<int>(sizeof(Message::Header)) );
while (m_bufer.size() >= static_cast<int>(sizeof(Message::Header))) {
Logger->trace("checkPrefix:{}", Message::checkPrefix(m_bufer));
if (Message::checkPrefix(m_bufer)) {
auto messageSize = Message::validate(m_bufer);
Logger->trace("validate:{}", messageSize);
if (messageSize > 0) {
m_messageQueue.push_back(Message{ m_bufer });
m_bufer.remove(0, messageSize);
Logger->trace("emit new message:");
emit(newMessage());
}
else {
Logger->trace("messageSize = 0");
break;
}
}
else {
Logger->warn("Buffer out of order {}", m_socket->peerAddress().toString().toStdString());
m_bufer.remove(0, 1);
}
}
}
| 26.903226 | 120 | 0.676259 | SanczoPL |
50af57283f0874a8f209829a0822eb507912716d | 536 | hpp | C++ | YYSloth/include/drivers/pic/pic8259.hpp | notYuriy/yayaos | 4df7b015cb6e572797dd40a5d2891cf24abcb4d1 | [
"MIT"
] | 12 | 2020-04-13T12:38:54.000Z | 2021-08-31T07:03:14.000Z | YYSloth/include/drivers/pic/pic8259.hpp | YayOrg/YayOS | 4df7b015cb6e572797dd40a5d2891cf24abcb4d1 | [
"MIT"
] | null | null | null | YYSloth/include/drivers/pic/pic8259.hpp | YayOrg/YayOS | 4df7b015cb6e572797dd40a5d2891cf24abcb4d1 | [
"MIT"
] | 1 | 2020-07-18T12:11:37.000Z | 2020-07-18T12:11:37.000Z | #ifndef __PIC_8259_HPP_INCLUDED__
#define __PIC_8259_HPP_INCLUDED__
#include <drivers/pic/pic.hpp>
#include <utils.hpp>
namespace drivers {
class PIC8259 : public IPIC {
uint8_t m_picMasterMask;
uint8_t m_picSlaveMask;
public:
void init();
bool registerLegacyIrq(uint8_t irq, x86_64::IDTVector vec);
virtual bool enableLegacyIrq(uint8_t irq);
virtual bool disableLegacyIrq(uint8_t irq);
virtual bool endOfLegacyIrq(uint8_t irq);
};
}; // namespace drivers
#endif | 23.304348 | 67 | 0.695896 | notYuriy |
50af8f89a9594ef35a72183c8ffc3c849c577598 | 6,043 | hpp | C++ | src/accelerator/Component.hpp | chrpilat/mnemosyne | bde60abf5e2be614dadf599e9e7b6a44afa83907 | [
"BSD-2-Clause"
] | 6 | 2017-03-02T16:02:00.000Z | 2022-02-15T13:25:50.000Z | src/accelerator/Component.hpp | chrpilat/mnemosyne | bde60abf5e2be614dadf599e9e7b6a44afa83907 | [
"BSD-2-Clause"
] | null | null | null | src/accelerator/Component.hpp | chrpilat/mnemosyne | bde60abf5e2be614dadf599e9e7b6a44afa83907 | [
"BSD-2-Clause"
] | 2 | 2019-04-25T15:53:20.000Z | 2020-02-10T02:45:32.000Z | /**
* @copyright
* Copyright (c) 2017 - SLD Group @ Columbia University. All Rights Reserved.
*
* This file is part of Mnemosyne.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @file Component.hpp
* @author Christian Pilato <pilato.christian@gmail.com>
*
* @brief Class to describe a component with memory access
*
*/
#ifndef _COMPONENT_HPP_
#define _COMPONENT_HPP_
#include "utils.hpp"
FORWARD_DECL(Array);
FORWARD_DECL(ArrayList);
FORWARD_DECL(ComponentList);
FORWARD_DECL(MemoryWrapper);
#include "UGraph.hpp"
/**
* @brief Component Declaration
*/
struct Component
{
//! Identifier of the component.
const std::string name;
std::string clock_name;
std::string reset_name;
std::string conf_done_name;
std::string acc_done_name;
std::set<std::string> dmain_prefix;
std::set<std::string> dmaout_prefix;
std::set<std::string> rdreq_prefix;
std::set<std::string> wrreq_prefix;
std::set<std::string> read_interfaces;
std::set<std::string> write_interfaces;
std::map<std::string, std::string> darkmem_to_buffer;
std::map<std::string, std::set<std::string> > buffer_to_darkmem;
/**
* @brief Constructor
*/
Component(const std::string& name);
/**
* @brief Print method
* @param os is the output stream
*/
void print(std::ostream& os) const;
/**
* @brief Overloaded operator to support print
* @param os is the output stream
* @param b is the component to be printed
* @return is the returned stream
*/
friend std::ostream& operator<<(std::ostream& os, const Component& b)
{
b.print(os);
return os;
}
void parse_interface(const YAML::Node& interface, const std::map<std::string, MemoryWrapperPtr> &buffer_to_wrapper);
std::string get_rdreq_prefix() const;
std::string get_wrreq_prefix() const;
std::string get_dmain_prefix() const;
std::string get_dmaout_prefix() const;
};
///refcount definition
typedef boost::shared_ptr<Component> ComponentPtr;
struct ComponentList
{
///verbosity level of the class
unsigned int verbosity;
///name of the top component
std::string top_name;
///archive of components
std::map<std::string, ComponentPtr> list;
///list of buffers to be stored
ArrayListPtr buffers;
typedef std::tuple<UGraphPtr, UNode> node_t;
std::map<std::string, ArrayPtr> id_to_buffer;
std::map<std::string, node_t> id_to_node;
std::map<UGraphPtr, std::map<UNode, ArrayPtr> > node_to_buffer;
std::map<UGraphPtr, std::string> graph_to_acc_name;
std::vector<node_t> node_list;
std::map<node_t, std::set<node_t> > comp_list;
/**
* @brief Component
* @param verbosity is the verbosity level of the class
*/
ComponentList(unsigned int verbosity);
/**
* @brief Create single array
* @param name is the id of the array
* @param width is the bitwidth
* @param height is the number of words
* @param interfaces is the list of interfaces
* @param init_file is the name of the initialization file (if any)
*/
void create_array(const std::string& name, const unsigned int width, unsigned int height, const std::string& interfaces, const std::string& init_file);
/**
* @brief Parse the multi-component definitions
* @param name is the name of the top component
* @param multiacc_config is the path to the file to be parsed
*/
bool parse_config(const std::string& name, const std::string& multiacc_config);
/**
* @brief Parse a single component definition
* @param name is the name of the component
* @param acc_config is the path to the configuration file to be parsed
* @param input_cgraph is the path to the compatibility graph file to be parsed
*/
bool parse_config(const std::string& name, const std::string& acc_config, const std::string& input_cgraph, const std::string& scenario_config);
/**
* @brief Prepare buffer data structures for the given accelerator
* @param name is the name of the accelerator
*/
void bufferLoad(const std::string& name);
/**
* @brief Parse the file describing the compatibilities
* @param name is the name of the current component to be analyzed
* @param input_cgraph is the file describing the compatibilities
*/
void parse_accelerator_config(const std::string& name, const std::string& input_cgraph);
/**
* @brief Get a string-based representation of the given clique
* @param clique is the set of nodes composing the clique
* @return the string representing the clique
*/
std::string get_clique_string(const std::set<node_t>& clique);
};
///refcount definition
typedef boost::shared_ptr<ComponentList> ComponentListPtr;
#endif
| 33.949438 | 154 | 0.707761 | chrpilat |
50b3329138cbe81855eaf86cf22bec99ae8d8dcc | 935 | hpp | C++ | libs/libSocketHandler/src/SocketHandler.hpp | maxDcb/ExplorationC2 | f7366118eaa43ca5172b5e9d4a03156d724748b1 | [
"MIT"
] | null | null | null | libs/libSocketHandler/src/SocketHandler.hpp | maxDcb/ExplorationC2 | f7366118eaa43ca5172b5e9d4a03156d724748b1 | [
"MIT"
] | null | null | null | libs/libSocketHandler/src/SocketHandler.hpp | maxDcb/ExplorationC2 | f7366118eaa43ca5172b5e9d4a03156d724748b1 | [
"MIT"
] | null | null | null | #pragma once
#include <fstream>
#include <memory>
#include <chrono>
#include <random>
#include <vector>
#include <thread>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
class Server
{
public:
Server(int port);
~Server();
bool send(std::string& data);
bool receive(std::string& data);
private:
void initServer();
void creatServerTcp(int port);
bool m_initDone;
int m_port;
std::thread* threadInit;
boost::asio::io_service m_ioService;
boost::asio::ip::tcp::socket* m_socketTcp;
boost::system::error_code m_error;
};
class Client
{
public:
Client(std::string& ip, int port);
~Client();
bool send(std::string& data);
bool receive(std::string& data);
private:
void creatClientTcp(int port, std::string& ip);
std::string m_ipServer;
int m_port;
boost::asio::io_service m_ioService;
boost::asio::ip::tcp::socket* m_socketTcp;
boost::system::error_code m_error;
};
| 15.327869 | 48 | 0.708021 | maxDcb |
50b528ab4d6ecd9b379fd23b296cae56f26bb391 | 2,047 | cc | C++ | src/image/b3TxSaveInfo.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/image/b3TxSaveInfo.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/image/b3TxSaveInfo.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | 1 | 2022-01-07T15:58:38.000Z | 2022-01-07T15:58:38.000Z | /*
**
** $Filename: b3TxSaveInfo.cc $
** $Release: Dortmund 2001, 2016 $
** $Revision$
** $Date$
** $Author$
** $Developer: Steffen A. Mork $
**
** Blizzard III - File format encoder
**
** (C) Copyright 2001 - 2021 Steffen A. Mork
** All Rights Reserved
**
**
*/
/*************************************************************************
** **
** Blizzard III includes **
** **
*************************************************************************/
#include "blz3/image/b3Tx.h"
#include "b3TxSaveInfo.h"
/*************************************************************************
** **
** PNG **
** **
*************************************************************************/
b3TxSaveInfo::b3TxSaveInfo(b3Tx * tx, const char * filename, const char * write_mode)
{
m_Tx = tx;
m_Tx->b3Name(filename);
bzero(m_SaveBuffer, sizeof(m_SaveBuffer));
m_ThisRow = b3TypedAlloc<b3_pkd_color>(tx->xSize);
if (m_ThisRow == nullptr)
{
b3PrintF(B3LOG_NORMAL, "Save Image: not enough memory!\n");
B3_THROW(b3TxException, B3_TX_MEMORY);
}
if (write_mode == nullptr)
{
m_FileHandle = nullptr;
if (!m_File.b3Open(filename, B_WRITE))
{
b3Free();
b3PrintF(B3LOG_NORMAL, "Save Image: file \"%s\" not created!\n", filename);
B3_THROW(b3TxException, B3_TX_NOT_SAVED);
}
}
else
{
m_FileHandle = fopen(filename, write_mode);
if (m_FileHandle == nullptr)
{
b3Free();
b3PrintF(B3LOG_NORMAL, "Save Image: file \"%s\" not created!\n", filename);
B3_THROW(b3TxException, B3_TX_NOT_SAVED);
}
}
}
b3TxSaveInfo::~b3TxSaveInfo()
{
if (m_FileHandle != nullptr)
{
fclose(m_FileHandle);
}
else
{
m_File.b3Close();
}
}
| 25.5875 | 85 | 0.429897 | stmork |
50b69ba7a31c994d4e138ca87f9a08b483c9e6de | 2,811 | hpp | C++ | include/codegen/include/Oculus/Platform/RoomType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Oculus/Platform/RoomType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Oculus/Platform/RoomType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:08 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.Enum
#include "System/Enum.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: Oculus.Platform
namespace Oculus::Platform {
// Autogenerated type: Oculus.Platform.RoomType
struct RoomType : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public Oculus.Platform.RoomType Unknown
static constexpr const int Unknown = 0;
// Get static field: static public Oculus.Platform.RoomType Unknown
static Oculus::Platform::RoomType _get_Unknown();
// Set static field: static public Oculus.Platform.RoomType Unknown
static void _set_Unknown(Oculus::Platform::RoomType value);
// static field const value: static public Oculus.Platform.RoomType Matchmaking
static constexpr const int Matchmaking = 1;
// Get static field: static public Oculus.Platform.RoomType Matchmaking
static Oculus::Platform::RoomType _get_Matchmaking();
// Set static field: static public Oculus.Platform.RoomType Matchmaking
static void _set_Matchmaking(Oculus::Platform::RoomType value);
// static field const value: static public Oculus.Platform.RoomType Moderated
static constexpr const int Moderated = 2;
// Get static field: static public Oculus.Platform.RoomType Moderated
static Oculus::Platform::RoomType _get_Moderated();
// Set static field: static public Oculus.Platform.RoomType Moderated
static void _set_Moderated(Oculus::Platform::RoomType value);
// static field const value: static public Oculus.Platform.RoomType Private
static constexpr const int Private = 3;
// Get static field: static public Oculus.Platform.RoomType Private
static Oculus::Platform::RoomType _get_Private();
// Set static field: static public Oculus.Platform.RoomType Private
static void _set_Private(Oculus::Platform::RoomType value);
// static field const value: static public Oculus.Platform.RoomType Solo
static constexpr const int Solo = 4;
// Get static field: static public Oculus.Platform.RoomType Solo
static Oculus::Platform::RoomType _get_Solo();
// Set static field: static public Oculus.Platform.RoomType Solo
static void _set_Solo(Oculus::Platform::RoomType value);
// Creating value type constructor for type: RoomType
RoomType(int value_ = {}) : value{value_} {}
}; // Oculus.Platform.RoomType
}
DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::RoomType, "Oculus.Platform", "RoomType");
#pragma pack(pop)
| 49.315789 | 83 | 0.728211 | Futuremappermydud |
50be740fd5091b26478e43a76633c15e31d3e26c | 1,586 | cpp | C++ | 2017/February/Silver/Why Did the Cow Cross the Road III.cpp | Sumitkk10/USACO-submissions | 543dafe041356e83a18e7a57e5d93d24bc266682 | [
"MIT"
] | 2 | 2020-12-09T05:43:19.000Z | 2020-12-09T06:24:45.000Z | 2017/February/Silver/Why Did the Cow Cross the Road III.cpp | Sumitkk10/USACO-submissions | 543dafe041356e83a18e7a57e5d93d24bc266682 | [
"MIT"
] | null | null | null | 2017/February/Silver/Why Did the Cow Cross the Road III.cpp | Sumitkk10/USACO-submissions | 543dafe041356e83a18e7a57e5d93d24bc266682 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
using namespace std;
const int N = 100 + 5;
const int MOD = 1e9 + 7;
int n, k, m, sol;
set<pair<int, pair<int, pair<int, int> > > > s;
bool ok, vis[N][N];
map<pair<int, int>, int> mp;
void check(int i, int j){
if(i <= 0 or j <= 0 or i > n or j > n or vis[i][j])
return;
sol += mp[{i,j}];
vis[i][j] = true;
if(s.find({i, {j, {i + 1, j}}}) == s.end())
check(i + 1, j);
if(s.find({i, {j, {i - 1, j}}}) == s.end())
check(i - 1, j);
if(s.find({i, {j, {i, j + 1}}}) == s.end())
check(i, j + 1);
if(s.find({i, {j, {i, j - 1}}}) == s.end())
check(i, j - 1);
}
int main() {
fast;
freopen("countcross.in", "r", stdin);
freopen("countcross.out", "w", stdout);
cin >> n >> k >> m;
for(int i = 0; i < m; ++i){
int a, b, x, y;
cin >> a >> b >> x >> y;
s.insert({a, {b, {x, y}}});
s.insert({x, {y, {a, b}}});
}
vector<pair<int, int> > cows;
for(int i = 0; i < k; ++i) {
int u, v;
cin >> u >> v;
mp[{u, v}]++;
}
long long ans1 = 0;
vector<int> ans;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
if(!vis[i][j]){
check(i, j);
ans.push_back(sol);
sol = 0;
}
}
}
for(int i = 0; i < ans.size(); ++i)
for(int j = i + 1; j < ans.size(); ++j)
ans1 += (ans[i] * ans[j]);
cout << ans1 << '\n';
return 0;
}
| 26.433333 | 70 | 0.406053 | Sumitkk10 |
50c316fdf459561e0def613aad0f9139b8a64c68 | 71,364 | cpp | C++ | PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp | rbnbr/S4 | 61534933e305e76d00cbefb75fc5c713c5b90c74 | [
"MIT"
] | 1 | 2021-09-27T11:29:48.000Z | 2021-09-27T11:29:48.000Z | PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp | rbnbr/S4 | 61534933e305e76d00cbefb75fc5c713c5b90c74 | [
"MIT"
] | null | null | null | PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp | rbnbr/S4 | 61534933e305e76d00cbefb75fc5c713c5b90c74 | [
"MIT"
] | 1 | 2022-02-10T16:07:27.000Z | 2022-02-10T16:07:27.000Z | #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include <vector>
#include <numeric>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <functional>
#include <random>
#include <thread>
#include <atomic>
#include <chrono>
#include <ctime>
#include <iostream>
#include "macros.h"
#include "BufferedNdArray.hpp"
#include "PythonExtrasCLib.h"
template<typename T>
void resize_array_point(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth,
void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth)
{
T* pInput = static_cast<T*>(pInputRaw);
T* pOutput = static_cast<T*>(pOutputRaw);
for (int x = 0; x < targetWidth; x++)
{
double tX = targetWidth > 1 ? static_cast<double>(x) / (targetWidth - 1) : 0;
int sourceX = lround(tX * (sourceWidth - 1));
for (int y = 0; y < targetHeight; y++)
{
double tY = targetHeight > 1 ? static_cast<double>(y) / (targetHeight - 1) : 0;
int sourceY = lround(tY * (sourceHeight - 1));
for (int z = 0; z < targetDepth; z++)
{
double tZ = targetDepth > 1 ? static_cast<double>(z) / (targetDepth - 1) : 0;
int sourceZ = lround(tZ * (sourceDepth - 1));
size_t sourceIndexFlat = sourceX * sourceHeight * sourceDepth + sourceY * sourceDepth + sourceZ;
pOutput[x * targetHeight * targetDepth + y * targetDepth + z] = pInput[sourceIndexFlat];
}
}
}
}
///
/// Compute the number of patches along each *patched* dimension.
/// Old function kept for compatibility. New ones don't use 'source axes' and patch all the dimensions.
///
std::vector<size_t> compute_patch_number_generic(const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes,
const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride,
const std::vector<size_t>& patchInnerStride, size_t predictionDelay)
{
std::vector<size_t> patchNumber(sourceAxes.size());
for (size_t i = 0; i < sourceAxes.size(); i++)
{
size_t dim = sourceAxes[i];
size_t stride = patchStride[i];
// How many voxels a patch covers.
// Last point in time (Y-value) is 'predictionDelay' frames away from the previous frame.
// E.g. if 'lastFrameGap' is 1, it immediately follows it.
size_t patchSupport = i > 0 ? (patchSize[i] - 1) * patchInnerStride[i] + 1
: (patchSize[i] - 2) * patchInnerStride[i] + 1 + predictionDelay;
size_t totalPatchNumber = dataSize[dim] - patchSupport + 1;
patchNumber[i] = (totalPatchNumber + stride - 1) / stride; // Round up.
}
return patchNumber;
}
//todo this code (and functions called by it) has too many vector allocations. look at '4d_fast' methods for optimization.
// The problem mostly is that the std vector doesn't have a small size optimization,
// and always allocates stuff on the heap.
template<typename T>
void extract_patches_batched(void* pDataVoid, void* pOutputVoid, size_t* pOutputCenters,
size_t ndim, const std::vector<size_t>& dataSize,
const std::vector<size_t>& sourceAxes,
const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride,
size_t firstPatchIndex, size_t patchesPerBatch, bool isBatchSizedBuffer = false)
{
T* pData = static_cast<T*>(pDataVoid);
T* pOutput = static_cast<T*>(pOutputVoid);
auto multiplies = std::multiplies<size_t>(); // Cache the functor, don't recreate it in a loop.
// Number of patched dimensions.
size_t nPatchDim = sourceAxes.size();
std::vector<size_t> patchInnerStride(nPatchDim, size_t{1});
// Number of patches along the patched dimensions.
std::vector<size_t> patchNumber = compute_patch_number_generic(dataSize, sourceAxes, patchSize, patchStride,
patchInnerStride, 1ULL);
// Compute the (data)size of each patch.
// (Depends on the spatial extent a.k.a. 'patch size' of each patch, and on the size of the orig. data.
std::vector<size_t> patchDataSize(ndim, 0);
for (size_t dim = 0; dim < ndim; dim++)
{
auto itSourceDim = std::find(sourceAxes.begin(), sourceAxes.end(), dim);
if (itSourceDim != sourceAxes.end())
{
// If the dimension is patched, use the patch size.
size_t patchDim = itSourceDim - sourceAxes.begin();
patchDataSize[dim] = patchSize[patchDim];
}
else
{
// Otherwise, take all data along that dimension.
patchDataSize[dim] = dataSize[dim];
}
}
// Total number of elements in a patch.
size_t patchDataSizeFlat = std::accumulate(patchDataSize.begin(), patchDataSize.end(),
size_t{1}, multiplies);
std::vector<size_t> patchCenterShift(nPatchDim);
for (size_t patchDim = 0; patchDim < nPatchDim; patchDim++)
patchCenterShift[patchDim] = patchSize[patchDim] / 2;
// For efficiency, we don't copy data element-by-element, but copy
// continuous columns in the memory.
// When dealing with columns, we simply ignore the last dimension (arrays are C-ordered)
// in index computations and copy whole lines along that dimension.
// The number of columns in each dimension of the orig. data.
std::vector<size_t> patchDataColumnNumber = std::vector<size_t>(patchDataSize.begin(), patchDataSize.end() - 1);
size_t patchDataColumnNumberFlat = std::accumulate(patchDataColumnNumber.begin(), patchDataColumnNumber.end(),
size_t{1}, multiplies);
// Length of a single column.
size_t columnSize = patchDataSize[ndim - 1];
// This function supports batching, i.e. we only extract 'patchesPerBatch' patches
// starting with 'firstPatchIndex' patch.
// Loop over all patches in a batch.
// Since the number of dimensions is dynamic, we loop over a flat index
// and then unflatten it.
for (size_t indexFlat = firstPatchIndex; indexFlat < firstPatchIndex + patchesPerBatch; indexFlat++)
{
std::vector<size_t> patchIndexNd = unflattenIndex(indexFlat, patchNumber);
// Figure out where in the orig. data the patch begins.
// For patched dimensions, this is index * stride.
// For the rest it's zero, since the whole dim. is copied.
std::vector<size_t> dataSelectorStart(ndim, 0);
std::vector<size_t> patchCenter(nPatchDim);
for (size_t dim = 0; dim < ndim; dim++)
{
auto itSourceDim = std::find(sourceAxes.begin(), sourceAxes.end(), dim);
if (itSourceDim != sourceAxes.end())
{
size_t patchDim = itSourceDim - sourceAxes.begin();
dataSelectorStart[dim] = patchIndexNd[patchDim] * patchStride[patchDim];
// Keep the location of the patch's center, which needs to be returned to the caller.
patchCenter[patchDim] = dataSelectorStart[dim] + patchCenterShift[patchDim];
}
}
// Where in the output array should we write.
// All the patches are stacked one after another.
size_t outputOffset = indexFlat * patchDataSizeFlat;
size_t centerOutputOffset = indexFlat * nPatchDim;
// If the output buffer is batch-sized. Adjust the offset to the batch.
if (isBatchSizedBuffer)
{
outputOffset = (indexFlat - firstPatchIndex) * patchDataSizeFlat;
centerOutputOffset = (indexFlat - firstPatchIndex) * nPatchDim;
}
for (size_t columnIndexFlat = 0; columnIndexFlat < patchDataColumnNumberFlat; columnIndexFlat++)
{
std::vector<size_t> columnIndexNd = unflattenIndex(columnIndexFlat, patchDataColumnNumber);
// Where the column starts in the original data .
std::vector<size_t> sourceIndexNd(ndim);
for (size_t dim = 0; dim < ndim; dim++)
sourceIndexNd[dim] = dataSelectorStart[dim] + columnIndexNd[dim];
// Handle the last 'column' dimension: point to its start, we take all the data.
sourceIndexNd[ndim - 1] = dataSelectorStart[ndim - 1];
size_t sourceIndexFlat = flattenIndex(sourceIndexNd, dataSize);
// Copy a whole column.
std::copy(&pData[sourceIndexFlat], &pData[sourceIndexFlat + columnSize],
pOutput + outputOffset + columnIndexFlat * columnSize);
}
// Copy the patch center.
std::copy(patchCenter.begin(), patchCenter.end(), pOutputCenters + centerOutputOffset);
}
}
template<typename T>
void extract_patches(void* pDataVoid, void* pOutputVoid, size_t* pOutputCenters,
size_t ndim, const std::vector<size_t>& dataSize,
const std::vector<size_t>& sourceAxes,
const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride)
{
auto multiplies = std::multiplies<size_t>(); // Cache the functor, don't recreate it in a loop.
// Number of patches along the patched dimensions.
std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, sourceAxes, patchSize, patchStride, 1ULL);
// Total flat number of patches that will be returned.
size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies);
extract_patches_batched<T>(pDataVoid, pOutputVoid, pOutputCenters, ndim, dataSize, sourceAxes,
patchSize, patchStride,
0, patchNumberFlat);
}
/**
* \brief
*
* Extract patches/windows from a 4-dimensional array.
* Each patch gets split into training data: X and Y.
* X holds the whole hypercube, except for the last frame. Y holds a single scalar
* from the center of the last frame. (Time is the first dimension, C-order is assumed.)
* 'Empty' patches are those, where all values in X and the Y value are equal to the 'empty value'.
* Empty patches do not get extracted.
* Extraction is performed in batches, returning control after 'batchSize' patches were extracted.
*
*/
template<typename T>
void extract_patched_training_data_without_empty_4d(
T* pData,
size_t dataStartFlat, size_t dataEndFlat,
const std::vector<size_t>& dataSize,
const std::vector<size_t>& patchSize,
const std::vector<size_t>& patchStride,
const std::vector<size_t>& patchInnerStride,
size_t lastFrameGap,
bool skipEmptyPatches, T emptyValue,
size_t batchStartIndex, size_t batchSize,
float_t undersamplingProb,
T* pOutX, T* pOutY, size_t* pOutIndices,
size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached)
{
// Cache the functor, don't recreate it in a loop.
auto multiplies = std::multiplies<size_t>();
// Prepare the random distribution for undersampling.
std::random_device r;
std::default_random_engine randomEngine(r());
std::uniform_real_distribution<float_t> randomDist(0.0f, 1.0f);
const size_t ndim = 4;
if (dataSize.size() != ndim || patchSize.size() != ndim || patchStride.size() != ndim)
throw std::runtime_error("Invalid number of dimensions. Expected four.");
if (patchInnerStride[3] != 1)
{
printf("Inner stride is probably broken, since we copy patch by columns. \n");
throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n");
}
// Number of patches along each dimension.
std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride,
patchInnerStride, lastFrameGap);
// Total flat number of patches.
size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies);
// Total number of elements in an 'X' patch.
std::vector<size_t> patchSizeX(patchSize);
// The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'.
patchSizeX[0] -= 1;
size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies);
// For efficiency, we don't copy data element-by-element, but copy
// continuous columns in the memory.
// When dealing with columns, we simply ignore the last dimension (arrays are C-ordered)
// in index computations and copy whole lines along that dimension.
// The number of columns in each dimension.
std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1);
size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(),
patchXColumnNumber.end(), size_t{1}, multiplies);
// Length of a single column.
size_t columnSize = patchSize[ndim - 1];
// This function supports batching, i.e. we only extract 'batchSize' patches
// starting with 'batchStartIndex' patch.
// Loop over all patches in a batch. Skip 'empty' patches.
// We loop over a flat index and then unflatten it. We could write 'ndim' nested loops,
// but this way is a little less verbose and more flexible.
// Optimization: prepare allocate all vectors that we'll need, instead doing it in the loop.
Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber);
IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber);
Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize);
Index4d dataIndexNd{};
Index4d patchIndexNd{};
IndexNd<3> columnIndexNd{};
Index4d sourceIndexNd{};
Index4d sourceIndexNdY{};
bool pInputEndReached = false;
size_t patchesExtracted = 0;
size_t indexFlat = batchStartIndex;
while (patchesExtracted < batchSize && indexFlat < patchNumberFlat)
{
// Skip some of the patches according to the provided probability.
float_t random = randomDist(randomEngine);
bool dontUndersample = undersamplingProb > 0.999; // Floating-point comparison.
if (dontUndersample || random < undersamplingProb)
{
unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd);
// Figure out where in the orig. data the patch begins.
for (size_t dim = 0; dim < ndim; dim++)
dataIndexNd.X[dim] = patchIndexNd.X[dim] * patchStride[dim];
// Where in the output array should we write.
// All the patches are stacked one after another.
size_t outputOffsetX = patchesExtracted * patchSizeXFlat;
size_t outputOffsetY = patchesExtracted;
size_t outputOffsetIndices = patchesExtracted * ndim;
bool xIsEmpty = skipEmptyPatches; // Init to false, if not skipping empty patches.
for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++)
{
unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd);
// Where the column starts in the original data .
for (size_t dim = 0; dim < ndim - 1; dim++)
sourceIndexNd.X[dim] = dataIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim];
// Handle the last 'column' dimension: point to its start, we take all the data.
sourceIndexNd.X[ndim - 1] = dataIndexNd.X[ndim - 1];
size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS);
size_t sourceIndexRel = sourceIndexFlat - dataStartFlat;
// The input data is buffered, i.e. we only have a chunk of it.
// Check if the buffer has the data we need.
if (sourceIndexFlat + columnSize >= dataEndFlat)
{
pInputEndReached = true;
break;
}
// Check if the column is empty.
auto first = &pData[sourceIndexRel];
auto last = &pData[sourceIndexRel + columnSize];
bool allValuesEqual = skipEmptyPatches && std::adjacent_find(first, last, std::not_equal_to<T>()) == last;
xIsEmpty = xIsEmpty && *first == emptyValue && allValuesEqual;
// Copy the whole column, even if it's empty. We don't know if the whole patch is empty or not.
std::copy(first, last, pOutX + outputOffsetX + columnIndexFlat * columnSize);
}
// Extract Y.
// Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead.
sourceIndexNdY.X[0] = dataIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap;
for (size_t dim = 1; dim < ndim; dim++)
{
// Take the value in the middle of the patch.
sourceIndexNdY.X[dim] = dataIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim];
}
size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS);
size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat;
// Check if the buffer has the data we need.
if (pInputEndReached || sourceIndexYFlat >= dataEndFlat)
{
pInputEndReached = true;
break;
}
T y = pData[sourceIndexYRel];
bool yIsEmpty = y == emptyValue;
if (!xIsEmpty || !yIsEmpty)
{
// Copy the results.
*(pOutY + outputOffsetY) = y;
std::copy(&dataIndexNd.X[0], &dataIndexNd.X[4], pOutIndices + outputOffsetIndices);
// Advance the output offset.
patchesExtracted += 1;
}
}
indexFlat += 1;
}
// Return the information about the extracted batch.
*pOutPatchesExtracted = patchesExtracted;
*pOutNextBatchIndex = indexFlat;
*pOutInputEndReached = pInputEndReached;
}
///
/// A multithreaded version of the same method. Uses an atomic counter to synchronize output to the buffer.
///
template<typename T>
void extract_patched_training_data_without_empty_4d_multi(
T* pData,
size_t dataStartFlat, size_t dataEndFlat,
const std::vector<size_t>& dataSize,
const std::vector<size_t>& patchSize,
const std::vector<size_t>& patchStride,
const std::vector<size_t>& patchInnerStride,
size_t lastFrameGap,
bool skipEmptyPatches, T emptyValue,
size_t batchStartIndex, size_t batchSize,
float_t undersamplingProb,
std::atomic<size_t>& globalBufferOffset,
T* pOutX, T* pOutY, size_t* pOutIndices,
size_t* pOutPatchesExtracted, size_t* pOutPatchesEmpty,
size_t* pOutNextBatchIndex, bool* pOutInputEndReached)
{
// Cache the functor, don't recreate it in a loop.
auto multiplies = std::multiplies<size_t>();
// Prepare the random distribution for undersampling.
std::random_device r;
std::default_random_engine randomEngine(r());
std::uniform_real_distribution<float_t> randomDist(0.0f, 1.0f);
const size_t ndim = 4;
if (dataSize.size() != ndim || patchSize.size() != ndim || patchStride.size() != ndim)
throw std::runtime_error("Invalid number of dimensions. Expected four.");
if (patchInnerStride[3] != 1)
{
printf("Inner stride is probably broken, since we copy patch by columns. \n");
throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n");
}
// Number of patches along each dimension.
std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride,
patchInnerStride, lastFrameGap);
// Total flat number of patches.
size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies);
// Total number of elements in an 'X' patch.
std::vector<size_t> patchSizeX(patchSize);
// The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'.
patchSizeX[0] -= 1;
size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies);
// For efficiency, we don't copy data element-by-element, but copy continuous columns in the memory.
// When dealing with columns, we simply ignore the last dimension (arrays are C-ordered)
// in index computations and copy whole lines along that dimension.
// The number of columns in each dimension.
std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1);
size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(),
patchXColumnNumber.end(), size_t{1}, multiplies);
// Length of a single column.
size_t columnSize = patchSize[ndim - 1];
// Consistency check: A thread should be allocated at least some work.
if (batchStartIndex >= patchNumberFlat)
{
printf("Thread's start index is larger than the total number of patches.\n");
throw std::runtime_error("Thread's start index is larger than the total number of patches.");
}
// This function supports batching, i.e. we only extract 'batchSize' patches
// starting with 'batchStartIndex' patch.
// Loop over all patches in a batch. Skip 'empty' patches.
// We loop over a flat index and then unflatten it. We could write 'ndim' nested loops,
// but this way is a little less verbose and more flexible.
// Optimization: allocate all the vectors that we'll need, instead of doing it in the loop.
Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber);
IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber);
Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize);
Index4d dataIndexNd{};
Index4d patchIndexNd{};
IndexNd<3> columnIndexNd{};
Index4d sourceIndexNd{};
Index4d sourceIndexNdY{};
// Allocate memory for storing a single patch that is being processed.
// When it's assembled, it will be copied to the global buffer.
// If we don't have an intermediate buffer, another thread can write over our results.
std::vector<T> patchDataX(patchSizeXFlat);
bool inputEndReached = false;
size_t patchesExtracted = 0;
size_t patchesEmpty = 0;
size_t indexFlat = batchStartIndex;
// Batch counts input patches, not the output (like in single-threaded code).
// This makes the code more deterministic, i.e. we are sure that at the end
// all input has been processed.
// But this also means, that fewer (or even zero) patches could be returned.
size_t batchEndIndex = batchStartIndex + batchSize;
while (indexFlat < batchEndIndex && indexFlat < patchNumberFlat) // Note: break conditions below, due to convenience.
{
// Skip some of the patches according to the provided probability.
float_t random = randomDist(randomEngine);
bool dontUndersample = undersamplingProb > 0.999; // Floating-point comparison.
if (dontUndersample || random < undersamplingProb)
{
unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd);
// Figure out where in the orig. data the patch begins.
for (size_t dim = 0; dim < ndim; dim++)
dataIndexNd.X[dim] = patchIndexNd.X[dim] * patchStride[dim];
bool xIsEmpty = skipEmptyPatches; // Init to false, if not skipping empty patches.
for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++)
{
unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd);
// Where the column starts in the original data .
for (size_t dim = 0; dim < ndim - 1; dim++)
sourceIndexNd.X[dim] = dataIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim];
// Handle the last 'column' dimension: point to its start, we take all the data.
sourceIndexNd.X[ndim - 1] = dataIndexNd.X[ndim - 1];
size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS);
size_t sourceIndexRel = sourceIndexFlat - dataStartFlat;
// The input data is buffered, i.e. we only have a chunk of it.
// Check if the buffer has the data we need.
if (sourceIndexFlat + columnSize >= dataEndFlat)
{
inputEndReached = true;
break;
}
// Check if the column is empty.
auto first = &pData[sourceIndexRel];
auto last = &pData[sourceIndexRel + columnSize];
bool allValuesEqual = skipEmptyPatches && std::adjacent_find(first, last, std::not_equal_to<T>()) == last;
xIsEmpty = xIsEmpty && *first == emptyValue && allValuesEqual;
// Copy the whole column, even if it's empty. We don't know if the whole patch is empty or not.
std::copy(first, last, patchDataX.data() + columnIndexFlat * columnSize);
}
// Extract Y.
// Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead.
sourceIndexNdY.X[0] = dataIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap;
for (size_t dim = 1; dim < ndim; dim++)
{
// Take the value in the middle of the patch.
sourceIndexNdY.X[dim] = dataIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim];
}
size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS);
size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat;
// Check if the buffer has the data we need.
if (inputEndReached || sourceIndexYFlat >= dataEndFlat)
{
inputEndReached = true;
break;
}
T y = pData[sourceIndexYRel];
bool yIsEmpty = y == emptyValue;
if (!xIsEmpty || !yIsEmpty)
{
// Claim output buffer space by advancing the atomic counter.
// Atomic fetch_add performs read-modify-write as a single operation, so we are thread safe.
size_t outputOffset = globalBufferOffset.fetch_add(1);
// Where in the output array should we write.
size_t outputOffsetX = outputOffset * patchSizeXFlat;
size_t outputOffsetY = outputOffset;
size_t outputOffsetIndices = outputOffset * ndim;
// Write the results.
std::copy(patchDataX.begin(), patchDataX.end(), pOutX + outputOffsetX);
*(pOutY + outputOffsetY) = y;
std::copy(&dataIndexNd.X[0], &dataIndexNd.X[4], pOutIndices + outputOffsetIndices);
// Count how many patches this thread has extracted.
patchesExtracted += 1;
}
else
{
patchesEmpty += 1;
}
}
indexFlat += 1;
}
// Return the information about the extracted batch.
*pOutPatchesExtracted = patchesExtracted;
*pOutPatchesEmpty = patchesEmpty;
*pOutNextBatchIndex = indexFlat;
*pOutInputEndReached = inputEndReached;
}
/**
*
* This version doesn't use undersampling, empty patch skipping or striding.
* It's meant for dense multi-threaded patch extraction.
*
*/
template<typename T>
void extract_patched_training_data_dense_4d(T* pData,
size_t dataStartFlat, size_t dataEndFlat,
const std::vector<size_t>& dataSize,
const std::vector<size_t>& patchSize,
const std::vector<size_t>& patchInnerStride,
size_t lastFrameGap,
size_t batchStartIndex, size_t batchSize,
T* pOutX, T* pOutY,
size_t* pOutPatchesExtracted,
bool* pOutInputEndReached)
{
const size_t ndim = 4;
const std::vector<size_t> patchStride{ 1, 1, 1, 1 };
// Cache the functor, don't recreate it in a loop.
auto multiplies = std::multiplies<size_t>();
if (dataSize.size() != ndim || patchSize.size() != ndim)
throw std::runtime_error("Invalid number of dimensions. Expected four.");
if (patchInnerStride[3] != 1)
{
printf("Inner stride is probably broken, since we copy patch by columns. \n");
throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n");
}
// Number of patches along each dimension.
std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride,
patchInnerStride, lastFrameGap);
// Total flat number of patches.
size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies);
// Total number of elements in an 'X' patch.
std::vector<size_t> patchSizeX(patchSize);
// The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'.
patchSizeX[0] -= 1;
size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies);
// For efficiency, we don't copy data element-by-element, but copy
// continuous columns in the memory.
// When dealing with columns, we simply ignore the last dimension (arrays are C-ordered)
// in index computations and copy whole lines along that dimension.
// The number of columns in each dimension.
std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1);
size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(),
patchXColumnNumber.end(), size_t{1}, multiplies);
// Length of a single column.
size_t columnSize = patchSize[ndim - 1];
// This function supports batching, i.e. we only extract 'batchSize' patches
// starting with 'batchStartIndex' patch.
// We loop over a flat index and then unflatten it. We could write 'ndim' nested loops,
// but this way is a little less verbose and more flexible.
// Optimization: allocate all vectors that we'll need, instead of doing it in the loop.
Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber);
Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize);
IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber);
// index4d_t dataIndexNd{}; <-- Is the same as patch index, since we have no striding.
Index4d patchIndexNd{};
IndexNd<3> columnIndexNd{};
Index4d sourceIndexNd{};
Index4d sourceIndexNdY{};
bool inputEndReached = false;
size_t patchesExtracted = 0;
while (patchesExtracted < batchSize && batchStartIndex + patchesExtracted < patchNumberFlat)
{
// Since we don't skip patches, flat index follows 'patchesExtracted'.
size_t indexFlat = batchStartIndex + patchesExtracted;
unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd);
// Where in the output array should we write.
// All the patches are stacked one after another.
size_t outputOffsetX = patchesExtracted * patchSizeXFlat;
size_t outputOffsetY = patchesExtracted;
for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++)
{
unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd);
// Where the column starts in the original data .
for (size_t dim = 0; dim < ndim - 1; dim++)
sourceIndexNd.X[dim] = patchIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim];
// Handle the last 'column' dimension: point to its start, we take all the data.
sourceIndexNd.X[ndim - 1] = patchIndexNd.X[ndim - 1];
size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS);
size_t sourceIndexRel = sourceIndexFlat - dataStartFlat;
// The input data is buffered, i.e. we only have a chunk of it.
// Check if the buffer has the data we need.
if (sourceIndexFlat + columnSize >= dataEndFlat)
{
inputEndReached = true;
break;
}
// Copy the whole column.
auto first = &pData[sourceIndexRel];
auto last = &pData[sourceIndexRel + columnSize];
std::copy(first, last, pOutX + outputOffsetX + columnIndexFlat * columnSize);
}
// Extract Y.
// Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead.
sourceIndexNdY.X[0] = patchIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap;
for (size_t dim = 1; dim < ndim; dim++)
{
// Take the value in the middle of the patch.
sourceIndexNdY.X[dim] = patchIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim];
}
size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS);
size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat;
// Check if the buffer has the data we need.
if (inputEndReached || sourceIndexYFlat >= dataEndFlat)
{
inputEndReached = true;
break;
}
// Copy the Y
*(pOutY + outputOffsetY) = pData[sourceIndexYRel];
// Advance the output offset.
patchesExtracted += 1;
}
// Return the information about the extracted batch.
*pOutPatchesExtracted = patchesExtracted;
*pOutInputEndReached = inputEndReached;
}
template <typename T>
void sparse_insert_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues,
size_t valueNumber)
{
size_t ndim = pArray->GetNdim();
typename BufferedNdArray<T>::Tuple indexNd(ndim);
for (size_t i = 0; i < valueNumber; i++)
{
size_t const* pIndex = pIndices + i * ndim;
std::copy(pIndex, pIndex + ndim, indexNd.data());
pArray->Write(indexNd, *(pValues + i));
}
}
template <typename T>
void sparse_insert_slices_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues,
size_t sliceNdim, size_t sliceNumber)
{
size_t ndim = pArray->GetNdim(); // Total array axis number.
size_t sliceIndexNdim = ndim - sliceNdim; // Length of a slice index (non-sliced axis number).
typename BufferedNdArray<T>::Tuple sliceIndexNd(sliceIndexNdim);
size_t sliceSizeFlat = pArray->GetSliceSizeFromNdim(sliceNdim);
for (size_t i = 0; i < sliceNumber; i++)
{
size_t const* pIndex = pIndices + i * sliceIndexNdim;
std::copy(pIndex, pIndex + sliceIndexNdim, sliceIndexNd.data());
pArray->WriteSlice(sliceIndexNd, sliceNdim, pValues + i * sliceSizeFlat);
}
}
///
/// Insert patches at location specified by the indices (lower patch corner).
/// If 'isConstPatch' is false, expect a buffer with N patches, otherwise take a buffer with a single patch.
///
template <typename T>
void sparse_insert_patches_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues,
size_t const* pPatchSize, size_t patchNumber, bool isConstPatch)
{
size_t ndim = pArray->GetNdim();
typename BufferedNdArray<T>::Tuple patchSize(pPatchSize, pPatchSize + ndim);
size_t patchSizeFlat = std::accumulate(patchSize.begin(), patchSize.end(), 1, std::multiplies<>());
typename BufferedNdArray<T>::Tuple patchIndexNd(ndim, 0);
for (size_t i = 0; i < patchNumber; i++)
{
size_t const* pIndex = pIndices + i * ndim;
std::copy(pIndex, pIndex + ndim, patchIndexNd.data());
if (!isConstPatch)
pArray->WritePatch(patchIndexNd, patchSize, pValues + i * patchSizeFlat);
else
pArray->WritePatch(patchIndexNd, patchSize, pValues); // Always write the same patch.
}
}
template <typename T>
void sparse_insert_const_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const& constValue,
size_t valuesToInsert)
{
size_t ndim = pArray->GetNdim();
typename BufferedNdArray<T>::Tuple indexNd(ndim);
for (size_t i = 0; i < valuesToInsert; i++)
{
size_t const* pIndex = pIndices + i * ndim;
std::copy(pIndex, pIndex + ndim, indexNd.data());
pArray->Write(indexNd, constValue);
}
}
void _multithreading_test_worker(uint8_t* pData, uint64_t offset, uint64_t size)
{
for (size_t i = 0; i < size; i++)
{
size_t computationNumber = 20;
size_t dummyResult = 0;
for (size_t j = 0; j < computationNumber; j++)
{
dummyResult += 13 + dummyResult * 5 % 3;
}
pData[offset + i] += static_cast<uint8_t>(dummyResult % 256);
}
}
//todo Keeping state between calls experiment.
uint64_t StaticState = 5;
extern "C" {
// todo Get rid of the void pointers. Ctypes can handle typed pointers.
// todo remove the test code.
__DLLEXPORT
void test(void* pInput, int width, int height) {
double* pData = static_cast<double *>(pInput);
for (int i = 0; i < width * height; ++i) {
pData[i] = pData[i] * 2;
}
}
__DLLEXPORT
void static_state_test(uint64_t increment, uint64_t* out)
{
StaticState += increment;
*out = StaticState;
}
__DLLEXPORT
void multithreading_test(uint8_t* pData, uint64_t size, uint64_t threadNumber)
{
std::vector<std::thread> threads{};
size_t chunkSize = size / threadNumber;
for (size_t i = 0; i < threadNumber; i++)
{
size_t chunkOffset = i * chunkSize;
size_t actualChunkSize = std::min(chunkSize, size - chunkOffset);
threads.emplace_back([=]() { _multithreading_test_worker(pData, chunkOffset, actualChunkSize); });
}
for (auto& thread : threads)
thread.join();
}
__DLLEXPORT
void resize_array_point_float32(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth,
void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) {
resize_array_point<float_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth,
pOutputRaw, targetWidth, targetHeight, targetDepth);
}
__DLLEXPORT
void resize_array_point_float64(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth,
void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) {
resize_array_point<double_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth,
pOutputRaw, targetWidth, targetHeight, targetDepth);
}
__DLLEXPORT
void resize_array_point_uint8(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth,
void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) {
resize_array_point<uint8_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth,
pOutputRaw, targetWidth, targetHeight, targetDepth);
}
__DLLEXPORT
void extract_patches_uint8(void* data, void* output, size_t* outputCenters, size_t ndim,
size_t* dataSize, size_t dataSizeL,
size_t* sourceAxes, size_t sourceAxesL,
size_t* patchSize, size_t patchSizeL,
size_t* patchStride, size_t patchStrideL)
{
extract_patches<uint8_t>(data, output, outputCenters, ndim,
std::vector<size_t>(dataSize, dataSize + dataSizeL),
std::vector<size_t>(sourceAxes, sourceAxes + sourceAxesL),
std::vector<size_t>(patchSize, patchSize + patchSizeL),
std::vector<size_t>(patchStride, patchStride + patchStrideL));
}
__DLLEXPORT
void extract_patches_batched_uint8(void* data, void* output, size_t* outputCenters, size_t ndim,
size_t* dataSize, size_t dataSizeL,
size_t* sourceAxes, size_t sourceAxesL,
size_t* patchSize, size_t patchSizeL,
size_t* patchStride, size_t patchStrideL,
size_t firstPatchIndex, size_t patchesPerBatch, bool isBatchSizedBuffer)
{
extract_patches_batched<uint8_t>(data, output, outputCenters, ndim,
std::vector<size_t>(dataSize, dataSize + dataSizeL),
std::vector<size_t>(sourceAxes, sourceAxes + sourceAxesL),
std::vector<size_t>(patchSize, patchSize + patchSizeL),
std::vector<size_t>(patchStride, patchStride + patchStrideL),
firstPatchIndex, patchesPerBatch, isBatchSizedBuffer);
}
__DLLEXPORT
void extract_patched_training_data_without_empty_4d_uint8(
uint8_t* pData,
size_t dataStartFlat,
size_t dataEndFlat,
size_t* dataSize,
size_t* patchSize,
size_t* patchStride,
size_t* patchInnerStride,
size_t lastFrameGap,
bool skipEmptyPatches,
uint8_t emptyValue,
size_t batchStartIndex,
size_t batchSize,
float_t undersamplingProb,
uint8_t* pOutX,
uint8_t* pOutY,
size_t* pOutIndices,
size_t* pOutPatchesExtracted,
size_t* pOutNextBatchIndex,
bool* pOutInputEndReached)
{
extract_patched_training_data_without_empty_4d<uint8_t>(pData,
dataStartFlat, dataEndFlat,
std::vector<size_t>(dataSize, dataSize + 4),
std::vector<size_t>(patchSize, patchSize + 4),
std::vector<size_t>(patchStride, patchStride + 4),
std::vector<size_t>(patchInnerStride, patchInnerStride + 4),
lastFrameGap,
skipEmptyPatches, emptyValue,
batchStartIndex, batchSize,
undersamplingProb,
pOutX, pOutY, pOutIndices,
pOutPatchesExtracted, pOutNextBatchIndex,
pOutInputEndReached);
}
__DLLEXPORT
void extract_patched_training_data_without_empty_4d_multithreaded_uint8(
uint8_t* pData,
size_t dataStartFlat,
size_t dataEndFlat,
size_t* pDataSize,
size_t* pPatchSize,
size_t* pPatchStride,
size_t* pPatchInnerStride,
size_t lastFrameGap,
bool skipEmptyPatches,
uint8_t emptyValue,
size_t batchStartIndex,
size_t batchSize,
float_t undersamplingProb,
size_t threadNumber,
uint8_t* pOutX,
uint8_t* pOutY,
size_t* pOutIndices,
size_t* pOutPatchesExtracted,
size_t* pOutNextBatchIndex,
bool* pOutInputEndReached)
{
const size_t ndim = 4;
std::vector<size_t> dataSize(pDataSize, pDataSize + ndim);
std::vector<size_t> patchSize(pPatchSize, pPatchSize + ndim);
std::vector<size_t> patchStride(pPatchStride, pPatchStride + ndim);
std::vector<size_t> patchInnerStride(pPatchInnerStride, pPatchInnerStride + ndim);
std::vector<std::thread> threads{};
std::atomic<size_t> globalBufferOffset{0};
std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap);
// Total flat number of patches.
size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, std::multiplies<>());
size_t patchesToProcess = std::min(batchSize, patchNumberFlat - batchStartIndex);
size_t chunkSize = patchesToProcess / threadNumber;
// Output buffers.
std::vector<size_t> patchesExtracted(threadNumber, 0);
std::vector<size_t> patchesEmpty(threadNumber, 0);
std::vector<size_t> nextBatchIndex(threadNumber, 0);
bool* inputEndReached = new bool[threadNumber];
for (size_t i = 0; i < threadNumber; i++)
{
// Each thread gets allocated a fixed chunk of the input.
// But a thread can write out an arbitrary number of patches, due to undersampling,
// running out of input buffer or empty patch skipping.
size_t chunkOffset = i * chunkSize;
size_t actualChunkSize = i < threadNumber - 1 ? chunkSize : patchesToProcess - chunkOffset;
threads.emplace_back([&, i, chunkOffset, actualChunkSize]() // Capture local vars by value!
{
extract_patched_training_data_without_empty_4d_multi<uint8_t>(
pData,
dataStartFlat, dataEndFlat,
dataSize, patchSize, patchStride, patchInnerStride,
lastFrameGap,
skipEmptyPatches, emptyValue,
batchStartIndex + chunkOffset,
actualChunkSize,
undersamplingProb,
globalBufferOffset,
pOutX, pOutY, pOutIndices,
&patchesExtracted[i], &patchesEmpty[i],
&nextBatchIndex[i], &inputEndReached[i]);
});
}
for (auto& thread : threads)
thread.join();
// Stop collecting results after encountering the first thread that couldn't finish.
bool endReached = false;
size_t totalPatchesExtracted = 0;
size_t lastNextBatchIndex = nextBatchIndex[threadNumber - 1]; // By default, the last thread is the last ;).
for (size_t i = 0; i < threadNumber; i++)
{
// printf("Thread %zu extracted %zu patches and skipped %zu. Run out: %d\n", i, patchesExtracted[i], patchesEmpty[i], inputEndReached[i]);
totalPatchesExtracted += patchesExtracted[i];
if (!endReached && inputEndReached[i])
{
endReached = true;
// If we didn't have enough data - start over (next batch) at the first thread that had to stop.
lastNextBatchIndex = nextBatchIndex[i];
}
else if (endReached)
{
// Validate the assumption that if a thread runs out of input data,
// then all the following threads extracted zero patches.
// We assume that patches are layed out linearly wrt. to input,
// if one thread requires an input element with at least index X, all following
// threads require that or even higher indices.
if (patchesExtracted[i] > 0)
{
printf("ASSUMPTION FAILED: We have run out of input data, \n");
printf("but the next thread %zu still extracted %zu patches. ", i, patchesExtracted[i]);
abort();
}
}
}
delete[] inputEndReached;
// Do a consistency check: number of global output buffer increments should be the same
// as the sum of local patch counters.
if (totalPatchesExtracted != globalBufferOffset)
{
printf("FAILED THE CONSISTENCY CHECK: PATCHES MISSING DUE TO A RACE CONDITION?\n");
printf("Expected %zu patches to be written, got %zu instead\n",
totalPatchesExtracted, globalBufferOffset.load());
abort();
}
*pOutPatchesExtracted = totalPatchesExtracted;
*pOutNextBatchIndex = lastNextBatchIndex;
*pOutInputEndReached = endReached;
}
__DLLEXPORT
void extract_patched_training_data_multithreaded_uint8(
uint8_t* pData,
size_t dataStartFlat,
size_t dataEndFlat,
size_t* dataSize,
size_t* patchSize,
size_t* patchInnerStride,
size_t lastFrameGap,
size_t batchStartIndex,
size_t batchSize,
size_t threadNumber,
uint8_t* pOutX,
uint8_t* pOutY,
size_t* pOutPatchesExtracted,
size_t* pOutNextBatchIndex,
bool* pOutInputEndReached)
{
const int ndim = 4;
auto multiplies = std::multiplies<size_t>();
// Total number of elements in an 'X' patch.
std::vector<size_t> patchSizeX(patchSize, patchSize + 4);
// The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'.
patchSizeX[0] -= 1;
size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies);
std::vector<std::thread> threads{};
size_t chunkSize = batchSize / threadNumber;
// Output buffers.
std::vector<size_t> patchesExtracted(threadNumber, 0);
std::vector<size_t> nextBatchIndex(threadNumber, 0);
bool* inputEndReached = new bool[threadNumber];
for (size_t i = 0; i < threadNumber; i++)
{
size_t chunkOffset = i * chunkSize;
size_t actualChunkSize = i < threadNumber - 1 ? chunkSize : batchSize - chunkOffset;
threads.emplace_back([&, i, chunkOffset, actualChunkSize]()
{
extract_patched_training_data_dense_4d<uint8_t>(
pData,
dataStartFlat, dataEndFlat,
std::vector<size_t>(dataSize, dataSize + ndim),
std::vector<size_t>(patchSize, patchSize + ndim),
std::vector<size_t>(patchInnerStride, patchInnerStride + ndim),
lastFrameGap,
batchStartIndex + chunkOffset,
actualChunkSize,
pOutX + chunkOffset * patchSizeXFlat,
pOutY + chunkOffset,
&patchesExtracted[i],
&inputEndReached[i]
);
});
}
for (auto& thread : threads)
thread.join();
// Stop collecting results after encountering the first thread that couldn't finish.
bool endReached = false;
size_t totalPatchesExtracted = 0;
for (size_t i = 0; i < threadNumber; i++)
{
totalPatchesExtracted += patchesExtracted[i];
if (inputEndReached[i])
{
endReached = true;
break;
}
}
*pOutPatchesExtracted = totalPatchesExtracted;
*pOutNextBatchIndex = batchStartIndex + totalPatchesExtracted; // No empty skipping, so it's the same.
*pOutInputEndReached = endReached;
delete[] inputEndReached;
}
__DLLEXPORT
void sparse_insert_into_bna_uint8(void* pArrayRaw,
size_t const* pIndices,
uint8_t const* pValues,
size_t valuesToInsert)
{
BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw);
sparse_insert_into_bna<uint8_t>(pArray, pIndices, pValues, valuesToInsert);
}
__DLLEXPORT
void sparse_insert_slices_into_bna_float32(void* pArrayRaw,
size_t const* pIndices,
float_t const* pValues,
size_t sliceNdim,
size_t valueNumber)
{
auto pArray = reinterpret_cast<BufferedNdArray<float_t>*>(pArrayRaw);
sparse_insert_slices_into_bna<float_t>(pArray, pIndices, pValues, sliceNdim, valueNumber);
}
__DLLEXPORT
void sparse_insert_patches_into_bna_uint8(void* pArrayRaw,
size_t const* pIndices,
uint8_t const* pValues,
size_t const* pPatchSize,
size_t patchNumber,
bool isConstPatch)
{
BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw);
sparse_insert_patches_into_bna(pArray, pIndices, pValues, pPatchSize, patchNumber, isConstPatch);
}
__DLLEXPORT
void sparse_insert_patches_into_bna_float32(void* pArrayRaw,
size_t const* pIndices,
float_t const* pValues,
size_t const* pPatchSize,
size_t patchNumber,
bool isConstPatch)
{
BufferedNdArray<float_t>* pArray = reinterpret_cast<BufferedNdArray<float_t>*>(pArrayRaw);
sparse_insert_patches_into_bna(pArray, pIndices, pValues, pPatchSize, patchNumber, isConstPatch);
}
__DLLEXPORT
void sparse_insert_const_into_bna_uint8(void* pArrayRaw,
size_t const* pIndices,
uint8_t constValue,
size_t valueNumber)
{
BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw);
sparse_insert_const_into_bna<uint8_t>(pArray, pIndices, constValue, valueNumber);
}
__DLLEXPORT
void smooth_3d_array_average_float(float_t const* pInputData,
size_t const* pDataSize,
size_t kernelRadius,
float_t* pOutputData)
{
smooth_3d_array_average(pInputData, IndexNd<3>(pDataSize, pDataSize + 3), kernelRadius, pOutputData);
}
void upscale_attention_patch(float_t const* pAttPatchSource,
std::vector<size_t> const& attPatchSize,
std::vector<size_t> const& attPatchSliceSizes,
std::vector<size_t> const& targetSize,
Index4d const& targetSliceSizes,
std::vector<float_t>& outputPatch)
{
for (size_t targetT = 0; targetT < targetSize[0]; targetT++)
{
size_t patchT = int(roundf(static_cast<float>(targetT) / (targetSize[0] - 1) * (attPatchSize[0] - 1)));
for (size_t targetZ = 0; targetZ < targetSize[1]; targetZ++)
{
// An edge-case for 2D data.
size_t patchZ = targetSize[1] > 1 ?
int(roundf(static_cast<float>(targetZ) / (targetSize[1] - 1) * (attPatchSize[1] - 1)))
: 0;
for (size_t targetY = 0; targetY < targetSize[2]; targetY++)
{
size_t patchY = int(roundf(static_cast<float>(targetY) / (targetSize[2] - 1) * (attPatchSize[2] - 1)));
for (size_t targetX = 0; targetX < targetSize[3]; targetX++)
{
size_t patchX = int(roundf(static_cast<float>(targetX) / (targetSize[3] - 1) * (attPatchSize[3] - 1)));
size_t outputIndexFlat = targetT * targetSliceSizes.X[0] + targetZ * targetSliceSizes.X[1] +
targetY * targetSliceSizes.X[2] + targetX * targetSliceSizes.X[3];
size_t attIndexFlat = patchT * attPatchSliceSizes[0] + patchZ * attPatchSliceSizes[1] +
patchY * attPatchSliceSizes[2] + patchX * attPatchSliceSizes[3];
outputPatch[outputIndexFlat] = *(pAttPatchSource + attIndexFlat);
}
}
}
}
}
///
/// Aggregates a raw 8D attention volume into a 4D volume
/// by adding attention from each patch to spatial positions.
/// Essentially computes "overall voxel importance".
///
// todo Move to a separate project?
__DLLEXPORT
void aggregate_attention_volume(void* pAttentionRawArray,
size_t* pDataSize,
size_t* pPatchXSize,
size_t* pPredictionStride,
void* pAttentionOutArray)
{
// todo prediction delay isn't needed anymore, because attention is written based on X-indices.
constexpr size_t DataNdim = 4;
constexpr size_t AttNdim = 8;
auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray);
auto pAttentionOut = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionOutArray);
std::vector<size_t> dataSize{ pDataSize, pDataSize + DataNdim };
std::vector<size_t> patchXSize{ pPatchXSize, pPatchXSize + DataNdim };
Index4d patchXSizeNd{pPatchXSize, pPatchXSize + DataNdim};
std::vector<size_t> predictionStride{ pPredictionStride, pPredictionStride + DataNdim };
std::vector<size_t> attVolSize = pAttentionRaw->GetShape();
// Domain size includes only the spatiotemporal dimensions.
std::vector<size_t> attVolDomainSize{ attVolSize.data(), attVolSize.data() + DataNdim };
std::vector<size_t> attPatchSize{ attVolSize.begin() + DataNdim, attVolSize.end() };
auto multiplesFunc = std::multiplies<>();
size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc);
size_t patchXSizeFlat = std::accumulate(patchXSize.begin(), patchXSize.end(), size_t{1}, multiplesFunc);
size_t attVolDomainSizeFlat = std::accumulate(attVolDomainSize.begin(), attVolDomainSize.end(), size_t{1}, multiplesFunc);
std::vector<size_t> attPatchSliceSizes = compute_slice_sizes(attPatchSize);
Index4d patchXSliceSizes = compute_slice_sizes_fast<DataNdim>(patchXSize);
Index4d dataSliceSizes = compute_slice_sizes_fast<DataNdim>(dataSize);
Index4d attVolDomainSliceSizes = compute_slice_sizes_fast<DataNdim>(attVolDomainSize);
std::vector<float_t> attPatchRaw(attPatchSizeFlat);
std::vector<float_t> attPatchScaled(patchXSizeFlat);
std::vector<size_t> attIndexVec(DataNdim, 0);
for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++)
{
Index4d attIndexNd{};
Index4d dataIndexNd{};
unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd);
std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector.
// Compute the data index of the lower patch corner. Att volume can be smaller in the case of strided prediction.
for (size_t dim = 0; dim < DataNdim; dim++)
dataIndexNd[dim] = attIndexNd[dim] * predictionStride[dim];
if (attIndexNd[1] == 0 && attIndexNd[2] == 0 && attIndexNd[3] == 0)
{
auto time = std::chrono::system_clock::now();
std::time_t timeC = std::chrono::system_clock::to_time_t(time);
std::string timeStr{std::ctime(&timeC)};
timeStr.pop_back();
printf("[%s] Processing frame %zu / %zu. \n", timeStr.c_str(), attIndexNd[0], attVolSize[0]);
std::cout.flush();
}
// Read the raw attention patch.
pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data());
// Upscale it to match the data patch size.
upscale_attention_patch(attPatchRaw.data(), attPatchSize, attPatchSliceSizes,
patchXSize, patchXSliceSizes, attPatchScaled);
size_t firstIndexFlat = flattenIndex_fast(dataIndexNd, dataSliceSizes);
size_t lastIndexFlat = flattenIndex_fast(dataIndexNd + patchXSizeNd, dataSliceSizes);
pAttentionOut->_assureRangeInBuffer(firstIndexFlat, lastIndexFlat);
for (size_t patchIndexFlat = 0; patchIndexFlat < patchXSizeFlat; patchIndexFlat++)
{
Index4d patchIndexNd{};
unflattenIndex_fast(patchIndexFlat, patchXSliceSizes, patchIndexNd);
size_t outputIndexFlat = flattenIndex_fast(dataIndexNd + patchIndexNd, dataSliceSizes);
size_t relIndexFlat = outputIndexFlat - pAttentionOut->_bufferOffset;
pAttentionOut->_buffer[relIndexFlat] = pAttentionOut->_buffer[relIndexFlat] + attPatchScaled[patchIndexFlat];
pAttentionOut->_isBufferDirty = true;
}
}
printf("Input buffer efficiency: %f\n", pAttentionRaw->ComputeBufferEfficiency());
printf("Output buffer efficiency: %f\n", pAttentionOut->ComputeBufferEfficiency());
std::cout.flush();
}
///
/// A dumb version of attention aggregation that works much faster.
/// Used for debugging purposes.
///
__DLLEXPORT
void aggregate_attention_volume_dumb(void* pAttentionRawArray,
size_t* pDataSize,
size_t* pPatchSize,
size_t predictionDelay,
void* pAttentionOutArray)
{
const size_t dataNdim = 4;
const size_t attNdim = 8;
auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray);
auto pAttentionOut = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionOutArray);
std::vector<size_t> dataSize{ pDataSize, pDataSize + dataNdim };
std::vector<size_t> patchSize{ pPatchSize, pPatchSize + dataNdim };
std::vector<size_t> attVolSize = pAttentionRaw->GetShape();
std::vector<size_t> attPatchSize{ attVolSize[4], attVolSize[5], attVolSize[6], attVolSize[7] };
auto multiplesFunc = std::multiplies<>();
size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc);
size_t patchSizeFlat = std::accumulate(patchSize.begin(), patchSize.end(), size_t{1}, multiplesFunc);
size_t dataSizeFlat = std::accumulate(dataSize.begin(), dataSize.end(), size_t{1}, multiplesFunc);
Index4d dataSliceSizes = compute_slice_sizes_fast<4>(dataSize);
std::vector<size_t> attPatchSliceSizes = compute_slice_sizes(attPatchSize);
std::vector<size_t> attVolSliceSizesVec = compute_slice_sizes(attVolSize);
std::vector<float_t> attPatchRaw(attPatchSizeFlat);
std::vector<float_t> attPatchScaled(patchSizeFlat);
std::vector<size_t> domainLow{
patchSize[0] - 2 + predictionDelay,
patchSize[1] / 2,
patchSize[2] / 2,
patchSize[3] / 2
};
std::vector<size_t> domainHigh{
dataSize[0],
dataSize[1] - (patchSize[1] - patchSize[1] / 2) + 1,
dataSize[2] - (patchSize[2] - patchSize[2] / 2) + 1,
dataSize[3] - (patchSize[3] - patchSize[3] / 2) + 1
};
std::vector<size_t> dataIndexVec(dataNdim, 0);
for (size_t dataIndexFlat = 0; dataIndexFlat < dataSizeFlat; dataIndexFlat++)
{
Index4d dataIndexNd{};
unflattenIndex_fast(dataIndexFlat, dataSliceSizes, dataIndexNd);
std::copy(dataIndexNd.X, dataIndexNd.X + dataNdim, dataIndexVec.data()); // Convert to vector.
if (dataIndexNd.X[1] == 0 && dataIndexNd.X[2] == 0 && dataIndexNd.X[3] == 0)
printf("Processing frame %zu. \n", dataIndexNd.X[0]);
if (dataIndexNd.X[0] < domainLow[0] || dataIndexNd.X[0] >= domainHigh[0] ||
dataIndexNd.X[1] < domainLow[1] || dataIndexNd.X[1] >= domainHigh[1] ||
dataIndexNd.X[2] < domainLow[2] || dataIndexNd.X[2] >= domainHigh[2] ||
dataIndexNd.X[3] < domainLow[3] || dataIndexNd.X[3] >= domainHigh[3])
{
continue;
}
// Read the raw attention patch.
pAttentionRaw->ReadSlice(dataIndexVec, attNdim - dataNdim, attPatchRaw.data());
// size_t attentionPatchIndexFlat = attPatchRaw.size() / 2;
size_t attentionPatchIndexFlat = 0;
// printf("%f \n", attPatchRaw[0]);
float_t oldValue = pAttentionOut->Read(dataIndexFlat);
pAttentionOut->Write(dataIndexFlat, oldValue + attPatchRaw[attentionPatchIndexFlat]);
}
printf("Input buffer efficiency: %f\n", pAttentionRaw->ComputeBufferEfficiency());
printf("Output buffer efficiency: %f\n", pAttentionOut->ComputeBufferEfficiency());
}
///
///
///
__DLLEXPORT
void aggregate_attention_volume_local_attention(void* pAttentionRawArray,
double_t* pOutAttentionAvg,
double_t* pOutAttentionVar)
{
constexpr size_t DataNdim = 4;
constexpr size_t AttNdim = 8;
auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray);
std::vector<size_t> attVolSize = pAttentionRaw->GetShape();
// Domain size includes only the spatiotemporal dimensions.
std::vector<size_t> attVolDomainSize{ attVolSize.data(), attVolSize.data() + DataNdim };
std::vector<size_t> attPatchSize{ attVolSize.begin() + DataNdim, attVolSize.end() };
auto multiplesFunc = std::multiplies<>();
size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc);
size_t attVolDomainSizeFlat = std::accumulate(attVolDomainSize.begin(), attVolDomainSize.end(), size_t{1}, multiplesFunc);
Index4d attVolDomainSliceSizes = compute_slice_sizes_fast<DataNdim>(attVolDomainSize);
// Zero-fill the output buffers to be safe.
memset(pOutAttentionAvg, 0, attPatchSizeFlat);
memset(pOutAttentionVar, 0, attPatchSizeFlat);
std::vector<float_t> attPatchRaw(attPatchSizeFlat);
std::vector<size_t> attIndexVec(DataNdim, 0);
for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++)
{
Index4d attIndexNd{};
unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd);
std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector.
// Read the raw attention patch.
pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data());
// For each voxel of the attention patch, add its value to the avg. patch buffer.
for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++)
{
double_t oldValue = *(pOutAttentionAvg + patchIndexFlat);
*(pOutAttentionAvg + patchIndexFlat) = oldValue + attPatchRaw[patchIndexFlat];
}
}
// Now that we have a sum of all attention patches, we can compute the average by dividing.
// For each voxel of the attention patch, add its value to the avg. patch buffer.
for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++)
{
double_t sum = *(pOutAttentionAvg + patchIndexFlat);
*(pOutAttentionAvg + patchIndexFlat) = sum / static_cast<double_t>(attVolDomainSizeFlat);
}
// Repeat the same loop over the attention patches, now computing their variance.
for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++)
{
Index4d attIndexNd{};
unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd);
std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector.
// Read the raw attention patch.
pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data());
// For each voxel of the attention patch, add its value to the avg. patch buffer.
for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++)
{
double_t oldValue = *(pOutAttentionVar + patchIndexFlat);
double_t mean = *(pOutAttentionAvg + patchIndexFlat);
// Sum average square deviation from the mean.
*(pOutAttentionVar + patchIndexFlat) = oldValue + std::pow(attPatchRaw[patchIndexFlat] - mean, 2);
}
}
// Divide by the number of patches to get variance.
for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++)
{
double_t sum = *(pOutAttentionVar + patchIndexFlat);
*(pOutAttentionVar + patchIndexFlat) = sum / static_cast<double_t>(attVolDomainSizeFlat);
}
}
}
| 46.011605 | 149 | 0.606749 | rbnbr |
50c650e0f191878630bdfa2f07e11db89750fae1 | 4,011 | cpp | C++ | flakor/math/GLMatrix.cpp | sainthsu/Flakor | c414502f85d637b82a47754f20d1175e747b0a7d | [
"Libpng",
"Apache-2.0",
"MIT"
] | 4 | 2015-01-26T08:42:51.000Z | 2015-04-14T09:22:12.000Z | flakor/math/GLMatrix.cpp | sainthsu/Flakor | c414502f85d637b82a47754f20d1175e747b0a7d | [
"Libpng",
"Apache-2.0",
"MIT"
] | null | null | null | flakor/math/GLMatrix.cpp | sainthsu/Flakor | c414502f85d637b82a47754f20d1175e747b0a7d | [
"Libpng",
"Apache-2.0",
"MIT"
] | null | null | null | #include "macros.h"
#include <assert.h>
#include "math/GLMatrix.h"
FLAKOR_NS_BEGIN
MatrixStack* modelviewStack;
MatrixStack* projectionStack;
MatrixStack* textureStack;
MatrixStack* currentStack = NULL;
static unsigned char initialized = 0;
#ifdef __cplusplus
extern "C" {
#endif
void lazyInitialize()
{
if (!initialized)
{
Matrix4* identity = new Matrix4(); //Temporary identity matrix
//Initialize all 3 stacks
modelviewStack = new MatrixStack();
projectionStack = new MatrixStack();
textureStack = new MatrixStack();
currentStack = modelviewStack;
initialized = 1;
//Make sure that each stack has the identity matrix
modelviewStack->push(identity);
projectionStack->push(identity);
textureStack->push(identity);
}
}
void GLMode(StackMode mode)
{
lazyInitialize();
switch(mode)
{
case GL_MODELVIEW:
currentStack = modelviewStack;
break;
case GL_PROJECTION:
currentStack = projectionStack;
break;
case GL_TEXTURE:
currentStack = textureStack;
break;
default:
assert(0 && "Invalid matrix mode specified"); //TODO: Proper error handling
break;
}
}
void GLPush(void)
{
Matrix4* top = new Matrix4();
lazyInitialize(); //Initialize the stacks if they haven't been already
//Duplicate the top of the stack (i.e the current matrix)
top->set(currentStack->top->get(),COLUMN_MAJOR);
currentStack->push(top);
}
void GLPop(void)
{
assert(initialized && "Cannot Pop empty matrix stack");
//No need to lazy initialize, you shouldn't be popping first anyway!
currentStack->pop(NULL);
}
void GLLoadIdentity()
{
lazyInitialize();
currentStack->top->identity(); //Replace the top matrix with the identity matrix
}
void GLFreeAll()
{
//Clear the matrix stacks
modelviewStack->release();
projectionStack->release();
textureStack->release();
//Delete the matrices
initialized = 0; //Set to uninitialized
currentStack = NULL; //Set the current stack to point nowhere
}
void GLMultiply(const Matrix4* in)
{
lazyInitialize();
*currentStack->top = (*currentStack->top)*(*in);
}
void GLLoad(Matrix4* in)
{
lazyInitialize();
in->set(currentStack->top->get(),COLUMN_MAJOR);
}
void GLGet(StackMode mode, Matrix4* out)
{
lazyInitialize();
switch(mode)
{
case GL_MODELVIEW:
FKLOG("MV TOP:%s",modelviewStack->top->toString());
out->set(modelviewStack->top->get(),COLUMN_MAJOR);
break;
case GL_PROJECTION:
FKLOG("P TOP:%s",projectionStack->top->toString());
out->set(projectionStack->top->get(),COLUMN_MAJOR);
break;
case GL_TEXTURE:
FKLOG("Tex TOP:%s",textureStack->top->toString());
out->set(textureStack->top->get(),COLUMN_MAJOR);
break;
default:
assert(1 && "Invalid matrix mode specified"); //TODO: Proper error handling
break;
}
}
void GLTranslatef(float x, float y, float z)
{
Matrix4 *translation = new Matrix4();
//Create a rotation matrix using the axis and the angle
translation->translate(x,y,z);
//Multiply the rotation matrix by the current matrix
*currentStack->top = (*currentStack->top)*(*translation);
}
void GLRotatef(float angle, float x, float y, float z)
{
//Create an axis vector
Vector3* axis = new Vector3(x, y, z);
Matrix4* rotation = new Matrix4();
//Create a rotation matrix using the axis and the angle
rotation->rotate(angle, *axis);
//Multiply the rotation matrix by the current matrix
*currentStack->top = (*currentStack->top)*(*rotation);
}
void GLScalef(float x, float y, float z)
{
Matrix4* scaling = new Matrix4();
scaling->scale(x, y, z);
*currentStack->top = (*currentStack->top)*(*scaling);
}
#ifdef __cplusplus
}
#endif
FLAKOR_NS_END
| 23.051724 | 87 | 0.640987 | sainthsu |
50c673c4e99d14630c64df5ad4f9829184d85221 | 9,577 | cpp | C++ | src/gfx/graphics/vulkan/swapchain_vulkan.cpp | johannes-braun/graphics_utilities | 191772a3ff1c14eea74b9b5614b6226cf1f8abb7 | [
"MIT"
] | null | null | null | src/gfx/graphics/vulkan/swapchain_vulkan.cpp | johannes-braun/graphics_utilities | 191772a3ff1c14eea74b9b5614b6226cf1f8abb7 | [
"MIT"
] | null | null | null | src/gfx/graphics/vulkan/swapchain_vulkan.cpp | johannes-braun/graphics_utilities | 191772a3ff1c14eea74b9b5614b6226cf1f8abb7 | [
"MIT"
] | null | null | null | #include "init_struct.hpp"
#include "swapchain_vulkan.hpp"
#include "image_view_vulkan.hpp"
#include "result.hpp"
namespace gfx {
inline namespace v1 {
namespace vulkan {
uint32_t swapchain_implementation::current_image() const noexcept
{
return _current_image;
}
void swapchain_implementation::present()
{
if (_presented) {
vkResetCommandBuffer(_primary_command_buffers[_current_image], 0);
init<VkCommandBufferBeginInfo> begin_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
vkBeginCommandBuffer(_primary_command_buffers[_current_image], &begin_info);
init<VkImageMemoryBarrier> imb{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
imb.srcAccessMask = 0;
imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
imb.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imb.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imb.image = _temp_images[_current_image];
imb.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
imb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imb.subresourceRange.baseArrayLayer = 0;
imb.subresourceRange.baseMipLevel = 0;
imb.subresourceRange.layerCount = 1;
imb.subresourceRange.levelCount = 1;
vkCmdPipelineBarrier(_primary_command_buffers[_current_image], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &imb);
vkEndCommandBuffer(_primary_command_buffers[_current_image]);
std::array<VkSemaphore, 1> wait_semaphores{_present_semaphore};
std::array<VkPipelineStageFlags, 1> wait_masks{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
std::array<VkCommandBuffer, 1> command_buffers{_primary_command_buffers[_current_image]};
init<VkSubmitInfo> submit{VK_STRUCTURE_TYPE_SUBMIT_INFO};
submit.commandBufferCount = 1;
submit.pCommandBuffers = &_primary_command_buffers[_current_image];
submit.pWaitSemaphores = std::data(wait_semaphores);
submit.waitSemaphoreCount = static_cast<u32>(std::size(wait_semaphores));
submit.pSignalSemaphores = &_render_semaphore;
submit.signalSemaphoreCount = 1;
submit.pWaitDstStageMask = std::data(wait_masks);
// In graphics queue. Waits on all posted semaphores.
check_result(vkQueueSubmit(_graphics_queue, 1, &submit, _render_fences[_current_image]));
uint32_t idx = _current_image;
init<VkPresentInfoKHR> present_info{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR};
present_info.pImageIndices = &idx;
present_info.pSwapchains = &_swapchain;
present_info.swapchainCount = 1;
present_info.pWaitSemaphores = &_render_semaphore;
present_info.waitSemaphoreCount = 1;
VkResult swapchain_result;
present_info.pResults = &swapchain_result;
// Solely in present queue, but waits for _render_semaphore which is triggered only after all posted semaphores are signaled.
VkResult present_result = check_result(vkQueuePresentKHR(_present_queue, &present_info));
check_result(swapchain_result);
}
check_result(vkAcquireNextImageKHR(_device, _swapchain, std::numeric_limits<uint64_t>::max(), _present_semaphore, nullptr, &_current_image));
// Wait until last frame using this image has finished rendering
check_result(vkWaitForFences(_device, 1, &_render_fences[_current_image], true, std::numeric_limits<uint64_t>::max()));
check_result(vkResetFences(_device, 1, &_render_fences[_current_image]));
_presented = true;
}
void swapchain_implementation::resize(uint32_t width, uint32_t height)
{
auto& ctx = context::current();
_ctx_impl = static_cast<context_implementation*>(std::any_cast<detail::context_implementation*>(ctx->implementation()));
if (!_render_fences.empty())
vkWaitForFences(_ctx_impl->device(), static_cast<u32>(_render_fences.size()), _render_fences.data(), true, default_fence_timeout);
vkDeviceWaitIdle(_ctx_impl->device());
this->~swapchain_implementation();
_presented = false;
_device = _ctx_impl->device();
init<VkSwapchainCreateInfoKHR> swapchain_info{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
swapchain_info.clipped = true;
swapchain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchain_info.imageArrayLayers = 1;
swapchain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT;
swapchain_info.pQueueFamilyIndices = &(_ctx_impl->queue_families()[fam::present]);
swapchain_info.queueFamilyIndexCount = 1;
VkSurfaceCapabilitiesKHR capabilities;
check_result(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &capabilities));
swapchain_info.surface = _ctx_impl->surface();
swapchain_info.imageExtent = VkExtent2D{width, height};
swapchain_info.minImageCount = ctx->options().framebuffer_images;
swapchain_info.preTransform = capabilities.currentTransform;
u32 fmt_count = 0;
check_result(vkGetPhysicalDeviceSurfaceFormatsKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &fmt_count, nullptr));
std::vector<VkSurfaceFormatKHR> formats(fmt_count);
check_result(vkGetPhysicalDeviceSurfaceFormatsKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &fmt_count, formats.data()));
if (const auto it = std::find_if(formats.begin(), formats.end(),
[](const VkSurfaceFormatKHR& fmt) {
return fmt.format == VK_FORMAT_B8G8R8A8_UNORM
&& fmt.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
});
it == formats.end())
{
elog << "Did not find bgra8 format with srgb-nonlinear color space.";
}
else
{
swapchain_info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
swapchain_info.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
}
u32 pm_count = 0;
check_result(vkGetPhysicalDeviceSurfacePresentModesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &pm_count, nullptr));
std::vector<VkPresentModeKHR> present_modes(pm_count);
check_result(vkGetPhysicalDeviceSurfacePresentModesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &pm_count, present_modes.data()));
if (const auto it = std::find_if(present_modes.begin(), present_modes.end(),
[](const VkPresentModeKHR& mode) { return mode == VK_PRESENT_MODE_MAILBOX_KHR; });
it == present_modes.end())
{
elog << "Did not find mailbox present mode.";
}
else
swapchain_info.presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
check_result(vkCreateSwapchainKHR(_device, &swapchain_info, nullptr, &_swapchain));
_present_queue = _ctx_impl->queues()[fam::present];
_graphics_queue = _ctx_impl->queues()[fam::graphics];
// TODO:
u32 img_count = 0;
check_result(vkGetSwapchainImagesKHR(_device, _swapchain, &img_count, nullptr));
_temp_images.resize(img_count);
check_result(vkGetSwapchainImagesKHR(_device, _swapchain, &img_count, _temp_images.data()));
init<VkCommandBufferAllocateInfo> cmd_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
cmd_info.commandBufferCount = static_cast<uint32_t>(_temp_images.size());
cmd_info.commandPool = _ctx_impl->command_pools()[fam::graphics];
cmd_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
_primary_command_buffers.resize(_temp_images.size());
check_result(vkAllocateCommandBuffers(_device, &cmd_info, _primary_command_buffers.data()));
_command_pool = _ctx_impl->command_pools()[fam::graphics];
init<VkSemaphoreCreateInfo> sem_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
check_result(vkCreateSemaphore(_device, &sem_info, nullptr, &_present_semaphore));
check_result(vkCreateSemaphore(_device, &sem_info, nullptr, &_render_semaphore));
init<VkFenceCreateInfo> fen_info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
fen_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (int i = 0; i < _temp_images.size(); ++i)
{
check_result(vkCreateFence(_device, &fen_info, nullptr, &_render_fences.emplace_back()));
image_view& view = _image_views.emplace_back();
static_cast<image_view_implementation*>(&*view.implementation())->initialize_vk(gfx::imgv_type::image2d, gfx::format::bgra8unorm, _temp_images[i], 0, 1, 0, 1);
}
}
const std::vector<image_view>& swapchain_implementation::image_views() const
{
return _image_views;
}
handle swapchain_implementation::api_handle()
{
return _swapchain;
}
swapchain_implementation::~swapchain_implementation()
{
if (_swapchain) vkDestroySwapchainKHR(_device, _swapchain, nullptr);
for (auto& f : _render_fences)
vkDestroyFence(_device, f, nullptr);
if (_device && !_primary_command_buffers.empty())
vkFreeCommandBuffers(_device, _command_pool, static_cast<u32>(_primary_command_buffers.size()), _primary_command_buffers.data());
if (_present_semaphore) vkDestroySemaphore(_device, _present_semaphore, nullptr);
if (_render_semaphore) vkDestroySemaphore(_device, _render_semaphore, nullptr);
}
} // namespace vulkan
} // namespace v1
} // namespace gfx | 49.365979 | 161 | 0.732066 | johannes-braun |
50ccf6e8002517cfa041552b8f5ac2102158a917 | 83 | cpp | C++ | ksn-2021-pertahanan/solution-1.cpp | ia-toki/ksn-2021 | e925029fa9ce6198aae489c5f8505c47078da28e | [
"CC-BY-4.0"
] | null | null | null | ksn-2021-pertahanan/solution-1.cpp | ia-toki/ksn-2021 | e925029fa9ce6198aae489c5f8505c47078da28e | [
"CC-BY-4.0"
] | null | null | null | ksn-2021-pertahanan/solution-1.cpp | ia-toki/ksn-2021 | e925029fa9ce6198aae489c5f8505c47078da28e | [
"CC-BY-4.0"
] | 1 | 2021-12-05T04:17:41.000Z | 2021-12-05T04:17:41.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
cout << 9 << '\n';
}
| 11.857143 | 24 | 0.554217 | ia-toki |
50cd7e3c47b62a36e926996848352808662522a0 | 831 | hh | C++ | src/websocket_server/Packets/Out/WeatherStatusPacket.hh | 3n16m4/websocket-server | 5b6575bbd459feeef459b20a093ada3fd9d035e5 | [
"MIT"
] | 2 | 2020-11-16T15:53:39.000Z | 2021-03-20T09:08:36.000Z | src/websocket_server/Packets/Out/WeatherStatusPacket.hh | 3n16m4/websocket-server | 5b6575bbd459feeef459b20a093ada3fd9d035e5 | [
"MIT"
] | 2 | 2020-12-09T23:54:55.000Z | 2020-12-11T20:14:52.000Z | src/websocket_server/Packets/Out/WeatherStatusPacket.hh | 3n16m4/websocket-server | 5b6575bbd459feeef459b20a093ada3fd9d035e5 | [
"MIT"
] | 1 | 2021-03-20T09:08:41.000Z | 2021-03-20T09:08:41.000Z | #ifndef WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH
#define WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH
#include <array>
namespace amadeus {
enum class WebSocketSessionFlag : std::uint8_t;
#pragma pack(push, 1)
namespace out {
/// \brief Defines the WeatherStatusPacket which is sent by the server if a
/// WebSocketSession requested a weather update for a specific TCP connection
/// (µC).
struct WeatherStatusPacket
{
/// Packet header.
std::uint8_t header{0x04};
/// A unique identifier for the corresponding TCP Client which is used for
/// authentication.
std::array<std::uint8_t, 16> uuid;
/// Reserved server specific flag, not used anymore.
WebSocketSessionFlag flag;
};
#pragma pack(pop)
} // namespace out
} // namespace amadeus
#endif // !WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH
| 29.678571 | 78 | 0.758123 | 3n16m4 |
50d35331a0380b1acbd4127c8f8c2c6966f4b433 | 831 | hpp | C++ | cpp2c/test_data/mmalloc.hpp | mendlin/SIMD-libgen | 0f386bb639c829275a00f46c4b31d59c5ed84a28 | [
"AFL-1.1"
] | 1 | 2021-01-07T03:18:27.000Z | 2021-01-07T03:18:27.000Z | cpp2c/test_data/mmalloc.hpp | Logicalmars/SIMD-libgen | 0f386bb639c829275a00f46c4b31d59c5ed84a28 | [
"AFL-1.1"
] | null | null | null | cpp2c/test_data/mmalloc.hpp | Logicalmars/SIMD-libgen | 0f386bb639c829275a00f46c4b31d59c5ed84a28 | [
"AFL-1.1"
] | 1 | 2021-11-29T07:28:13.000Z | 2021-11-29T07:28:13.000Z | #ifndef ALIGNED_MMALLOC_HPP
#define ALIGNED_MMALLOC_HPP
/*=============================================================================
allocator.hpp - Platform independent aligned memory allocation.
Created on: 06-December-2011
Author: Ken Herdy
Description:
TODO - Wrap routines inside a class scope and/or C++ custom namespace.
=============================================================================*/
#include "bitblock.hpp"
#if defined USE_NEON
#error "Neon aligned memory allocation not implemented. Aborting compilation."
#else // USE_SSE
template <class T> T * simd_malloc(uint32_t n)
{
return (T*)_mm_malloc(n*sizeof(T), sizeof(BitBlock));
}
template <class T> void simd_free(T* p)
{
if(p != NULL)
{
_mm_free(p);
p = NULL;
}
}
#endif
#endif // ALIGNED_MMALLOC_HPP
| 22.459459 | 79 | 0.565584 | mendlin |
50db783e21b99550fa09f93b00936396feab61e9 | 9,908 | hpp | C++ | ze_common/include/ze/common/ringbuffer.hpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 30 | 2016-09-27T07:41:28.000Z | 2021-12-03T20:44:28.000Z | ze_common/include/ze/common/ringbuffer.hpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 1 | 2018-12-18T15:53:06.000Z | 2018-12-21T03:10:06.000Z | ze_common/include/ze/common/ringbuffer.hpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 12 | 2016-11-05T07:51:29.000Z | 2020-07-13T02:26:08.000Z | // Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye
// 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <map>
#include <tuple>
#include <thread>
#include <utility>
#include <mutex>
#include <Eigen/Dense>
#include <ze/common/logging.hpp>
#include <ze/common/ring_view.hpp>
#include <ze/common/types.hpp>
#include <ze/common/time_conversions.hpp>
namespace ze {
//! @todo: move the interpolators somewhere where they make more sense?
//!
//! Interpolators have to implement:
//! _ interpolate(Ringbuffer<...>*, int64_t time, Ringbuffer<...>timering_t::iterator);
//! Passing the (optional) interator to the timestamp right before the to be
//! interpolated value speeds up the process.
//! The passed it_before is expected to be valid.
//!
//! A nearest neighbour "interpolator".
struct InterpolatorNearest
{
template<typename Ringbuffer_T>
static typename Ringbuffer_T::DataType interpolate(
Ringbuffer_T* buffer,
int64_t time,
typename Ringbuffer_T::timering_t::iterator it_before)
{
// the end value
auto it_after = it_before + 1;
if (it_after == buffer->times_.end())
{
LOG(WARNING) << "Interpolation hit end of buffer.";
return buffer->dataAtTimeIterator(it_before);
}
// The times are ordered, we can guarantee those differences to be positive
if ((time - *it_before) < (*it_after - time))
{
return buffer->dataAtTimeIterator(it_before);
}
return buffer->dataAtTimeIterator(it_after);
}
template<typename Ringbuffer_T>
static typename Ringbuffer_T::DataType interpolate(
Ringbuffer_T* buffer,
int64_t time)
{
auto it_before = buffer->iterator_equal_or_before(time);
// caller should check the bounds:
CHECK(it_before != buffer->times_.end());
return interpolate(buffer, time, it_before);
}
};
//! A simple linear interpolator
struct InterpolatorLinear
{
template<typename Ringbuffer_T>
static typename Ringbuffer_T::DataType interpolate(
Ringbuffer_T* buffer,
int64_t time,
typename Ringbuffer_T::timering_t::iterator it_before)
{
// the end value
auto it_after = it_before + 1;
if (it_after == buffer->times_.end())
{
LOG(WARNING) << "Interpolation hit end of buffer.";
return buffer->dataAtTimeIterator(it_before);
}
const real_t w1 =
static_cast<real_t>(time - *it_before) /
static_cast<real_t>(*it_after - *it_before);
return (real_t{1.0} - w1) * buffer->dataAtTimeIterator(it_before)
+ w1 * buffer->dataAtTimeIterator(it_after);
}
template<typename Ringbuffer_T>
static typename Ringbuffer_T::DataType interpolate(
Ringbuffer_T* buffer,
int64_t time)
{
auto it_before = buffer->iterator_equal_or_before(time);
// caller should check the bounds:
CHECK(it_before != buffer->times_.end());
return interpolate(buffer, time, it_before);
}
};
using DefaultInterpolator = InterpolatorLinear;
//! A fixed size timed buffer templated on the number of entries.
//! Opposed to the `Buffer`, values are expected to be received ORDERED in
//! TIME!
// Oldest entry: buffer.begin(), newest entry: buffer.rbegin()
template <typename Scalar, size_t ValueDim, size_t Size>
class Ringbuffer
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
//! Ringbuffer is friend with the interpolator types.
friend struct InterpolatorNearest;
friend struct InterpolatorLinear;
typedef int64_t time_t;
typedef Eigen::Matrix<time_t, Size, 1> times_t;
typedef Eigen::Matrix<time_t, Eigen::Dynamic, 1> times_dynamic_t;
typedef Eigen::Matrix<Scalar, ValueDim, Size> data_t;
typedef Eigen::Matrix<Scalar, ValueDim, Eigen::Dynamic> data_dynamic_t;
// time ring is used to keep track of the positions of the data
// in the dataring
// uses fixed size ring_view
typedef ring_view<time_t> timering_t;
using DataType = Eigen::Matrix<Scalar, ValueDim, 1>;
using DataTypeMap = Eigen::Map<DataType>;
// a series of return types
using DataBoolPair = std::pair<DataType, bool>;
using TimeDataBoolTuple = std::tuple<time_t, DataType, bool>;
using TimeDataRangePair = std::pair<times_dynamic_t, data_dynamic_t>;
Ringbuffer()
: times_(timering_t(times_raw_.data(),
times_raw_.data() + Size,
times_raw_.data(),
0))
{}
//! no copy, no move as there is no way to track the mutex
Ringbuffer(const Ringbuffer& from) = delete;
Ringbuffer(const Ringbuffer&& from) = delete;
inline void insert(time_t stamp,
const DataType& data)
{
std::lock_guard<std::mutex> lock(mutex_);
times_.push_back(stamp);
data_.col(times_.back_idx()) = data;
}
//! Get value with timestamp closest to stamp. Boolean returns if successful.
std::tuple<time_t, DataType, bool> getNearestValue(time_t stamp);
//! Get oldest value in buffer.
std::pair<DataType, bool> getOldestValue() const;
//! Get newest value in buffer.
std::pair<DataType, bool> getNewestValue() const;
//! Get timestamps of newest and oldest entry.
std::tuple<time_t, time_t, bool> getOldestAndNewestStamp() const;
/*! @brief Get Values between timestamps.
*
* If timestamps are not matched, the values
* are interpolated. Returns a vector of timestamps and a block matrix with
* values as columns. Returns empty matrices if not successful.
*/
template <typename Interpolator = DefaultInterpolator>
TimeDataRangePair
getBetweenValuesInterpolated(time_t stamp_from, time_t stamp_to);
//! Get the values of the container at the given timestamps
//! The requested timestamps are expected to be in order!
template <typename Interpolator = DefaultInterpolator>
data_dynamic_t getValuesInterpolated(times_dynamic_t stamps);
//! Interpolate a single value
template <typename Interpolator = DefaultInterpolator>
bool getValueInterpolated(time_t t, Eigen::Ref<data_dynamic_t> out);
inline void clear()
{
std::lock_guard<std::mutex> lock(mutex_);
times_.reset();
}
inline size_t size() const
{
std::lock_guard<std::mutex> lock(mutex_);
return times_.size();
}
inline bool empty() const
{
std::lock_guard<std::mutex> lock(mutex_);
return times_.empty();
}
//! technically does not remove but only moves the beginning of the ring
inline void removeDataBeforeTimestamp(time_t stamp)
{
std::lock_guard<std::mutex> lock(mutex_);
removeDataBeforeTimestamp_impl(stamp);
}
inline void removeDataOlderThan(real_t seconds)
{
std::lock_guard<std::mutex> lock(mutex_);
if(times_.empty())
{
return;
}
removeDataBeforeTimestamp_impl(
times_.back() - secToNanosec(seconds));
}
inline void lock() const
{
mutex_.lock();
}
inline void unlock() const
{
mutex_.unlock();
}
const data_t& data() const
{
CHECK(!mutex_.try_lock()) << "Call lock() before accessing data.";
return data_;
}
const timering_t& times() const
{
CHECK(!mutex_.try_lock()) << "Call lock() before accessing data.";
return times_;
}
typename timering_t::iterator iterator_equal_or_before(time_t stamp);
typename timering_t::iterator iterator_equal_or_after(time_t stamp);
//! returns an iterator to the first element in the times_ ring that
//! is greater or equal to stamp
inline typename timering_t::iterator lower_bound(time_t stamp);
inline std::mutex& mutex() {return mutex_;}
protected:
mutable std::mutex mutex_;
data_t data_;
times_t times_raw_;
timering_t times_;
//! return the data at a given point in time
inline DataType dataAtTimeIterator(typename timering_t::iterator iter) const
{
//! @todo: i believe this is wrong.
return data_.col(iter.container_index());
}
//! return the data at a given point in time (const)
inline DataType dataAtTimeIterator(typename timering_t::const_iterator iter) const
{
//! @todo: i believe this is wrong.
return data_.col(iter.container_index());
}
//! shifts the starting point of the ringbuffer to the given timestamp
//! no resizing or deletion happens.
inline void removeDataBeforeTimestamp_impl(time_t stamp)
{
auto it = lower_bound(stamp);
times_.reset_front(it.container_index());
}
};
} // namespace ze
#include <ze/common/ringbuffer-inl.hpp>
| 31.858521 | 87 | 0.709931 | rockenbf |
50e125deb4b320ce3f86b69e55896749b3dd1652 | 70 | cpp | C++ | gui/applicationdata.cpp | UnnamedCompany/UnnamedSoftware | 3251dc9844f35622f616fd3d5a40cb8c89ac0b28 | [
"MIT"
] | 4 | 2016-02-18T00:48:10.000Z | 2016-03-02T23:41:54.000Z | gui/applicationdata.cpp | UnnamedCompany/UnnamedSoftware | 3251dc9844f35622f616fd3d5a40cb8c89ac0b28 | [
"MIT"
] | null | null | null | gui/applicationdata.cpp | UnnamedCompany/UnnamedSoftware | 3251dc9844f35622f616fd3d5a40cb8c89ac0b28 | [
"MIT"
] | 1 | 2016-02-29T18:13:34.000Z | 2016-02-29T18:13:34.000Z | #include "applicationdata.h"
ApplicationData::ApplicationData() { }
| 14 | 38 | 0.757143 | UnnamedCompany |
50e75f1d819c1c35e5f770807a9f53e427904d2f | 1,144 | hpp | C++ | DOS_Boat_Source/RequireSpace.hpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | DOS_Boat_Source/RequireSpace.hpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | DOS_Boat_Source/RequireSpace.hpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | /****************************************************************************
* Author: Michael S. Lewis *
* Date: 6/3/2016 *
* Description: RequireSpace.hpp is the RequireSpace class declaration *
* (interface) file (for Final Project "DOS Boat"). *
* A Require Space tests whether a specific object is in *
* inventory before allowing the user to proceed to a *
* particular adjacent space. *
*****************************************************************************/
#ifndef REQUIRESPACE_HPP
#define REQUIRESPACE_HPP
#include <string>
#include "Ocean.hpp"
class Babbage; // Declaration of Babbage class.
class RequireSpace : public Ocean
{
private:
virtual void playSpace(Babbage* babbage, bool displayHint);
virtual void nextSpace(Babbage* babbage);
std::string required;
std::string restricted;
public:
RequireSpace();
RequireSpace(std::string nameSpacem, std::string spaceHeading,
std::string spaceType, std::string requiredItem, std::string restrictedArea);
};
#endif // REQUIRESPACE_HPP
| 35.75 | 79 | 0.566434 | michaelslewis |
50e8fb9c008d57e9f0091fbfd6c1d3c827741bbc | 1,836 | cpp | C++ | tests/rect_follow_mouse.cpp | AlexandruIca/SoftRender | 9466251ad919d6896a1e3d1455a156186106cbaa | [
"Unlicense"
] | null | null | null | tests/rect_follow_mouse.cpp | AlexandruIca/SoftRender | 9466251ad919d6896a1e3d1455a156186106cbaa | [
"Unlicense"
] | null | null | null | tests/rect_follow_mouse.cpp | AlexandruIca/SoftRender | 9466251ad919d6896a1e3d1455a156186106cbaa | [
"Unlicense"
] | null | null | null | #include <chrono>
#include <cmath>
#include "softrender.hpp"
struct rect_t
{
softrender::point_t pos{ 0, 0 };
int w{ 0 };
int h{ 0 };
};
using microsecond_t =
decltype(std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::seconds(1))
.count());
auto follow_mouse(rect_t& t_rect,
softrender::point_t const& t_mouse_pos,
microsecond_t const t_elapsed_time) noexcept -> void
{
double const elapsed = t_elapsed_time / double{ 1e6 };
int constexpr velocity = 300; // pixels
double const center_x = t_rect.pos.x + t_rect.w / 2.0;
double const center_y = t_rect.pos.y + t_rect.h / 2.0;
double const dest_x = t_mouse_pos.x;
double const dest_y = t_mouse_pos.y;
double const dx = dest_x - center_x;
double const dy = dest_y - center_y;
double const distance = std::sqrt(dx * dx + dy * dy);
if(distance < 5) {
return;
}
t_rect.pos.x += static_cast<int>(velocity * elapsed * dx / distance);
t_rect.pos.y += static_cast<int>(velocity * elapsed * dy / distance);
}
auto main(int, char*[]) -> int
{
using namespace softrender;
window_t window{ 1280, 720 };
microsecond_t elapsed{ 0 };
rect_t rect{ { window.width() / 2 - 200, window.height() / 2 - 200 },
400,
400 };
auto start = std::chrono::high_resolution_clock::now();
while(!window.closed()) {
auto end = std::chrono::high_resolution_clock::now();
elapsed =
std::chrono::duration_cast<std::chrono::microseconds>(end - start)
.count();
start = end;
follow_mouse(rect, window.get_mouse_position(), elapsed);
window.draw_rectangle(rect.pos, rect.w, rect.h, pink);
window.draw();
}
}
| 26.228571 | 78 | 0.594227 | AlexandruIca |
50f527b18788b52c38ea6e11fa240c91a476f68d | 2,346 | cpp | C++ | iOS/Game/GameWindows.cpp | Amazong/Nebula | 8b5b0d3dea53b4a9558b6149c84d10564b86cf6d | [
"MIT"
] | null | null | null | iOS/Game/GameWindows.cpp | Amazong/Nebula | 8b5b0d3dea53b4a9558b6149c84d10564b86cf6d | [
"MIT"
] | 11 | 2016-07-14T11:55:17.000Z | 2016-07-14T12:14:01.000Z | iOS/Game/GameWindows.cpp | Amazong/iOS---Instrument-Outlet-Simulator | 8b5b0d3dea53b4a9558b6149c84d10564b86cf6d | [
"MIT"
] | null | null | null | #include "headers\GameWindows.h"
#include "headers\Errors.h"
int render_splash()
{
sf::RenderWindow *splash_screen = new sf::RenderWindow(sf::VideoMode(887, 407), "", sf::Style::None);
sf::Clock splash_clk;
sf::Texture splash_png;
if (!(splash_png.loadFromFile("res/png/Splash.png"))) {
splash_screen->setVisible(0);
return 42;
}
sf::Sprite splash_sprite;
splash_sprite.setTexture(splash_png);
while (splash_clk.getElapsedTime().asSeconds() < 4.0f) {
splash_screen->clear(sf::Color::Black);
splash_screen->draw(splash_sprite);
splash_screen->display();
}
delete splash_screen;
return 0;
}
int n_words(const std::string & str)
{
if (str.empty())
return(0);
int counter = 0;
int size = str.length();
int num = str.find_first_of(' ');
if (num == std::string::npos)
return(1);
while (num != std::string::npos)
{
counter++;
num = str.find_first_of(' ', num + 1);
}
return(counter + 1);
}
std::string * get_string_tab(std::string & str, int & size, unsigned int line_size)
{
if (str.empty())
{
size = 1;
return(new std::string(""));
}
if (str.length() <= line_size)
{
size = 1;
return(new std::string(str));
}
int words = n_words(str), pos = 0, counter = 0, i = 0;
size = str.length();
if (words == 1)
{
size = 1;
return(new std::string(str));
}
// edge cases
std::string * tab_ptr = new std::string[words];
for (int i = 0, j = 0; i < size; i++)
{
if (str[i] == ' ')
{
tab_ptr[j] = str.substr(pos, (i - pos)) + ' ';
pos = ++i;
counter++;
j++;
}
if (words - counter == 1)
tab_ptr[j] = str.substr(pos);
}
// now tab_ptr[j] has all words of phrase.
std::vector<std::string *> fitted_strings;
std::string temp = "";
for (int i = 0; i < words; i++)
{
if (temp.size() + tab_ptr[i].size() > line_size)
{
fitted_strings.push_back(new std::string(temp));
temp.clear();
temp += tab_ptr[i];
continue;
}
temp += tab_ptr[i];
}
fitted_strings.push_back(new std::string(temp));
delete[] tab_ptr;
size = fitted_strings.size();
std::string * str_ptr = new std::string[size];
for (int i = 0; i < size; i++)
{
str_ptr[i] = *(fitted_strings[i]);
delete fitted_strings[i];
}
return(str_ptr);
}
void show_textbox(std::string & str, unsigned int line_size, unsigned int char_size) //NO DOUBLE FUCKING SPACES
{
} | 18.046154 | 113 | 0.617221 | Amazong |
50f5eac597a7a48fdf25f1af7c48233c64a486e6 | 260 | cpp | C++ | Version0.2/Kernel/Discretization/preprocessing.cpp | glwagner/Exasim | ee4540443435f958fa2ca78d59cbf9cff0fe69de | [
"MIT"
] | 37 | 2020-12-09T20:24:36.000Z | 2022-02-18T17:19:23.000Z | Version0.2/Kernel/Discretization/preprocessing.cpp | glwagner/Exasim | ee4540443435f958fa2ca78d59cbf9cff0fe69de | [
"MIT"
] | 25 | 2020-11-25T20:37:33.000Z | 2022-02-25T15:53:11.000Z | Version0.2/Kernel/Discretization/preprocessing.cpp | glwagner/Exasim | ee4540443435f958fa2ca78d59cbf9cff0fe69de | [
"MIT"
] | 8 | 2020-11-30T15:34:06.000Z | 2022-01-09T21:06:00.000Z | #ifndef __PREPROCESSING
#define __PREPROCESSING
#include "../preprocessing/errormsg.cpp"
#include "../preprocessing/ioutilities.cpp"
#include "../preprocessing/readbinaryfiles.cpp"
#ifdef HAVE_CUDA
#include "../preprocessing/gpuDeviceInfo.cpp"
#endif
#endif | 21.666667 | 47 | 0.788462 | glwagner |
50f96c187b9ce94499cc1b4e6b8e24405bfdfa12 | 4,365 | cxx | C++ | STEER/STEERBase/AliDetectorTagCuts.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | STEER/STEERBase/AliDetectorTagCuts.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | STEER/STEERBase/AliDetectorTagCuts.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Author: Panos Christakoglou. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------
// AliDetectorTagCuts class
// This is the class to deal with the Detector tag level cuts
// Origin: Panos Christakoglou, UOA-CERN, Panos.Christakoglou@cern.ch
//-----------------------------------------------------------------
class AliLog;
#include "AliDetectorTag.h"
#include "AliDetectorTagCuts.h"
#include "TObjString.h"
#include "TString.h"
ClassImp(AliDetectorTagCuts)
//___________________________________________________________________________
AliDetectorTagCuts::AliDetectorTagCuts() :
TObject(),
fDetectorsReco(0),
fDetectorsDAQ(0),
fDetectorsFlag(kFALSE),
fDetectorValidityMatch(),
fDetectorValidityFlag()
{
//Default constructor which calls the Reset method.
for (int iter = 0; iter<AliDAQ::kHLTId; iter++) {
fDetectorValidityMatch[iter] = 0;
fDetectorValidityFlag[iter] = 0;
}
}
//___________________________________________________________________________
AliDetectorTagCuts::~AliDetectorTagCuts() {
//Defaut destructor.
}
//___________________________________________________________________________
Bool_t AliDetectorTagCuts::IsAccepted(AliDetectorTag *detTag) const {
//Returns true if the event is accepted otherwise false.
if (fDetectorsFlag) {
Bool_t daqsel = (detTag->GetIntDetectorMaskDAQ() & fDetectorsDAQ) > 0;
Bool_t recsel = (detTag->GetIntDetectorMaskReco() & fDetectorsReco) > 0;
Bool_t valsel = kTRUE;
for (int iter=0; iter<AliDAQ::kHLTId; iter++) {
if (fDetectorValidityFlag[iter])
if (!(fDetectorValidityMatch[iter] == detTag->GetDetectorValidityRange(iter)))
valsel = kFALSE;
}
return (daqsel && recsel && valsel);
}
return true;
// if(fDetectorsFlag){
// TString detStr = fDetectors;
// TObjArray *activeDetectors = detTag->GetDetectorMask();
// for (Int_t iDet = 0; iDet < activeDetectors->GetEntries(); iDet++) {
// TObjString *detectorString = (TObjString *)activeDetectors->At(iDet);
// if (!IsSelected(detectorString->GetString(), detStr))return kFALSE;
// }
// }
// return kTRUE;
}
void AliDetectorTagCuts::SetDetectorValidityValue(TString det, UShort_t val)
{
// Set Validity requiement for detector
Short_t detid = AliDAQ::DetectorID(det.Data());
if (detid >= 0) {
fDetectorValidityMatch[detid] = val;
fDetectorsFlag = kTRUE;
}
}
//___________________________________________________________________________
// Bool_t AliDetectorTagCuts::IsSelected(TString detName, TString& detectors) const {
// //Returns true if the detector is included
// if ((detectors.CompareTo("ALL") == 0) ||
// detectors.BeginsWith("ALL ") ||
// detectors.EndsWith(" ALL") ||
// detectors.Contains(" ALL ")) {
// detectors = "ALL";
// return kTRUE;
// }
// // search for the given detector
// Bool_t result = kFALSE;
// if ((detectors.CompareTo(detName) == 0) ||
// detectors.BeginsWith(detName+" ") ||
// detectors.EndsWith(" "+detName) ||
// detectors.Contains(" "+detName+" ")) {
// detectors.ReplaceAll(detName, "");
// result = kTRUE;
// }
// // clean up the detectors string
// while (detectors.Contains(" ")) detectors.ReplaceAll(" ", " ");
// while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
// while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
// return result;
// }
| 36.680672 | 85 | 0.6252 | AllaMaevskaya |
50ff1bc5ed5b30251e2a0c6b4e0289112d84e0e2 | 6,165 | hpp | C++ | src/morda/widgets/group/list.hpp | igagis/morda | dd7b58f7cb2689d56b7796cc9b6b9302aad1a529 | [
"MIT"
] | 69 | 2016-12-07T05:56:53.000Z | 2020-11-27T20:59:05.000Z | src/morda/widgets/group/list.hpp | igagis/morda | dd7b58f7cb2689d56b7796cc9b6b9302aad1a529 | [
"MIT"
] | 103 | 2015-07-10T14:42:21.000Z | 2020-09-09T16:16:21.000Z | src/morda/widgets/group/list.hpp | igagis/morda | dd7b58f7cb2689d56b7796cc9b6b9302aad1a529 | [
"MIT"
] | 18 | 2016-11-22T14:41:37.000Z | 2020-04-22T18:16:10.000Z | /*
morda - GUI framework
Copyright (C) 2012-2021 Ivan Gagis <igagis@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ================ LICENSE END ================ */
#pragma once
#include "../widget.hpp"
#include "../container.hpp"
#include "../base/oriented_widget.hpp"
namespace morda{
/**
* @brief Scrollable list widget.
* This is a base class for vertical and horizontal lists.
*/
class list_widget :
// NOTE: order of virtual public and private declarations here matters for clang due to some bug,
// see http://stackoverflow.com/questions/42427145/clang-cannot-cast-to-private-base-while-there-is-a-public-virtual-inheritance
virtual public widget,
public container,
protected oriented_widget
{
// index of the first item added to container as child
size_t added_index = size_t(-1);
size_t pos_index = 0; // index of the first visible item
// offset in pixels of the first visible item.
// the value is positive, tough the item is biased towards negative coordinate values.
real pos_offset = real(0);
size_t num_tail_items = 0; // zero means that number of tail items has to be recomputed
size_t first_tail_item_index = 0;
real first_tail_item_offset = real(0);
real first_tail_item_dim = real(0);
protected:
list_widget(std::shared_ptr<morda::context> c, const treeml::forest& desc, bool vertical);
public:
list_widget(const list_widget&) = delete;
list_widget& operator=(const list_widget&) = delete;
/**
* @brief list items provider.
* User should subclass this class to provide items to the list.
*/
class provider : virtual public utki::shared{
friend class list_widget;
list_widget* parent_list = nullptr;
protected:
provider(){}
public:
/**
* @brief Get parent list widget.
* @return list widget which owns the provider, in case the provider is set to some list widget.
* @return nullptr in case the provider is not set to any list widget.
*/
list_widget* get_list()noexcept{
return this->parent_list;
}
/**
* @brief Get total number of items in the list.
* @return Number of items in the list.
*/
virtual size_t count()const noexcept = 0;
/**
* @brief Get widget for item.
* @param index - index of item to get widget for.
* @return widget for the requested item.
*/
virtual std::shared_ptr<widget> get_widget(size_t index) = 0;
/**
* @brief Recycle widget of item.
* @param index - index of item to recycle widget of.
* @param w - widget to recycle.
*/
virtual void recycle(size_t index, std::shared_ptr<widget> w){}
void notify_data_set_change();
};
void set_provider(std::shared_ptr<provider> item_provider = nullptr);
void lay_out()override;
morda::vector2 measure(const morda::vector2& quotum) const override;
/**
* @brief Set scroll position as factor from [0:1].
* @param factor - factor of the scroll position to set.
*/
void set_scroll_factor(real factor);
/**
* @brief Get scroll factor.
* @return Current scroll position as factor from [0:1].
*/
real get_scroll_factor()const noexcept;
/**
* @brief Get scroll band.
* Returns scroll band as a fraction of 1. This is basically the number of visible elements divided by total number of elements in the list.
* @return scroll band.
*/
real get_scroll_band()const noexcept;
/**
* @brief Get index of the first visible item.
* @return index of the first visible item.
*/
size_t get_pos_index()const noexcept{
return this->pos_index;
}
/**
* @brief Get offset of the first visible item.
* The value is positive, though the item coordinate is <= 0.
* @return offset in pixels of the first visible item.
*/
real get_pos_offset()const noexcept{
return this->pos_offset;
}
/**
* @brief Scroll the list by given number of pixels.
* @param delta - number of pixels to scroll, can be positive or negative.
*/
void scroll_by(real delta);
/**
* @brief Data set changed signal.
* Emitted when list widget contents have actually been updated due to change in provider's model data set.
*/
std::function<void(list_widget&)> data_set_change_handler;
/**
* @brief Scroll position changed signal.
* Emitted when list's scroll position has changed.
*/
std::function<void(list_widget&)> scroll_change_handler;
private:
std::shared_ptr<provider> item_provider;
void update_children_list();
// returns true if it was the last visible widget
bool arrange_widget(
std::shared_ptr<widget>& w,
real& pos,
bool add,
size_t index,
widget_list::const_iterator& insertBefore
);
void update_tail_items_info();
void handle_data_set_changed();
void notify_scroll_pos_changed();
void notify_scroll_pos_changed(size_t old_index, real old_offset);
real calc_num_visible_items()const noexcept;
};
/**
* @brief Horizontal list widget.
* Panorama list widget.
* From GUI script it can be instantiated as "pan_list".
*/
class pan_list : public list_widget{
public:
pan_list(std::shared_ptr<morda::context> c, const treeml::forest& desc) :
widget(std::move(c), desc),
list_widget(this->context, desc, false)
{}
pan_list(const pan_list&) = delete;
pan_list& operator=(const pan_list&) = delete;
};
/**
* @brief Vertical list widget.
* From GUI script it can be instantiated as "list".
*/
class list : public list_widget{
public:
list(std::shared_ptr<morda::context> c, const treeml::forest& desc) :
widget(std::move(c), desc),
list_widget(this->context, desc, true)
{}
list(const list&) = delete;
list& operator=(const list&) = delete;
};
}
| 28.022727 | 144 | 0.710949 | igagis |
dd00c037105c4c257d0293e8d5c4d7cc9b5180d3 | 1,415 | cpp | C++ | libs/settings/src/help.cpp | robertdickson/ledger | fd9ba1a3fb2ccbb212561695ebb745747a5402b4 | [
"Apache-2.0"
] | 96 | 2018-08-23T16:49:05.000Z | 2021-11-25T00:47:16.000Z | libs/settings/src/help.cpp | robertdickson/ledger | fd9ba1a3fb2ccbb212561695ebb745747a5402b4 | [
"Apache-2.0"
] | 1,011 | 2018-08-17T12:25:21.000Z | 2021-11-18T09:30:19.000Z | libs/settings/src/help.cpp | robertdickson/ledger | fd9ba1a3fb2ccbb212561695ebb745747a5402b4 | [
"Apache-2.0"
] | 65 | 2018-08-20T20:05:40.000Z | 2022-02-26T23:54:35.000Z | //------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// 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 "settings/help.hpp"
#include "settings/setting_collection.hpp"
namespace {
constexpr char const *NAME = "help";
constexpr char const *DESCRIPTION = "Print this help and exit";
} // namespace
namespace fetch {
namespace settings {
Help::Help(SettingCollection ®)
: SettingBase(reg, NAME, DESCRIPTION)
, reg_(reg)
{}
void Help::FromStream(std::istream & /*stream*/)
{}
void Help::ToStream(std::ostream & /*stream*/) const
{}
bool Help::TerminateNow() const
{
reg_.DisplayHelp();
return true;
}
std::string Help::envname() const
{
return {};
}
} // namespace settings
} // namespace fetch
| 25.267857 | 80 | 0.619081 | robertdickson |
dd033758b6c3f0807ce81c62ef206680f2338422 | 1,930 | hpp | C++ | experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp | ValtoForks/pomdog | 73798ae5f4a4c3b9b1e1e96239187c4b842c93b2 | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include "Pomdog.Experimental/Gameplay/detail/ComponentTypeIndex.hpp"
#include "Pomdog.Experimental/Gameplay/Component.hpp"
#include "Pomdog/Basic/Export.hpp"
#include "Pomdog/Math/Quaternion.hpp"
#include "Pomdog/Math/Radian.hpp"
#include "Pomdog/Math/Vector2.hpp"
#include "Pomdog/Math/Vector3.hpp"
namespace Pomdog {
class POMDOG_EXPORT Transform final : public Component {
public:
Transform() noexcept;
Vector2 GetPosition2D() const noexcept;
void SetPosition2D(const Vector2& positionIn) noexcept;
const Vector3& GetPosition() const noexcept;
void SetPosition(const Vector3& positionIn) noexcept;
void SetPositionX(float x) noexcept;
void SetPositionY(float y) noexcept;
void SetPositionZ(float z) noexcept;
const Vector3& GetScale() const noexcept;
void SetScale(const Vector3& scaleIn) noexcept;
void SetScale(float scaleIn) noexcept;
Vector2 GetScale2D() const noexcept;
Radian<float> GetRotation2D() const noexcept;
Quaternion GetRotation() const noexcept;
void SetRotation(const Quaternion& rotationIn) noexcept;
void SetRotationX(const Radian<float>& angle) noexcept;
void SetRotationY(const Radian<float>& angle) noexcept;
void SetRotationZ(const Radian<float>& angle) noexcept;
void Rotate(const Vector3& eulerAngles);
void Rotate2D(const Radian<float>& rotationZ);
Matrix4x4 GetTransformMatrix() const noexcept;
private:
Vector3 position;
Vector3 scale;
Quaternion rotation;
};
template <>
struct ComponentTypeDeclaration<Transform> final {
static std::uint8_t GetTypeIndex();
};
template <>
class ComponentCreator<Transform> final : public ComponentCreatorBase {
public:
std::shared_ptr<Component> CreateComponent() override;
std::uint8_t GetComponentType() override;
};
} // namespace Pomdog
| 24.43038 | 71 | 0.74715 | ValtoForks |
dd04eeadcb3d3eec69af42fe91c490728494de2b | 3,977 | cpp | C++ | ch08/8.exercise.05.cpp | 0p3r4t4/PPPUCPP2nd | cf1bd23bb22ee00a77172e43678b7eaa91f592e0 | [
"MIT"
] | 51 | 2017-03-24T06:08:11.000Z | 2022-03-18T00:28:14.000Z | ch08/8.exercise.05.cpp | 0p3r4t4/PPPUCPP2nd | cf1bd23bb22ee00a77172e43678b7eaa91f592e0 | [
"MIT"
] | 1 | 2019-06-23T07:33:42.000Z | 2019-12-12T13:14:04.000Z | ch08/8.exercise.05.cpp | 0p3r4t4/PPPUCPP2nd | cf1bd23bb22ee00a77172e43678b7eaa91f592e0 | [
"MIT"
] | 25 | 2017-04-07T13:22:45.000Z | 2022-03-18T00:28:15.000Z | // 8.exercise.05.cpp
//
// Write two functions that reverse the order of element in a vector<int>.
// For example, 1, 3, 5, 6, 9 becomes 9, 7, 5, 3, 1. The first reverse
// function should produce a new vector with the reverse sequence, leaving the
// original vector unchanged. The other reverse function should reverse the
// elements of its vector without using any other vectors (hint: swap).
//
// COMMENTS
//
// The fibonacci() and print() functions comes in handy to test the proposed
// functions on this exercise.
//
// The first function will be named reverse_cr() as parameter will be passed
// by const-reference. The other one will be reverse_r() as parameter will be
// passed by reference. For this one we use swap(), as the hint says, but we
// will no implement it since its available on the standard library, as
// pointed out in §8.5.5.
//
// We must check for odd and even size sequences.
#include "std_lib_facilities.h"
void print(const string& label, const vector<int>& data)
// Only read arguments, so it safe to pass them by const-reference
{
cout << label << ": { ";
for (int i : data)
cout << i << ' ';
cout << "}\n";
}
int check_add(int a, int b)
// Adds two integers performing overflow control to avoid undefined behavior.
// (Search for INT32-C on https://www.securecoding.cert.org)
{
if (((b > 0) && (a > (numeric_limits<int>::max() - b))) ||
((b < 0) && (a < (numeric_limits<int>::min() - b))))
error("check_add(): integer add overflows.");
else
return a+b;
}
void fibonacci(int x, int y, vector<int>& v, int n)
// Generates a Fibonacci sequence of n values into v, starting with values x
// and y (integers passed by value, and we are modifying v, so it is passed by
// reference).
// Preconditions:
// Vector must be empty
// To simplify, n must be equal or greater than two.
{
if (v.size() != 0)
error("fibonacci(): Non empty vector passed as argument.");
if (n < 2)
error("fibonacci(): n must be al least 2.");
v.push_back(x);
v.push_back(y);
// Add a try-catch block to catch overflow and let the program continue
try {
for (int i = 2; i < n; ++i)
v.push_back(check_add(v[i-2],v[i-1]));
}
catch(exception& e){
cerr << e.what() << '\n';
}
}
vector<int> reverse_cr(const vector<int>& v)
// Returns a new vector with vector v elements in reverse order
{
vector<int> r;
for (size_t i = v.size(); i > 0; --i)
r.push_back(v[i-1]);
return r;
}
void reverse_r(vector<int>& v)
// Reverses order of elements of vector v
{
size_t limit{v.size()/2}; // Only traverse half of the elements.
// This way, if we have an odd number of elements
// the division ignores the middle one.
size_t last_idx{v.size()-1}; // Last element index. To avoid recalc.
for (size_t i = 0; i < limit; ++i)
swap(v[i], v[last_idx-i]);
}
int main()
try {
// Test a vector with even element number
vector<int> e1;
fibonacci(1, 2, e1, 8); // Generate a vector with even element number
print("Original even ", e1);
vector<int> e2{reverse_cr(e1)}; // New vector reversed
print("Reverse even by const-ref", e2);
reverse_r(e1); // Reverse original vector
print("Reverse even by ref ", e1);
// Test a vector with odd element number
vector<int> o1;
fibonacci(1, 2, o1, 7); // Generate a vector with odd element number
print("Original odd ", o1);
vector<int> o2{reverse_cr(o1)}; // New vector reversed
print("Reverse odd by const-ref ", o2);
reverse_r(o1); // Reverse original vector
print("Reverse odd by ref ", o1);
return 0;
}
catch(exception& e)
{
cerr << e.what() << '\n';
return 1;
}
catch(...)
{
cerr << "Unknwon exception!!\n";
return 2;
}
| 31.816 | 81 | 0.608499 | 0p3r4t4 |
dd050b40b3689ecaa72f8691d1d6f53df4276d02 | 274 | cpp | C++ | source/shared_traits.cpp | phikaczu/logging | c926d9ac72208ae10364adb368e9b39f0c43cbdc | [
"MIT"
] | null | null | null | source/shared_traits.cpp | phikaczu/logging | c926d9ac72208ae10364adb368e9b39f0c43cbdc | [
"MIT"
] | null | null | null | source/shared_traits.cpp | phikaczu/logging | c926d9ac72208ae10364adb368e9b39f0c43cbdc | [
"MIT"
] | null | null | null | #include "shared_traits.h"
#include<cassert>
using namespace logs2::SharedTraits;
AssertCheck::AssertCheck()
: _threadId{ std::this_thread::get_id() }
{
}
void AssertCheck::isSameThread() const
{
assert(std::this_thread::get_id() == _threadId);
}
| 17.125 | 53 | 0.671533 | phikaczu |
dd08360f1d9633daaf49c3bce9979d7835eca5e8 | 6,324 | cpp | C++ | core/src/zxing/qrcode/decoder/BitMatrixParser.cpp | camposm/tinyzxing | ab156e0c7e0602f0b091a1e0a24afdf670c6373e | [
"Apache-2.0"
] | null | null | null | core/src/zxing/qrcode/decoder/BitMatrixParser.cpp | camposm/tinyzxing | ab156e0c7e0602f0b091a1e0a24afdf670c6373e | [
"Apache-2.0"
] | 1 | 2021-09-27T13:16:08.000Z | 2021-09-27T13:16:08.000Z | core/src/zxing/qrcode/decoder/BitMatrixParser.cpp | camposm/tinyzxing | ab156e0c7e0602f0b091a1e0a24afdf670c6373e | [
"Apache-2.0"
] | null | null | null | /*
* BitMatrixParser.cpp
* zxing
*
* Created by Christian Brunschen on 20/05/2008.
* Copyright 2008 ZXing authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <zxing/qrcode/decoder/BitMatrixParser.h>
#include <zxing/qrcode/decoder/DataMask.h>
namespace zxing {
namespace qrcode {
int BitMatrixParser::copyBit(size_t x, size_t y, int versionBits) {
return bitMatrix_.get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1;
}
BitMatrixParser::BitMatrixParser (sampled_grid_t& bitMatrix) :
bitMatrix_(bitMatrix),
found_error(false),
parsedVersion_(0),
parsedFormatInfo_()
{
size_t dimension = bitMatrix.getHeight();
if ((dimension < 21) || (dimension & 0x03) != 1)
{
found_error = true;
}
}
std::optional<FormatInformation> BitMatrixParser::readFormatInformation()
{
if (parsedFormatInfo_)
{
return parsedFormatInfo_;
}
// Read top-left format info bits
int formatInfoBits1 = 0;
for (int i = 0; i < 6; i++)
{
formatInfoBits1 = copyBit(i, 8, formatInfoBits1);
}
// .. and skip a bit in the timing pattern ...
formatInfoBits1 = copyBit(7, 8, formatInfoBits1);
formatInfoBits1 = copyBit(8, 8, formatInfoBits1);
formatInfoBits1 = copyBit(8, 7, formatInfoBits1);
// .. and skip a bit in the timing pattern ...
for (int j = 5; j >= 0; j--)
{
formatInfoBits1 = copyBit(8, j, formatInfoBits1);
}
// Read the top-right/bottom-left pattern
int dimension = bitMatrix_.getHeight();
int formatInfoBits2 = 0;
int jMin = dimension - 7;
for (int j = dimension - 1; j >= jMin; j--)
{
formatInfoBits2 = copyBit(8, j, formatInfoBits2);
}
for (int i = dimension - 8; i < dimension; i++)
{
formatInfoBits2 = copyBit(i, 8, formatInfoBits2);
}
return FormatInformation::decodeFormatInformation(formatInfoBits1,formatInfoBits2);
}
const Version* BitMatrixParser::readVersion()
{
if (parsedVersion_ != nullptr)
{
return parsedVersion_;
}
int dimension = bitMatrix_.getHeight();
int provisionalVersion = (dimension - 17) >> 2;
if (provisionalVersion <= 6)
{
return Version::getVersionForNumber(provisionalVersion);
}
// Read top-right version info: 3 wide by 6 tall
int versionBits = 0;
for (int y = 5; y >= 0; y--)
{
int xMin = dimension - 11;
for (int x = dimension - 9; x >= xMin; x--)
{
versionBits = copyBit(x, y, versionBits);
}
}
parsedVersion_ = Version::decodeVersionInformation(versionBits);
if (parsedVersion_ != nullptr && parsedVersion_->getDimensionForVersion() == dimension)
{
return parsedVersion_;
}
// Hmm, failed. Try bottom left: 6 wide by 3 tall
versionBits = 0;
for (int x = 5; x >= 0; x--)
{
int yMin = dimension - 11;
for (int y = dimension - 9; y >= yMin; y--)
{
versionBits = copyBit(x, y, versionBits);
}
}
parsedVersion_ = Version::decodeVersionInformation(versionBits);
if (parsedVersion_ != nullptr && parsedVersion_->getDimensionForVersion() == dimension)
{
return parsedVersion_;
}
return nullptr;
}
codewords_t BitMatrixParser::readCodewords()
{
codewords_t result = {0};
auto formatInfo = readFormatInformation();
const Version* version = readVersion();
if (version == nullptr || !formatInfo)
{
return result;
}
// Get the data mask for the format used in this QR Code. This will exclude
// some bits from reading as we wind through the bit matrix.
auto dataMask = DataMask::select((int) formatInfo.value().getDataMask());
if (!dataMask)
{
return result;
}
int dimension = bitMatrix_.getHeight();
dataMask.value().unmaskBitMatrix(bitMatrix_, dimension);
bitmatrix_t<config::MaxGridSize, config::MaxGridSize> functionPattern(dimension);
version->buildFunctionPattern(functionPattern);
bool readingUp = true;
int resultOffset = 0;
int currentByte = 0;
int bitsRead = 0;
// Read columns in pairs, from right to left
for (int x = dimension - 1; x > 0; x -= 2)
{
if (x == 6)
{
// Skip whole column with vertical alignment pattern;
// saves time and makes the other code proceed more cleanly
x--;
}
// Read alternatingly from bottom to top then top to bottom
for (int counter = 0; counter < dimension; counter++)
{
int y = readingUp ? dimension - 1 - counter : counter;
for (int col = 0; col < 2; col++)
{
// Ignore bits covered by the function pattern
if (!functionPattern.get(x - col, y))
{
// Read a bit
bitsRead++;
currentByte <<= 1;
if (bitMatrix_.get(x - col, y))
{
currentByte |= 1;
}
// If we've made a whole byte, save it off
if (bitsRead == 8)
{
result[resultOffset++] = (char)currentByte;
bitsRead = 0;
currentByte = 0;
}
}
}
}
readingUp = !readingUp; // switch directions
}
if (resultOffset != version->getTotalCodewords())
{
for (auto n = 0; n < result.size(); ++n)
{
result[n] = 0;
}
}
return result;
}
} // ns qrcode
} // ns zxing
| 28.232143 | 92 | 0.576534 | camposm |
dd085a10754d853dfa6fc05db45c3c43bdb39bf4 | 155 | hpp | C++ | src/utils/assert.hpp | JacobDomagala/Shady | cdb8b07a83d179f58bd70c42957e987ddd201eb4 | [
"MIT"
] | 2 | 2020-10-27T00:16:18.000Z | 2021-03-29T12:59:48.000Z | src/utils/assert.hpp | JacobDomagala/DEngine | cdb8b07a83d179f58bd70c42957e987ddd201eb4 | [
"MIT"
] | 58 | 2020-08-23T21:38:21.000Z | 2021-08-05T16:12:31.000Z | src/utils/assert.hpp | JacobDomagala/Shady | cdb8b07a83d179f58bd70c42957e987ddd201eb4 | [
"MIT"
] | null | null | null | #pragma once
#include <string_view>
namespace shady::utils {
void
Assert(bool assertion, std::string_view logMsg);
} // namespace shady::utils | 15.5 | 49 | 0.703226 | JacobDomagala |
dd085d6124666640274f9c20f98790de6a10b19f | 2,554 | cpp | C++ | examples/tumor/tumor_main.cpp | Pan-Maciek/iga-ads | 4744829c98cba4e9505c5c996070119e73ba18fa | [
"MIT"
] | 7 | 2018-01-19T00:19:19.000Z | 2021-06-22T00:53:00.000Z | examples/tumor/tumor_main.cpp | Pan-Maciek/iga-ads | 4744829c98cba4e9505c5c996070119e73ba18fa | [
"MIT"
] | 66 | 2021-06-22T22:44:21.000Z | 2022-03-16T15:18:00.000Z | examples/tumor/tumor_main.cpp | Pan-Maciek/iga-ads | 4744829c98cba4e9505c5c996070119e73ba18fa | [
"MIT"
] | 6 | 2017-04-13T19:42:27.000Z | 2022-03-26T18:46:24.000Z | // SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com>
// SPDX-License-Identifier: MIT
#include "ads/simulation.hpp"
#include "tumor.hpp"
#include "vasculature.hpp"
// clang-tidy 12 complains about deleted default constructor not
// initializing some members
//
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
struct sim_params {
int p; // 2
int elems; // 80
ads::timesteps_config steps; // 10000, 0.1
int plot_every;
tumor::params tumor_params;
tumor::vasc::config vasc_config;
};
sim_params parse_params(char* args[], int idx) {
using std::atof;
using std::atoi;
auto next = [&]() { return args[idx++]; };
auto next_int = [&]() { return atoi(next()); };
auto next_float = [&]() { return atof(next()); };
int p = next_int();
int elems = next_int();
int nsteps = next_int();
double dt = next_float();
int plot_every = next_int();
// tumor parameters
tumor::params tumor;
tumor.tau_b = next_float();
tumor.o_prol_TC = next_float();
tumor.o_death_TC = next_float();
tumor.t_prol_TC = next_float();
tumor.t_death_TC = next_float();
tumor.P_b = next_float();
tumor.r_b = next_float();
tumor.beta_m = next_float();
tumor.gamma_a = next_float();
tumor.chi_aA = next_float();
tumor.gamma_oA = next_float();
tumor.diff_c = next_float();
tumor.cons_c = next_float();
// 3D only
tumor.alpha_0 = next_float();
tumor.gamma_T = next_float();
tumor.alpha_1 = next_float();
// Vasculature parameters
tumor::vasc::config vasc;
vasc.init_stability = next_float();
vasc.degeneration = next_float();
vasc.t_ec_sprout = next_float();
vasc.segment_length = next_float();
vasc.t_ec_collapse = next_float();
vasc.c_min = next_float();
// 2D only
vasc.t_ec_migr = next_float();
// 3D only
vasc.r_sprout = next_float();
vasc.r_max = next_float();
vasc.t_ec_switch = next_float();
vasc.c_switch = next_float();
vasc.dilatation = next_float();
return {p, elems, {nsteps, dt}, plot_every, tumor, vasc};
}
int main(int /*argc*/, char* argv[]) {
sim_params sp = parse_params(argv, 1);
ads::dim_config dim{sp.p, sp.elems, 0, 3000.0};
int ders = 1;
ads::config_2d c{dim, dim, sp.steps, ders};
tumor::vasc::random_vasculature rand_vasc{sp.vasc_config, 0};
tumor::tumor_2d sim{c, sp.tumor_params, sp.plot_every, rand_vasc()};
sim.run();
}
| 26.884211 | 76 | 0.632733 | Pan-Maciek |
dd0b9b7c456ca5ce3c9b526dde6e385123c9401a | 1,012 | cpp | C++ | src/hdfs_common.cpp | ZEMUSHKA/pydoop | e3d3378ae9921561f6c600c79364c2ad42ec206d | [
"Apache-2.0"
] | 1 | 2017-11-16T02:13:15.000Z | 2017-11-16T02:13:15.000Z | src/hdfs_common.cpp | ZEMUSHKA/pydoop | e3d3378ae9921561f6c600c79364c2ad42ec206d | [
"Apache-2.0"
] | null | null | null | src/hdfs_common.cpp | ZEMUSHKA/pydoop | e3d3378ae9921561f6c600c79364c2ad42ec206d | [
"Apache-2.0"
] | null | null | null | // BEGIN_COPYRIGHT
//
// Copyright 2009-2014 CRS4.
//
// 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.
//
// END_COPYRIGHT
#include "hdfs_common.hpp"
void hdfs_exception_translator(hdfs_exception const& x) {
PyErr_SetString(PyExc_IOError, x.what());
}
//++++++++++++++++++++++++++++++//
// Exporting class definitions. //
//++++++++++++++++++++++++++++++//
using namespace boost::python;
void export_hdfs_common() {
register_exception_translator<hdfs_exception>(hdfs_exception_translator);
}
| 28.111111 | 78 | 0.699605 | ZEMUSHKA |
dd0eb99be4447e58a8bfd4d6efe3a0f03c41d8ff | 26,469 | cpp | C++ | libraries/graphic/context.cpp | Max1412/vgraphics | 852141a63b24c975f0ab59d1d4517ea4dc64e3a5 | [
"CC-BY-4.0"
] | 1 | 2021-12-09T14:24:04.000Z | 2021-12-09T14:24:04.000Z | libraries/graphic/context.cpp | Max1412/vgraphics | 852141a63b24c975f0ab59d1d4517ea4dc64e3a5 | [
"CC-BY-4.0"
] | null | null | null | libraries/graphic/context.cpp | Max1412/vgraphics | 852141a63b24c975f0ab59d1d4517ea4dc64e3a5 | [
"CC-BY-4.0"
] | null | null | null | #include <set>
#define GLFW_INCLUDE_VULKAN
#include "Context.h"
#include "imgui/imgui_impl_vulkan.h"
#include "imgui/imgui_impl_glfw.h"
#include "spdlog/sinks/stdout_color_sinks.h"
namespace help
{
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pCallback) {
auto func = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"));
if (func != nullptr) {
return func(instance, pCreateInfo, pAllocator, pCallback);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT callback, const VkAllocationCallbacks* pAllocator) {
auto func = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"));
if (func != nullptr) {
func(instance, callback, pAllocator);
}
}
}
//todo remove this when the SDK update happened
VkResult vkCreateAccelerationStructureNV(VkDevice device, const VkAccelerationStructureCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureNV* pAccelerationStructure) {
auto func = reinterpret_cast<PFN_vkCreateAccelerationStructureNV>(vkGetDeviceProcAddr(device, "vkCreateAccelerationStructureNV"));
if (func != nullptr) {
return func(device, pCreateInfo, pAllocator, pAccelerationStructure);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void vkDestroyAccelerationStructureNV(VkDevice device, VkAccelerationStructureNV accelerationStructure, const VkAllocationCallbacks* pAllocator) {
auto func = reinterpret_cast<PFN_vkDestroyAccelerationStructureNV>(vkGetDeviceProcAddr(device, "vkDestroyAccelerationStructureNV"));
if (func != nullptr) {
return func(device, accelerationStructure, pAllocator);
}
}
void vkGetAccelerationStructureMemoryRequirementsNV(VkDevice device, const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) {
auto func = reinterpret_cast<PFN_vkGetAccelerationStructureMemoryRequirementsNV>(vkGetDeviceProcAddr(device, "vkGetAccelerationStructureMemoryRequirementsNV"));
if (func != nullptr) {
return func(device, pInfo, pMemoryRequirements);
}
}
VkResult vkBindAccelerationStructureMemoryNV(VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) {
auto func = reinterpret_cast<PFN_vkBindAccelerationStructureMemoryNV>(vkGetDeviceProcAddr(device, "vkBindAccelerationStructureMemoryNV"));
if (func != nullptr) {
return func(device, bindInfoCount, pBindInfos);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
VkResult vkGetAccelerationStructureHandleNV(
VkDevice device,
VkAccelerationStructureNV accelerationStructure,
size_t dataSize,
void* pData)
{
auto func = reinterpret_cast<PFN_vkGetAccelerationStructureHandleNV>(vkGetDeviceProcAddr(device, "vkGetAccelerationStructureHandleNV"));
if (func != nullptr) {
return func(device, accelerationStructure, dataSize, pData);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
VkResult vkCreateRayTracingPipelinesNV(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkRayTracingPipelineCreateInfoNV* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines)
{
auto func = reinterpret_cast<PFN_vkCreateRayTracingPipelinesNV>(vkGetDeviceProcAddr(device, "vkCreateRayTracingPipelinesNV"));
if (func != nullptr) {
return func(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
VkResult vkGetRayTracingShaderGroupHandlesNV(VkDevice device, VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void* pData)
{
auto func = reinterpret_cast<PFN_vkGetRayTracingShaderGroupHandlesNV>(vkGetDeviceProcAddr(device, "vkGetRayTracingShaderGroupHandlesNV"));
if (func != nullptr) {
return func(device, pipeline, firstGroup, groupCount, dataSize, pData);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
namespace vg
{
Context::Context(const std::vector<const char*>& requiredDeviceExtensions) : m_requiredDeviceExtensions(requiredDeviceExtensions)
{
// init logger
m_logger = spdlog::stdout_color_mt("standard");
m_logger->info("Logger initialized.");
// init rest
initWindow();
initVulkan();
initImgui();
}
Context::~Context()
{
cleanupImgui();
vmaDestroyAllocator(m_allocator);
for (const auto& imageView : m_swapChainImageViews)
{
m_device.destroyImageView(imageView);
}
m_device.destroySwapchainKHR(m_swapchain);
m_instance.destroySurfaceKHR(m_surface);
m_device.destroy();
help::DestroyDebugUtilsMessengerEXT(m_instance, m_callback, nullptr);
m_instance.destroy();
glfwDestroyWindow(m_window);
glfwTerminate();
}
void Context::initWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
//glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
m_window = glfwCreateWindow(m_width, m_height, "Vulkan", nullptr, nullptr);
glfwSetWindowUserPointer(m_window, this);
glfwSetFramebufferSizeCallback(m_window, framebufferResizeCallback);
}
void Context::framebufferResizeCallback(GLFWwindow* window, int width, int height)
{
auto context = reinterpret_cast<Context*>(glfwGetWindowUserPointer(window));
context->m_frameBufferResized = true;
}
void Context::initVulkan()
{
createInstance();
setupDebugCallback();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
createAllocator();
createSwapChain();
createImageViews();
}
void Context::createAllocator()
{
VmaAllocatorCreateInfo createInfo = {};
createInfo.device = m_device;
createInfo.physicalDevice = m_phsyicalDevice;
//createInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
auto result = vmaCreateAllocator(&createInfo, &m_allocator);
if (result != VK_SUCCESS)
throw std::runtime_error("Failed to create Allocator");
}
void Context::createInstance()
{
if (g_enableValidationLayers && !checkValidationLayerSupport())
{
throw std::runtime_error("Validation layers requested, but not available!");
}
vk::ApplicationInfo appInfo("Vulkan Test New", 1, "No Engine", 1, VK_API_VERSION_1_1);
// glfw + (cond.) debug layer
auto requiredExtensions = getRequiredExtensions();
std::vector<const char*> layerNames;
if constexpr (g_enableValidationLayers)
layerNames = g_validationLayers;
vk::InstanceCreateInfo createInfo({}, &appInfo, static_cast<uint32_t>(layerNames.size()), layerNames.data(), static_cast<uint32_t>(requiredExtensions.size()), requiredExtensions.data());
if (vk::createInstance(&createInfo, nullptr, &m_instance) != vk::Result::eSuccess)
throw std::runtime_error("Instance could not be created");
// print instance extensions
// getAllSupportedExtensions(true);
}
std::vector<const char*> Context::getRequiredExtensions()
{
uint32_t glfwExtensionCount = 0;
const auto exts = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> extensions(exts, exts + glfwExtensionCount);
if constexpr (g_enableValidationLayers)
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
return extensions;
}
std::vector<vk::ExtensionProperties> Context::getAllSupportedExtensions()
{
return vk::enumerateInstanceExtensionProperties();
}
bool Context::checkValidationLayerSupport() const
{
auto availableLayers = vk::enumerateInstanceLayerProperties();
for (const char* layerName : g_validationLayers)
{
bool layerFound = false;
for (const auto& layerProperties : availableLayers)
{
if (strcmp(layerName, layerProperties.layerName) == 0)
{
layerFound = true;
break;
}
}
if (!layerFound)
{
return false;
}
}
return true;
}
VKAPI_ATTR VkBool32 VKAPI_CALL Context::debugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
auto logger = spdlog::get("standard");
// todo log this properly depending on severity & type
switch (messageSeverity)
{
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
logger->info("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage);
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
logger->info("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage);
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
logger->warn("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage);
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
logger->critical("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage);
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT: break;
default: break ;
}
return VK_FALSE;
}
void Context::setupDebugCallback()
{
if constexpr (!g_enableValidationLayers) return;
using sevFlags = vk::DebugUtilsMessageSeverityFlagBitsEXT;
using typeFlags = vk::DebugUtilsMessageTypeFlagBitsEXT;
vk::DebugUtilsMessengerCreateInfoEXT createInfo(
{},
sevFlags::eError | sevFlags::eWarning | sevFlags::eVerbose,// | sevFlags::eInfo,
typeFlags::eGeneral | typeFlags::ePerformance | typeFlags::eValidation,
reinterpret_cast<PFN_vkDebugUtilsMessengerCallbackEXT>(debugCallback)
);
if (help::CreateDebugUtilsMessengerEXT(m_instance,
reinterpret_cast<VkDebugUtilsMessengerCreateInfoEXT*>(&createInfo), nullptr,
reinterpret_cast<VkDebugUtilsMessengerEXT *>(&m_callback)) != VK_SUCCESS)
{
throw std::runtime_error("failed to set up debug callback!");
}
}
void Context::pickPhysicalDevice()
{
// TODO scoring system preferring discrete GPUs
auto physDevices = m_instance.enumeratePhysicalDevices();
if (physDevices.empty())
throw std::runtime_error("No physical devices found");
for (const auto& device : physDevices)
{
if (isDeviceSuitable(device))
{
m_phsyicalDevice = device;
break;
}
}
if (!m_phsyicalDevice)
throw std::runtime_error("No suitable physical device found");
}
bool Context::isDeviceSuitable(vk::PhysicalDevice physDevice)
{
// TODO use actual stuff here
auto properties = physDevice.getProperties();
auto features = physDevice.getFeatures();
vk::PhysicalDeviceSubgroupProperties subProps;
vk::PhysicalDeviceProperties2 props;
props.pNext = &subProps;
if(std::find_if(m_requiredDeviceExtensions.begin(), m_requiredDeviceExtensions.end(),
[](const char* input){ return (strcmp(input, "VK_NV_ray_tracing") == 0); })
!= m_requiredDeviceExtensions.end())
{
m_raytracingProperties.emplace();
props.pNext = &m_raytracingProperties.value();
m_raytracingProperties.value().pNext = &subProps;
}
physDevice.getProperties2(&props); //NVIDIA only?
const bool testSubgroups = static_cast<uint32_t>(subProps.supportedStages) & static_cast<uint32_t>(vk::ShaderStageFlagBits::eRaygenNV);
// look for a GPU with geometry shader
const bool suitable = (properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu ||
properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu)
&& features.geometryShader;
// look for a graphics queue
QueueFamilyIndices indices = findQueueFamilies(physDevice);
// look if the wanted extensions are supported
const bool extensionSupport = checkDeviceExtensionSupport(physDevice);
// look for swapchain support
bool swapChainAdequate = false;
if (extensionSupport)
{
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physDevice);
swapChainAdequate = !swapChainSupport.m_formats.empty() && !swapChainSupport.m_presentModes.empty();
}
return suitable && indices.isComplete() && extensionSupport && swapChainAdequate && features.samplerAnisotropy;
}
bool Context::checkDeviceExtensionSupport(vk::PhysicalDevice physDevice)
{
auto availableExtensions = physDevice.enumerateDeviceExtensionProperties();
std::set<std::string> requiredExtensions(m_requiredDeviceExtensions.begin(), m_requiredDeviceExtensions.end());
for (const auto& extension : availableExtensions)
requiredExtensions.erase(extension.extensionName);
return requiredExtensions.empty();
}
QueueFamilyIndices Context::findQueueFamilies(vk::PhysicalDevice physDevice) const
{
QueueFamilyIndices indices;
auto qfprops = physDevice.getQueueFamilyProperties();
uint32_t i = 0;
for (const auto& queueFamily : qfprops)
{
if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eGraphics)
indices.graphicsFamily = i;
bool presentSupport = physDevice.getSurfaceSupportKHR(i, m_surface);
if (queueFamily.queueCount > 0 && presentSupport && queueFamily.queueFlags & vk::QueueFlagBits::eGraphics)
indices.presentFamily = i;
if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eTransfer && !(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics))
indices.transferFamily = i;
if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eCompute && !(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics))
indices.computeFamily = i;
if (indices.isComplete())
break;
i++;
}
//indices.computeFamily = 0;
return indices;
}
void Context::createLogicalDevice()
{
QueueFamilyIndices indices = findQueueFamilies(m_phsyicalDevice);
std::vector<vk::DeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value(), indices.transferFamily.value(), indices.computeFamily.value() };
const float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies)
{
vk::DeviceQueueCreateInfo queueCreateInfo({}, queueFamily, 1, &queuePriority);
queueCreateInfos.push_back(queueCreateInfo);
}
vk::PhysicalDeviceFeatures deviceFeatures;
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.vertexPipelineStoresAndAtomics = VK_TRUE;
deviceFeatures.fragmentStoresAndAtomics = VK_TRUE;
deviceFeatures.multiDrawIndirect = VK_TRUE;
deviceFeatures.shaderStorageImageExtendedFormats = VK_TRUE;
vk::DeviceCreateInfo createInfo({},
static_cast<uint32_t>(queueCreateInfos.size()), queueCreateInfos.data(),
0, nullptr,
static_cast<uint32_t>(m_requiredDeviceExtensions.size()), m_requiredDeviceExtensions.data(), &deviceFeatures);
if constexpr (g_enableValidationLayers)
{
createInfo.enabledLayerCount = static_cast<uint32_t>(g_validationLayers.size());
createInfo.ppEnabledLayerNames = g_validationLayers.data();
}
m_device = m_phsyicalDevice.createDevice(createInfo);
// get all the queues!
m_presentQueue = m_device.getQueue(indices.presentFamily.value(), 0);
m_graphicsQueue = m_device.getQueue(indices.graphicsFamily.value(), 0);
m_transferQueue = m_device.getQueue(indices.transferFamily.value(), 0);
m_computeQueue = m_device.getQueue(indices.computeFamily.value(), 0);
}
void Context::createSurface()
{
if (glfwCreateWindowSurface(m_instance, m_window, nullptr, reinterpret_cast<VkSurfaceKHR*>(&m_surface)) != VK_SUCCESS)
throw std::runtime_error("Surface creation failed");
}
SwapChainSupportDetails Context::querySwapChainSupport(vk::PhysicalDevice physDevice) const
{
SwapChainSupportDetails details;
details.m_capabilities = physDevice.getSurfaceCapabilitiesKHR(m_surface);
details.m_formats = physDevice.getSurfaceFormatsKHR(m_surface);
details.m_presentModes = physDevice.getSurfacePresentModesKHR(m_surface);
return details;
}
vk::SurfaceFormatKHR Context::chooseSwapChainSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats)
{
if (availableFormats.size() == 1 && availableFormats.at(0).format == vk::Format::eUndefined)
return { vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear };
for (const auto& availableFormat : availableFormats)
{
if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear)
return availableFormat;
}
return availableFormats.at(0);
}
vk::PresentModeKHR Context::chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes)
{
auto bestMode = vk::PresentModeKHR::eFifo;
for (const auto& availablePresentMode : availablePresentModes)
{
if (availablePresentMode == vk::PresentModeKHR::eMailbox)
return availablePresentMode;
if (availablePresentMode == vk::PresentModeKHR::eImmediate)
bestMode = availablePresentMode;
}
return bestMode;
}
vk::Extent2D Context::chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities)
{
if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max())
{
return capabilities.currentExtent;
}
else
{
glfwGetFramebufferSize(m_window, &m_width, &m_height);
VkExtent2D actualExtent = { static_cast<uint32_t>(m_width), static_cast<uint32_t>(m_height) };
actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width));
actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height));
return actualExtent;
}
}
void Context::createSwapChain()
{
auto swapChainSupport = querySwapChainSupport(m_phsyicalDevice);
auto surfaceFormat = chooseSwapChainSurfaceFormat(swapChainSupport.m_formats);
auto presentMode = chooseSwapPresentMode(swapChainSupport.m_presentModes);
auto extent = chooseSwapExtent(swapChainSupport.m_capabilities);
// determine the number of images in the swapchain (queue length)
uint32_t imageCount = swapChainSupport.m_capabilities.minImageCount + 1;
if (swapChainSupport.m_capabilities.maxImageCount > 0 && imageCount > swapChainSupport.m_capabilities.maxImageCount)
imageCount = swapChainSupport.m_capabilities.maxImageCount;
vk::SwapchainCreateInfoKHR createInfo({}, m_surface, imageCount, surfaceFormat.format, surfaceFormat.colorSpace, extent, 1, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eStorage);
QueueFamilyIndices indices = findQueueFamilies(m_phsyicalDevice);
uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
if (indices.graphicsFamily != indices.presentFamily)
{
createInfo.imageSharingMode = vk::SharingMode::eConcurrent; // exclusive is standard value
createInfo.queueFamilyIndexCount = 2; // 0 is standard value
}
else
{
createInfo.imageSharingMode = vk::SharingMode::eExclusive;
createInfo.queueFamilyIndexCount = 1;
}
createInfo.pQueueFamilyIndices = queueFamilyIndices;
createInfo.preTransform = swapChainSupport.m_capabilities.currentTransform;
createInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
createInfo.presentMode = presentMode;
createInfo.clipped = true;
createInfo.oldSwapchain = nullptr;
m_swapchain = m_device.createSwapchainKHR(createInfo);
m_swapChainImages = m_device.getSwapchainImagesKHR(m_swapchain);
m_swapChainImageFormat = surfaceFormat.format;
m_swapChainExtent = extent;
}
void Context::createImageViews()
{
m_swapChainImageViews.resize(m_swapChainImages.size());
for (size_t i = 0; i < m_swapChainImages.size(); i++)
{
vk::ImageViewCreateInfo createInfo({}, m_swapChainImages.at(i), vk::ImageViewType::e2D, m_swapChainImageFormat, {}, { vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 });
m_swapChainImageViews.at(i) = m_device.createImageView(createInfo);
}
}
vk::ShaderModule Context::createShaderModule(const std::vector<char>& code) const
{
vk::ShaderModuleCreateInfo createInfo({}, code.size(), reinterpret_cast<const uint32_t*>(code.data()));
return m_device.createShaderModule(createInfo);
}
void Context::initImgui()
{
ImGui::CreateContext();
ImGui_ImplGlfw_InitForVulkan(m_window, true);
// create imgui descriptor pool
vk::DescriptorPoolSize poolSizeCombinedImageSampler(vk::DescriptorType::eCombinedImageSampler, 1);
std::array<vk::DescriptorPoolSize, 1> poolSizes = { poolSizeCombinedImageSampler };
vk::DescriptorPoolCreateInfo poolInfo({}, 1, static_cast<uint32_t>(poolSizes.size()), poolSizes.data());
m_imguiDescriptorPool = m_device.createDescriptorPool(poolInfo);
// create imgui renderpass
vk::AttachmentDescription colorAttachment({}, m_swapChainImageFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eStore, // load store op
vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, // stencil op
vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::ePresentSrcKHR
);
vk::AttachmentReference colorAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal);
vk::AttachmentDescription depthAttachment({}, vk::Format::eD32SfloatS8Uint,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eDontCare,
vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::ImageLayout::eDepthStencilAttachmentOptimal
);
vk::AttachmentReference depthAttachmentRef(1, vk::ImageLayout::eDepthStencilAttachmentOptimal);
vk::SubpassDependency dependency(VK_SUBPASS_EXTERNAL, 0,
vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput,
{}, vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite, vk::DependencyFlagBits::eByRegion);
vk::SubpassDescription subpass({}, vk::PipelineBindPoint::eGraphics,
0, nullptr, // input attachments (standard values)
1, &colorAttachmentRef, // color attachments: layout (location = 0) out -> colorAttachmentRef is at index 0
nullptr, // no resolve attachment
&depthAttachmentRef); // depth stencil attachment
// other attachment at standard values: Preserved
std::array<vk::AttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
vk::RenderPassCreateInfo renderpassInfo({}, static_cast<uint32_t>(attachments.size()), attachments.data(), 1, &subpass, 1, &dependency);
m_imguiRenderpass = m_device.createRenderPass(renderpassInfo);
// init imgui
ImGui_ImplVulkan_InitInfo initInfo = {};
initInfo.Instance = static_cast<VkInstance>(m_instance);
initInfo.PhysicalDevice = static_cast<VkPhysicalDevice>(m_phsyicalDevice);
initInfo.Device = static_cast<VkDevice>(m_device);
initInfo.QueueFamily = findQueueFamilies(m_phsyicalDevice).graphicsFamily.value();
initInfo.Queue = m_graphicsQueue;
initInfo.PipelineCache = nullptr;
initInfo.DescriptorPool = m_imguiDescriptorPool;
ImGui_ImplVulkan_Init(&initInfo, static_cast<VkRenderPass>(m_imguiRenderpass));
}
void Context::cleanupImgui()
{
ImGui_ImplVulkan_InvalidateFontUploadObjects();
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
m_device.destroyDescriptorPool(m_imguiDescriptorPool);
m_device.destroyRenderPass(m_imguiRenderpass);
}
} | 41.55259 | 231 | 0.689297 | Max1412 |
dd1068e1623204396bc4ae2d3b64b14cb7c2f6e8 | 1,381 | cpp | C++ | 025_reverseNodesInKGroup/main.cpp | IdLeoO/LC | 445d8f1521d02c8481d590e5af914b6599bf8d7d | [
"MIT"
] | null | null | null | 025_reverseNodesInKGroup/main.cpp | IdLeoO/LC | 445d8f1521d02c8481d590e5af914b6599bf8d7d | [
"MIT"
] | null | null | null | 025_reverseNodesInKGroup/main.cpp | IdLeoO/LC | 445d8f1521d02c8481d590e5af914b6599bf8d7d | [
"MIT"
] | null | null | null | #include "main.hpp"
#include <iostream>
#include <stack>
using namespace std;
ListNode* Solution::reverseKGroup(ListNode* head, int k){
stack<ListNode*> storage;
ListNode* curPtr = head;
if (k == 1){
return head;
}
for (int i = 0; i < k; i++){
if (curPtr == nullptr){
return head;
}
storage.push(curPtr);
curPtr = curPtr->next;
}
ListNode* reverseHead = storage.top();
ListNode* nextRec = reverseHead->next;
storage.pop();
reverseHead->next = storage.top();
for (int i = 0; i < k - 1; i++){
ListNode* reverseCur = storage.top();
storage.pop();
if (storage.empty()){
reverseCur->next = reverseKGroup(nextRec, k);
}
else{
reverseCur->next = storage.top();
}
}
return reverseHead;
}
int main(int argc, char* argv[]){
ListNode *empty = new ListNode();
ListNode *a1 = new ListNode(1);
ListNode *a2 = new ListNode(2);
ListNode *a3 = new ListNode(3);
ListNode *a4 = new ListNode(4);
ListNode *a5 = new ListNode(5);
a1->next = a2;
a2->next = a3;
a3->next = a4;
a4->next = a5;
Solution sol;
auto result = sol.reverseKGroup(a1, 1);
while (result){
cout << result->val << " ";
result = result->next;
}
cout << endl;
return 0;
} | 23.40678 | 57 | 0.539464 | IdLeoO |
dd113b5535d1ff6a1a61ff598beeb5c329880ad4 | 871 | cpp | C++ | leddriver/src/ledimage.cpp | freesurfer-rge/picolife | db54c3398baf3fdfab5c72c75a5207b73847f443 | [
"MIT"
] | null | null | null | leddriver/src/ledimage.cpp | freesurfer-rge/picolife | db54c3398baf3fdfab5c72c75a5207b73847f443 | [
"MIT"
] | 7 | 2021-12-25T11:54:10.000Z | 2021-12-27T17:24:30.000Z | leddriver/src/ledimage.cpp | freesurfer-rge/picolife | db54c3398baf3fdfab5c72c75a5207b73847f443 | [
"MIT"
] | null | null | null | #include "leddriver/ledimage.hpp"
namespace LEDDriver
{
LEDImage::LEDImage() : red(std::make_unique<Channel>()),
green(std::make_unique<Channel>()),
blue(std::make_unique<Channel>())
{
this->Clear();
}
void LEDImage::Clear()
{
this->red->fill(0);
this->green->fill(0);
this->blue->fill(0);
}
void LEDImage::SetPixel(const unsigned int ix, const unsigned int iy,
const uint8_t r, const uint8_t g, const uint8_t b)
{
const size_t idx = ix + (LEDArray::nCols * iy);
this->red->at(idx) = r;
this->green->at(idx) = g;
this->blue->at(idx) = b;
}
void LEDImage::SendToLEDArray(LEDArray &target) const
{
target.UpdateBuffer(*(this->red), *(this->green), *(this->blue));
}
} | 27.21875 | 78 | 0.523536 | freesurfer-rge |
dd13f8ef1f5dc809a9358cb3a5be8178d5e380e8 | 726 | cpp | C++ | CD12/Maximum Number of Events That Can Be Attended.cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | 4 | 2019-12-12T19:59:50.000Z | 2020-01-20T15:44:44.000Z | CD12/Maximum Number of Events That Can Be Attended.cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | null | null | null | CD12/Maximum Number of Events That Can Be Attended.cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | null | null | null | // Question Link ---> https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/
class Solution {
public:
static bool cmp(vector<int> &a, vector<int> &b) {
if (a[1] == b[1]) {
return a[0] < b[0];
}
return a[1] < b[1];
}
int maxEvents(vector<vector<int>>& events) {
unordered_set<int> attended;
sort(events.begin(), events.end(), cmp);
for (auto event : events) {
for (int i = event[0]; i <= event[1]; i++) {
if (!attended.count(i)) {
attended.insert(i);
break;
}
}
}
return attended.size();
}
}; | 30.25 | 100 | 0.453168 | shtanriverdi |
dd1d9c969864541580624569ad00c7b04983d2c8 | 2,471 | cpp | C++ | component-tester/src/component-tester.cpp | shawnmharris/tachyon-examples | 0e634b969063ef87186b4863bf71c93b9c512df6 | [
"MIT"
] | null | null | null | component-tester/src/component-tester.cpp | shawnmharris/tachyon-examples | 0e634b969063ef87186b4863bf71c93b9c512df6 | [
"MIT"
] | null | null | null | component-tester/src/component-tester.cpp | shawnmharris/tachyon-examples | 0e634b969063ef87186b4863bf71c93b9c512df6 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <tachyon/component.hpp>
#include <itestcontract.hpp>
using namespace tachyon;
int main()
{
MasterFactory &mf = MasterFactory::Instance();
mf.Manage("component1");
mf.Manage("component2");
// test 1 is implemented in a shared dll
sp<ITestContract> sp1 = mf.Create<ITestContract>("ITestContract.TestComponent1");
// test 2 is implemented in a shared dll
sp<ITestContract> sp2 = mf.Create<ITestContract>("ITestContract.TestComponent2");
sp<ITestContract> sp3 = sp1;
sp<ITestContract> sp4 = sp2;
sp<ITestContract> sp5 = mf.Create<ITestContract>("ITestContract.TestComponent1");
if (!sp1.isValid() || !sp3.isValid() || !sp5.isValid())
{
std::cerr << "Invalid TestComponent1, program abort" << std::endl;
exit(0);
}
if (!sp2.isValid() || !sp4.isValid())
{
std::cerr << "Invalid TestComponent2, program abort" << std::endl;
exit(0);
}
if (!sp1->PostInit() || !sp3->PostInit() || !sp5->PostInit())
{
std::cerr << "TestComponent1, PostInit failure, program abort" << std::endl;
exit(0);
}
if (!sp2->PostInit() || !sp4->PostInit())
{
std::cerr << "TestComponent2, PostInit failure, program abort" << std::endl;
exit(0);
}
std::cout << std::endl;
std::cout << "BEGIN TESTS" << std::endl;
std::cout << std::endl;
std::cout << "TEST sp1->TestMethod() shows Implementation TestComponent1" << std::endl;
sp1->TestMethod();
std::cout << std::endl;
std::cout << "TEST sp2->TestMethod() shows Implementation TestComponent2" << std::endl;
sp2->TestMethod();
std::cout << std::endl;
std::cout << "TEST sp1 and sp3 have same name" << std::endl;
std::cout << "sp1 name :" << sp1->GetName() << std::endl;
std::cout << "sp3 name :" << sp3->GetName() << std::endl;
std::cout << std::endl;
std::cout << "TEST sp5 has unique name" << std::endl;
std::cout << "sp5 name :" << sp5->GetName() << std::endl;
std::cout << std::endl;
std::cout << "TEST sp2 and sp4 have same name" << std::endl;
std::cout << "sp2 name :" << sp2->GetName() << std::endl;
std::cout << "sp4 name :" << sp4->GetName() << std::endl;
std::cout << std::endl;
std::string pattern = "ITestContract\\.(.*)";
std::cout << "TEST find contracts using Regex pattern: " << pattern << std::endl;
auto spList = mf.CreateAll<ITestContract>(pattern);
for (auto itr = spList.begin(); itr != spList.end(); itr++)
{
if (itr->isValid())
{
std::cout << "PATTERN TEST FOUND : " << (*itr)->GetName() << std::endl;
}
}
}
| 27.455556 | 88 | 0.630109 | shawnmharris |
dd1f67c1ddda587b369e6747e25dc400b32df9f1 | 2,336 | hh | C++ | src/ui/win32/bindings/MultiLineGridBinding.hh | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 71 | 2018-04-15T13:02:43.000Z | 2022-03-26T11:19:18.000Z | src/ui/win32/bindings/MultiLineGridBinding.hh | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 309 | 2018-04-15T12:10:59.000Z | 2022-01-22T20:13:04.000Z | src/ui/win32/bindings/MultiLineGridBinding.hh | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 17 | 2018-04-17T16:09:31.000Z | 2022-03-04T08:49:03.000Z | #ifndef RA_UI_WIN32_MULTILINEGRIDBINDING_H
#define RA_UI_WIN32_MULTILINEGRIDBINDING_H
#pragma once
#include "GridBinding.hh"
namespace ra {
namespace ui {
namespace win32 {
namespace bindings {
class MultiLineGridBinding : public GridBinding
{
public:
explicit MultiLineGridBinding(ViewModelBase& vmViewModel) noexcept : GridBinding(vmViewModel) {}
GSL_SUPPRESS_F6 ~MultiLineGridBinding() noexcept = default;
MultiLineGridBinding(const MultiLineGridBinding&) noexcept = delete;
MultiLineGridBinding& operator=(const MultiLineGridBinding&) noexcept = delete;
MultiLineGridBinding(MultiLineGridBinding&&) noexcept = delete;
MultiLineGridBinding& operator=(MultiLineGridBinding&&) noexcept = delete;
GSL_SUPPRESS_CON3 LRESULT OnLvnItemChanging(const LPNMLISTVIEW pnmListView) override;
GSL_SUPPRESS_CON3 void OnLvnItemChanged(const LPNMLISTVIEW pnmListView) override;
LRESULT OnCustomDraw(NMLVCUSTOMDRAW* pCustomDraw) override;
void OnNmClick(const NMITEMACTIVATE* pnmItemActivate) override;
void OnNmDblClick(const NMITEMACTIVATE* pnmItemActivate) override;
void EnsureVisible(gsl::index nIndex) override;
protected:
void UpdateAllItems() override;
void UpdateItems(gsl::index nColumn) override;
void OnViewModelStringValueChanged(gsl::index nIndex, const StringModelProperty::ChangeArgs& args) override;
void OnViewModelAdded(gsl::index nIndex) override;
void OnViewModelRemoved(gsl::index nIndex) override;
void OnEndViewModelCollectionUpdate() override;
private:
gsl::index GetIndexForLine(gsl::index nLine) const;
void UpdateLineBreaks(gsl::index nIndex, gsl::index nColumn, const ra::ui::win32::bindings::GridColumnBinding* pColumn, size_t nChars);
static void GetLineBreaks(const std::wstring& sText, size_t nChars, std::vector<unsigned int>& vLineBreaks);
void UpdateLineOffsets();
int GetMaxCharsForColumn(gsl::index nColumn) const;
struct ItemMetrics
{
unsigned int nFirstLine = 0;
unsigned int nNumLines = 1;
std::map<int, std::vector<unsigned int>> mColumnLineOffsets;
};
std::vector<ItemMetrics> m_vItemMetrics;
gsl::index m_nLastClickedItem = 0;
};
} // namespace bindings
} // namespace win32
} // namespace ui
} // namespace ra
#endif // !RA_UI_WIN32_MULTILINEGRIDBINDING_H
| 36.5 | 139 | 0.769692 | Jamiras |
dd237c93e24ce9fe0246c6a0e207899a455714f3 | 2,610 | cpp | C++ | CApp.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | CApp.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | CApp.cpp | abishek-sampath/SDL-GameFramework | 0194540851eeaff6b4563feefb8edae7ca868700 | [
"MIT"
] | null | null | null | #include "CApp.h"
#undef main
CApp::CApp() {
// SDL resources
window = NULL;
renderer = NULL;
// User Resources
resourceManager = NULL;
running = true;
score = 0;
beginTime = 0;
numb_lives_to_gen = PLAYER_MAX_HEALTH - 2;
generateLives = true;
}
CApp::CApp(SDL_Renderer* renderer, ResourceManager* resourceManager)
{
// SDL resources
window = NULL;
this->renderer = renderer;
// User Resources
this->resourceManager = resourceManager;
running = true;
score = 0;
beginTime = 0;
numb_lives_to_gen = PLAYER_MAX_HEALTH - 2;
generateLives = true;
}
int CApp::OnExecute() {
if(OnInit() == false) {
printf("Initialization failed!\n");
OnCleanup();
return -1;
}
SDL_Event event;
while (running)
{
while (SDL_PollEvent(&event))
{
OnEvent(&event);
}
OnLoop();
OnRender();
}
if(score != -1) {
// load the music file
gameover_music = Mix_LoadMUS(GAMEOVER_MUSIC_FILE);
if (gameover_music != NULL)
{
Mix_PlayMusic(gameover_music, -1);
}
// START display GameLost
SDL_RenderClear(renderer);
SDL_Color whiteColor = { 0xff, 0xff, 0xff };
FontTexture endMsgTexture;
FontTexture endTexture;
std::stringstream endMsg;
endMsg << GAME_END_1 << score << GAME_END_2 << timeText.str() << GAME_END_3;
resourceManager->loadFontTexture(endMsgTexture, endMsg.str(), &whiteColor, FONT_SIZE_SMALL, (SCREEN_WIDTH * 0.9));
endMsgTexture.render(renderer, (SCREEN_WIDTH * 0.05), (SCREEN_HEIGHT * 0.3));
resourceManager->loadFontTexture(endTexture, GAME_END, &whiteColor, FONT_SIZE_SMALL, (SCREEN_WIDTH * 0.9));
endTexture.render(renderer, (SCREEN_WIDTH * 0.05), (SCREEN_HEIGHT * 0.9));
SDL_RenderPresent(renderer);
SDL_Event e;
// remove events during delay
SDL_Delay(1000);
SDL_PumpEvents();
SDL_FlushEvent(SDL_KEYDOWN | SDL_QUIT);
while(SDL_WaitEvent(&e))
{
if (e.type == SDL_KEYDOWN || e.type == SDL_QUIT)
{
break;
}
}
// set elaped time in milliseconds
beginTime = SDL_GetTicks() - beginTime;
// END display GameLost
}
OnCleanup();
return 0;
}
int main2(int argc, char* argv[])
{
CApp theApp;
return theApp.OnExecute();
}
int CApp::GetFinalScore()
{
return score;
}
Uint32 CApp::GetFinalTime()
{
return beginTime;
}
| 21.570248 | 122 | 0.586207 | abishek-sampath |
dd248d32555237459b88abf3d9a3703abb16eac6 | 174 | hpp | C++ | src/nSkinz.hpp | Massimoni/skinchanger | f2638f9cea2fe72340a62cc05d2d3c42cacc59ab | [
"MIT"
] | null | null | null | src/nSkinz.hpp | Massimoni/skinchanger | f2638f9cea2fe72340a62cc05d2d3c42cacc59ab | [
"MIT"
] | null | null | null | src/nSkinz.hpp | Massimoni/skinchanger | f2638f9cea2fe72340a62cc05d2d3c42cacc59ab | [
"MIT"
] | 1 | 2019-05-23T11:09:42.000Z | 2019-05-23T11:09:42.000Z | #pragma once
#include "SDK.hpp"
#include "RecvProxyHook.hpp"
extern VMTHook* g_client_hook;
extern VMTHook* g_game_event_manager_hook;
extern RecvPropHook* g_sequence_hook; | 21.75 | 42 | 0.821839 | Massimoni |
dd25f6c5d6c0376cd11b5e8d0bba88ddfba6a7d8 | 421 | cpp | C++ | src/math/agg_final.cpp | tarkmeper/numpgsql | a5098af9b7c4d88564092c0a4809029aab9f614f | [
"MIT"
] | 5 | 2019-04-08T15:25:32.000Z | 2019-12-07T16:31:55.000Z | src/math/agg_final.cpp | tarkmeper/numpgsql | a5098af9b7c4d88564092c0a4809029aab9f614f | [
"MIT"
] | null | null | null | src/math/agg_final.cpp | tarkmeper/numpgsql | a5098af9b7c4d88564092c0a4809029aab9f614f | [
"MIT"
] | null | null | null | #include "agg.hpp"
extern "C" {
PG_FUNCTION_INFO_V1(internal_to_array);
Datum internal_to_array(PG_FUNCTION_ARGS);
}
Datum internal_to_array(PG_FUNCTION_ARGS) {
//TODO trigger destructor
Assert(AggCheckCallContext(fcinfo, NULL));
if (PG_ARGISNULL(0)) {
PG_RETURN_NULL();
} else {
AggInternal* state = (AggInternal*)(PG_GETARG_POINTER(0));
PG_RETURN_ARRAYTYPE_P( state->fnc(state) );
}
}
| 21.05 | 63 | 0.712589 | tarkmeper |
dd2f39398626d6035f8b8ec8dcb0379927b7c5cc | 1,555 | cpp | C++ | src/utils.cpp | atlochowski/harbour-powietrze | e47bf1f397d81a9f69363a44e785ca9248ecef17 | [
"BSD-3-Clause"
] | 2 | 2019-10-24T12:43:18.000Z | 2019-12-22T20:59:18.000Z | src/utils.cpp | atlochowski/harbour-powietrze | e47bf1f397d81a9f69363a44e785ca9248ecef17 | [
"BSD-3-Clause"
] | 9 | 2019-07-18T19:39:14.000Z | 2021-06-13T18:29:55.000Z | src/utils.cpp | atlochowski/harbour-powietrze | e47bf1f397d81a9f69363a44e785ca9248ecef17 | [
"BSD-3-Clause"
] | 5 | 2019-10-24T12:49:15.000Z | 2021-05-17T10:47:42.000Z | #include "utils.h"
#include <notification.h>
#include <iostream>
void Utils::simpleNotification(QString header, QString body, QString function, QVariantList parameters)
{
Notification notification;
notification.setCategory("powietrze.update");
notification.setSummary(header);
notification.setBody(body);
notification.setPreviewSummary(header);
notification.setPreviewBody(body);
notification.setRemoteAction(Notification::remoteAction("default",
"",
"harbour.powietrze.service",
"/harbour/powietrze/service",
"harbour.powietrze.service",
function,
parameters));
notification.publish();
}
float Utils::calculateWHONorms(const Pollution& sensorData) {
if (!sensorData.isInitialized()) {
return -1;
}
std::list<WHONorm> pollutions = {
{"pm25", 25.f, 24},
{"pm10", 50.f, 24},
{"no2", 200.f, 1},
{"o3", 100.f, 8},
{"so2", 350.f, 1},
{"co", 30000.f, 1}
};
for (auto pollution: pollutions) {
if (pollution.name == sensorData.code) {
float avg = sensorData.avg(pollution.hours);
return avg / pollution.value * 100;
}
}
return -1;
}
| 31.1 | 103 | 0.48746 | atlochowski |
dd35531bf699f1b942f91eee1b38b6f15f2bdb4b | 69 | hpp | C++ | include/components/battle/Fainted.hpp | Ghabriel/PokemonCpp | dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e | [
"Apache-2.0"
] | 6 | 2018-08-05T21:45:23.000Z | 2021-10-30T19:48:34.000Z | include/components/battle/Fainted.hpp | Ghabriel/PokemonCpp | dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e | [
"Apache-2.0"
] | null | null | null | include/components/battle/Fainted.hpp | Ghabriel/PokemonCpp | dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e | [
"Apache-2.0"
] | 1 | 2021-11-01T20:15:38.000Z | 2021-11-01T20:15:38.000Z | #ifndef FAINTED_HPP
#define FAINTED_HPP
struct Fainted { };
#endif
| 9.857143 | 19 | 0.753623 | Ghabriel |
dd37a9ec1f567d6efebbf27b6a8daabc460e3d5a | 4,472 | cpp | C++ | 601-700/636-Exclusive_Time_of_Functions-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | 1 | 2018-10-02T22:44:52.000Z | 2018-10-02T22:44:52.000Z | 601-700/636-Exclusive_Time_of_Functions-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | 601-700/636-Exclusive_Time_of_Functions-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | // Given the running logs of n functions that are executed in a nonpreemptive
// single threaded CPU, find the exclusive time of these functions.
// Each function has a unique id, start from 0 to n-1. A function may be called
// recursively or by another function.
// A log is a string has this format : function_id:start_or_end:timestamp. For
// example, "0:start:0" means function 0 starts from the very beginning of time
// 0. "0:end:0" means function 0 ends to the very end of time 0.
// Exclusive time of a function is defined as the time spent within this
// function, the time spent by calling other functions should not be considered
// as this function's exclusive time. You should return the exclusive time of
// each function sorted by their function id.
// Example 1:
// Input:
// n = 2
// logs =
// ["0:start:0",
// "1:start:2",
// "1:end:5",
// "0:end:6"]
// Output:[3, 4]
// Explanation:
// Function 0 starts at time 0, then it executes 2 units of time and reaches the
// end of time 1. Now function 0 calls function 1, function 1 starts at time 2,
// executes 4 units of time and end at time 5. Function 0 is running again at
// time 6, and also end at the time 6, thus executes 1 unit of time. So function
// 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4
// units of time.
// Note:
// Input logs will be sorted by timestamp, NOT log id.
// Your output should be sorted by function id, which means the 0th element
// of your output corresponds to the exclusive time of function 0. Two
// functions won't start or end at the same time. Functions could be called
// recursively, and will always end. 1 <= n <= 100
// WTF the problem description is
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string> &logs) {
vector<int> ret(n);
vector<vector<int>> ilogs(logs.size(), vector<int>(3));
// ilogs[i] == {id, start or end, time}, with unified timestamp
for (int i = 0; i < logs.size(); ++i) {
auto c = logs[i].find(':');
ilogs[i][0] = stoi(logs[i].substr(0, c));
ilogs[i][1] = logs[i][c + 1];
ilogs[i][2] = stoi(logs[i].substr(logs[i].rfind(':') + 1)) +
(ilogs[i][1] == 'e');
}
stack<vector<int>> s;
for (int i = 0; i < ilogs.size(); ++i) {
if (s.empty()) {
s.push(ilogs[i]);
continue;
}
ret[s.top()[0]] += ilogs[i][2] - s.top()[2];
if (ilogs[i][0] == s.top()[0] && ilogs[i][1] == 'e') {
int t = ilogs[i][2];
s.pop();
if (!s.empty())
s.top()[2] = t;
} else
s.push(ilogs[i]);
// cout << ret[0] << ' ' << ret[1] << endl;
}
return ret;
}
};
// simplified
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string> &logs) {
vector<int> ret(n);
stack<array<int, 3>> s;
int id, status, t; // {id, status, unified timestamp}
for (auto &&lg : logs) {
auto c = lg.find(':');
id = stoi(lg.substr(0, c));
status = lg[c + 1];
t = stoi(lg.substr(lg.rfind(':') + 1)) + (status == 'e');
if (s.empty()) {
s.push({id, status, t});
continue;
}
ret[s.top()[0]] += t - s.top()[2];
if (id == s.top()[0] && status == 'e') {
s.pop();
if (!s.empty())
s.top()[2] = t;
} else
s.push({id, status, t});
}
return ret;
}
};
// further simplified
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string> &logs) {
vector<int> ret(n);
stack<int> s;
int id, t, prevt;
char status;
for (auto &&lg : logs) {
auto c = lg.find(':');
id = stoi(lg.substr(0, c));
status = lg[c + 1];
t = stoi(lg.substr(lg.rfind(':') + 1)) + (status == 'e');
if (s.empty())
s.push(id);
else {
ret[s.top()] += t - prevt;
if (id == s.top() && status == 'e')
s.pop();
else
s.push(id);
}
prevt = t;
}
return ret;
}
}; | 30.421769 | 80 | 0.503801 | ysmiles |
dd3b3c9771b3885e6a182e1137e291c6d2a4d353 | 541 | hpp | C++ | src/color/gray/akin/lab.hpp | ehtec/color | aa6d8c796303d1f3cfd7361978bfa58eac808b6e | [
"Apache-2.0"
] | 120 | 2015-12-31T22:30:14.000Z | 2022-03-29T15:08:01.000Z | src/color/gray/akin/lab.hpp | ehtec/color | aa6d8c796303d1f3cfd7361978bfa58eac808b6e | [
"Apache-2.0"
] | 6 | 2016-08-22T02:14:56.000Z | 2021-11-06T22:39:52.000Z | src/color/gray/akin/lab.hpp | ehtec/color | aa6d8c796303d1f3cfd7361978bfa58eac808b6e | [
"Apache-2.0"
] | 23 | 2016-02-03T01:56:26.000Z | 2021-09-28T16:36:27.000Z | #ifndef color_gray_akin_lab
#define color_gray_akin_lab
#include "../../generic/akin/gray.hpp"
#include "../category.hpp"
#include "../../lab/category.hpp"
namespace color
{
namespace akin
{
template
<
typename tag_name
,::color::constant::lab::reference_enum lab_reference_number
>
struct gray< ::color::category::lab< tag_name, lab_reference_number > >
{
public:
typedef ::color::category::gray< tag_name > akin_type;
};
}
}
#endif
| 19.321429 | 77 | 0.593346 | ehtec |
dd3dfe96c626cba5ef08dd7a1d50a578b5654795 | 1,383 | cpp | C++ | source/requests/EdgarRequests.cpp | Jde-cpp/TwsWebSocket | 099ef66e2481bd12019d634ba8125b17d9c2d67e | [
"MIT"
] | null | null | null | source/requests/EdgarRequests.cpp | Jde-cpp/TwsWebSocket | 099ef66e2481bd12019d634ba8125b17d9c2d67e | [
"MIT"
] | null | null | null | source/requests/EdgarRequests.cpp | Jde-cpp/TwsWebSocket | 099ef66e2481bd12019d634ba8125b17d9c2d67e | [
"MIT"
] | null | null | null | #include "EdgarRequests.h"
#include "../../../Private/source/markets/edgar/Edgar.h"
#include "../../../Private/source/markets/edgar/Form13F.h"
namespace Jde::Markets::TwsWebSocket
{
void EdgarRequests::Filings( Cik cik, ProcessArg&& inputArg )noexcept
{
std::thread( [cik, arg=move(inputArg)]()
{
try
{
auto p = Edgar::LoadFilings(cik); p->set_request_id( arg.ClientId );
MessageType msg; msg.set_allocated_filings( p.release() );
arg.Push( move(msg) );
}
catch( IException& e )
{
arg.Push( "could not retreive filings", e );
}
}).detach();
}
void Investors2( function<up<Edgar::Proto::Investors>()> f, ProcessArg&& inputArg )noexcept
{
std::thread( [f, arg=move(inputArg)]()
{
try
{
auto p = f(); p->set_request_id( arg.ClientId );
MessageType msg; msg.set_allocated_investors( p.release() );
arg.Push( move(msg) );
}
catch( IException& e )
{
arg.Push( "Could not load investors", e );
}
}).detach();
}
void EdgarRequests::Investors( ContractPK contractId, ProcessArg&& arg )noexcept
{
return Investors2( [contractId]()
{
auto pDetails = SFuture<::ContractDetails>( Tws::ContractDetail(contractId) ).get();
//TwsClientSync::ReqContractDetails( contractId ).get(); CHECK( (pDetails->size()==1) );
return Edgar::Form13F::LoadInvestors( pDetails->longName );
}, move(arg) );
}
} | 27.66 | 92 | 0.647144 | Jde-cpp |
dd3f5a22d08de4ccd846d871c43757f0f2945b2c | 8,007 | cpp | C++ | Game/Game/Game/Export/Export_Lua_Scene.cpp | CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493 | da25260dc8128ed66b48d391c738eb15134d7d4f | [
"Zlib",
"MIT-0",
"MIT"
] | null | null | null | Game/Game/Game/Export/Export_Lua_Scene.cpp | CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493 | da25260dc8128ed66b48d391c738eb15134d7d4f | [
"Zlib",
"MIT-0",
"MIT"
] | null | null | null | Game/Game/Game/Export/Export_Lua_Scene.cpp | CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493 | da25260dc8128ed66b48d391c738eb15134d7d4f | [
"Zlib",
"MIT-0",
"MIT"
] | null | null | null | #include "Export_Lua_Scene.h"
#include "Export_Lua_Const.h"
#include "../Header/SceneConst.h"
#include "../Classes/LoadingScene.h"
#include "../Classes/TitleScene.h"
#include "../Classes/HelpScene.h"
#include "../Classes/StageSelectScene.h"
#include "../Classes/MissionSelectScene.h"
#include "../Classes/StoryScene.h"
#include "../Classes/PlayScene.h"
#define LUASCENE_SCENE_IO "Scene_IO"
#define LUASCENE_SCENE_CB "Scene_CB"
#define LUASCENE_INPUTLAYER_CB "InputLayer_CB"
#define LUASCENE_TOUCHLAYER_CB "TouchLayer_CB"
LuaFunction<bool> * Export_Lua_Scene::ioScene;
LuaFunction<bool> * Export_Lua_Scene::cbScene;
LuaFunction<bool> * Export_Lua_Scene::cbInputLayer;
LuaFunction<bool> * Export_Lua_Scene::cbTouchLayer;
bool Export_Lua_Scene::_LuaRegistConst(LuaObject * obj)
{
obj->SetInteger("SceneIOFlag_OnInit", LUASCENE_IOFLAG_ONINIT);
obj->SetInteger("SceneIOFlag_OnEnter", LUASCENE_IOFLAG_ONENTER);
obj->SetInteger("SceneIOFlag_OnEnterA", LUASCENE_IOFLAG_ONENTERA);
obj->SetInteger("SceneIOFlag_OnEnterTDF", LUASCENE_IOFLAG_ONENTERTDF);
obj->SetInteger("SceneIOFlag_OnEnterTDFA", LUASCENE_IOFLAG_ONENTERTDFA);
obj->SetInteger("SceneIOFlag_OnUpdate", LUASCENE_IOFLAG_ONUPDATE);
obj->SetInteger("SceneIOFlag_OnExit", LUASCENE_IOFLAG_ONEXIT);
obj->SetInteger("SceneIOFlag_OnTouchBegin", LUASCENE_IOFLAG_ONTOUCHBEGIN);
obj->SetInteger("SceneIOFlag_OnTouchEnd", LUASCENE_IOFLAG_ONTOUCHEND);
obj->SetInteger("ktag_BaseSceneLayer", KTAG_BASESCENELAYER);
obj->SetInteger("ktag_LoadingSceneLayer", KTAG_LOADINGSCENELAYER);
obj->SetInteger("ktag_TitleSceneLayer", KTAG_TITLESCENELAYER);
obj->SetInteger("ktag_HelpSceneLayer", KTAG_HELPSCENELAYER);
obj->SetInteger("ktag_StageSelectSceneLayer", KTAG_STAGESELECTSCENELAYER);
obj->SetInteger("ktag_MissionSelectSceneLayer", KTAG_MISSIONSELECTSCENELAYER);
obj->SetInteger("ktag_StorySceneLayer", KTAG_STORYSCENELAYER);
obj->SetInteger("ktag_PlaySceneLayer", KTAG_PLAYSCENELAYER);
obj->SetInteger("ktag_OverlayLayer", KTAG_OVERLAYLAYER);
return true;
}
bool Export_Lua_Scene::_LuaRegistFunction(LuaObject * obj)
{
return true;
}
bool Export_Lua_Scene::InitCallbacks()
{
LuaState * ls = state;
LuaObject _obj = ls->GetGlobal(LUASCENE_SCENE_IO);
if (!_obj.IsFunction())
{
ShowError(LUAERROR_NOTFUNCTION, LUASCENE_SCENE_IO);
return false;
}
static LuaFunction<bool> _fsceneio = _obj;
_fsceneio = _obj;
ioScene = &_fsceneio;
_obj = ls->GetGlobal(LUASCENE_SCENE_CB);
if (!_obj.IsFunction())
{
ShowError(LUAERROR_NOTFUNCTION, LUASCENE_SCENE_CB);
return false;
}
static LuaFunction<bool> _fscenecb = _obj;
_fscenecb = _obj;
cbScene = &_fscenecb;
_obj = ls->GetGlobal(LUASCENE_INPUTLAYER_CB);
if (!_obj.IsFunction())
{
ShowError(LUAERROR_NOTFUNCTION, LUASCENE_INPUTLAYER_CB);
return false;
}
static LuaFunction<bool> _finputlayercb = _obj;
_finputlayercb = _obj;
cbInputLayer = &_finputlayercb;
_obj = ls->GetGlobal(LUASCENE_TOUCHLAYER_CB);
if (!_obj.IsFunction())
{
ShowError(LUAERROR_NOTFUNCTION, LUASCENE_TOUCHLAYER_CB);
return false;
}
static LuaFunction<bool> _ftouchlayercb = _obj;
_ftouchlayercb = _obj;
cbTouchLayer = &_ftouchlayercb;
return true;
}
/************************************************************************/
/* SceneGet */
/************************************************************************/
void Export_Lua_Scene::_GetSceneMenuCallback(int scenetag, SEL_MenuHandler * cbfunc, SEL_CallFuncND * cbndfunc)
{
scenetag = scenetag & KTAG_SCENELAYERMASK;
switch (scenetag)
{
case KTAG_LOADINGSCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(LoadingScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(LoadingScene::NodeCallbackFunc);
}
break;
case KTAG_TITLESCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(TitleScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(TitleScene::NodeCallbackFunc);
}
break;
case KTAG_HELPSCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(HelpScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(HelpScene::NodeCallbackFunc);
}
break;
case KTAG_STAGESELECTSCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(StageSelectScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(StageSelectScene::NodeCallbackFunc);
}
break;
case KTAG_MISSIONSELECTSCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(MissionSelectScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(MissionSelectScene::NodeCallbackFunc);
}
break;
case KTAG_STORYSCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(StoryScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(StoryScene::NodeCallbackFunc);
}
break;
case KTAG_PLAYSCENELAYER:
if (cbfunc)
{
*cbfunc = menu_selector(PlayScene::MenuCallbackFunc);
}
if (cbndfunc)
{
*cbndfunc = callfuncND_selector(PlayScene::NodeCallbackFunc);
}
break;
}
}
int Export_Lua_Scene::_GetTopTag(int itemtag)
{
return itemtag & KTAG_SCENELAYERMASK;
}
int Export_Lua_Scene::_GetSubLayerTag(int itemtag)
{
return itemtag & KTAG_SUBLAYERMASK;
}
int Export_Lua_Scene::_GetMenuGroupTag(int itemtag)
{
return itemtag & KTAG_MENUGROUPMASK;
}
int Export_Lua_Scene::_GetMenuItemTag(int itemtag)
{
return itemtag & KTAG_MENUITEMMASK;
}
CCScene * Export_Lua_Scene::_GetNewScene(int scenetag)
{
scenetag = scenetag & KTAG_SCENELAYERMASK;
switch (scenetag)
{
case KTAG_LOADINGSCENELAYER:
return LoadingScene::scene();
break;
case KTAG_TITLESCENELAYER:
return TitleScene::scene();
break;
case KTAG_HELPSCENELAYER:
return HelpScene::scene();
break;
case KTAG_STAGESELECTSCENELAYER:
return StageSelectScene::scene();
break;
case KTAG_MISSIONSELECTSCENELAYER:
return MissionSelectScene::scene();
break;
case KTAG_STORYSCENELAYER:
return StoryScene::scene();
break;
case KTAG_PLAYSCENELAYER:
return PlayScene::scene();
break;
}
return NULL;
}
/************************************************************************/
/* Callback */
/************************************************************************/
bool Export_Lua_Scene::ExecuteIOScene(BYTE flag, CCLayer *toplayer, int toptag)
{
LuaState * ls = state;
bool bret = (*ioScene)(flag, CDOUBLEN(toplayer), toptag);
if (state->CheckError())
{
Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError());
}
return bret;
}
bool Export_Lua_Scene::ExecuteCBScene(int tag, CCLayer * toplayer, int dataindex /* = -1 */)
{
LuaState * ls = state;
bool bret = (*cbScene)(tag, CDOUBLEN(toplayer), _GetTopTag(tag), _GetSubLayerTag(tag), _GetMenuGroupTag(tag), _GetMenuItemTag(tag), dataindex);
if (state->CheckError())
{
Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError());
}
return bret;
}
bool Export_Lua_Scene::ExecuteCBInputLayer(int tag, CCLayer * toplayer, int eventtag, const char * text)
{
LuaState * ls = state;
bool bret = (*cbInputLayer)(tag, CDOUBLEN(toplayer), eventtag, _GetTopTag(tag), _GetSubLayerTag(tag), text);
if (state->CheckError())
{
Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError());
}
return bret;
}
bool Export_Lua_Scene::ExecuteCBTouchLayer(int tag, CCLayer * toplayer, int eventtag, CCLayer * thislayer, int index, BYTE gesture)
{
LuaState * ls = state;
bool bret = (*cbTouchLayer)(CDOUBLEN(toplayer), eventtag, _GetTopTag(tag), tag&KTAG_SUBLAYERMASK, CDOUBLEN(thislayer), index, gesture);
if (state->CheckError())
{
Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError());
}
return bret;
} | 28.393617 | 145 | 0.690396 | CBE7F1F65 |
dd50ebbb858c8453eb9a4bd8aabf945f87c3bd67 | 1,716 | hpp | C++ | HugeCTR/include/pybind/data_source_wrapper.hpp | mikemckiernan/HugeCTR | 1a0a618f9848eb908e9d1265c555fba9924d2861 | [
"Apache-2.0"
] | 130 | 2021-10-11T11:55:28.000Z | 2022-03-31T21:53:07.000Z | HugeCTR/include/pybind/data_source_wrapper.hpp | Teora/HugeCTR | c55a63401ad350669ccfcd374aefd7a5fc879ca2 | [
"Apache-2.0"
] | 72 | 2021-10-09T04:59:09.000Z | 2022-03-31T11:27:54.000Z | HugeCTR/include/pybind/data_source_wrapper.hpp | Teora/HugeCTR | c55a63401ad350669ccfcd374aefd7a5fc879ca2 | [
"Apache-2.0"
] | 29 | 2021-11-03T22:35:01.000Z | 2022-03-30T13:11:59.000Z | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <hdfs_backend.hpp>
namespace HugeCTR {
namespace python_lib {
void DataSourcePybind(pybind11::module &m) {
pybind11::module data = m.def_submodule("data", "data submodule of hugectr");
pybind11::class_<HugeCTR::DataSourceParams, std::shared_ptr<HugeCTR::DataSourceParams>>(
data, "DataSourceParams")
.def(pybind11::init<const bool, const std::string &, const int>(),
pybind11::arg("use_hdfs") = false, pybind11::arg("namenode") = "localhost",
pybind11::arg("port") = 9000)
.def_readwrite("use_hdfs", &HugeCTR::DataSourceParams::use_hdfs)
.def_readwrite("namenode", &HugeCTR::DataSourceParams::namenode)
.def_readwrite("port", &HugeCTR::DataSourceParams::port);
pybind11::class_<HugeCTR::DataSource, std::shared_ptr<HugeCTR::DataSource>>(data, "DataSource")
.def(pybind11::init<const DataSourceParams &>(), pybind11::arg("data_source_params"))
.def("move_to_local", &HugeCTR::DataSource::move_to_local);
}
} // namespace python_lib
} // namespace HugeCTR | 41.853659 | 97 | 0.7162 | mikemckiernan |
dd55c9a76e5fab0d929abdd83067aeef115e8bf4 | 64 | cc | C++ | MCDataProducts/src/CrvDigiMC.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:00:12.000Z | 2021-06-25T00:00:12.000Z | MCDataProducts/src/CrvDigiMC.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 125 | 2020-04-03T13:44:30.000Z | 2021-10-15T21:29:57.000Z | MCDataProducts/src/CrvDigiMC.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 2 | 2019-10-14T17:46:58.000Z | 2020-03-30T21:05:15.000Z | #include "MCDataProducts/inc/CrvDigiMC.hh"
namespace mu2e
{
}
| 10.666667 | 42 | 0.75 | bonventre |
dd5bd5d2272934b306850d72505e29339fcaf099 | 2,006 | cc | C++ | cpp/functions/run/run_benchmark_santos.cc | michieluithetbroek/A-MDVRP | fe7739f3961ddb25db8f64ec20472915d3c95168 | [
"MIT"
] | 23 | 2020-04-09T16:33:23.000Z | 2022-03-21T16:41:11.000Z | cpp/functions/run/run_benchmark_santos.cc | michieluithetbroek/A-MDVRP | fe7739f3961ddb25db8f64ec20472915d3c95168 | [
"MIT"
] | 2 | 2020-04-10T11:55:28.000Z | 2020-04-10T12:11:51.000Z | cpp/functions/run/run_benchmark_santos.cc | michieluithetbroek/A-MDVRP | fe7739f3961ddb25db8f64ec20472915d3c95168 | [
"MIT"
] | 10 | 2020-05-28T18:59:52.000Z | 2022-03-10T13:32:44.000Z | #include "./../../main.ih"
/*
* This functions runs all the instances from Santos
*
* TODO remove bool deterministic
*/
void run_benchmark_santos(int idx_instance, bool deterministic, int rep)
{
bool const withoutGurobi = false;
if (not deterministic)
throw string("Opportunistic run is not allowed! (run_benchmark_santos)");
g_cutPasses = 500;
g_userSettingA = 200; //200;
g_userSettingB = 200;
g_cplexFocusLB = true; // CPLEX focussed on LB
g_onlyRoot = false; // Solve the whole branch-and-bound
g_cplexCuts = true; // 0 = with cplex cuts, -1 = without
g_useGurobi = true;
if (withoutGurobi)
{
g_cplexFocusLB = false; // CPLEX focussed on LB
g_onlyRoot = false; // Solve the whole branch-and-bound
g_cplexCuts = true; // 0 = with cplex cuts, -1 = without
g_useGurobi = false;
}
int const cutProfile = 1;
/*
* The following sets the global enums INSTANCE and DATA_ASYMMETRY
* This is used in the Data struct to set the costs and to activate
* the proper constraints in the ModelA class.
*
*/
hash_and_set_globals(12, 0);
Data data (idx_instance);
if (deterministic and not withoutGurobi)
{
string folder("results/santos/"
+ to_string(idx_instance)
+ "_nThreads-"
+ to_string(g_nThreads)
+ "_rep-"
+ to_string(rep));
run_single_instance(data, folder, cutProfile);
}
else if (deterministic and withoutGurobi)
{
cout << "without Gurobi!" << endl;
string folder("results/santos/"
+ to_string(idx_instance)
+ "_nThreads-"
+ to_string(g_nThreads)
+ "_withoutGurobi"
+ "_rep-"
+ to_string(rep));
run_single_instance(data, folder, cutProfile);
}
else
{
string folder("results/santos/"
+ to_string(idx_instance)
+ "_par_" + to_string(rep));
run_single_instance(data, folder, cutProfile);
}
}
| 24.168675 | 77 | 0.621137 | michieluithetbroek |
dd5f44f135378685091c3e4105c9a09dec58f000 | 2,639 | cpp | C++ | src/main.cpp | finnff/IPASS-19 | b65ad79282a63c1f0db3addfaf865e99677ecd2c | [
"MIT"
] | null | null | null | src/main.cpp | finnff/IPASS-19 | b65ad79282a63c1f0db3addfaf865e99677ecd2c | [
"MIT"
] | null | null | null | src/main.cpp | finnff/IPASS-19 | b65ad79282a63c1f0db3addfaf865e99677ecd2c | [
"MIT"
] | null | null | null | #include "mpu6050.hpp"
#include "pongresources.hpp"
int main(int argc, char **argv) {
namespace target = hwlib::target;
// Intialize OLED display
auto scl = target::pin_oc(target::pins::d10);
auto sda = target::pin_oc(target::pins::d11);
auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda(scl, sda);
auto w = hwlib::glcd_oled(i2c_bus, 0x3c);
// Intialize i2c bus for use with 2x gy-521 Breakout boards
auto scl1 = target::pin_oc(target::pins::d21);
auto sda1 = target::pin_oc(target::pins::d20);
auto iic = hwlib::i2c_bus_bit_banged_scl_sda(scl1, sda1);
auto chipL = mpu6050(iic, 0x68); // AD0 LOW
auto chipR = mpu6050(iic, 0x69); // AD0 HI
chipL.init();
chipR.init();
int rwidth =
128; // Set screen width resolution , OLED is 128*64, used for scaling
int rheight = 64;
int Lscore = 0; // init score
int Rscore = 0;
RandomBall b(w, 128, 64); // Construct random ball object
bat r(w, hwlib::xy((rwidth - (rwidth / 10)) - 2, rheight / 2),
hwlib::xy((rwidth - (rwidth / 10)), ((rheight / 2) + (rheight / 5))));
bat l(w, hwlib::xy(rwidth / 10, rheight / 2),
hwlib::xy((rwidth / 10 + 2), ((rheight / 2) + (rheight / 5))));
for (;;) {
int lroll = chipL.readRollAngle(); // read roll angle of MPU6050, this is
// the input of the game.
int rroll = chipR.readRollAngle();
w.clear();
if (lroll < -30 && l.start.y > 0) {
l.moveup();
}
if (lroll > 30 && l.end.y < rheight) {
l.movedown();
}
if (rroll < -30 && r.start.y > 0) {
r.moveup();
}
if (rroll > 30 && r.end.y < rheight) {
r.movedown();
}
r.draw();
l.draw();
b.move();
if (b.end.x == (rwidth - (rwidth / 10) - 2) ||
b.end.x == (rwidth - (rwidth / 10) - 3)) { // Right Collision
if (b.start.y <= r.end.y && b.start.y >= r.start.y) {
b.change_speed_factor(-1, 1);
} else {
Lscore++; // Lose condition
hwlib::cout << Lscore << " - " << Rscore << hwlib::endl;
hwlib::wait_ms(500);
b.reset();
}
}
if (b.start.x == (rwidth / 10) + 1 ||
b.start.x == (rwidth / 10)) { // Left Collision
if (b.start.y <= l.end.y && b.start.y >= l.start.y) {
b.change_speed_factor(-1, 1);
} else {
Rscore++; // Lose condition
hwlib::cout << Lscore << " - " << Rscore << hwlib::endl;
hwlib::wait_ms(500);
b.reset();
}
}
if (b.start.y >= rheight - 1 ||
b.start.y <= 0) { // Bounce top/bottom of screen
b.change_speed_factor(1, -1);
}
w.flush();
}
}
| 29.322222 | 78 | 0.535809 | finnff |
e578239b4948fa914b39f0e674029a09d13b6d54 | 7,285 | cpp | C++ | src/engine/drawSys.cpp | karwler/BKGraph | 1b65f82d4c44e3982cf6cef775e88a16c857d6e3 | [
"WTFPL"
] | null | null | null | src/engine/drawSys.cpp | karwler/BKGraph | 1b65f82d4c44e3982cf6cef775e88a16c857d6e3 | [
"WTFPL"
] | null | null | null | src/engine/drawSys.cpp | karwler/BKGraph | 1b65f82d4c44e3982cf6cef775e88a16c857d6e3 | [
"WTFPL"
] | 2 | 2017-11-09T16:14:39.000Z | 2018-02-08T19:09:40.000Z | #include "world.h"
// FONT SET
FontSet::FontSet(const string& path) :
file(path)
{
// check if font can be loaded
TTF_Font* tmp = TTF_OpenFont(file.c_str(), Default::fontTestHeight);
if (!tmp)
throw "Couldn't open font " + file + '\n' + TTF_GetError();
// get approximate height scale factor
int size;
TTF_SizeUTF8(tmp, Default::fontTestString, nullptr, &size);
heightScale = float(Default::fontTestHeight) / float(size);
TTF_CloseFont(tmp);
}
FontSet::~FontSet() {
for (const pair<const int, TTF_Font*>& it : fonts)
TTF_CloseFont(it.second);
}
void FontSet::clear() {
for (const pair<const int, TTF_Font*>& it : fonts)
TTF_CloseFont(it.second);
fonts.clear();
}
TTF_Font* FontSet::addSize(int size) {
TTF_Font* font = TTF_OpenFont(file.c_str(), size);
if (font)
fonts.insert(make_pair(size, font));
return font;
}
TTF_Font* FontSet::getFont(int height) {
height = int(float(height) * heightScale);
return fonts.count(height) ? fonts.at(height) : addSize(height); // load font if it hasn't been loaded yet
}
int FontSet::length(const string& text, int height) {
int len = 0;
TTF_Font* font = getFont(height);
if (font)
TTF_SizeUTF8(font, text.c_str(), &len, nullptr);
return len;
}
// DRAW SYS
DrawSys::DrawSys(SDL_Window* window, int driverIndex) :
fontSet(Filer::findFont(World::winSys()->getSettings().font))
{
renderer = SDL_CreateRenderer(window, driverIndex, Default::rendererFlags);
if (!renderer)
throw "Couldn't create renderer:\n" + string(SDL_GetError());
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
}
DrawSys::~DrawSys() {
SDL_DestroyRenderer(renderer);
}
SDL_Rect DrawSys::viewport() const {
SDL_Rect view;
SDL_RenderGetViewport(renderer, &view);
return view;
}
SDL_Texture* DrawSys::renderText(const string& text, int height, vec2i& size) {
if (text.empty()) { // not possible to draw empty text
size = 0;
return nullptr;
}
SDL_Surface* surf = TTF_RenderUTF8_Blended(fontSet.getFont(height), text.c_str(), Default::colorText);
SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf);
size = vec2i(surf->w, surf->h);
SDL_FreeSurface(surf);
return tex;
}
void DrawSys::drawWidgets() {
SDL_SetRenderDrawColor(renderer, Default::colorBackground.r, Default::colorBackground.g, Default::colorBackground.b, Default::colorBackground.a);
SDL_RenderClear(renderer);
World::scene()->getLayout()->drawSelf(); // draw main widgets
if (World::scene()->getPopup()) { // draw popup if exists and dim main widgets
SDL_Rect view = viewport();
SDL_SetRenderDrawColor(renderer, Default::colorPopupDim.r, Default::colorPopupDim.g, Default::colorPopupDim.b, Default::colorPopupDim.a);
SDL_RenderFillRect(renderer, &view);
World::scene()->getPopup()->drawSelf();
}
if (World::scene()->getContext()) // draw context if exists
drawContext(World::scene()->getContext());
if (LineEdit* let = dynamic_cast<LineEdit*>(World::scene()->capture)) // draw caret if capturing LineEdit
drawRect(let->caretRect(), Default::colorLight);
SDL_RenderPresent(renderer);
}
void DrawSys::drawButton(Button* wgt) {
drawRect(overlapRect(wgt->rect(), wgt->parentFrame()), Default::colorNormal);
}
void DrawSys::drawCheckBox(CheckBox* wgt) {
SDL_Rect frame = wgt->parentFrame();
drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background
drawRect(overlapRect(wgt->boxRect(), frame), wgt->on ? Default::colorLight : Default::colorDark); // draw checkbox
}
void DrawSys::drawColorBox(ColorBox* wgt) {
SDL_Rect frame = wgt->parentFrame();
drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background
drawRect(overlapRect(wgt->boxRect(), frame), wgt->color); // draw colorbox
}
void DrawSys::drawSlider(Slider* wgt) {
SDL_Rect frame = wgt->parentFrame();
drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background
drawRect(overlapRect(wgt->barRect(), frame), Default::colorDark); // draw bar
drawRect(overlapRect(wgt->sliderRect(), frame), Default::colorLight); // draw slider
}
void DrawSys::drawLabel(Label* wgt) {
SDL_Rect rect = overlapRect(wgt->rect(), wgt->parentFrame());
drawRect(rect, Default::colorNormal); // draw background
if (wgt->tex) { // modify frame and draw text if exists
rect.x += Default::textOffset;
rect.w -= Default::textOffset * 2;
drawText(wgt->tex, wgt->textRect(), rect);
}
}
void DrawSys::drawGraphView(GraphView* wgt) {
vec2i pos = wgt->position();
vec2i siz = wgt->size();
int endy = pos.y + siz.y;
// draw lines
vec2i lstt = vec2i(dotToPix(vec2f(World::winSys()->getSettings().viewPos.x, 0.f), World::winSys()->getSettings().viewPos, World::winSys()->getSettings().viewSize, vec2f(siz))) + pos;
drawLine(lstt, vec2i(lstt.x + siz.x - 1, lstt.y), Default::colorGraph, {pos.x, pos.y, siz.x, siz.y});
lstt = vec2i(dotToPix(vec2f(0.f, World::winSys()->getSettings().viewPos.y), World::winSys()->getSettings().viewPos, World::winSys()->getSettings().viewSize, vec2f(siz))) + pos;
drawLine(lstt, vec2i(lstt.x, lstt.y + siz.y - 1), Default::colorGraph, {pos.x, pos.y, siz.x, siz.y});
// draw graphs
for (const Graph& it : wgt->getGraphs()) {
SDL_Color color = World::program()->getFunction(it.fid).color;
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
sizt start = 0;
bool lastIn = false;
for (sizt x=0; x<it.pixs.size(); x++) {
bool curIn = inRange(it.pixs[x].y, pos.y, endy);
if (curIn) {
if (!lastIn)
start = x;
} else if (lastIn)
SDL_RenderDrawLines(renderer, &it.pixs[start], int(x-start));
lastIn = curIn;
}
if (lastIn)
SDL_RenderDrawLines(renderer, &it.pixs[start], int(it.pixs.size()-start));
}
}
void DrawSys::drawScrollArea(ScrollArea* box) {
vec2t vis = box->visibleWidgets(); // get index interval of items on screen and draw children
for (sizt i=vis.l; i<vis.u; i++)
box->getWidget(i)->drawSelf();
drawRect(box->barRect(), Default::colorDark); // draw scroll bar
drawRect(box->sliderRect(), Default::colorLight); // draw scroll slider
}
void DrawSys::drawPopup(Popup* pop) {
drawRect(pop->rect(), Default::colorNormal); // draw background
for (Widget* it : pop->getWidgets()) // draw children
it->drawSelf();
}
void DrawSys::drawContext(Context* con) {
SDL_Rect rect = con->rect();
drawRect(rect, Default::colorLight); // draw background
const vector<ContextItem>& items = con->getItems();
for (sizt i=0; i<items.size(); i++) // draw items aka. text
drawText(items[i].tex, con->itemRect(i), rect);
}
void DrawSys::drawRect(const SDL_Rect& rect, SDL_Color color) {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(renderer, &rect);
}
void DrawSys::drawLine(vec2i pos, vec2i end, SDL_Color color, const SDL_Rect& frame) {
if (cropLine(pos, end, frame)) {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderDrawLine(renderer, pos.x, pos.y, end.x, end.y);
}
}
void DrawSys::drawText(SDL_Texture* tex, const SDL_Rect& rect, const SDL_Rect& frame) {
// crop destination rect and original texture rect
if (SDL_Rect dst; SDL_IntersectRect(&rect, &frame, &dst)) {
SDL_Rect src = {dst.x - rect.x, dst.y - rect.y, dst.w, dst.h};
SDL_RenderCopy(renderer, tex, &src, &dst);
}
}
| 33.883721 | 183 | 0.700069 | karwler |
e57c906c68ba77d31d2b02e65cc1fbd6aa245ee8 | 4,123 | cpp | C++ | solution/solutionthread.cpp | vitkorob/studentprojects | 3b071eabec33f9e27eec81eaf5df339276c039be | [
"MIT"
] | null | null | null | solution/solutionthread.cpp | vitkorob/studentprojects | 3b071eabec33f9e27eec81eaf5df339276c039be | [
"MIT"
] | null | null | null | solution/solutionthread.cpp | vitkorob/studentprojects | 3b071eabec33f9e27eec81eaf5df339276c039be | [
"MIT"
] | null | null | null | #include "solutionthread.h"
solutionThread::solutionThread()
{
metRKu = 1;
gam = 0.2;
g = 9.81;
L = 2;
del = 0.9;
p2 = 4;
eps = 0.0005;
x0 = 2;
v0 = 3;
t = 30;
step = 0.01;
}
double solutionThread::p(double y2)
{
return y2;
}
double solutionThread::q(double x2, double y2, double t2)
{
return ((-1) * gam * y2) - g * x2 / (L * (1 + del * cos(p2 * t2)));
}
void solutionThread::nextValueEuler(double *x, double *y, double t, double h)
{
*x += h * p(*y);
*y += h * q(*x, *y, t);
}
void solutionThread::nextValueRKutt(double *x, double *y, double t, double h)
{
double x1 = h * p(*y);
double y1 = h * q(*x, *y, t);
double x2 = h * p(*y + y1 * 0.5);
double y2 = h * q(*x + x1 * 0.5, *y + y1 * 0.5, t + h * 0.5);
double x3 = h * p(*y + y2 * 0.5);
double y3 = h * q(*x + x2 * 0.5, *y + y2 * 0.5, t + h * 0.5);
double x4 = h * p(*y + y3);
double y4 = h * q(*x + x3, *y + y3, t + h);
*x += (x1 + 2 * x2 + 2 * x3 + x4) / 6;
*y += (y1 + 2 * y2 + 2 * y3 + y4) / 6;
}
void solutionThread::run()
{
pnt_t.clear();
pnt_x.clear();
pnt_y.clear();
pnt_t.append(0);
pnt_x.append(x0);
pnt_y.append(v0);
double next_t0 = 0;
FILE *data = fopen("ivan-data.txt", "w");
fprintf(data, "%f\t%f\t%f\n", 0.0, x0, v0);
FILE *fileMetod = fopen("ivan-step.txt", "a");
double next_x0;
double next_y0;
double next_x1;
double next_y1;
double next_x2;
double next_y2;
double next_x3;
double next_y3;
double next_x_tmp = x0;
double next_y_tmp = v0;
if(metRKu)
{
while(next_t0 < t)
{
next_x0 = next_x1 = next_x2 = next_x_tmp;
next_y0 = next_y1 = next_y2 = next_y_tmp;
nextValueRKutt(&next_x0, &next_y0, next_t0, step);
nextValueRKutt(&next_x1, &next_y1, next_t0, 2 * step);
next_x3 = next_x0;
next_y3 = next_y0;
nextValueRKutt(&next_x3, &next_y3, next_t0 + step, step);
nextValueRKutt(&next_x2, &next_y2, next_t0, 0.5 * step);
nextValueRKutt(&next_x2, &next_y2, next_t0 + 0.5 * step, 0.5 * step);
if((fabs(next_x0 - next_x2) / 15 <= eps && fabs(next_x3 - next_x1) / 15 > eps) || next_y_tmp == 0)
{
pnt_t.append(next_t0 += step);
pnt_x.append(next_x_tmp = next_x0);
pnt_y.append(next_y_tmp = next_y0);
fprintf(data, "%f\t%f\t%f\n", next_t0, next_x0, next_y0);
}
else if(fabs(next_x3 - next_x1) / 15 < eps)
{
step *= 2;
}
else
{
step *= 0.5;
}
}
fprintf(fileMetod, "rkutt\t%.18lf\t%.18lf\n", eps, t / pnt_t.size());
fclose(fileMetod);
}
else
{
while(next_t0 < t)
{
next_x0 = next_x1 = next_x2 = next_x_tmp;
next_y0 = next_y1 = next_y2 = next_y_tmp;
nextValueEuler(&next_x0, &next_y0, next_t0, step);
nextValueEuler(&next_x1, &next_y1, next_t0, 2 * step);
next_x3 = next_x0;
next_y3 = next_y0;
nextValueEuler(&next_x3, &next_y3, next_t0 + step, step);
nextValueEuler(&next_x2, &next_y2, next_t0, 0.5 * step);
nextValueEuler(&next_x2, &next_y2, next_t0 + 0.5 * step, 0.5 * step);
if((fabs(next_x0 - next_x2) <= eps && fabs(next_x3 - next_x1) > eps) || next_y_tmp == 0)
{
pnt_t.append(next_t0 += step);
pnt_x.append(next_x_tmp = next_x0);
pnt_y.append(next_y_tmp = next_y0);
fprintf(data, "%f\t%f\t%f\n", next_t0, next_x0, next_y0);
}
else if(fabs(next_x3 - next_x1) < eps)
{
step *= 2;
}
else
{
step *= 0.5;
}
}
fprintf(fileMetod, "euler\t%.18lf\t%.18lf\n", eps, t / pnt_t.size());
fclose(fileMetod);
}
fclose(data);
}
| 25.140244 | 110 | 0.489207 | vitkorob |
e57eee5672315a1c7762eba6e21dd57c0a8e7435 | 128 | hpp | C++ | Vendor/GLM/glm/ext/vector_uint1.hpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | 2 | 2022-01-11T21:15:31.000Z | 2022-02-22T21:14:33.000Z | Vendor/GLM/glm/ext/vector_uint1.hpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | null | null | null | Vendor/GLM/glm/ext/vector_uint1.hpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:936046e1e48adf16a2daa297a69e3318537c55f39572a05efbae9aca1479cf89
size 711
| 32 | 75 | 0.882813 | wdrDarx |
e57fbaf38376bfb6b8788e60265427cd6c14091e | 3,882 | hpp | C++ | include/cynodelic/mulinum/detail/split_helpers.hpp | cynodelic/mulinum | fc7b9e750aadaede2cee8d840e65fa3832787764 | [
"BSL-1.0"
] | null | null | null | include/cynodelic/mulinum/detail/split_helpers.hpp | cynodelic/mulinum | fc7b9e750aadaede2cee8d840e65fa3832787764 | [
"BSL-1.0"
] | null | null | null | include/cynodelic/mulinum/detail/split_helpers.hpp | cynodelic/mulinum | fc7b9e750aadaede2cee8d840e65fa3832787764 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 Álvaro Ceballos
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
/**
* @file split_helpers.hpp
*
* @brief Helpers for the `split` metafunction.
*/
#ifndef CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
#define CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
#include <cstddef>
#include <cynodelic/mulinum/config.hpp>
#include <cynodelic/mulinum/if.hpp>
#include <cynodelic/mulinum/string.hpp>
#include <cynodelic/mulinum/concat.hpp>
#include <cynodelic/mulinum/make_from_tag.hpp>
namespace cynodelic { namespace mulinum {
namespace detail
{
/**
* @brief Helper for @ref split.
*/
template <char, typename>
struct split_remove_front_delims;
/**
* @brief Helper for @ref split.
*/
template <char Delim, char First_, char... Others_>
struct split_remove_front_delims<Delim, string<First_, Others_...>>
{
using type = if_<
(Delim == First_),
typename split_remove_front_delims<Delim, string<Others_...>>::type,
string<First_, Others_...>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, char Last_>
struct split_remove_front_delims<Delim, string<Last_>>
{
using type = if_<
(Delim == Last_),
string<>,
string<Last_>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char, std::size_t, typename, bool>
struct split_make_delims_unique;
/**
* @brief Helper for @ref split.
*/
template <char Delim, std::size_t N, char First_, char Second_>
struct split_make_delims_unique<Delim, N, string<First_, Second_>, true>
{
using type = if_<
(First_ == Delim) && (Second_ == Delim),
string<>,
string<First_>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, std::size_t N, char First_, char Second_, char... Others_>
struct split_make_delims_unique<Delim, N, string<First_, Second_, Others_...>, false>
{
using type = concat<
if_<
(First_ == Delim) && (Second_ == Delim),
string<>,
string<First_>
>,
typename split_make_delims_unique<Delim, N - 1, string<Second_, Others_...>, (N - 1) == 0>::type
>;
};
/**
* @brief Helper for @ref split.
*/
template <char, typename>
struct split_take_first_item;
/**
* @brief Helper for @ref split.
*/
template <char Delim, char First_, char... Others_>
struct split_take_first_item<Delim, string<First_, Others_...>>
{
using type = if_<
(First_ == Delim),
string<>,
concat<
string<First_>,
typename split_take_first_item<Delim, string<Others_...>>::type
>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, char Last_>
struct split_take_first_item<Delim, string<Last_>>
{
using type = if_<
Last_ == Delim,
string<>,
string<Last_>
>;
};
/**
* @brief Helper for @ref split.
*/
template <char Delim, typename StringT_, std::size_t From>
using split_take_item = typename detail::split_take_first_item<Delim, take_c<StringT_, From, StringT_::size - From>>::type;
/**
* @brief Helper for @ref split.
*/
template <typename TypeContainerTag, char Delim, typename StringT_, std::size_t Count, bool = (Count == StringT_::size)>
struct splitter
{
using type = concat<
make_from_tag<TypeContainerTag, split_take_item<Delim, StringT_, Count>>,
typename splitter<
TypeContainerTag,
Delim,
StringT_,
(Count + split_take_item<Delim, StringT_, Count>::size + 1)
>::type
>;
};
/**
* @brief Helper for @ref split.
*/
template <typename TypeContainerTag, char Delim, typename StringT_, std::size_t Count>
struct splitter<TypeContainerTag, Delim, StringT_, Count, true>
{
using type = make_from_tag<TypeContainerTag>;
};
} // end of "detail" namespace
}} // end of "cynodelic::mulinum" namespace
#endif // CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
| 21.687151 | 124 | 0.676455 | cynodelic |
e582a8d0fc49f20af9374fe9a7e4fda2278e60e7 | 129 | cc | C++ | tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:516879d2c1b04ff8b7ba32487c8446e3241805e4352f374533aa6756863b4cad
size 4366
| 32.25 | 75 | 0.883721 | initialz |
e5847e79f40e20540105d7d68c2b19de80dc5ceb | 4,115 | cpp | C++ | ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp | ufora/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571 | 2015-11-05T20:07:07.000Z | 2022-01-24T22:31:09.000Z | ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218 | 2015-11-05T20:37:55.000Z | 2021-05-30T03:53:50.000Z | ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40 | 2015-11-07T21:42:19.000Z | 2021-05-23T03:48:19.000Z | /***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#include "MutableVectorHandleCodegen.hpp"
#include "NativeLayoutType.hppml"
#include "../../Judgment/JudgmentOnValue.hppml"
#include "../../../core/SymbolExport.hpp"
#include "../../../core/Logging.hpp"
#include "../../Native/NativeCode.hppml"
#include "../../Native/NativeTypeFor.hpp"
#include "../../Native/NativeExpressionBuilder.hppml"
#include "../../Native/TypedNativeLibraryFunction.hpp"
#include "DestructorsAndConstructors.hppml"
using TypedFora::Abi::MutableVectorHandle;
NativeType NativeTypeForImpl<MutableVectorHandle>::get()
{
return
NativeType::Composite("mRefcount", NativeType::uword()) +
NativeType::Composite("mSize", NativeType::uword()) +
NativeType::Composite("mRawDataPtr", NativeType::uint8().ptr()) +
NativeType::Composite("mOwningMemoryPool", NativeType::Nothing().ptr()) +
NativeType::Composite("mElementJOV", NativeTypeFor<JudgmentOnValue>::get()) +
NativeType::Composite("mVectorHash", NativeTypeFor<hash_type>::get())
;
}
extern "C" {
BSA_DLLEXPORT
void FORA_clib_incrementMutableVectorHandleRefcount(MutableVectorHandle* handle)
{
handle->incrementRefcount();
}
BSA_DLLEXPORT
uint8_t FORA_clib_decrementMutableVectorHandleRefcount(MutableVectorHandle* handle)
{
return handle->decrementRefcount();
}
}
namespace TypedFora {
namespace Abi {
namespace MutableVectorHandleCodegen {
NativeExpression sizeExpression(
const NativeExpression& arrayPtrE
)
{
lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr());
return arrayPtrE["mSize"].load();
}
NativeExpression incrementRefcountExpr(
const NativeExpression& arrayPtrE
)
{
lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr());
return makeTypedNativeLibraryFunction(
&FORA_clib_incrementMutableVectorHandleRefcount
)(arrayPtrE).getExpression()
;
}
NativeExpression decrementRefcountExpr(
const NativeExpression& arrayPtrE
)
{
lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr());
return makeTypedNativeLibraryFunction(
&FORA_clib_decrementMutableVectorHandleRefcount
)(arrayPtrE).getExpression()
;
}
NativeExpression basePointerExpressionAsRawPtr(
const NativeExpression& arrayPtrE
)
{
return
arrayPtrE["mRawDataPtr"]
.load()
;
}
NativeExpression getItemExpr(
const NativeExpression& arrayPtrE,
const NativeExpression& indexE,
const JudgmentOnValue& elementJov
)
{
if (elementJov.constant())
return NativeExpression();
return TypedFora::Abi::duplicate(
elementJov,
arrayPtrE["mRawDataPtr"]
.load()
.cast(nativeLayoutType(elementJov).ptr(), true)
[indexE].load()
);
}
NativeExpression setItemExpr(
const NativeExpression& arrayPtrE,
const NativeExpression& indexE,
const NativeExpression& dataE,
const JudgmentOnValue& elementJov
)
{
NativeExpressionBuilder builder;
if (elementJov.constant())
return NativeExpression();
NativeExpression eltPtr = builder.add(
arrayPtrE["mRawDataPtr"].load()
.cast(nativeLayoutType(elementJov).ptr(), false)
[indexE]
);
NativeExpression duplicatedVal =
builder.add(
TypedFora::Abi::duplicate(elementJov, dataE)
);
builder.add(
TypedFora::Abi::destroy(elementJov, eltPtr.load())
);
builder.add(
eltPtr.store(duplicatedVal)
);
return builder(NativeExpression());
}
}
}
}
| 25.401235 | 83 | 0.710814 | ufora |
e588ba30a9a4c0dc44a82cb38413c711dd3b5fc2 | 14,602 | cpp | C++ | src/qt-console/tray-monitor/runjob.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | src/qt-console/tray-monitor/runjob.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | src/qt-console/tray-monitor/runjob.cpp | tech-niche-biz/bacula-9.4.4 | 5e74458b612354f6838652dac9ddff94be1bbce6 | [
"BSD-2-Clause"
] | null | null | null | /*
Bacula(R) - The Network Backup Solution
Copyright (C) 2000-2018 Kern Sibbald
The original author of Bacula is Kern Sibbald, with contributions
from many others, a complete list can be found in the file AUTHORS.
You may use this file and others of this release according to the
license defined in the LICENSE file, which includes the Affero General
Public License, v3.0 ("AGPLv3") and some additional permissions and
terms pursuant to its AGPLv3 Section 7.
This notice must be preserved when any source code is
conveyed and/or propagated.
Bacula(R) is a registered trademark of Kern Sibbald.
*/
#include "runjob.h"
#include <QMessageBox>
static void fillcombo(QComboBox *cb, alist *lst, bool addempty=true)
{
if (lst && lst->size() > 0) {
QStringList list;
char *str;
if (addempty) {
list << QString("");
}
foreach_alist(str, lst) {
list << QString(str);
}
cb->addItems(list);
} else {
cb->setEnabled(false);
}
}
RunJob::RunJob(RESMON *r): QDialog(), res(r), tabAdvanced(NULL)
{
int nbjob;
if (res->jobs->size() == 0) {
QMessageBox msgBox;
msgBox.setText(_("This restricted console does not have access to Backup jobs"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
deleteLater();
return;
}
ui.setupUi(this);
setModal(true);
connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(close_cb()));
connect(ui.okButton, SIGNAL(clicked()), this, SLOT(runjob()));
connect(ui.jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(jobChanged(int)));
connect(ui.levelCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(levelChanged(int)));
ui.dateTimeEdit->setMinimumDate(QDate::currentDate());
ui.dateTimeEdit->setMaximumDate(QDate::currentDate().addDays(7));
ui.dateTimeEdit->setDate(QDate::currentDate());
ui.dateTimeEdit->setTime(QTime::currentTime());
ui.boxEstimate->setVisible(false);
res->mutex->lock();
nbjob = res->jobs->size();
fillcombo(ui.jobCombo, res->jobs, (nbjob > 1));
fillcombo(ui.clientCombo, res->clients);
fillcombo(ui.filesetCombo,res->filesets);
fillcombo(ui.poolCombo, res->pools);
fillcombo(ui.storageCombo,res->storages);
fillcombo(ui.catalogCombo,res->catalogs);
res->mutex->unlock();
connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChange(int)));
QStringList levels;
levels << "" << "Incremental" << "Differential" << "Full";
ui.levelCombo->addItems(levels);
MONITOR *m = (MONITOR*) GetNextRes(R_MONITOR, NULL);
if (!m->display_advanced_options) {
tabAdvanced = ui.tabWidget->widget(1);
ui.tabWidget->removeTab(1);
}
show();
}
void RunJob::tabChange(int idx)
{
QString q = ui.tabWidget->tabText(idx);
if (q.contains("Advanced")) {
if (ui.jobCombo->currentText().compare("") == 0) {
pm_strcpy(curjob, "");
ui.tab2->setEnabled(false);
} else if (ui.jobCombo->currentText().compare(curjob.c_str()) != 0) {
task *t = new task();
char *job = bstrdup(ui.jobCombo->currentText().toUtf8().data());
pm_strcpy(curjob, job); // Keep the job name to not refresh the Advanced tab the next time
Dmsg1(10, "get defaults for %s\n", job);
res->mutex->lock();
bfree_and_null(res->defaults.job);
res->defaults.job = job;
res->mutex->unlock();
ui.tab2->setEnabled(false);
connect(t, SIGNAL(done(task *)), this, SLOT(fill_defaults(task *)), Qt::QueuedConnection);
t->init(res, TASK_DEFAULTS);
res->wrk->queue(t);
}
}
}
void RunJob::runjob()
{
POOL_MEM tmp;
char *p;
p = ui.jobCombo->currentText().toUtf8().data();
if (!p || !*p) {
QMessageBox msgBox;
msgBox.setText(_("Nothing selected"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
return;
}
Mmsg(command, "run job=\"%s\" yes", p);
if (strcmp(p, NPRTB(res->defaults.job)) == 0 || strcmp("", NPRTB(res->defaults.job)) == 0) {
p = ui.storageCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.storage)) != 0) {
Mmsg(tmp, " storage=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.clientCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.client)) != 0) {
Mmsg(tmp, " client=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.levelCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.level)) != 0) {
Mmsg(tmp, " level=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.poolCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.pool)) != 0) {
Mmsg(tmp, " pool=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
p = ui.filesetCombo->currentText().toUtf8().data();
if (p && *p && strcmp(p, NPRTB(res->defaults.fileset)) != 0) {
Mmsg(tmp, " fileset=\"%s\"", p);
pm_strcat(command, tmp.c_str());
}
if (res->defaults.priority && res->defaults.priority != ui.prioritySpin->value()) {
Mmsg(tmp, " priority=\"%d\"", res->defaults.priority);
pm_strcat(command, tmp.c_str());
}
}
QDate dnow = QDate::currentDate();
QTime tnow = QTime::currentTime();
QDate dval = ui.dateTimeEdit->date();
QTime tval = ui.dateTimeEdit->time();
if (dval > dnow || (dval == dnow && tval > tnow)) {
Mmsg(tmp, " when=\"%s %s\"", dval.toString("yyyy-MM-dd").toUtf8().data(), tval.toString("hh:mm:00").toUtf8().data());
pm_strcat(command, tmp.c_str());
}
if (res->type == R_CLIENT) {
pm_strcat(command, " fdcalled=1");
}
// Build the command and run it!
task *t = new task();
t->init(res, TASK_RUN);
connect(t, SIGNAL(done(task *)), this, SLOT(jobStarted(task *)), Qt::QueuedConnection);
t->arg = command.c_str();
res->wrk->queue(t);
}
void RunJob::jobStarted(task *t)
{
Dmsg1(10, "%s\n", command.c_str());
Dmsg1(10, "-> jobid=%d\n", t->result.i);
deleteLater();
delete t;
}
void RunJob::close_cb(task *t)
{
deleteLater();
delete t;
}
void RunJob::close_cb()
{
task *t = new task();
connect(t, SIGNAL(done(task *)), this, SLOT(close_cb(task *)), Qt::QueuedConnection);
t->init(res, TASK_DISCONNECT);
res->wrk->queue(t);
}
void RunJob::jobChanged(int)
{
char *p;
ui.levelCombo->setCurrentIndex(0);
ui.storageCombo->setCurrentIndex(0);
ui.filesetCombo->setCurrentIndex(0);
ui.clientCombo->setCurrentIndex(0);
ui.storageCombo->setCurrentIndex(0);
ui.poolCombo->setCurrentIndex(0);
ui.catalogCombo->setCurrentIndex(0);
p = ui.jobCombo->currentText().toUtf8().data();
if (p && *p) {
task *t = new task();
t->init(res, TASK_INFO);
pm_strcpy(info, p);
connect(t, SIGNAL(done(task *)), this, SLOT(jobInfo(task *)), Qt::QueuedConnection);
t->arg = info.c_str(); // Jobname
t->arg2 = NULL; // Level
res->wrk->queue(t);
}
}
void RunJob::levelChanged(int)
{
char *p;
p = ui.jobCombo->currentText().toUtf8().data();
if (p && *p) {
pm_strcpy(info, p);
p = ui.levelCombo->currentText().toUtf8().data();
if (p && *p) {
task *t = new task();
pm_strcpy(level, p);
connect(t, SIGNAL(done(task *)), this, SLOT(jobInfo(task *)), Qt::QueuedConnection);
t->init(res, TASK_INFO);
t->arg = info.c_str(); // Jobname
t->arg2 = level.c_str(); // Level
res->wrk->queue(t);
}
}
}
void RunJob::jobInfo(task *t)
{
char ed1[50];
res->mutex->lock();
if (res->infos.CorrNbJob == 0) {
ui.boxEstimate->setVisible(false);
} else {
QString t;
edit_uint64_with_suffix(res->infos.JobBytes, ed1);
strncat(ed1, "B", sizeof(ed1));
ui.labelJobBytes->setText(QString(ed1));
ui.labelJobFiles->setText(QString(edit_uint64_with_commas(res->infos.JobFiles, ed1)));
ui.labelJobLevel->setText(QString(job_level_to_str(res->infos.JobLevel)));
t = tr("Computed over %1 job%2, the correlation is %3/100.").arg(res->infos.CorrNbJob).arg(res->infos.CorrNbJob>1?"s":"").arg(res->infos.CorrJobBytes);
ui.labelJobBytes_2->setToolTip(t);
t = tr("Computed over %1 job%2, The correlation is %3/100.").arg(res->infos.CorrNbJob).arg(res->infos.CorrNbJob>1?"s":"").arg(res->infos.CorrJobFiles);
ui.labelJobFiles_2->setToolTip(t);
ui.boxEstimate->setVisible(true);
}
res->mutex->unlock();
t->deleteLater();
}
static void set_combo(QComboBox *dest, char *str)
{
if (str) {
int idx = dest->findText(QString(str), Qt::MatchExactly);
if (idx >= 0) {
dest->setCurrentIndex(idx);
}
}
}
void RunJob::fill_defaults(task *t)
{
if (t->status == true) {
res->mutex->lock();
set_combo(ui.levelCombo, res->defaults.level);
set_combo(ui.filesetCombo, res->defaults.fileset);
set_combo(ui.clientCombo, res->defaults.client);
set_combo(ui.storageCombo, res->defaults.storage);
set_combo(ui.poolCombo, res->defaults.pool);
set_combo(ui.catalogCombo, res->defaults.catalog);
res->mutex->unlock();
}
ui.tab2->setEnabled(true);
t->deleteLater();
}
RunJob::~RunJob()
{
Dmsg0(10, "~RunJob()\n");
if (tabAdvanced) {
delete tabAdvanced;
}
}
void TSched::init(const char *cmd_dir)
{
bool started = (timer >= 0);
if (started) {
stop();
}
bfree_and_null(command_dir);
command_dir = bstrdup(cmd_dir);
if (started) {
start();
}
}
TSched::TSched() {
timer = -1;
command_dir = NULL;
}
TSched::~TSched() {
if (timer >= 0) {
stop();
}
bfree_and_null(command_dir);
}
#include <dirent.h>
int breaddir(DIR *dirp, POOLMEM *&dname);
bool TSched::read_command_file(const char *file, alist *lst, btime_t mtime)
{
POOLMEM *line;
bool ret=false;
char *p;
TSchedJob *s;
Dmsg1(50, "open command file %s\n", file);
FILE *fp = fopen(file, "r");
if (!fp) {
return false;
}
line = get_pool_memory(PM_FNAME);
/* Get the first line, client/component:command */
while (bfgets(line, fp) != NULL) {
strip_trailing_junk(line);
Dmsg1(50, "%s\n", line);
if (line[0] == '#') {
continue;
}
if ((p = strchr(line, ':')) != NULL) {
*p=0;
s = new TSchedJob(line, p+1, mtime);
lst->append(s);
ret = true;
}
}
free_pool_memory(line);
fclose(fp);
return ret;
}
#include "lib/plugins.h"
#include "lib/cmd_parser.h"
void TSched::timerEvent(QTimerEvent *event)
{
Q_UNUSED(event)
POOL_MEM tmp, command;
TSchedJob *j;
alist lst(10, not_owned_by_alist);
arg_parser parser;
int i;
task *t;
RESMON *res;
scan_for_commands(&lst);
foreach_alist(j, (&lst)) {
if (parser.parse_cmd(j->command) == bRC_OK) {
if ((i = parser.find_arg_with_value("job")) > 0) {
QMessageBox msgbox;
foreach_res(res, R_CLIENT) {
if (strcmp(res->hdr.name, j->component) == 0) {
break;
}
}
if (!res) {
foreach_res(res, R_DIRECTOR) {
if (strcmp(res->hdr.name, j->component) == 0) {
break;
}
}
}
if (!res) {
msgbox.setIcon(QMessageBox::Information);
msgbox.setText(QString("Unable to find the component \"%1\" to run the job \"%2\".").arg(j->component, j->command));
msgbox.setStandardButtons(QMessageBox::Ignore);
} else {
msgbox.setIcon(QMessageBox::Information);
msgbox.setText(QString("The job \"%1\" will start automatically in few seconds...").arg(parser.argv[i]));
msgbox.setStandardButtons(QMessageBox::Ok | QMessageBox::Ignore);
msgbox.setDefaultButton(QMessageBox::Ok);
msgbox.button(QMessageBox::Ok)->animateClick(6000);
}
switch(msgbox.exec()) {
case QMessageBox::Ok:
Mmsg(command, "%s yes", j->command);
if (res->type == R_CLIENT) {
pm_strcat(command, " fdcalled=1");
}
// Build the command and run it!
t = new task();
t->init(res, TASK_RUN);
connect(t, SIGNAL(done(task *)), this, SLOT(jobStarted(task *)), Qt::QueuedConnection);
t->arg = command.c_str();
res->wrk->queue(t);
break;
case QMessageBox::Cancel:
case QMessageBox::Ignore:
break;
}
}
}
delete j;
}
}
void TSched::jobStarted(task *t)
{
Dmsg1(10, "-> jobid=%d\n", t->result.i);
t->deleteLater();
}
bool TSched::scan_for_commands(alist *commands)
{
int name_max, len;
DIR* dp = NULL;
POOL_MEM fname(PM_FNAME), fname2(PM_FNAME);
POOL_MEM dir_entry;
bool ret=false, found=false;
struct stat statp;
name_max = pathconf(".", _PC_NAME_MAX);
if (name_max < 1024) {
name_max = 1024;
}
if (!(dp = opendir(command_dir))) {
berrno be;
Dmsg2(0, "Failed to open directory %s: ERR=%s\n",
command_dir, be.bstrerror());
goto bail_out;
}
for ( ;; ) {
if (breaddir(dp, dir_entry.addr()) != 0) {
if (!found) {
goto bail_out;
}
break;
}
if (strcmp(dir_entry.c_str(), ".") == 0 ||
strcmp(dir_entry.c_str(), "..") == 0) {
continue;
}
len = strlen(dir_entry.c_str());
if (len <= 5) {
continue;
}
if (strcmp(dir_entry.c_str() + len - 5, ".bcmd") != 0) {
continue;
}
Mmsg(fname, "%s/%s", command_dir, dir_entry.c_str());
if (lstat(fname.c_str(), &statp) != 0 || !S_ISREG(statp.st_mode)) {
continue; /* ignore directories & special files */
}
if (read_command_file(fname.c_str(), commands, statp.st_mtime)) {
Mmsg(fname2, "%s.ok", fname.c_str());
unlink(fname2.c_str());
rename(fname.c_str(), fname2.c_str()); // TODO: We should probably unlink the file
}
}
bail_out:
if (dp) {
closedir(dp);
}
return ret;
}
| 28.631373 | 157 | 0.571566 | tech-niche-biz |
e58c9e92abb9149e44fdef1940720e0adde09a69 | 4,425 | hpp | C++ | ramus/patch/ips.hpp | qwertymodo/Mercurial-Magic | e5ce65510d12ac04e7ebea4ce11d200276baa141 | [
"ISC"
] | 2 | 2019-01-20T13:05:10.000Z | 2021-03-31T14:09:03.000Z | ramus/patch/ips.hpp | qwertymodo/Mercurial-Magic | e5ce65510d12ac04e7ebea4ce11d200276baa141 | [
"ISC"
] | null | null | null | ramus/patch/ips.hpp | qwertymodo/Mercurial-Magic | e5ce65510d12ac04e7ebea4ce11d200276baa141 | [
"ISC"
] | 1 | 2018-10-12T02:47:57.000Z | 2018-10-12T02:47:57.000Z | #pragma once
#include <nall/file.hpp>
#include <nall/filemap.hpp>
#include <nall/stdint.hpp>
#include <nall/string.hpp>
namespace ramus {
struct ipspatch {
inline auto modify(const uint8_t* data, uint size) -> bool;
inline auto source(const uint8_t* data, uint size) -> void;
inline auto target(uint8_t* data, uint size) -> void;
inline auto modify(const string& filename) -> bool;
inline auto source(const string& filename) -> bool;
inline auto target(const string& filename) -> bool;
inline auto size() const -> uint;
enum result : uint {
unknown,
success,
patch_too_small,
patch_invalid_header,
target_too_small,
};
inline auto apply() -> result;
protected:
filemap modifyFile;
const uint8_t* modifyData;
uint modifySize;
filemap sourceFile;
const uint8_t* sourceData;
uint sourceSize;
filemap targetFile;
uint8_t* targetData;
uint targetSize;
uint modifyTargetSize;
bool truncate;
};
auto ipspatch::modify(const uint8_t* data, uint size) -> bool {
if(size < 8) return false;
modifyData = data;
modifySize = size;
uint offset = 5;
auto read8 = [&]() -> uint8_t {
uint8_t data = modifyData[offset++];
return data;
};
auto read16 = [&]() -> uint16_t {
return read8() << 8 | read8();
};
auto read24 = [&]() -> uint32_t {
return read8() << 16 | read16();
};
uint blockAddr, blockSize, rleSize;
uint maxBlockAddr = 0;
modifyTargetSize = 0;
while(offset < modifySize) {
blockAddr = read24();
if(blockAddr == 0x454f46) break; //"EOF"
maxBlockAddr = max(maxBlockAddr, blockAddr);
blockSize = read16();
if(blockSize == 0) { //RLE
rleSize = read16();
modifyTargetSize = max(modifyTargetSize, blockAddr + rleSize);
offset++;
} else {
modifyTargetSize = max(modifyTargetSize, blockAddr + blockSize);
offset += blockSize;
}
}
if(size - offset != 0 && size - offset != 3) return false;
truncate = size - offset == 3;
if(truncate) modifyTargetSize = read24();
return true;
}
auto ipspatch::source(const uint8_t* data, uint size) -> void {
sourceData = data;
sourceSize = size;
if(!truncate) modifyTargetSize = max(modifyTargetSize, sourceSize);
}
auto ipspatch::target(uint8_t* data, uint size) -> void {
targetData = data;
targetSize = size;
}
auto ipspatch::modify(const string& filename) -> bool {
if(modifyFile.open(filename, filemap::mode::read) == false) return false;
return modify(modifyFile.data(), modifyFile.size());
}
auto ipspatch::source(const string& filename) -> bool {
if(sourceFile.open(filename, filemap::mode::read) == false) return false;
source(sourceFile.data(), sourceFile.size());
return true;
}
auto ipspatch::target(const string& filename) -> bool {
file fp;
if(fp.open(filename, file::mode::write) == false) return false;
fp.truncate(modifyTargetSize);
fp.close();
if(targetFile.open(filename, filemap::mode::readwrite) == false) return false;
target(targetFile.data(), targetFile.size());
return true;
}
auto ipspatch::size() const -> uint {
return modifyTargetSize;
}
auto ipspatch::apply() -> result {
if(modifySize < 8) return result::patch_too_small;
uint modifyOffset = 0, sourceRelativeOffset = 0, targetRelativeOffset = 0;
auto read8 = [&]() -> uint8_t {
uint8_t data = modifyData[modifyOffset++];
return data;
};
auto read16 = [&]() -> uint16_t {
return read8() << 8 | read8();
};
auto read24 = [&]() -> uint32_t {
return read8() << 16 | read16();
};
if(read8() != 'P') return result::patch_invalid_header;
if(read8() != 'A') return result::patch_invalid_header;
if(read8() != 'T') return result::patch_invalid_header;
if(read8() != 'C') return result::patch_invalid_header;
if(read8() != 'H') return result::patch_invalid_header;
if(modifyTargetSize > targetSize) return result::target_too_small;
memory::copy(targetData, sourceData, sourceSize);
uint blockAddr, blockSize, rleSize;
while(modifyOffset < modifySize) {
blockAddr = read24();
if(blockAddr == 0x454f46) break; //"EOF"
blockSize = read16();
if(blockSize == 0) { //RLE
rleSize = read16();
memory::fill(targetData + blockAddr, rleSize, read8());
} else {
memory::copy(targetData + blockAddr, modifyData + modifyOffset, blockSize);
modifyOffset += blockSize;
}
}
return result::success;
}
}
| 25.726744 | 81 | 0.660339 | qwertymodo |
e5916831f922f5efaa3a87ce01db382c07a90c38 | 2,472 | hpp | C++ | Assignments/P01/Menu.hpp | Landon-Brown1/2143-OOP-Brown | fded2b021b588bced3ba2a5c67e8e29694d42b2e | [
"MIT"
] | null | null | null | Assignments/P01/Menu.hpp | Landon-Brown1/2143-OOP-Brown | fded2b021b588bced3ba2a5c67e8e29694d42b2e | [
"MIT"
] | null | null | null | Assignments/P01/Menu.hpp | Landon-Brown1/2143-OOP-Brown | fded2b021b588bced3ba2a5c67e8e29694d42b2e | [
"MIT"
] | null | null | null | /*
* AUTHOR: Landon Brown
* FILE TITLE: Menu.hpp
* FILE DESCRIPTION: Menu for the beginning of the game
* DUE DATE: TBD
* DATE CREATED: 03/26/2020
*/
#include <iostream>
#include <string>
using namespace std;
struct Menu{
Menu(){
}
void printIntro(){
cout << endl << " @@----------------------------------------------------@@ " << endl
<< " @@ Welcome to Pokemon: Brown Version! @@ " << endl
<< " @@ If you would like to play, please press 'y'. @@ " << endl
<< "(( ))" << endl
<< " @@ @@ " << endl
<< " @@ @@ " << endl
<< " @@----------------------------------------------------@@ " << endl;
}
void firstSelect(){
cout << endl << " @@----------------------------------------------------@@ " << endl
<< " @@ Player One, please select your Pokemon by typing @@ " << endl
<< " @@ The respective Pokedex number of each Pokemon @@ " << endl
<< "(( you would like in your party (up to 6). The first ))" << endl
<< " @@ Pokemon you choose will be the first in your @@ " << endl
<< " @@ lineup to be sent to battle! @@ " << endl
<< " @@----------------------------------------------------@@ " << endl;
}
void secondSelect(){
cout << endl << " @@----------------------------------------------------@@ " << endl
<< " @@ @@ " << endl
<< " @@ @@ " << endl
<< "(( ))" << endl
<< " @@ @@ " << endl
<< " @@ @@ " << endl
<< " @@----------------------------------------------------@@ " << endl;
}
}; | 51.5 | 101 | 0.222492 | Landon-Brown1 |
e59fe0557fffaea876c7d5aecde27a3afe0f5c40 | 1,034 | cpp | C++ | codeforces/N - Egg Drop/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/N - Egg Drop/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/N - Egg Drop/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: JU_AAA: prdx9_abir, aniks2645, kzvd4729 created: Sep/15/2017 22:21
* solution_verdict: Accepted language: GNU C++14
* run_time: 15 ms memory_used: 0 KB
* problem: https://codeforces.com/gym/100819/problem/N
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
long n,k,x;
string s;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
long sf=1,br=k;
for(long i=1; i<=n; i++)
{
cin>>x>>s;
if(s=="SAFE")
{
sf=max(sf,x);
}
if(s=="BROKEN")
{
br=min(br,x);
}
}
cout<<sf+1<<" ";
cout<<br-1<<endl;
return 0;
} | 30.411765 | 111 | 0.352998 | kzvd4729 |
e5a9272774f3c2af98b49b6bc3803df1d49c988e | 3,815 | cpp | C++ | src/renderEffects/auraCompositing.cpp | mfirmin/xray-vision | c40fc300d95d55c15f0dffa484b7123eb69238b5 | [
"MIT"
] | 1 | 2021-09-13T20:22:29.000Z | 2021-09-13T20:22:29.000Z | src/renderEffects/auraCompositing.cpp | mfirmin/xray-vision | c40fc300d95d55c15f0dffa484b7123eb69238b5 | [
"MIT"
] | null | null | null | src/renderEffects/auraCompositing.cpp | mfirmin/xray-vision | c40fc300d95d55c15f0dffa484b7123eb69238b5 | [
"MIT"
] | 1 | 2021-09-13T20:22:31.000Z | 2021-09-13T20:22:31.000Z | #include "auraCompositing.hpp"
#include "gl/shaderUtils.hpp"
#include "light/light.hpp"
#include <array>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <string>
#include <sstream>
AuraCompositingEffect::AuraCompositingEffect(int w, int h) :
width(w), height(h)
{
}
void AuraCompositingEffect::initialize() {
createDebugProgram();
createProgram();
createArrayObjects();
}
AuraCompositingEffect::~AuraCompositingEffect() {
// TODO: Free buffers
}
void AuraCompositingEffect::createArrayObjects() {
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vertexBuffer);
glGenBuffers(1, &uvBuffer);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// NDC Coords
std::vector<float> vertices = {
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f
};
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GL_FLOAT), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvBuffer);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
std::vector<float> uvs = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f
};
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(GL_FLOAT), uvs.data(), GL_STATIC_DRAW);
}
void AuraCompositingEffect::createDebugProgram() {
std::string vertexShaderSource = R"(
#version 330
layout(location = 0) in vec2 position;
layout(location = 1) in vec2 uv;
out vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 0.0, 1.0);
}
)";
std::string fragmentShaderSource = R"(
#version 330
uniform sampler2D input;
in vec2 vUv;
out vec4 fragColor;
void main() {
vec3 color = texture(input, vUv).rgb;
color = color + vec3(1.0) * 0.5;
fragColor = vec4(color, 1.0);
}
)";
debugProgram = ShaderUtils::compile(vertexShaderSource, fragmentShaderSource);
}
void AuraCompositingEffect::createProgram() {
std::string vertexShaderSource = R"(
#version 330
layout(location = 0) in vec2 position;
layout(location = 1) in vec2 uv;
out vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 0.0, 1.0);
}
)";
std::string fragmentShaderSource = R"(
#version 330
uniform mat4 viewMatrix;
uniform sampler2D scene;
uniform sampler2D aura;
in vec2 vUv;
out vec4 fragColor;
void main() {
vec4 sceneColor = texture(scene, vUv);
vec4 auraColor = texture(aura, vUv);
fragColor = vec4(mix(sceneColor.rgb, auraColor.rgb, auraColor.a), 1.0);
}
)";
program = ShaderUtils::compile(vertexShaderSource, fragmentShaderSource);
}
void AuraCompositingEffect::render(GLuint sceneTexture, GLuint auraTexture) {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.0, 0.0, 0.0, 1.0);
// Clear it
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// render the screen object to it
glBindVertexArray(vao);
auto prog = program;
// use the debug program from the deferred target (just render 1 property)
glUseProgram(prog);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, sceneTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, auraTexture);
glUniform1i(glGetUniformLocation(prog, "scene"), 0);
glUniform1i(glGetUniformLocation(prog, "aura"), 1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glUseProgram(0);
}
| 23.404908 | 103 | 0.627785 | mfirmin |
e5b2c5518f46c1344445a67cd64dc67eb029a489 | 5,117 | cpp | C++ | test/block.cpp | MaskRay/asteria | 56a9251f5bb80b92e5aff25eac145f8cd2495096 | [
"BSD-3-Clause"
] | null | null | null | test/block.cpp | MaskRay/asteria | 56a9251f5bb80b92e5aff25eac145f8cd2495096 | [
"BSD-3-Clause"
] | null | null | null | test/block.cpp | MaskRay/asteria | 56a9251f5bb80b92e5aff25eac145f8cd2495096 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of Asteria.
// Copyleft 2018, LH_Mouse. All wrongs reserved.
#include "_test_init.hpp"
#include "../asteria/src/block.hpp"
#include "../asteria/src/xpnode.hpp"
#include "../asteria/src/statement.hpp"
#include "../asteria/src/global_context.hpp"
#include "../asteria/src/executive_context.hpp"
using namespace Asteria;
int main()
{
Vector<Statement> text;
// var res = 0;
Vector<Xpnode> expr;
expr.emplace_back(Xpnode::S_literal { D_integer(0) });
text.emplace_back(Statement::S_var_def { String::shallow("res"), false, std::move(expr) });
// const data = [ 1, 2, 3, 2 * 5 ];
expr.clear();
expr.emplace_back(Xpnode::S_literal { D_integer(1) });
expr.emplace_back(Xpnode::S_literal { D_integer(2) });
expr.emplace_back(Xpnode::S_literal { D_integer(3) });
expr.emplace_back(Xpnode::S_literal { D_integer(2) });
expr.emplace_back(Xpnode::S_literal { D_integer(5) });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_mul, false });
expr.emplace_back(Xpnode::S_unnamed_array { 4 });
text.emplace_back(Statement::S_var_def { String::shallow("data"), true, std::move(expr) });
// for(each k, v in data) {
// res += k * v;
// }
Vector<Xpnode> range;
range.emplace_back(Xpnode::S_named_reference { String::shallow("data") });
expr.clear();
expr.emplace_back(Xpnode::S_named_reference { String::shallow("res") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("k") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("v") });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_mul, false });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_add, true });
Vector<Statement> body;
body.emplace_back(Statement::S_expr { std::move(expr) });
text.emplace_back(Statement::S_for_each { String::shallow("k"), String::shallow("v"), std::move(range), std::move(body) });
// for(var j = 0; j <= 3; ++j) {
// res += data[j];
// if(data[j] == 2) {
// break;
// }
// }
body.clear();
expr.clear();
expr.emplace_back(Xpnode::S_named_reference { String::shallow("res") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("data") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
expr.emplace_back(Xpnode::S_subscript { String::shallow("") });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_add, true });
body.emplace_back(Statement::S_expr { std::move(expr) });
expr.clear();
expr.emplace_back(Xpnode::S_named_reference { String::shallow("data") });
expr.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
expr.emplace_back(Xpnode::S_subscript { String::shallow("") });
expr.emplace_back(Xpnode::S_literal { D_integer(2) });
expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_cmp_eq, false });
Vector<Statement> branch_true;
branch_true.emplace_back(Statement::S_break { Statement::target_unspec });
body.emplace_back(Statement::S_if { std::move(expr), std::move(branch_true), Block() });
expr.clear();
expr.emplace_back(Xpnode::S_literal { D_integer(0) });
Vector<Statement> init;
init.emplace_back(Statement::S_var_def { String::shallow("j"), false, std::move(expr) });
Vector<Xpnode> cond;
cond.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
cond.emplace_back(Xpnode::S_literal { D_integer(3) });
cond.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_cmp_lte, false });
Vector<Xpnode> step;
step.emplace_back(Xpnode::S_named_reference { String::shallow("j") });
step.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_prefix_inc, false });
text.emplace_back(Statement::S_for { std::move(init), std::move(cond), std::move(step), std::move(body) });
auto block = Block(std::move(text));
Global_context global;
Executive_context ctx;
Reference ref;
auto status = block.execute_in_place(ref, ctx, global);
ASTERIA_TEST_CHECK(status == Block::status_next);
auto qref = ctx.get_named_reference_opt(String::shallow("res"));
ASTERIA_TEST_CHECK(qref != nullptr);
ASTERIA_TEST_CHECK(qref->read().check<D_integer>() == 41);
qref = ctx.get_named_reference_opt(String::shallow("data"));
ASTERIA_TEST_CHECK(qref != nullptr);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().size() == 4);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(0).check<D_integer>() == 1);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(1).check<D_integer>() == 2);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(2).check<D_integer>() == 3);
ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(3).check<D_integer>() == 10);
qref = ctx.get_named_reference_opt(String::shallow("k"));
ASTERIA_TEST_CHECK(qref == nullptr);
qref = ctx.get_named_reference_opt(String::shallow("v"));
ASTERIA_TEST_CHECK(qref == nullptr);
qref = ctx.get_named_reference_opt(String::shallow("j"));
ASTERIA_TEST_CHECK(qref == nullptr);
}
| 49.679612 | 127 | 0.676959 | MaskRay |
e5b5c80434acda90be4e02bfcc27736f0c17d656 | 2,910 | cpp | C++ | 11. DP 2/Maximum_sum_rect.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | 11. DP 2/Maximum_sum_rect.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | 11. DP 2/Maximum_sum_rect.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | /* Maximum Sum Rectangle
Send Feedback
Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix.
Input Format:
First line of input will contain T(number of test case), each test case follows as.
First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm.
Output Format:
Output a single integer, maximum sum rectangle for each test case in a newline.
Constraints
1 <= T <= 50
1<=n,m<=100
-10^5 <= mat[i][j] <= 10^5
Sample Input
1
4 5
1 2 -1 -4 -20
-8 -3 4 2 1
3 8 10 1 3
-4 -1 1 7 -6
Sample Output
29 */
#include <bits/stdc++.h>
using namespace std;
int kadane(vector<int> vec)
{
int maxSum = INT_MIN, curSum = 0;
for (int i = 0; i < vec.size(); i++)
{
curSum += vec[i];
maxSum = max(maxSum, curSum);
curSum = (curSum < 0) ? 0 : curSum;
}
return maxSum;
}
int findMaxSum(vector<vector<int>> arr, int row, int col)
{
// int ans = 0;
// int startx = 0, starty = 0, endx = 0, endy = 0;
// for (int i = 0; i < row; i++)
// {
// startx = i;
// for (int j = 0; j < col; j++)
// {
// starty = j;
// for (int m = 0; m < row; m++)
// {
// endx = m;
// for (int n = 0; n < col; n++)
// {
// endy = n;
// int sum = 0;
// for (int a = startx; a <= endx; a++)
// {
// for (int b = starty; b <= endy; b++)
// {
// sum += arr[a][b];
// }
// }
// if (sum > ans)
// ans = sum;
// }
// }
// }
// }
//? 2nd approch
int max_sum_soFar = INT_MIN;
for(int i = 0; i < row; i++){
vector<int> temp(row);
for (int j = i; j < col; j++)
{
for (int k = 0; k < row; k++){
temp[k] += arr[k][j];
}
max_sum_soFar = max(max_sum_soFar, kadane(temp));
}
}
return max_sum_soFar;
}
int main()
{
freopen("/home/spy/Desktop/input.txt", "r", stdin);
freopen("/home/spy/Desktop/output.txt", "w", stdout);
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
vector<vector<int>> arr;
for (int i = 0; i < n; i++)
{
vector<int> tmp;
for (int j = 0; j < m; j++)
{
int x;
cin >> x;
tmp.push_back(x);
}
arr.push_back(tmp);
}
int ans;
ans = findMaxSum(arr, n, m);
cout << ans << endl;
}
return 0;
} | 24.453782 | 165 | 0.434021 | bhavinvirani |
e5c0f68c90c0999dfe19a01d29d9c0ff54282c05 | 3,491 | cpp | C++ | src/OptPlan/Opt_SnowflakeInterestingOrders.cpp | fsaintjacques/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 14 | 2016-07-11T04:08:09.000Z | 2022-03-11T05:56:59.000Z | src/OptPlan/Opt_SnowflakeInterestingOrders.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | null | null | null | src/OptPlan/Opt_SnowflakeInterestingOrders.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 13 | 2016-06-01T10:41:15.000Z | 2022-01-06T09:01:15.000Z | /*
* Opt_SnowflakeInterestingOrders.h
* OptDev
*
* Created by Nga Tran on 11/10/05.
* Questions, ask Nga Tran at nga@brandeis.edu or Tien Hoang at hoangt@brandeis.edu
*
* This class keeps interesting orders of a snowflake query
*/
#include "Opt_SnowflakeInterestingOrders.h"
// Default constructor
Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders()
{
m_sQueryName = "";
}
// Provide query name
Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders(string sQueryName)
{
m_sQueryName = sQueryName;
}
// Provide query names and 1 object
Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders(string sQueryName, list<Opt_Column*> order)
{
m_sQueryName = sQueryName;
mOrderList.push_back(order);
}
// Destructor
Opt_SnowflakeInterestingOrders::~Opt_SnowflakeInterestingOrders()
{
}
// String presentation of this class
string Opt_SnowflakeInterestingOrders::toStringNoTableDot(string sIndent)
{
string sReturn = sIndent;
sReturn.append(m_sQueryName);
sReturn.append(": \n");
sIndent += "\t";
list<InterestingOrder>::iterator orderIt;
for (orderIt = mOrderList.begin(); orderIt != mOrderList.end(); orderIt++)
{
sReturn.append(sIndent);
InterestingOrder order = *orderIt;
list<Opt_Column*>::iterator colIt;
for (colIt = order.begin(); colIt != order.end(); colIt++)
{
sReturn.append((*colIt)->toStringNoTableDot());
sReturn.append(" ");
}
sReturn.append("\n");
}
return sReturn;
}
// String presentation of this class
string Opt_SnowflakeInterestingOrders::toString(string sIndent)
{
string sReturn = sIndent;
sReturn.append(m_sQueryName);
sReturn.append(": \n");
sIndent += "\t";
list<InterestingOrder>::iterator orderIt;
for (orderIt = mOrderList.begin(); orderIt != mOrderList.end(); orderIt++)
{
sReturn.append(sIndent);
InterestingOrder order = *orderIt;
list<Opt_Column*>::iterator colIt;
for (colIt = order.begin(); colIt != order.end(); colIt++)
{
sReturn.append((*colIt)->toString());
sReturn.append(" ");
}
sReturn.append("\n");
}
return sReturn;
}
void Opt_SnowflakeInterestingOrders::setQueryName(string sQueryName)
{
m_sQueryName = sQueryName;
}
string Opt_SnowflakeInterestingOrders::getQueryName()
{
return m_sQueryName;
}
list<InterestingOrder> Opt_SnowflakeInterestingOrders::getOrderList()
{
return mOrderList;
}
// Add an order
// return true (1) if the order added
bool Opt_SnowflakeInterestingOrders::addOrder(string sQueryName, list<Opt_Column*> order)
{
if (m_sQueryName.compare(sQueryName) == 0)
{
// Check if the order already existed
list<InterestingOrder>::iterator it;
for (it = mOrderList.begin(); it != mOrderList.end(); it++)
{
list<Opt_Column*> intertestingOrder = *it;
// Check if number of columns in the orders are the same
if (intertestingOrder.size() != order.size())
{
continue;
}
// Compare if orders are exactly the same
bool isTheSame = 1;
list<Opt_Column*>::iterator existColIt = intertestingOrder.begin();
list<Opt_Column*>::iterator colIt = order.begin();
while( (existColIt != intertestingOrder.end()) && (colIt != order.end()) )
{
if (((*existColIt)->getColumnName()).compare((*colIt)->getColumnName()) != 0)
{
isTheSame = 0;
}
existColIt++;
colIt++;
}
if (isTheSame)
{
// the order already existed
return 1;
}
}
mOrderList.push_back(order);
return 1;
}
return 0;
}
| 22.967105 | 106 | 0.696649 | fsaintjacques |
e5c3467258e82f5fb0ba2c296149d9a250bf4d61 | 1,964 | cpp | C++ | tools/faodel-stress/serdes/SerdesStringObject.cpp | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-01-25T21:21:07.000Z | 2021-04-29T17:24:00.000Z | tools/faodel-stress/serdes/SerdesStringObject.cpp | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 8 | 2018-10-09T14:35:30.000Z | 2020-09-30T20:09:42.000Z | tools/faodel-stress/serdes/SerdesStringObject.cpp | faodel/faodel | ef2bd8ff335433e695eb561d7ecd44f233e58bf0 | [
"MIT"
] | 2 | 2019-04-23T19:01:36.000Z | 2021-05-11T07:44:55.000Z | // Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
#include <iostream>
#include "lunasa/common/GenericSequentialDataBundle.hh"
#include "SerdesStringObject.hh"
using namespace std;
SerdesStringObject::SerdesStringObject(JobSerdes::params_t params,
std::function<int ()> f_prng) {
//Populate our string list
for(int i=0; i<params.num_items; i++) {
strings.emplace_back(faodel::RandomString( f_prng() ));
}
}
typedef lunasa::GenericSequentialBundle<uint64_t> bundle_t;
lunasa::DataObject SerdesStringObject::pup() const {
// Since this is a series of random length strings, the easiest thing to
// do is just pack them into an LDO using the GenericSequentialBundler
// class. You allocate space for all the strings, and then use a
// bundle_offsets_t to keep track of where you are in the LDO.
//Figure out how much space our strings need. Note: each item as a 32b length
uint32_t payload_size=0;
for(auto &s: strings) {
payload_size += s.size() + sizeof(uint32_t);
}
//Allocate an LDO, overlay our bundle structure on it, and wipe the header
lunasa::DataObject ldo(sizeof(bundle_t), payload_size,lunasa::DataObject::AllocatorType::eager);
auto *msg = ldo.GetMetaPtr<bundle_t *>();
msg->Init();
//Use the offsets to track where we are so we don't overflow
lunasa::bundle_offsets_t counters(&ldo);
for(auto &s : strings) {
bool ok=msg->AppendBack(counters, s);
if(!ok) std::cerr<<"Serialization problems in SerdesStringObject\n";
}
return ldo;
}
void SerdesStringObject::pup(const lunasa::DataObject &ldo) {
auto *msg = ldo.GetMetaPtr<bundle_t *>();
lunasa::bundle_offsets_t counters(&ldo);
strings.resize(0);
string s;
while(msg->GetNext(counters, &s)) {
strings.emplace_back(s);
}
} | 31.174603 | 98 | 0.709776 | faodel |
e5c71a4a32057faabff0ea40bcba8665a95d7538 | 2,072 | cpp | C++ | android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JLongArray.hpp"
#include "../ipsec/ike/IkeTunnelConnectionParams.hpp"
#include "./VcnGatewayConnectionConfig.hpp"
#include "../../../JString.hpp"
#include "./VcnGatewayConnectionConfig_Builder.hpp"
namespace android::net::vcn
{
// Fields
// QJniObject forward
VcnGatewayConnectionConfig_Builder::VcnGatewayConnectionConfig_Builder(QJniObject obj) : JObject(obj) {}
// Constructors
VcnGatewayConnectionConfig_Builder::VcnGatewayConnectionConfig_Builder(JString arg0, android::net::ipsec::ike::IkeTunnelConnectionParams arg1)
: JObject(
"android.net.vcn.VcnGatewayConnectionConfig$Builder",
"(Ljava/lang/String;Landroid/net/ipsec/ike/IkeTunnelConnectionParams;)V",
arg0.object<jstring>(),
arg1.object()
) {}
// Methods
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::addExposedCapability(jint arg0) const
{
return callObjectMethod(
"addExposedCapability",
"(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0
);
}
android::net::vcn::VcnGatewayConnectionConfig VcnGatewayConnectionConfig_Builder::build() const
{
return callObjectMethod(
"build",
"()Landroid/net/vcn/VcnGatewayConnectionConfig;"
);
}
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::removeExposedCapability(jint arg0) const
{
return callObjectMethod(
"removeExposedCapability",
"(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0
);
}
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::setMaxMtu(jint arg0) const
{
return callObjectMethod(
"setMaxMtu",
"(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0
);
}
android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::setRetryIntervalsMillis(JLongArray arg0) const
{
return callObjectMethod(
"setRetryIntervalsMillis",
"([J)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;",
arg0.object<jlongArray>()
);
}
} // namespace android::net::vcn
| 31.876923 | 143 | 0.770753 | YJBeetle |
e5cdc4d1f569a0ed885f165863170e5e1a0ebb24 | 764 | cpp | C++ | InsertionSortList.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | 3 | 2017-11-27T03:01:50.000Z | 2021-03-13T08:14:00.000Z | InsertionSortList.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | null | null | null | InsertionSortList.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *new_head = NULL;
while (head) {
ListNode *next = head->next;
if (new_head == NULL || new_head->val > head->val) {
head->next = new_head;
new_head = head;
} else {
ListNode *p = new_head;
while (p->next != NULL && p->next->val < head->val) p = p->next;
head->next = p->next;
p->next = head;
}
head = next;
}
return new_head;
}
}; | 27.285714 | 80 | 0.458115 | yplusplus |
e5d5698fd37e77a6821d26a04bb9c8aa4ce06e25 | 48 | hpp | C++ | include/EnglishLogicConfig.hpp | mikhov-ivan/english-logic | 1554cb42d816bc8446ec3be3ba35509fb3dfe0d0 | [
"MIT"
] | null | null | null | include/EnglishLogicConfig.hpp | mikhov-ivan/english-logic | 1554cb42d816bc8446ec3be3ba35509fb3dfe0d0 | [
"MIT"
] | null | null | null | include/EnglishLogicConfig.hpp | mikhov-ivan/english-logic | 1554cb42d816bc8446ec3be3ba35509fb3dfe0d0 | [
"MIT"
] | null | null | null | #define VERSION_MAJOR 1
#define VERSION_MINOR 0
| 16 | 23 | 0.833333 | mikhov-ivan |
e5d5f4730db4ae23fed4f1331cfe1f7b949c1554 | 4,806 | hh | C++ | 3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh | kunal71091/Depth_Normal_Fusion | 407e204abfbd6c8efe2f98a07415bd623ad84422 | [
"MIT"
] | 1 | 2019-10-23T06:32:40.000Z | 2019-10-23T06:32:40.000Z | 3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh | kunal71091/Depth_Normal_Fusion | 407e204abfbd6c8efe2f98a07415bd623ad84422 | [
"MIT"
] | null | null | null | 3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh | kunal71091/Depth_Normal_Fusion | 407e204abfbd6c8efe2f98a07415bd623ad84422 | [
"MIT"
] | 1 | 2021-09-23T03:35:30.000Z | 2021-09-23T03:35:30.000Z | /*===========================================================================*\
* *
* IsoEx *
* Copyright (C) 2002 by Computer Graphics Group, RWTH Aachen *
* www.rwth-graphics.de *
* *
*---------------------------------------------------------------------------*
* *
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS ExtendedMarchingCubesT
//
//=============================================================================
#ifndef ISOEX_EXTMARCHINGCUBEST_HH
#define ISOEX_EXTMARCHINGCUBEST_HH
//== INCLUDES =================================================================
#include <IsoEx/Extractors/Edge2VertexMapT.hh>
#include <IsoEx/Grids/Grid.hh>
#include <vector>
//== NAMESPACES ===============================================================
namespace IsoEx {
//== CLASS DEFINITION =========================================================
/** \class ExtendedMarchingCubesT ExtendedMarchingCubesT.hh <IsoEx/Extractors/ExtendedMarchingCubesT.hh>
This class implements the Extended Marching Cubes of Kobbelt et al,
Siggraph 2001.
The 0-level iso-surface is extracted in the constructor. Use it through
the convenience function
<b>IsoEx::extended_marching_cubes()</b>.
\ingroup extractors
*/
template <class Mesh, class Grid>
class ExtendedMarchingCubesT
{
public:
ExtendedMarchingCubesT(const Grid& _grid,
Mesh& _mesh,
double _feature_angle);
private:
typedef typename Grid::PointIdx PointIdx;
typedef typename Grid::CubeIdx CubeIdx;
typedef typename Grid::CubeIterator CubeIterator;
typedef typename Mesh::VertexHandle VertexHandle;
typedef std::vector<VertexHandle> VertexHandleVector;
void process_cube(CubeIdx _idx);
VertexHandle add_vertex(PointIdx _p0, PointIdx _p1);
VertexHandle find_feature(const VertexHandleVector& _vhandles);
void flip_edges();
const Grid& grid_;
Mesh& mesh_;
float feature_angle_;
unsigned int n_edges_, n_corners_;
// maps an edge to the sample vertex generated on it
Edge2VertexMapT<PointIdx, VertexHandle> edge2vertex_;
};
//-----------------------------------------------------------------------------
/** Convenience wrapper for the Extended Marching Cubes algorithm.
\see IsoEx::ExtendedMarchingCubesT
\ingroup extractors
*/
template <class Mesh, class Grid>
void extended_marching_cubes(const Grid& _grid,
Mesh& _mesh,
double _feature_angle)
{
ExtendedMarchingCubesT<Mesh,Grid> emc(_grid, _mesh, _feature_angle);
}
//=============================================================================
} // namespace IsoEx
//=============================================================================
#if defined(INCLUDE_TEMPLATES) && !defined(ISOEX_EXTMARCHINGCUBEST_C)
#define ISOEX_EXTMARCHINGCUBEST_TEMPLATES
#include "ExtendedMarchingCubesT.cc"
#endif
//=============================================================================
#endif // ISOEX_EXTMARCHINGCUBEST_HH defined
//=============================================================================
| 38.142857 | 104 | 0.445901 | kunal71091 |
e5d9066ad1106be9e446fbc5f940183ea2859206 | 3,455 | cpp | C++ | src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 108 | 2018-10-08T17:03:32.000Z | 2022-03-21T00:52:26.000Z | src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 287 | 2018-09-18T14:59:12.000Z | 2022-01-13T12:28:23.000Z | src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 32 | 2018-10-19T14:35:03.000Z | 2021-11-12T09:36:46.000Z | /*
Copyright 2015-2017 Kai Huebl (kai@huebl-sgh.de)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl (kai@huebl-sgh.de)
*/
#include "OpcUaStackServer/AddressSpaceModel/BaseNodeClass.h"
namespace OpcUaStackServer
{
BaseNodeClass::BaseNodeClass(void)
: nodeId_()
, nodeClass_()
, browseName_()
, displayName_()
, description_()
, writeMask_()
, userWriteMask_()
, forwardNodeSync_()
{
}
BaseNodeClass::BaseNodeClass(NodeClassType nodeClass)
: nodeId_()
, nodeClass_(nodeClass)
, browseName_()
, displayName_()
, description_()
, writeMask_()
, userWriteMask_()
, forwardNodeSync_()
{
}
BaseNodeClass::~BaseNodeClass(void)
{
}
NodeIdAttribute&
BaseNodeClass::nodeId(void)
{
return nodeId_;
}
NodeClassAttribute&
BaseNodeClass::nodeClass(void)
{
return nodeClass_;
}
BrowseNameAttribute&
BaseNodeClass::browseName(void)
{
return browseName_;
}
DisplayNameAttribute&
BaseNodeClass::displayName(void)
{
return displayName_;
}
DescriptionAttribute&
BaseNodeClass::description(void)
{
return description_;
}
WriteMaskAttribute&
BaseNodeClass::writeMask(void)
{
return writeMask_;
}
UserWriteMaskAttribute&
BaseNodeClass::userWriteMask(void)
{
return userWriteMask_;
}
Attribute*
BaseNodeClass::nodeIdAttribute(void)
{
return &nodeId_;
}
Attribute*
BaseNodeClass::nodeClassAttribute(void)
{
return &nodeClass_;
}
Attribute*
BaseNodeClass::browseNameAttribute(void)
{
return &browseName_;
}
Attribute*
BaseNodeClass::displayNameAttribute(void)
{
return &displayName_;
}
Attribute*
BaseNodeClass::descriptionAttribute(void)
{
return &description_;
}
Attribute*
BaseNodeClass::writeMaskAttribute(void)
{
return &writeMask_;
}
Attribute*
BaseNodeClass::userWriteMaskAttribute(void)
{
return &userWriteMask_;
}
ReferenceItemMap&
BaseNodeClass::referenceItemMap(void)
{
return referenceItemMap_;
}
void
BaseNodeClass::copyTo(BaseNodeClass::SPtr baseNodeClass)
{
copyTo(*baseNodeClass);
}
void
BaseNodeClass::copyTo(BaseNodeClass& baseNodeClass)
{
nodeIdAttribute()->copyTo(baseNodeClass.nodeIdAttribute());
nodeClassAttribute()->copyTo(baseNodeClass.nodeClassAttribute());
browseNameAttribute()->copyTo(baseNodeClass.browseNameAttribute());
displayNameAttribute()->copyTo(baseNodeClass.displayNameAttribute());
descriptionAttribute()->copyTo(baseNodeClass.descriptionAttribute());
writeMaskAttribute()->copyTo(baseNodeClass.writeMaskAttribute());
userWriteMaskAttribute()->copyTo(baseNodeClass.userWriteMaskAttribute());
referenceItemMap_.copyTo(baseNodeClass.referenceItemMap());
}
void
BaseNodeClass::forwardNodeSync(ForwardNodeSync::SPtr forwardNodeSync)
{
forwardNodeSync_ = forwardNodeSync;
}
ForwardNodeSync::SPtr
BaseNodeClass::forwardNodeSync(void)
{
return forwardNodeSync_;
}
}
| 19.971098 | 86 | 0.754269 | gianricardo |
e5db1ceefa47fb1c63edd6f59d89695fab5ebf8a | 1,860 | hpp | C++ | code/include/boids2D/Boid.hpp | Shutter-Island-Team/Shutter-island | c5e7c0b2c60c34055e64104dcbc396b9e1635f33 | [
"MIT"
] | 4 | 2016-06-24T09:22:18.000Z | 2019-06-13T13:50:53.000Z | code/include/boids2D/Boid.hpp | Shutter-Island-Team/Shutter-island | c5e7c0b2c60c34055e64104dcbc396b9e1635f33 | [
"MIT"
] | null | null | null | code/include/boids2D/Boid.hpp | Shutter-Island-Team/Shutter-island | c5e7c0b2c60c34055e64104dcbc396b9e1635f33 | [
"MIT"
] | 2 | 2016-06-10T12:46:17.000Z | 2018-10-14T06:37:21.000Z | #ifndef BOID_HPP
#define BOID_HPP
#include <glm/glm.hpp>
#include <memory>
#include <vector>
#include "BoidType.hpp"
/**
* @class Boid
* @brief Parent class for a Boid (can be rooted or movable)
*/
class Boid
{
public:
/**
* @brief Constructor for a Boid
* @param[in] location The initial position
* @param[in] t Type of the boid
*/
Boid(glm::vec3 location, BoidType t);
/**
* @brief Getter for the location
*/
const glm::vec3 & getLocation() const;
/**
* @brief Setter for the location
* @param[in] location The new location
*/
void setLocation(const glm::vec3 & location);
/**
* @brief Getter of the angle
*/
const float & getAngle() const;
/**
* @brief Setter of the angle
* @param[in] angle The new angle
*/
void setAngle(const float & angle);
/**
* @brief Getter of the type of the boid
* @return Type of the boid
*/
const BoidType & getBoidType() const;
/**
* @brief Getter of the size of the boid
*/
const float & getScale() const;
/**
* @brief Setter of the size of the boid
*/
void setScale(const float & scale);
void disapear();
const bool & toDisplay() const;
bool isFoodRemaining() const;
void decreaseFoodRemaining();
bool isDecomposed() const;
void bodyDecomposition();
protected:
/**
* @brief Constructor for a Boid
* @param[in] location The initial position
* @param[in] t Type of the boid
*/
Boid(glm::vec3 location, BoidType t, int amountFood);
glm::vec3 m_location; ///< Position of the boid
private:
BoidType m_boidType; ///< Type of the boid @see BoidType.hpp
float m_angle; ///< Angle of position of the boid
float m_scale; ///< Size of the boid
bool m_display;
int m_amountFood;
float m_decomposition;
};
typedef std::shared_ptr<Boid> BoidPtr;
#endif
| 19.375 | 62 | 0.639247 | Shutter-Island-Team |
e5dbc06954d6a35ea13235b91c158246ea1a534a | 287 | cpp | C++ | DarkestTowerServer/DarkestTowerServer/Fighter.cpp | OztGod/DarkestTowerServer | 65043e1e7b158727f7f6ad7c008f1f2847174542 | [
"MIT"
] | null | null | null | DarkestTowerServer/DarkestTowerServer/Fighter.cpp | OztGod/DarkestTowerServer | 65043e1e7b158727f7f6ad7c008f1f2847174542 | [
"MIT"
] | 2 | 2015-09-23T17:17:52.000Z | 2015-09-23T18:16:46.000Z | DarkestTowerServer/DarkestTowerServer/Fighter.cpp | OztGod/DarkestTowerServer | 65043e1e7b158727f7f6ad7c008f1f2847174542 | [
"MIT"
] | null | null | null | #include "Fighter.h"
#include "FighterAttack.h"
#include "Charge.h"
Fighter::Fighter(int idx)
:Hero(HeroClass::FIGHTER, 17 + rand() % 4, 5 + rand() % 2, idx)
{
skills.push_back(SkillInfo(std::make_unique<FighterAttack>()));
skills.push_back(SkillInfo(std::make_unique<Charge>()));
}
| 26.090909 | 64 | 0.700348 | OztGod |
e5de1c12a0f2f37847a3bf7b8f1b83a25aa37ca3 | 202 | hpp | C++ | addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp | ASO-TheM/ChemicalWarfare | 51322934ef1da7ba0f3bb04c1d537767d8e48cc4 | [
"MIT"
] | 4 | 2018-04-28T16:09:21.000Z | 2021-08-24T12:51:55.000Z | addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp | ASO-TheM/ChemicalWarfare | 51322934ef1da7ba0f3bb04c1d537767d8e48cc4 | [
"MIT"
] | 29 | 2018-04-01T23:31:33.000Z | 2020-01-02T17:02:11.000Z | addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp | ASO-TheM/ChemicalWarfare | 51322934ef1da7ba0f3bb04c1d537767d8e48cc4 | [
"MIT"
] | 10 | 2018-07-13T15:02:06.000Z | 2021-04-06T17:12:11.000Z | class Sound_CBRN_cough_assaultboy:Sound_CBRN_coughBase {sound = "CBRN_cough_assaultboy";};
class Sound_CBRN_coughMuffled_assaultboy:Sound_CBRN_coughMuffledBase {sound = "CBRN_coughMuffled_assaultboy";}; | 101 | 111 | 0.876238 | ASO-TheM |
e5e7a30ebbffc75b417222539fae251a92732333 | 2,747 | cpp | C++ | Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | #include "CameraComponentWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
namespace editor::impl {
CameraComponentWidget::CameraComponentWidget(QWidget* parent)
: QWidget(parent)
, m_Camera(nullptr)
, m_Projection(nullptr)
, m_ProjectionLabel(nullptr)
, m_IsActiveCamera(nullptr)
, m_IsActiveCameraLabel(nullptr) {
QVBoxLayout* layout = new QVBoxLayout(this);
QHBoxLayout* projectionLayout = new QHBoxLayout();
m_Projection = new QComboBox(this);
m_Projection->addItem("Perspective", pawn::math::CameraType::Perspective);
m_Projection->addItem("Orthographic", pawn::math::CameraType::Orthographic);
m_ProjectionLabel = new QLabel("Projection", this);
m_ProjectionLabel->setMinimumWidth(80);
projectionLayout->addWidget(m_ProjectionLabel);
projectionLayout->addWidget(m_Projection);
QHBoxLayout* activeCameraLayout = new QHBoxLayout();
m_IsActiveCamera = new QCheckBox(this);
m_IsActiveCameraLabel = new QLabel("Active camera", this);
m_IsActiveCameraLabel->setMinimumWidth(80);
activeCameraLayout->addWidget(m_IsActiveCameraLabel);
activeCameraLayout->addWidget(m_IsActiveCamera);
layout->addLayout(projectionLayout);
layout->addLayout(activeCameraLayout);
setLayout(layout);
InitConnections();
}
void CameraComponentWidget::OnProjectionChanged(int index) {
if (m_Camera) {
pawn::math::Camera& camera = static_cast<pawn::math::Camera&>(*m_Camera);
pawn::math::CameraType type = qvariant_cast<pawn::math::CameraType>(m_Projection->itemData(index));
switch (type) {
case pawn::math::CameraType::Perspective:
{
camera.SetPerspective();
break;
}
case pawn::math::CameraType::Orthographic:
{
camera.SetOrthographic();
break;
}
default:
break;
}
}
}
void CameraComponentWidget::OnActiveCameraStateChanged(bool state) {
if (m_Camera) {
m_Camera->IsActiveCamera = state;
}
}
void CameraComponentWidget::SetCamera(pawn::engine::CameraComponent* camera) {
m_Camera = camera;
if (m_Camera) {
pawn::math::Camera& camera = static_cast<pawn::math::Camera&>(*m_Camera);
pawn::math::CameraType type = camera.GetType();
int index = m_Projection->findData(type);
if (index != -1) {
m_Projection->setCurrentIndex(index);
}
m_IsActiveCamera->setChecked(m_Camera->IsActiveCamera);
}
}
void CameraComponentWidget::InitConnections() {
connect(
m_Projection,
SIGNAL(currentIndexChanged(int)),
this,
SLOT(OnProjectionChanged(int))
);
connect(
m_IsActiveCamera,
SIGNAL(clicked(bool)),
this,
SLOT(OnActiveCameraStateChanged(bool))
);
}
}
| 25.201835 | 103 | 0.69312 | obivan43 |
e5e9918171f8610da10971bf5ef47eacc1d9275c | 5,711 | cpp | C++ | CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | #include "Core/Math/Mat4.hpp"
#include "Render/D3D11Helper.hpp"
#include "Resources/Mesh.hpp"
#include "Resources/Texture.hpp"
#include "Core/Primitives.hpp"
#include "Resources/Map.hpp"
#include "Render/DrawDataHandler.hpp"
#include "Render/Drawers/MiniMapDrawer.hpp"
#include "Render/Camera.hpp"
using namespace Cookie::Core::Math;
using namespace Cookie::Render;
struct VS_CONSTANT_BUFFER
{
Mat4 model;
Vec4 tileNb;
};
/*======================= CONSTRUCTORS/DESTRUCTORS =======================*/
MiniMapDrawer::MiniMapDrawer():
mapMesh{Core::Primitives::CreateCube()},
quadColor{ std::make_unique<Resources::Texture>("White", Vec4(MINI_MAP_QUAD_COLOR)) }
{
InitShader();
/* creating a quad that works with line strips */
std::vector<float> vertices = { -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f };
std::vector<unsigned int> indices = { 0 , 1, 2, 3 , 0 };
quad = std::make_unique<Resources::Mesh>("lineQuad", vertices, indices, 5);
}
MiniMapDrawer::~MiniMapDrawer()
{
if (VShader)
{
VShader->Release();
}
if (PShader)
{
PShader->Release();
}
if (VCBuffer)
{
VCBuffer->Release();
}
if (ILayout)
{
ILayout->Release();
}
}
/*======================= INIT METHODS =======================*/
void MiniMapDrawer::InitShader()
{
ID3DBlob* blob = nullptr;
std::string source = (const char*)R"(#line 27
struct VOut
{
float4 position : SV_POSITION;
float2 uv : UV;
};
cbuffer MODEL_CONSTANT : register(b0)
{
float4x4 model;
float2 tileNb;
};
cbuffer CAM_CONSTANT : register(b1)
{
float4x4 proj;
float4x4 view;
};
VOut main(float3 position : POSITION, float2 uv : UV, float3 normal : NORMAL)
{
VOut output;
output.position = mul(mul(mul(float4(position,1.0),model),view), proj);
output.uv = uv * tileNb;
return output;
}
)";
Render::CompileVertex(source, &blob, &VShader);
source = (const char*)R"(#line 83
Texture2D albedoTex : register(t0);
SamplerState WrapSampler : register(s0);
float4 main(float4 position : SV_POSITION, float2 uv : UV) : SV_TARGET
{
return float4(albedoTex.Sample(WrapSampler,uv).rgb,1.0);
})";
struct Vertex
{
Core::Math::Vec3 position;
Core::Math::Vec2 uv;
Core::Math::Vec3 normal;
};
// create the input layout object
D3D11_INPUT_ELEMENT_DESC ied[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex,position), D3D11_INPUT_PER_VERTEX_DATA, 0},
{"UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(Vertex, uv), D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, normal), D3D11_INPUT_PER_VERTEX_DATA, 0},
};
Render::CreateLayout(&blob, ied, 3, &ILayout);
Render::CompilePixel(source, &PShader);
VS_CONSTANT_BUFFER vbuffer = {};
Render::CreateBuffer(&vbuffer, sizeof(VS_CONSTANT_BUFFER), &VCBuffer);
blob->Release();
}
/*======================= REALTIME METHODS =======================*/
void MiniMapDrawer::Set(const Camera& cam, const Resources::Map& map)
{
mapAlbedo = map.model.albedo;
mapTrs = map.trs.TRS;
tileNb = map.tilesNb;
Vec3 middle = cam.ScreenPointToWorldDir({ { 0.0f,0.0f } });
//Vec3 UpperRight = cam.ScreenPointToWorldDir({ { 1.0f,1.0f } });
//Vec3 DownLeft = cam.ScreenPointToWorldDir({ { -1.0f,-1.0f } });
//
float t = (-cam.pos.y) / middle.y;
middle = cam.pos + middle * t;
//t = (-cam.pos.y) / UpperRight.y;
//UpperRight = cam.pos + UpperRight * t;
//t = (-cam.pos.y) / DownLeft.y;
//DownLeft = cam.pos + DownLeft * t;
quadTrs = Mat4::Scale({ 10.0f,1.0f,10.0f }) * Mat4::Translate(middle);
}
void MiniMapDrawer::Draw()
{
/* set shader */
RendererRemote::context->VSSetShader(VShader, nullptr, 0);
RendererRemote::context->PSSetShader(PShader, nullptr, 0);
RendererRemote::context->IASetInputLayout(ILayout);
/* filling constant buffer with map info */
VS_CONSTANT_BUFFER vbuffer = {};
vbuffer.model = mapTrs;
vbuffer.tileNb = { tileNb.x,tileNb.y,0.0f,0.0f };
RendererRemote::context->VSSetConstantBuffers(0, 1, &VCBuffer);
WriteBuffer(&vbuffer, sizeof(vbuffer), 0, &VCBuffer);;
/* map texture */
if (mapAlbedo)
mapAlbedo->Set(0);
/* then draw the map */
mapMesh->Set();
mapMesh->Draw();
/* drawing the quad of view of the cam */
RendererRemote::context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
/* removing depth buffer */
ID3D11RenderTargetView* rtv = nullptr;
Render::RendererRemote::context->OMGetRenderTargets(1, &rtv, nullptr);
Render::RendererRemote::context->OMSetRenderTargets(1, &rtv, nullptr);
/* we can use the same shader as it is pretty close put matrix in vbuffer */
vbuffer.model = quadTrs;
WriteBuffer(&vbuffer, sizeof(vbuffer), 0, &VCBuffer);
/* set a white texture and draw */
quadColor->Set();
quad->Set();
quad->Draw();
/* when you use Getter in dx11 it adds a ref in the object,
* so we release it*/
rtv->Release();
RendererRemote::context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
} | 28.133005 | 120 | 0.596568 | qbleuse |
e5ec6bfd9225a596f2111ae906a938b3348f3bd1 | 2,495 | hpp | C++ | inc/dirac_op.hpp | lkeegan/canonical | 9380e8026f637e50b6354eaf9aeb6728b28bac3c | [
"MIT"
] | null | null | null | inc/dirac_op.hpp | lkeegan/canonical | 9380e8026f637e50b6354eaf9aeb6728b28bac3c | [
"MIT"
] | null | null | null | inc/dirac_op.hpp | lkeegan/canonical | 9380e8026f637e50b6354eaf9aeb6728b28bac3c | [
"MIT"
] | null | null | null | #ifndef LKEEGAN_CANONICAL_DIRAC_OP_H
#define LKEEGAN_CANONICAL_DIRAC_OP_H
#include <random>
#include "4d.hpp"
#include "Eigen3/Eigen/Eigenvalues"
#include "omp.h"
#include "su3.hpp"
// staggered space-dependent gamma matrices
// for now stored as 5x doubles per site but they are just +/- signs, and g[0]
// is just + everywhere g[4] is gamma_5
class gamma_matrices {
private:
double g_[5];
public:
double& operator[](int i) { return g_[i]; }
double operator[](int i) const { return g_[i]; }
};
// Staggered dirac operator
class dirac_op {
private:
// Construct staggered eta (gamma) matrices
void construct_eta(field<gamma_matrices>& eta, const lattice& grid);
public:
std::ranlux48 rng;
double mass;
double mu_I;
field<gamma_matrices> eta;
bool ANTI_PERIODIC_BCS = true;
bool GAUGE_LINKS_INCLUDE_ETA_BCS = false;
dirac_op(const lattice& grid, double mass, double mu_I = 0.0);
explicit dirac_op(const lattice& grid) : dirac_op::dirac_op(grid, 0.0, 0.0) {}
void apbcs_in_time(field<gauge>& U) const;
// Applies eta matrices and apbcs in time to the gauge links U
// Required before and after using EO versions of dirac op
// Toggles flag GAUGE_LINKS_INCLUDE_ETA_BCS
void apply_eta_bcs_to_U(field<gauge>& U);
void remove_eta_bcs_from_U(field<gauge>& U);
// Axial gauge: all timelike links 1 except at T-1 boundary
void gauge_fix_axial(field<gauge>& U) const;
void gaussian_P(field<gauge>& P);
void random_U(field<gauge>& U, double eps);
// Returns eigenvalues of Dirac op
// Explicitly constructs dense (3*VOL)x(3*VOL) matrix Dirac op and finds all
// eigenvalues
Eigen::MatrixXcd D_eigenvalues(field<gauge>& U);
// Same for DDdagger, but much faster since we can use a hermitian solver.
Eigen::MatrixXcd DDdagger_eigenvalues(field<gauge>& U);
// explicitly construct dirac op as dense (3*VOL)x(3*VOL) matrix
Eigen::MatrixXcd D_dense_matrix(field<gauge>& U);
// explicitly construct dense (2x3xVOL3)x(2x3xVOL3) matrix P
// diagonalise and return all eigenvalues
// NOTE: also gauge fixes U to axial gauge
// NOTE2: also multiplies single gauge link U[T-1,ix3=0] by exp(i theta)
Eigen::MatrixXcd P_eigenvalues(field<gauge>& U, double theta = 0.0);
// explicitly construct dense (2x3xVOL3)x(2x3xVOL3) matrix
// B at timeslice it, using normalisation D = 2m + U..
// MUST be lexi grid layout for U!
Eigen::MatrixXcd B_dense_matrix(field<gauge>& U, int it);
};
#endif // LKEEGAN_CANONICAL_DIRAC_OP_H | 32.828947 | 80 | 0.726653 | lkeegan |
e5ec74faa22ac5c889e31f6c93ef137cdb41447a | 5,108 | cc | C++ | src/tim/vx/ops/rnn_cell.cc | gdh1995/TIM-VX | 242a6bd05ae9153a6b563c39e6f6de16568812df | [
"MIT"
] | null | null | null | src/tim/vx/ops/rnn_cell.cc | gdh1995/TIM-VX | 242a6bd05ae9153a6b563c39e6f6de16568812df | [
"MIT"
] | null | null | null | src/tim/vx/ops/rnn_cell.cc | gdh1995/TIM-VX | 242a6bd05ae9153a6b563c39e6f6de16568812df | [
"MIT"
] | null | null | null | /****************************************************************************
*
* Copyright (c) 2021 Vivante Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#include "tim/vx/ops.h"
#include "vsi_nn_pub.h"
#include "op_impl.h"
#include <array>
namespace tim {
namespace vx {
namespace ops {
class RNNCellImpl : public OpImpl {
public:
enum {
// signature
FULLY_CONNECTED_0_IN = 0,
FULLY_CONNECTED_0_WEIGHT = 1,
FULLY_CONNECTED_0_BIAS = 2,
FULLY_CONNECTED_1_WEIGHT = 3,
FULLY_CONNECTED_1_STATE_IN = 4,
INPUT_CNT,
OUT = 0,
STATE_OUT,
OUT_CNT,
// signature end
};
RNNCellImpl(Graph* graph, int input_cnt, int output_cnt,
DataLayout layout = DataLayout::ANY)
: OpImpl(graph, -1, input_cnt, output_cnt, layout) {
fc0_ = graph->CreateOperation<tim::vx::ops::FullyConnected>(0, 4);
fc1_ = graph->CreateOperation<tim::vx::ops::FullyConnected>(0, 4);
add_ = graph->CreateOperation<tim::vx::ops::Add>();
tanh_ = graph->CreateOperation<tim::vx::ops::Tanh>();
data_convert_ = graph->CreateOperation<tim::vx::ops::DataConvert>();
}
~RNNCellImpl() {}
RNNCellImpl& BindInput(const std::shared_ptr<Tensor>& tensor) override {
in_tensors_[input_tensor_index] = tensor;
if (this->input_tensor_index == INPUT_CNT - 1) {
// Get all input tensor
tim::vx::ShapeType shape = {0, 0};
tim::vx::TensorSpec FC0_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
tim::vx::TensorSpec FC1_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
tim::vx::TensorSpec add_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
auto FC0_tensor = graph_->CreateTensor(FC0_spec);
auto FC1_tensor = graph_->CreateTensor(FC1_spec);
auto add_tensor = graph_->CreateTensor(add_spec);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_IN]);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_WEIGHT]);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_BIAS]);
fc0_->BindOutput(FC0_tensor);
fc1_->BindInput(in_tensors_[FULLY_CONNECTED_1_WEIGHT]);
fc1_->BindInput(in_tensors_[FULLY_CONNECTED_1_STATE_IN]);
fc1_->BindOutput(FC1_tensor);
add_->BindInput(FC0_tensor);
add_->BindInput(FC1_tensor);
add_->BindOutput(add_tensor);
tanh_->BindInput(add_tensor);
}
this->input_tensor_index++;
return *this;
}
RNNCellImpl& BindOutput(const std::shared_ptr<Tensor>& tensor) override {
out_tensors_[output_tensor_index] = tensor;
tanh_->BindOutput(out_tensors_[OUT]);
data_convert_->BindInput(out_tensors_[OUT]);
if (this->output_tensor_index == OUT_CNT - 1) {
data_convert_->BindOutput(out_tensors_[STATE_OUT]);
}
this->output_tensor_index++;
return *this;
}
vsi_nn_node_t* node() override { return nullptr; }
std::vector<std::shared_ptr<Tensor>> InputsTensor() override {
return inputs_tensor_;
}
std::vector<std::shared_ptr<Tensor>> OutputsTensor() override {
return outputs_tensor_;
}
private:
std::shared_ptr<tim::vx::Operation> fc0_;
std::shared_ptr<tim::vx::Operation> fc1_;
std::shared_ptr<tim::vx::Operation> add_;
std::shared_ptr<tim::vx::Operation> tanh_;
std::shared_ptr<tim::vx::Operation> data_convert_;
std::array<std::shared_ptr<tim::vx::Tensor>, INPUT_CNT> in_tensors_;
std::array<std::shared_ptr<tim::vx::Tensor>, OUT_CNT> out_tensors_;
};
RNNCell::RNNCell(Graph* graph, ActivationType activation)
: activation_(activation) {
impl_ = std::make_unique<RNNCellImpl>(graph, 0, 0, DataLayout::ANY);
}
std::shared_ptr<Operation> RNNCell::Clone(std::shared_ptr<Graph>& graph) const {
return graph->CreateOperation<RNNCell>(this->activation_);
}
} // namespace ops
} // namespace vx
} // namespace tim
| 35.72028 | 80 | 0.669538 | gdh1995 |
e5f27ff62e3c8fe8f15130737b095fadf08dec16 | 3,670 | cpp | C++ | src/coinbase_pro/parser.cpp | olned/ssc2ce-cpp | 306188fa66322773721f71a8b52ea107ff2288cd | [
"BSL-1.0"
] | null | null | null | src/coinbase_pro/parser.cpp | olned/ssc2ce-cpp | 306188fa66322773721f71a8b52ea107ff2288cd | [
"BSL-1.0"
] | null | null | null | src/coinbase_pro/parser.cpp | olned/ssc2ce-cpp | 306188fa66322773721f71a8b52ea107ff2288cd | [
"BSL-1.0"
] | null | null | null | // Copyright Oleg Nedbaylo 2020.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE
// or copy at http://www.boost.org/LICENSE_1_0.txt
#include "parser.hpp"
#include <cstdlib>
#include <fmt/format.h>
#include <iostream>
#include <rapidjson/document.h>
namespace ssc2ce {
CoinbaseParser::CoinbaseParser()
{
}
bool CoinbaseParser::parse(const char *message)
{
if (message[0] == char(0)) {
last_error_msg_ = "Empty string.";
return false;
}
last_error_msg_.clear();
using namespace rapidjson;
rapidjson::Document doc;
doc.Parse(message);
if (doc.IsNull()) {
last_error_msg_ = "Unable to parse the message, probably the wrong JSON format.";
return false;
}
bool processed = false;
if (doc.HasMember("type")) {
const char *message_type = doc["type"].GetString();
switch (message_type[0]) {
case 'a':
// activate
break;
case 'c':
// change
break;
case 'd':
// done
break;
case 'h':
// heartbeat
break;
case 'l':
// l2update
processed = handle_l2update(doc);
case 'm':
// match
break;
case 'o':
// open
break;
case 'r':
// received
break;
case 's':
switch (message_type[1]) {
case 'n':
processed = handle_snapshot(doc);
case 't':
// status
break;
default:
// subscribe
break;
}
break;
case 't':
// ticker
break;
default:
break;
}
if (!processed) {
last_error_msg_ = fmt::format("CoinbaseParser Unsupported: {} in message: {}", message_type, message);
}
} // namespace ssc2ce
else {
last_error_msg_ = fmt::format("CoinbaseParser Unknown message format: {}", message);
}
return processed;
} // namespace ssc2ce
bool CoinbaseParser::handle_snapshot(const rapidjson::Value &data)
{
auto &book = find_or_create_book(data["product_id"].GetString());
book.clear();
for (const auto &item : data["bids"].GetArray()) {
auto price = std::atof(item[0].GetString());
auto size = std::atof(item[1].GetString());
book.add_bid(price, size);
}
for (const auto &item : data["asks"].GetArray()) {
auto price = std::atof(item[0].GetString());
auto size = std::atof(item[1].GetString());
book.add_ask(price, size);
}
if (on_book_setup_)
on_book_setup_(&book);
return true;
}
bool CoinbaseParser::handle_l2update(const rapidjson::Value &data)
{
auto &book = find_or_create_book(data["product_id"].GetString());
book.set_time(data["time"].GetString());
for (const auto &item : data["changes"].GetArray()) {
if (item[0].GetString()[0] == 's') // sell
{
const auto price = std::atof(item[1].GetString());
const auto size = std::atof(item[2].GetString());
book.update_ask(price, size);
} else {
const auto price = std::atof(item[1].GetString());
const auto size = std::atof(item[2].GetString());
book.update_bid(price, size);
}
}
if (on_book_update_)
on_book_update_(&book);
return true;
}
CoinbaseBookL2 &CoinbaseParser::find_or_create_book(const std::string_view &instrumnet)
{
const auto key = std::hash<std::string_view>{}(instrumnet);
if (auto p = books_.find(key); p != books_.end()) {
return p->second;
} else {
auto [x, ok] = books_.emplace(key, CoinbaseBookL2(std::string(instrumnet)));
return x->second;
}
};
BookL2 const *CoinbaseParser::get_book(const std::string_view &instrument)
{
BookL2 const *book = &find_or_create_book(instrument);
return book;
}
} // namespace ssc2ce | 22.9375 | 108 | 0.617984 | olned |
e5fa89f24b53ada66750cbf7e14b96d67cba0025 | 2,386 | hpp | C++ | docker/private/priority_queue.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 41 | 2019-09-24T02:17:34.000Z | 2022-01-18T03:14:46.000Z | docker/private/priority_queue.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 2 | 2019-11-04T09:01:40.000Z | 2020-06-23T03:03:38.000Z | docker/private/priority_queue.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 8 | 2019-09-24T02:17:35.000Z | 2021-09-11T00:21:03.000Z | #ifndef xpack_docker_priority_queue
#define xpack_docker_priority_queue
#pragma push_macro("xuser")
#undef xuser
#define xuser mixc::docker_priority_queue::inc
#include"algo/heap_root.hpp"
#include"define/base_type.hpp"
#include"docker/shared_array.hpp"
#include"docker/transmitter.hpp"
#include"dumb/mirror.hpp"
#include"macro/xexport.hpp"
#include"macro/xis_nullptr.hpp"
#include"macro/xref.hpp"
#include"macro/xstruct.hpp"
#include"memop/cast.hpp"
#pragma pop_macro("xuser")
namespace mixc::docker_priority_queue {
template<class final_t, class item_t>
xstruct(
xtmpl(priority_queue, final_t, item_t),
xprif(m_items, inc::shared_array<item_t>)
)
using mirror = inc::shared_array<inc::mirror<item_t>>;
priority_queue(){}
template<class finalx_t >
priority_queue(priority_queue<finalx_t, item_t> const & object) :
m_items((inc::shared_array<item_t> &)object.m_items){}
priority_queue(::length initial_capacity) :
m_items(initial_capacity){}
void clear() {
the_t{}.m_items.swap(xref(m_items));
}
void push(item_t const & value) {
// 本次 push 无需拷贝构造
inc::cast<mirror>(m_items).push(inc::mirror<item_t>{});
// 本次 push 默认内部拷贝构造
inc::heap_root::push(m_items, m_items.length() - 1, value);
}
inc::transmitter<item_t> pop() {
auto length = m_items.length();
inc::transmitter<item_t> r = m_items[0];
inc::heap_root::pop(m_items, length, m_items[length - 1]);
inc::cast<mirror>(m_items).pop();
return r;
}
void swap(the_t * object){
m_items.swap(object);
}
final_t & operator= (decltype(nullptr)){
m_items = nullptr;
return thex;
}
final_t & operator= (the_t const & object){
m_items = object.m_items;
return thex;
}
xpubgetx(root, inc::transmitter<item_t>){
return m_items[0];
}
xpubgetx(length, uxx){
return m_items.length();
}
xpubgetx(is_empty, bool){
return m_items.length() == 0;
}
xis_nullptr(
m_items == nullptr
)
};
}
#endif
#define xusing_docker_name ::mixc::docker_priority_queue
| 26.808989 | 74 | 0.594719 | Better-Idea |
f905d68556ea6891fbacf9aa7d32580665bbd957 | 2,194 | cc | C++ | src/hlib/libcpp/os.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/os.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/os.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | string os_name()
{
#ifdef _WIN32
return "win32";
#elif _WIN64
return "win64";
#elif __APPLE__ || __MACH__ || macintosh || Macintosh
return "macos";
#elif __linux__
return "linux";
#elif __FreeBSD__
return "freebsd";
#elif __unix || __unix__
return "unix";
#elif __ANDROID__
return "android";
#elif AMIGA
return "amiga";
#elif __FreeBSD__ || __OpenBSD__ || __NetBSD__ || __DragonFly__
return "bsd";
#elif __CYGWIN__
return "cygwin";
#elif __minix
return "minix";
#elif __MSDOS__
return "msdos";
#elif __sun
return "solaris";
#elif __SYMBIAN32__
return "symbian";
#elif __MVS__
return "zvm";
#else
return "unknown";
#endif
}
int system(string cmd)
{
return system(cmd.c_str());
}
bool is_x86(){
if(sizeof(void*) == 4)
return true;
else
return false;
}
bool is_64(){
return !is_x86();
}
string compiler_name(){
#ifdef __clang__
return "clang";
#elif __GNUC__
return "gcc";
#elif _MSC_VER
return "msvc";
#elif __BORLANDC__
return "bcc";
#elif __DMC__
return "dmc";
#elif __INTEL_COMPILER
return "icc";
#else
return "unknown";
#endif
}
// refernce: https://sourceforge.net/p/predef/wiki/Architectures/
string arch()
{
string comname = compiler_name();
if(comname == "msvc"){
#ifdef _M_AMD64
return "AMD64";
#elif _M_IX86
return "intel32";
#elif _M_IA64
return "ia64"; // also supports by intel c++ : __itanium__
#elif _M_PPC
return "powerpc";
#else
return "unknown";
#endif
}else if(comname == "gcc"){
#ifdef __amd64__ || __amd64
return "AMD64";
#elif __arm__
return "arm";
#elif __i386__ || __i486__ || __i586__ || __i686__
return "intel32";
#elif __ia64__
return "ia64";
#elif __mips__
return "mips";
#elif __powerpc__ || __powerpc64__
return "powerpc";
#else
return "unknown";
#endif
}
// todo : support intel c++
return "unknown";
} | 20.12844 | 67 | 0.568368 | hascal |
f90bd9d71cd5d5659b11dbb985099333744bbc32 | 3,714 | hpp | C++ | rmvmathtest/profile/Profiler.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | rmvmathtest/profile/Profiler.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | rmvmathtest/profile/Profiler.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | //
// Created by Vitali Kurlovich on 3/22/16.
//
#ifndef RMVECTORMATH_PROFILER_HPP
#define RMVECTORMATH_PROFILER_HPP
#include <vector>
#include <stack>
#include <chrono>
#include "ProfileCase.hpp"
#include <profiler/MathStatistic.hpp>
namespace profiler {
class Profiler {
protected:
std::vector<const ProfileCase*> profileCases;
std::stack<std::chrono::steady_clock::time_point> timestack;
bool _blockCout{false};
public:
void addProfileCases(const ProfileCase* profileCase ) {
profileCases.push_back(profileCase);
}
void run() {
std::cout << "Start profiling..." << std::endl;
std::vector<const ProfileCase*>::iterator i;
_blockCout = true;
for (u_int32_t iter = 0; iter < 10; iter++) {
for (i = profileCases.begin(); i != profileCases.end(); ++i) {
rmmath::MathStatistic::instance().resetAll();
(*i)->run();
}
}
_blockCout = false;
for (i = profileCases.begin(); i!= profileCases.end(); ++i) {
printProfileCaseHeader(*i);
rmmath::MathStatistic::instance().resetAll();
(*i)->run();
}
}
public:
void beginProfileCase(const char* casename) {
if (_blockCout)
return;
printBeginProfileCase(casename);
rmmath::MathStatistic::instance().resetAll();
auto now = std::chrono::steady_clock::now();
timestack.push(now);
}
void endProfileCase(const char* casename) {
if (_blockCout)
return;
auto now = std::chrono::steady_clock::now();
auto begintime = timestack.top();
timestack.pop();
std::cout << "Duration: " << std::chrono::duration_cast<std::chrono::milliseconds>(now - begintime).count() << "ms" << std::endl;
printMathStatistic();
}
protected:
void printProfileCaseHeader(const ProfileCase* profileCase) {
std::cout << "[--- " << profileCase->getName() << " ---]" << std::endl;
}
void printMathStatistic() {
bool show = false;
auto mul = rmmath::MathStatistic::instance().mul();
show |= (mul > 0);
auto div = rmmath::MathStatistic::instance().div();
show |= (div > 0);
auto sum = rmmath::MathStatistic::instance().sum();
show |= (sum > 0);
auto sub = rmmath::MathStatistic::instance().sub();
show |= (sub > 0);
auto sqrt = rmmath::MathStatistic::instance().sqrt();
show |= (sqrt > 0);
if (!show)
return;
std::cout << "[ Math Statistic ]" << std::endl;
if (sum > 0) {
std::cout << " Sum: " << sum <<std::endl;
}
if (sub > 0) {
std::cout << " Sub: " << sub <<std::endl;
}
if (mul > 0) {
std::cout << " Mul: " << mul <<std::endl;
}
if (div > 0) {
std::cout << " Div: " << div <<std::endl;
}
if (sqrt > 0) {
std::cout << " Sqrt: " << sqrt <<std::endl;
}
std::cout << "[ -------------- ]" << std::endl;
}
void printBeginProfileCase(const char* casename) {
std::cout << "+++ " << casename << " +++" << std::endl;
}
};
}
#endif //RMVECTORMATH_PROFILER_HPP
| 27.511111 | 142 | 0.469575 | vitali-kurlovich |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.