hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
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
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
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
ee1ca5d0de54794324ae2ca93083f823b95f728e
1,608
hpp
C++
src/ncp-spinel/spinel_encrypter.hpp
piotrkoziar/wpantund
a4fb3ca5c53701f1267321674093d2fdeeb7dbe5
[ "Apache-2.0" ]
161
2016-06-09T22:51:27.000Z
2022-03-07T22:32:44.000Z
src/ncp-spinel/spinel_encrypter.hpp
Matt-Harvill/ti-wisunfantund
a7a0a85ae7d61f603a64fdb233b0b6cac27204e6
[ "Apache-2.0" ]
284
2016-06-09T23:19:03.000Z
2022-02-15T01:22:11.000Z
src/ncp-spinel/spinel_encrypter.hpp
Matt-Harvill/ti-wisunfantund
a7a0a85ae7d61f603a64fdb233b0b6cac27204e6
[ "Apache-2.0" ]
119
2016-06-10T00:25:09.000Z
2022-03-25T11:09:30.000Z
/** * Allows to encrypt spinel frames sent between Application Processor (AP) and Network Co-Processor (NCP). */ namespace SpinelEncrypter { /** * Encrypts spinel frames before sending to AP/NCP. * * This method encrypts outbound frames in both directions, i.e. from AP to NCP and from NCP to AP. * * @param[in,out] aFrameBuf Pointer to buffer containing the frame, also where the encrypted frame will be placed. * @param[in] aFrameSize Max number of bytes in frame buffer (max length of spinel frame + additional data for encryption). * @param[in,out] aFrameLength Pointer to store frame length, on input value is set to frame length, * on output changed to show the frame length after encryption. * @return \c true on success, \c false otherwise. */ bool EncryptOutbound(unsigned char *aFrameBuf, size_t aFrameSize, size_t *aFrameLength); /** * Decrypts spinel frames received from AP/NCP. * * This method decrypts inbound frames in both directions, i.e. from AP to NCP and from NCP to AP. * * @param[in,out] aFrameBuf Pointer to buffer containing encrypted frame, also where the decrypted frame will be placed. * @param[in] aFrameSize Max number of bytes in frame buffer (max length of spinel frame + additional data for encryption). * @param[in,out] aFrameLength Pointer to store frame length, on input value is set to encrypted frame length, * on output changed to show the frame length after decryption. * @return \c true on success, \c false otherwise. */ bool DecryptInbound(unsigned char *aFrameBuf, size_t aFrameSize, size_t *aFrameLength); } // namespace SpinelEncrypter
47.294118
123
0.754975
piotrkoziar
ee1d05f59c8073c0b9306615a6de558873e373b4
1,290
cpp
C++
Game Theory/Tower Breakers, Revisited!.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Game Theory/Tower Breakers, Revisited!.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Game Theory/Tower Breakers, Revisited!.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
/* **************************************************************** **************************************************************** -> Coded by Stavros Chryselis -> Visit my github for more solved problems over multiple sites -> https://github.com/StavrosChryselis -> Feel free to email me at stavrikios@gmail.com **************************************************************** **************************************************************** */ #include <iostream> #include <cstring> #define MAXN 1000007 using namespace std; int memo[MAXN]; inline void pre() { memset(memo, -1, sizeof(memo)); memo[1] = 0; } inline int mex(bool *a) { for (int i = 0; 1; i++) if (!a[i]) return i; return 0; } int gr(int n) { if (memo[n] != -1) return memo[n]; bool t[64]; memset(t, 0, sizeof(t)); t[0] = 1; for (int i = 2; i * i <= n; i++) if (n % i == 0) { t[gr(i)] = 1; t[gr(n / i)] = 1; } memo[n] = mex(t); return memo[n]; } inline int solve() { int i, N, num; int xxor = 0; cin >> N; while (N--) { cin >> num; xxor ^= gr(num); } if (!xxor) return 2; return 1; } int main() { ios::sync_with_stdio(0); int T; // freopen("input.txt", "r", stdin); pre(); cin >> T; while (T--) cout << solve() << "\n"; return 0; }
13.870968
64
0.431783
StavrosChryselis
ee1f0833e1fdd22d9c3b1090453ac71230614fd3
2,665
cpp
C++
Particles-Playground/System/gpubufferuploadmanager.cpp
lukaszlipski/Particles-Playground
1082f4ab043cd4a7eed29d1116883358f93da0fb
[ "MIT" ]
1
2021-03-13T04:35:08.000Z
2021-03-13T04:35:08.000Z
Particles-Playground/System/gpubufferuploadmanager.cpp
lukaszlipski/Particles-Playground
1082f4ab043cd4a7eed29d1116883358f93da0fb
[ "MIT" ]
null
null
null
Particles-Playground/System/gpubufferuploadmanager.cpp
lukaszlipski/Particles-Playground
1082f4ab043cd4a7eed29d1116883358f93da0fb
[ "MIT" ]
null
null
null
#include "gpubufferuploadmanager.h" uint8_t* UploadBufferTemporaryRange::Map() { uint8_t* data = nullptr; const CD3DX12_RANGE range(mStartRange, mEndRange); HRESULT res = GetResource()->Map(0, &range, reinterpret_cast<void**>(&data)); Assert(SUCCEEDED(res)); return data + mStartRange; } void UploadBufferTemporaryRange::Unmap() { const CD3DX12_RANGE range(mStartRange, mEndRange); GetResource()->Unmap(0, &range); } ID3D12Resource* UploadBufferTemporaryRange::GetResource() const { return GPUBufferUploadManager::Get().GetResource(); } bool GPUBufferUploadManager::Startup() { ID3D12Device* const device = Graphic::Get().GetDevice(); D3D12_HEAP_DESC heapProps{}; heapProps.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; heapProps.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; heapProps.Properties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD); heapProps.SizeInBytes = UploadHeapSize; HRESULT res = device->CreateHeap(&heapProps, IID_PPV_ARGS(&mHeap)); Assert(SUCCEEDED(res)); const CD3DX12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(UploadHeapSize); res = device->CreatePlacedResource(mHeap, 0, &bufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&mUploadRes)); Assert(SUCCEEDED(res)); return true; } bool GPUBufferUploadManager::Shutdown() { if (mHeap) { mHeap->Release(); } if (mUploadRes) { mUploadRes->Release(); } for (Allocation& alloc : mAllocations) { mAllocator.Free(alloc.AllocationRange); } return true; } void GPUBufferUploadManager::PreUpdate() { const uint64_t currentFrameNum = Graphic::Get().GetCurrentFrameNumber(); const uint32_t frameCount = Graphic::Get().GetFrameCount(); for (Allocation& alloc : mAllocations) { // Merge not needed memory block if (alloc.FrameNumber + frameCount <= currentFrameNum) { mAllocator.Free(alloc.AllocationRange); } } mAllocations.remove_if([currentFrameNum, frameCount](const Allocation& alloc) { return alloc.FrameNumber + frameCount <= currentFrameNum; }); } UploadBufferTemporaryRangeHandle GPUBufferUploadManager::Reserve(uint32_t size, uint32_t alignment) { ID3D12Device* const device = Graphic::Get().GetDevice(); Range alloc = mAllocator.Allocate(size, alignment); Assert(alloc.IsValid()); const uint64_t currentFrameNum = Graphic::Get().GetCurrentFrameNumber(); mAllocations.push_back({ alloc.Start, alloc.Size, currentFrameNum }); return std::make_unique<UploadBufferTemporaryRange>(alloc.Start, alloc.Start + alloc.Size); }
29.94382
133
0.722702
lukaszlipski
ee1f7cbd530e73818d0cc5d5e787c992f3076d84
18,061
cxx
C++
SRC/analysis/analysis_cutline_recursive.cxx
shikc/wotan
e6962ed5b3e14033f49666b2fc210ea8c3f77290
[ "MIT" ]
6
2018-12-15T03:31:41.000Z
2020-11-09T12:50:03.000Z
SRC/analysis/analysis_cutline_recursive.cxx
shikc/wotan
e6962ed5b3e14033f49666b2fc210ea8c3f77290
[ "MIT" ]
null
null
null
SRC/analysis/analysis_cutline_recursive.cxx
shikc/wotan
e6962ed5b3e14033f49666b2fc210ea8c3f77290
[ "MIT" ]
5
2019-04-22T12:47:58.000Z
2021-03-04T06:34:20.000Z
/* The 'cutline' method of analyzing reachability in a graph is invoked after paths have been enumerated through the routing resource graph. blah blah The 'cutline recursive' method of reachability analysis builds on top of a topological traversal of the subraph. Hence the constituent functions are meant to be passed-in to a topological traversal function (see topological_traversal.h) */ #include <algorithm> #include "analysis_main.h" #include "analysis_cutline_recursive.h" #include "topological_traversal.h" #include "exception.h" #include "wotan_util.h" using namespace std; /**** Function Declarations ****/ /* returns height of node based on node's corresponding ss_distances */ static int get_node_height(SS_Distances &node_ss_distances); /* returns true if specified node has legal parents (their source-hop number is smaller) at the specified height */ static bool has_parents_of_height(int node_ind, int height, t_rr_node &rr_node, t_ss_distances &ss_distances, e_traversal_dir traversal_dir, int max_path_weight); /* adds specified node to the cutline probability structure according to the node's level in the topological traversal */ static void add_node_to_cutline_structure(int node_ind, int level, t_cutline_rec_prob_struct &cutline_probability_struct); /* estimates probability that a source/dest connection can be made based on the cutline structure. returns UNDEFINED if any one of the levels is empty */ static float connection_probability_cutlines(t_rr_node &rr_node, Cutline_Recursive_Structs *cutline_rec_structs, t_node_topo_inf &node_topo_inf, t_topo_inf_backups &topo_inf_backups, int recursion_level, t_ss_distances &ss_distances, User_Options *user_opts); /**** Function Definitions ****/ /* Called when node is popped from expansion queue during topological traversal */ void cutline_recursive_node_popped_func(int popped_node, int from_node_ind, int to_node_ind, t_rr_node &rr_node, t_ss_distances &ss_distances, t_node_topo_inf &node_topo_inf, e_traversal_dir traversal_dir, int max_path_weight, User_Options *user_opts, void *user_data){ Cutline_Recursive_Structs *cutline_rec_structs = (Cutline_Recursive_Structs*)user_data; int relative_level = UNDEFINED; /* get node's height relative to root node of this traversal */ int node_height = get_node_height(ss_distances[popped_node]); int from_height = get_node_height(ss_distances[from_node_ind]); int relative_height = node_height - from_height; /* get node's source hops relative to root node of this traversal (this isn't necessarily the shortest number of hops from root to this node -- only an approximation) */ int node_source_hops = ss_distances[popped_node].get_source_hops(); int from_source_hops = ss_distances[from_node_ind].get_source_hops(); int relative_source_hops = node_source_hops - from_source_hops; /* Error Checks */ //TODO: remove this after debugging done if (relative_source_hops < 0){ WTHROW(EX_PATH_ENUM, "Seem to have stepped backward from root node"); } if (relative_source_hops >= cutline_rec_structs->bound_source_hops){ WTHROW(EX_PATH_ENUM, "Seem to have exceeded source-hop bounds"); } if (relative_height < 0){ WTHROW(EX_PATH_ENUM, "Seem to have stepped down in height"); } /* If node hasn't been 'smoothed' out in a different traversal, then it will be assigned a level. But if node has been smoothed, it doesn't get a level; though its children are still traversed and potentially placed on expansion queue */ bool node_smoothed = node_topo_inf[popped_node].get_node_smoothed(); if (!node_smoothed){ /* set relative node level */ if (relative_height == 0){ /* at same height as root --> level is relative hops from root */ relative_level = relative_source_hops; } else { if ( has_parents_of_height(popped_node, node_height, rr_node, ss_distances, traversal_dir, max_path_weight) ){ /* not the first node of its height */ relative_level = relative_source_hops - relative_height; } else { /* first node at this height -- some of its descendents need to be smoothed out so that nodes in subgraph can be assigned levels in a more-natural manner */ Cutline_Recursive_Structs new_cutline_rec_structs; new_cutline_rec_structs.bound_source_hops = node_source_hops + relative_height + 1; new_cutline_rec_structs.recurse_level = cutline_rec_structs->recurse_level + 1; new_cutline_rec_structs.cutline_rec_prob_struct.assign( relative_height + 1, vector<int>() ); new_cutline_rec_structs.source_ind = cutline_rec_structs->source_ind; new_cutline_rec_structs.sink_ind = cutline_rec_structs->sink_ind; new_cutline_rec_structs.fill_type = cutline_rec_structs->fill_type; /* back up topo inf for this node */ Topo_Inf_Backup node_backup; node_backup.backup(popped_node, node_topo_inf); node_backup.clear_node_topo_inf(node_topo_inf); /* RECURSE on this node */ do_topological_traversal(popped_node, to_node_ind, rr_node, ss_distances, node_topo_inf, traversal_dir, max_path_weight, user_opts, (void*)&new_cutline_rec_structs, cutline_recursive_node_popped_func, cutline_recursive_child_iterated_func, cutline_recursive_traversal_done_func); /* resture this node's backed up info */ node_backup.restore(node_topo_inf); /* get adjusted demand of this node from passed-in new_cutline-rec_structs */ float prob_routable = new_cutline_rec_structs.prob_routable; if (prob_routable == UNDEFINED){ node_topo_inf[popped_node].set_node_smoothed(true); node_smoothed = true; } else { float popped_node_demand = get_node_demand_adjusted_for_path_history(popped_node, rr_node, cutline_rec_structs->source_ind, cutline_rec_structs->sink_ind, cutline_rec_structs->fill_type, user_opts); float adjusted_demand = or_two_probs(popped_node_demand, 1-prob_routable); node_topo_inf[popped_node].set_adjusted_demand( adjusted_demand ); } /* if node wasn't smoothed out as a result of the previous recursive traversal, then it is assigned a level */ if (!node_smoothed){ relative_level = relative_source_hops; } else { relative_level = UNDEFINED; } } } if (relative_level > 0){ /* if the node was assigned a relative level, push it onto the cutline probabilities structure */ //cout << "relative source hops: " << relative_source_hops << " relative_height: " << relative_height << endl; add_node_to_cutline_structure(popped_node, relative_level, cutline_rec_structs->cutline_rec_prob_struct); } if (cutline_rec_structs->recurse_level != 0 && popped_node != from_node_ind){ /* Recursion to higher recurse levels is meant to smooth out nodes. If a node is smoothed out here, it will remain smoothed out in the parent traversal, which is what we want */ node_topo_inf[popped_node].set_node_smoothed(true); } } } /* Called when topological traversal is iterateing over a node's children */ bool cutline_recursive_child_iterated_func(int parent_ind, int parent_edge_ind, int node_ind, t_rr_node &rr_node, t_ss_distances &ss_distances, t_node_topo_inf &node_topo_inf, e_traversal_dir traversal_dir, int max_path_weight, int from_node_ind, int to_node_ind, User_Options *user_opts, void *user_data){ Cutline_Recursive_Structs *cutline_rec_structs = (Cutline_Recursive_Structs*)user_data; bool ignore_node = false; /* check height/levels of children */ /* get node's height relative to root node of this traversal */ int node_height = get_node_height(ss_distances[node_ind]); int from_height = get_node_height(ss_distances[from_node_ind]); int relative_height = node_height - from_height; /* get node's source hops relative to root node of this traversal (this isn't necessarily the shortest number of hops from root to this node -- only an approximation) */ int node_source_hops = ss_distances[node_ind].get_source_hops(); int from_source_hops = ss_distances[from_node_ind].get_source_hops(); int relative_source_hops = node_source_hops - from_source_hops; //TODO: are these all correct? if (relative_source_hops < 0){ ignore_node = true; } if (relative_source_hops >= cutline_rec_structs->bound_source_hops){ ignore_node = true; } if (relative_height < 0){ ignore_node = true; } //node_topo_inf[node_ind].set_was_visited(true); /* backup node info if this is not the top-most level of recursion */ if (cutline_rec_structs->recurse_level > 0 && !ignore_node){ //TODO: problem. node info needs to be cleared before child traversal function looks at any node inf data... // but only thing child traversal checks is done_from_source/sink. I don't think a parent traversal // would set this value before a child traversal does, so should be OK... /* backup child node inf into a map if it's not already there */ t_topo_inf_backups &topo_inf_backups = cutline_rec_structs->topo_inf_backups; if (topo_inf_backups.count(node_ind) == 0){ /* first time encountering this node, it's not on the backups map yet */ Topo_Inf_Backup topo_inf_backup; topo_inf_backup.backup(node_ind, node_topo_inf); topo_inf_backups[node_ind] = topo_inf_backup; } /* now clear relevant data fields in the node_topo_inf structure (each recursive traversal need to start fresh) */ topo_inf_backups[node_ind].clear_node_topo_inf( node_topo_inf ); } return ignore_node; } /* Called once topological traversal is complete. Calculates probability of a source/sink connection being routable */ void cutline_recursive_traversal_done_func(int from_node_ind, int to_node_ind, t_rr_node &rr_node, t_ss_distances &ss_distances, t_node_topo_inf &node_topo_inf, e_traversal_dir traversal_dir, int max_path_weight, User_Options *user_opts, void *user_data){ /* compute probability that connection is routable. also restore backed-up node inf's */ Cutline_Recursive_Structs *cutline_rec_structs = (Cutline_Recursive_Structs*)user_data; float routable = connection_probability_cutlines(rr_node, cutline_rec_structs, node_topo_inf, cutline_rec_structs->topo_inf_backups, cutline_rec_structs->recurse_level, ss_distances, user_opts); cutline_rec_structs->prob_routable = routable; } /* returns height of node based on node's corresponding ss_distances */ static int get_node_height(SS_Distances &node_ss_distances){ int height; int source_hops = node_ss_distances.get_source_hops(); int sink_hops = node_ss_distances.get_sink_hops(); if (source_hops < 0 || sink_hops < 0){ height = UNDEFINED; //WTHROW(EX_PATH_ENUM, "Source hops or sink hops is < 0"); } else { height = source_hops + sink_hops; } return height; } /* returns true if specified node has legal parents (their source-hop number is smaller) at the specified height */ static bool has_parents_of_height(int node_ind, int height, t_rr_node &rr_node, t_ss_distances &ss_distances, e_traversal_dir traversal_dir, int max_path_weight){ bool result = false; int node_source_hops = ss_distances[node_ind].get_source_hops(); int *edge_list; int num_parents; /* want to iterate over parent nodes; this depends on direction of traversal */ if (traversal_dir == FORWARD_TRAVERSAL){ edge_list = rr_node[node_ind].in_edges; num_parents = rr_node[node_ind].get_num_in_edges(); } else { edge_list = rr_node[node_ind].out_edges; num_parents = rr_node[node_ind].get_num_out_edges(); } /* traverse all parents */ for (int inode = 0; inode < num_parents; inode++){ int parent_ind = edge_list[inode]; /* skip illegal parents */ int parent_weight = rr_node[parent_ind].get_weight(); if ( !ss_distances[parent_ind].is_legal(parent_weight, max_path_weight) ){ continue; } /* if this node has a lower source-hop number, then it can be considered a parent */ int parent_height = get_node_height( ss_distances[parent_ind]); if ( ss_distances[parent_ind].get_source_hops() < node_source_hops && parent_height == height){ result = true; break; } } return result; } /* adds specified node to the cutline probability structure according to the node's level in the topological traversal */ static void add_node_to_cutline_structure(int node_ind, int level, t_cutline_rec_prob_struct &cutline_probability_struct){ int num_cutlines = (int)cutline_probability_struct.size(); if (level >= num_cutlines){ //WTHROW(EX_PATH_ENUM, "Level of node with index " << node_ind << " exceeds number of cutline levels" << endl << // "num_cutlines: " << num_cutlines << " level: " << level << endl); //TODO: figure out how the above condition is possible! return; } if (level < 0){ WTHROW(EX_PATH_ENUM, "Level of node with index " << node_ind << " is less than 0: " << level); } /* put node onto the cutline structure according to its level */ //cout << " level: " << level << " num_cutlines: " << num_cutlines << endl; cutline_probability_struct[level].push_back(node_ind); } /* estimates probability that a source/dest connection can be made based on the cutline structure. returns UNDEFINED if any one of the levels is empty */ static float connection_probability_cutlines(t_rr_node &rr_node, Cutline_Recursive_Structs *cutline_rec_structs, t_node_topo_inf &node_topo_inf, t_topo_inf_backups &topo_inf_backups, int recursion_level, t_ss_distances &ss_distances, User_Options *user_opts){ t_cutline_rec_prob_struct &cutline_probability_struct = cutline_rec_structs->cutline_rec_prob_struct; float reachable = UNDEFINED; int num_levels = (int)cutline_probability_struct.size(); bool empty_level = false; float unreachable = 0; for (int ilevel = 1; ilevel < num_levels; ilevel++){ int num_nodes = (int)cutline_probability_struct[ilevel].size(); /* want to return UNDEFINED if any one level is empty */ if (num_nodes == 0){ empty_level = true; break; } /* AND probabilities of nodes on the same level */ float level_prob = 1; for (int inode = 0; inode < num_nodes; inode++){ int node_ind = cutline_probability_struct[ilevel][inode]; //commenting because a smoothing traversal smoothes nodes, but still assigns them a level ///* check that node wasn't smoothed-out */ //if (node_topo_inf[node_ind].get_node_smoothed()){ // WTHROW(EX_PATH_ENUM, "Node with index " << node_ind << " was assigned a level, but apparently is supposed to be smoothed out"); //} /* look at adjusted node demand (node may have been root of a recursed traversal */ float node_demand = node_topo_inf[node_ind].get_adjusted_demand(); if (node_demand == UNDEFINED){ node_demand = get_node_demand_adjusted_for_path_history(node_ind, rr_node, cutline_rec_structs->source_ind, cutline_rec_structs->sink_ind, cutline_rec_structs->fill_type, user_opts); } //cout << "node " << node_ind << " on cutline level " << ilevel << " demand: " << node_demand << endl; //cout << " source hops: " << ss_distances[node_ind].get_source_hops() << " sink hops: " << ss_distances[node_ind].get_sink_hops() << endl; /* bound probability that node is unavailable to 1 */ float node_unavailable = min(1.0F, node_demand); level_prob *= node_unavailable; /* restore this node's topo inf */ if (recursion_level > 0){ if (topo_inf_backups.count(node_ind) > 0){ topo_inf_backups[node_ind].restore( node_topo_inf ); } else { WTHROW(EX_PATH_ENUM, "Node with index " << node_ind << " was not backed up or appeared in more than one cutline level." << endl << "Recursion level: " << recursion_level); } } } /* OR probabilities of different levels being unavailable */ unreachable = or_two_probs(level_prob, unreachable); } if (!empty_level){ reachable = 1 - unreachable; } else { reachable = UNDEFINED; } return reachable; } /* backup topological node info */ void Topo_Inf_Backup::backup(int target_node_ind, t_node_topo_inf &node_topo_inf){ Node_Topological_Info &topo_inf = node_topo_inf[target_node_ind]; this->node_ind = target_node_ind; this->done_from_source = topo_inf.get_done_from_source(); this->done_from_sink = topo_inf.get_done_from_sink(); this->times_visited_from_source = topo_inf.get_times_visited_from_source(); this->times_visited_from_sink = topo_inf.get_times_visited_from_sink(); this->num_legal_in_nodes = topo_inf.get_num_legal_in_nodes(); this->num_legal_out_nodes = topo_inf.get_num_legal_out_nodes(); this->node_smoothed = topo_inf.get_node_smoothed(); this->node_waiting_info = topo_inf.node_waiting_info; } /* restore topological node info */ void Topo_Inf_Backup::restore(t_node_topo_inf &node_topo_inf){ Node_Topological_Info &topo_inf = node_topo_inf[this->node_ind]; topo_inf.set_done_from_source( this->done_from_source ); topo_inf.set_done_from_sink( this->done_from_sink ); topo_inf.set_times_visited_from_source( this->times_visited_from_source ); topo_inf.set_times_visited_from_sink( this->times_visited_from_sink ); topo_inf.set_num_legal_in_nodes( this->num_legal_in_nodes ); topo_inf.set_num_legal_out_nodes( this->num_legal_out_nodes ); topo_inf.set_node_smoothed( this->node_smoothed ); topo_inf.node_waiting_info = this->node_waiting_info; } /* clears relevant node_topo_inf structures (should be backed up before this is called */ void Topo_Inf_Backup::clear_node_topo_inf( t_node_topo_inf &node_topo_inf ){ Node_Topological_Info &topo_inf = node_topo_inf[this->node_ind]; topo_inf.set_done_from_source( false ); topo_inf.set_done_from_sink( false ); topo_inf.set_times_visited_from_source( 0 ); topo_inf.set_times_visited_from_sink( 0 ); topo_inf.set_num_legal_in_nodes( UNDEFINED ); topo_inf.set_num_legal_out_nodes( UNDEFINED ); topo_inf.set_node_smoothed( false ); topo_inf.node_waiting_info.clear(); }
44.267157
175
0.751177
shikc
ee2a690fd963aa1ffe4e4b037607ae19d3101de0
696
cpp
C++
srcV2/App.cpp
Platinum-Phoenix/Photorealistic
ecff2c6ae52686fffb4f6c7799e002f2898622c2
[ "MIT" ]
null
null
null
srcV2/App.cpp
Platinum-Phoenix/Photorealistic
ecff2c6ae52686fffb4f6c7799e002f2898622c2
[ "MIT" ]
null
null
null
srcV2/App.cpp
Platinum-Phoenix/Photorealistic
ecff2c6ae52686fffb4f6c7799e002f2898622c2
[ "MIT" ]
null
null
null
#include "App.hpp" App::App() : mWindow(nullptr), mIsRunning(true), mIo(nullptr) { } bool App::Init() { } void App::RunLoop() { while (mIsRunning) { ProcessInput(); Update(); } } void App::ProcessInput() { SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); switch (event.type) { case SDL_QUIT: mIsRunning = false; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(mWindow)) { mIsRunning = false; } } } }
17.846154
117
0.515805
Platinum-Phoenix
ee2ae08c38b3274545adff164e69987d0f27210f
6,008
cpp
C++
applic/domotica/source/P_Log.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
applic/domotica/source/P_Log.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
applic/domotica/source/P_Log.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//---------- P_Log.cpp ----------------------------------------------------- //---------------------------------------------------------------------------- #include "precHeader.h" //---------------------------------------------------------------------------- #include "P_Log.h" #include "pOwnBtnImageStd.h" #include "macro_utils.h" #include "base64.h" #include "p_param.h" #include "p_param_v.h" #include <richedit.h> //---------------------------------------------------------------------------- HINSTANCE hinstRichEdit; //---------------------------------------------------------------------------- #define YELLOW_COLOR RGB(0xff,0xff,0xcf) #define bkgColor YELLOW_COLOR //---------------------------------------------------------------------------- P_Log::P_Log(PConnBase* conn, PWin* parent, uint resId, HINSTANCE hinstance) : baseClass(conn, parent, resId, hinstance) { #define MAX_BMP SIZE_A(idBmp) int idBmp[] = { IDB_BITMAP_LOAD, IDB_BITMAP_CANC, IDB_BITMAP_DONE }; Bmp.setDim(MAX_BMP); for(uint i = 0; i < MAX_BMP; ++i) Bmp[i] = new PBitmap(idBmp[i], getHInstance()); new POwnBtnImageStd(this, IDC_BUTTON_LOAD, Bmp[0]); new POwnBtnImageStd(this, IDC_BUTTON_DELETE, Bmp[1]); new POwnBtnImageStd(this, IDCANCEL, Bmp[2]); hinstRichEdit = LoadLibrary(_T("RICHED32.DLL")); } //---------------------------------------------------------------------------- P_Log::~P_Log() { if(hinstRichEdit) { FreeLibrary(hinstRichEdit); hinstRichEdit = 0; } int nElem = Bmp.getElem(); for(int i = 0; i < nElem; ++i) delete Bmp[i]; } //---------------------------------------------------------------------------- //static enum eFile { eL_Email = 1, eL_Access, eL_Alarm }; //---------------------------------------------------------------------------- int P_Log::getCurrSel() { if(IS_CHECKED(IDC_RADIO_EMAIL)) return 1; if(IS_CHECKED(IDC_RADIO_ACCESS)) return 2; if(IS_CHECKED(IDC_RADIO_ALARM)) return 3; return 0; } //---------------------------------------------------------------------------- static bool confirmDelete(PWin* w) { return IDYES == MessageBox(*w, _T("Do you confirm deleting the log file?"), _T("Log management"), MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING); } //---------------------------------------------------------------------------- void P_Log::loadLog() { clearReceived(); char buff[256] = ""; int ix = getCurrSel(); if(!ix) return; wsprintfA(buff, "cmd=showlog:%d#", ix); connSend cs(Conn); cs.send(buff, strlen(buff)); } //---------------------------------------------------------------------------- void P_Log::delLog() { if(!confirmDelete(this)) return; clearReceived(); char buff[256] = ""; int ix = getCurrSel(); if(!ix) return; wsprintfA(buff, "cmd=remlog:%d#", ix); connSend cs(Conn); cs.send(buff, strlen(buff)); } //---------------------------------------------------------------------------- bool P_Log::create() { if(!baseClass::create()) return false; Conn->passThrough(cReset, 0); HWND hwnd = GetDlgItem(*this, IDC_EDIT_REC); SendMessage(hwnd, EM_SETTEXTMODE, TM_PLAINTEXT, 0); LONG style = GetWindowLong(hwnd, GWL_STYLE); SetWindowLong(hwnd, GWL_STYLE, (style & ~(WS_SIZEBOX)) | WS_BORDER); SET_CHECK(IDC_RADIO_EMAIL); return true; } //---------------------------------------------------------------------------- LRESULT P_Log::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDCANCEL: EndDialog(hwnd, LOWORD(wParam)); return 0; case IDC_BUTTON_LOAD: loadLog(); break; case IDC_BUTTON_DELETE: delLog(); break; } } return baseClass::windowProc(hwnd, message, wParam, lParam); } //---------------------------------------------------------------------------- void P_Log::clearReceived() { HWND ctrl = GetDlgItem(*this, IDC_EDIT_REC); SendMessage(ctrl, WM_SETTEXT, 0, 0); InvalidateRect(ctrl, 0, 1); } //---------------------------------------------------------------------------- void P_Log::readConn(WORD ) { static bool inExec; if(inExec) return; inExec = true; #define SIZE_READ (512 * 2) BYTE buff[SIZE_READ]; Conn->reqNotify(false); HWND ctrl = GetDlgItem(*this, IDC_EDIT_REC); while(true) { if(!Conn) break; int avail = Conn->has_string(); if(!avail) break; Sleep(100); avail = Conn->has_string(); avail = min(SIZE_READ -1, avail); Conn->read_string(buff, avail); buff[avail] = 0; int currLen = SendMessage(ctrl, WM_GETTEXTLENGTH, 0, 0); SendMessage(ctrl, EM_SETSEL, currLen, currLen); performShowChar(ctrl, buff, avail); SendMessage(ctrl, EM_SCROLLCARET, 0, 0); getAppl()->pumpMessages(); Sleep(0); } InvalidateRect(ctrl, 0, false); if(Conn) { if(Conn->has_string()) PostMessage(*this, WM_CUSTOM_MSG_CONNECTION, MAKEWPARAM(CM_MSG_HAS_CHAR, 1), 0); else Conn->reqNotify(true); } inExec = false; } //---------------------------------------------------------------------------- #define MAX_COUNT 50 //---------------------------------------------------------------------------- void P_Log::performShowChar(HWND ctrl, const BYTE* buff, int avail) { const BYTE* base = buff; DWORD count = 0; CHARRANGE range = { 0x7ffffff, 0x7ffffff }; LPCBYTE pb = buff; int len = strlen((LPCSTR)buff); while(true) { SendMessageA(ctrl, EM_REPLACESEL, 0, (LPARAM)buff); avail -= len + 1; getAppl()->pumpMessages(); if(avail <= 0) break; SendMessage(ctrl, EM_EXSETSEL, 0, (LPARAM)&range); SendMessage(ctrl, EM_REPLACESEL, 0, (LPARAM)_T(".")); SendMessage(ctrl, EM_EXSETSEL, 0, (LPARAM)&range); buff += len + 1; if(!len && ++count < MAX_COUNT) continue; count = 0; getAppl()->pumpMessages(); } } //----------------------------------------------------------------------------
30.969072
143
0.490513
NPaolini
ee2bcd5f2fc82d6330ee1fde5ceaec256c23ea00
656
cpp
C++
363B.cpp
AdithyaViswanathan/Codeforces
4f045759227845ced165dfae5763ce76cdca852d
[ "MIT" ]
null
null
null
363B.cpp
AdithyaViswanathan/Codeforces
4f045759227845ced165dfae5763ce76cdca852d
[ "MIT" ]
null
null
null
363B.cpp
AdithyaViswanathan/Codeforces
4f045759227845ced165dfae5763ce76cdca852d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long void solve() { ll n,k,temp,mini=INT_MAX,ind=0; vector<ll>a,b; cin>>n>>k; for(int i=0;i<n;i++) cin>>temp,a.push_back(temp); temp = 0; for(int i=0;i<n;i++) { if(i==0) b.push_back(a[i]); else b.push_back(a[i]+b[i-1]); } mini = b[k-1]; for(int i=0;i<n-k;i++) { temp = b[i+k]-b[i]; // cout<<temp<<endl; mini = min(mini,temp); if(mini == temp) ind = i+1; } cout<<ind+1<<endl; } int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); long testcase = 1; //cin >> testcase ; while(testcase--) solve(); return 0; }
15.255814
38
0.550305
AdithyaViswanathan
ee2be0141fd9835306f0c61b0bfc32ec7de181f5
2,369
cpp
C++
A1718/1718Redundant Paths.cpp
instr3/BZOJ-solution-legacy
a71f7df2241602ad744e8ca2453a8423590d5678
[ "MIT" ]
null
null
null
A1718/1718Redundant Paths.cpp
instr3/BZOJ-solution-legacy
a71f7df2241602ad744e8ca2453a8423590d5678
[ "MIT" ]
null
null
null
A1718/1718Redundant Paths.cpp
instr3/BZOJ-solution-legacy
a71f7df2241602ad744e8ca2453a8423590d5678
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> //#include <cmath> #include <algorithm> using namespace std; #define each(i,n) (int i=1;i<=(n);++i) struct enode{int to,fr,next;int mk;}mye[100001]; struct vnode{int first;}myv[100001]; int n,nm; int idex; int dnf[100001]; int low[100001]; bool visit[100001]; int stk[100001];int pstk; int tnewv[100001]; int tcn[100001]; void dfs(int iv) { dnf[iv]=low[iv]=++idex; //cout<<iv<<":"<<idex<<endl; visit[iv]=true; int pt; for (int p=myv[iv].first;p;p=mye[p].next) { pt=mye[p].to; if(!visit[pt]) { mye[p].mk=1; mye[p^1].mk=1; dfs(pt); low[iv]=min(low[iv],low[pt]); } else { if(!mye[p].mk) { low[iv]=min(low[iv],dnf[pt]); } } } } void dfs2(int iv) { visit[iv]=true; tnewv[iv]=idex; int pt; for (int p=myv[iv].first;p;p=mye[p].next) { if(mye[p].mk==9)continue; pt=mye[p].to; if(!visit[pt]) { dfs2(pt); } } } int main() { freopen("1718.in","r",stdin); freopen("1718.out","w",stdout); scanf("%d%d",&n,&nm); int pf,pt; for(int i=1,j=1;i<=nm;++i) { scanf("%d%d",&pf,&pt); mye[++j].to=pt; mye[j].fr=pf; mye[j].next=myv[pf].first; myv[pf].first=j; mye[++j].to=pf; mye[j].fr=pt; mye[j].next=myv[pt].first; myv[pt].first=j; } dfs(1); for each(j,nm*2+1) { pf=mye[j].fr; pt=mye[j].to; if(mye[j].mk) { if(dnf[pf]<low[pt]) { mye[j].mk=9; mye[j^1].mk=9; //cout<<pf<<"->"<<pt<<"Goto (9)"<<endl; } } } memset(visit,0,sizeof(visit)); idex=0; for each(i,n) { if(!visit[i]) { idex++; dfs2(i); } } for each(j,nm*2+1) { if(mye[j].mk==9) { //cout<<mye[j].to<<"->"<<tnewv[mye[j].to]<<"++"<<endl; tcn[tnewv[mye[j].to]]++; } } int tot=0; for each(i,idex) { if(tcn[i]==1)++tot; if(tcn[i]==0)tot+=2; } if(idex==1)cout<<0<<endl;else cout<<(tot+1)/2<<endl; }
19.741667
66
0.425074
instr3
0c54580a55fe4f7cdb0d876e24ca775a36468df8
558
hpp
C++
FW/src/Drivers/Button.hpp
abbeman/BCD-watch
56a9d86c1266c28456a0ee8a8ff4be62cb39f654
[ "MIT" ]
1
2019-11-09T18:36:42.000Z
2019-11-09T18:36:42.000Z
FW/src/Drivers/Button.hpp
abbeman/BCD-watch
56a9d86c1266c28456a0ee8a8ff4be62cb39f654
[ "MIT" ]
9
2019-11-08T21:35:07.000Z
2020-01-16T22:17:53.000Z
FW/src/Drivers/Button.hpp
abbeman/BCD-watch
56a9d86c1266c28456a0ee8a8ff4be62cb39f654
[ "MIT" ]
1
2020-01-14T19:17:53.000Z
2020-01-14T19:17:53.000Z
#ifndef _BUTTON_HPP #define _BUTTON_HPP #include "GPIO.hpp" #include "stdint.h" #include "stdbool.h" #include "Events.hpp" #include "Task.hpp" #include "Queue.hpp" namespace Button { class PushButton : public FreeRTOS::Task<256> { public: PushButton(GPIO::Pin *pin, FreeRTOS::Queue<Events, EventQueueLength> *eventQueue); void Run() override; private: GPIO::Pin *m_pin; FreeRTOS::Queue<Events, EventQueueLength> *m_eventQueue; static constexpr uint32_t ButtonPeriodMilliseconds = 100; }; } #endif
21.461538
90
0.681004
abbeman
0c575fcb114523fe367b5a3aff46e31a408c3d0e
256
cpp
C++
CommonGame/Displayable.cpp
krynetix/pspace
5719d02f302783cc3675876ad10b87a1bb031399
[ "BSD-3-Clause" ]
null
null
null
CommonGame/Displayable.cpp
krynetix/pspace
5719d02f302783cc3675876ad10b87a1bb031399
[ "BSD-3-Clause" ]
null
null
null
CommonGame/Displayable.cpp
krynetix/pspace
5719d02f302783cc3675876ad10b87a1bb031399
[ "BSD-3-Clause" ]
null
null
null
#include "Displayable.h" Displayable::Displayable() /*: displayId(-1)*/ { } Displayable::~Displayable() { } /*void Displayable::setDisplayID(int id) { displayId = id; } int Displayable::getDisplayID() const { return displayId; }*/
12.8
41
0.632813
krynetix
0c57c617110143e360f4edf443bec14eceddc5ac
4,357
cpp
C++
digitanks/src/dtintro/intro_renderer.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
5
2015-07-03T18:42:32.000Z
2017-08-25T10:28:12.000Z
digitanks/src/dtintro/intro_renderer.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
digitanks/src/dtintro/intro_renderer.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
#include "intro_renderer.h" #include <mtrand.h> #include <tinker/application.h> #include <tinker/cvar.h> #include <textures/materiallibrary.h> #include <game/gameserver.h> #include <renderer/shaders.h> #include <renderer/game_renderingcontext.h> #include "intro_window.h" CIntroRenderer::CIntroRenderer() : CGameRenderer(CApplication::Get()->GetWindowWidth(), CApplication::Get()->GetWindowHeight()) { m_flLayer1Speed = -RandomFloat(0.1f, 0.5f); m_flLayer2Speed = -RandomFloat(0.1f, 0.5f); m_flLayer3Speed = -RandomFloat(0.1f, 0.5f); m_flLayer4Speed = -RandomFloat(0.1f, 0.5f); m_flLayer5Speed = -RandomFloat(0.1f, 0.5f); m_flLayer1Alpha = RandomFloat(0.2f, 1); m_flLayer2Alpha = RandomFloat(0.2f, 1); m_flLayer3Alpha = RandomFloat(0.2f, 1); m_flLayer4Alpha = RandomFloat(0.2f, 1); m_flLayer5Alpha = RandomFloat(0.2f, 1); m_bRenderOrthographic = true; } #define FRUSTUM_NEAR 0 #define FRUSTUM_FAR 1 #define FRUSTUM_LEFT 2 #define FRUSTUM_RIGHT 3 #define FRUSTUM_UP 4 #define FRUSTUM_DOWN 5 CVar cam_free_ortho("cam_free_ortho", "off"); void CIntroRenderer::Initialize() { BaseClass::Initialize(); m_hBackdrop = CMaterialLibrary::AddMaterial("textures/intro/backdrop.mat"); m_bDrawBackground = true; CVar::SetCVar("r_bloom", 0.7f); } void CIntroRenderer::StartRendering(class CRenderingContext* pContext) { BaseClass::StartRendering(pContext); RenderBackdrop(); } void CIntroRenderer::RenderBackdrop() { float flWidth = (float)CApplication::Get()->GetWindowWidth(); { CGameRenderingContext c(this, true); c.UseMaterial(m_hBackdrop); c.UseProgram("scroll"); c.SetUniform("flTime", (float)GameServer()->GetGameTime()); c.SetBlend(BLEND_ADDITIVE); c.SetDepthTest(false); c.SetUniform("flAlpha", m_flLayer1Alpha); c.SetUniform("flSpeed", m_flLayer1Speed); c.SetUniform("vecColor", Color(100, 255, 100, 255)); c.BeginRenderTriFan(); c.TexCoord(Vector(-0.2f, 0, 0)); c.Vertex(Vector(-100, -flWidth/2, -flWidth/2)); c.TexCoord(Vector(1.8f, 0, 0)); c.Vertex(Vector(-100, flWidth/2, -flWidth/2)); c.TexCoord(Vector(1.8f, 2, 0)); c.Vertex(Vector(-100, flWidth/2, flWidth/2)); c.TexCoord(Vector(-0.2f, 2, 0)); c.Vertex(Vector(-100, -flWidth/2, flWidth/2)); c.EndRender(); c.SetUniform("flAlpha", m_flLayer2Alpha); c.SetUniform("flSpeed", m_flLayer2Speed); c.SetUniform("vecColor", Color(0, 255, 0, 255)); c.BeginRenderTriFan(); c.TexCoord(Vector(-0.5f, -0.5f, 0)); c.Vertex(Vector(-200, -flWidth/2, -flWidth/2)); c.TexCoord(Vector(1.5f, -0.5f, 0)); c.Vertex(Vector(-200, flWidth/2, -flWidth/2)); c.TexCoord(Vector(1.5f, 1.5f, 0)); c.Vertex(Vector(-200, flWidth/2, flWidth/2)); c.TexCoord(Vector(-0.5f, 1.5f, 0)); c.Vertex(Vector(-200, -flWidth/2, flWidth/2)); c.EndRender(); c.SetUniform("flAlpha", m_flLayer3Alpha); c.SetUniform("flSpeed", m_flLayer3Speed); c.SetUniform("vecColor", Color(55, 255, 55, 155)); c.BeginRenderTriFan(); c.TexCoord(Vector(-2.5f, -2.5f, 0)); c.Vertex(Vector(-300, -flWidth/2, -flWidth/2)); c.TexCoord(Vector(1, -2.5f, 0)); c.Vertex(Vector(-300, flWidth/2, -flWidth/2)); c.TexCoord(Vector(1, 1, 0)); c.Vertex(Vector(-300, flWidth/2, flWidth/2)); c.TexCoord(Vector(-2.5f, 1, 0)); c.Vertex(Vector(-300, -flWidth/2, flWidth/2)); c.EndRender(); c.SetUniform("flAlpha", m_flLayer4Alpha); c.SetUniform("flSpeed", m_flLayer4Speed); c.SetUniform("vecColor", Color(100, 255, 100, 205)); c.BeginRenderTriFan(); c.TexCoord(Vector(0.4f, 0.5f, 0)); c.Vertex(Vector(-400, -flWidth/2, -flWidth/2)); c.TexCoord(Vector(2.4f, 0.5f, 0)); c.Vertex(Vector(-400, flWidth/2, -flWidth/2)); c.TexCoord(Vector(2.4f, 2.5f, 0)); c.Vertex(Vector(-400, flWidth/2, flWidth/2)); c.TexCoord(Vector(0.4f, 2.5f, 0)); c.Vertex(Vector(-400, -flWidth/2, flWidth/2)); c.EndRender(); c.SetUniform("flAlpha", m_flLayer5Alpha); c.SetUniform("flSpeed", m_flLayer5Speed); c.SetUniform("vecColor", Color(55, 255, 55, 120)); c.BeginRenderTriFan(); c.TexCoord(Vector(-.1f, 0.2f, 0)); c.Vertex(Vector(-500, -flWidth/2, -flWidth/2)); c.TexCoord(Vector(0.9f, 0.2f, 0)); c.Vertex(Vector(-500, flWidth/2, -flWidth/2)); c.TexCoord(Vector(0.9f, 1.2f, 0)); c.Vertex(Vector(-500, flWidth/2, flWidth/2)); c.TexCoord(Vector(-.1f, 1.2f, 0)); c.Vertex(Vector(-500, -flWidth/2, flWidth/2)); c.EndRender(); } }
29.241611
95
0.685793
BSVino
0c58b44fb8fe0f2e2a28151071651319dd48328a
733
cpp
C++
sphinx/cpp_tutorial/tutorial.cpp
sbrisard/pw85
515da5a74002c956c9e12b4918659a51b92eca37
[ "BSD-3-Clause" ]
null
null
null
sphinx/cpp_tutorial/tutorial.cpp
sbrisard/pw85
515da5a74002c956c9e12b4918659a51b92eca37
[ "BSD-3-Clause" ]
19
2018-08-02T07:15:25.000Z
2021-05-24T04:52:38.000Z
docs/_downloads/c2b7b2965f34e12a0073f1577700ca31/tutorial.cpp
sbrisard/pw85
515da5a74002c956c9e12b4918659a51b92eca37
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <array> #include "pw85/pw85.hpp" using Vec = std::array<double, pw85::dim>; using SymMat = std::array<double, pw85::sym>; int main() { Vec x1{-0.5, 0.4, -0.7}; Vec n1{0., 0., 1.}; double a1 = 10.; double c1 = 0.1; Vec x2{0.2, -0.3, 0.4}; Vec n2{1., 0., 0.}; double a2 = 0.5; double c2 = 5.; Vec r12; for (int i = 0; i < pw85::dim; i++) r12[i] = x2[i] - x1[i]; SymMat q1, q2; pw85::spheroid(a1, c1, n1.data(), q1.data()); pw85::spheroid(a2, c2, n2.data(), q2.data()); std::array<double, 2> out; pw85::contact_function(r12.data(), q1.data(), q2.data(), out.data()); std::cout << "mu^2 = " << out[0] << std::endl; std::cout << "lambda = " << out[1] << std::endl; }
22.90625
71
0.542974
sbrisard
0c59fb7a666dc51c30814a95512a19aafdaca22c
999
cpp
C++
Basic_Algorithms/Calculadora de Matrizes.cpp
Isaquehg/algorithms_and_data_structures
7062a6d9564dfcca35e4692ad864b4c48a279d3f
[ "MIT" ]
null
null
null
Basic_Algorithms/Calculadora de Matrizes.cpp
Isaquehg/algorithms_and_data_structures
7062a6d9564dfcca35e4692ad864b4c48a279d3f
[ "MIT" ]
null
null
null
Basic_Algorithms/Calculadora de Matrizes.cpp
Isaquehg/algorithms_and_data_structures
7062a6d9564dfcca35e4692ad864b4c48a279d3f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int mat[100][100];//matriz 2x2 int transposta[100][100];//matriz transposta int determinante;//determinante da matriz int l, c;//contadores //input for(l = 0; l < 2; l ++){ for(c = 0; c < 2; c ++) cin >> mat[l][c]; } //calculo determinante determinante = (mat[0][0] * mat[1][1]) - (mat[0][1] * mat[1][0]); //transpondo for(c = 0; c < 2; c ++){ for(l = 0; l < 2; l ++) transposta[c][l] = mat[l][c]; } //output //matriz cout << "M:" << endl; for(l = 0; l < 2; l ++){ for(c = 0; c < 2; c ++) cout << mat[l][c] << " "; cout << endl; } //transposta cout << "M transposta:" << endl; for(c = 0; c < 2; c ++){ for(l = 0; l < 2; l ++) cout << transposta[c][l] << " "; cout << endl; } //determinante cout << "Determinante: " << determinante << endl; return 0; }
24.365854
69
0.442442
Isaquehg
0c5b2859c83d8742475838aa5d809fed84400b3e
283
hpp
C++
src/util/string_utils.hpp
TobiasNienhaus/npp
ff6023ad5c160240cbaa029dce065b2cdf58ae74
[ "MIT" ]
null
null
null
src/util/string_utils.hpp
TobiasNienhaus/npp
ff6023ad5c160240cbaa029dce065b2cdf58ae74
[ "MIT" ]
null
null
null
src/util/string_utils.hpp
TobiasNienhaus/npp
ff6023ad5c160240cbaa029dce065b2cdf58ae74
[ "MIT" ]
null
null
null
// // Created by Tobias on 1/21/2021. // #ifndef NPP_STRING_UTILS_HPP #define NPP_STRING_UTILS_HPP #include <string> namespace npp::str_util { std::string wstr_to_str(const std::wstring &wstr); std::wstring str_to_wstr(const std::string &str); } #endif // NPP_STRING_UTILS_HPP
15.722222
50
0.745583
TobiasNienhaus
0c6ac7c6fbffc464e54b6036e7d2e66ec46aadb1
64,064
cpp
C++
WRK-V1.2/csharp/sccomp/typebind.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/csharp/sccomp/typebind.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
WRK-V1.2/csharp/sccomp/typebind.cpp
intj-t/openvmsft
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
[ "Intel" ]
null
null
null
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== // =========================================================================== // File: typebind.cpp // // Type lookup and binding. // =========================================================================== #include "stdafx.h" /*************************************************************************************************** Initialize the TypeBind instance. ***************************************************************************************************/ void TypeBind::Init(COMPILER * cmp, SYM * symCtx, SYM * symStart, SYM * symAccess, SYM * symTypeVars, TypeBindFlagsEnum flags) { // symAccess may be NULL (indicating that only publics are accessible). ASSERT(cmp && symCtx && symStart); ASSERT(!symTypeVars || symTypeVars->isMETHSYM() || symTypeVars->isAGGSYM()); m_cmp = cmp; m_symCtx = symCtx; m_symStart = symStart; m_symAccess = symAccess; m_symTypeVars = symTypeVars; m_flags = flags; m_fUsingAlias = false; DebugOnly(m_fValid = true); // In define members or before, we shouldn't check deprecated. if (cmp->AggStateMax() < AggState::Prepared) m_flags = m_flags | TypeBindFlags::NoDeprecated; } /*************************************************************************************************** Bind a dotted name, a single name (generic or not), or an alias qualified name. ***************************************************************************************************/ SYM * TypeBind::BindNameCore(BASENODE * node) { ASSERT(m_fValid); ASSERT(node); switch (node->kind) { case NK_DOT: return BindDottedNameCore(node->asANYBINOP(), node->asANYBINOP()->p2->asANYNAME()->pName); case NK_NAME: case NK_GENERICNAME: case NK_OPENNAME: return BindSingleNameCore(node->asANYNAME(), node->asANYNAME()->pName); case NK_ALIASNAME: return BindAliasNameCore(node->asALIASNAME()); default: VSFAIL("Bad node kind in BindNameCore"); return NULL; } } /*************************************************************************************************** Bind a dotted name or a single name (generic or not). This is only called by BindAttributeTypeCore so it doesn't need to deal with OPENNAME and ALIASNAME. ***************************************************************************************************/ SYM * TypeBind::BindNameCore(BASENODE * node, NAME * name) { ASSERT(m_fValid); ASSERT(name); switch (node->kind) { case NK_DOT: return BindDottedNameCore(node->asANYBINOP(), name); case NK_NAME: case NK_GENERICNAME: return BindSingleNameCore(node->asANYNAME(), name); default: VSFAIL("Bad node kind in BindNameCore"); return NULL; } } /*************************************************************************************************** Bind a dotted name, a single name (generic or not), or an alias qualified name (A::B<...>) to a type. ***************************************************************************************************/ TYPESYM * TypeBind::BindNameToTypeCore(BASENODE * node) { ASSERT(m_fValid); ASSERT(node); SYM * sym; switch (node->kind) { case NK_DOT: sym = BindDottedNameCore(node->asANYBINOP(), node->asANYBINOP()->p2->asANYNAME()->pName); if (sym != NULL && sym->isTYPESYM() && !sym->isERRORSYM() && compiler()->compileCallback.CheckForNameSimplification()) { if (sym->asTYPESYM()->isPredefined() && predefTypeInfo[sym->asTYPESYM()->getPredefType()].niceName != NULL) { compiler()->compileCallback.CanSimplifyNameToPredefinedType(m_symCtx->getInputFile()->pData, node, sym->asTYPESYM()); } else { NAMENODE* pLastName = node->asANYBINOP()->p2->asANYNAME(); if (sym == BindSingleNameCore(pLastName, pLastName->pName)) { compiler()->compileCallback.CanSimplifyName(m_symCtx->getInputFile()->pData, node->asDOT()); } } } break; case NK_NAME: case NK_OPENNAME: case NK_GENERICNAME: sym = BindSingleNameCore(node->asANYNAME(), node->asANYNAME()->pName); if (sym != NULL && sym->isTYPESYM() && !sym->isERRORSYM() && sym->asTYPESYM()->isPredefined() && compiler()->compileCallback.CheckForNameSimplification()) { compiler()->compileCallback.CanSimplifyNameToPredefinedType(m_symCtx->getInputFile()->pData, node, sym->asTYPESYM()); } break; case NK_ALIASNAME: sym = BindAliasNameCore(node->asALIASNAME()); break; default: VSFAIL("Bad node kind in BindNameToTypeCore"); return NULL; } ASSERT(sym || FAllowMissing()); if (!sym || sym->isTYPESYM()) return sym->asTYPESYM(); ASSERT(sym->isNSAIDSYM()); if (!FSuppressErrors()) compiler()->Error(node, ERR_BadSKknown, sym, ErrArgSymKind(sym), SK_AGGSYM); // Construct the error sym. switch (node->kind) { default: VSFAIL("Unexpected node kind in BindNameToTypeCore"); case NK_DOT: break; case NK_NAME: case NK_ALIASNAME: return compiler()->getBSymmgr().GetErrorType(NULL, node->asSingleName()->pName, NULL); } // Construct the parent NSAIDSYM. NSAIDSYM * nsa = sym->asNSAIDSYM(); ASSERT(nsa->GetNS()->Parent()); NSAIDSYM * nsaPar = compiler()->getBSymmgr().GetNsAid(nsa->GetNS()->Parent(), nsa->GetAid()); return compiler()->getBSymmgr().GetErrorType(nsaPar, nsa->GetNS()->name, NULL); } /*************************************************************************************************** Bind a single name (generic or not). ***************************************************************************************************/ SYM * TypeBind::BindSingleNameCore(NAMENODE * node, NAME * name, TypeArray * typeArgs) { ASSERT(m_fValid); ASSERT(node); SYM * sym; if (!typeArgs) typeArgs = BindTypeArgsCore(node); ASSERT(typeArgs); ClearErrorInfo(); if (m_fUsingAlias) { // We're binding a using alias. ASSERT(m_symStart->isNSDECLSYM()); ASSERT(!m_symTypeVars); NSDECLSYM * nsd = m_symStart->asNSDECLSYM(); sym = SearchNamespacesCore(nsd, node, name, typeArgs); } else { sym = NULL; SYM * symSearch = m_symStart; SYM * symTypeVars = m_symTypeVars; if ((m_flags & TypeBindFlags::CallPreHook) && (sym = PreLookup(name, typeArgs)) != NULL) goto LDone; // Search the type variables in the method if (symSearch->isMETHSYM()) { ASSERT(!symTypeVars || symTypeVars == symSearch); symTypeVars = symSearch; symSearch = symSearch->asMETHSYM()->declaration; } // check for type parameters while resolving base types, where clauses, XML comments, etc. if (symTypeVars && (sym = SearchTypeVarsCore(symTypeVars, name, typeArgs)) != NULL) goto LDone; // search class if (symSearch->isAGGDECLSYM()) { AGGSYM * agg = symSearch->asAGGDECLSYM()->Agg(); // Include outer types and type vars. if ((sym = SearchClassCore(agg->getThisType(), name, typeArgs, true)) != NULL) goto LDone; } while (!symSearch->isNSDECLSYM()) { symSearch = symSearch->containingDeclaration(); } sym = SearchNamespacesCore(symSearch->asNSDECLSYM(), node, name, typeArgs); } LDone: ReportErrors(node, name, NULL, typeArgs, &sym); return sym; } /*************************************************************************************************** Bind the alias name. Returns an NSAIDSYM or AGGTYPESYM (the latter only after reporting an error). Doesn't call ClearErrorInfo or ReportErrors. ***************************************************************************************************/ SYM * TypeBind::BindAliasNameCore(NAMENODE * node) { ASSERT(m_fValid); ASSERT(node->kind == NK_ALIASNAME && node->pName); SYM * sym; NAME * name = node->pName; if (node->flags & NF_GLOBAL_QUALIFIER) { sym = compiler()->getBSymmgr().GetGlobalNsAid(); return sym; } SYM * symSearch = m_symStart; while (!symSearch->isNSDECLSYM()) symSearch = symSearch->containingDeclaration(); for (NSDECLSYM * nsd = symSearch->asNSDECLSYM(); nsd; nsd = nsd->DeclPar()) { // Check the using aliases. compiler()->clsDeclRec.ensureUsingClausesAreResolved(nsd); FOREACHSYMLIST(nsd->usingClauses, symUse, SYM) if (symUse->name != name || !symUse->isALIASSYM() || !FAliasAvailable(symUse->asALIASSYM())) continue; sym = BindUsingAlias(compiler(), symUse->asALIASSYM()); if (!sym) continue; //Found something within this using. it is not "unused" compiler()->compileCallback.BoundToUsing(nsd, symUse); switch (sym->getKind()) { case SK_ERRORSYM: return sym; case SK_NSAIDSYM: return sym; case SK_AGGTYPESYM: // Should have used . not :: if (FSuppressErrors()) return compiler()->getBSymmgr().GetErrorType(NULL, name, NULL); // Can't use type aliases with ::. compiler()->ErrorRef(node, ERR_ColColWithTypeAlias, symUse->asALIASSYM()); return sym; default: VSFAIL("Alias resolved to bad kind"); break; } ENDFOREACHSYMLIST } if (FAllowMissing()) return NULL; if (!FSuppressErrors()) compiler()->Error(node, ERR_AliasNotFound, name); sym = compiler()->getBSymmgr().GetErrorType(NULL, name, NULL); return sym; } /*************************************************************************************************** Bind the type arguments on a generic name. ***************************************************************************************************/ TypeArray * TypeBind::BindTypeArgsCore(NAMENODE * node) { ASSERT(m_fValid); int ctype; bool fUnit; switch (node->kind) { default: return BSYMMGR::EmptyTypeArray(); case NK_GENERICNAME: ctype = CountListNode(node->asGENERICNAME()->pParams); fUnit = false; break; case NK_OPENNAME: ctype = node->asOPENNAME()->carg; fUnit = true; break; } ASSERT(ctype > 0); TYPESYM ** prgtype = STACK_ALLOC(TYPESYM *, ctype); if (fUnit) { TYPESYM * typeUnit = compiler()->getBSymmgr().GetUnitType(); for (int itype = 0; itype < ctype; itype++) prgtype[itype] = typeUnit; } else { // Turn off AllowMissing when binding type parameters. TypeBindFlagsEnum flagsOrig = m_flags; m_flags = m_flags & ~TypeBindFlags::AllowMissing; int itype = 0; NODELOOP(node->asGENERICNAME()->pParams, TYPEBASE, arg) // bind the type, and wrap it if the variable is byref TYPESYM * type = BindTypeCore(arg); ASSERT(type); prgtype[itype++] = type; ENDLOOP; ASSERT(itype == ctype); m_flags = flagsOrig; } // get the formal (and unique) param array for the given types... return compiler()->getBSymmgr().AllocParams(ctype, prgtype); } /*************************************************************************************************** Bind a dotted name. ***************************************************************************************************/ SYM * TypeBind::BindDottedNameCore(BINOPNODE * node, NAME * name) { ASSERT(m_fValid); ASSERT(node && node->kind == NK_DOT); SYM * symLeft = BindNameCore(node->p1); if (!symLeft) return NULL; return BindRightSideCore(symLeft, node, node->p2->asANYNAME(), name); } /*************************************************************************************************** Bind the right identifier of a dotted name. ***************************************************************************************************/ SYM * TypeBind::BindRightSideCore(SYM * symLeft, BASENODE * nodePar, NAMENODE * nodeName, NAME * name, TypeArray * typeArgs) { ASSERT(m_fValid); if (!typeArgs) typeArgs = BindTypeArgsCore(nodeName); ASSERT(typeArgs); ClearErrorInfo(); SYM * sym; switch (symLeft->getKind()) { case SK_ERRORSYM: sym = compiler()->getBSymmgr().GetErrorType(symLeft->asERRORSYM(), name, typeArgs); break; case SK_NUBSYM: symLeft = symLeft->asNUBSYM()->GetAts(); // The parser shouldn't allo T?.x - only Nullable<T>.x - so we know Nullable // exists. ASSERT(symLeft); ASSERT(symLeft->isAGGTYPESYM()); // Fall through. case SK_AGGTYPESYM: { AGGTYPESYM * ats = symLeft->asAGGTYPESYM(); sym = SearchClassCore(ats, name, typeArgs, false); // no outer and no type vars } break; case SK_NSAIDSYM: sym = SearchSingleNamespaceCore(symLeft->asNSAIDSYM(), nodeName, name, typeArgs); break; case SK_TYVARSYM: // Can't lookup in a type variable. if (!FSuppressErrors()) compiler()->Error(nodePar, ERR_LookupInTypeVariable, symLeft); // Note: don't fall through and report more errors sym = compiler()->getBSymmgr().GetErrorType(symLeft->asPARENTSYM(), name, typeArgs); return sym; default: VSFAIL("Bad symbol kind in BindRightSideCore"); return NULL; } ReportErrors(nodeName, name, symLeft, typeArgs, &sym); return sym; } /*************************************************************************************************** Bind a TYPEBASENODE to a type. ***************************************************************************************************/ TYPESYM * TypeBind::BindTypeCore(TYPEBASENODE * node) { ASSERT(m_fValid); TYPESYM * type; switch (node->kind) { case NK_PREDEFINEDTYPE: if (node->asPREDEFINEDTYPE()->iType == PT_VOID) type = compiler()->getBSymmgr().GetVoid(); else { PREDEFTYPE pt = (PREDEFTYPE)node->asPREDEFINEDTYPE()->iType; type = compiler()->GetOptPredefType(pt, false); if (!type) { // If decimal is missing we'll get here. Use the nice name in the error symbol. if (!FSuppressErrors()) compiler()->getBSymmgr().ReportMissingPredefTypeError(pt); NAME * name = compiler()->namemgr->LookupString(compiler()->getBSymmgr().GetNiceName(pt)); type = compiler()->getBSymmgr().GetErrorType(NULL, name, NULL); } } break; case NK_ARRAYTYPE: { TYPESYM * typeElem = BindTypeCore(node->asARRAYTYPE()->pElementType); if (!typeElem) return NULL; if (!FSuppressErrors()) { if (typeElem->isSpecialByRefType()) compiler()->Error(node, ERR_ArrayElementCantBeRefAny, typeElem); if (compiler()->AggStateMax() >= AggState::DefinedMembers) compiler()->CheckForStaticClass(node, NULL, typeElem, ERR_ArrayOfStaticClass); } int rank = node->asARRAYTYPE()->iDims; ASSERT(rank > 0); type = compiler()->getBSymmgr().GetArray(typeElem, rank); } break; case NK_NAMEDTYPE: type = BindNameToTypeCore(node->asNAMEDTYPE()->pName); break; case NK_OPENTYPE: type = BindNameToTypeCore(node->asOPENTYPE()->pName); ASSERT(!type || type->isERRORSYM() || type->isAGGTYPESYM() && type->asAGGTYPESYM()->typeArgsAll->size > 0); break; case NK_POINTERTYPE: { TYPESYM * typeInner = BindTypeCore(node->asPOINTERTYPE()->pElementType); if (!typeInner) return NULL; type = compiler()->getBSymmgr().GetPtrType(typeInner); if (!typeInner->isPTRSYM()) compiler()->clsDeclRec.checkUnmanaged(node, type); } break; case NK_NULLABLETYPE: { TYPESYM * typeInner = BindTypeCore(node->asNULLABLETYPE()->pElementType); if (!typeInner) return NULL; // Convert to NUBSYM. type = compiler()->getBSymmgr().GetNubTypeOrError(typeInner); if (type->isNUBSYM() && compiler()->CompPhase() >= CompilerPhase::EvalConstants) CheckConstraints(compiler(), node, type->asNUBSYM()->GetAts(), CheckConstraintsFlags::None); } break; case NK_TYPEWITHATTR: compiler()->Error(node, ERR_AttrOnTypeArg); type = BindTypeCore(node->asTYPEWITHATTR()->pType); break; default: VSFAIL("BAD type node kind"); return NULL; } return type; } /*************************************************************************************************** Search a class for the name (as a nested type). If fOuterAndTypeVars is true, this searches first for type variables, then for nested types in this class and its base classes, then for nested types in outer types and base classes of the outer types. If fOuterAndTypeVars is false, this searches for nested types just in this type and its base classes. ***************************************************************************************************/ SYM * TypeBind::SearchClassCore(AGGTYPESYM * ats, NAME * name, TypeArray * typeArgs, bool fOuterAndTypeVars) { ASSERT(m_fValid); ASSERT(typeArgs); // Check this class and all classes that this class is nested in. for ( ; ats; ats = ats->outerType) { AGGSYM * agg = ats->getAggregate(); if (agg->AggState() < AggState::Prepared) { if (compiler()->AggStateMax() >= AggState::Prepared) compiler()->EnsureState(agg); else if (agg->AggState() < AggState::Inheritance) { // Note: we cannot assert that this succeeds. If it fails, we're in ResolveInheritanceRec // and it will be detected by ResolveInheritanceRec (eventually). compiler()->clsDeclRec.ResolveInheritanceRec(agg); } } if (fOuterAndTypeVars) { SYM * sym = SearchTypeVarsCore(ats->getAggregate(), name, typeArgs); if (sym) return sym; } // Check this class and all base classes. for (AGGTYPESYM * atsCur = ats; atsCur; atsCur = atsCur->GetBaseClass()) { AGGSYM * aggCur = atsCur->getAggregate(); for (SYM * sym = compiler()->getBSymmgr().LookupAggMember(name, aggCur, MASK_ALL); sym; sym = sym->nextSameName) { if (sym->isAGGSYM()) { // Arity must be checked before access! SYM * symRet = sym; CheckArity(&symRet, typeArgs, atsCur); CheckAccess(&symRet); if (symRet) return symRet; } else if (!m_symBadKind && !sym->isTYVARSYM()) { m_symBadKind = sym; } } } if (!fOuterAndTypeVars) return NULL; } return NULL; } /*************************************************************************************************** Searches for the name among the type variables of symOwner. ***************************************************************************************************/ TYVARSYM * TypeBind::SearchTypeVarsCore(SYM * symOwner, NAME * name, TypeArray * typeArgs) { ASSERT(m_fValid); ASSERT(symOwner->isMETHSYM() || symOwner->isAGGSYM()); ASSERT(typeArgs); TYVARSYM * var = compiler()->LookupGlobalSym(name, symOwner->asPARENTSYM(), MASK_TYVARSYM)->asTYVARSYM(); if (var) CheckArity((SYM **)&var, typeArgs, NULL); return var; } /*************************************************************************************************** Searches for the name among the members of a single (filtered) namespace. Returns either an NSAIDSYM, AGGTYPESYM or ERRORSYM. ***************************************************************************************************/ SYM * TypeBind::SearchSingleNamespaceCore(NSAIDSYM * nsa, BASENODE * node, NAME * name, TypeArray * typeArgs, bool fAggOnly) { SYM * sym = SearchSingleNamespaceCore(nsa->GetNS(), nsa->GetAid(), node, name, typeArgs, fAggOnly); if (!sym || sym->isERRORSYM()) return sym; if (sym->isNSSYM()) return compiler()->getBSymmgr().GetNsAid(sym->asNSSYM(), nsa->GetAid()); // Translate "Nullable<T>" to "T?". if (sym->asAGGTYPESYM()->isPredefType(PT_G_OPTIONAL) && !sym->asAGGTYPESYM()->typeArgsAll->Item(0)->isUNITSYM()) { return compiler()->getBSymmgr().GetNubFromNullable(sym->asAGGTYPESYM()); } return sym->asAGGTYPESYM(); } enum { krankNone, krankTypeImp, // Public type in an imported assembly. krankNamespaceImp, // Namespace used in imported assemblies. krankNamespaceThis, // Namespace used in this assembly. krankTypeThis, // Type in source or an added module (this assembly). }; /*************************************************************************************************** Private method for SearchSingleNamespaceCore. Determines what kind of SYM we're dealing with for ambiguity error / warning reporting. Returns a value from the enum above. Note that this is only called on NSSYMs and AGGTYPESYMs where the AGGSYM is NOT nested. ***************************************************************************************************/ int TypeBind::RankSym(SYM * sym) { ASSERT(sym->isNSSYM() || sym->isAGGTYPESYM()); if (sym->isNSSYM()) { if (sym->asNSSYM()->InAlias(compiler(), kaidThisAssembly)) return krankNamespaceThis; return krankNamespaceImp; } AGGSYM * agg = sym->asAGGTYPESYM()->getAggregate(); ASSERT(!agg->isNested()); if (agg->isSource || agg->InAlias(kaidThisAssembly)) return krankTypeThis; // CheckAccess should have dealt with private types already. ASSERT(agg->GetAccess() > ACC_INTERNAL || agg->GetAccess() == ACC_INTERNAL && agg->InternalsVisibleTo(kaidThisAssembly)); return krankTypeImp; } /*************************************************************************************************** Searches for the name among the members of a single (filtered) namespace. Returns either an NSSYM (not NSAIDSYM) or AGGTYPESYM. ***************************************************************************************************/ SYM * TypeBind::SearchSingleNamespaceCore(NSSYM * ns, int aid, BASENODE * node, NAME * name, TypeArray * typeArgs, bool fAggOnly) { ASSERT(m_fValid); ASSERT(typeArgs); symbmask_t mask = fAggOnly ? MASK_AGGSYM : MASK_NSSYM | MASK_AGGSYM; SYM * symBest = NULL; int rankBest = krankNone; SYM * symAmbig = NULL; int rankAmbig = krankNone; for (BAGSYM * bag = compiler()->LookupInBagAid(name, ns, aid, mask)->asBAGSYM(); bag; bag = compiler()->LookupNextInAid(bag, aid, mask)->asBAGSYM()) { SYM * symNew = bag; // Arity must be checked before access! CheckArity(&symNew, typeArgs, NULL); CheckAccess(&symNew); if (!symNew) continue; ASSERT(symNew->isNSSYM() || symNew->isAGGTYPESYM()); // If it's ambiguous, at least one of them should be a type. ASSERT(!symBest || symBest->isAGGTYPESYM() || symNew->isAGGTYPESYM()); int rankNew = RankSym(symNew); if (rankNew > rankBest) { symAmbig = symBest; rankAmbig = rankBest; symBest = symNew; rankBest = rankNew; } else if (rankNew > rankAmbig) { symAmbig = symNew; rankAmbig = rankNew; } } ASSERT(rankBest >= rankAmbig); if (!symAmbig) return symBest; ASSERT(symBest && rankBest == RankSym(symBest)); ASSERT(symAmbig && rankAmbig == RankSym(symAmbig)); // Handle errors and warnings. // NOTE: Representing (rankBest,rankAmbig) as a pair (x,y), the following should be true: // * If (x,y) is a warning then (z,y) must be a warning for any z >= x. // * If (x,y) is a warning then (x,z) must be a warning for any z <= y. int err; switch (rankAmbig) { case krankTypeImp: if (FSuppressErrors()) { if (rankBest >= krankNamespaceThis) return symBest; goto LRetErrorSym; } switch (rankBest) { case krankTypeImp: err = ERR_SameFullNameAggAgg; break; case krankNamespaceImp: err = ERR_SameFullNameNsAgg; break; case krankNamespaceThis: err = WRN_SameFullNameThisNsAgg; break; case krankTypeThis: err = WRN_SameFullNameThisAggAgg; break; default: VSFAIL("Bad rank"); err = ERR_SameFullNameAggAgg; break; } break; case krankNamespaceImp: ASSERT(rankBest == krankTypeThis); if (FSuppressErrors()) return symBest; err = WRN_SameFullNameThisAggNs; break; case krankNamespaceThis: ASSERT(rankBest == krankTypeThis); if (FSuppressErrors()) goto LRetErrorSym; err = ERR_SameFullNameThisAggThisNs; break; case krankTypeThis: ASSERT(rankBest == krankTypeThis); if (FSuppressErrors()) { LRetErrorSym: NSAIDSYM * nsa = compiler()->getBSymmgr().GetNsAid(ns, aid); return compiler()->getBSymmgr().GetErrorType(nsa, name, typeArgs); } compiler()->ErrorRef(node, ERR_SameFullNameThisAggThisAgg, ErrArgAggKind(symBest->asAGGTYPESYM()), symBest, ErrArgAggKind(symAmbig->asAGGTYPESYM()), symAmbig); return symBest; default: VSFAIL("Bad rank"); err = ERR_SameFullNameAggAgg; break; } DECLSYM * declBest; DECLSYM * declAmbig; if (symBest->isAGGTYPESYM()) declBest = (DECLSYM *)symBest->asAGGTYPESYM()->getAggregate()->DeclFirst(); else { declBest = symBest->asNSSYM()->DeclFirst(); if (rankBest == krankNamespaceThis) { while (!declBest->getInputFile()->InAlias(kaidThisAssembly) && declBest->DeclNext()) declBest = declBest->DeclNext(); } } if (symAmbig->isAGGTYPESYM()) declAmbig = (DECLSYM *)symAmbig->asAGGTYPESYM()->getAggregate()->DeclFirst(); else { declAmbig = symAmbig->asNSSYM()->DeclFirst(); if (rankAmbig == krankNamespaceThis) { while (!declAmbig->getInputFile()->InAlias(kaidThisAssembly) && declAmbig->DeclNext()) declAmbig = declAmbig->DeclNext(); } } compiler()->ErrorRef(node, err, declBest->getInputFile()->name, declBest, declAmbig->getInputFile()->name, declAmbig); return symBest; } /*************************************************************************************************** Searches for the name in the using aliases of the given namespace declaration. If there is an ambiguity and SuppressErrors is set, this returns ERRORSYM. If there is an ambiguity and SuppressErrors is not set, this reports an error and returns the best symbol found. ***************************************************************************************************/ SYM * TypeBind::SearchUsingAliasesCore(NSDECLSYM * nsd, BASENODE * node, NAME * name, TypeArray * typeArgs) { ASSERT(m_fValid); ASSERT(typeArgs); ASSERT(!m_fUsingAlias || m_symStart->isNSDECLSYM()); if (typeArgs->size && m_symBadArity) return NULL; compiler()->clsDeclRec.ensureUsingClausesAreResolved(nsd); FOREACHSYMLIST(nsd->usingClauses, symUse, SYM) if (symUse->name != name || !symUse->isALIASSYM() || !FAliasAvailable(symUse->asALIASSYM())) continue; ALIASSYM * alias = symUse->asALIASSYM(); SYM * sym = BindUsingAlias(compiler(), alias); if (!sym) continue; if (typeArgs->size) { m_symBadArity = alias; return NULL; } //Found something within this using. it is not "unused" compiler()->compileCallback.BoundToUsing(nsd, symUse); if (alias->symDup) { // Error - alias conflicts with other element of the namespace. if (FSuppressErrors()) return compiler()->getBSymmgr().GetErrorType(NULL, name, NULL); compiler()->Error(node, ERR_ConflictAliasAndMember, name, alias->symDup->parent, ErrArgRefOnly(alias->symDup)); } return sym; ENDFOREACHSYMLIST return NULL; } /*************************************************************************************************** Searches for the name in the using clauses of the given namespace declaration. Checks only normal using clauses - not aliases. If there is an ambiguity and SuppressErrors is set, this returns ERRORSYM. If there is an ambiguity and SuppressErrors is not set, this reports an error and returns the best symbol found. ***************************************************************************************************/ SYM * TypeBind::SearchUsingClausesCore(NSDECLSYM * nsd, BASENODE * node, NAME * name, TypeArray * typeArgs) { ASSERT(m_fValid); ASSERT(typeArgs); ASSERT(!m_fUsingAlias || m_symStart->isNSDECLSYM()); // Don't check using namespaces when binding aliases in this decl. if (m_fUsingAlias && m_symStart == nsd) return NULL; compiler()->clsDeclRec.ensureUsingClausesAreResolved(nsd); SYM * symRet = NULL; FOREACHSYMLIST(nsd->usingClauses, symUse, SYM) if (!symUse->isNSAIDSYM()) continue; // Only search for types. SYM * sym = SearchSingleNamespaceCore(symUse->asNSAIDSYM(), node, name, typeArgs, true); if (!sym) continue; //Found something within this using. it is not "unused" compiler()->compileCallback.BoundToUsing(nsd, symUse); if (sym->isERRORSYM()) return sym; // Check for ambiguity between different using namespaces. if (symRet) { if (FSuppressErrors()) return compiler()->getBSymmgr().GetErrorType(NULL, name, NULL); // After reporting the error just run with the first one. compiler()->ErrorRef(node, ERR_AmbigContext, name, symRet, sym); return symRet; } symRet = sym; ENDFOREACHSYMLIST return symRet; } /****************************************************************************** Searches for the name in a namespace declaration and containing declarations. This searches using clauses as well. ******************************************************************************/ SYM * TypeBind::SearchNamespacesCore(NSDECLSYM * nsd, BASENODE * node, NAME * name, TypeArray * typeArgs) { ASSERT(m_fValid); ASSERT(typeArgs); for ( ; nsd; nsd = nsd->DeclPar()) { SYM * sym; // Check the using aliases and extern aliases. sym = SearchUsingAliasesCore(nsd, node, name, typeArgs); if (sym) return sym; // Check the namespace. sym = SearchSingleNamespaceCore(compiler()->getBSymmgr().GetNsAid(nsd->NameSpace(), kaidGlobal), node, name, typeArgs); if (sym) return sym; // Check the using clauses for this declaration. sym = SearchUsingClausesCore(nsd, node, name, typeArgs); if (sym) return sym; } return NULL; } /*************************************************************************************************** Searches for an alias with the given name in a namespace declaration and containing declarations. Reports an error if not found. ***************************************************************************************************/ SYM * TypeBind::SearchNamespacesForAliasCore(NSDECLSYM * nsd, BASENODE * node, NAME * name) { ASSERT(m_fValid); ASSERT(!m_fUsingAlias); // This doesn't check for extern vs regular. for ( ; nsd; nsd = nsd->DeclPar()) { // Check the using aliases. compiler()->clsDeclRec.ensureUsingClausesAreResolved(nsd); FOREACHSYMLIST(nsd->usingClauses, symUse, SYM) if (symUse->name != name || !symUse->isALIASSYM()) continue; SYM * sym = BindUsingAlias(compiler(), symUse->asALIASSYM()); if (sym) { //Found something within this using. it is not "unused" compiler()->compileCallback.BoundToUsing(nsd, symUse); return sym; } ENDFOREACHSYMLIST } if (FAllowMissing()) return NULL; if (!FSuppressErrors()) compiler()->Error(node, ERR_AliasNotFound, name); return compiler()->getBSymmgr().GetErrorType(NULL, name, NULL); } /*************************************************************************************************** Check access and bogosity of the given symbol. Sets *psym to NULL if it's not accessible or is bogus. Updates m_symInaccess and m_symBogus as appropriate. Generally this should be called after CheckArity so only SYMs with the correct arity are put in m_symInaccess and m_symBogus. ReportErrors may return m_symInaccess or m_symBogus after reporting the errors! ***************************************************************************************************/ void TypeBind::CheckAccess(SYM ** psym) { ASSERT(m_fValid); ASSERT(psym); SYM * sym = *psym; if (!sym || sym->isNSSYM()) return; ASSERT(sym->isAGGTYPESYM()); AGGTYPESYM * atsCheck = NULL; // CLSDREC::CheckAccess wants an AGGSYM and containing AGGTYPESYM. if (sym->isAGGTYPESYM()) { atsCheck = sym->asAGGTYPESYM(); sym = atsCheck->getAggregate(); atsCheck = atsCheck->outerType; } if (!compiler()->clsDeclRec.CheckAccess(sym, atsCheck, m_symAccess, NULL)) { if (!m_symInaccess) m_symInaccess = *psym; // Set the original. *psym = NULL; return; } if (!(m_flags & TypeBindFlags::NoBogusCheck) && compiler()->CheckBogus(sym)) { if (!m_symBogus) m_symBogus = *psym; // Set the original. *psym = NULL; } } /*************************************************************************************************** Check the arity of the given symbol. If the arity doesn't match, sets *psym to NULL. If the arity does match (and it's a type), sets *psym to the AGGTYPESYM. Call this before CheckAccess! ***************************************************************************************************/ void TypeBind::CheckArity(SYM ** psym, TypeArray * typeArgs, AGGTYPESYM * typeOuter) { ASSERT(m_fValid); ASSERT(psym); ASSERT(typeArgs); SYM * sym = *psym; if (!sym) return; ASSERT(sym->isAGGSYM() || sym->isNSSYM() || sym->isTYVARSYM()); switch (sym->getKind()) { case SK_AGGSYM: if (typeArgs->size != sym->asAGGSYM()->typeVarsThis->size) { if (!m_symBadArity) m_symBadArity = sym; *psym = NULL; return; } *psym = compiler()->getBSymmgr().GetInstAgg(sym->asAGGSYM(), typeOuter, typeArgs); break; default: if (typeArgs->size) { if (!m_symBadArity) m_symBadArity = sym; *psym = NULL; } break; } } /*************************************************************************************************** Static method to check for type errors - like deprecated, constraints, etc. ***************************************************************************************************/ void TypeBind::CheckType(COMPILER * cmp, BASENODE * node, TYPESYM * type, SYM * symCtx, TypeBindFlagsEnum flags) { if (!type || type->isERRORSYM()) return; if (cmp->AggStateMax() >= AggState::Prepared) cmp->EnsureState(type); if (flags & TypeBindFlags::SuppressErrors) return; if (type->isAGGTYPESYM() || type->isNUBSYM()) { if (cmp->CompPhase() >= CompilerPhase::EvalConstants) CheckConstraints(cmp, node, type, CheckConstraintsFlags::None); } if (type->IsDeprecated() && !(flags & TypeBindFlags::NoDeprecated)) { cmp->clsDeclRec.ReportDeprecated(node, symCtx, SymWithType(type, NULL)); } if (type->isPredefType(PT_SYSTEMVOID)) { cmp->Error(node, ERR_SystemVoid); } } /*************************************************************************************************** Report the errors found. May morph *psym from NULL to non-NULL after reporting an error. If the compiler's AggStateMax is at least Prepared then this prepares any type that is returned. ***************************************************************************************************/ void TypeBind::ReportErrors(BASENODE * node, NAME * name, SYM * symLeft, TypeArray * typeArgs, SYM ** psym) { ASSERT(m_fValid); ASSERT(node && name && psym); ASSERT(!symLeft || symLeft->isAGGTYPESYM() || symLeft->isNSAIDSYM() || symLeft->isERRORSYM()); ASSERT(!m_symInaccess || m_symInaccess != m_symBadKind); if (FSuppressErrors()) { if (!*psym && (m_flags & TypeBindFlags::AllowInaccessible)) { if (m_symInaccess) *psym = m_symInaccess; else if (m_symBogus) *psym = m_symBogus; } if (!*psym && FAllowMissing()) return; goto LDone; } if (*psym) { if ((*psym)->isTYPESYM()) CheckType(compiler(), node, (*psym)->asTYPESYM(), m_symCtx, m_flags); // CheckType already called EnsureState so just return. return; } if (FAllowMissing()) return; if (m_symInaccess) { // found an inaccessible name or an uncallable name if (!m_symInaccess->isUserCallable()) { compiler()->Error(node, ERR_CantCallSpecialMethod, name, ErrArgRefOnly(m_symInaccess)); } else { compiler()->Error(node, ERR_BadAccess, m_symInaccess); } *psym = m_symInaccess; } else if (m_symBogus) { compiler()->ErrorRef(node, ERR_BogusType, m_symBogus); *psym = m_symBogus; } else if (m_symBadKind || m_symBadArity) { if (m_symBadKind) { compiler()->Error(node, ERR_BadSKknown, m_symBadKind, ErrArgSymKind(m_symBadKind), SK_AGGSYM); } if (m_symBadArity) { if (m_symBadArity->isAGGSYM()) { int cvar = m_symBadArity->asAGGSYM()->typeVarsThis->size; compiler()->ErrorRef(node, cvar > 0 ? ERR_BadArity : ERR_HasNoTypeVars, m_symBadArity, ErrArgSymKind(m_symBadArity), cvar); } else { compiler()->ErrorRef(node, ERR_TypeArgsNotAllowed, m_symBadArity, ErrArgSymKind(m_symBadArity)); } } } // Didn't find anything at all. else if (symLeft) { if (symLeft == compiler()->getBSymmgr().GetGlobalNsAid()) { compiler()->Error(node, ERR_GlobalSingleTypeNameNotFound, name); } else { int err = symLeft->isNSAIDSYM() ? ERR_DottedTypeNameNotFoundInNS : ERR_DottedTypeNameNotFoundInAgg; compiler()->Error(node, err, name, symLeft); } } else { compiler()->Error(node, ERR_SingleTypeNameNotFound, name, m_symCtx); } LDone: if (!*psym) *psym = compiler()->getBSymmgr().GetErrorType(symLeft->asPARENTSYM(), name, typeArgs); else if ((*psym)->isTYPESYM() && compiler()->AggStateMax() >= AggState::Prepared && !(m_flags & TypeBindFlags::AvoidEnsureState)) compiler()->EnsureState((*psym)->asTYPESYM()); } /*************************************************************************************************** Search a single namespace for the name. ***************************************************************************************************/ SYM * TypeBind::SearchSingleNamespace(COMPILER * cmp, BASENODE * node, NAME * name, TypeArray * typeArgs, NSAIDSYM * nsa, SYM * symAccess, TypeBindFlagsEnum flags) { TypeBind tb(cmp, nsa->GetNS(), nsa->GetNS(), symAccess, NULL, flags); tb.ClearErrorInfo(); SYM * sym = tb.SearchSingleNamespaceCore(nsa, node, name, typeArgs); tb.ReportErrors(node, name, nsa, typeArgs, &sym); return sym; } /*************************************************************************************************** Search a namespace declaration and its containing declarations (including using claues) for the name. This is an instance method. ***************************************************************************************************/ SYM * TypeBind::SearchNamespacesInst(COMPILER * cmp, BASENODE * node, NAME * name, TypeArray * typeArgs, DECLSYM * decl, SYM * symAccess, TypeBindFlagsEnum flags) { ASSERT(decl->isAGGDECLSYM() || decl->isNSDECLSYM()); // Find the NSDECL DECLSYM * declStart; for (declStart = decl; !declStart->isNSDECLSYM(); declStart = declStart->DeclPar()) ; Init(cmp, decl, declStart, symAccess, NULL, flags); ClearErrorInfo(); return SearchNamespacesCore(declStart->asNSDECLSYM(), node, name, typeArgs); } /*************************************************************************************************** Static method to search a namespace declaration and its containing declarations (including using claues) for the name. ***************************************************************************************************/ SYM * TypeBind::SearchNamespaces(COMPILER * cmp, BASENODE * node, NAME * name, TypeArray * typeArgs, NSDECLSYM * nsd, SYM * symAccess, TypeBindFlagsEnum flags) { TypeBind tb(cmp, nsd, nsd, symAccess, NULL, flags); tb.ClearErrorInfo(); SYM * sym = tb.SearchNamespacesCore(nsd, node, name, typeArgs); tb.ReportErrors(node, name, NULL, typeArgs, &sym); return sym; } /*************************************************************************************************** Static method to search a namespace declaration and its containing declarations for a using/extern alias. ***************************************************************************************************/ SYM * TypeBind::SearchNamespacesForAlias(COMPILER * cmp, BASENODE * node, NAME * name, NSDECLSYM * nsd, TypeBindFlagsEnum flags) { TypeBind tb(cmp, nsd, nsd, nsd, NULL, flags); tb.ClearErrorInfo(); SYM * sym = tb.SearchNamespacesForAliasCore(nsd, node, name); // SearchNamespaceForAliasCore already reported an error if the alias wasn't found. // Don't set the node sym. It's already been set to the alias sym. // tb.ReportErrors(node, name, NULL, NULL, &sym); return sym; } /*************************************************************************************************** Bind the given node to an NSAIDSYM or AGGTYPESYM. The node should be an NK_DOT, NK_NAME, NK_GENERICNAME or NK_ALIASQUALNAME. ***************************************************************************************************/ SYM * TypeBind::BindName(COMPILER * cmp, BASENODE * node, SYM * symCtx, TypeBindFlagsEnum flags) { ASSERT(symCtx->isNSDECLSYM() || symCtx->isAGGDECLSYM() || symCtx->isMETHSYM()); TypeBind tb(cmp, symCtx, symCtx, symCtx, NULL, flags); return tb.BindNameCore(node); } /*************************************************************************************************** Bind the given node to a type. If the name resolves to something other than a type, reports an error (if !SuppressErrors) and returns ERRORSYM. The node should be an NK_DOT, NK_NAME, NK_GENERICNAME or NK_ALIASQUALNAME (the latter will always produce an error). ***************************************************************************************************/ TYPESYM * TypeBind::BindNameToType(COMPILER * cmp, BASENODE * node, SYM * symCtx, TypeBindFlagsEnum flags) { ASSERT(symCtx->isNSDECLSYM() || symCtx->isAGGDECLSYM() || symCtx->isMETHSYM()); TypeBind tb(cmp, symCtx, symCtx, symCtx, NULL, flags); return tb.BindNameToTypeCore(node); } /*************************************************************************************************** Bind the given node to a type. ***************************************************************************************************/ TYPESYM * TypeBind::BindType(COMPILER * cmp, TYPEBASENODE * node, SYM * symCtx, TypeBindFlagsEnum flags) { ASSERT(symCtx->isNSDECLSYM() || symCtx->isAGGDECLSYM() || symCtx->isMETHSYM()); TypeBind tb(cmp, symCtx, symCtx, symCtx, NULL, flags); return tb.BindTypeCore(node); } /*************************************************************************************************** Bind the given node to a type. Only the "exterior" of the agg is in scope - type variables are in scope but members are not. ***************************************************************************************************/ TYPESYM * TypeBind::BindTypeAggDeclExt(COMPILER * cmp, TYPEBASENODE * node, AGGDECLSYM * ads, TypeBindFlagsEnum flags) { TypeBind tb(cmp, ads, ads->DeclPar(), ads, ads->Agg(), flags); return tb.BindTypeCore(node); } /*************************************************************************************************** Bind the given node to a type. The search starts with the type variables of symTypeVars, then continues with symStart. ***************************************************************************************************/ TYPESYM * TypeBind::BindTypeWithTypeVars(COMPILER * cmp, TYPEBASENODE * node, SYM * symStart, SYM * symAccess, SYM * symTypeVars, TypeBindFlagsEnum flags) { TypeBind tb(cmp, symStart, symStart, symAccess, symTypeVars, flags); return tb.BindTypeCore(node); } /*************************************************************************************************** Bind the generic args of the given NAMENODE to a type array. If the NAMENODE is not generic, return the empty type array (not NULL). Returns NULL iff SuppressErrors is specified and there were errors in binding one or more type argument. ***************************************************************************************************/ TypeArray * TypeBind::BindTypeArgs(COMPILER * cmp, NAMENODE * node, SYM * symCtx, TypeBindFlagsEnum flags) { if (node->kind != NK_GENERICNAME) return BSYMMGR::EmptyTypeArray(); TypeBind tb(cmp, symCtx, symCtx, symCtx, NULL, flags); return tb.BindTypeArgsCore(node); } /*************************************************************************************************** Bind the node as an attribute type. The resulting types actually name may have "Attribute" appended to the last identifier. ***************************************************************************************************/ TYPESYM * TypeBind::BindAttributeType(COMPILER * cmp, BASENODE * node, SYM * symCtx, TypeBindFlagsEnum flags) { TypeBind tb(cmp, symCtx, symCtx, symCtx, NULL, flags); return tb.BindAttributeTypeCore(node); } /*************************************************************************************************** Return the identifier in node concatenated with "Attribute". May return NULL indicating that appending Attribute is not appropriate (because the identifier was specified with the literal prefix @). ***************************************************************************************************/ NAME * TypeBind::AppendAttrSuffix(NAMENODE * node) { if (node->flags & NF_NAME_LITERAL) return NULL; size_t cch = wcslen(node->pName->text) + wcslen(L"Attribute") + 1; PWSTR psz = STACK_ALLOC(WCHAR, cch); StringCchCopyW(psz, cch, node->pName->text); StringCchCatW (psz, cch, L"Attribute"); return compiler()->namemgr->AddString(psz); } /*************************************************************************************************** Determines whether the sym is an attribute type. This calls EnsureState before checking. ***************************************************************************************************/ bool TypeBind::IsAttributeType(SYM * sym) { if (!sym || !sym->isAGGTYPESYM()) return false; AGGSYM * agg = sym->asAGGTYPESYM()->getAggregate(); compiler()->EnsureState(agg); return agg->isAttribute; } /*************************************************************************************************** Bind the node as an attribute type. The resulting type's actual name may have "Attribute" appended to the last identifier. ***************************************************************************************************/ TYPESYM * TypeBind::BindAttributeTypeCore(BASENODE * node) { // ALIASNAME and OPENNAME shouldn't come through here. ASSERT(node->kind == NK_DOT || node->kind == NK_NAME || node->kind == NK_GENERICNAME); ASSERT(!FSuppressErrors()); NAMENODE * nodeName; switch (node->kind) { case NK_DOT: nodeName = node->asDOT()->p2->asNAME(); break; case NK_NAME: nodeName = node->asNAME(); break; default: VSFAIL("Bad node kind in BindAttributeTypeCore"); return NULL; } // lookup both names but don't report errors when doing so NAME * nameShort = nodeName->pName; NAME * nameLong = AppendAttrSuffix(nodeName); // Suppress the errors for the initial lookup. TypeBindFlagsEnum flagsOrig = m_flags; m_flags = flagsOrig | TypeBindFlags::AllowMissing; SYM * symShort = BindNameCore(node, nameShort); SYM * symLong = nameLong ? BindNameCore(node, nameLong) : NULL; // Reset the SuppressErrors bit. m_flags = flagsOrig; if (FAllowMissing() && !symShort && !symLong) return NULL; // Check results. bool fShort = IsAttributeType(symShort); bool fLong = IsAttributeType(symLong); TYPESYM * typeRet; if (fShort == fLong) { if (fShort) { compiler()->ErrorRef(nodeName, ERR_AmbigousAttribute, nameShort, symShort, symLong); // Use the short one. typeRet = symShort->asAGGTYPESYM(); goto LDone; } if (symShort && symShort->isERRORSYM()) { typeRet = symShort->asERRORSYM(); goto LDone; } if (symLong && symLong->isERRORSYM()) { typeRet = symLong->asERRORSYM(); goto LDone; } // Need to generate at least one error. if (!symShort && !symLong) BindNameCore(node, nameShort); // Generate missing error. else { if (symShort) compiler()->ErrorRef(nodeName, ERR_NotAnAttributeClass, symShort); if (symLong) compiler()->ErrorRef(nodeName, ERR_NotAnAttributeClass, symLong); } typeRet = compiler()->getBSymmgr().GetErrorType(NULL, nameShort, NULL); } else typeRet = fShort ? symShort->asAGGTYPESYM() : symLong->asAGGTYPESYM(); LDone: return typeRet; } /*************************************************************************************************** Return the type or namespace that the using alias references. Resolves the alias if it hasn't been resolved yet. May return NULL indicating that there was an error resolving the alias. Can only return an NSAIDSYM or AGGTYPESYM. ***************************************************************************************************/ SYM * TypeBind::BindUsingAlias(COMPILER * cmp, ALIASSYM *alias) { if (!alias->hasBeenBound) { if (alias->fExtern) { // Extern alias. ASSERT(!alias->parseTree->asUSING()->pName); EXTERNALIASSYM * ext = cmp->LookupGlobalSym(alias->name, cmp->GetExternAliasContainer(), MASK_EXTERNALIASSYM)->asEXTERNALIASSYM(); if (!ext) cmp->Error(alias->parseTree, ERR_BadExternAlias, alias); else alias->sym = ext->nsa; } else { NSDECLSYM * nsdPar = alias->parent->asNSDECLSYM(); BASENODE * nodeRight = alias->parseTree->asUSING()->pName; ASSERT(nodeRight); // Right hand side of alias isn't bound yet. Check enclosing namespace (but not using clauses) // then parent namespace declarations. TypeBind tb(cmp, nsdPar, nsdPar, nsdPar, NULL, TypeBindFlags::None); tb.m_fUsingAlias = true; alias->sym = tb.BindNameCore(nodeRight); ASSERT(!alias->sym || alias->sym->isNSAIDSYM() || alias->sym->isAGGTYPESYM() || alias->sym->isERRORSYM()); } alias->hasBeenBound = true; } return alias->sym; } /*************************************************************************************************** Check the constraints of any type arguments in the given TYPESYM. ***************************************************************************************************/ bool TypeBind::CheckConstraints(COMPILER * cmp, BASENODE * tree, TYPESYM * type, CheckConstraintsFlagsEnum flags) { type = type->GetNakedType(); if (type->isNUBSYM()) { TYPESYM * typeT = type->asNUBSYM()->GetAts(); if (typeT) type = typeT; else type = type->GetNakedType(true); } if (!type->isAGGTYPESYM()) return true; AGGTYPESYM * ats = type->asAGGTYPESYM(); if (ats->typeArgsAll->size == 0) { // Common case: there are no type vars, so there are no constraints. ats->fConstraintsChecked = true; ats->fConstraintError = false; return true; } if (ats->fConstraintsChecked) { // Already checked. if (!ats->fConstraintError || (flags & CheckConstraintsFlags::NoDupErrors)) { // No errors or no need to report errors again. return !ats->fConstraintError; } } TypeArray *typeVars = ats->getAggregate()->typeVarsThis; TypeArray *typeArgsThis = ats->typeArgsThis; TypeArray *typeArgsAll = ats->typeArgsAll; ASSERT(typeVars->size == typeArgsThis->size); cmp->EnsureState(ats); cmp->EnsureState(typeVars); cmp->EnsureState(typeArgsAll); cmp->EnsureState(typeArgsThis); if (ats->AggState() < AggState::DefinedMembers || typeVars->AggState() < AggState::DefinedMembers || typeArgsAll->AggState() < AggState::DefinedMembers || typeArgsThis->AggState() < AggState::DefinedMembers) { // Too early to check anything. ASSERT(cmp->AggStateMax() < AggState::DefinedMembers); return true; } if (!ats->fConstraintsChecked) { ats->fConstraintsChecked = true; ats->fConstraintError = false; } // Check the outer type first. If CheckConstraintsFlags::Outer is not specified and the // outer type has already been checked then don't bother checking it. if (ats->outerType && ((flags & CheckConstraintsFlags::Outer) || !ats->outerType->fConstraintsChecked)) { CheckConstraints(cmp, tree, ats->outerType, flags); ats->fConstraintError |= ats->outerType->fConstraintError; } if (typeVars->size > 0) ats->fConstraintError |= !CheckConstraintsCore(cmp, tree, ats->getAggregate(), typeVars, typeArgsThis, typeArgsAll, NULL, (flags & CheckConstraintsFlags::NoErrors) ); // Now check type args themselves. for (int i = 0; i < typeArgsThis->size; i++) { TYPESYM * arg = typeArgsThis->Item(i)->GetNakedType(true); if (arg->isAGGTYPESYM() && !arg->asAGGTYPESYM()->fConstraintsChecked) { CheckConstraints(cmp, tree, arg->asAGGTYPESYM(), flags | CheckConstraintsFlags::Outer); if (arg->asAGGTYPESYM()->fConstraintError) ats->fConstraintError = true; } } // Nullable should have the value type constraint! ASSERT(!ats->isPredefType(PT_G_OPTIONAL) || typeVars->ItemAsTYVARSYM(0)->FValCon()); return !ats->fConstraintError; } /*************************************************************************************************** Check the constraints on the method instantiation. ***************************************************************************************************/ void TypeBind::CheckMethConstraints(COMPILER * cmp, BASENODE * tree, MethWithInst mwi) { ASSERT(mwi.Meth() && mwi.Type() && mwi.TypeArgs()); ASSERT(mwi.Meth()->typeVars->size == mwi.TypeArgs()->size); ASSERT(mwi.Type()->getAggregate() == mwi.Meth()->getClass()); if (mwi.TypeArgs()->size > 0) { cmp->EnsureState(mwi.Meth()->typeVars); cmp->EnsureState(mwi.TypeArgs()); ASSERT(mwi.Meth()->typeVars->AggState() >= AggState::DefinedMembers); ASSERT(mwi.TypeArgs()->AggState() >= AggState::DefinedMembers); CheckConstraintsCore(cmp, tree, mwi.Meth(), mwi.Meth()->typeVars, mwi.TypeArgs(), mwi.Type()->typeArgsAll, mwi.TypeArgs(), CheckConstraintsFlags::None); } } /*************************************************************************************************** Check whether typeArgs satisfies the constraints of typeVars. The typeArgsCls and typeArgsMeth are used for substitution on the bounds. The tree and symErr are used for error reporting. ***************************************************************************************************/ bool TypeBind::CheckConstraintsCore(COMPILER * cmp, BASENODE * tree, SYM * symErr, TypeArray * typeVars, TypeArray * typeArgs, TypeArray * typeArgsCls, TypeArray * typeArgsMeth, CheckConstraintsFlagsEnum flags) { ASSERT(typeVars->size == typeArgs->size); ASSERT(typeVars->size > 0); ASSERT(typeVars->AggState() >= AggState::DefinedMembers); ASSERT(typeArgs->AggState() >= AggState::DefinedMembers); ASSERT(flags == CheckConstraintsFlags::None || flags == CheckConstraintsFlags::NoErrors); bool fReportErrors = !(flags & CheckConstraintsFlags::NoErrors); bool fError = false; for (int i = 0; i < typeVars->size; i++) { // Empty bounds should be set to object. TYVARSYM * var = typeVars->ItemAsTYVARSYM(i); ASSERT(var->FResolved()); TYPESYM * arg = typeArgs->Item(i); if (arg->isUNITSYM()) continue; if (arg->isERRORSYM()) { // Error should have been reported previously. fError = true; continue; } if (cmp->CheckBogus(arg)) { if (fReportErrors) cmp->ErrorRef(tree, ERR_BogusType, arg); fError = true; continue; } if (arg->isPTRSYM() || arg->isSpecialByRefType()) { if (fReportErrors) cmp->Error(tree, ERR_BadTypeArgument, arg); fError = true; continue; } if (arg->isStaticClass()) { if (fReportErrors) cmp->ReportStaticClassError(tree, NULL, arg, ERR_GenericArgIsStaticClass); fError = true; continue; } if (var->FRefCon() && !arg->IsRefType()) { if (fReportErrors) cmp->ErrorRef(tree, ERR_RefConstraintNotSatisfied, symErr, ErrArgNoRef(var), arg); fError = true; } TypeArray * bnds = cmp->getBSymmgr().SubstTypeArray(var->GetBnds(), typeArgsCls, typeArgsMeth); int itypeMin = 0; if (var->FValCon()) { if (!arg->IsValType() || arg->isNUBSYM()) { if (fReportErrors) cmp->ErrorRef(tree, ERR_ValConstraintNotSatisfied, symErr, ErrArgNoRef(var), arg); fError = true; } // Since FValCon() is set it is redundant to check System.ValueType as well. if (bnds->size && bnds->Item(0)->isPredefType(PT_VALUE)) itypeMin = 1; } for (int j = itypeMin; j < bnds->size; j++) { TYPESYM * typeBnd = bnds->Item(j); if (!SatisfiesBound(cmp, arg, typeBnd)) { if (fReportErrors) { cmp->Error(tree, ERR_GenericConstraintNotSatisfied, ErrArgRef(symErr), ErrArg(typeBnd, ErrArgFlags::Unique), var, ErrArgRef(arg, ErrArgFlags::Unique)); } fError = true; } } // Check the newable constraint. if (!var->FNewCon() || arg->IsValType()) continue; if (arg->isClassType()) { AGGSYM * agg = arg->asAGGTYPESYM()->getAggregate(); if (agg->hasPubNoArgCtor && !agg->isAbstract) continue; } else if (arg->isTYVARSYM() && arg->asTYVARSYM()->FNewCon()) { continue; } if (fReportErrors) cmp->ErrorRef(tree, ERR_NewConstraintNotSatisfied, symErr, ErrArgNoRef(var), arg); fError = true; } return !fError; } /*************************************************************************************************** Determine whether the arg type satisfies the typeBnd constraint. Note that typeBnd could be just about any type (since we added naked type parameter constraints). ***************************************************************************************************/ bool TypeBind::SatisfiesBound(COMPILER * cmp, TYPESYM * arg, TYPESYM * typeBnd) { if (typeBnd == arg) return true; switch (typeBnd->getKind()) { default: ASSERT(0); return false; case SK_PTRSYM: case SK_ERRORSYM: return false; case SK_ARRAYSYM: case SK_TYVARSYM: break; case SK_NUBSYM: typeBnd = typeBnd->asNUBSYM()->GetAts(); if (!typeBnd) return true; break; case SK_AGGTYPESYM: break; } ASSERT(typeBnd->isAGGTYPESYM() || typeBnd->isTYVARSYM() || typeBnd->isARRAYSYM()); switch (arg->getKind()) { default: ASSERT(0); return false; case SK_ERRORSYM: case SK_PTRSYM: return false; case SK_NUBSYM: arg = arg->asNUBSYM()->GetAts(); if (!arg) return true; // Fall through. case SK_TYVARSYM: case SK_ARRAYSYM: // IsBaseType handles IList<T>.... case SK_AGGTYPESYM: return cmp->IsBaseType(arg, typeBnd); } }
36.214811
174
0.532218
intj-t
0c6cd6425e8121b8f8b07f2ffab4104175edd6d2
4,579
cpp
C++
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/menu.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/menu.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/menu.cpp
dcliche/studioengine
1a18d373b26575b040d014ae2650a1aaeb208a89
[ "Apache-2.0" ]
null
null
null
// // menu.cpp // MDStudio // // Created by Daniel Cliche on 2016-09-10. // Copyright (c) 2016-2021 Daniel Cliche. All rights reserved. // #include "menu.h" #include "draw.h" #include "listitemview.h" using namespace MDStudio; std::unique_ptr<Window> Menu::_window; int Menu::_highlightedItemIndex = -1; // --------------------------------------------------------------------------------------------------------------------- Menu::Menu(const std::string& name, void* owner, const std::string& title) : View(name, owner), _title(title) { _didSelectItemFn = nullptr; } // --------------------------------------------------------------------------------------------------------------------- Menu::~Menu() {} // --------------------------------------------------------------------------------------------------------------------- void Menu::addMenuItem(std::shared_ptr<MenuItem> menuItem) { _menuItems.push_back(menuItem); } // --------------------------------------------------------------------------------------------------------------------- Size Menu::contentSize() { float width = 0.0f; for (auto menuItem : _menuItems) { float w = getTextWidth(SystemFonts::sharedInstance()->semiboldFont(), menuItem->title()); if (w > width) width = w; } return makeSize(width + 20.0f, static_cast<float>(_menuItems.size()) * 20.0f + 2.0f); } // --------------------------------------------------------------------------------------------------------------------- void Menu::setFrame(Rect frame) { View::setFrame(frame); } // --------------------------------------------------------------------------------------------------------------------- void Menu::draw() { auto dc = drawContext(); dc->pushStates(); dc->setStrokeColor(whiteColor); dc->setStrokeWidth(1.0f); dc->setFillColor(blackColor); dc->drawRect(bounds()); auto r = makeRect(0, bounds().size.height - 20.0f, bounds().size.width, 20.0f); r = makeInsetRect(r, 1.0f, 1.0f); int itemIndex = 0; for (auto menuItem : _menuItems) { if (itemIndex == _highlightedItemIndex) { dc->pushStates(); dc->setStrokeColor(zeroColor); dc->setFillColor(blueColor); dc->drawRect(r); dc->popStates(); } dc->drawLeftText(SystemFonts::sharedInstance()->semiboldFont(), makeInsetRect(r, 10.0f, 0.0f), menuItem->title()); r.origin.y -= 20.0f; ++itemIndex; } dc->popStates(); } // --------------------------------------------------------------------------------------------------------------------- bool Menu::handleEvent(const UIEvent* event) { if (isPointInRect(event->pt, clippedRect())) { if (event->type == MOUSE_MOVED_UIEVENT) { _highlightedItemIndex = static_cast<unsigned int>(_menuItems.size()) - (event->pt.y - rect().origin.y) / 20.0f; setDirty(); } else if (event->type == MOUSE_DOWN_UIEVENT) { return true; } else if (event->type == MOUSE_UP_UIEVENT) { unsigned int itemIndex = static_cast<unsigned int>(_menuItems.size()) - (event->pt.y - rect().origin.y) / 20.0f; if (_didSelectItemFn) _didSelectItemFn(this, itemIndex); return true; } } else { if (event->type == MOUSE_MOVED_UIEVENT && _highlightedItemIndex >= 0) { _highlightedItemIndex = -1; setDirty(); } } return false; } // --------------------------------------------------------------------------------------------------------------------- void Menu::popUpContextMenu(std::shared_ptr<Menu> menu, Point location, View* view) { _window = std::make_unique<Window>(); Size size = menu->contentSize(); _highlightedItemIndex = -1; _window->contentView()->addSubview(menu); _window->contentView()->setLayoutFn([menu](View* sender, Rect frame) { menu->setFrame(sender->bounds()); }); menu->setDisposeFn([](View* sender) { Menu::closePopUp(); }); _window->setDidResignKeyWindowFn([](Window* sender) { Menu::closePopUp(); }); auto viewOrigin = view->rect().origin; _window->open(makeRect(location.x + viewOrigin.x, location.y + viewOrigin.y - size.height, size.width, size.height), true); } // --------------------------------------------------------------------------------------------------------------------- void Menu::closePopUp() { if (_window) { _window->close(); _window = nullptr; } }
38.478992
120
0.463202
dcliche
0c6eb7510c7714020e18be9ee3c70f08954d8966
59
cpp
C++
RealmLib/Structures/TileData.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
10
2018-11-25T21:59:43.000Z
2022-01-09T22:41:52.000Z
RealmLib/Structures/TileData.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
1
2018-11-28T12:59:59.000Z
2018-11-28T12:59:59.000Z
RealmLib/Structures/TileData.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
6
2018-12-28T22:34:13.000Z
2021-10-16T10:17:17.000Z
#include "stdafx.h" #include <DataStructures/TileData.h>
11.8
36
0.745763
SometimesRain
0c6f9f5fd9163b76aee5191714296f2b890997ee
29,986
cpp
C++
scripts/workload.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
150
2015-01-14T15:06:38.000Z
2018-08-28T09:34:17.000Z
scripts/workload.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
28
2015-05-11T02:45:39.000Z
2018-08-24T11:43:17.000Z
scripts/workload.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
91
2015-05-04T09:52:41.000Z
2018-08-18T13:02:15.000Z
#include <iostream> #include <set> #include <vector> #include <deque> #include <algorithm> #include <fstream> #include <mutex> #include <thread> #include <string> #include <atomic> #include <sstream> #include "../Database/Txn_manager.h" using namespace std; struct MyTriple { string subject; string predicate; string object; MyTriple(string _subject, string _predicate, string _object):subject(_subject), predicate(_predicate), object(_object){ } }; const int txn_num = 1000; const int read_num = 5; const int update_num = 1; const int threads_num = 4; const int oltp_query_num = 2; const int oltp_update_num = 1; const bool is_wat = false; const int model = 3; //1:seq_txn 2:part_txn 3:oltp_txn other: no_txn const string updates_path = "../../insert_lubm.nt"; //const string updates_path = "../../../../watdiv_insert.nt"; const string wat_name = "wat"; const string lubm_name = "lubm"; const string dir = lubm_name + to_string(oltp_update_num) + '.' + to_string(oltp_query_num) ; const string time_statics = "/time_statics.txt"; const string restart_statics = "/restart_statics.txt"; vector<long> time_rec(threads_num * txn_num); vector<int> restartcnts(threads_num * txn_num); vector<string> updates_line; int line_num = 0; atomic<int> offset = {0}; atomic<int> restart_times = {0}; string lubm_q[21] = { "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x where{?x rdf:type ub:GraduateStudent.?y rdf:type ub:University.?z rdf:type ub:Department.?x ub:memberOf ?z.?z ub:subOrganizationOf ?y.?x ub:undergraduateDegreeFrom ?y.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x where{?x rdf:type ub:Course.?x ub:name ?y.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x where { ?x rdf:type ub:UndergraduateStudent. ?y rdf:type ub:University. ?z rdf:type ub:Department. ?x ub:memberOf ?z. ?z ub:subOrganizationOf ?y. ?x ub:undergraduateDegreeFrom ?y. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x ?y1 ?y2 ?y3 where { ?x ub:worksFor <http://www.Department0.University0.edu>. ?x rdf:type ub:FullProfessor. ?x ub:name ?y1. ?x ub:emailAddress ?y2. ?x ub:telephone ?y3. } ", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x where { ?x ub:subOrganizationOf <http://www.Department0.University0.edu>. ?x rdf:type ub:ResearchGroup. } ", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x ?y where { ?y ub:subOrganizationOf <http://www.University0.edu>. ?y rdf:type ub:Department. ?x ub:worksFor ?y. ?x rdf:type ub:FullProfessor. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?x ?y ?z where { ?x rdf:type ub:UndergraduateStudent. ?y rdf:type ub:FullProfessor. ?z rdf:type ub:Course. ?x ub:advisor ?y. ?x ub:takesCourse ?z. ?y ub:teacherOf ?z.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { ?X rdf:type ub:GraduateStudent. ?X ub:takesCourse <http://www.Department0.University0.edu/GraduateCourse0>. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X ?Y ?Z where { ?X rdf:type ub:GraduateStudent. ?Y rdf:type ub:University. ?Z rdf:type ub:Department. ?X ub:memberOf ?Z. ?Z ub:subOrganizationOf ?Y. ?X ub:undergraduateDegreeFrom ?Y.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { ?X rdf:type ub:Publication. ?X ub:publicationAuthor <http://www.Department0.University0.edu/AssistantProfessor0>.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?Y1 ?Y2 ?Y3 where { ?X rdf:type ub:FullProfessor. ?X ub:worksFor <http://www.Department0.University0.edu>. ?X ub:name ?Y1. ?X ub:emailAddress ?Y2. ?X ub:telephone ?Y3.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { ?X ub:memberOf <http://www.Department0.University0.edu>. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { ?X rdf:type ub:UndergraduateStudent. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X ?Y where{ ?X rdf:type ub:Student. ?Y rdf:type ub:Course. ?X ub:takesCourse ?Y. <http://www.Department0.University0.edu/AssociateProfessor0> ub:teacherOf ?Y.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { ?X rdf:type ub:UndergraduateStudent. ?Y rdf:type ub:Department.?X ub:memberOf ?Y. ?Y ub:subOrganizationOf <http://www.University0.edu>. ?X ub:emailAddress ?Z.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X ?Y ?Z where { ?X rdf:type ub:UndergraduateStudent. ?Z rdf:type ub:Course. ?X ub:advisor ?Y. ?Y ub:teacherOf ?Z. ?X ub:takesCourse ?Z.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { ?X rdf:type ub:GraduateStudent. ?X ub:takesCourse <http://www.Department0.University0.edu/GraduateCourse0>. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where{ ?X rdf:type ub:ResearchGroup. ?X ub:subOrganizationOf <http://www.University0.edu>.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X ?Y where { ?Y rdf:type ub:Department. ?X ub:worksFor ?Y. ?Y ub:subOrganizationOf <http://www.University0.edu>. }", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where { <http://www.University0.edu> ub:undergraduateDegreeFrom ?X.}", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> select ?X where{ ?X rdf:type ub:UndergraduateStudent.}" }; vector<MyTriple> triples; void write_statics() { map<long, int> rec; ofstream time_if; cerr << dir << endl; string path = dir + time_statics; cerr << path << endl; time_if.open(path.c_str()); for(auto t: time_rec) { rec[t]++; } for(auto it = rec.begin(); it != rec.end(); it++) { time_if << it->first << " " << it->second << endl; } time_if.close(); string path1 = dir + restart_statics; time_if.open(path1.c_str()); map<int, int> cnt; for(auto t: restartcnts) { cnt[t]++; } for(auto it = cnt.begin(); it != cnt.end(); it++) { time_if << it->first << " " << it->second << endl; } time_if.close(); } void read_triples() { ifstream insert_if; insert_if.open(updates_path.c_str()); string line; int len = line.length(); while(!insert_if.eof()){ if(is_wat){ int idx = 0; getline(insert_if, line); cout << line << endl; string s = "", p = "", o = ""; while(line[idx] != '>') s.push_back(line[idx++]); s.push_back(line[idx++]); while(line[idx] == '\t') idx++; while(line[idx] != '>') p.push_back(line[idx++]); p.push_back(line[idx++]); while(line[idx] == '\t') idx++; char ch = line[idx++]; o.push_back(ch); if(ch == '\"'){ while(line[idx] != '\"') idx++; o.push_back(line[idx]); } else if(ch == '<'){ while(line[idx] != '>') { o.push_back(line[idx]); idx++; } o.push_back('>'); } //cerr << s << " " << p << " " << o << endl; MyTriple tri(s, p, o); triples.push_back(tri); line_num++; } else{ int idx = 0; getline(insert_if, line); cout << line << endl; stringstream ss(line); string s, p, o; ss >> s >> p >> o; //cerr << s << " " << p << " " << o << endl; MyTriple tri(s, p, o); triples.push_back(tri); line_num++; } } cout << "lines: " << line_num << endl; insert_if.close(); } vector<string> get_node_query(vector<MyTriple> &triples) { vector<string> ret; int k = 0; for(auto &tri: triples){ string q1 = "select ?x where {"; //q1 = q1 + tri.subject + " ?p ?x}"; q1 = q1 + "?x ?p " + tri.object + "}"; string q2 = "select ?x where {"; //q2 = q2 + "?x ?p " + tri.object + "}"; q2 = q2 + tri.subject + " ?p ?x}"; ret.push_back(q1); ret.push_back(q2); ret.push_back(q1); ret.push_back(q2); k += 4; if(k >= oltp_query_num) return ret; } while(k < oltp_query_num){ ret.push_back(ret[ret.size()-2]); ret.push_back(ret[ret.size()-2]); k += 2; } return ret; } string get_insert_sparql(MyTriple& triple) { string ret = "insert data { "; ret = ret + triple.subject + " " + triple.predicate + " " + triple.object + " .}"; return ret; } long start = Util::get_cur_time(); struct task { vector<string> query; vector<string> updates; task() { query.clear(); updates.clear(); } ~task(){ query.clear(); updates.clear(); } void add_query(string line){ query.push_back(line); } void add_updates(string line){ updates.push_back(line); } vector<string>& get_query(){ return query; } vector<string>& get_updates(){ return updates; } bool is_empty() { return updates.size() <= 0; } }; void open_file() { ifstream insert_if; insert_if.open(updates_path.c_str()); string sparql = "INSERT DATA {"; string line; while(!insert_if.eof()){ sparql = "INSERT DATA {"; getline(insert_if, line); if(line.size() > 0) line[line.size() - 1] = ' '; sparql += line; sparql += "}"; updates_line.push_back(sparql); line_num++; if(line_num % 100000 == 0) cout << line_num << endl; } cout << updates_line[2] << endl; cout << "lines: " << line_num << endl; insert_if.close(); } task get_task_1(Txn_manager& txn_m, int k) { task ret; for(int i = 0; i < read_num; i++) { ret.add_query(lubm_q[rand() % 21]); } for(int i = 0, j = k; i < update_num; i++, k++) { //cerr << idx << endl; if(j >= line_num) return ret; ret.add_updates(updates_line[j]); } cout << "get task success" << endl; return ret; } task get_task(Txn_manager& txn_m) { task ret; for(int i = 0; i < read_num; i++) { ret.add_query(lubm_q[rand() % 21]); } // ret.add_query(lubm_q[0]); // ret.add_query(lubm_q[3]); for(int i = 0; i < update_num; i++) { int idx = offset.fetch_add(1); //cerr << idx << endl; if(idx >= line_num) return ret; if(idx != 0 && idx % 1000 == 0){ long end = Util::get_cur_time(); cerr << idx << " : " << end - start << " ms" << endl; //cerr << "check times " << txn_m.GetDatabase()->check_times.load() << endl; //cerr << "restart times:" << restart_times.load() << endl; start = end; } if(idx % 20000 == 0 && idx != 0){ txn_m.Checkpoint(); cerr << "checkpoint done!" << endl; } ret.add_updates(updates_line[idx]); } cout << "get task success" << endl; return ret; } task get_oltp_task(int k) { task ret; vector<MyTriple> data; for(int i = 0, j = k; i < oltp_update_num; i++, j++) { if(j >= line_num) break; //ret.add_updates(get_insert_sparql(triples[j])); data.push_back(triples[j]); } auto qv = get_node_query(data); for(auto q: qv) ret.add_query(q); for(auto t: data) { auto iv = get_insert_sparql(t); ret.add_updates(iv); } return ret; } task get_oltp_task_wat() { task ret; vector<MyTriple> data; for(int i = 0; i < oltp_update_num; i++) { int idx = offset.fetch_add(1); //cerr << idx << endl; if(idx >= line_num) return ret; //ret.add_updates(get_insert_sparql(triples[j])); data.push_back(triples[idx]); } auto qv = get_node_query(data); for(auto q: qv) ret.add_query(q); for(auto t: data) { auto iv = get_insert_sparql(t); ret.add_updates(iv); } return ret; } void run_transaction_1(int isolevel, Txn_manager& txn_m, int idx) { int update_lines = line_num / threads_num; int cnt = 0; int k = update_lines * idx; //cerr << "thread " << idx << " k: " << k << endl; task t; string res, sparql; int base_time = 1000; txn_id_t TID; int num = 0; bool prev_succ = true; task tsk; long start_tv = Util::get_cur_time(); while(true){ if(prev_succ){//reset tsk = get_task_1(txn_m, k); //print_task(tsk); base_time = 1000; if(tsk.is_empty()) return; } else prev_succ = true; //retry vector<string>& query = tsk.get_query(); vector<string>& updates = tsk.get_updates(); //cout << "query.size()" << query.size() << " " << "updates.size()" << updates.size() << endl; int ret = 0; TID = txn_m.Begin(static_cast<IsolationLevelType>(isolevel)); for(int i = 0; i < query.size(); i++){ // cout << "query " << i << " " << query[i] << endl; ret = txn_m.Query(TID, query[i], res); if(ret != -100) { usleep(base_time); //base_time = min(base_time*2, 1000); prev_succ = false; //cerr << "query failed and abort!" << endl; restart_times++; break; } } if(prev_succ == false) continue; for(int i = 0; i < updates.size(); i++){ //cout << "update " << i << " " << updates[i] << endl; ret = txn_m.Query(TID, updates[i], res); if(ret < 0) { usleep(base_time); //base_time = min(base_time*2, 1000); prev_succ = false; restart_times++; break; } //if(ret >= 0) cout << "update nums" << ret << endl; } if(prev_succ == false) continue; if(txn_m.Commit(TID) != 0) { prev_succ = false; } else{ k += update_num; cnt++; if(cnt == 1000){ long end_tv = Util::get_cur_time(); cerr << (end_tv - start_tv) << " ms" << endl; return; } } } } void OLTP_workload(int isolevel, Txn_manager& txn_m, int idx) { const int max_time = 250000; const int base = 1000; const int wait_time = 1000; int update_lines = (line_num+1) / threads_num; int k = update_lines * idx; //cerr << "oltp thread " << idx << " k: " << k << endl; task t; string res, sparql; int base_time = base; txn_id_t TID; int num = 0; bool prev_succ = true; task tsk; int cnt = 0; long start = Util::get_cur_time(); int restart_cnt = 0; while(true){ if(prev_succ){//reset if(is_wat) tsk = get_oltp_task_wat(); else tsk = get_oltp_task(k); k += oltp_update_num; //print_task(tsk); base_time = base; if(tsk.is_empty()) return; } else prev_succ = true; //retry vector<string>& query = tsk.get_query(); vector<string>& updates = tsk.get_updates(); //cout << "query.size()" << query.size() << " " << "updates.size()" << updates.size() << endl; int ret = 0; TID = txn_m.Begin(static_cast<IsolationLevelType>(isolevel)); //int qsize = min(query.size(), oltp_query_num); int j = 0; for(int i = 0; i < updates.size(); i++){ for(int t = 0; t < 2 && j < oltp_query_num; t++, j++){ // cout << "query " << i << " " << query[i] << endl; ret = txn_m.Query(TID, query[j], res); if(ret != -100) { usleep(base_time); restart_cnt++; base_time = min(base_time*2, max_time); prev_succ = false; //cerr << "query failed and abort!" << endl; restart_times++; if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; break; } } if(prev_succ == false) break; //cout << "update " << i << " " << updates[i] << endl; ret = txn_m.Query(TID, updates[i], res); if(ret < 0) { usleep(base_time); restart_cnt++; base_time = min(base_time*2, max_time); prev_succ = false; restart_times++; if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; break; } //if(ret >= 0) cout << "update nums" << ret << endl; if(prev_succ == false) break; for(int t = 0;t < 2 && j < oltp_query_num; t++, j++){ // cout << "query " << i << " " << query[i] << endl; ret = txn_m.Query(TID, query[j], res); if(ret != -100) { usleep(base_time); restart_cnt++; base_time = min(base_time*2, max_time); prev_succ = false; //cerr << "query failed and abort!" << endl; restart_times++; if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; break; } } if(prev_succ == false) break; } if(prev_succ == false) continue; for(;j < oltp_query_num; j++){ // cout << "query " << i << " " << query[i] << endl; ret = txn_m.Query(TID, query[j], res); if(ret != -100) { usleep(base_time); restart_cnt++; base_time = min(base_time*2, max_time); prev_succ = false; //cerr << "query failed and abort!" << endl; restart_times++; if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; break; } } if(prev_succ == false) continue; if(txn_m.Commit(TID) != 0) { restart_cnt++; prev_succ = false; } else{ long end = Util::get_cur_time(); time_rec[idx*txn_num+cnt] = end - start; start = end; restartcnts[idx*txn_num+cnt] = restart_cnt; restart_cnt = 0; cnt++; if(cnt % 100 == 0) cerr << cnt << endl; if(cnt == txn_num) return; } } } void print_task(task & tsk) { vector<string> query = tsk.get_query(); vector<string> updates = tsk.get_updates(); cout << "print task" << endl; for(auto q: query) cout << q << endl; for(auto u: updates) cout << u << endl; } void run_transaction(int isolevel, Txn_manager& txn_m) { //cerr << "run_transaction thread "<< endl; task t; string res, sparql; int cnt = 0; const int base = 1000; const int max_time = 250000; int base_time = base; txn_id_t TID; int num = 0; bool prev_succ = true; task tsk; int k = 0; while(true){ if(prev_succ){//reset tsk = get_task(txn_m); print_task(tsk); base_time = base; if(tsk.is_empty()) return; } else prev_succ = true; //retry vector<string>& query = tsk.get_query(); vector<string>& updates = tsk.get_updates(); //cout << "query.size()" << query.size() << " " << "updates.size()" << updates.size() << endl; int ret = 0; TID = txn_m.Begin(static_cast<IsolationLevelType>(isolevel)); for(int i = 0; i < query.size(); i++){ // cout << "query " << i << " " << query[i] << endl; ret = txn_m.Query(TID, query[i], res); if(ret != -100) { usleep(base_time); base_time = min(base_time*2, max_time); prev_succ = false; //cerr << "query failed and abort!" << endl; restart_times++; //if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; break; } } if(prev_succ == false) continue; for(int i = 0; i < updates.size(); i++){ //cout << "update " << i << " " << updates[i] << endl; ret = txn_m.Query(TID, updates[i], res); if(ret < 0) { usleep(base_time); base_time = min(base_time*2, max_time); prev_succ = false; restart_times++; //if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; break; } //if(ret >= 0) cout << "update nums" << ret << endl; } if(prev_succ == false) continue; if(txn_m.Commit(TID) != 0) { restart_times++; if(restart_times.load() % 1000 == 0) cerr << restart_times.load() << endl; prev_succ = false; } else{ k++; if(k == 1000){ return; } } } } void read_only_transaction(int isolevel, Txn_manager& txn_m) { int times = 50; txn_id_t TID; int ret = 0; string res; cerr << "read_only_transaction" << endl; for(int i = 0; i < times; i++) { //cerr << i << endl; TID = txn_m.Begin(static_cast<IsolationLevelType>(isolevel)); ret = txn_m.Query(TID, lubm_q[1], res); if(ret < -100) { cerr << " read_only_transaction failed!" << ret << endl; continue; } ret = txn_m.Query(TID, lubm_q[1], res); if(ret != -100) { cerr << " read_only_transaction failed! " << ret <<endl; continue; } if(txn_m.Commit(TID) != 0) { cerr << "read only transaction commit failed!" << endl; continue; } } } void create_versions(Txn_manager& txn_m) { string query = "select ?v {<V1> <R1> ?v.}"; string insert1 = "insert data { <V1> <R1> \"5\"^^<http://www.w3.org/2001/XMLSchema#integer> }"; string insert2 = "insert data { <V1> <R1> \"15\"^^<http://www.w3.org/2001/XMLSchema#integer> }"; string delete1 = "delete data { <V1> <R1> \"5\"^^<http://www.w3.org/2001/XMLSchema#integer> }"; string delete2 = "delete data { <V1> <R1> \"15\"^^<http://www.w3.org/2001/XMLSchema#integer> }"; string res; txn_id_t id = txn_m.Begin(); txn_m.Query(id, query, res); txn_m.print_txn_dataset(id); txn_m.Commit(id); id = txn_m.Begin(); txn_m.Query(id, insert1, res); txn_m.print_txn_dataset(id); txn_m.Commit(id); id = txn_m.Begin(); txn_m.Query(id, insert2, res); txn_m.print_txn_dataset(id); txn_m.Commit(id); id = txn_m.Begin(); txn_m.Query(id, delete1, res); txn_m.print_txn_dataset(id); txn_m.Commit(id); id = txn_m.Begin(); txn_m.Query(id, delete2, res); txn_m.print_txn_dataset(id); txn_m.Commit(id); } void no_txn_update(Database &db) { const string insert_filename = "./scripts/insert.nt"; const string delete_filename = "./scripts/delete.nt"; fstream in; string line, sparql, res; ResultSet rs; in.open(insert_filename, ios::in); while(getline(in, line)) { sparql = "insert data {" + line + "}"; FILE *fp = stdout; db.query(sparql, rs, fp); } in.close(); in.open(delete_filename, ios::in); while(getline(in, line)) { sparql = "delete data {" + line + "}"; FILE *fp = stdout; db.query(sparql, rs, fp); } in.close(); } bool single_txn(int threads_num, Txn_manager& txn_m) { txn_id_t TID = txn_m.Begin(static_cast<IsolationLevelType>(3)); ifstream in; string line, sparql, res; in.open("./scripts/insert.nt", ios::in); int num = 0; while(getline(in, line)) { sparql = "insert data {" + line + "}"; int ret = txn_m.Query(TID, sparql, res); num += ret; //txn_m.Get_Transaction(TID)->print_all(); //if(ret != 0) cerr << "wrong answer!" << endl; // getline(in, line); // sparql = "insert data {" + line + "}"; // ret = txn_m.Query(TID, sparql, res); //txn_m.Get_Transaction(TID)->print_all(); //if(ret != 0) cerr << "wrong answer!" << endl; } in.close(); in.open("./scripts/delete.nt", ios::in); while(getline(in, line)) { sparql = "delete data{" + line + "}"; int ret = txn_m.Query(TID, sparql, res); //if(ret == 0) cerr << "wrong answer!wrong answer!wrong answer!wrong answer!" << endl; num += ret; } //txn_m.Get_Transaction(TID)->print_all(); in.close(); txn_m.Commit(TID); cout << "update num: " << num << endl; return true; } void check_results(int threads_num, Txn_manager& txn_m) { txn_id_t TID = txn_m.Begin(); ifstream in; in.open("./scripts/insert.nt", ios::in); for(int i = 0; i < threads_num; i++) { string line, sparql, res; getline(in, line); sparql = "ask where {" + line + "}"; int ret = txn_m.Query(TID, sparql, res); cout << res << endl; getline(in, line); sparql = "ask where {" + line + "}"; ret = txn_m.Query(TID, sparql, res); cout << res << endl; } in.close(); in.open("./scripts/delete.nt", ios::in); for(int i = 0; i < threads_num; i++) { string line, sparql, query, res; getline(in, line); sparql = "ask where{" + line + "}"; int ret = txn_m.Query(TID, sparql, res); cout << ret << endl; } txn_m.Commit(TID); } int main(int argc, char* argv[]) { //open_file(); if(model == 3 ){ read_triples(); cerr << "triples read" << endl; auto tk = get_oltp_task_wat(); auto qs = tk.get_query(); auto us = tk.get_updates(); for(int i = 0; i < qs.size(); i++) cerr << qs[i] << endl; for(int i = 0; i < us.size(); i++) cerr << us[i] << endl; } else{ open_file(); // auto tk = get_task(); // auto qs = tk.get_query(); // auto us = tk.get_updates(); // for(int i = 0; i < qs.size(); i++) cerr << qs[i] << endl; // for(int i = 0; i < us.size(); i++) cerr << us[i] << endl; } // atomic<__uint128_t> l; // cerr << l.is_lock_free() << endl; Util util; string lubm_10M = "lubm10M"; string lubm_100M = "lubm100M"; string lubm_1M = "lubm1M"; string wat_1M = "watdiv1M"; string wat_10M = "watdiv10M"; string db_folder = "lubm"; Database _db(db_folder); _db.load(); cerr << "finish loading" << endl; Txn_manager txn_m(&_db, string("lubm_1M")); //threads_num = thread::hardware_concurrency()-1; vector<thread> pool(threads_num); int n = pool.size(); long start1 = Util::get_cur_time(); if(model == 1){ for(int i = 0; i < n ; i++) { pool[i] = thread(run_transaction, 1 , ref(txn_m)); } } else if(model == 2){ for(int i = 0; i < n ; i++) { pool[i] = thread(run_transaction_1, 2 , ref(txn_m), i); } } else if(model == 3){ for(int i = 0; i < n ; i++) { pool[i] = thread(OLTP_workload, 1 , ref(txn_m), i); } } // // for(int i = 0; i < n; i++) // // { // // pool[i].join(); // // } // // for(int i = 0; i < n; i++) // // { // // pool[i] = thread(read_only_transaction, 1, ref(txn_m)); // // } if(model == 1 || model == 2 || model == 3){ for(int i = 0; i < n; i++) { pool[i].join(); } } long end1 = Util::get_cur_time(); cerr << end1 - start1 << "ms" << endl; //cerr << restart_times.load() << endl; // cout << "workload finished!" << endl; cerr << "restart times" << restart_times.load() << endl; cerr << time_rec[0] << " " << restartcnts[0] << endl; write_statics(); //cerr << "write statics over" << endl; return 0; }
34.706019
328
0.532982
SoftlySpoken
0c7181d1e871ebcd1848c446b7097e8dda89349a
2,045
cpp
C++
gloox-1.0.13/src/delayeddelivery.cpp
hailanghu/gloox_test
00b0d9b22335e50eb957c838ffa2b8f38931b60f
[ "Apache-2.0" ]
null
null
null
gloox-1.0.13/src/delayeddelivery.cpp
hailanghu/gloox_test
00b0d9b22335e50eb957c838ffa2b8f38931b60f
[ "Apache-2.0" ]
null
null
null
gloox-1.0.13/src/delayeddelivery.cpp
hailanghu/gloox_test
00b0d9b22335e50eb957c838ffa2b8f38931b60f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2006-2015 by Jakob Schröter <js@camaya.net> This file is part of the gloox library. http://camaya.net/gloox This software is distributed under a license. The full license agreement can be found in the file LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. */ #include "delayeddelivery.h" #include "tag.h" namespace gloox { DelayedDelivery::DelayedDelivery( const JID& from, const std::string stamp, const std::string& reason ) : StanzaExtension( ExtDelay ), m_from( from ), m_stamp( stamp ), m_reason( reason ), m_valid( false ) { if( !m_stamp.empty() ) m_valid = true; } DelayedDelivery::DelayedDelivery( const Tag* tag ) : StanzaExtension( ExtDelay ), m_valid( false ) { if( !tag || !tag->hasAttribute( "stamp" ) ) return; if( !( tag->name() == "x" && tag->hasAttribute( XMLNS, XMLNS_X_DELAY ) ) ) if( !( tag->name() == "delay" && tag->hasAttribute( XMLNS, XMLNS_DELAY ) ) ) return; m_reason = tag->cdata(); m_stamp = tag->findAttribute( "stamp" ); m_from = tag->findAttribute( "from" ); m_valid = true; } DelayedDelivery::~DelayedDelivery() { } const std::string& DelayedDelivery::filterString() const { static const std::string filter = "/presence/delay[@xmlns='" + XMLNS_DELAY + "']" "|/message/delay[@xmlns='" + XMLNS_DELAY + "']" "|/presence/x[@xmlns='" + XMLNS_X_DELAY + "']" "|/message/x[@xmlns='" + XMLNS_X_DELAY + "']"; return filter; } Tag* DelayedDelivery::tag() const { if( !m_valid ) return 0; Tag* t = new Tag( "delay" ); t->addAttribute( XMLNS, XMLNS_DELAY ); if( m_from ) t->addAttribute( "from", m_from.full() ); if( !m_stamp.empty() ) t->addAttribute( "stamp", m_stamp ); if( !m_reason.empty() ) t->setCData( m_reason ); return t; } }
26.907895
105
0.619071
hailanghu
0c75923e94217498c27ee44cb309821b227cf385
3,740
hpp
C++
Code/Engine/Math/Matrix44.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/Math/Matrix44.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/Math/Matrix44.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#pragma once #include "DirectXMath.h" #include "Engine/Math/Vector3.hpp" #include "Engine/Math/MathUtils.hpp" using namespace DirectX; class Matrix44 { public: Matrix44() { } Matrix44(XMVECTOR r1, XMVECTOR r2, XMVECTOR r3, XMVECTOR r4) : m_matrix(r1, r2, r3, r4) { } Matrix44(Vector4 r1, Vector4 r2, Vector4 r3, Vector4 r4) : m_matrix(XMVectorSet(r1.x, r1.y, r1.z, r1.w), XMVectorSet(r2.x, r2.y, r2.z, r2.w), XMVectorSet(r3.x, r3.y, r3.z, r3.w), XMVectorSet(r4.x, r4.y, r4.z, r4.w)) { } Matrix44(XMMATRIX mat) : m_matrix(mat) { } void LookAt(Vector3& camPos, float yaw, float pitch, float roll); void SetAsPerspectiveProjection(float fovRads, float aspectRatio, float near, float farPlane); void SetAsOrthographicProjection(float viewWidth, float viewHeight, float zNear, float zFar); void SetAsIdentity(); void Transpose(); void Invert(); void SetPosition(const Vector3& position); void Scale(const Vector3& scale); XMMATRIX m_matrix; static const Matrix44 BASIS; static const Matrix44 IDENTITY; }; //--------------------------------------------------------------------------------------------------------------------------- inline Matrix44 Inverse(XMMATRIX mat) { return Matrix44(XMMatrixInverse(nullptr, mat)); } //--------------------------------------------------------------------------------------------------------------------------- inline Matrix44 TransposeMatrix(XMMATRIX mat) { return Matrix44(XMMatrixTranspose(mat)); } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::Invert() { m_matrix = XMMatrixInverse(nullptr, m_matrix); } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::Transpose() { m_matrix = XMMatrixTranspose(m_matrix); } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::LookAt(Vector3& camPos, float yaw, float pitch, float roll) { XMVECTOR eye = XMVectorSet(camPos.x, camPos.y, camPos.z, 1.f); m_matrix = XMMatrixRotationRollPitchYaw(ToRadians(pitch), ToRadians(yaw), ToRadians(roll)); m_matrix.r[3] = eye; } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::SetAsPerspectiveProjection(float fovRads, float aspectRatio, float nearPlane, float farPlane) { m_matrix = XMMatrixPerspectiveFovLH(fovRads, aspectRatio, nearPlane, farPlane); } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::SetAsOrthographicProjection(float viewWidth, float viewHeight, float zNear, float zFar) { m_matrix = XMMatrixOrthographicOffCenterLH(0.f, viewWidth, 0.f, viewHeight, zNear, zFar); } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::SetAsIdentity() { m_matrix = XMMatrixIdentity(); } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::SetPosition(const Vector3& position) { XMVECTOR pos = XMVectorSet(position.x, position.y, position.z, 1.f); m_matrix.r[3] = pos; } //--------------------------------------------------------------------------------------------------------------------------- inline void Matrix44::Scale(const Vector3& scale) { XMMATRIX scalingMatrix = XMMatrixScaling(scale.x, scale.y, scale.z); m_matrix = scalingMatrix * m_matrix; }
34.62963
125
0.490107
ntaylorbishop
0c803c5b0e794fd767a56a5a62ca95e00a55fa68
3,646
cpp
C++
csgocheat/hooks/cte_effects.cpp
garryhvh420/e_xyz
668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9
[ "Apache-2.0" ]
null
null
null
csgocheat/hooks/cte_effects.cpp
garryhvh420/e_xyz
668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9
[ "Apache-2.0" ]
null
null
null
csgocheat/hooks/cte_effects.cpp
garryhvh420/e_xyz
668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9
[ "Apache-2.0" ]
null
null
null
#include "cte_effects.h" #include "../hacks/c_resolver.h" #include "../sdk/c_debug_overlay.h" c_fire g_firingresolver; void c_ct_effects::hook() { auto dwFireBullets = *(DWORD**)(sig("client_panorama.dll", "55 8B EC 51 53 56 8B F1 BB ? ? ? ? B8") + 0x131); static c_hook hook((PDWORD)dwFireBullets); _FireBullets = hook.apply<FireBullets_t>(7, TEFireBulletsPostDataUpdate_h); } void __stdcall c_ct_effects::FireBullets_PostDataUpdate(C_TEFireBullets *thisptr, DataUpdateType_t updateType) { const auto local = c_cs_player::get_local_player(); if (!engine_client()->is_ingame() || !engine_client()->is_connected()) return _FireBullets(thisptr, updateType); if (config.rage.enabled && thisptr && config.esp.show_on_shot_hitboxes) { int iPlayer = thisptr->m_iPlayer + 1; if (iPlayer < 64) { auto player = (c_cs_player*)client_entity_list()->get_client_entity(iPlayer); if (!player->is_enemy() || !player->is_alive() || player->get_gun_game_immunity()) return _FireBullets(thisptr, updateType); matrix3x4 animation_matrix[128]; matrix3x4 setup_bones_matrix[128]; auto animations = animation_system->get_latest_firing_animation(player); if (player->setup_bones(setup_bones_matrix, 128, bone_used_by_anything, player->get_simtime())) { const auto model = player->get_model(); if (!model) return _FireBullets(thisptr, updateType); const auto hdr = model_info_client()->get_studio_model(model); if (!hdr) return _FireBullets(thisptr, updateType); if (!animations.has_value()) return _FireBullets(thisptr, updateType); std::memcpy(animation_matrix, animations.value()->bones, sizeof(animations.value()->bones)); const auto set = hdr->get_hitbox_set(0); if (set) { for (auto i = 0; i < set->numhitboxes; i++) { const auto hitbox = set->get_hitbox(i); if (!hitbox) continue; if (hitbox->radius == -1.0f) { const auto position = math::matrix_position(animation_matrix[hitbox->bone]); const auto position_actual = math::matrix_position(setup_bones_matrix[hitbox->bone]); const auto roation = math::angle_matrix(hitbox->rotation); auto transform = math::multiply_matrix(animation_matrix[hitbox->bone], roation); auto transform_actual = math::multiply_matrix(setup_bones_matrix[hitbox->bone], roation); const auto angles = math::matrix_angles(transform); const auto angles_actual = math::matrix_angles(transform_actual); debug_overlay()->add_box_overlay(position, hitbox->bbmin, hitbox->bbmax, angles, 255, 0, 0, 150, 0.8f); debug_overlay()->add_box_overlay(position_actual, hitbox->bbmin, hitbox->bbmax, angles_actual, 0, 0, 255, 150, 0.8f); } else { c_vector3d min, max, min_actual, max_actual; math::vector_transform(hitbox->bbmin, animation_matrix[hitbox->bone], min); math::vector_transform(hitbox->bbmax, animation_matrix[hitbox->bone], max); math::vector_transform(hitbox->bbmin, setup_bones_matrix[hitbox->bone], min_actual); math::vector_transform(hitbox->bbmax, setup_bones_matrix[hitbox->bone], max_actual); debug_overlay()->add_capsule_overlay(min, max, hitbox->radius, 255, 0, 0, 150, 0.8f); debug_overlay()->add_capsule_overlay(min_actual, max_actual, hitbox->radius, 0, 0, 255, 150, 0.8f); } } } } } } _FireBullets(thisptr, updateType); } __declspec (naked) void __stdcall c_ct_effects::TEFireBulletsPostDataUpdate_h(DataUpdateType_t updateType) { __asm { push[esp + 4] push ecx call FireBullets_PostDataUpdate retn 4 } }
31.982456
124
0.699397
garryhvh420
0c8be596d1e2b879ed34358403917d0f3a328ffa
4,189
cpp
C++
app/src/main/jni/ProcForm.cpp
oaup/imgprocess
37c7aa77210bbfe51347fc62cabd696d7281e7e8
[ "MIT" ]
2
2020-08-19T06:06:11.000Z
2021-07-29T01:44:59.000Z
app/src/main/jni/ProcForm.cpp
oaup/imgprocess
37c7aa77210bbfe51347fc62cabd696d7281e7e8
[ "MIT" ]
null
null
null
app/src/main/jni/ProcForm.cpp
oaup/imgprocess
37c7aa77210bbfe51347fc62cabd696d7281e7e8
[ "MIT" ]
null
null
null
/* Copyright (C) 2004 Yefeng Zheng This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You are free to use this program for non-commercial purpose. If you plan to use this code in commercial applications, you need additional licensing: please contact zhengyf@cfar.umd.edu */ //////////////////////////////////////////////////////////////////////////////////////////////// // File NAME: ProcForm.cpp // File Function: Model based line detection for batch form processing // // Developed by: Yefeng Zheng // First created: Aug. 2003 // University of Maryland, College Park /////////////////////////////////////////////////////////////////////////////////////////////////// #include "ProcForm.h" #include "GetProcessFile.h" #include "Tools.h" //CWinApp theApp; extern int GAP_VAR; /***************************************************************************** /* Name: Usage /* Function: Print help /* Parameter: NULL /* Return: NULL /*****************************************************************************/ void Usage( ) { printf( "Usage: ProcForm [-h] [-t] [-i] [-d] HMM_file img_file\n" ); printf( " -t -- Train an HMM model\n" ); printf( " -d -- Line detection\n" ); printf( " -i -- Form identification followed by line detection\n" ); printf( " with the automatically selected model.\n" ); printf( " HMM_file -- HMM model file or a list file of all HMM model files\n" ); printf( " img_file -- Image file, such as 1.tiff, *.tiff, etc.\n" ); printf( " -h -- Help\n" ); return; } /***************************************************************************** /* Name: _tmain /* Function: Main function of the program /* Parameter: /* Return: /*****************************************************************************/ //int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) //{ // int nOperation = OPER_IDLE; // int nLineOption = ALL_LINE; // char fnHMM[MAX_PATH]; // char fnFormIdConfig[MAX_PATH]; // // strcpy( fnHMM, "" ); // strcpy( fnFormIdConfig, "" ); // int bFilter = TRUE; // ////Parse command line // int i = 1; // for(;i<argc;i++) // { // if(argv[i][0] != '-') break; // ++i; // switch(tolower(argv[i-1][1])) // { // case 'g': // GAP_VAR = atoi( argv[i] ); // break; // case 't': // if( nOperation != OPER_IDLE ) // { // printf( "Wrong operation!\n" ); // Usage(); // } // nOperation = OPER_TRAIN; // i--; // break; // case 'd': // if( nOperation != OPER_IDLE ) // { // printf( "Wrong operation!\n" ); // Usage(); // } // nOperation = OPER_DETECT; // i--; // break; // case 'i': // if( nOperation != OPER_IDLE ) // { // printf( "Wrong operation!\n" ); // Usage(); // } // nOperation = OPER_FORM_ID; // i--; // break; // case 'l': // bFileList = TRUE; // i--; // break; // case '?': // Usage(); // return 0; // default: // printf( "Input parameters error!\n" ); // Usage(); // return -1; // } // } // if( i != argc-2 ) // { // printf( "Input parameters error!\n" ); // Usage(); // return -1; // } // if( nOperation == OPER_IDLE ) // { // printf( "Please input operation type!\n" ); // Usage(); // } // if( nOperation == OPER_TRAIN || nOperation == OPER_DETECT ) // strcpy( fnHMM, argv[i] ); // if( nOperation == OPER_FORM_ID ) // strcpy( fnFormIdConfig, argv[i] ); // strcpy( fnFile, argv[i+1] ); // // // Processing // switch(nOperation) // { // case OPER_TRAIN: // // Train the HMM model // TrainHMM( fnHMM, nLineOption, bFilter ); // break; // case OPER_DETECT: // //Detect lines // DetectLine( fnHMM, bFilter ); // break; // case OPER_FORM_ID: // //Form identification // FormIdentify( fnFormIdConfig, bFilter ); // break; // } // return 0; //}
25.858025
99
0.530914
oaup
0c914d2b56499e8c71962e5e1fbe305fc229503e
3,309
cpp
C++
Sources/Folders/SeedingCodes/TreeCodes.cpp
RedShyGuy/Vapecord-ACNL-Plugin
811bb9a0011470c18af6ac920c3a5a9d5985906f
[ "MIT" ]
52
2020-01-17T08:12:04.000Z
2022-03-19T20:02:57.000Z
Sources/Folders/SeedingCodes/TreeCodes.cpp
RedShyGuy/Vapecord-ACNL-Plugin
811bb9a0011470c18af6ac920c3a5a9d5985906f
[ "MIT" ]
67
2020-05-06T04:47:27.000Z
2022-03-31T16:25:19.000Z
Sources/Folders/SeedingCodes/TreeCodes.cpp
RedShyGuy/Vapecord-ACNL-Plugin
811bb9a0011470c18af6ac920c3a5a9d5985906f
[ "MIT" ]
7
2021-01-20T17:42:25.000Z
2022-03-08T09:29:42.000Z
#include "cheats.hpp" #include "Helpers/Address.hpp" #include "TextFileParser.hpp" #include "Helpers/Wrapper.hpp" #include "Color.h" namespace CTRPluginFramework { //Infinite Fruit Tree void fruitStays(MenuEntry *entry) { static const Address fruitstay(0x5972CC, 0x5967E4, 0x596314, 0x596314, 0x595C04, 0x595C04, 0x5958D8, 0x5958D8); std::vector<std::string> cmnOpt = { "" }; bool IsON = *(u32 *)fruitstay.addr == 0xEA000000; cmnOpt[0] = (IsON ? Color(pGreen) << Language->Get("VECTOR_ENABLED") : Color(pRed) << Language->Get("VECTOR_DISABLED")); Keyboard optKb(Language->Get("KEY_CHOOSE_OPTION")); optKb.Populate(cmnOpt); Sleep(Milliseconds(100)); int op = optKb.Open(); if(op == -1) return; Process::Patch(fruitstay.addr, *(u32 *)fruitstay.addr == 0xEA000000 ? 0xE1A01006 : 0xEA000000); fruitStays(entry); } //Axe Tree Shake void shakechop(MenuEntry *entry) { static const Address shake1(0x5971D4, 0x5966EC, 0x59621C, 0x59621C, 0x595B0C, 0x595B0C, 0x5957E0, 0x5957E0); static const Address shake2(0x5971DC, 0x5966F4, 0x596224, 0x596224, 0x595B14, 0x595B14, 0x5957E8, 0x5957E8); static const Address shake3(0x5971E4, 0x5966FC, 0x59622C, 0x59622C, 0x595B1C, 0x595B1C, 0x5957F0, 0x5957F0); static const Address shake4(0x5971EC, 0x596704, 0x596234, 0x596234, 0x595B24, 0x595B24, 0x5957F8, 0x5957F8); std::vector<std::string> cmnOpt = { "" }; bool IsON = *(u32 *)shake1.addr == 0xE1A00000; cmnOpt[0] = (IsON ? Color(pGreen) << Language->Get("VECTOR_ENABLED") : Color(pRed) << Language->Get("VECTOR_DISABLED")); Keyboard optKb(Language->Get("KEY_CHOOSE_OPTION")); optKb.Populate(cmnOpt); Sleep(Milliseconds(100)); s8 op = optKb.Open(); if(op < 0) return; Process::Patch(shake1.addr, *(u32 *)shake1.addr == 0xE1A00000 ? 0x0A000008 : 0xE1A00000); Process::Patch(shake2.addr, *(u32 *)shake2.addr == 0xE1A00000 ? 0x0A00005B : 0xE1A00000); Process::Patch(shake3.addr, *(u32 *)shake3.addr == 0x1A00001B ? 0x0A00001B : 0x1A00001B); Process::Patch(shake4.addr, *(u32 *)shake4.addr == 0xEA000080 ? 0x0A000080 : 0xEA000080); shakechop(entry); } //Fruit Tree Item Modifier void fruititemmod(MenuEntry *entry) { static const Address fruitmod(0x2FE6A0, 0x2FE510, 0x2FE5E8, 0x2FE5E8, 0x2FE5AC, 0x2FE5AC, 0x2FE5D0, 0x2FE5D0); static u32 val = 0x2018; if(entry->WasJustActivated()) { Process::Patch(fruitmod.addr, 0xE59F0020); Process::Write32(fruitmod.addr + 0xC, 0xE3500000); Process::Patch(fruitmod.addr + 0x28, val); } if(entry->Hotkeys[0].IsDown()) { if(Wrap::KB<u32>(Language->Get("ENTER_ID"), true, 8, val, val)) Process::Patch(fruitmod.addr + 0x28, val); } if(!entry->IsActivated()) { Process::Patch(fruitmod.addr, 0xE59F1020); Process::Patch(fruitmod.addr + 0xC, 0xE1510002); Process::Patch(fruitmod.addr + 0x28, 0x172B); } } //Instant Tree Chop void instantchop(MenuEntry *entry) { static const Address instchop(0x59945C, 0x598974, 0x5984A4, 0x5984A4, 0x597D94, 0x597D94, 0x597A68, 0x597A68); if(entry->WasJustActivated()) Process::Patch(instchop.addr, 0xE1A00000); else if(!entry->IsActivated()) Process::Patch(instchop.addr, 0xCA000005); } }
38.929412
123
0.679964
RedShyGuy
0c91565e24b4bf402739894cb7c2f0682a52387f
724
hpp
C++
dynamic_programming/largest_rectangle.hpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
1
2021-12-26T14:17:29.000Z
2021-12-26T14:17:29.000Z
dynamic_programming/largest_rectangle.hpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
3
2020-07-13T06:23:02.000Z
2022-02-16T08:54:26.000Z
dynamic_programming/largest_rectangle.hpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
null
null
null
#pragma once #include <stack> #include <vector> template <typename T> long long largest_rectangle(const std::vector<T> &height) { int n = height.size(); std::vector<int> left(n); std::stack<T> st; long long res = 0; for (int i = 0; i < n; ++i) { while (!st.empty() && height[st.top()] >= height[i]) { long long tmp = static_cast<long long>(height[st.top()]) * (i - left[st.top()]); if (tmp > res) res = tmp; st.pop(); } left[i] = st.empty() ? 0 : st.top() + 1; st.emplace(i); } while (!st.empty()) { long long tmp = static_cast<long long>(height[st.top()]) * (n - left[st.top()]); if (tmp > res) res = tmp; st.pop(); } return res; }
26.814815
87
0.529006
emthrm
0c950ff67b60e6cbd1c2541211ac5c07ae637230
645
hpp
C++
Extensions/ZilchShaders/ForwardDeclarations.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
Extensions/ZilchShaders/ForwardDeclarations.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
Extensions/ZilchShaders/ForwardDeclarations.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2016, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zilch { class SyntaxTree; } namespace Zero { class ShaderCodeBuilder; class ShaderCompilationErrors; class ZilchShaderSettings; class TranslationErrorEvent; class ZilchShaderSpirVSettings; typedef Zilch::Ref<ZilchShaderSettings> ZilchShaderSettingsRef; typedef Zilch::Ref<ZilchShaderSpirVSettings> ZilchShaderSpirVSettingsRef; }//namespace Zero
23.888889
80
0.581395
jodavis42
0c99d184396399b1446daab70641961da13318eb
5,282
cpp
C++
BZ_Backend_Student/src/pass/loop_search.cpp
CSRic/SysYF-CodeGen-Opt
784c0b21dbcaae7d9f0b25765715e0837a50aa94
[ "Apache-2.0" ]
null
null
null
BZ_Backend_Student/src/pass/loop_search.cpp
CSRic/SysYF-CodeGen-Opt
784c0b21dbcaae7d9f0b25765715e0837a50aa94
[ "Apache-2.0" ]
null
null
null
BZ_Backend_Student/src/pass/loop_search.cpp
CSRic/SysYF-CodeGen-Opt
784c0b21dbcaae7d9f0b25765715e0837a50aa94
[ "Apache-2.0" ]
null
null
null
#include "pass/loop_search.h" bool add_new_loop = false; Loop *curloop = nullptr; void LoopSearch::run() { for(auto fun: m_->get_functions()){ if(fun->get_basic_blocks().size() == 0) continue; cur_fun = fun; index = 0; std::set<BasicBlock *> bb_set; for(auto bb: fun->get_basic_blocks()){ bb_set.insert(bb); } curloop = nullptr; Tarjan(fun->get_entry_block(), bb_set); add_new_loop = false; // find inner loop while(!work_list.empty()){ auto loop = work_list.back(); curloop = loop; work_list.pop_back(); if(loop->get_loop().size() == 1) continue; std::set<BasicBlock *> loop_bb; for(auto bb: loop->get_loop()){ loop_bb.insert(bb); } loop_bb.erase(loop->get_loop_entry()); index = 0; DFN.clear();Low.clear();in_stack.clear();visited.clear(); for(auto succ: loop->get_loop_entry()->get_succ_basic_blocks()){ if(loop_bb.find(succ) != loop_bb.end()){ Tarjan(succ, loop_bb); break; } } } for(auto loop: fun_loop[cur_fun]){ build_pre_succ_relation(loop); } } build_map(); } Loop *LoopSearch::get_inner_loop(const std::set<Loop *>& loops, BasicBlock *bb) { if (loops.empty()) return nullptr; for (auto loop: loops) { if (loop->contain_bb(bb)) { auto inner_loop = get_inner_loop(get_child_loop(loop), bb); if (inner_loop != nullptr) return inner_loop; else return loop; } } return nullptr; } void LoopSearch::build_map() { for (auto f: m_->get_functions()) { if (f->is_declaration()) continue; std::map<BasicBlock *, Loop *> _sub_map; for (auto bb: f->get_basic_blocks()) { _sub_map[bb] = get_inner_loop(get_loop(f), bb); } _nested_loop[f] = _sub_map; } } void LoopSearch::print_loop(){ auto white_space = " "; for(auto x: fun_loop){ int i = 0; std::cout<< "in function: " << x.first->get_name() << std::endl; for(auto loop: x.second){ std::cout << "Loop " << i << ":" << std::endl; std::cout << "entry block: " << loop->get_loop_entry()->get_name() << std::endl; for(auto bb: loop->get_loop()){ std::cout<< bb->get_name() << std::endl; std::cout<< "pre: " << std::endl; for(auto pre: loop->get_loop_bb_pre(bb)){ std::cout<< white_space << pre->get_name() << std::endl; } std::cout<< "succ: " << std::endl; for(auto succ: loop->get_loop_bb_succ(bb)){ std::cout<< white_space << succ->get_name() << std::endl; } } i++; } } } void LoopSearch::Tarjan(BasicBlock *bb, std::set<BasicBlock *> blocks) { // find loop in blocks DFN[bb] = index; Low[bb] = index; index ++; loop_stack.push(bb); in_stack.insert(bb); visited.insert(bb); for(auto succ_bb: bb->get_succ_basic_blocks()){ if(blocks.find(succ_bb) == blocks.end()) continue; if(visited.find(succ_bb) == visited.end()) { // not visited Tarjan(succ_bb, blocks); Low[bb] = std::min(Low[bb], Low[succ_bb]); } else if(in_stack.find(succ_bb) != in_stack.end()){ // still in stack Low[bb] = std::min(Low[bb], DFN[succ_bb]); } } if(DFN[bb] == Low[bb]){ BasicBlock* v = loop_stack.top(); loop_stack.pop(); in_stack.erase(v); Loop *new_loop = new Loop(); new_loop->add_loop_block(v); while(bb != v){ v = loop_stack.top(); loop_stack.pop(); in_stack.erase(v); new_loop->add_loop_block(v); } new_loop->set_entry_block(bb); if(new_loop->get_loop().size() > 1){ fun_loop[cur_fun].insert(new_loop); work_list.push_back(new_loop); if(curloop != nullptr){ child_loop[curloop].insert(new_loop); } } else if(new_loop->get_loop().size() == 1){ for(auto succ_bb: bb->get_succ_basic_blocks()){ if(succ_bb == bb){ fun_loop[cur_fun].insert(new_loop); work_list.push_back(new_loop); if(curloop != nullptr){ child_loop[curloop].insert(new_loop); } break; } } } } } void LoopSearch::build_pre_succ_relation(Loop *loop) { auto bb_set = loop->get_loop(); for(auto bb: bb_set){ for(auto succ_bb: bb->get_succ_basic_blocks()){ if(bb_set.find(succ_bb) != bb_set.end()){ loop->add_loop_bb_succ(bb, succ_bb); } } for(auto pre_bb: bb->get_pre_basic_blocks()){ if(bb_set.find(pre_bb) != bb_set.end()){ loop->add_loop_bb_pre(bb, pre_bb); } } } }
33.0125
92
0.500757
CSRic
0c9e27fba18690ae27d362b9ff80d6407e5be518
1,144
hpp
C++
src/tests/functional/plugin/shared/include/behavior/ov_infer_request/batched_tensors.hpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
null
null
null
src/tests/functional/plugin/shared/include/behavior/ov_infer_request/batched_tensors.hpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/tests/functional/plugin/shared/include/behavior/ov_infer_request/batched_tensors.hpp
ematroso/openvino
403339f8f470c90dee6f6d94ed58644b2787f66b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <gtest/gtest.h> #include <string> #include "functional_test_utils/ov_plugin_cache.hpp" #include <base/behavior_test_utils.hpp> namespace ov { namespace test { namespace behavior { class OVInferRequestBatchedTests : public testing::WithParamInterface<std::string>, public CommonTestUtils::TestsCommon { public: static std::string getTestCaseName(const testing::TestParamInfo<std::string>& device_name); protected: void SetUp() override; void TearDown() override; static std::string generateCacheDirName(const std::string& test_name); static std::shared_ptr<Model> create_n_inputs(size_t num, element::Type type, const PartialShape& shape, const ov::Layout& layout); std::shared_ptr<runtime::Core> ie = utils::PluginCache::get().core(); std::string targetDevice; std::string m_cache_dir; // internal member bool m_need_reset_core = false; }; } // namespace behavior } // namespace test } // namespace ov
29.333333
103
0.687937
ivkalgin
0ca7eaebddd3e24b7760ce46b67de6b49fbd7756
160
cpp
C++
GameEngine/CollisionCuboid.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/CollisionCuboid.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
GameEngine/CollisionCuboid.cpp
BenMarshall98/Game-Engine-Uni
cb2e0a75953db0960e3d58a054eb9a6e213ae12a
[ "MIT" ]
null
null
null
#include "CollisionCuboid.h" CollisionCuboid::~CollisionCuboid() { } //Gets the collision shape Shape CollisionCuboid::GetShape() { return Shape::CUBOID; }
12.307692
35
0.74375
BenMarshall98
0ca893c2dcd16135c774d17759802cdf89951db0
14,657
cc
C++
src/pmast/mapworld.cc
KonstantinRr/pmast
b26bf2cd63acd1fd8178d66fd35e8948db7b7651
[ "MIT" ]
null
null
null
src/pmast/mapworld.cc
KonstantinRr/pmast
b26bf2cd63acd1fd8178d66fd35e8948db7b7651
[ "MIT" ]
null
null
null
src/pmast/mapworld.cc
KonstantinRr/pmast
b26bf2cd63acd1fd8178d66fd35e8948db7b7651
[ "MIT" ]
null
null
null
/// MIT License /// /// Copyright (c) 2020 Konstantin Rolf /// /// 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. /// /// Written by Konstantin Rolf (konstantin.rolf@gmail.com) /// July 2020 #include <pmast/mapworld.hpp> #include <pmast/osm_mesh.hpp> #include <pmast/osm.hpp> #include <pmast/agent.hpp> #include <glm/gtx/quaternion.hpp> #include <iostream> using namespace traffic; MapWorld::MapWorld( const std::shared_ptr<nyrem::Engine> &engine, const std::shared_ptr<traffic::World> &world) { using namespace nyrem; try { m_engine = engine; m_world = world; glm::mat4x4 mat = glm::lookAt( glm::vec3{0.0f, 1.0f, 1.0f}, glm::vec3{0.0f, 1.0f, 0.0f}, glm::vec3{0.0f, 1.0f, 0.0f}); glm::quat q = toQuat(mat); m_camera = std::make_shared<Camera3D<>>( Projection3DSettings(0.1f, 500.0f, glm::radians(80.0f), 1.0f), Translation3DSettings(1.0f, 1.0f, 1.0f), RotationSettings3DQuat(q) ); m_shader = make_shader<PhongMemoryShader>(); m_shader_stage = std::make_shared<PhongListStage>(m_shader); m_entities = std::make_shared<RenderList<Entity>>(); m_shader_stage->stageBuffer().renderList = std::make_shared<RenderList<Entity>>(); m_shader_stage->stageBuffer().camera = m_camera; m_shader_stage->stageBuffer().lightPosition = {100.0f, 100.0f, 100.0f}; m_pipeline.addStage(m_shader_stage); loadWorld(m_world->getMap()); loadHighway(m_world->getHighwayMap()); MeshBuilder cube; cube.addCube({0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f}); auto expFile = cube.exporter().addVertex().addNormal().exportData(); m_cubeModel = std::make_shared<GLModel>(expFile); //m_shader_stage->stageBuffer().renderList->add(cubeEntity); } catch (const std::exception &excp) { m_shader = nullptr; m_shader_stage = nullptr; throw; } } void MapWorld::activate(nyrem::Navigator &nav) { using namespace nyrem; using namespace nyrem::keys; using namespace nyrem::mouse; InputHandler &m_input = m_engine->input(); m_keys[m_key_w] = m_input.loopKey(NYREM_KEY_W).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->moveForward(cameraSpeedForward); }); m_keys[m_key_s] = m_input.loopKey(NYREM_KEY_S).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->moveBackward(cameraSpeedForward); }); m_keys[m_key_a] = m_input.loopKey(NYREM_KEY_A).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->moveLeft(cameraSpeedLeft); }); m_keys[m_key_d] = m_input.loopKey(NYREM_KEY_D).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->moveRight(cameraSpeedLeft); }); m_keys[m_key_space] = m_input.loopKey(NYREM_KEY_SPACE).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->moveUp(cameraSpeedUp); }); m_keys[m_key_shift] = m_input.loopKey(NYREM_KEY_LEFT_SHIFT).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->moveDown(cameraSpeedUp); }); m_keys[m_key_g] = m_input.callbackKey(NYREM_KEY_G).listen(true, [this, &nav](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) nav.pushReplacementNamed("canvas"); }); m_keys[m_key_r] = m_input.callbackKey(NYREM_KEY_R).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) { m_start = m_camera->translation().translation(); m_hasStart = true; } }); m_keys[m_key_t] = m_input.callbackKey(NYREM_KEY_T).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) { m_end = m_camera->translation().translation(); m_hasEnd = true; } }); m_keys[m_key_enter] = m_input.callbackKey(NYREM_KEY_ENTER).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED && m_hasStart && m_hasEnd) { spdlog::info("Finding way from {},{} to {},{}", m_start.x, m_start.z, m_end.x, m_end.z); auto &traffic = m_world->getTrafficGraph(); TrafficGraphNodeIndex idStart = traffic->findClosestNodeIdxPlane({m_start.x, m_start.z}); TrafficGraphNodeIndex idStop = traffic->findClosestNodeIdxPlane({m_end.x, m_end.z}); spdlog::info("Found Nodes: {} to {}", idStart, idStop); IndexRoute route = traffic->findIndexRoute(idStart, idStop); // finds the positions of all routes on the way std::vector<vec2> positions(route.size()); for (size_t i = 0; i < route.size(); i++) { spdlog::info("Point {}", route[i]); positions[i] = traffic->findNodeByIndex(route[i]).plane(); } MeshBuilder builder; generateWayMesh(builder, positions, streetSelectedHeight, streetWidth); auto expFile = builder.exporter().addVertex().addNormal().exportData(); auto model = std::make_shared<GLModel>(expFile); auto routeEntity = std::make_shared<TransformableEntity>(); routeEntity->getColorStorage().addColor({0.0f, 1.0f, 0.0f}); routeEntity->setModel(model); m_entities->add(routeEntity); } }); // Arrow keybindings m_keys[m_key_up] = m_input.loopKey(NYREM_KEY_UP).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->rotateUp(cameraSpeedRotateUp); }); m_keys[m_key_down] = m_input.loopKey(NYREM_KEY_DOWN).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->rotateDown(cameraSpeedRotateUp); }); m_keys[m_key_left] = m_input.loopKey(NYREM_KEY_LEFT).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->rotateLeft(cameraSpeedRotateDown); }); m_keys[m_key_right] = m_input.loopKey(NYREM_KEY_RIGHT).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_camera->rotateRight(cameraSpeedRotateDown); }); m_keys[m_key_h] = m_input.callbackKey(NYREM_KEY_H).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED && m_hasStart && m_hasEnd) { const auto &traffic = m_world->getTrafficGraph(); TrafficGraphNodeIndex idStart = traffic->findClosestNodeIdxPlane({m_start.x, m_start.z}); TrafficGraphNodeIndex idStop = traffic->findClosestNodeIdxPlane({m_end.x, m_end.z}); m_world->createAgent(idStart, idStop); } }); m_keys[m_key_z] = m_input.callbackKey(NYREM_KEY_Z).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_run = true; }); m_keys[m_key_x] = m_input.callbackKey(NYREM_KEY_X).listen(true, [this](KeyEvent e) { if (e.action == KEYSTATUS_PRESSED) m_run = false; }); } void MapWorld::deactivate(nyrem::Navigator &nav) { for (size_t i = 0; i < m_key_last; i++) m_keys[i].remove(); } bool MapWorld::isRunning() const noexcept { return m_run; } void MapWorld::loadWorld(const std::shared_ptr<traffic::OSMSegment> &map) noexcept { using std::vector; using namespace nyrem; OSMViewTransformer &transformer = *m_world->transformer(); vector<vector<dvec2>> buildings = map->findBuildings(); // calculates some meta information and the geographical center size_t nodeCount = 0; for (const auto& building : buildings) nodeCount += building.size(); spdlog::info("Found {} Buildings with {} Nodes", buildings.size(), nodeCount); // converts the information to natural space vector<vector<vec2>> naturalSpace(buildings.size()); for (size_t i = 0; i < buildings.size(); i++) { // the used references for the buildings that are transformed const auto& building = buildings[i]; auto& naturalBuilding = naturalSpace[i]; naturalBuilding.resize(building.size()); for (size_t k = 0; k < buildings[i].size(); k++) naturalBuilding[k] = vec2(transformer.transform(building[k])); } // we don't need the original list of buildings anymore buildings.clear(); // creates a list of MeshBuilders from the natural space float height = 4.0f; vec3 heightVector = {0.0f, height, 0.0f}; vector<MeshBuilder> objectMeshes(naturalSpace.size()); for (size_t i = 0; i < naturalSpace.size(); i++) { auto &naturalBuilding = naturalSpace[i]; // creates the top polygon MeshBuilder2D top; top.addPolygon(naturalBuilding); top.invertWinding(false); // inverts the winding objectMeshes[i].add(top, 4.0f, false); // adds the walls for (size_t k = 0; k < naturalBuilding.size() - 1; k++) { vec2 x1 = naturalBuilding[k]; vec2 x2 = naturalBuilding[k + 1]; objectMeshes[i].addPlane( {x1.x, 0.0f, x1.y}, {x1.x, height, x1.y }, {x2.x, height, x2.y}, {x2.x, 0.0f, x2.y } ); } } MeshBuilder total; for (const auto& childMesh : objectMeshes) total.add(childMesh); ExportFile file = total.exporter() .addVertex().addNormal().exportData(); models.push_back(std::make_shared<GLModel>(file)); // creates the model entity m_world_entity = std::make_shared<TransformableEntity>(); m_world_entity->setModel(models.front()); std::cout << total.info() << std::endl; // ==== Generates the plane ==== // // finds the min and max coordinates vec2 mins = { 10000, 10000 }, maxs = { -10000, -10000}; const auto& verts = total.getVertices(); for (size_t i = 0; i < verts.size(); i++) { if (verts[i].x < mins.x) mins.x = verts[i].x; if (verts[i].z < mins.y) mins.y = verts[i].z; if (verts[i].x > maxs.x) maxs.x = verts[i].x; if (verts[i].z > maxs.y) maxs.y = verts[i].z; } float planeHeight = 0.0f; MeshBuilder plane; plane.addPlane( {mins.x, planeHeight, maxs.y}, {maxs.x, planeHeight, maxs.y}, {maxs.x, planeHeight, mins.y}, {mins.x, planeHeight, mins.y} ); ExportFile exportPlane = plane.exporter() .addVertex().addNormal().exportData(); auto planeModel = std::make_shared<GLModel>(exportPlane); m_plane_entity = std::make_shared<TransformableEntity>(); m_plane_entity->setModel(planeModel); m_plane_entity->setMaterial(std::make_shared<GLMaterial>(0.3, 0.7, 0.2, 2.0)); } void MapWorld::generateWayMesh( nyrem::MeshBuilder &mesh, const std::vector<nyrem::vec2> &points, float height, float width) { using namespace nyrem; vec2 last; for (size_t i = 0; i < points.size(); i++) { vec2 vec = points[i]; if (i != 0) { vec2 diff = glm::normalize(last - vec); vec2 cross = vec2(diff.y, -diff.x) * width; mesh.addPlane( {last.x - cross.x, height, last.y - cross.y}, {last.x + cross.x, height, last.y + cross.y}, {vec.x + cross.x, height, vec.y + cross.y}, {vec.x - cross.x, height, vec.y - cross.y} ); } last = vec; } } void MapWorld::loadHighway(const std::shared_ptr<traffic::OSMSegment> &highwayMap) noexcept { using std::vector; using namespace nyrem; OSMViewTransformer &trans = *m_world->transformer(); MeshBuilder highwayMesh; const auto &ways = *(highwayMap->getWays()); for (const auto &way : ways) { const auto& wayNodes = way.getNodes(); std::vector<vec2> positions(wayNodes.size()); for (size_t i = 0; i < wayNodes.size(); i++) positions[i] = vec2(trans.transform( highwayMap->getNode(wayNodes[i]).asVector())); generateWayMesh(highwayMesh, positions, streetHeight, streetWidth); } ExportFile exportHighway = highwayMesh.exporter() .addVertex().addNormal().exportData(); auto streetModel = std::make_shared<GLModel>(exportHighway); m_highway_entity = std::make_shared<TransformableEntity>(); m_highway_entity->setModel(streetModel); m_highway_entity->getColorStorage().addColor({1.0f, 0.0f, 0.0f}); m_highway_entity->setMaterial(std::make_shared<GLMaterial>(0.3, 0.7, 0.2, 2.0)); } void MapWorld::render(const nyrem::RenderContext &context) { using namespace nyrem; auto& renderList = m_shader_stage->stageBuffer().renderList; renderList->clear(); renderList->add(m_highway_entity); renderList->add(m_world_entity); renderList->add(m_plane_entity); for (const auto &fp : *m_entities) renderList->add(fp); static float t = 0.0f; t += 0.01f; const auto &agents = m_world->getAgents(); for (const Agent& agent : agents) { auto agentEntity = std::make_shared<TransformableEntity>(); vec2 physPosition = agent.physical().position(); //+ nyrem::vec2(4.0f, 4.0f) * cos(t); agentEntity->translation().set( {physPosition.x, agentHeight, physPosition.y}); agentEntity->setModel(m_cubeModel); agentEntity->getColorStorage().addColor({0.0f, 0.0f, 1.0f}); renderList->add(agentEntity); } m_camera->projection().setAspectRatio(context.aspectRatio()); m_pipeline.render(context); }
39.294906
97
0.630074
KonstantinRr
0caebd0243f9b0aedbc7c18b7b976bb5be4ddf77
4,471
cpp
C++
tools/ifaceed/ifaceed/history/animations/animationsremove.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
tools/ifaceed/ifaceed/history/animations/animationsremove.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
tools/ifaceed/ifaceed/history/animations/animationsremove.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include "animationsremove.h" #include "../../core/editor.h" #include "../../closuremethodcall.h" #include "../../gui/actions/actions.h" #include "../../gui/actions/animationactions.h" #include "../../gui/uiblocks/uiblocks.h" #include "../../gui/uiblocks/uianimationblock.h" #include "../../gui/uiblocks/uianimationinstanceblock.h" #include <QListWidgetItem> Q_DECLARE_METATYPE(sad::animations::Animation*) //-V566 history::animations::Remove::Remove(sad::animations::Animation* a) : m_animation(a), m_position_in_animation_list(-1), m_position_in_animation_instance_list(-1) { m_animation->addRef(); } history::animations::Remove::~Remove() { m_animation->delRef(); } void history::animations::Remove::set( int position_in_animation_list, int position_in_animation_instance_list, const sad::Vector< sad::Pair<sad::animations::Composite*, sad::Vector<int> > >& list ) { m_position_in_animation_list = position_in_animation_list; m_position_in_animation_instance_list = position_in_animation_instance_list; m_composites = list; } void history::animations::Remove::set( const sad::Vector< sad::animations::Instance* >& list ) { m_dependent_instances = list; } void history::animations::Remove::commit(core::Editor * ob) { m_animation->Active = false; for(size_t i = 0; i < m_composites.size(); i++) { const sad::Vector<int>& positions_vector = m_composites[i]._2(); for(int j = positions_vector.size() - 1; j > -1; j--) { m_composites[i]._1()->remove(positions_vector[j]); } } for(size_t i = 0; i < m_dependent_instances.size(); i++) { m_dependent_instances[i]->setAnimationMajorId(0); } if (ob) { ob->emitClosure( bind(ob->actions()->animationActions(), &gui::actions::AnimationActions::removeAnimationFromViewingLists, m_animation) ); ob->emitClosure( bind(ob->actions()->animationActions(), &gui::actions::AnimationActions::updateCompositeList)); for(size_t i = 0; i < m_dependent_instances.size(); i++) { if (m_dependent_instances[i] == ob->shared()->selectedInstance()) { ob->emitClosure( bind(ob->uiBlocks()->uiAnimationInstanceBlock()->cmbAnimationInstanceAnimationFromDatabase, &QComboBox::setCurrentIndex, 0)); } } } } void history::animations::Remove::rollback(core::Editor * ob) { m_animation->Active = true; for(size_t i = 0; i < m_composites.size(); i++) { const sad::Vector<int>& positions_vector = m_composites[i]._2(); for(size_t j = 0; j < positions_vector.size(); j++) { m_composites[i]._1()->insert(m_animation->MajorId, positions_vector[j]); } } for(size_t i = 0; i < m_dependent_instances.size(); i++) { m_dependent_instances[i]->setAnimationMajorId(m_animation->MajorId); } if (ob) { if (ob->panel()) { ob->emitClosure( bind(this, &history::animations::Remove::insertAnimationIntoUI, ob) ); ob->emitClosure( bind(ob->actions()->animationActions(), &gui::actions::AnimationActions::updateCompositeList)); for(size_t i = 0; i < m_dependent_instances.size(); i++) { if (m_dependent_instances[i] == ob->shared()->selectedInstance()) { ob->emitClosure( bind(ob->uiBlocks()->uiAnimationInstanceBlock()->cmbAnimationInstanceAnimationFromDatabase, &QComboBox::setCurrentIndex, m_position_in_animation_instance_list)); } } } } } void history::animations::Remove::insertAnimationIntoUI(core::Editor* editor) { QString name = editor->actions()->animationActions()->nameForAnimation(m_animation); QVariant v; v.setValue(m_animation); if (m_position_in_animation_list > -1) { QListWidgetItem* item = new QListWidgetItem(name); item->setData(Qt::UserRole, v); editor->uiBlocks()->uiAnimationBlock()->lstAnimations->insertItem(m_position_in_animation_list, item); } if (m_position_in_animation_instance_list > -1) { editor->uiBlocks()->uiAnimationInstanceBlock()->cmbAnimationInstanceAnimationFromDatabase->insertItem(m_position_in_animation_instance_list, name, v); } }
35.204724
199
0.632297
mamontov-cpp
0cb1d7c3db6800b91d9e1fe0adc579e49bec0fa6
6,610
cpp
C++
B.cpp
turing228/Generating-Functions
97536c14953ed3051d194310e8b4245f1618aa95
[ "MIT" ]
null
null
null
B.cpp
turing228/Generating-Functions
97536c14953ed3051d194310e8b4245f1618aa95
[ "MIT" ]
null
null
null
B.cpp
turing228/Generating-Functions
97536c14953ed3051d194310e8b4245f1618aa95
[ "MIT" ]
null
null
null
// Copyright (c) Nikita Lisovetin. All rights reserved. // Licensed under the MIT License. // Nikita Lisovetin, github.com/turing228 // Please let me know if you have any questions. It's easy to find me in google/yandex /******************************************************************************************************************************** * Лабораторная работа по производящим функциям. Дискретная математика, университет ИТМО, кафедра КТ * * Задача B. Операции с многочленами - 2 * * Условие и решения других задач из лабораторной можно найти здесь: github.com/turing228 * * * * Тесты в конце файла * * * * Аккуратная реализация функций. * * Как брать корень из формального степенного ряда: * * https://www.coursera.org/lecture/modern-combinatorics/7-10-izvliechieniie-kornia-iz-formal-nogho-stiepiennogho-riada-Yjp4D * * GNU C++ 14 * ********************************************************************************************************************************/ #include <iostream> #include <vector> using namespace std; const int64_t MOD = 998244353; // модуль, по которому производим все вычисления int point; // количество первых членов производящих функций во время вычислений int64_t get_number(vector<int64_t> const &v, size_t i) { return i >= v.size() ? 0 : v[i]; } vector<int64_t> sum(vector<int64_t> const &p, vector<int64_t> const &q) { vector<int64_t> res; int64_t temp; for (size_t i = 0; i < max(p.size(), q.size()); ++i) { temp = get_number(p, i) + get_number(q, i); temp %= MOD; if (temp < 0) { temp += MOD; } res.push_back(temp); } return res; } vector<int64_t> product(vector<int64_t> const &p, vector<int64_t> const &q) { vector<int64_t> res; int64_t temp; for (int i = 0; i <= min(point, static_cast<const int &>(p.size() + q.size() - 2)); ++i) { temp = 0; for (int j = max(0, i - int(q.size())); j <= i, j < p.size(); ++j) { temp = (temp + get_number(p, j) * get_number(q, i - j)) % MOD; if (temp < 0) { temp += MOD; } } res.push_back(temp); } return res; } int64_t divDmod(int64_t x, int64_t D) { if (x < 0) { x = x % MOD + MOD; } while (x % D != 0) { x += MOD; } return x / D; } vector<int64_t> squart(vector<int64_t> const &p) { vector<int64_t> res; res.push_back(1); vector<int64_t> powered_p; powered_p.push_back(1); for (size_t i = 1; i < point; ++i) { powered_p = product(vector<int64_t>(1, divDmod(3 - 2 * i, 2 * i)), powered_p); powered_p = product(powered_p, p); res = sum(res, powered_p); } return res; } vector<int64_t> exp(vector<int64_t> const &p) { vector<int64_t> res; res.push_back(1); vector<int64_t> powered_p; powered_p.push_back(1); for (size_t i = 1; i < point; ++i) { powered_p = product(vector<int64_t>(1, divDmod(1, i)), powered_p); powered_p = product(powered_p, p); res = sum(res, powered_p); } return res; } vector<int64_t> ln(vector<int64_t> const &p) { vector<int64_t> res; res.push_back(0); vector<int64_t> powered_p; powered_p.push_back(1); for (size_t i = 1; i < point; ++i) { powered_p = product(powered_p, p); res = sum(res, product(vector<int64_t>(1, divDmod(i % 2 == 1 ? 1 : -1, i)), powered_p)); } return res; } void out_vector(vector<int64_t> const &v) { for (size_t i = 0; i < point; ++i) { cout << v[i] << ' '; } cout << std::endl; } int main() { ios::sync_with_stdio(false); size_t n; int m; cin >> n >> m; point = m; vector<int64_t> p(n + 1); for (size_t i = 0; i < n + 1; ++i) { cin >> p[i]; } out_vector(squart(p)); out_vector(exp(p)); out_vector(ln(p)); return 0; } /* Tests: input: 1 4 0 1 output: 1 499122177 124780544 935854081 1 1 499122177 166374059 0 1 499122176 332748118 input: 1 10 0 1 output: 1 499122177 124780544 935854081 38993920 970948609 20471808 982159361 13069056 987353473 1 1 499122177 166374059 291154603 856826403 641926577 376916469 421456191 712324701 0 1 499122176 332748118 249561088 598946612 831870294 855638017 124780544 443664157 input: 1 10 0 -1 output: 1 499122176 124780544 62390272 38993920 27295744 20471808 16084992 13069056 10890880 1 998244352 499122177 831870294 291154603 141417950 641926577 621327884 421456191 285919652 0 998244352 499122176 665496235 249561088 399297741 831870294 142606336 124780544 554580196 input: 1 10 0 2 output: 1 1 499122176 499122177 623902720 124780545 311951359 935854083 350945277 413335558 1 2 2 332748119 665496236 465847365 155282455 329579088 82394772 351058067 0 2 998244351 665496238 998244349 199648877 332748107 713031699 998244321 554580253 input: 2 10 0 1 1 output: 1 499122177 623902721 187170816 974848001 939753473 55566336 988008449 971832065 28834176 1 1 499122178 166374060 291154604 524078286 849894151 984181784 585057349 172797396 0 1 499122177 332748117 748683265 598946612 665496235 855638017 873463809 110916039 input: 10 10 0 1 -1 2 -2 3 -3 4 -4 5 -5 output: 1 499122177 623902720 686292994 850067455 752582660 141352955 968511498 701799153 245737885 1 1 499122176 166374060 291154603 191330168 267584946 684708477 931669974 223105741 0 1 499122175 332748121 748683259 598946623 998244332 855638058 873463728 443664319 input: 10 10 0 -1 1 -2 2 -3 3 -4 4 -5 5 output: 1 499122176 623902721 811073536 475725825 931954688 492298241 969486336 570194689 20883071 1 998244352 499122178 831870291 291154608 474166059 184397929 596371753 219034454 32397223 0 998244352 499122177 665496234 748683265 399297740 665496235 142606335 873463808 221832077 */
31.932367
130
0.562632
turing228
0cb52de4ae924a76468d1b162ef4ca2fdfd082cd
179
cc
C++
SHM_version_for_beginers/sources/Island.cc
majkel84/kurs_cpp_podstawowy
eddaffb310c6132304aa26dc87ec04ddfc09c541
[ "MIT" ]
8
2020-05-17T18:04:40.000Z
2021-04-15T07:52:33.000Z
SHM_version_for_beginers/sources/Island.cc
majkel84/kurs_cpp_podstawowy
eddaffb310c6132304aa26dc87ec04ddfc09c541
[ "MIT" ]
292
2020-03-10T18:03:14.000Z
2022-03-26T17:00:51.000Z
SHM_version_for_beginers/sources/Island.cc
majkel84/kurs_cpp_podstawowy
eddaffb310c6132304aa26dc87ec04ddfc09c541
[ "MIT" ]
126
2020-05-11T16:25:40.000Z
2022-02-21T00:41:03.000Z
#include "Island.h" #include "GTime.h" Island::Island(size_t pos_x, size_t pos_y, Time* time): position_(Coordinates(pos_x, pos_y)), store_(std::make_unique<Store>(time)) { }
22.375
56
0.715084
majkel84
0cb7959d0045eb02d9a1538e96a1bb081ba57fef
21,518
cpp
C++
src/njli/graphics/opengl_es_3.0/ShaderProgram.cpp
njligames/Engine
899c7b79cea33a72fc34f159134f721b56715d3d
[ "MIT" ]
1
2019-02-13T05:41:54.000Z
2019-02-13T05:41:54.000Z
src/njli/graphics/opengl_es_3.0/ShaderProgram.cpp
njligames/Engine
899c7b79cea33a72fc34f159134f721b56715d3d
[ "MIT" ]
null
null
null
src/njli/graphics/opengl_es_3.0/ShaderProgram.cpp
njligames/Engine
899c7b79cea33a72fc34f159134f721b56715d3d
[ "MIT" ]
null
null
null
// // ShaderProgram.cpp // JLIGameEngineTest // // Created by James Folk on 1/8/15. // Copyright (c) 2015 James Folk. All rights reserved. // #include "ShaderProgram.h" #include "JLIFactoryTypes.h" #include "World.h" #include "ShaderProgramBuilder.h" #include "GLPlatform.h" #include "Camera.h" #include "Log.h" #define TAG "ShaderProgram.cpp" #define FORMATSTRING "{\"njli::ShaderProgram\":[]}" #include "btPrint.h" enum njliGLSLVarType { JLI_GL_FLOAT = GL_FLOAT, JLI_GL_FLOAT_VEC2 = GL_FLOAT_VEC2, JLI_GL_FLOAT_VEC3 = GL_FLOAT_VEC3, JLI_GL_FLOAT_VEC4 = GL_FLOAT_VEC4, JLI_GL_INT = GL_INT, JLI_GL_INT_VEC2 = GL_INT_VEC2, JLI_GL_INT_VEC3 = GL_INT_VEC3, JLI_GL_INT_VEC4 = GL_INT_VEC4, JLI_GL_BOOL = GL_BOOL, JLI_GL_BOOL_VEC2 = GL_BOOL_VEC2, JLI_GL_BOOL_VEC3 = GL_BOOL_VEC3, JLI_GL_BOOL_VEC4 = GL_BOOL_VEC4, JLI_GL_FLOAT_MAT2 = GL_FLOAT_MAT2, JLI_GL_FLOAT_MAT3 = GL_FLOAT_MAT3, JLI_GL_FLOAT_MAT4 = GL_FLOAT_MAT4, JLI_GL_SAMPLER_2D = GL_SAMPLER_2D, JLI_GL_SAMPLER_CUBE = GL_SAMPLER_CUBE }; static const char *getGLSLVarTypeName(njliGLSLVarType var) { switch (var) { case JLI_GL_FLOAT: return "GL_FLOAT"; case JLI_GL_FLOAT_VEC2: return "GL_FLOAT_VEC2"; case JLI_GL_FLOAT_VEC3: return "GL_FLOAT_VEC3"; case JLI_GL_FLOAT_VEC4: return "GL_FLOAT_VEC4"; case JLI_GL_INT: return "GL_INT"; case JLI_GL_INT_VEC2: return "GL_INT_VEC2"; case JLI_GL_INT_VEC3: return "GL_INT_VEC3"; case JLI_GL_INT_VEC4: return "GL_INT_VEC4"; case JLI_GL_BOOL: return "GL_BOOL"; case JLI_GL_BOOL_VEC2: return "GL_BOOL_VEC2"; case JLI_GL_BOOL_VEC3: return "GL_BOOL_VEC3"; case JLI_GL_BOOL_VEC4: return "GL_BOOL_VEC4"; case JLI_GL_FLOAT_MAT2: return "GL_FLOAT_MAT2"; case JLI_GL_FLOAT_MAT3: return "GL_FLOAT_MAT3"; case JLI_GL_FLOAT_MAT4: return "GL_FLOAT_MAT4"; case JLI_GL_SAMPLER_2D: return "GL_SAMPLER_2D"; case JLI_GL_SAMPLER_CUBE: return "GL_SAMPLER_CUBE"; default: return "UNKNOW UNIFORM VARIABLE"; } } static void log_v_fixed_length(const GLchar* source, const GLint length) { if (LOGGING_ON) { char log_buffer[length + 1]; memcpy(log_buffer, source, length); log_buffer[length] = '\0'; // DEBUG_LOG_V(TAG, "<glGetShaderSource>\n%s\n</glGetShaderSource>", log_buffer); } } static void log_shader_info_log(GLuint shader_object_id) { if (LOGGING_ON) { DEBUG_ASSERT_PRINT(glIsShader(shader_object_id), "%s:%d", "Not a shader", shader_object_id); GLint log_length = 0; glGetShaderiv(shader_object_id, GL_INFO_LOG_LENGTH, &log_length);DEBUG_GL_ERROR_WRITE("glGetShaderiv"); if(log_length > 0) { GLchar log_buffer[log_length]; glGetShaderInfoLog(shader_object_id, log_length, NULL, log_buffer);DEBUG_GL_ERROR_WRITE("glGetShaderInfoLog"); DEBUG_LOG_PRINT_E(TAG, "The glGetShaderiv log = `%s`", log_buffer); } } } static void log_program_info_log(GLuint program_object_id) { if (LOGGING_ON) { DEBUG_ASSERT_PRINT(glIsProgram(program_object_id), "%s:%d", "Not a shader", program_object_id); GLint log_length; glGetProgramiv(program_object_id, GL_INFO_LOG_LENGTH, &log_length);DEBUG_GL_ERROR_WRITE("glGetProgramiv"); if(log_length > 1) { GLchar log_buffer[log_length]; glGetProgramInfoLog(program_object_id, log_length, NULL, log_buffer);DEBUG_GL_ERROR_WRITE("glGetProgramInfoLog"); DEBUG_LOG_PRINT_E(TAG, "The glGetProgramiv log(%d) = `%s`", log_length, log_buffer); } } } static GLuint compile_shader(const GLenum type, const GLchar* source, const GLint length) { DEBUG_ASSERT(source != NULL); DEBUG_ASSERT(type == GL_VERTEX_SHADER || type == GL_FRAGMENT_SHADER); GLuint shader_object_id = glCreateShader(type);DEBUG_GL_ERROR_WRITE("glCreateShader"); // log_shader_info_log(shader_object_id); GLint compile_status; DEBUG_ASSERT(shader_object_id != 0); // DEBUG_LOG_V("compile_shader", "id=%d", shader_object_id); GLchar**str = new GLchar*[1]; str[0] = new GLchar[length]; strcpy(str[0], source); DEBUG_LOG_V(TAG, "source : %s", source); glShaderSource(shader_object_id, 1, (const GLchar**)&(str[0]), NULL);DEBUG_GL_ERROR_PRINT("glShaderSource", "id:%d,source:%s",shader_object_id,str[0]); log_shader_info_log(shader_object_id); glCompileShader(shader_object_id);DEBUG_GL_ERROR_WRITE("glCompileShader"); log_shader_info_log(shader_object_id); glGetShaderiv(shader_object_id, GL_COMPILE_STATUS, &compile_status);DEBUG_GL_ERROR_WRITE("glGetShaderiv"); log_shader_info_log(shader_object_id); delete [] str[0];str[0]=NULL; delete [] str;str=NULL; if (false && LOGGING_ON) { DEBUG_LOG_D(TAG, "Results of compiling shader source = %s", (compile_status==GL_TRUE)?"true":"false"); GLsizei bufSize = 0; GLsizei _length = 0; glGetShaderiv(shader_object_id, GL_SHADER_SOURCE_LENGTH, &bufSize);DEBUG_GL_ERROR_WRITE("glGetShaderiv"); log_shader_info_log(shader_object_id); DEBUG_ASSERT(bufSize>0); GLchar *the_source = new GLchar[bufSize]; glGetShaderSource(shader_object_id, bufSize, &_length, the_source);DEBUG_GL_ERROR_WRITE("glGetShaderSource"); // log_shader_info_log(shader_object_id); log_v_fixed_length(the_source, _length); delete [] the_source;the_source=NULL; } DEBUG_ASSERT(compile_status != 0); return shader_object_id; } static GLuint link_program(const GLuint vertex_shader, const GLuint fragment_shader) { GLuint program_object_id = glCreateProgram();DEBUG_GL_ERROR_WRITE("glCreateProgram"); // log_program_info_log(program_object_id); GLint link_status; DEBUG_ASSERT(program_object_id != 0); // DEBUG_LOG_V("link_program", "id=%d", program_object_id); glAttachShader(program_object_id, vertex_shader);DEBUG_GL_ERROR_WRITE("glAttachShader"); // log_shader_info_log(vertex_shader); // log_program_info_log(program_object_id); glAttachShader(program_object_id, fragment_shader);DEBUG_GL_ERROR_WRITE("glAttachShader"); // log_shader_info_log(fragment_shader); // log_program_info_log(program_object_id); glLinkProgram(program_object_id);DEBUG_GL_ERROR_WRITE("glLinkProgram"); // log_program_info_log(program_object_id); glGetProgramiv(program_object_id, GL_LINK_STATUS, &link_status);DEBUG_GL_ERROR_WRITE("glGetProgramiv"); // log_program_info_log(program_object_id); if (LOGGING_ON) { DEBUG_LOG_D(TAG, "Results of linking program = %s\n", (link_status==GL_TRUE)?"true":"false"); log_program_info_log(program_object_id); } DEBUG_ASSERT(link_status != 0); return program_object_id; } static GLint validate_program(const GLuint program) { if (LOGGING_ON) { int validate_status; glValidateProgram(program);DEBUG_GL_ERROR_WRITE("glValidateProgram"); // log_program_info_log(program); glGetProgramiv(program, GL_VALIDATE_STATUS, &validate_status);DEBUG_GL_ERROR_WRITE("glGetProgramiv"); DEBUG_LOG_D(TAG, "Results of validating program = %s\n", (validate_status==GL_TRUE)?"true":"false"); // log_program_info_log(program); return validate_status; } return GL_TRUE; } namespace njli { ShaderProgram::ShaderProgram(): AbstractFactoryObject(this), program(-1),//glCreateProgram()), vertShader(-1), fragShader(-1) { enableRenderObject(); } ShaderProgram::ShaderProgram(const AbstractBuilder &builder): AbstractFactoryObject(this), program(-1),//glCreateProgram()), vertShader(-1), fragShader(-1) { enableRenderObject(); } ShaderProgram::ShaderProgram(const ShaderProgram &copy): AbstractFactoryObject(this), program(-1),//glCreateProgram()), vertShader(-1), fragShader(-1) { enableRenderObject(); } ShaderProgram::~ShaderProgram() { unLoadGPU(); } ShaderProgram &ShaderProgram::operator=(const ShaderProgram &rhs) { if(this != &rhs) { } return *this; } s32 ShaderProgram::calculateSerializeBufferSize() const { //TODO: calculateSerializeBufferSize return 0; } void ShaderProgram::serialize(void* dataBuffer, btSerializer* serializer) const { //TODO: serialize } const char *ShaderProgram::getClassName()const { return "ShaderProgram"; } s32 ShaderProgram::getType()const { return ShaderProgram::type(); } ShaderProgram::operator std::string() const { return njli::JsonJLI::parse(string_format("%s", FORMATSTRING).c_str()); } ShaderProgram **ShaderProgram::createArray(const u32 size) { return (ShaderProgram**)World::getInstance()->getWorldFactory()->createArray(ShaderProgram::type(), size); } void ShaderProgram::destroyArray(ShaderProgram **array, const u32 size) { World::getInstance()->getWorldFactory()->destroyArray((AbstractFactoryObject**)array, size); } ShaderProgram *ShaderProgram::create() { return dynamic_cast<ShaderProgram*>(World::getInstance()->getWorldFactory()->create(ShaderProgram::type())); } ShaderProgram *ShaderProgram::create(const ShaderProgramBuilder &builder) { AbstractBuilder *b = (AbstractBuilder *)&builder; return dynamic_cast<ShaderProgram*>(World::getInstance()->getWorldFactory()->create(*b)); } ShaderProgram *ShaderProgram::clone(const ShaderProgram &object) { return dynamic_cast<ShaderProgram*>(World::getInstance()->getWorldFactory()->clone(object, false)); } ShaderProgram *ShaderProgram::copy(const ShaderProgram &object) { return dynamic_cast<ShaderProgram*>(World::getInstance()->getWorldFactory()->clone(object, true)); } void ShaderProgram::destroy(ShaderProgram *object) { if(object) { World::getInstance()->getWorldFactory()->destroy(object); } } void ShaderProgram::load(ShaderProgram &object, lua_State *L, int index) { // Push another reference to the table on top of the stack (so we know // where it is, and this function can work for negative, positive and // pseudo indices lua_pushvalue(L, index); // stack now contains: -1 => table lua_pushnil(L); // stack now contains: -1 => nil; -2 => table while (lua_next(L, -2)) { // stack now contains: -1 => value; -2 => key; -3 => table // copy the key so that lua_tostring does not modify the original lua_pushvalue(L, -2); // stack now contains: -1 => key; -2 => value; -3 => key; -4 => table const char *key = lua_tostring(L, -1); const char *value = lua_tostring(L, -2); if(lua_istable(L, -2)) { ShaderProgram::load(object, L, -2); } else { if(lua_isnumber(L, index)) { double number = lua_tonumber(L, index); printf("%s => %f\n", key, number); } else if(lua_isstring(L, index)) { const char *v = lua_tostring(L, index); printf("%s => %s\n", key, v); } else if(lua_isboolean(L, index)) { bool v = lua_toboolean(L, index); printf("%s => %d\n", key, v); } else if(lua_isuserdata(L, index)) { // swig_lua_userdata *usr; // swig_type_info *type; // DEBUG_ASSERT(lua_isuserdata(L,index)); // usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */ // type = usr->type; // njli::AbstractFactoryObject *object = static_cast<njli::AbstractFactoryObject*>(usr->ptr); // printf("%s => %d:%s\n", key, object->getType(), object->getClassName()); } } // pop value + copy of key, leaving original key lua_pop(L, 2); // stack now contains: -1 => key; -2 => table } // stack now contains: -1 => table (when lua_next returns 0 it pops the key // but does not push anything.) // Pop table lua_pop(L, 1); // Stack is now the same as it was on entry to this function } u32 ShaderProgram::type() { return JLI_OBJECT_TYPE_ShaderProgram; } bool ShaderProgram::compile(const char *source, njliShaderType type) { bool ret = false; switch (type) { case JLI_SHADER_TYPE_FRAGMENT: { if (-1 != fragShader) { glDeleteShader(fragShader);DEBUG_GL_ERROR_WRITE("glDeleteShader"); } compileShader(&fragShader, GL_FRAGMENT_SHADER, source); ret = true; // ret = compileShader(&fragShader, GL_FRAGMENT_SHADER, source); // if(ret) // { // glAttachShader(program, fragShader); // } } break; case JLI_SHADER_TYPE_VERTEX: { if (-1 != vertShader) { glDeleteShader(vertShader);DEBUG_GL_ERROR_WRITE("glDeleteShader"); } compileShader(&vertShader, GL_VERTEX_SHADER, source); ret = true; // ret = compileShader(&vertShader, GL_VERTEX_SHADER, source); // if(ret) // { // glAttachShader(program, vertShader); // } } break; default: break; } return ret; } void ShaderProgram::bindAttribute(const char *attributeName) { s32 index = getAttributeIndex(attributeName); glBindAttribLocation(program, index, attributeName);DEBUG_GL_ERROR_WRITE("glBindAttribLocation"); // log_program_info_log(program); } u32 ShaderProgram::getAttributeIndex(const char *attributeName)const { s32 _id = glGetAttribLocation(program, attributeName);DEBUG_GL_ERROR_WRITE("glGetAttribLocation\n"); // log_program_info_log(program); DEBUG_ASSERT_PRINT(-1 != _id, "The named attribute variable (%s) is not an active attribute in the specified program object or if name starts with the reserved prefix \"gl_\"", attributeName); return _id; } u32 ShaderProgram::getUniformIndex(const char *uniformName)const { s32 _id = glGetUniformLocation(program, uniformName);DEBUG_GL_ERROR_PRINT("glGetUniformLocation\n", "%d,%s",program,uniformName); DEBUG_ASSERT_PRINT(-1 != _id, "The named uniform variable (%s) is not an active uniform in the specified program object or if name starts with the reserved prefix \"gl_\"", uniformName); return _id; } bool ShaderProgram::link() { DEBUG_ASSERT(!isLinked()); if(!compile(m_VertexShaderSource.c_str(), JLI_SHADER_TYPE_VERTEX)) { DEBUG_LOG_PRINT_E(TAG, "Vertex log: `%s`\n", vertexShaderLog()); return false; } if(!compile(m_FragmentShaderSource.c_str(), JLI_SHADER_TYPE_FRAGMENT)) { DEBUG_LOG_PRINT_E(TAG, "Vertex log: `%s`\n", fragmentShaderLog()); return false; } program = link_program(vertShader, fragShader); GLint status = validate_program(program); if( LOGGING_ON && GL_TRUE == status) { GLint active = 0; GLsizei length = 0; GLsizei size = 0; GLenum type = 0; GLint nameMaxLength = 0; GLchar *variableName = NULL; glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &active);DEBUG_GL_ERROR_WRITE("glGetProgramiv\n"); glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &nameMaxLength);DEBUG_GL_ERROR_WRITE("glGetProgramiv\n"); variableName = new GLchar[nameMaxLength]; for(GLuint index = 0; index < active; ++index) { glGetActiveUniform(program, index, nameMaxLength, &length, &size, &type, variableName);DEBUG_GL_ERROR_WRITE("glGetActiveUniform\n"); // DEBUG_LOG_V(TAG, "Uniform Variable Loaded: %s %s (size=%d)", getGLSLVarTypeName((njliGLSLVarType)type), variableName, size); } delete [] variableName;variableName=NULL; glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES, &active);DEBUG_GL_ERROR_WRITE("glGetProgramiv\n"); glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &nameMaxLength);DEBUG_GL_ERROR_WRITE("glGetProgramiv\n"); variableName = new GLchar[nameMaxLength]; for(GLuint index = 0; index < active; ++index) { glGetActiveAttrib(program, index, nameMaxLength, &length, &size, &type, variableName);DEBUG_GL_ERROR_WRITE("glGetActiveAttrib\n"); // DEBUG_LOG_V(TAG, "Attribute Loaded: %s %s (size=%d)", getGLSLVarTypeName((njliGLSLVarType)type), variableName, size); } delete [] variableName;variableName=NULL; } // // glLinkProgram(program); // glGetProgramiv(program, GL_LINK_STATUS, &status); //#if defined(DEBUG) || defined (_DEBUG) // if (status == GL_FALSE) // { // GLint logLength = 4098; // GLchar *log = new GLchar[logLength]; // glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); // glGetShaderInfoLog(program, 4098, &logLength, (GLchar*)log); // DEBUG_LOG_V(TAG, "%s", log); // // glValidateProgram(program); // glGetShaderInfoLog(program, 4098, &logLength, (GLchar*)log); // DEBUG_LOG_V(TAG, "%s", log); // // delete [] log; // } //#endif if (status == GL_FALSE) return false; return true; } void ShaderProgram::saveSource(const std::string &vertexShaderSource, const std::string &fragmentShaderSource) { m_VertexShaderSource = vertexShaderSource; m_FragmentShaderSource = fragmentShaderSource; } bool ShaderProgram::isLinked()const { return (program != -1); } void ShaderProgram::use() { // DEBUG_LOG_D("SHADER", "BEFORE USE %d", program); glUseProgram(program);//DEBUG_GL_ERROR_PRINT("glUseProgram", "%d", program); // DEBUG_LOG_D("SHADER", "AFTER USE %d", program); } // void ShaderProgram::unUse() // { //// glUseProgram(0);DEBUG_GL_ERROR_WRITE("glUseProgram"); // } const char *ShaderProgram::vertexShaderLog()const { return logForOpenGLObject(vertShader, (GLInfoFunction)&glGetProgramiv, (GLLogFunction)&glGetProgramInfoLog); } const char *ShaderProgram::fragmentShaderLog()const { return logForOpenGLObject(fragShader, (GLInfoFunction)&glGetProgramiv, (GLLogFunction)&glGetProgramInfoLog); } const char *ShaderProgram::programLog()const { return logForOpenGLObject(program, (GLInfoFunction)&glGetProgramiv, (GLLogFunction)&glGetProgramInfoLog); } void ShaderProgram::unLoadGPU() { if(-1 != vertShader) glDeleteShader(vertShader);DEBUG_GL_ERROR_WRITE("glDeleteProgram\n"); vertShader = -1; if(-1 != fragShader) glDeleteShader(fragShader);DEBUG_GL_ERROR_WRITE("glDeleteProgram\n"); fragShader = -1; if(-1 != program) glDeleteProgram(program);DEBUG_GL_ERROR_WRITE("glDeleteProgram\n"); program = -1; } bool ShaderProgram::compileShader(s32 *shader, const GLenum type, const char *source) { *shader = compile_shader(type, source, (int)strlen(source) + 1); return GL_TRUE; } const char *ShaderProgram::logForOpenGLObject(u32 object, GLInfoFunction infoFunc, GLLogFunction logFunc)const { GLint logLength = 0, charsWritten = 0; infoFunc(object, GL_INFO_LOG_LENGTH, &logLength);DEBUG_GL_ERROR_WRITE("GLInfoFunction\n"); if (logLength < 1) return NULL; char *logBytes = new char[logLength]; logFunc(object, logLength, &charsWritten, logBytes);DEBUG_GL_ERROR_WRITE("GLLogFunction\n"); std::string s(logBytes); delete [] logBytes;logBytes=NULL; return s.c_str(); } }
35.625828
200
0.61265
njligames
0cbe41bbd320e482875de0a03fbb6ce20b451071
608
cpp
C++
C++/0039.cpp
AndroAvi/DSA
5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582
[ "MIT" ]
4
2021-08-28T19:16:50.000Z
2022-03-04T19:46:31.000Z
C++/0039.cpp
AndroAvi/DSA
5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582
[ "MIT" ]
8
2021-10-29T19:10:51.000Z
2021-11-03T12:38:00.000Z
C++/0039.cpp
AndroAvi/DSA
5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582
[ "MIT" ]
4
2021-09-06T05:53:07.000Z
2021-12-24T10:31:40.000Z
class Solution { public: void backtrack(vector<int> &arr, int target, vector<vector<int>> &ans, vector<int> &curr, int start = 0) { if (target < 0) return; if (target == 0) ans.push_back(curr); else { for (int i{start}; i < int(arr.size()); i++) { curr.push_back(arr[i]); backtrack(arr, target - arr[i], ans, curr, i); curr.pop_back(); } } } vector<vector<int>> combinationSum(vector<int> &arr, int target) { vector<vector<int>> ans; vector<int> curr; backtrack(arr, target, ans, curr); return ans; } };
26.434783
72
0.550987
AndroAvi
0cc5acc0487516b25aac4ef3714f2c5987902527
89
cpp
C++
src/examples/007Chapter/7-6-static-member/main.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
src/examples/007Chapter/7-6-static-member/main.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
src/examples/007Chapter/7-6-static-member/main.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
#include "screen.h" int main() { Screen screen; screen.clear(); return 0; }
9.888889
19
0.573034
artgonzalez
0cc6fe2b4775b9e44b2e607c19ef04ffa62d4783
2,352
cpp
C++
Libraries/AP_Motors/AP_Motors.cpp
SuWeipeng/car_407ve_rtt
c04745c4801998e6d82db516138d6adf846e64f8
[ "Apache-2.0" ]
8
2020-01-19T00:04:35.000Z
2022-01-05T19:08:05.000Z
Libraries/AP_Motors/AP_Motors.cpp
SuWeipeng/car_407ve_rtt
c04745c4801998e6d82db516138d6adf846e64f8
[ "Apache-2.0" ]
null
null
null
Libraries/AP_Motors/AP_Motors.cpp
SuWeipeng/car_407ve_rtt
c04745c4801998e6d82db516138d6adf846e64f8
[ "Apache-2.0" ]
3
2020-02-26T01:26:22.000Z
2021-01-26T06:02:56.000Z
#include "AP_Motors.h" #include "AP_Motors_L298N_3Wire_ABEncoder.h" AP_Motors *AP_Motors::_instance; AP_Motors::AP_Motors() : _backend(nullptr) , _pid(nullptr) { _instance = this; } void AP_Motors::init(TIM_HandleTypeDef* enc_tim, // encoder timer int8_t enc_dir, // encoder direction GPIO_TypeDef* dir_port, // L298N GPIO port uint16_t pin_1, // L298N in1 uint16_t pin_2, // L298N in2 TIM_HandleTypeDef* pwm_tim, // pwm timer uint8_t channel, // pwm channel uint16_t pwm_max, AC_PID* pid) { _backend = new AP_Motors_L298N_3Wire_ABEncoder(*this, enc_tim, enc_dir, dir_port, pin_1, pin_2, pwm_tim, channel, pwm_max, pid); } void AP_Motors::set_rpm(float rpm) { if(_backend != nullptr){ _backend->set_rpm(rpm); } } int32_t AP_Motors::get_delta_tick() { if(_backend != nullptr){ return _backend->get_delta_tick(); } return 0; } int32_t AP_Motors::get_tick() { if(_backend != nullptr){ return _backend->get_tick(); } return 0; } double AP_Motors::get_delta_min() { if(_backend != nullptr){ return _backend->get_delta_min(); } return 0.0; } int16_t AP_Motors::get_pwm() { if(_backend != nullptr){ return _backend->get_pwm(); } return 0; } uint16_t AP_Motors::get_delta_ms() { if(_backend != nullptr){ return _backend->get_delta_ms(); } return 0; } float AP_Motors::get_rpm() { if(_backend != nullptr){ return _backend->get_rpm(); } return 0.0f; } float AP_Motors::get_rpm_target() { if(_backend != nullptr){ return _backend->get_rpm_target(); } return 0.0f; } float AP_Motors::get_rpm_encoder() { if(_backend != nullptr){ return _backend->get_rpm_encoder(); } return 0.0f; }
20.452174
65
0.491071
SuWeipeng
0ccdfc083a30a31d158ec1cff9b2d2967e9b24dd
8,075
hpp
C++
include/mckl/random/internal/philox_avx2_4x32.hpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
12
2016-08-02T17:01:13.000Z
2021-03-04T12:11:33.000Z
include/mckl/random/internal/philox_avx2_4x32.hpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
5
2017-05-09T12:05:06.000Z
2021-03-16T10:39:23.000Z
include/mckl/random/internal/philox_avx2_4x32.hpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
2
2016-08-25T13:10:29.000Z
2019-05-01T01:54:29.000Z
//============================================================================ // MCKL/include/mckl/random/internal/philox_avx2_4x32.hpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2018, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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. //============================================================================ #ifndef MCKL_RANDOM_INTERNAL_PHILOX_AVX2_4X32_HPP #define MCKL_RANDOM_INTERNAL_PHILOX_AVX2_4X32_HPP #include <mckl/random/internal/common.hpp> #include <mckl/random/internal/philox_avx2_32_common.hpp> #include <mckl/random/internal/philox_common.hpp> #include <mckl/random/internal/philox_constants.hpp> #include <mckl/random/internal/philox_generic_4x.hpp> MCKL_PUSH_GCC_WARNING("-Wignored-attributes") namespace mckl { namespace internal { template <typename T, typename Constants> class Philox4x32GeneratorAVX2Impl { static_assert(std::numeric_limits<T>::digits == 32, "**Philox4x32GeneratorAVX2Impl** used with T other than a 32-bit " "unsigned integers"); static constexpr std::size_t K = 4; static constexpr std::size_t Rounds = 10; public: static void eval( const void *plain, void *cipher, const std::array<T, K / 2> &key) { Philox4xGeneratorGenericImpl<T, Constants>::eval(plain, cipher, key); } template <typename ResultType> static void eval(std::array<std::uint64_t, 2> &ctr, ResultType *r, const std::array<T, K / 2> &key) { Philox4xGeneratorGenericImpl<T, Constants>::eval(ctr, r, key); } template <typename ResultType> static void eval(std::array<std::uint64_t, 2> &ctr, std::size_t n, ResultType *r, const std::array<T, K / 2> &key) { constexpr std::size_t R = sizeof(T) * K / sizeof(ResultType); const std::size_t n0 = static_cast<std::size_t>(std::min(static_cast<std::uint64_t>(n), std::numeric_limits<std::uint64_t>::max() - ctr.front())); eval_kernel(ctr, n0, r, key); n -= n0; r += n0 * R; if (n != 0) { eval(ctr, r, key); n -= 1; r += R; } eval_kernel(ctr, n, r, key); } private: template <typename ResultType> static void eval_kernel(std::array<std::uint64_t, 2> &ctr, std::size_t n, ResultType *r, const std::array<T, K / 2> &key) { #if MCKL_USE_ASM_LIBRARY constexpr T m0 = Constants::multiplier::value[0]; constexpr T m1 = Constants::multiplier::value[1]; constexpr T w0 = Constants::weyl::value[0]; constexpr T w1 = Constants::weyl::value[1]; const T mwk[12] = {m0, 0, m1, 0, 0, w0, 0, w1, 0, std::get<0>(key), 0, std::get<1>(key)}; mckl_philox4x32_avx2_kernel(ctr.data(), n, r, mwk); #else // MCKL_USE_ASM_LIBRARY constexpr std::size_t S = 8; constexpr std::size_t N = sizeof(__m256i) * S / (sizeof(T) * K); const int k0 = static_cast<int>(std::get<0>(key)); const int k1 = static_cast<int>(std::get<1>(key)); const __m256i ymmk0 = _mm256_set_epi32(k1, 0, k0, 0, k1, 0, k0, 0); __m256i ymmc = _mm256_set_epi64x(static_cast<MCKL_INT64>(std::get<1>(ctr)), static_cast<MCKL_INT64>(std::get<0>(ctr)), static_cast<MCKL_INT64>(std::get<1>(ctr)), static_cast<MCKL_INT64>(std::get<0>(ctr))); ctr.front() += n; __m256i *rptr = reinterpret_cast<__m256i *>(r); while (n != 0) { __m256i ymm0 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x02, 0, 0x01)); __m256i ymm1 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x04, 0, 0x03)); __m256i ymm2 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x06, 0, 0x05)); __m256i ymm3 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x08, 0, 0x07)); __m256i ymm4 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x0A, 0, 0x09)); __m256i ymm5 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x0C, 0, 0x0B)); __m256i ymm6 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x0E, 0, 0x0D)); __m256i ymm7 = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x10, 0, 0x0F)); ymmc = _mm256_add_epi64(ymmc, _mm256_set_epi64x(0, 0x10, 0, 0x10)); ymm0 = _mm256_shuffle_epi32(ymm0, 0xC6); ymm1 = _mm256_shuffle_epi32(ymm1, 0xC6); ymm2 = _mm256_shuffle_epi32(ymm2, 0xC6); ymm3 = _mm256_shuffle_epi32(ymm3, 0xC6); ymm4 = _mm256_shuffle_epi32(ymm4, 0xC6); ymm5 = _mm256_shuffle_epi32(ymm5, 0xC6); ymm6 = _mm256_shuffle_epi32(ymm6, 0xC6); ymm7 = _mm256_shuffle_epi32(ymm7, 0xC6); MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 0, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 1, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 2, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 3, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 4, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 5, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 6, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 7, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 8, 0x93) MCKL_RANDOM_INTERNAL_PHILOX_AVX2_32_RBOX(4, 9, 0xB1) if (n >= N) { n -= N; _mm256_storeu_si256(rptr++, ymm0); _mm256_storeu_si256(rptr++, ymm1); _mm256_storeu_si256(rptr++, ymm2); _mm256_storeu_si256(rptr++, ymm3); _mm256_storeu_si256(rptr++, ymm4); _mm256_storeu_si256(rptr++, ymm5); _mm256_storeu_si256(rptr++, ymm6); _mm256_storeu_si256(rptr++, ymm7); } else { std::array<__m256i, S> s; std::get<0>(s) = ymm0; std::get<1>(s) = ymm1; std::get<2>(s) = ymm2; std::get<3>(s) = ymm3; std::get<4>(s) = ymm4; std::get<5>(s) = ymm5; std::get<6>(s) = ymm6; std::get<7>(s) = ymm7; std::memcpy(rptr, s.data(), n * sizeof(T) * K); break; } } #endif // MCKL_USE_ASM_LIBRARY } }; // class Philox4x32GeneratorAVX2Impl } // namespace internal } // namespace mckl MCKL_POP_GCC_WARNING #endif // MCKL_RANDOM_INTERNAL_PHILOX_AVX2_4X32_HPP
40.782828
79
0.597399
zhouyan
0ccf2623b098bd019c880f70065590c3661a1ae6
172
cpp
C++
C++/Qt/windowsInherit/car.cpp
aadshalshihry/sandbox
87650335d8a9cfe7d4612592180d3d22de8f3dcb
[ "MIT" ]
null
null
null
C++/Qt/windowsInherit/car.cpp
aadshalshihry/sandbox
87650335d8a9cfe7d4612592180d3d22de8f3dcb
[ "MIT" ]
null
null
null
C++/Qt/windowsInherit/car.cpp
aadshalshihry/sandbox
87650335d8a9cfe7d4612592180d3d22de8f3dcb
[ "MIT" ]
null
null
null
#include "car.h" #include "ui_car.h" car::car(QWidget *parent) : QScrollArea(parent), ui(new Ui::car) { ui->setupUi(this); } car::~car() { delete ui; }
10.117647
27
0.569767
aadshalshihry
0cd1f644fbbfc70cd0eea612839c0cb7724b7063
1,047
cpp
C++
src/Logger.cpp
Anonymous-275/LeagueAPI
7f41ac68b7c000f13e6a36a9af20c2123b3646cd
[ "MIT" ]
null
null
null
src/Logger.cpp
Anonymous-275/LeagueAPI
7f41ac68b7c000f13e6a36a9af20c2123b3646cd
[ "MIT" ]
null
null
null
src/Logger.cpp
Anonymous-275/LeagueAPI
7f41ac68b7c000f13e6a36a9af20c2123b3646cd
[ "MIT" ]
1
2022-03-07T18:33:55.000Z
2022-03-07T18:33:55.000Z
/// /// Created by Anonymous275 on 12/26/21 /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// #include "Logger.h" INITIALIZE_EASYLOGGINGPP using namespace el; void Log::Init() { Configurations Conf; Conf.setToDefault(); std::string DFormat("%datetime{[%d/%M/%y %H:%m:%s]} %fbase:%line [%level] %msg"); Conf.setGlobally(ConfigurationType::Format, "%datetime{[%d/%M/%y %H:%m:%s]} [%level] %msg"); Conf.setGlobally(ConfigurationType::LogFlushThreshold, "2"); Conf.set(Level::Verbose,ConfigurationType::Format, DFormat); Conf.set(Level::Debug,ConfigurationType::Format, DFormat); Conf.set(Level::Trace,ConfigurationType::Format, DFormat); Conf.set(Level::Fatal,ConfigurationType::Format, DFormat); Conf.setGlobally(ConfigurationType::Filename, "LeagueAPI.log"); Conf.setGlobally(ConfigurationType::MaxLogFileSize, "7340032"); Loggers::reconfigureAllLoggers(Conf); Loggers::addFlag(LoggingFlag::HierarchicalLogging); Loggers::setLoggingLevel(Level::Global); }
41.88
96
0.717287
Anonymous-275
7b48853969d1b8629af44dd60ef7e35fdfb3261b
845
hpp
C++
Assignment2/include/MemoryFunction.hpp
dissolete/cs466
07a3813fc0cbee4d1406f763189c215f998c39f2
[ "MIT" ]
null
null
null
Assignment2/include/MemoryFunction.hpp
dissolete/cs466
07a3813fc0cbee4d1406f763189c215f998c39f2
[ "MIT" ]
null
null
null
Assignment2/include/MemoryFunction.hpp
dissolete/cs466
07a3813fc0cbee4d1406f763189c215f998c39f2
[ "MIT" ]
null
null
null
// Program Information ///////////////////////////////////////////////////////// /** * @file Simulator Functions.c * * @brief Memory Address Locator for CS 446/646 at the Univserity of * Nevada, Reno * * @details This file includes the necessary function for assignment 2 of the * CS 446/646 course simulator. * * @author Vineeth Rajamohan * * @version 1.01 (27 Jan 17) */ // PRECOMPILER DIRECTIVES ////////////////////////////////////////////////////// #ifndef MEM_FUNC_H #define MEM_FUNC_H // HEADER FILES //////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> // GLOBAL CONSTANTS //////////////////////////////////////////////////////////// // None unsigned int allocateMemory( int totMem ); #endif // MEM_FUNC_H
24.142857
80
0.489941
dissolete
7b4d77bb9d3581b30a9061bc9170d036b98ad3a6
15,512
cpp
C++
source/mclib/stuff/trace.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/mclib/stuff/trace.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/mclib/stuff/trace.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
//===========================================================================// // File: analysis.cpp // // Contents: Utilities for using logic analyzer with parallel port dongle // //---------------------------------------------------------------------------// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// #include "stdinc.h" //#include "stuff/stuffheaders.h" //#define TRACE_ENABLED #if defined(TRACE_ENABLED) //#include "gameos.hpp" #include "toolos.hpp" #include "stuff/filestream.h" #include "stuff/trace.h" //########################################################################## //############################ Trace ################################# //########################################################################## uint8_t Stuff::Trace::NextTraceID = 0; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Stuff::Trace::Trace(const std::wstring_view& name, Type type) : Plug(DefaultData) { traceNumber = NextTraceID++; traceType = (uint8_t)type; traceName = name; lastActivity = 0; Check_Object(Stuff::TraceManager::Instance); Stuff::TraceManager::Instance->Add(this); } #if defined(USE_TIME_ANALYSIS) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::Trace::PrintUsage(float usage) { // Check_Object(this); SPEW((GROUP_STUFF_TRACE, "%f+", usage)); } #endif //########################################################################## //########################### BitTrace ############################### //########################################################################## uint8_t Stuff::BitTrace::NextActiveLine = 0; int32_t Stuff::BitTrace::NextBit = 0; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Stuff::BitTrace::BitTrace(const std::wstring_view& name) : Trace(name, BitType) { activeLine = NextActiveLine++; bitFlag = (NextBit < 32) ? uint32_t(1 << NextBit++) : uint32_t(0); #if defined(USE_ACTIVE_PROFILE) DEBUG_STREAM << name << " used trace line " << static_cast<int32_t>(activeLine) << "!\n"; if (!IsLineValidImplementation(activeLine)) { STOP(("Invalid active trace line!")); } #endif BitTrace::ResetTrace(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::DumpTraceStatus() { // Check_Object(this); SPEW((GROUP_STUFF_TRACE, "%d = %d+", static_cast<int32_t>(activeLine), traceUp)); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::ResetTrace() { #if defined(USE_TIME_ANALYSIS) traceUp = 0; lastUpTime = 0; totalUpTime = 0; Stuff::TraceManager::Instance->activeBits &= ~bitFlag; #endif #if defined(USE_ACTIVE_PROFILE) ClearLineImplementation(activeLine); #endif } #if defined(USE_TIME_ANALYSIS) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::StartTiming() { // Check_Object(this); totalUpTime = 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // float Stuff::BitTrace::CalculateUsage(int64_t when, int64_t sample_time) { if (traceUp > 0) { totalUpTime += when - lastActivity; } float result = static_cast<float>(totalUpTime / sample_time); SPEW((GROUP_STUFF_TRACE, "%4fs, +", totalUpTime)); return result; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::PrintUsage(float usage) { // Check_Object(this); SPEW((GROUP_STUFF_TRACE, "%4f%% CPU+", (usage * 100.0f))); #if defined(USE_ACTIVE_PROFILE) SPEW((GROUP_STUFF_TRACE, " (active on line %d)", static_cast<int32_t>(activeLine))); #endif } #endif //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::Set(void) { // Check_Object(this); if (!traceUp++) { #if defined(USE_ACTIVE_PROFILE) SetLineImplementation(activeLine); #endif Stuff::TraceManager::Instance->activeBits |= bitFlag; #if defined(USE_TIME_ANALYSIS) || defined(USE_TRACE_LOG) int64_t now = gos_GetHiResTime(); #endif #if defined(USE_TIME_ANALYSIS) lastActivity = now; #endif #if defined(USE_TRACE_LOG) // Check_Object(traceManager); IncrementSampleCount(); std::iostream& log = GetTraceLog(); if (log) { Check_Object(log); TraceSample* sample = Cast_Pointer(TraceSample*, log->GetPointer()); sample->sampleLength = sizeof(*sample); sample->sampleType = TraceSample::GoingUp; sample->traceNumber = traceNumber; sample->sampleTime = now; log->AdvancePointer(sample->sampleLength); } #endif } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::Clear(void) { // Check_Object(this); if (--traceUp == 0) { Stuff::TraceManager::Instance->activeBits &= ~bitFlag; #if defined(USE_TIME_ANALYSIS) || defined(USE_TRACE_LOG) int64_t now = gos_GetHiResTime(); #endif #if defined(USE_TIME_ANALYSIS) lastUpTime = now - lastActivity; #if 0 // HACK _ASSERT(lastUpTime >= 0.0f) totalUpTime += lastUpTime; #else if (lastUpTime >= 0.0f) { totalUpTime += lastUpTime; } #endif #endif #if defined(USE_TRACE_LOG) // Check_Object(traceManager); IncrementSampleCount(); std::iostream& log = GetTraceLog(); if (log) { Check_Object(log); TraceSample* sample = Cast_Pointer(TraceSample*, log->GetPointer()); sample->sampleLength = sizeof(*sample); sample->sampleType = TraceSample::GoingDown; sample->traceNumber = traceNumber; sample->sampleTime = now; log->AdvancePointer(sample->sampleLength); } #endif #if defined(USE_ACTIVE_PROFILE) ClearLineImplementation(activeLine); #endif } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::BitTrace::TestInstance(void) { _ASSERT(traceUp >= 0); } //########################################################################## //######################## TraceManager ############################## //########################################################################## Stuff::TraceManager* Stuff::TraceManager::Instance = nullptr; void Stuff::TraceManager::InitializeClass(void) { _ASSERT(!Stuff::TraceManager::Instance); Stuff::TraceManager::Instance = new Stuff::TraceManager; Register_Object(Stuff::TraceManager::Instance); } void Stuff::TraceManager::TerminateClass() { Unregister_Object(Stuff::TraceManager::Instance); delete Stuff::TraceManager::Instance; Stuff::TraceManager::Instance = nullptr; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Stuff::TraceManager::TraceManager(void) : traceChain(nullptr) { sampleStart = 0; actualSampleCount = 0; ignoredSampleCount = 0; traceCount = 0; activeTraceLog = nullptr; allocatedTraceLog = nullptr; activeBits = 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Stuff::TraceManager::~TraceManager() { // Check_Object(this); if (allocatedTraceLog) { Check_Object(allocatedTraceLog); allocatedTraceLog->Rewind(); TraceSample* samples = Cast_Pointer(TraceSample*, allocatedTraceLog->GetPointer()); Unregister_Object(allocatedTraceLog); delete allocatedTraceLog; activeTraceLog = allocatedTraceLog = nullptr; Unregister_Pointer(samples); delete[] samples; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::Add(Trace* trace) { // Check_Object(this); traceCount = (uint8_t)(traceCount + 1); traceChain.Add(trace); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::DumpTracesStatus() { ChainIteratorOf<Trace*> traces(&traceChain); Trace* trace; while ((trace = traces.ReadAndNext()) != nullptr) { Check_Object(trace); SPEW((GROUP_STUFF_TRACE, "%s: +", trace->traceName)); trace->DumpTraceStatus(); SPEW((GROUP_STUFF_TRACE, "")); } SPEW((GROUP_STUFF_TRACE, "")); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::ResetTraces() { ChainIteratorOf<Trace*> traces(&traceChain); Trace* trace; while ((trace = traces.ReadAndNext()) != nullptr) { Check_Object(trace); trace->ResetTrace(); } #if defined(USE_TRACE_LOG) actualSampleCount = 0; ignoredSampleCount = 0; if (allocatedTraceLog) { allocatedTraceLog->Rewind(); } #endif } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // const std::wstring_view& Stuff::TraceManager::GetNameOfTrace(int32_t bit_no) { // // Set up the iterator // ChainIteratorOf<Trace*> traces(&traceChain); Trace* trace; while ((trace = traces.ReadAndNext()) != nullptr) { Check_Object(trace); if (trace->traceType == Trace::BitType) { if (!bit_no) { break; } --bit_no; } } Check_Object(trace); return trace ? trace->traceName : nullptr; } #if defined(USE_TIME_ANALYSIS) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::StartTimingAnalysis() { sampleStart = gos_GetHiResTime(); ChainIteratorOf<Trace*> traces(&traceChain); Trace* trace; while ((trace = traces.ReadAndNext()) != nullptr) { Check_Object(trace); trace->StartTiming(); trace->lastActivity = sampleStart; } #if defined(USE_TRACE_LOG) actualSampleCount = 0; ignoredSampleCount = 0; if (allocatedTraceLog) { allocatedTraceLog->Rewind(); } #endif } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // int32_t Stuff::TraceManager::SnapshotTimingAnalysis(bool print) { int64_t now = gos_GetHiResTime(); int64_t time = now - sampleStart; if (time < SMALL) { return false; } ChainIteratorOf<Trace*> traces(&traceChain); Trace* trace; if (print) { SPEW((GROUP_STUFF_TRACE, "TIMING ANALYSIS")); SPEW((GROUP_STUFF_TRACE, "Sample length: %4fs", time)); } while ((trace = traces.ReadAndNext()) != nullptr) { Check_Object(trace); if (print) { SPEW((GROUP_STUFF_TRACE, "%s: +", trace->traceName)); float usage = trace->CalculateUsage(now, time); trace->PrintUsage(usage); SPEW((GROUP_STUFF_TRACE, "")); } trace->StartTiming(); trace->lastActivity = now; } SPEW((GROUP_STUFF_TRACE, "")); sampleStart = now; return true; } #endif #if defined(USE_TRACE_LOG) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::CreateTraceLog(size_t max_trace_count, bool start_logging) { // Check_Object(this); _ASSERT(!allocatedTraceLog); TraceSample* samples = new TraceSample[max_trace_count]; Register_Pointer(samples); allocatedTraceLog = new MemoryStream(samples, max_trace_count * sizeof(TraceSample)); Register_Object(allocatedTraceLog); if (start_logging) { activeTraceLog = allocatedTraceLog; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::SaveTraceLog(const std::wstring_view& filename) { // Check_Object(this); if (allocatedTraceLog) { Check_Object(allocatedTraceLog); // //-------------------------------------------------------- // Rewind the memory stream and save it out in a disk file //-------------------------------------------------------- // std::fstream output(filename, std::fstream::WriteOnly); size_t size = allocatedTraceLog->GetBytesUsed(); if (size > 0) { uint8_t trace_count = GetTraceCount(); // //---------------------------- // Write out the record header //---------------------------- // output << static_cast<int32_t>('RVNO') << sizeof(int32_t) << 2; // //--------------------------------------------------------- // Write out the header section after figuring out its size //--------------------------------------------------------- // ChainIteratorOf<Trace*> traces(&traceChain); Trace* trace; size_t header_size = sizeof(int32_t); while ((trace = traces.ReadAndNext()) != nullptr) { header_size += 2 * sizeof(int32_t); header_size += (strlen(trace->traceName) + 4) & ~3; } output << static_cast<int32_t>('HDRS') << header_size; output << static_cast<int32_t>(trace_count); traces.First(); while ((trace = traces.ReadAndNext()) != nullptr) { size_t str_len = strlen(trace->traceName) + 1; header_size = sizeof(int32_t) + ((str_len + 4) & ~3); output << header_size << static_cast<int32_t>(trace->traceType); output.WriteBytes(trace->traceName, str_len); while (str_len & 3) { output << '\0'; ++str_len; } } output << static_cast<int32_t>('LOGS') << ((size + 3) & ~3); allocatedTraceLog->Rewind(); output.WriteBytes(allocatedTraceLog->GetPointer(), size); while (size & 3) { output << '\0'; ++size; } } // //------------------- // Release the memory //------------------- // output.Close(); TraceSample* samples = Cast_Pointer(TraceSample*, allocatedTraceLog->GetPointer()); Unregister_Object(allocatedTraceLog); delete allocatedTraceLog; activeTraceLog = allocatedTraceLog = nullptr; Unregister_Pointer(samples); delete[] samples; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::MarkTraceLog() { // Check_Object(this); if (activeTraceLog) { Check_Object(activeTraceLog); int64_t now = gos_GetHiResTime(); TraceSample* sample = Cast_Pointer(TraceSample*, activeTraceLog->GetPointer()); sample->sampleLength = sizeof(*sample); sample->sampleType = TraceSample::Marker; sample->sampleTime = now; sample->traceNumber = 0; activeTraceLog->AdvancePointer(sample->sampleLength); } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::SuspendTraceLogging() { // Check_Object(this); if (activeTraceLog) { Check_Object(activeTraceLog); int64_t now = gos_GetHiResTime(); TraceSample* sample = Cast_Pointer(TraceSample*, activeTraceLog->GetPointer()); sample->sampleLength = sizeof(*sample); sample->sampleType = TraceSample::SuspendSampling; sample->sampleTime = now; sample->traceNumber = 0; activeTraceLog->AdvancePointer(sample->sampleLength); activeTraceLog = nullptr; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::ResumeTraceLogging() { // Check_Object(this); if (allocatedTraceLog && !activeTraceLog) { Check_Object(allocatedTraceLog); activeTraceLog = allocatedTraceLog; int64_t now = gos_GetHiResTime(); TraceSample* sample = Cast_Pointer(TraceSample*, activeTraceLog->GetPointer()); sample->sampleLength = sizeof(*sample); sample->sampleType = TraceSample::ResumeSampling; sample->sampleTime = now; sample->traceNumber = 0; activeTraceLog->AdvancePointer(sample->sampleLength); } } #if 0 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void Stuff::TraceManager::WriteClassBlocks(MemoryStream& stream) { stream << static_cast<int32_t>('MSGS') << RegisteredClass::DefaultData->WriteClassBlock(stream, false); RegisteredClass::DefaultData->WriteClassBlock(stream, true); } #endif #endif #if defined(USE_ACTIVE_PROFILE) void Stuff::TraceManager::SetLineImplementation(uint8_t) { } void Stuff::TraceManager::ClearLineImplementation(uint8_t) {} bool Stuff::TraceManager::IsLineValidImplementation(uint8_t) { return true; } #endif #endif
25.72471
90
0.560469
mechasource
7b54b295d9712fe9c0297724a10d0fe1d39993f8
1,135
cpp
C++
src/classifier/svm/svm_classifier.cpp
bububa/openvision
0864e48ec8e69ac13d6889d41f7e1171f53236dd
[ "Apache-2.0" ]
1
2022-02-08T06:42:05.000Z
2022-02-08T06:42:05.000Z
src/classifier/svm/svm_classifier.cpp
bububa/openvision
0864e48ec8e69ac13d6889d41f7e1171f53236dd
[ "Apache-2.0" ]
null
null
null
src/classifier/svm/svm_classifier.cpp
bububa/openvision
0864e48ec8e69ac13d6889d41f7e1171f53236dd
[ "Apache-2.0" ]
null
null
null
#include "../svm_classifier.h" #include "svm_binary_classifier.hpp" #include "svm_multiclass_classifier.hpp" ISVMClassifier new_svm_binary_classifier() { return new ovclassifier::SVMBinaryClassifier(); } ISVMClassifier new_svm_multiclass_classifier() { return new ovclassifier::SVMMultiClassClassifier(); } void destroy_svm_classifier(ISVMClassifier e) { delete static_cast<ovclassifier::SVMClassifier *>(e); } int svm_classifier_load_model(ISVMClassifier e, const char *modelfile) { return static_cast<ovclassifier::SVMClassifier *>(e)->LoadModel(modelfile); } double svm_predict(ISVMClassifier e, const float *vec) { return static_cast<ovclassifier::SVMClassifier *>(e)->Predict(vec); } int svm_classify(ISVMClassifier e, const float *vec, FloatVector *scores) { std::vector<float> scores_; int ret = static_cast<ovclassifier::SVMClassifier *>(e)->Classify(vec, scores_); if (ret != 0) { return ret; } scores->length = scores_.size(); scores->values = (float *)malloc(sizeof(float) * scores->length); for (int i = 0; i < scores->length; ++i) { scores->values[i] = scores_[i]; } return 0; }
33.382353
77
0.734802
bububa
7b5d9bdbbc29bebe8c7b3f19eabb9cf174545711
7,233
cpp
C++
qt/main.cpp
kainjow/Glypha
b0ff71fd942cdb7abfa95310acd9764f2df786de
[ "MIT" ]
25
2015-08-15T17:42:31.000Z
2022-01-20T04:40:36.000Z
qt/main.cpp
kainjow/Glypha
b0ff71fd942cdb7abfa95310acd9764f2df786de
[ "MIT" ]
9
2015-08-11T00:46:13.000Z
2022-01-20T04:21:49.000Z
qt/main.cpp
kainjow/Glypha
b0ff71fd942cdb7abfa95310acd9764f2df786de
[ "MIT" ]
1
2018-10-28T14:48:58.000Z
2018-10-28T14:48:58.000Z
// sudo apt-get install libqt4-dev libqt4-opengl-dev #include <QApplication> #include <QWidget> #include <QMainWindow> #include <QHBoxLayout> #include <QMenuBar> #include <QMessageBox> #include <QInputDialog> #include "main.hpp" GLWidget::GLWidget(QWidget *parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) , game_(callback, highScoreNameCallback, this) { timer_.setInterval(1000.0 / 30.0); connect(&timer_, SIGNAL(timeout()), this, SLOT(updateGL())); timer_.start(); setFocusPolicy(Qt::StrongFocus); } void GLWidget::callback(GL::Game::Event event, void *context) { GLWidget *widget = (GLWidget*)context; MainWindow *win = (MainWindow*)widget->window(); win->callback(event); } void GLWidget::highScoreNameCallback(const char *name, int place, void *context) { GLWidget *widget = (GLWidget*)context; widget->highScoreNameCallback(name, place); } void GLWidget::highScoreNameCallback(const char *name, int place) { QString label = tr("Your score #%1 of the ten best! Enter your name (15 chars.).").arg(place); QString input; bool ok; do { input = QInputDialog::getText(this, tr("High Score"), label, QLineEdit::Normal, QString::fromStdString(name), &ok); } while (!ok); game_.processHighScoreName(input.toStdString().c_str(), place); } void GLWidget::paintGL() { game_.run(); } void GLWidget::resizeGL(int width, int height) { game_.renderer()->resize(width, height); } void GLWidget::newGame() { game_.newGame(); } bool GLWidget::pauseGame() { game_.pauseResumeGame(); return game_.paused(); } void GLWidget::endGame() { game_.endGame(); } void GLWidget::showHelp() { game_.showHelp(); } void GLWidget::showAbout() { game_.showAbout(); } void GLWidget::showHighScores() { game_.showHighScores(); } void GLWidget::resetHighScores() { QMessageBox msgbox(QMessageBox::Warning, tr("Reset Scores"), tr("Are you sure you want to reset " GL_GAME_NAME "'s scores?"), QMessageBox::Yes | QMessageBox::No, this, Qt::Dialog); if (msgbox.exec() == QMessageBox::Yes) { game_.resetHighScores(); } } bool GLWidget::handleKeyEvent(int key, bool down) { GL::Game::Key gameKey = GL::Game::KeyNone; switch (key) { case Qt::Key_Up: gameKey = GL::Game::KeyUpArrow; break; case Qt::Key_Down: gameKey = GL::Game::KeyDownArrow; break; case Qt::Key_Left: gameKey = GL::Game::KeyLeftArrow; break; case Qt::Key_Right: gameKey = GL::Game::KeyRightArrow; break; case Qt::Key_Space: gameKey = GL::Game::KeySpacebar; break; case Qt::Key_PageUp: gameKey = GL::Game::KeyPageUp; break; case Qt::Key_PageDown: gameKey = GL::Game::KeyPageDown; break; } if (gameKey) { if (down) { game_.handleKeyDownEvent(gameKey); } else { game_.handleKeyUpEvent(gameKey); } return true; } return false; } void GLWidget::keyPressEvent(QKeyEvent *event) { if (!handleKeyEvent(event->key(), true)) { QGLWidget::keyPressEvent(event); } } void GLWidget::keyReleaseEvent(QKeyEvent *event) { if (!handleKeyEvent(event->key(), false)) { QGLWidget::keyReleaseEvent(event); } } void GLWidget::mousePressEvent(QMouseEvent *event) { game_.handleMouseDownEvent(GL::Point(event->pos().x(), event->pos().y())); } MainWindow::MainWindow() : QMainWindow() { setWindowTitle(GL_GAME_NAME); QWidget *mainWidget = new QWidget; glwid_ = new GLWidget; glwid_->setFixedSize(640, 460); QHBoxLayout *layout = new QHBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(glwid_); mainWidget->setLayout(layout); setCentralWidget(mainWidget); QMenu *fileMenu = new QMenu("&File"); newAction_ = fileMenu->addAction("&New Game"); QObject::connect(newAction_, SIGNAL(triggered()), glwid_, SLOT(newGame())); newAction_->setShortcut(QKeySequence("Ctrl+N")); pauseAction_ = fileMenu->addAction("&Pause Game\tCtrl+P"); QObject::connect(pauseAction_, SIGNAL(triggered()), this, SLOT(pauseGame())); pauseAction_->setShortcut(QKeySequence("Ctrl+P")); pauseAction_->setEnabled(false); endAction_ = fileMenu->addAction("&End Game\tCtrl+E"); QObject::connect(endAction_, SIGNAL(triggered()), glwid_, SLOT(endGame())); endAction_->setShortcut(QKeySequence("Ctrl+E")); endAction_->setEnabled(false); fileMenu->addSeparator(); QAction *quitMenu = fileMenu->addAction("&Quit"); QObject::connect(quitMenu, SIGNAL(triggered()), qApp, SLOT(quit())); quitMenu->setShortcut(QKeySequence("Ctrl+Q")); menuBar()->addMenu(fileMenu); QMenu *optionsMenu = new QMenu("&Options"); helpAction_ = optionsMenu->addAction("&Help"); QObject::connect(helpAction_, SIGNAL(triggered()), glwid_, SLOT(showHelp())); helpAction_->setShortcut(QKeySequence("Ctrl+H")); optionsMenu->addSeparator(); scoresAction_ = optionsMenu->addAction("High &Scores"); QObject::connect(scoresAction_, SIGNAL(triggered()), glwid_, SLOT(showHighScores())); scoresAction_->setShortcut(QKeySequence("Ctrl+S")); resetAction_ = optionsMenu->addAction("&Reset Scores..."); QObject::connect(resetAction_, SIGNAL(triggered()), glwid_, SLOT(resetHighScores())); optionsMenu->addSeparator(); aboutAction_ = optionsMenu->addAction("&About " GL_GAME_NAME); QObject::connect(aboutAction_, SIGNAL(triggered()), glwid_, SLOT(showAbout())); menuBar()->addMenu(optionsMenu); } void MainWindow::pauseGame() { if (glwid_->pauseGame()) { pauseAction_->setText("&Resume Game\tCtrl+R"); pauseAction_->setShortcut(QKeySequence("Ctrl+R")); } else { pauseAction_->setText("&Pause Game\tCtrl+P"); pauseAction_->setShortcut(QKeySequence("Ctrl+P")); } } void MainWindow::callback(GL::Game::Event event) { switch (event) { case GL::Game::EventStarted: newAction_->setEnabled(false); pauseAction_->setEnabled(true); endAction_->setEnabled(true); helpAction_->setEnabled(false); scoresAction_->setEnabled(false); resetAction_->setEnabled(false); aboutAction_->setEnabled(false); break; case GL::Game::EventEnded: newAction_->setEnabled(true); pauseAction_->setEnabled(false); pauseAction_->setText("&Pause Game\tCtrl+P"); pauseAction_->setShortcut(QKeySequence("Ctrl+P")); endAction_->setEnabled(false); helpAction_->setEnabled(true); scoresAction_->setEnabled(true); resetAction_->setEnabled(true); aboutAction_->setEnabled(true); break; } } int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("kainjow"); app.setOrganizationDomain("kainjow.com"); app.setApplicationName(GL_GAME_NAME); MainWindow win; win.show(); return app.exec(); }
28.932
123
0.640813
kainjow
7b5ee4f62ce90cc3dda26e1b5f64c6c2f2ba7e5e
9,015
cpp
C++
Operations/albaOpClassicICPRegistration.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Operations/albaOpClassicICPRegistration.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Operations/albaOpClassicICPRegistration.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaOpClassicICPRegistration Authors: Stefania Paperini, Stefano Perticoni, porting Matteo Giacomoni Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include <wx/wxprec.h> #include "albaDecl.h" #include "albaOp.h" #include "albaEvent.h" #include "albaGUI.h" #include "vtkALBASmartPointer.h" #include "albaOpClassicICPRegistration.h" #include "albaVME.h" #include "albaVMELandmarkCloud.h" #include "albaAbsMatrixPipe.h" #include "albaVMEItem.h" #include "albaVMESurface.h" #include "vtkMatrix4x4.h" #include "vtkTransform.h" #include "albaVMERoot.h" #include "albaClassicICPRegistration.h" #include "vtkTransformPolyDataFilter.h" //---------------------------------------------------------------------------- albaOpClassicICPRegistration::albaOpClassicICPRegistration(wxString label) : albaOp(label) //---------------------------------------------------------------------------- { m_OpType = OPTYPE_OP; m_Canundo = true; m_Target = NULL; m_Registered = NULL; m_Convergence = 0.0001; m_ReportFilename = ""; m_InputName = ""; m_TargetName = _("none"); m_CopySubTree = false; } //---------------------------------------------------------------------------- albaOpClassicICPRegistration::~albaOpClassicICPRegistration( ) //---------------------------------------------------------------------------- { albaDEL(m_Registered); } //---------------------------------------------------------------------------- albaOp* albaOpClassicICPRegistration::Copy() //---------------------------------------------------------------------------- { return new albaOpClassicICPRegistration(m_Label); } //---------------------------------------------------------------------------- bool albaOpClassicICPRegistration::Accept(albaVME* vme) //---------------------------------------------------------------------------- { if(!vme) return false; if( vme->IsA("albaVMESurface") || vme->IsA("albaVMESurfaceParametric")) return true; if( vme->IsA("albaVMELandmarkCloud") && ((albaVMELandmarkCloud *)vme)->IsRigid() ) return true; return false; }; //---------------------------------------------------------------------------- // wodget id's //---------------------------------------------------------------------------- enum { ID_CHOOSE = MINID, ID_CONVERGENCE, ID_FILE, }; //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::CreateGui() //---------------------------------------------------------------------------- { wxString wildcard = _("Report log (*.log)|*.log"); wxString dir = albaGetLastUserFolder().c_str(); if(!wxDirExists(dir)) dir = ""; m_ReportFilename = dir + _("report.log"); m_InputName = m_Input->GetName(); m_Gui = new albaGUI(this); m_Gui->SetListener(this); m_Gui->Label(_("Source:"),true); m_Gui->Label(&m_InputName); m_Gui->Label(_("Target:"),true); m_Gui->Label(&m_TargetName); m_Gui->Button(ID_CHOOSE,_("Choose target")); m_Gui->Bool(-1, "Copy subtree", &m_CopySubTree,true); m_Gui->Divider(1); m_Gui->Double(ID_CONVERGENCE, _("Conv.step"), &m_Convergence, 1.0e-20, 1.0e+20, 10); m_Gui->FileSave(ID_FILE,_("Report log"),&m_ReportFilename,wildcard); ////////////////////////////////////////////////////////////////////////// m_Gui->Label(""); m_Gui->Divider(1); m_Gui->OkCancel(); m_Gui->Label(""); m_Gui->Enable(wxOK,false); } //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::OpRun() //---------------------------------------------------------------------------- { CreateGui(); ShowGui(); } //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::OnEvent(albaEventBase *alba_event) //---------------------------------------------------------------------------- { if (albaEvent *e = albaEvent::SafeDownCast(alba_event)) { switch(e->GetId()) { case ID_CHOOSE: OnChooseTarget(); break; case wxOK: OpStop(OP_RUN_OK); break; case wxCANCEL: OpStop(OP_RUN_CANCEL); break; default: albaEventMacro(*e); break; } } } //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::OpStop(int result) //---------------------------------------------------------------------------- { HideGui(); albaEventMacro(albaEvent(this,result)); } //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::OpDo() //---------------------------------------------------------------------------- { wxBusyCursor *busyCursor = NULL; if (!m_TestMode) { busyCursor = new wxBusyCursor(); } assert( m_Target); assert(!m_Registered); m_Input->GetOutput()->Update(); albaSmartPointer<albaMatrix> icp_matrix; albaSmartPointer<albaMatrix> final_matrix; vtkALBASmartPointer<vtkTransform> inputTra,targetTra; vtkALBASmartPointer<vtkTransformPolyDataFilter> inputTraFilter,targetTraFilter; albaMatrix *inputMatr = m_Input->GetOutput()->GetAbsMatrix(); inputTra->SetMatrix(inputMatr->GetVTKMatrix()); inputTraFilter->SetInput((vtkPolyData *)m_Input->GetOutput()->GetVTKData()); inputTraFilter->SetTransform(inputTra); inputTraFilter->Update(); albaMatrix *targetMatr = m_Target->GetOutput()->GetAbsMatrix(); targetTra->SetMatrix(targetMatr->GetVTKMatrix()); targetTraFilter->SetInput((vtkPolyData *)m_Target->GetOutput()->GetVTKData()); targetTraFilter->SetTransform(targetTra); targetTraFilter->Update(); vtkALBASmartPointer<albaClassicICPRegistration> icp; //to be deleted //albaProgressMacro(icp,"classic ICP - registering"); icp->SetConvergence(m_Convergence); icp->SetSource(inputTraFilter->GetOutput()); icp->SetTarget(targetTraFilter->GetOutput()); icp->SetResultsFileName(m_ReportFilename.GetCStr()); icp->SaveResultsOn(); icp->Update(); vtkALBASmartPointer<vtkMatrix4x4> appo_matrix; icp->GetMatrix(appo_matrix); icp_matrix->SetVTKMatrix(appo_matrix); //modified by Stefano 7-11-2004 double error = icp->GetRegistrationError(); albaMatrix::Multiply4x4(*icp_matrix, *inputMatr, *final_matrix); wxString name = wxString::Format(_("%s registered on %s"),m_Input->GetName(), m_Target->GetName()); if (m_CopySubTree) { m_Registered = albaVME::CopyTree(m_Input, m_Input->GetParent()); } else { m_Registered = m_Input->NewInstance(); m_Registered->Register(this); m_Registered->DeepCopy(m_Input); //not to be deleted, - delete it in the Undo or in destructor m_Registered->GetOutput()->Update(); } m_Registered->SetName(name); m_Registered->ReparentTo(m_Input->GetParent()); m_Registered->SetAbsMatrix(*final_matrix); m_Output = m_Registered; GetLogicManager()->CameraUpdate(); wxString regString; regString = _("Registration done!"); regString << '\n'; regString << _("ICP registration error: "); regString << error; if (!m_TestMode) { wxMessageBox(regString); } cppDEL(busyCursor); } //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::OnChooseTarget() //---------------------------------------------------------------------------- { albaEvent e(this,VME_CHOOSE); albaEventMacro(e); albaVME *vme = e.GetVme(); if(!vme) return; // the user choosed cancel - keep previous target if(!Accept(vme)) // the user choosed ok - check if it is a valid vme { wxString msg = _("target vme must be a non-empty LandmarkCloud or Surface\n please choose another vme \n"); wxMessageBox(msg,_("incorrect vme type"),wxOK|wxICON_ERROR); m_Target = NULL; m_TargetName = _("none"); m_Gui->Enable(wxOK,false); m_Gui->Update(); return; } SetTarget(vme); m_Gui->Enable(wxOK,true); m_Gui->Update(); } //---------------------------------------------------------------------------- void albaOpClassicICPRegistration::SetTarget(albaVME* node) //---------------------------------------------------------------------------- { m_Target = node; m_TargetName = m_Target->GetName(); }
31.968085
111
0.542207
IOR-BIC
7b5ef3f45bf9f989c62b3eb00f546ddb2663fceb
5,040
hpp
C++
sources/Framework/Tools/spStoryboard.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/Framework/Tools/spStoryboard.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/Framework/Tools/spStoryboard.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2020-02-15T09:17:41.000Z
2020-05-21T14:10:40.000Z
/* * Storyboard header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_STORYBOARD_H__ #define __SP_STORYBOARD_H__ #include "Base/spStandard.hpp" #ifdef SP_COMPILE_WITH_STORYBOARD #include "Framework/Tools/spStoryboardTrigger.hpp" #include "Framework/Tools/spStoryboardEvent.hpp" #include "Framework/Tools/spStoryboardLogicGate.hpp" #include <list> #include <vector> namespace sp { namespace tool { class SP_EXPORT Storyboard { public: Storyboard(); ~Storyboard(); /* === Functions === */ //! Updates the whole storyboard. void update(); void deleteTrigger(Trigger* Obj); void clearTriggers(); void deleteEvent(Event* Obj); void clearEvents(); /* === Template functions === */ template <typename T> T* createTrigger() { return addTrigger(new T()); } template <typename T, typename Arg0> T* createTrigger(const Arg0 &arg0) { return addTrigger(new T(arg0)); } template <typename T, typename Arg0, typename Arg1> T* createTrigger(const Arg0 &arg0, const Arg1 &arg1) { return addTrigger(new T(arg0, arg1)); } template <typename T, typename Arg0, typename Arg1, typename Arg2> T* createTrigger(const Arg0 &arg0, const Arg1 &arg1, const Arg2 &arg2) { return addTrigger(new T(arg0, arg1, arg2)); } template <typename T, typename Arg0, typename Arg1, typename Arg2, typename Arg3> T* createTrigger(const Arg0 &arg0, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3) { return addTrigger(new T(arg0, arg1, arg2, arg3)); } template <typename T, typename Arg0, typename Arg1, typename Arg2, typename Arg3, typename Arg4> T* createTrigger(const Arg0 &arg0, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4) { return addTrigger(new T(arg0, arg1, arg2, arg3, arg4)); } template <typename T> T* createEvent() { return addEvent(new T()); } template <typename T, typename Arg0> T* createEvent(const Arg0 &arg0) { return addEvent(new T(arg0)); } template <typename T, typename Arg0, typename Arg1> T* createEvent(const Arg0 &arg0, const Arg1 &arg1) { return addEvent(new T(arg0, arg1)); } template <typename T, typename Arg0, typename Arg1, typename Arg2> T* createEvent(const Arg0 &arg0, const Arg1 &arg1, const Arg2 &arg2) { return addEvent(new T(arg0, arg1, arg2)); } template <typename T, typename Arg0, typename Arg1, typename Arg2, typename Arg3> T* createEvent(const Arg0 &arg0, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3) { return addEvent(new T(arg0, arg1, arg2, arg3)); } template <typename T, typename Arg0, typename Arg1, typename Arg2, typename Arg3, typename Arg4> T* createEvent(const Arg0 &arg0, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4) { return addEvent(new T(arg0, arg1, arg2, arg3, arg4)); } /* === Static functions === */ static Storyboard* getActive(); static void setActive(Storyboard* ActiveStoryboard); /* === Inline functions === */ inline const std::list<Trigger*>& getTriggerList() const { return Triggers_; } inline const std::vector<Trigger*>& getActiveTriggerList() const { return ActiveTriggers_; } inline const std::vector<Event*>& getEventList() const { return Events_; } private: friend class Trigger; /* === Functions === */ void addLoopUpdate(Trigger* Obj); void removeLoopUpdate(Trigger* Obj); /* === Template functions === */ template <typename T> T* addTrigger(T* NewTrigger) { Triggers_.push_back(NewTrigger); return NewTrigger; } template <typename T> T* addEvent(T* NewEvent) { Events_.push_back(NewEvent); return NewEvent; } /* === Members === */ std::list<Trigger*> Triggers_; std::vector<Trigger*> ActiveTriggers_; std::vector<Event*> Events_; static Storyboard* Active_; }; } // /namespace tool } // /namespace sp #endif #endif // ================================================================================
27.845304
118
0.544444
rontrek
7b66ef8030c8421f381736683b616af59b1c053d
976
cpp
C++
src/stable/condition.cpp
zippy/libbu
6c79102419f9e79d25751fefc155f746496f4b50
[ "BSD-3-Clause" ]
1
2020-02-20T23:15:54.000Z
2020-02-20T23:15:54.000Z
src/stable/condition.cpp
zippy/libbu
6c79102419f9e79d25751fefc155f746496f4b50
[ "BSD-3-Clause" ]
null
null
null
src/stable/condition.cpp
zippy/libbu
6c79102419f9e79d25751fefc155f746496f4b50
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2007-2013 Xagasoft, All rights reserved. * * This file is part of the libbu++ library and is released under the * terms of the license contained in the file LICENSE. */ #include <sys/time.h> #include "bu/condition.h" Bu::Condition::Condition() { pthread_cond_init( &cond, NULL ); } Bu::Condition::~Condition() { pthread_cond_destroy( &cond ); } int Bu::Condition::wait() { return pthread_cond_wait( &cond, &mutex ); } int Bu::Condition::wait( int nSec, int nUSec ) { struct timeval now; struct timespec timeout; struct timezone tz; gettimeofday( &now, &tz ); timeout.tv_sec = now.tv_sec + nSec + ((now.tv_usec + nUSec)/1000000); timeout.tv_nsec = ((now.tv_usec + nUSec)%1000000)*1000; return pthread_cond_timedwait( &cond, &mutex, &timeout ); } int Bu::Condition::signal() { return pthread_cond_signal( &cond ); } int Bu::Condition::broadcast() { return pthread_cond_broadcast( &cond ); }
19.52
73
0.664959
zippy
7b6b78c8bd174ed04ec9dc3b68d77719dc50f538
2,023
cpp
C++
commander/hints.cpp
alamb/aal_commander
98904febdd1da0e17cbdc1f15669197e74d997de
[ "BSD-2-Clause", "MIT" ]
null
null
null
commander/hints.cpp
alamb/aal_commander
98904febdd1da0e17cbdc1f15669197e74d997de
[ "BSD-2-Clause", "MIT" ]
null
null
null
commander/hints.cpp
alamb/aal_commander
98904febdd1da0e17cbdc1f15669197e74d997de
[ "BSD-2-Clause", "MIT" ]
null
null
null
#include "hints.h" #include "parsed_line.h" #include <algorithm> const int Hints::COLOR_MAGENTA = 35; const int Hints::COLOR_RED = 31; const int Hints::COLOR_GREEN = 32; Hints::Hints() { } // create the expected hints from a set of possibilities Hints::Hints(const Parsed_line &line, const std::vector<std::string> &completions) { if (completions.empty()) { hint_text_ = " (INVALID " + line.dump() + ")"; color_ = COLOR_RED; bold_ = true; } else if (completions.size() == 1) { hint_text_ = line.remove_command_and_args(completions[0]); color_ = COLOR_GREEN; } else { // find longest common prefix between all completions std::string common_prefix = completions[0]; for (const std::string &s : completions) { size_t len = 0; while (len < s.size() && len < common_prefix.size() && common_prefix[len] == s[len]) { len++; } common_prefix = common_prefix.substr(0,len); } // create a sorted list of remaining completions (sorted by shortest to longest) std::vector<std::string> remainders; for (const std::string &s : completions) { if (s.size() > common_prefix.size()) { remainders.emplace_back(s.substr(common_prefix.size())); } } std::sort(remainders.begin(), remainders.end(), [](const auto &s1, const auto &s2) { return s1.size() < s2.size(); }); std::stringstream ss; ss << "{"; bool first = true; for (const std::string &s : remainders) { if (!first) { ss << ","; } first = false; ss << s; } ss << "}"; hint_text_ = line.remove_command_and_args(common_prefix) + ss.str(); color_ = COLOR_MAGENTA; } }
27.712329
88
0.512605
alamb
7b7108a927f6aeadb188551b6509b64d506056f6
1,299
cpp
C++
Source/Source/block.cpp
JuanDiegoMontoya/2D_Game_Engine
b2b026de9d5e0953331cb5a4db55bb6cacf5b55e
[ "MIT" ]
3
2021-07-12T08:06:13.000Z
2021-12-22T15:03:09.000Z
Source/Source/block.cpp
JuanDiegoMontoya/3D_Voxel_Engine
b2b026de9d5e0953331cb5a4db55bb6cacf5b55e
[ "MIT" ]
null
null
null
Source/Source/block.cpp
JuanDiegoMontoya/3D_Voxel_Engine
b2b026de9d5e0953331cb5a4db55bb6cacf5b55e
[ "MIT" ]
2
2021-02-07T04:20:51.000Z
2021-07-12T08:06:14.000Z
#include "stdafx.h" #include "pipeline.h" #include "block.h" const std::vector<BlockProperties> Block::PropertiesTable = { {BlockProperties("air", {0, 0, 0, 0}, Visibility::Invisible)}, {BlockProperties("stone", {0, 0, 0, 0})}, {BlockProperties("dirt", {0, 0, 0, 0}, Visibility::Opaque)}, {BlockProperties("metal", {0, 0, 0, 0})}, {BlockProperties("grass", {0, 0, 0, 0})}, {BlockProperties("sand", {0, 0, 0, 0})}, {BlockProperties("snow", {0, 0, 0, 0})}, {BlockProperties("water", {0, 0, 0, 0})}, {BlockProperties("oak wood", {0, 0, 0, 0})}, {BlockProperties("oak leaves", {0, 0, 0, 0}, Visibility::Partial)}, {BlockProperties("error", {0, 0, 0, 0})}, {BlockProperties("dry grass", {0, 0, 0, 0})}, {BlockProperties("Olight", {15, 8, 0, 0})}, {BlockProperties("Rlight", {15, 0, 0, 0})}, {BlockProperties("Glight", {0, 15, 0, 0})}, {BlockProperties("Blight", {0, 0, 15, 0})}, {BlockProperties("Smlight", {15, 15, 15, 0})}, {BlockProperties("Ylight", {15, 15, 0, 0})}, {BlockProperties("RGlass", {0, 0, 0, 0}, Visibility::Partial)}, {BlockProperties("GGlass", {0, 0, 0, 0}, Visibility::Partial)}, {BlockProperties("BGlass", {0, 0, 0, 0}, Visibility::Partial)}, };
44.793103
71
0.555812
JuanDiegoMontoya
7b77473424a6251452e5e6a721e952b3f91e3440
234
hh
C++
src/elle/cryptography/dsa/fwd.hh
infinitio/elle
d9bec976a1217137436db53db39cda99e7024ce4
[ "Apache-2.0" ]
521
2016-02-14T00:39:01.000Z
2022-03-01T22:39:25.000Z
src/elle/cryptography/dsa/fwd.hh
infinitio/elle
d9bec976a1217137436db53db39cda99e7024ce4
[ "Apache-2.0" ]
8
2017-02-21T11:47:33.000Z
2018-11-01T09:37:14.000Z
src/elle/cryptography/dsa/fwd.hh
infinitio/elle
d9bec976a1217137436db53db39cda99e7024ce4
[ "Apache-2.0" ]
48
2017-02-21T10:18:13.000Z
2022-03-25T02:35:20.000Z
#ifndef ELLE_CRYPTOGRAPHY_DSA_FWD_HH # define ELLE_CRYPTOGRAPHY_DSA_FWD_HH namespace elle { namespace cryptography { namespace dsa { class PrivateKey; class PublicKey; class KeyPair; } } } #endif
13
37
0.683761
infinitio
7b7f453a9ac4f03a38a5042b2e033dc6c86b48b4
4,102
hpp
C++
modules/cuml/src/node_cuml/umap.hpp
love-lena/node-rapids
27c9e2468372df4fae3779d859089b54c8d32c4f
[ "Apache-2.0" ]
1
2021-06-24T23:08:49.000Z
2021-06-24T23:08:49.000Z
modules/cuml/src/node_cuml/umap.hpp
love-lena/node-rapids
27c9e2468372df4fae3779d859089b54c8d32c4f
[ "Apache-2.0" ]
null
null
null
modules/cuml/src/node_cuml/umap.hpp
love-lena/node-rapids
27c9e2468372df4fae3779d859089b54c8d32c4f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // todo: including the below headers with undef guards is the only way cuml builds with raft // locally #include "cuml/manifold/umap.hpp" #include "cuml/manifold/umapparams.hpp" #include <node_cudf/column.hpp> #include <nv_node/objectwrap.hpp> #include <nv_node/utilities/args.hpp> #include <cuml/common/device_buffer.hpp> #include <raft/handle.hpp> #include <napi.h> namespace nv { /** * @brief An owning wrapper around a cuml::manifold::UMAP * */ struct UMAP : public EnvLocalObjectWrap<UMAP> { /** * @brief Initialize and export the UMAP JavaScript constructor and prototype * * @param env The active JavaScript environment * @param exports The exports object to decorate * @return Napi::Function The UMAP constructor function */ static Napi::Function Init(Napi::Env const& env, Napi::Object exports); /** * @brief Construct a new UMAP instance from C++. */ static wrapper_t New(Napi::Env const& env); /** * @brief Construct a new UMAP instance from JavaScript * * @param args */ UMAP(CallbackArgs const& args); void fit(DeviceBuffer::wrapper_t const& X, cudf::size_type n_samples, cudf::size_type n_features, DeviceBuffer::wrapper_t const& y, DeviceBuffer::wrapper_t const& knn_indices, DeviceBuffer::wrapper_t const& knn_dists, bool convert_dtype, DeviceBuffer::wrapper_t const& embeddings); void transform(DeviceBuffer::wrapper_t const& X, cudf::size_type n_samples, cudf::size_type n_features, DeviceBuffer::wrapper_t const& knn_indices, DeviceBuffer::wrapper_t const& knn_dists, DeviceBuffer::wrapper_t const& orig_X, int orig_n, bool convert_dtype, DeviceBuffer::wrapper_t const& embeddings, DeviceBuffer::wrapper_t const& transformed); private: ML::UMAPParams params_{}; Napi::Value get_embeddings(Napi::CallbackInfo const& info); Napi::Value fit(Napi::CallbackInfo const& info); Napi::Value fit_sparse(Napi::CallbackInfo const& info); Napi::Value transform(Napi::CallbackInfo const& info); Napi::Value transform_sparse(Napi::CallbackInfo const& info); Napi::Value n_neighbors(Napi::CallbackInfo const& info); Napi::Value n_components(Napi::CallbackInfo const& info); Napi::Value n_epochs(Napi::CallbackInfo const& info); Napi::Value learning_rate(Napi::CallbackInfo const& info); Napi::Value min_dist(Napi::CallbackInfo const& info); Napi::Value spread(Napi::CallbackInfo const& info); Napi::Value set_op_mix_ratio(Napi::CallbackInfo const& info); Napi::Value local_connectivity(Napi::CallbackInfo const& info); Napi::Value repulsion_strength(Napi::CallbackInfo const& info); Napi::Value negative_sample_rate(Napi::CallbackInfo const& info); Napi::Value transform_queue_size(Napi::CallbackInfo const& info); Napi::Value a(Napi::CallbackInfo const& info); Napi::Value b(Napi::CallbackInfo const& info); Napi::Value initial_alpha(Napi::CallbackInfo const& info); Napi::Value init(Napi::CallbackInfo const& info); Napi::Value target_n_neighbors(Napi::CallbackInfo const& info); Napi::Value target_weight(Napi::CallbackInfo const& info); Napi::Value target_metric(Napi::CallbackInfo const& info); Napi::Value verbosity(Napi::CallbackInfo const& info); Napi::Value random_state(Napi::CallbackInfo const& info); }; } // namespace nv
38.336449
92
0.70941
love-lena
7b80841d149060e600a5c3fd3f1b15647d9e90be
3,550
cpp
C++
Source/Projects/GoddamnCore/Source/GoddamnEngine/Core/Platform/Posix/PosixPlatformAllocator.cpp
GoddamnIndustries/GoddamnEngine
018c6582f6a2ebcba2c59693c677744434d66b20
[ "MIT" ]
4
2015-07-05T16:46:12.000Z
2021-02-04T09:32:47.000Z
Source/Projects/GoddamnCore/Source/GoddamnEngine/Core/Platform/Posix/PosixPlatformAllocator.cpp
GoddamnIndustries/GoddamnEngine
018c6582f6a2ebcba2c59693c677744434d66b20
[ "MIT" ]
null
null
null
Source/Projects/GoddamnCore/Source/GoddamnEngine/Core/Platform/Posix/PosixPlatformAllocator.cpp
GoddamnIndustries/GoddamnEngine
018c6582f6a2ebcba2c59693c677744434d66b20
[ "MIT" ]
1
2017-01-27T22:49:12.000Z
2017-01-27T22:49:12.000Z
// ========================================================================================== // Copyright (C) Goddamn Industries 2018. All Rights Reserved. // // This software or any its part is distributed under terms of Goddamn Industries End User // License Agreement. By downloading or using this software or any its part you agree with // terms of Goddamn Industries End User License Agreement. // ========================================================================================== /*! * @file * Allocator implementation. */ #include <GoddamnEngine/Core/Platform/PlatformAllocator.h> #if GD_PLATFORM_API_POSIX #include <stdlib.h> GD_NAMESPACE_BEGIN // **~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~** //! Memory allocator on Posix platforms. // **~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~** class GD_PLATFORM_KERNEL PosixPlatformAllocator final : public IPlatformAllocator { private: // ------------------------------------------------------------------------------------------ // Memory allocation. // ------------------------------------------------------------------------------------------ /*! * Allocates a memory block of the specified size. * * @param allocationPointer Allocated memory pointer. * @param allocationSizeBytes Size of memory block to allocate in bytes. * * @returns True if operation succeeded. */ GDINT virtual bool MemoryAllocate(Handle& allocationPointer, SizeTp const allocationSizeBytes) override final { if (allocationSizeBytes == 0) { allocationPointer = nullptr; return true; } allocationPointer = malloc(allocationSizeBytes); return allocationPointer != nullptr; } /*! * Allocates an aligned memory block of the specified size. * * @param allocationPointer Allocated memory pointer. * @param allocationAlignment Memory alignment. * @param allocationSizeBytes Size of memory block to allocate in bytes. * * @returns True if operation succeeded. */ GDINT virtual bool MemoryAllocateAligned(Handle& allocationPointer, SizeTp const allocationSizeBytes, SizeTp const allocationAlignment) override final { if (allocationSizeBytes == 0) { allocationPointer = nullptr; return true; } return posix_memalign(&allocationPointer, allocationAlignment, allocationSizeBytes) == 0; } // ------------------------------------------------------------------------------------------ // Memory deallocation. // ------------------------------------------------------------------------------------------ /*! * Deallocates the specified memory block. * Memory should be allocated with @c MemoryAllocate function. * * @param allocationPointer Allocated memory pointer. * @returns True if operation succeeded. */ GDINT virtual bool MemoryFree(Handle const allocationPointer) override final { free(allocationPointer); return true; } /*! * Deallocates the specified aligned memory block. * Memory should be allocated with @c MemoryAllocateAligned function. * * @param allocationPointer Allocated memory pointer. * @returns True if operation succeeded. */ GDINT virtual bool MemoryFreeAligned(Handle const allocationPointer) override final { free(allocationPointer); return true; } }; // class PosixPlatformAllocator GD_IMPLEMENT_SINGLETON(IPlatformAllocator, PosixPlatformAllocator); GD_NAMESPACE_END #endif // if GD_PLATFORM_API_POSIX
33.809524
152
0.581972
GoddamnIndustries
7b8311270285f799b8c9171660ce54b57b4e6c06
7,425
cpp
C++
plugin/com.blackberry.pim.calendar/src/blackberry10/native/account_folder_mgr.cpp
timwindsor/cordova-blackberry-plugins
a3e9e7d22f54d464647e60ef3ec574b324a5972e
[ "Apache-2.0" ]
5
2015-03-04T00:17:54.000Z
2019-06-27T13:36:05.000Z
plugin/com.blackberry.pim.calendar/src/blackberry10/native/account_folder_mgr.cpp
timwindsor/cordova-blackberry-plugins
a3e9e7d22f54d464647e60ef3ec574b324a5972e
[ "Apache-2.0" ]
6
2015-02-09T21:33:52.000Z
2017-06-02T16:19:26.000Z
plugin/com.blackberry.pim.calendar/src/blackberry10/native/account_folder_mgr.cpp
timwindsor/cordova-blackberry-plugins
a3e9e7d22f54d464647e60ef3ec574b324a5972e
[ "Apache-2.0" ]
10
2015-01-27T22:58:19.000Z
2019-02-15T19:07:01.000Z
/* * Copyright 2012 Research In Motion Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <webworks_utils.hpp> #include <QList> #include <sstream> #include <string> #include <utility> #include <map> #include "account_folder_mgr.hpp" AccountFolderManager::AccountFolderManager(ServiceProvider* provider) : m_pProvider(provider) { } bbpimAccount::Account AccountFolderManager::GetAccount(bbpim::AccountId accountId, bool fresh) { if (fresh || m_accountsMap.find(accountId) == m_accountsMap.end()) { fetchAccounts(); } AccountMap::const_iterator found = m_accountsMap.find(accountId); if (found != m_accountsMap.end()) { return found->second; } else { return bbpimAccount::Account(); // return invalid account if not found } } QList<bbpimAccount::Account> AccountFolderManager::GetAccounts(bool fresh) { if (fresh || m_accountsMap.empty()) { fetchAccounts(); } QList<bbpimAccount::Account> list; for (AccountMap::const_iterator i = m_accountsMap.begin(); i != m_accountsMap.end(); i++) { list.append(i->second); } return list; } bbpimAccount::Account AccountFolderManager::GetDefaultAccount(bool fresh) { if (fresh || !m_defaultAccount.isValid()) { fetchDefaultAccount(); } return m_defaultAccount; } bbpim::CalendarFolder AccountFolderManager::GetDefaultFolder(bool fresh) { if (fresh || !m_defaultFolder.isValid()) { fetchDefaultFolder(); } return m_defaultFolder; } bool AccountFolderManager::IsDefaultFolder(const bbpim::CalendarFolder& folder, bool fresh) { bbpim::CalendarFolder defaultFolder = GetDefaultFolder(fresh); return (folder.accountId() == defaultFolder.accountId() && folder.id() == defaultFolder.id()); } bbpim::CalendarFolder AccountFolderManager::GetFolder(bbpim::AccountId accountId, bbpim::FolderId folderId, bool fresh) { std::string key = GetFolderKey(accountId, folderId); if (fresh || m_foldersMap.find(key) == m_foldersMap.end()) { fetchFolders(); } FolderMap::const_iterator found = m_foldersMap.find(key); if (found != m_foldersMap.end()) { return found->second; } else { return bbpim::CalendarFolder(); // return invalid folder if not found } } QList<bbpim::CalendarFolder> AccountFolderManager::GetFolders(bool fresh) { if (fresh || m_foldersMap.empty()) { fetchFolders(); } QList<bbpim::CalendarFolder> list; for (FolderMap::const_iterator i = m_foldersMap.begin(); i != m_foldersMap.end(); i++) { list.append(i->second); } return list; } QList<bbpim::CalendarFolder> AccountFolderManager::GetFoldersForAccount(bbpim::AccountId accountId, bool fresh) { QList<bbpim::CalendarFolder> folders = GetFolders(fresh); QList<bbpim::CalendarFolder> result; for (QList<bbpim::CalendarFolder>::const_iterator i = folders.constBegin(); i != folders.constEnd(); i++) { bbpim::CalendarFolder folder = *i; if (folder.accountId() == accountId) { result.append(folder); } } return result; } Json::Value AccountFolderManager::GetAccountJson(const bbpimAccount::Account& account, bool fresh) { Json::Value val; val["id"] = webworks::Utils::intToStr(account.id()); val["name"] = account.displayName().toStdString(); val["enterprise"] = account.isEnterprise(); Json::Value foldersVal; QList<bbpim::CalendarFolder> folders = GetFoldersForAccount(account.id(), fresh); for (QList<bbpim::CalendarFolder>::const_iterator i = folders.constBegin(); i != folders.constEnd(); i++) { bbpim::CalendarFolder folder = *i; foldersVal.append(GetFolderJson(folder, false, false)); } val["folders"] = foldersVal; return val; } Json::Value AccountFolderManager::GetFolderJson(const bbpim::CalendarFolder& folder, bool skipDefaultCheck, bool fresh) { Json::Value val; val["id"] = webworks::Utils::intToStr(folder.id()); val["accountId"] = webworks::Utils::intToStr(folder.accountId()); val["name"] = folder.name().toStdString(); val["readonly"] = folder.isReadOnly(); val["ownerEmail"] = folder.ownerEmail().toStdString(); val["type"] = folder.type(); val["color"] = QString("%1").arg(folder.color(), 6, 16, QChar('0')).toUpper().toStdString(); val["visible"] = folder.isVisible(); val["default"] = skipDefaultCheck ? true : IsDefaultFolder(folder, fresh); val["enterprise"] = GetAccount(folder.accountId(), false).isEnterprise() == 1 ? true : false; return val; } void AccountFolderManager::fetchAccounts() { if (mutex_lock() == 0) { m_accountsMap.clear(); QList<bbpimAccount::Account> accounts = getAccountService()->accounts(bbpimAccount::Service::Calendars); for (QList<bbpimAccount::Account>::const_iterator i = accounts.constBegin(); i != accounts.constEnd(); i++) { bbpimAccount::Account account = *i; m_accountsMap.insert(std::pair<bbpim::AccountId, bbpimAccount::Account>(account.id(), account)); } mutex_unlock(); } } void AccountFolderManager::fetchFolders() { if (mutex_lock() == 0) { m_foldersMap.clear(); QList<bbpim::CalendarFolder> folders = getCalendarService()->folders(); for (QList<bbpim::CalendarFolder>::const_iterator i = folders.constBegin(); i != folders.constEnd(); i++) { bbpim::CalendarFolder folder = *i; std::string key = GetFolderKey(folder.accountId(), folder.id()); m_foldersMap.insert(std::pair<std::string, bbpim::CalendarFolder>(key, folder)); } mutex_unlock(); } } void AccountFolderManager::fetchDefaultAccount() { if (mutex_lock() == 0) { m_defaultAccount = getAccountService()->defaultAccount(bbpimAccount::Service::Calendars); mutex_unlock(); } } void AccountFolderManager::fetchDefaultFolder() { bbpim::AccountId accountId = GetDefaultAccount().id(); if (mutex_lock() == 0) { bbpim::FolderId folderId = bbpim::FolderId(getAccountService()->getDefault(bb::pim::account::Service::Calendars)); mutex_unlock(); std::string key = GetFolderKey(accountId, folderId); if (m_foldersMap.find(key) == m_foldersMap.end()) { fetchFolders(); } m_defaultFolder = m_foldersMap[key]; } } std::string AccountFolderManager::GetFolderKey(const bbpim::AccountId accountId, const bbpim::FolderId folderId) { std::string str(webworks::Utils::intToStr(accountId)); str += '-'; str += webworks::Utils::intToStr(folderId); return str; } bbpim::CalendarService* AccountFolderManager::getCalendarService() { return m_pProvider->GetCalendarService(); } bbpimAccount::AccountService* AccountFolderManager::getAccountService() { return m_pProvider->GetAccountService(); }
31.197479
122
0.677037
timwindsor
7b8a3842b48d53f72e2558800c73c066eb45cca2
537
hpp
C++
LPI/aula18/include/Conta.hpp
dayvisonmsilva/LPI
0e3186e03b0ed438795f513dd968911c6845f5e4
[ "Apache-2.0" ]
null
null
null
LPI/aula18/include/Conta.hpp
dayvisonmsilva/LPI
0e3186e03b0ed438795f513dd968911c6845f5e4
[ "Apache-2.0" ]
null
null
null
LPI/aula18/include/Conta.hpp
dayvisonmsilva/LPI
0e3186e03b0ed438795f513dd968911c6845f5e4
[ "Apache-2.0" ]
null
null
null
#ifndef CONTA_HPP #define CONTA_HPP #include <iostream> #include <string> #include "ClientePF.hpp" #include "Agencia.hpp" class Conta { public: int numero; double saldo; ClientePF titular; Agencia agencia; static int quantidadeContas; Conta(int numero, double saldo, ClientePF titular, Agencia agencia); Conta(); ~Conta(); void saca(double valor); void deposita(double valor); void transfere(double valor, Conta &c); }; #endif // !CONTA_HPP
20.653846
76
0.625698
dayvisonmsilva
7b8fd6a2445848a584066049efd9f87e2c5ab6f9
7,597
cpp
C++
es-core/src/guis/GuiTextEditPopupKeyboard.cpp
tlanks/esbusyness
41ed9e6b552585476c81f2f89b9e3d539c54d4ab
[ "Apache-2.0", "MIT" ]
10
2016-08-08T17:50:18.000Z
2019-03-08T02:54:13.000Z
es-core/src/guis/GuiTextEditPopupKeyboard.cpp
tlanks/esbusyness
41ed9e6b552585476c81f2f89b9e3d539c54d4ab
[ "Apache-2.0", "MIT" ]
7
2016-08-10T03:07:30.000Z
2018-10-10T15:24:40.000Z
es-core/src/guis/GuiTextEditPopupKeyboard.cpp
tlanks/esbusyness
41ed9e6b552585476c81f2f89b9e3d539c54d4ab
[ "Apache-2.0", "MIT" ]
16
2016-08-09T02:11:02.000Z
2019-09-24T10:17:56.000Z
#include "guis/GuiTextEditPopupKeyboard.h" #include "components/MenuComponent.h" #include "Log.h" #include <locale> using namespace Eigen; GuiTextEditPopupKeyboard::GuiTextEditPopupKeyboard(Window* window, const std::string& title, const std::string& initValue, const std::function<void(const std::string&)>& okCallback, bool multiLine, const char* acceptBtnText) : GuiComponent(window), mBackground(window, ":/frame.png"), mGrid(window, Vector2i(1, 7)), mMultiLine(multiLine) { addChild(&mBackground); addChild(&mGrid); mTitle = std::make_shared<TextComponent>(mWindow, strToUpper(title), Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER); mKeyboardGrid = std::make_shared<ComponentGrid>(mWindow, Vector2i(10, 5)); mText = std::make_shared<TextEditComponent>(mWindow); mText->setValue(initValue); if(!multiLine) mText->setCursor(initValue.size()); // Header mGrid.setEntry(mTitle, Vector2i(0, 0), false, true); // Text edit add mGrid.setEntry(mText, Vector2i(0, 1), true, false, Vector2i(1, 1), GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM); // Keyboard // Case for if multiline is enabled, then don't create the keyboard. if (!mMultiLine) { // Locale for shifting upper/lower case std::locale loc; // Digit Row & Special Chara. for (int k = 0; k < 10; k++) { // Create string for button display name. std::string strName = ""; strName += numRow[k]; strName += " "; strName += numRowUp[k]; // Init button and store in Vector digitButtons.push_back(std::make_shared<ButtonComponent> (mWindow, strName, numRow[k], [this, okCallback, k, loc] { okCallback(mText->getValue()); mText->startEditing(); if (mShift) mText->textInput(numRowUp[k]); else mText->textInput(numRow[k]); mText->stopEditing(); })); // Send just created button into mGrid mKeyboardGrid->setEntry(digitButtons[k], Vector2i(k, 0), true, false); } // Top row for (int k = 0; k < 10; k++) { kButtons.push_back(std::make_shared<ButtonComponent> (mWindow, topRowUp[k], topRowUp[k], [this, okCallback, k, loc] { okCallback(mText->getValue()); mText->startEditing(); if (mShift) mText->textInput(topRowUp[k]); else mText->textInput(topRow[k]); mText->stopEditing(); })); // Send just created button into mGrid mKeyboardGrid->setEntry(kButtons[k], Vector2i(k, 1), true, false); } // Home Row for (int k = 0; k < 10; k++) { hButtons.push_back(std::make_shared<ButtonComponent> (mWindow, homeRowUp[k], homeRowUp[k], [this, okCallback, k] { okCallback(mText->getValue()); mText->startEditing(); if (mShift) mText->textInput(homeRowUp[k]); else mText->textInput(homeRow[k]); mText->stopEditing(); })); // Send just created button into mGrid mKeyboardGrid->setEntry(hButtons[k], Vector2i(k, 2), true, false); } // Special case for shift key bButtons.push_back(std::make_shared<ButtonComponent>(mWindow, "SHIFT", "SHIFTS FOR UPPER,LOWER, AND SPECIAL", [this, okCallback] { okCallback(mText->getValue()); if (mShift) mShift = false; else mShift = true; shiftKeys(); })); // Bottom row [Z - M] for (int k = 0; k < 7; k++) { bButtons.push_back(std::make_shared<ButtonComponent> (mWindow, bottomRowUp[k], bottomRowUp[k], [this, okCallback, k, loc] { okCallback(mText->getValue()); mText->startEditing(); if (mShift) mText->textInput(bottomRowUp[k]); else mText->textInput(bottomRow[k]); mText->stopEditing(); })); } // Add in the last two manualy because they're special chara [,< and .>] for (int k = 7; k < 9; k++) { bButtons.push_back(std::make_shared<ButtonComponent>(mWindow, bottomRow[7], bottomRow[7], [this, okCallback, k] { okCallback(mText->getValue()); mText->startEditing(); if (mShift) mText->textInput(bottomRowUp[k]); else mText->textInput(bottomRow[k]); mText->stopEditing(); })); } // Do a sererate for loop because shift key makes it weird for (int k = 0; k < 10; k++) { mKeyboardGrid->setEntry(bButtons[k], Vector2i(k, 3), true, false); } // END KEYBOARD IF } // Accept/Cancel buttons buttons.push_back(std::make_shared<ButtonComponent>(mWindow, acceptBtnText, acceptBtnText, [this, okCallback] { okCallback(mText->getValue()); delete this; })); buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "CANCEL", "discard changes", [this] { delete this; })); // Add a/c buttons mKeyboardGrid->setEntry(buttons[0], Vector2i(3, 4), true, false); mKeyboardGrid->setEntry(buttons[1], Vector2i(6, 4), true, false); mGrid.setEntry(mKeyboardGrid, Vector2i(0, 2), true, true, Vector2i(2, 5)); // Determine size from text size float textHeight = mText->getFont()->getHeight(); if (multiLine) textHeight *= 6; mText->setSize(0, textHeight); // If multiline, set all diminsions back to default, else draw size for keyboard. if (mMultiLine) { setSize(Renderer::getScreenWidth() * 0.5f, mTitle->getFont()->getHeight() + textHeight + mKeyboardGrid->getSize().y() + 40); setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2); } else { // Set size based on ScreenHieght * .08f by the amount of keyboard rows there are. setSize(Renderer::getScreenWidth() * 0.75f, mTitle->getFont()->getHeight() + textHeight + 40 + (Renderer::getScreenHeight() * 0.085f) * 5); setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2); } } void GuiTextEditPopupKeyboard::onSizeChanged() { mBackground.fitTo(mSize, Eigen::Vector3f::Zero(), Eigen::Vector2f(-32, -32)); mText->setSize(mSize.x() - 40, mText->getSize().y()); // update grid mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / mSize.y()); mGrid.setRowHeightPerc(2, mKeyboardGrid->getSize().y() / mSize.y()); mGrid.setSize(mSize); } bool GuiTextEditPopupKeyboard::input(InputConfig* config, Input input) { if (GuiComponent::input(config, input)) return true; // pressing back when not text editing closes us if (config->isMappedTo("b", input) && input.value) { delete this; return true; } // For deleting a chara (Left Top Button) if (config->isMappedTo("lefttop", input) && input.value) { mText->startEditing(); mText->textInput("\b"); mText->stopEditing(); } // For Adding a space (Right Top Button) if (config->isMappedTo("righttop", input) && input.value) { mText->startEditing(); mText->textInput(" "); } // For Shifting (X) if (config->isMappedTo("x", input) && input.value) { if (mShift) mShift = false; else mShift = true; shiftKeys(); } return false; } void GuiTextEditPopupKeyboard::update(int deltatime) { } // Shifts the keys when user hits the shift button. void GuiTextEditPopupKeyboard::shiftKeys() { if (mShift) { // FOR SHIFTING UP // Change Shift button color bButtons[0]->setColorShift(0xEBFD00AA); // Change Special chara hButtons[9]->setText(":", ":"); bButtons[8]->setText("<", "<"); bButtons[9]->setText(">", ">"); } else { // UNSHIFTING // Remove button color bButtons[0]->removeColorShift(); // Change Special chara hButtons[9]->setText(";", ";"); bButtons[8]->setText(",", ","); bButtons[9]->setText(".", "."); } } std::vector<HelpPrompt> GuiTextEditPopupKeyboard::getHelpPrompts() { std::vector<HelpPrompt> prompts = mGrid.getHelpPrompts(); prompts.push_back(HelpPrompt("x", "SHIFT")); prompts.push_back(HelpPrompt("b", "back")); prompts.push_back(HelpPrompt("r", "SPACE")); prompts.push_back(HelpPrompt("l", "DELETE")); return prompts; }
31.008163
161
0.673029
tlanks
7b9277cc62bf704d88aeec6b268dfec84e64bc88
1,471
cpp
C++
TOPCODER/TC510/1000.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
TOPCODER/TC510/1000.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
TOPCODER/TC510/1000.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <bitset> #include <cstring> #define ALL(x) (x).begin(),x.end() #define CLEAR(v, x) memset(v, x, sizeof(v)) #define CLEAR0(v) memset(v, 0, sizeof(v)) #define REP(i,n) for(int i = 0; i<n; i++) #define REPP(i,a,n) for(int i = a; i<n; i++) #define REPD(i,n) for(int i = n-1; i>-1; i--) using namespace std; class TheLuckyBasesDivTwo { public: long long ANS; unsigned long long N; unsigned long long row[100]; unsigned long long aval(int col, unsigned long long base){ unsigned long long ans = 0ULL; unsigned long long b = 1ULL; REP(j, col){ ans += row[j]*b; b *= base; if(base <= row[j]) return 0ULL; if(ans > N) return 1000000000000000ULL; } return ans; } void bt(int col){ if(col > 0){ //cout << " ROW EH "; REP(i, col) cout << row[i] << " "; cout << "\nANS EH " << ANS << endl; if(found(col)){ ANS++; } if(col == 18) return; } row[col] = 4ULL; bt(col+1); row[col] = 7ULL; bt(col+1); } bool found(int col){ unsigned long long hi = N+2, num, lo = 1, mid, res = 0ULL; while(hi-lo > 1){ mid = (hi+lo)/2; num = aval(col, mid); if(num == N){ res = mid; break; } else if(num < N){ lo = mid; } else{ hi = mid; } } return (res != 0ULL); } long long find(long long n) { N = (unsigned long long) n; if(n == 7LL || n == 4LL) return -1LL; ANS = 0LL; bt(0); return ANS; } };
19.613333
95
0.561523
henviso
7b93bd41a69723a90eb3aac380418d5ee34f46c4
1,576
cpp
C++
aws-cpp-sdk-migrationhubstrategy/source/model/ApplicationComponentSummary.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-migrationhubstrategy/source/model/ApplicationComponentSummary.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-migrationhubstrategy/source/model/ApplicationComponentSummary.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/migrationhubstrategy/model/ApplicationComponentSummary.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MigrationHubStrategyRecommendations { namespace Model { ApplicationComponentSummary::ApplicationComponentSummary() : m_appType(AppType::NOT_SET), m_appTypeHasBeenSet(false), m_count(0), m_countHasBeenSet(false) { } ApplicationComponentSummary::ApplicationComponentSummary(JsonView jsonValue) : m_appType(AppType::NOT_SET), m_appTypeHasBeenSet(false), m_count(0), m_countHasBeenSet(false) { *this = jsonValue; } ApplicationComponentSummary& ApplicationComponentSummary::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("appType")) { m_appType = AppTypeMapper::GetAppTypeForName(jsonValue.GetString("appType")); m_appTypeHasBeenSet = true; } if(jsonValue.ValueExists("count")) { m_count = jsonValue.GetInteger("count"); m_countHasBeenSet = true; } return *this; } JsonValue ApplicationComponentSummary::Jsonize() const { JsonValue payload; if(m_appTypeHasBeenSet) { payload.WithString("appType", AppTypeMapper::GetNameForAppType(m_appType)); } if(m_countHasBeenSet) { payload.WithInteger("count", m_count); } return payload; } } // namespace Model } // namespace MigrationHubStrategyRecommendations } // namespace Aws
20.205128
88
0.74302
perfectrecall
7ba6643acb5627d77daf358dd1a493aaaaafb894
4,830
cpp
C++
osquery/tables/applications/windows/carbon_black.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
23
2016-12-07T15:26:58.000Z
2019-07-18T21:39:06.000Z
osquery/tables/applications/windows/carbon_black.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
4
2016-12-07T06:18:36.000Z
2017-01-19T19:39:38.000Z
osquery/tables/applications/windows/carbon_black.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
5
2017-06-26T11:54:37.000Z
2019-02-18T01:23:02.000Z
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <osquery/core.h> #include <osquery/filesystem.h> #include <osquery/tables.h> #include "osquery/filesystem/fileops.h" #include "osquery/tables/system/windows/registry.h" namespace fs = boost::filesystem; namespace osquery { namespace tables { // Carbon Black registry path #define kCbRegLoc "SOFTWARE\\CarbonBlack\\config" void getQueue(Row& r) { fs::path cbDir = getSystemRoot(); cbDir /= "CarbonBlack"; std::vector<std::string> files_list; if (!listFilesInDirectory(cbDir, files_list, true)) { return; } uintmax_t binary_queue_size = 0; uintmax_t event_queue_size = 0; // Go through each file for (const auto& kfile : files_list) { fs::path file(kfile); if (file.filename() == "data" || file.filename() == "info.txt") { binary_queue_size += fs::file_size(kfile); } if (file.filename() == "active-event.log" || boost::starts_with(file.filename().c_str(), "eventlog_")) { event_queue_size += fs::file_size(kfile); } } r["binary_queue"] = INTEGER(binary_queue_size); r["event_queue"] = INTEGER(event_queue_size); } void getSettings(Row& r) { QueryData results; queryKey("HKEY_LOCAL_MACHINE", kCbRegLoc, results); for (const auto& kKey : results) { if (kKey.at("name") == "CollectCrossProcess") { r["collect_cross_processes"] = SQL_TEXT(kKey.at("data")); } if (kKey.at("name") == "CollectStoreFiles") { r["collect_store_files"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectDataFileWrites") { r["collect_data_file_writes"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectEmetEvents") { r["collect_emet_events"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectFileMods") { r["collect_file_mods"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectModuleInfo") { r["collect_module_info"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectModuleLoads") { r["collect_module_loads"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectNetConns") { r["collect_net_conns"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectProcesses") { r["collect_processes"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectProcessUserContext") { r["collect_process_user_context"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectRegMods") { r["collect_reg_mods"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectSensorOperations") { r["collect_sensor_operations"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "CollectStoreFiles") { r["collect_store_files"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "ConfigName") { std::string config_name = kKey.at("data"); boost::replace_all(config_name, "%20", " "); r["config_name"] = SQL_TEXT(config_name); } if (kKey.at("name") == "LogFileDiskQuotaMb") { r["log_file_disk_quota_mb"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "LogFileDiskQuotaPercentage") { r["log_file_disk_quota_percentage"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "ProtectionDisabled") { r["protection_disabled"] = INTEGER(kKey.at("data")); } if (kKey.at("name") == "SensorIpAddr") { r["sensor_ip_addr"] = SQL_TEXT(kKey.at("data")); } if (kKey.at("name") == "SensorBackendServer") { std::string server = kKey.at("data"); boost::replace_all(server, "%3A", ":"); r["sensor_backend_server"] = SQL_TEXT(server); } if (kKey.at("name") == "SensorId") { // from a string to an int, to hex, a portion of the hex, then to int uint64_t int_sensor_id = strtoll(kKey.at("data").c_str(), nullptr, 10); std::stringstream hex_sensor_id; hex_sensor_id << std::hex << int_sensor_id; unsigned int sensor_id; std::string small_hex_sensor_id = hex_sensor_id.str().substr(11, 16); std::stringstream converter(small_hex_sensor_id); converter >> std::hex >> sensor_id; r["sensor_id"] = INTEGER(sensor_id); } } } QueryData genCarbonBlackInfo(QueryContext& context) { Row r; QueryData results; getSettings(r); getQueue(r); results.push_back(r); return results; } } }
33.082192
79
0.634783
justintime32
7ba68af90a71564dac5092dc6c23b9a199d4f5ed
16,631
cpp
C++
level_zero/tools/source/tracing/tracing_device_imp.cpp
8tab/compute-runtime
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
[ "MIT" ]
1
2020-04-17T05:46:04.000Z
2020-04-17T05:46:04.000Z
level_zero/tools/source/tracing/tracing_device_imp.cpp
8tab/compute-runtime
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
[ "MIT" ]
null
null
null
level_zero/tools/source/tracing/tracing_device_imp.cpp
8tab/compute-runtime
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
[ "MIT" ]
1
2020-05-25T21:57:51.000Z
2020-05-25T21:57:51.000Z
/* * Copyright (C) 2019-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/tools/source/tracing/tracing_imp.h" __zedllexport ze_result_t __zecall zeDeviceGet_Tracing(ze_driver_handle_t hDriver, uint32_t *pCount, ze_device_handle_t *phDevices) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGet, hDriver, pCount, phDevices); ze_device_get_params_t tracerParams; tracerParams.phDriver = &hDriver; tracerParams.ppCount = &pCount; tracerParams.pphDevices = &phDevices; L0::APITracerCallbackDataImp<ze_pfnDeviceGetCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetCb_t, Device, pfnGetCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGet, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDriver, *tracerParams.ppCount, *tracerParams.pphDevices); } __zedllexport ze_result_t __zecall zeDeviceGetProperties_Tracing(ze_device_handle_t hDevice, ze_device_properties_t *pDeviceProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetProperties, hDevice, pDeviceProperties); ze_device_get_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppDeviceProperties = &pDeviceProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetPropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetPropertiesCb_t, Device, pfnGetPropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppDeviceProperties); } __zedllexport ze_result_t __zecall zeDeviceGetComputeProperties_Tracing(ze_device_handle_t hDevice, ze_device_compute_properties_t *pComputeProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetComputeProperties, hDevice, pComputeProperties); ze_device_get_compute_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppComputeProperties = &pComputeProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetComputePropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetComputePropertiesCb_t, Device, pfnGetComputePropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetComputeProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppComputeProperties); } __zedllexport ze_result_t __zecall zeDeviceGetMemoryProperties_Tracing(ze_device_handle_t hDevice, uint32_t *pCount, ze_device_memory_properties_t *pMemProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetMemoryProperties, hDevice, pCount, pMemProperties); ze_device_get_memory_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppCount = &pCount; tracerParams.ppMemProperties = &pMemProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetMemoryPropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetMemoryPropertiesCb_t, Device, pfnGetMemoryPropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetMemoryProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppCount, *tracerParams.ppMemProperties); } __zedllexport ze_result_t __zecall zeDeviceGetCacheProperties_Tracing(ze_device_handle_t hDevice, ze_device_cache_properties_t *pCacheProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetCacheProperties, hDevice, pCacheProperties); ze_device_get_cache_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppCacheProperties = &pCacheProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetCachePropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetCachePropertiesCb_t, Device, pfnGetCachePropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetCacheProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppCacheProperties); } __zedllexport ze_result_t __zecall zeDeviceGetImageProperties_Tracing(ze_device_handle_t hDevice, ze_device_image_properties_t *pImageProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetImageProperties, hDevice, pImageProperties); ze_device_get_image_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppImageProperties = &pImageProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetImagePropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetImagePropertiesCb_t, Device, pfnGetImagePropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetImageProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppImageProperties); } __zedllexport ze_result_t __zecall zeDeviceGetSubDevices_Tracing(ze_device_handle_t hDevice, uint32_t *pCount, ze_device_handle_t *phSubdevices) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetSubDevices, hDevice, pCount, phSubdevices); ze_device_get_sub_devices_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppCount = &pCount; tracerParams.pphSubdevices = &phSubdevices; L0::APITracerCallbackDataImp<ze_pfnDeviceGetSubDevicesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetSubDevicesCb_t, Device, pfnGetSubDevicesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetSubDevices, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppCount, *tracerParams.pphSubdevices); } __zedllexport ze_result_t __zecall zeDeviceGetP2PProperties_Tracing(ze_device_handle_t hDevice, ze_device_handle_t hPeerDevice, ze_device_p2p_properties_t *pP2PProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetP2PProperties, hDevice, hPeerDevice, pP2PProperties); ze_device_get_p2_p_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.phPeerDevice = &hPeerDevice; tracerParams.ppP2PProperties = &pP2PProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetP2PPropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetP2PPropertiesCb_t, Device, pfnGetP2PPropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetP2PProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.phPeerDevice, *tracerParams.ppP2PProperties); } __zedllexport ze_result_t __zecall zeDeviceCanAccessPeer_Tracing(ze_device_handle_t hDevice, ze_device_handle_t hPeerDevice, ze_bool_t *value) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnCanAccessPeer, hDevice, hPeerDevice, value); ze_device_can_access_peer_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.phPeerDevice = &hPeerDevice; tracerParams.pvalue = &value; L0::APITracerCallbackDataImp<ze_pfnDeviceCanAccessPeerCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceCanAccessPeerCb_t, Device, pfnCanAccessPeerCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnCanAccessPeer, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.phPeerDevice, *tracerParams.pvalue); } __zedllexport ze_result_t __zecall zeKernelSetIntermediateCacheConfig_Tracing(ze_kernel_handle_t hKernel, ze_cache_config_t cacheConfig) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Kernel.pfnSetIntermediateCacheConfig, hKernel, cacheConfig); ze_kernel_set_intermediate_cache_config_params_t tracerParams; tracerParams.phKernel = &hKernel; tracerParams.pCacheConfig = &cacheConfig; L0::APITracerCallbackDataImp<ze_pfnKernelSetIntermediateCacheConfigCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnKernelSetIntermediateCacheConfigCb_t, Kernel, pfnSetIntermediateCacheConfigCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Kernel.pfnSetIntermediateCacheConfig, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phKernel, *tracerParams.pCacheConfig); } __zedllexport ze_result_t __zecall zeDeviceSetLastLevelCacheConfig_Tracing(ze_device_handle_t hDevice, ze_cache_config_t cacheConfig) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnSetLastLevelCacheConfig, hDevice, cacheConfig); ze_device_set_last_level_cache_config_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.pCacheConfig = &cacheConfig; L0::APITracerCallbackDataImp<ze_pfnDeviceSetLastLevelCacheConfigCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceSetLastLevelCacheConfigCb_t, Device, pfnSetLastLevelCacheConfigCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnSetLastLevelCacheConfig, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.pCacheConfig); } __zedllexport ze_result_t __zecall zeDeviceGetKernelProperties_Tracing(ze_device_handle_t hDevice, ze_device_kernel_properties_t *pKernelProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetKernelProperties, hDevice, pKernelProperties); ze_device_get_kernel_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppKernelProperties = &pKernelProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetKernelPropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetKernelPropertiesCb_t, Device, pfnGetKernelPropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetKernelProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppKernelProperties); } __zedllexport ze_result_t __zecall zeDeviceGetMemoryAccessProperties_Tracing(ze_device_handle_t hDevice, ze_device_memory_access_properties_t *pMemAccessProperties) { ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.Device.pfnGetMemoryAccessProperties, hDevice, pMemAccessProperties); ze_device_get_memory_access_properties_params_t tracerParams; tracerParams.phDevice = &hDevice; tracerParams.ppMemAccessProperties = &pMemAccessProperties; L0::APITracerCallbackDataImp<ze_pfnDeviceGetMemoryAccessPropertiesCb_t> api_callbackData; ZE_GEN_PER_API_CALLBACK_STATE(api_callbackData, ze_pfnDeviceGetMemoryAccessPropertiesCb_t, Device, pfnGetMemoryAccessPropertiesCb); return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.Device.pfnGetMemoryAccessProperties, &tracerParams, api_callbackData.apiOrdinal, api_callbackData.prologCallbacks, api_callbackData.epilogCallbacks, *tracerParams.phDevice, *tracerParams.ppMemAccessProperties); }
46.716292
137
0.622031
8tab
7bb105878ce9b128cf4fefd20d1c11f0556c07f9
714
cpp
C++
codeforces/489/C.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
5
2020-06-30T12:44:25.000Z
2021-07-14T06:35:57.000Z
codeforces/489/C.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
null
null
null
codeforces/489/C.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int m,s,tmp; cin>>m>>s; tmp=s; vector<int> arr(m,0); vector<int> vec(m,0); if(s==0 && m==1){ cout<<0<<" "<<0; return 0; } if(s==0){ cout<<-1<<" "<<-1; return 0; } if(s>9*m){ cout<<-1<<" "<<-1; return 0; } for(int i=0;i<m;i++){ if(tmp>=9){ tmp-=9; arr[i]=9; } else if(tmp<=0){ break; } else{ arr[i]=tmp; break; } } vec[0]=1; tmp=s; tmp-=1; for(int i=m-1;i>=0;i--){ if(tmp>=9){ tmp-=9; vec[i]=9; } else if(tmp<=0){ break; } else{ vec[i]+=tmp; break; } } for(int i=0;i<m;i++){ cout<<vec[i]; } cout<<" "; for(int i=0;i<m;i++){ cout<<arr[i]; } return 0; }
12.101695
25
0.442577
amitdu6ey
7bb3195b212022e8e90b9bfc9b0b3a0d2b3f8bb3
624
cpp
C++
Chapter-6-Functions/Other/using-static-variable-within-for-loop-scope.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
3
2019-10-28T01:12:46.000Z
2021-10-16T09:16:31.000Z
Chapter-6-Functions/using-static-variable-within-for-loop-scope.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
null
null
null
Chapter-6-Functions/using-static-variable-within-for-loop-scope.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
4
2020-04-10T17:22:17.000Z
2021-11-04T14:34:00.000Z
//*********************************************************** // This program uses a static local variable. // // By: Jesus Hilario Hernandez // Last Updated: October 22nd, 2016 //*********************************************************** #include <iostream> using namespace std; void showVar(); // Function prototype int main() { for (int count = 0; count < 10; count ++) { showVar(); } return 0; } //*********************************** // Definition of function showVar * //*********************************** void showVar() { static int var = 10; cout << var << endl; var++; }
19.5
61
0.408654
jesushilarioh
7bbc81d28f8e03c65e9b28f95f32f724bd694b37
3,023
cpp
C++
watorword/redis_entry.cpp
WatorVapor/wai.native.wator
e048df159e2952c143f8832264b20da20dcd88fa
[ "MIT" ]
null
null
null
watorword/redis_entry.cpp
WatorVapor/wai.native.wator
e048df159e2952c143f8832264b20da20dcd88fa
[ "MIT" ]
null
null
null
watorword/redis_entry.cpp
WatorVapor/wai.native.wator
e048df159e2952c143f8832264b20da20dcd88fa
[ "MIT" ]
null
null
null
#include "redis_entry.hpp" #include "log.hpp" const string strConstTrainChannelName("wai.train"); const string strConstTrainResponseChannelName("wai.train.response"); #include<memory> #include <chrono> #include <thread> #include <atomic> void redis_sub_main(void) { for(;;) { try{ boost::asio::io_service ioService; /* boost::asio::ip::tcp::resolver resolver(ioService); boost::asio::ip::tcp::resolver::query query("127.0.0.1", "6379"); boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query); */ boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 6379); DUMP_VAR(endpoint); RedisEntryClient client(ioService); redisclient::RedisAsyncClient subscriber(ioService); subscriber.connect(endpoint, [&](boost::system::error_code ec){ if(ec) { DUMP_VAR(ec); } else { DUMP_VAR(ec); subscriber.subscribe(strConstTrainChannelName,std::bind(&RedisEntryClient::onMessageAPI, &client, std::placeholders::_1)); } }); ioService.run(); } catch(std::exception &e) { DUMP_VAR(e.what()); } std::this_thread::sleep_for(10s); } } static std::weak_ptr<redisclient::RedisAsyncClient> gPublishRef; //static std::atomic_bool gPublishConnected(false); void redis_pub_main(void) { for(;;) { try { boost::asio::io_service ioService; /* boost::asio::ip::tcp::resolver resolver(ioService); boost::asio::ip::tcp::resolver::query query("127.0.0.1", "6379"); boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query); */ boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 6379);; DUMP_VAR(endpoint); RedisEntryClient client(ioService); auto publish = std::make_shared<redisclient::RedisAsyncClient>(ioService); DUMP_VAR(publish); gPublishRef = publish; publish->connect(endpoint, [&](boost::system::error_code ec) { if(ec) { DUMP_VAR(ec); } else { DUMP_VAR(ec); //gPublishConnected = true; } }); DUMP_VAR(publish); ioService.run(); } catch(std::exception &e) { DUMP_VAR(e.what()); } //gPublishConnected = false; std::this_thread::sleep_for(10s); } } #include <nlohmann/json.hpp> using json = nlohmann::json; string processText(const string &text); void RedisEntryClient::onMessageAPI(const std::vector<char> &buf) { string msg(buf.begin(),buf.end()); DUMP_VAR(msg); auto result = processText(msg); TRACE_VAR(result); if(result.empty()) { auto emptyObj = R"({"finnish": true})"_json; result = emptyObj.dump(); } auto publish = gPublishRef.lock(); DUMP_VAR2(publish,result); if(publish &&publish->isConnected()) { publish->publish(strConstTrainResponseChannelName, result,[&](const redisclient::RedisValue &) { }); } else { DUMP_VAR(publish); } }
29.637255
132
0.634469
WatorVapor
dcf081f30c3214d93be8518c130bdec2c69d37c2
369
hh
C++
Mu2eInterfaces/inc/ConditionsEntity.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
Mu2eInterfaces/inc/ConditionsEntity.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
Mu2eInterfaces/inc/ConditionsEntity.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
#ifndef ConditionsService_ConditionsEntity_hh #define ConditionsService_ConditionsEntity_hh // // A base class for objects held by the conditions data system. // // // Original author Rob Kutschke // #include <string> namespace mu2e { class ConditionsEntity { public: virtual ~ConditionsEntity(); }; } #endif /* ConditionsService_ConditionsEntity_hh */
16.043478
63
0.753388
lborrel
dcf109a17a49b4b6bc0ff5da68abb564bf92c62a
1,106
cpp
C++
parameteroptimization/src/Common.cpp
BioroboticsLab/parameteroptimization
47d094bb76ba0f46a9048b306c93f03a1fc48e2b
[ "MIT" ]
1
2018-09-17T17:28:10.000Z
2018-09-17T17:28:10.000Z
parameteroptimization/src/Common.cpp
BioroboticsLab/parameteroptimization
47d094bb76ba0f46a9048b306c93f03a1fc48e2b
[ "MIT" ]
4
2015-09-11T16:40:45.000Z
2017-01-30T12:23:08.000Z
parameteroptimization/src/Common.cpp
BioroboticsLab/parameteroptimization
47d094bb76ba0f46a9048b306c93f03a1fc48e2b
[ "MIT" ]
null
null
null
#include "Common.h" namespace opt { bool operator<(const opt::OptimizationResult &a, const opt::OptimizationResult &b) { return a.fscore > b.fscore; } double getFScore(const double recall, const double precision, const double beta) { return ((1 + std::pow(beta, 2)) * ((precision * recall) / (std::pow(beta, 2) * precision + recall))); } OptimizationResult getOptimizationResult(const size_t numGroundTruth, const size_t numTruePositives, const size_t numFalsePositives, const double beta) { const double recall = numGroundTruth ? (static_cast<double>(numTruePositives) / static_cast<double>(numGroundTruth)) : 0.; const double precision = (numTruePositives + numFalsePositives) ? (static_cast<double>(numTruePositives) / static_cast<double>(numTruePositives + numFalsePositives)) : 0.; const double fscore = getFScore(recall, precision, beta); if (std::isnan(fscore)) { OptimizationResult result{0, 0, 0}; return result; } else { OptimizationResult result{fscore, recall, precision}; return result; } } }
31.6
103
0.692586
BioroboticsLab
dcf5136bf9ef47d406dfa55ed10117060d1e2654
1,130
cpp
C++
src/Equations/Fluid/SPIHeatAbsorbtionTerm.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Equations/Fluid/SPIHeatAbsorbtionTerm.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Equations/Fluid/SPIHeatAbsorbtionTerm.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Implementation of the pellet ablation term (takes ablation rate provided by SPIHandler). */ #include "DREAM/Equations/Fluid/SPIHeatAbsorbtionTerm.hpp" using namespace DREAM; SPIHeatAbsorbtionTerm::SPIHeatAbsorbtionTerm( FVM::Grid* g, SPIHandler *SPI, real_t scaleFactor=1.0 ): EquationTerm(g),SPI(SPI), scaleFactor(scaleFactor){} void SPIHeatAbsorbtionTerm::Rebuild(const real_t, const real_t, FVM::UnknownQuantityHandler* ){ heatAbsorbtionRate=SPI->GetHeatAbsorbtionRate(); } bool SPIHeatAbsorbtionTerm::SetJacobianBlock(const len_t, const len_t derivId, FVM::Matrix *jac, const real_t*){ return SPI->setJacobianAdiabaticHeatAbsorbtionRate(jac, derivId, scaleFactor); } /** * Set the linear operator matrix elements corresponding * to this term. */ void SPIHeatAbsorbtionTerm::SetMatrixElements(FVM::Matrix*, real_t *rhs) { this->SetVectorElements(rhs, nullptr); } /** * Set the non-linear function vector for this term. */ void SPIHeatAbsorbtionTerm::SetVectorElements(real_t *vec, const real_t*){ for(len_t ir=0;ir<nr;ir++){ vec[ir]+=scaleFactor*heatAbsorbtionRate[ir]; } }
29.736842
112
0.751327
chalmersplasmatheory
dcf5486a88eef9e5bae14cdd119affa7fee2f17b
482
hpp
C++
Include/Uplink/core/platform.hpp
Team-AllyHyeseongKim/http-image-server4bundle-fusion-scanner
2a6c196aeb9bacd2c88a0bb6a8bbadd04afca260
[ "RSA-MD" ]
null
null
null
Include/Uplink/core/platform.hpp
Team-AllyHyeseongKim/http-image-server4bundle-fusion-scanner
2a6c196aeb9bacd2c88a0bb6a8bbadd04afca260
[ "RSA-MD" ]
null
null
null
Include/Uplink/core/platform.hpp
Team-AllyHyeseongKim/http-image-server4bundle-fusion-scanner
2a6c196aeb9bacd2c88a0bb6a8bbadd04afca260
[ "RSA-MD" ]
null
null
null
#pragma once #include "platform.h" namespace uplink { inline TCPConnection::TCPConnection () : disconnecting(false) { } inline TCPConnection::~TCPConnection () { } inline TCPConnection* TCPConnection::connect (CString host, uint16 port) { ScopedProfiledTask _(ProfilerTask_TCPConnection); return TCPConnection_connect(host, port); } inline TCPConnection* TCPConnection::create (int descriptor) { return TCPConnection_create(descriptor); } } // uplink namespace
14.606061
53
0.757261
Team-AllyHyeseongKim
0d02ac9764cf49396e551acdd93a9e3a5fbce536
12,217
hpp
C++
src/HTJ2KDecoder.hpp
chafey/openjphjs
d24644b395f00395a7c99a7208852e7157d4a8f5
[ "MIT" ]
13
2020-05-03T00:33:25.000Z
2022-02-23T01:29:14.000Z
src/HTJ2KDecoder.hpp
chafey/openjphjs
d24644b395f00395a7c99a7208852e7157d4a8f5
[ "MIT" ]
1
2021-06-05T18:40:24.000Z
2022-02-23T01:27:03.000Z
src/HTJ2KDecoder.hpp
chafey/openjphjs
d24644b395f00395a7c99a7208852e7157d4a8f5
[ "MIT" ]
2
2020-05-08T04:10:49.000Z
2021-03-22T17:53:41.000Z
// Copyright (c) Chris Hafey. // SPDX-License-Identifier: MIT #pragma once #include <exception> #include <memory> #include <limits.h> #include <ojph_arch.h> #include <ojph_file.h> #include <ojph_mem.h> #include <ojph_params.h> #include <ojph_codestream.h> #ifdef __EMSCRIPTEN__ #include <emscripten/val.h> #endif #include "FrameInfo.hpp" #include "Point.hpp" #include "Size.hpp" /// <summary> /// JavaScript API for decoding HTJ2K bistreams with OpenJPH /// </summary> class HTJ2KDecoder { public: /// <summary> /// Constructor for decoding a HTJ2K image from JavaScript. /// </summary> HTJ2KDecoder() { } #ifdef __EMSCRIPTEN__ /// <summary> /// Resizes encoded buffer and returns a TypedArray of the buffer allocated /// in WASM memory space that will hold the HTJ2K encoded bitstream. /// JavaScript code needs to copy the HTJ2K encoded bistream into the /// returned TypedArray. This copy operation is needed because WASM runs /// in a sandbox and cannot access memory managed by JavaScript. /// </summary> emscripten::val getEncodedBuffer(size_t encodedSize) { encoded_.resize(encodedSize); return emscripten::val(emscripten::typed_memory_view(encoded_.size(), encoded_.data())); } /// <summary> /// Returns a TypedArray of the buffer allocated in WASM memory space that /// holds the decoded pixel data /// </summary> emscripten::val getDecodedBuffer() { return emscripten::val(emscripten::typed_memory_view(decoded_.size(), decoded_.data())); } #else /// <summary> /// Returns the buffer to store the encoded bytes. This method is not exported /// to JavaScript, it is intended to be called by C++ code /// </summary> std::vector<uint8_t>& getEncodedBytes() { return encoded_; } /// <summary> /// Returns the buffer to store the decoded bytes. This method is not exported /// to JavaScript, it is intended to be called by C++ code /// </summary> const std::vector<uint8_t>& getDecodedBytes() const { return decoded_; } #endif /// <summary> /// Reads the header from an encoded HTJ2K bitstream. The caller must have /// copied the HTJ2K encoded bitstream into the encoded buffer before /// calling this method, see getEncodedBuffer() and getEncodedBytes() above. /// </summary> void readHeader() { ojph::codestream codestream; ojph::mem_infile mem_file; mem_file.open(encoded_.data(), encoded_.size()); readHeader_(codestream, mem_file); } /// <summary> /// Calculates the resolution for a given decomposition level based on the /// current values in FrameInfo (which is populated via readHeader() and /// decode()). level = 0 = full res, level = _numDecompositions = lowest resolution /// </summary> Size calculateSizeAtDecompositionLevel(int decompositionLevel) { Size result(frameInfo_.width, frameInfo_.height); while(decompositionLevel > 0) { result.width = ojph_div_ceil(result.width, 2); result.height = ojph_div_ceil(result.height, 2); decompositionLevel--; } return result; } /// <summary> /// Decodes the encoded HTJ2K bitstream. The caller must have copied the /// HTJ2K encoded bitstream into the encoded buffer before calling this /// method, see getEncodedBuffer() and getEncodedBytes() above. /// </summary> void decode() { ojph::codestream codestream; ojph::mem_infile mem_file; mem_file.open(encoded_.data(), encoded_.size()); readHeader_(codestream, mem_file); decode_(codestream, frameInfo_, 0); } /// <summary> /// Decodes the encoded HTJ2K bitstream to the requested decomposition level. /// The caller must have copied the HTJ2K encoded bitstream into the encoded /// buffer before calling this method, see getEncodedBuffer() and /// getEncodedBytes() above. /// </summary> void decodeSubResolution(size_t decompositionLevel) { ojph::codestream codestream; ojph::mem_infile mem_file; mem_file.open(encoded_.data(), encoded_.size()); readHeader_(codestream, mem_file); decode_(codestream, frameInfo_, decompositionLevel); } /// <summary> /// returns the FrameInfo object for the decoded image. /// </summary> const FrameInfo& getFrameInfo() const { return frameInfo_; } /// <summary> /// returns the number of wavelet decompositions. /// </summary> const size_t getNumDecompositions() const { return numDecompositions_; } /// <summary> /// returns true if the image is lossless, false if lossy /// </summary> const bool getIsReversible() const { return isReversible_; } /// <summary> /// returns progression order. // 0 = LRCP // 1 = RLCP // 2 = RPCL // 3 = PCRL // 4 = CPRL /// </summary> const size_t getProgressionOrder() const { return progressionOrder_; } /// <summary> /// returns the down sampling used for component. /// </summary> Point getDownSample(size_t component) const { return downSamples_[component]; } /// <summary> /// returns the image offset /// </summary> Point getImageOffset() const { return imageOffset_; } /// <summary> /// returns the tile size /// </summary> Size getTileSize() const { return tileSize_; } /// <summary> /// returns the tile offset /// </summary> Point getTileOffset() const { return tileOffset_; } /// <summary> /// returns the block dimensions /// </summary> Size getBlockDimensions() const { return blockDimensions_; } /// <summary> /// returns the precinct for the specified resolution decomposition level /// </summary> Size getPrecinct(size_t level) const { return precincts_[level]; } /// <summary> /// returns the number of layers /// </summary> int32_t getNumLayers() const { return numLayers_; } /// <summary> /// returns whether or not a color transform is used /// </summary> bool getIsUsingColorTransform() const { return isUsingColorTransform_; } private: void readHeader_(ojph::codestream& codestream, ojph::mem_infile& mem_file) { // NOTE - enabling resilience does not seem to have any effect at this point... codestream.enable_resilience(); codestream.read_headers(&mem_file); ojph::param_siz siz = codestream.access_siz(); frameInfo_.width = siz.get_image_extent().x - siz.get_image_offset().x; frameInfo_.height = siz.get_image_extent().y - siz.get_image_offset().y; frameInfo_.componentCount = siz.get_num_components(); frameInfo_.bitsPerSample = siz.get_bit_depth(0); frameInfo_.isSigned = siz.is_signed(0); downSamples_.resize(frameInfo_.componentCount); for(size_t i=0; i < frameInfo_.componentCount; i++) { downSamples_[i].x = siz.get_downsampling(i).x; downSamples_[i].y = siz.get_downsampling(i).y; } imageOffset_.x = siz.get_image_offset().x; imageOffset_.y = siz.get_image_offset().y; tileSize_.width = siz.get_tile_size().w; tileSize_.height = siz.get_tile_size().h; tileOffset_.x = siz.get_tile_offset().x; tileOffset_.y = siz.get_tile_offset().y; ojph::param_cod cod = codestream.access_cod(); numDecompositions_ = cod.get_num_decompositions(); isReversible_ = cod.is_reversible(); progressionOrder_ = cod.get_progression_order(); blockDimensions_.width = cod.get_block_dims().w; blockDimensions_.height = cod.get_block_dims().h; precincts_.resize(numDecompositions_); for(size_t i=0; i < numDecompositions_; i++) { precincts_[i].width = cod.get_precinct_size(i).w; precincts_[i].height = cod.get_precinct_size(i).h; } numLayers_ = cod.get_num_layers(); isUsingColorTransform_ = cod.is_using_color_transform(); } void decode_(ojph::codestream& codestream, const FrameInfo& frameInfo, size_t decompositionLevel) { // calculate the resolution at the requested decomposition level and // allocate destination buffer Size sizeAtDecompositionLevel = calculateSizeAtDecompositionLevel(decompositionLevel); int resolutionLevel = numDecompositions_ - decompositionLevel; const size_t bytesPerPixel = (frameInfo_.bitsPerSample + 8 - 1) / 8; const size_t destinationSize = sizeAtDecompositionLevel.width * sizeAtDecompositionLevel.height * frameInfo.componentCount * bytesPerPixel; decoded_.resize(destinationSize); // set the level to read to and reconstruction level to the specified decompositionLevel codestream.restrict_input_resolution(decompositionLevel, decompositionLevel); // parse it if(frameInfo.componentCount == 1) { codestream.set_planar(true); } else { if(isUsingColorTransform_) { codestream.set_planar(false); } else { // for color images without a color transform, // calling set_planar(true) invokes an optimization // https://github.com/aous72/OpenJPH/issues/34 codestream.set_planar(true); } } codestream.create(); // Extract the data line by line... // NOTE: All values must be clamped https://github.com/aous72/OpenJPH/issues/35 int comp_num; for (int y = 0; y < sizeAtDecompositionLevel.height; y++) { size_t lineStart = y * sizeAtDecompositionLevel.width * frameInfo.componentCount * bytesPerPixel; if(frameInfo.componentCount == 1) { ojph::line_buf *line = codestream.pull(comp_num); if(frameInfo.bitsPerSample <= 8) { unsigned char* pOut = (unsigned char*)&decoded_[lineStart]; for (size_t x = 0; x < sizeAtDecompositionLevel.width; x++) { int val = line->i32[x]; pOut[x] = std::max(0, std::min(val, UCHAR_MAX)); } } else { if(frameInfo.isSigned) { short* pOut = (short*)&decoded_[lineStart]; for (size_t x = 0; x < sizeAtDecompositionLevel.width; x++) { int val = line->i32[x]; pOut[x] = std::max(SHRT_MIN, std::min(val, SHRT_MAX)); } } else { unsigned short* pOut = (unsigned short*)&decoded_[lineStart] ; for (size_t x = 0; x < sizeAtDecompositionLevel.width; x++) { int val = line->i32[x]; pOut[x] = std::max(0, std::min(val, USHRT_MAX)); } } } } else { for (int c = 0; c < frameInfo.componentCount; c++) { ojph::line_buf *line = codestream.pull(comp_num); if(frameInfo.bitsPerSample <= 8) { uint8_t* pOut = &decoded_[lineStart] + c; for (size_t x = 0; x < sizeAtDecompositionLevel.width; x++) { int val = line->i32[x]; pOut[x * frameInfo.componentCount] = std::max(0, std::min(val, UCHAR_MAX)); } } else { // This should work but has not been tested yet if(frameInfo.isSigned) { short* pOut = (short*)&decoded_[lineStart] + c; for (size_t x = 0; x < sizeAtDecompositionLevel.width; x++) { int val = line->i32[x]; pOut[x * frameInfo.componentCount] = std::max(SHRT_MIN, std::min(val, SHRT_MAX)); } } else { unsigned short* pOut = (unsigned short*)&decoded_[lineStart] + c; for (size_t x = 0; x < sizeAtDecompositionLevel.width; x++) { int val = line->i32[x]; pOut[x * frameInfo.componentCount] = std::max(0, std::min(val, USHRT_MAX)); } } } } } } } std::vector<uint8_t> encoded_; std::vector<uint8_t> decoded_; FrameInfo frameInfo_; std::vector<Point> downSamples_; size_t numDecompositions_; bool isReversible_; size_t progressionOrder_; Point imageOffset_; Size tileSize_; Point tileOffset_; Size blockDimensions_; std::vector<Size> precincts_; int32_t numLayers_; bool isUsingColorTransform_; };
33.563187
145
0.641238
chafey
0d036d665e1b6943190b571435de0286aca76c99
2,211
cpp
C++
src/tool/Window.cpp
qcoumes/OpenGL_GLEW_SLD2_Template
1411e25bcebaa9117e41667202e2f18a008e427d
[ "MIT" ]
1
2021-01-12T16:58:05.000Z
2021-01-12T16:58:05.000Z
src/tool/Window.cpp
qcoumes/mastercraft
5ee36fde6eab80d18075970eff47b4a5c45143f5
[ "MIT" ]
null
null
null
src/tool/Window.cpp
qcoumes/mastercraft
5ee36fde6eab80d18075970eff47b4a5c45143f5
[ "MIT" ]
1
2020-03-23T19:17:06.000Z
2020-03-23T19:17:06.000Z
#include <iostream> #include <SDL.h> #include <tool/Window.hpp> namespace tool { Window::Window(const char *title, uint32_t flags) { if (0 != SDL_Init(SDL_INIT_VIDEO)) { throw std::runtime_error(SDL_GetError()); } this->window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP | flags ); if (this->window == nullptr) { throw std::runtime_error(SDL_GetError()); } this->context = SDL_GL_CreateContext(this->window); if (this->context == nullptr) { throw std::runtime_error(SDL_GetError()); } SDL_GL_MakeCurrent(this->window, this->context); } Window::Window(const char *title, int32_t width, int32_t height, uint32_t flags) { if (0 != SDL_Init(SDL_INIT_VIDEO)) { throw std::runtime_error(SDL_GetError()); } this->window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | flags ); if (this->window == nullptr) { throw std::runtime_error(SDL_GetError()); } this->context = SDL_GL_CreateContext(this->window); if (this->context == nullptr) { throw std::runtime_error(SDL_GetError()); } SDL_GL_MakeCurrent(this->window, this->context); } Window::~Window() { SDL_GL_DeleteContext(this->context); SDL_DestroyWindow(this->window); } void Window::refresh() { SDL_GL_SwapWindow(this->window); } SDL_Window *Window::getWindow() const { return this->window; } SDL_GLContext Window::getContext() const { return this->context; } SDL_DisplayMode Window::getDisplayMode() const { SDL_DisplayMode mode; if (SDL_GetDesktopDisplayMode(0, &mode)) { throw std::runtime_error(SDL_GetError()); } return mode; } }
26.011765
87
0.557666
qcoumes
0d0413addb282ceb567e38953e5bb993440fa91e
412
hpp
C++
core/src/api/enum_from_string.hpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
92
2016-11-13T01:28:34.000Z
2022-03-25T01:11:37.000Z
core/src/api/enum_from_string.hpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
242
2016-11-28T11:13:09.000Z
2022-03-04T13:02:53.000Z
core/src/api/enum_from_string.hpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
91
2017-06-20T10:35:28.000Z
2022-03-09T14:15:40.000Z
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from tezos_like_wallet.djinni #ifndef DJINNI_GENERATED_ENUM_FROM_STRING_HPP #define DJINNI_GENERATED_ENUM_FROM_STRING_HPP #include <string> namespace ledger { namespace core { namespace api { template <typename T> T from_string(const std::string&); } } } // namespace ledger::core::api #endif //DJINNI_GENERATED_ENUM_FROM_STRING_HPP
25.75
62
0.791262
RomanWlm
0d04ab99c836bdbe1fa000e1665b7fc6e2b00d81
2,649
hh
C++
app/demo-loop/KernelUtils.hh
amandalund/celeritas
c631594b00c040d5eb4418fa2129f88c01e29316
[ "Apache-2.0", "MIT" ]
null
null
null
app/demo-loop/KernelUtils.hh
amandalund/celeritas
c631594b00c040d5eb4418fa2129f88c01e29316
[ "Apache-2.0", "MIT" ]
null
null
null
app/demo-loop/KernelUtils.hh
amandalund/celeritas
c631594b00c040d5eb4418fa2129f88c01e29316
[ "Apache-2.0", "MIT" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// // Copyright 2021 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file KernelUtils.hh //---------------------------------------------------------------------------// #pragma once #include "base/Macros.hh" #include "geometry/GeoMaterialView.hh" #include "geometry/GeoTrackView.hh" #include "physics/base/ParticleTrackView.hh" #include "physics/base/PhysicsStepUtils.hh" using namespace celeritas; namespace demo_loop { //---------------------------------------------------------------------------// // INLINE HELPER FUNCTIONS //---------------------------------------------------------------------------// template<class Rng> inline CELER_FUNCTION void calc_step_limits(const MaterialTrackView& mat, const ParticleTrackView& particle, PhysicsTrackView& phys, SimTrackView& sim, Rng& rng); template<class Rng> inline CELER_FUNCTION void move_and_select_model(const CutoffView& cutoffs, const GeoMaterialView& geo_mat, GeoTrackView& geo, MaterialTrackView& mat, ParticleTrackView& particle, PhysicsTrackView& phys, SimTrackView& sim, Rng& rng, real_type* edep, Interaction* result); inline CELER_FUNCTION void post_process(const CutoffView& cutoffs, GeoTrackView& geo, ParticleTrackView& particle, PhysicsTrackView& phys, SimTrackView& sim, real_type* edep, const Interaction& result); //---------------------------------------------------------------------------// } // namespace demo_loop #include "KernelUtils.i.hh"
49.055556
80
0.365043
amandalund
0d092925377633b5e1cf9fe4a203337e44f40a09
9,210
cpp
C++
BasicPlatform/BasicPlatform/Intermediate/Build/Win64/UE4Editor/Inc/BasicPlatform/BasicPlatformCharacter.gen.cpp
JCharlieDev/Unreal-Projects
fd3d97fc41b45d0f826b2c096f5e377d504ae023
[ "MIT" ]
null
null
null
BasicPlatform/BasicPlatform/Intermediate/Build/Win64/UE4Editor/Inc/BasicPlatform/BasicPlatformCharacter.gen.cpp
JCharlieDev/Unreal-Projects
fd3d97fc41b45d0f826b2c096f5e377d504ae023
[ "MIT" ]
null
null
null
BasicPlatform/BasicPlatform/Intermediate/Build/Win64/UE4Editor/Inc/BasicPlatform/BasicPlatformCharacter.gen.cpp
JCharlieDev/Unreal-Projects
fd3d97fc41b45d0f826b2c096f5e377d504ae023
[ "MIT" ]
null
null
null
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "BasicPlatform/BasicPlatformCharacter.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeBasicPlatformCharacter() {} // Cross Module References BASICPLATFORM_API UClass* Z_Construct_UClass_ABasicPlatformCharacter_NoRegister(); BASICPLATFORM_API UClass* Z_Construct_UClass_ABasicPlatformCharacter(); ENGINE_API UClass* Z_Construct_UClass_ACharacter(); UPackage* Z_Construct_UPackage__Script_BasicPlatform(); ENGINE_API UClass* Z_Construct_UClass_UCameraComponent_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_USpringArmComponent_NoRegister(); // End Cross Module References void ABasicPlatformCharacter::StaticRegisterNativesABasicPlatformCharacter() { } UClass* Z_Construct_UClass_ABasicPlatformCharacter_NoRegister() { return ABasicPlatformCharacter::StaticClass(); } struct Z_Construct_UClass_ABasicPlatformCharacter_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseLookUpRate_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseLookUpRate; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseTurnRate_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseTurnRate; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FollowCamera_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_FollowCamera; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CameraBoom_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_CameraBoom; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_ABasicPlatformCharacter_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_ACharacter, (UObject* (*)())Z_Construct_UPackage__Script_BasicPlatform, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABasicPlatformCharacter_Statics::Class_MetaDataParams[] = { { "HideCategories", "Navigation" }, { "IncludePath", "BasicPlatformCharacter.h" }, { "ModuleRelativePath", "BasicPlatformCharacter.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseLookUpRate_MetaData[] = { { "Category", "Camera" }, { "Comment", "/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */" }, { "ModuleRelativePath", "BasicPlatformCharacter.h" }, { "ToolTip", "Base look up/down rate, in deg/sec. Other scaling may affect final rate." }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseLookUpRate = { "BaseLookUpRate", nullptr, (EPropertyFlags)0x0010000000020015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ABasicPlatformCharacter, BaseLookUpRate), METADATA_PARAMS(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseLookUpRate_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseLookUpRate_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseTurnRate_MetaData[] = { { "Category", "Camera" }, { "Comment", "/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */" }, { "ModuleRelativePath", "BasicPlatformCharacter.h" }, { "ToolTip", "Base turn rate, in deg/sec. Other scaling may affect final turn rate." }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseTurnRate = { "BaseTurnRate", nullptr, (EPropertyFlags)0x0010000000020015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ABasicPlatformCharacter, BaseTurnRate), METADATA_PARAMS(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseTurnRate_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseTurnRate_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_FollowCamera_MetaData[] = { { "AllowPrivateAccess", "true" }, { "Category", "Camera" }, { "Comment", "/** Follow camera */" }, { "EditInline", "true" }, { "ModuleRelativePath", "BasicPlatformCharacter.h" }, { "ToolTip", "Follow camera" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_FollowCamera = { "FollowCamera", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ABasicPlatformCharacter, FollowCamera), Z_Construct_UClass_UCameraComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_FollowCamera_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_FollowCamera_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_CameraBoom_MetaData[] = { { "AllowPrivateAccess", "true" }, { "Category", "Camera" }, { "Comment", "/** Camera boom positioning the camera behind the character */" }, { "EditInline", "true" }, { "ModuleRelativePath", "BasicPlatformCharacter.h" }, { "ToolTip", "Camera boom positioning the camera behind the character" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_CameraBoom = { "CameraBoom", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ABasicPlatformCharacter, CameraBoom), Z_Construct_UClass_USpringArmComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_CameraBoom_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_CameraBoom_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_ABasicPlatformCharacter_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseLookUpRate, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_BaseTurnRate, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_FollowCamera, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABasicPlatformCharacter_Statics::NewProp_CameraBoom, }; const FCppClassTypeInfoStatic Z_Construct_UClass_ABasicPlatformCharacter_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<ABasicPlatformCharacter>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ABasicPlatformCharacter_Statics::ClassParams = { &ABasicPlatformCharacter::StaticClass, "Game", &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_ABasicPlatformCharacter_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_ABasicPlatformCharacter_Statics::PropPointers), 0, 0x008000A4u, METADATA_PARAMS(Z_Construct_UClass_ABasicPlatformCharacter_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_ABasicPlatformCharacter_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_ABasicPlatformCharacter() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ABasicPlatformCharacter_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(ABasicPlatformCharacter, 497423843); template<> BASICPLATFORM_API UClass* StaticClass<ABasicPlatformCharacter>() { return ABasicPlatformCharacter::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_ABasicPlatformCharacter(Z_Construct_UClass_ABasicPlatformCharacter, &ABasicPlatformCharacter::StaticClass, TEXT("/Script/BasicPlatform"), TEXT("ABasicPlatformCharacter"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(ABasicPlatformCharacter); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
60.993377
579
0.821716
JCharlieDev
0d0e9e7b61c5275d8b190ac4fd624deea19c2cff
763
hpp
C++
include/tudocomp/Decompressor.hpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-22T11:29:02.000Z
2020-09-22T11:29:02.000Z
include/tudocomp/Decompressor.hpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/tudocomp/Decompressor.hpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-29T08:57:13.000Z
2020-09-29T08:57:13.000Z
#pragma once #include <tudocomp/io.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { /// \brief Base for decompressors. class Decompressor : public Algorithm { public: static inline constexpr TypeDesc type_desc() { return TypeDesc("decompressor"); } virtual ~Decompressor() = default; Decompressor(Decompressor const&) = default; Decompressor(Decompressor&&) = default; Decompressor& operator=(Decompressor const&) = default; Decompressor& operator=(Decompressor&&) = default; using Algorithm::Algorithm; /// \brief Decompress the given input to the given output. /// /// \param input The input. /// \param output The output. virtual void decompress(Input& input, Output& output) = 0; }; }
23.84375
62
0.682831
421408
0d12be007c5aa5f76c2b558a1bb3ca39338549ec
733
hpp
C++
onychophora/Worm.hpp
renato-grottesi/arduboy
7bf33ef64a18b0ae783819e2a4e498b5ab442bdd
[ "MIT" ]
6
2019-11-18T02:23:15.000Z
2021-05-16T19:24:15.000Z
onychophora/Worm.hpp
renato-grottesi/arduboy
7bf33ef64a18b0ae783819e2a4e498b5ab442bdd
[ "MIT" ]
39
2019-08-28T21:53:40.000Z
2020-03-08T17:54:18.000Z
onychophora/Worm.hpp
renato-grottesi/arduboy
7bf33ef64a18b0ae783819e2a4e498b5ab442bdd
[ "MIT" ]
2
2019-08-28T18:57:00.000Z
2021-12-10T20:11:18.000Z
#pragma once #include "Utility.hpp" /* Class that implements the worm. */ class Worm { public: Worm(Arduboy2& arduboy) : arduboy(arduboy) {} bool moveTo(Cell newHead, bool enlarge, bool shorten); void render(); void addPiece(Cell c); void reset(Cell c); Cell getHead() { return cells[0]; } bool fall(uint16_t solids[8]); bool intersects(uint16_t solids[8]); private: Arduboy2& arduboy; /* The body can be at most 16 cells long. First cell is the head. */ Cell cells[16] = {}; uint8_t count = 0; static const uint8_t R = 0; static const uint8_t U = 8; static const uint8_t L = 16; static const uint8_t D = 24; uint8_t extrRotation(uint8_t f, uint8_t l); uint8_t joinRotation(uint8_t j); };
22.90625
70
0.678035
renato-grottesi
0d13ee9fa0ba1e1be0d19b66637ef55d8a764013
3,520
hpp
C++
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/mbedtls/crypto/hmac.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
10
2021-03-29T13:52:06.000Z
2022-03-10T02:24:25.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/mbedtls/crypto/hmac.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
1
2019-07-19T02:40:32.000Z
2019-07-19T02:40:32.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/mbedtls/crypto/hmac.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
7
2018-07-11T10:37:02.000Z
2019-08-03T10:34:08.000Z
// OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License Version 3 // as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program in the COPYING file. // If not, see <http://www.gnu.org/licenses/>. // Wrap the mbed TLS HMAC API defined in <mbedtls/md.h> so // that it can be used as part of the crypto layer of the OpenVPN core. #ifndef OPENVPN_MBEDTLS_CRYPTO_HMAC_H #define OPENVPN_MBEDTLS_CRYPTO_HMAC_H #include <string> #include <openvpn/common/size.hpp> #include <openvpn/common/exception.hpp> #include <openvpn/mbedtls/crypto/digest.hpp> namespace openvpn { namespace MbedTLSCrypto { class HMACContext { HMACContext(const HMACContext&) = delete; HMACContext& operator=(const HMACContext&) = delete; public: OPENVPN_SIMPLE_EXCEPTION(mbedtls_hmac_uninitialized); OPENVPN_EXCEPTION(mbedtls_hmac_error); enum { MAX_HMAC_SIZE = MBEDTLS_MD_MAX_SIZE }; HMACContext() : initialized(false) { } HMACContext(const CryptoAlgs::Type digest, const unsigned char *key, const size_t key_size) : initialized(false) { init(digest, key, key_size); } ~HMACContext() { erase() ; } void init(const CryptoAlgs::Type digest, const unsigned char *key, const size_t key_size) { erase(); ctx.md_ctx = nullptr; mbedtls_md_init(&ctx); if (mbedtls_md_setup(&ctx, DigestContext::digest_type(digest), 1) < 0) throw mbedtls_hmac_error("mbedtls_md_setup"); if (mbedtls_md_hmac_starts(&ctx, key, key_size) < 0) throw mbedtls_hmac_error("mbedtls_md_hmac_starts"); initialized = true; } void reset() { check_initialized(); if (mbedtls_md_hmac_reset(&ctx) < 0) throw mbedtls_hmac_error("mbedtls_md_hmac_reset"); } void update(const unsigned char *in, const size_t size) { check_initialized(); if (mbedtls_md_hmac_update(&ctx, in, size) < 0) throw mbedtls_hmac_error("mbedtls_md_hmac_update"); } size_t final(unsigned char *out) { check_initialized(); if (mbedtls_md_hmac_finish(&ctx, out) < 0) throw mbedtls_hmac_error("mbedtls_md_hmac_finish"); return size_(); } size_t size() const { check_initialized(); return size_(); } bool is_initialized() const { return initialized; } private: void erase() { if (initialized) { mbedtls_md_free(&ctx); initialized = false; } } size_t size_() const { return mbedtls_md_get_size(ctx.md_info); } void check_initialized() const { #ifdef OPENVPN_ENABLE_ASSERT if (!initialized) throw mbedtls_hmac_uninitialized(); #endif } bool initialized; mbedtls_md_context_t ctx; }; } } #endif
26.074074
97
0.67358
TiagoPedroByterev
0d15a537a0f08194d2c3c9ed6e3ccfcde7482dc5
5,051
cpp
C++
source/utils/network/tests/network_serializer_test.cpp
gummikana/poro
70162aca06ca5a1d4f92b8d01728e1764e4c6873
[ "Zlib" ]
3
2015-02-09T15:31:32.000Z
2022-03-06T20:49:48.000Z
source/utils/network/tests/network_serializer_test.cpp
gummikana/poro
70162aca06ca5a1d4f92b8d01728e1764e4c6873
[ "Zlib" ]
null
null
null
source/utils/network/tests/network_serializer_test.cpp
gummikana/poro
70162aca06ca5a1d4f92b8d01728e1764e4c6873
[ "Zlib" ]
2
2019-09-26T22:00:16.000Z
2019-10-03T22:02:43.000Z
/*************************************************************************** * * Copyright (c) 2003 - 2011 Petri Purho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ***************************************************************************/ #include "../network_serializer.h" #include "../network_libs.h" #include <fstream> #include <algorithm> #ifdef PORO_TESTER_ENABLED namespace network_utils { namespace test { //----------------------------------------------------------------------------- int NetworkSerializerTest() { { bool test_bool = true; uint8 test_uint8 = 56; uint32 test_uint32 = 0x12345678; float32 test_float32 = 12465.4356f; types::ustring test_ustring; test_ustring += (uint8)'n'; test_ustring += (uint8)'o'; test_ustring += (uint8)'o'; test_ustring += (uint8)'b'; CSerialSaver saver; saver.IO( test_bool ); saver.IO( test_uint8 ); saver.IO( test_uint32 ); saver.IO( test_float32 ); saver.IO( test_ustring ); types::ustring buffer = saver.GetData(); // std::cout << buffer.size() << std::endl; bool load_bool = true; uint8 load_uint8 = 56; uint32 load_uint32 = 0x12345678; float32 load_float32 = 12465.4356f; types::ustring load_ustring; CSerialLoader loader( buffer ); loader.IO( load_bool ); loader.IO( load_uint8 ); loader.IO( load_uint32 ); loader.IO( load_float32 ); loader.IO( load_ustring ); test_assert( test_bool == load_bool ); test_assert( test_uint8 == load_uint8 ); test_assert( test_uint32 == load_uint32 ); test_float( test_float32 == load_float32 ); test_assert( test_ustring == load_ustring ); } // this works fine { int test_int32 = 1; CSerialSaver saver; saver.IO( test_int32 ); types::ustring buffer = saver.GetData(); int load_int32 = -1; CSerialLoader loader( buffer ); loader.IO( load_int32 ); test_assert( test_int32 == load_int32 ); } // char buffer test { int test_int32 = 1; CSerialSaver saver; saver.IO( test_int32 ); types::ustring buffer = saver.GetData(); char char_buffer[1024]; std::copy(buffer.begin(), buffer.end(), char_buffer); char_buffer[buffer.size()] = '\0'; // don't forget the terminating 0 types::ustring buffer_from_char_shit; buffer_from_char_shit.resize( buffer.size() ); std::copy( char_buffer, char_buffer + buffer.size(), buffer_from_char_shit.begin() ); int load_int32 = -1; CSerialLoader loader( buffer_from_char_shit ); loader.IO( load_int32 ); test_assert( test_int32 == load_int32 ); } return 0; } template <typename T> void swap_endian(T& pX) { // should static assert that T is a POD char& raw = reinterpret_cast<char&>(pX); std::reverse(&raw, &raw + sizeof(T)); } inline void endian_swap(unsigned short& x) { x = (x>>8) | (x<<8); } unsigned char littleShort( unsigned char l ) { unsigned char b1, b2; b1 = l & 64; b2 = ( l >> 6 ) & 64; return ( b1 << 6 ) + b2; } int NetworkSerializerEndianTest() { { uint8 test_uint8 = 64; CSerialSaver saver; saver.IO( test_uint8 ); types::ustring buffer = saver.GetData(); test_assert( buffer.size() == 1 ); test_assert( buffer[0] == '@' ); } { uint32 test_uint32 = 64; CSerialSaver saver; saver.IO( test_uint32 ); types::ustring buffer = saver.GetData(); test_assert( buffer.size() == 4 ); test_assert( buffer[3] == '@' ); test_assert( buffer[3] == 0x40 ); std::fstream file_output; file_output.open( "temp/endian_out.txt" , std::ios::out ); file_output << buffer; file_output.close(); // file read test std::fstream file_input; file_input.open( "temp/endian_cmpr.txt" , std::ios::in ); test_assert( file_input.good() ); types::ustring line_in; std::getline( file_input, line_in ); file_input.close(); test_assert( line_in.size() == buffer.size() ); for( std::size_t i = 0; i < line_in.size(); ++i ) test_assert( line_in[i] == buffer[i] ); } return 0; } //----------------------------------------------------------------------------- TEST_REGISTER( NetworkSerializerTest ); // TEST_REGISTER( NetworkSerializerEndianTest ); } // end o namespace test } // end o namespace network_utils #endif // PORO_TESTER_ENABLED
23.602804
87
0.636112
gummikana
0d15de21ac87dc73c3fbecb63ee0bdc0b8031b54
12,222
cpp
C++
src/cpu/sc61860/ops.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
51
2015-11-22T14:53:28.000Z
2021-12-14T07:17:42.000Z
src/cpu/sc61860/ops.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
13
2015-08-25T03:53:08.000Z
2022-03-30T18:02:35.000Z
src/cpu/sc61860/ops.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
40
2015-08-25T05:09:21.000Z
2022-02-08T05:02:30.000Z
INLINE UINT8 READ_OP(void) { return cpu_readop(sc61860.pc++); } INLINE UINT8 READ_OP_ARG(void) { return cpu_readop_arg(sc61860.pc++); } INLINE UINT16 READ_OP_ARG_WORD(void) { UINT16 t=cpu_readop(sc61860.pc++)<<8; t|=cpu_readop(sc61860.pc++); return t; } INLINE UINT8 READ_BYTE(UINT16 adr) { return cpu_readmem16(adr); } INLINE void WRITE_BYTE(UINT16 a,UINT8 v) { cpu_writemem16(a,v); } #define PUSH(v) sc61860.ram[--sc61860.r]=v #define POP() sc61860.ram[sc61860.r++] INLINE void sc61860_load_imm(int r, UINT8 v) { sc61860.ram[r]=v; } INLINE void sc61860_load(void) { sc61860.ram[A]=sc61860.ram[sc61860.p]; } INLINE void sc61860_load_imm_p(UINT8 v) { sc61860.p=v; } INLINE void sc61860_load_imm_q(UINT8 v) { sc61860.q=v; } INLINE void sc61860_load_r(void) { sc61860.r=sc61860.ram[A]; } INLINE void sc61860_load_ext(int r) { sc61860.ram[r]=READ_BYTE(sc61860.dp); } INLINE void sc61860_load_dp(void) { sc61860.dp=READ_OP_ARG_WORD(); } INLINE void sc61860_load_dl(void) { sc61860.dp=(sc61860.dp&~0xff)|READ_OP_ARG(); } INLINE void sc61860_store_p(void) { sc61860.ram[A]=sc61860.p; } INLINE void sc61860_store_q(void) { sc61860.ram[A]=sc61860.q; } INLINE void sc61860_store_r(void) { sc61860.ram[A]=sc61860.r; } INLINE void sc61860_store_ext(int r) { WRITE_BYTE(sc61860.dp, sc61860.ram[r]); } INLINE void sc61860_exam(int a, int b) { UINT8 t=sc61860.ram[a]; sc61860.ram[a]=sc61860.ram[b]; sc61860.ram[b]=t; } INLINE void sc61860_test(int reg, UINT8 value) { sc61860.zero=(sc61860.ram[reg]&value)==0; } INLINE void sc61860_test_ext(void) { sc61860.zero=(READ_BYTE(sc61860.dp)&READ_OP_ARG())==0; } INLINE void sc61860_and(int reg, UINT8 value) { sc61860.zero=(sc61860.ram[reg]&=value)==0; } INLINE void sc61860_and_ext(void) { UINT8 t=READ_BYTE(sc61860.dp)&READ_OP_ARG(); sc61860.zero=t==0; WRITE_BYTE(sc61860.dp,t); } INLINE void sc61860_or(int reg, UINT8 value) { sc61860.zero=(sc61860.ram[reg]|=value)==0; } INLINE void sc61860_or_ext(void) { UINT8 t=READ_BYTE(sc61860.dp)|READ_OP_ARG(); sc61860.zero=t==0; WRITE_BYTE(sc61860.dp,t); } INLINE void sc61860_rotate_right(void) { int t=sc61860.ram[A]; if (sc61860.carry) t|=0x100; sc61860.carry=t&1; sc61860.ram[A]=t>>1; } INLINE void sc61860_rotate_left(void) { int t=sc61860.ram[A]<<1; if (sc61860.carry) t|=1; sc61860.carry=t&0x100; sc61860.ram[A]=t; } INLINE void sc61860_swap(void) { int t=sc61860.ram[A]; sc61860.ram[A]=(t<<4)|((t>>4)&0xf); } INLINE void sc61860_inc(int reg) { sc61860.q=reg; sc61860.ram[reg]++; sc61860.zero=sc61860.carry=sc61860.ram[reg]==0; } INLINE void sc61860_inc_p(void) { sc61860.p++; } INLINE void sc61860_dec(int reg) { sc61860.q=reg; sc61860.ram[reg]--; sc61860.zero=sc61860.ram[reg]==0; sc61860.carry=sc61860.ram[reg]==0xff; } INLINE void sc61860_dec_p(void) { sc61860.p--; } INLINE void sc61860_add(int reg, UINT8 value) { int t=sc61860.ram[reg]+value; sc61860.zero=(sc61860.ram[reg]=t)==0; sc61860.carry=t>=0x100; } INLINE void sc61860_add_carry(void) { int t=sc61860.ram[sc61860.p]+sc61860.ram[A]; if (sc61860.carry) t++; sc61860.zero=(sc61860.ram[sc61860.p]=t)==0; sc61860.carry=t>=0x100; } INLINE void sc61860_add_word(void) { int t=sc61860.ram[sc61860.p]+sc61860.ram[A],t2; sc61860.ram[sc61860.p]=t; t2=sc61860.ram[sc61860.p+1]+sc61860.ram[B]; if (t>=0x100) t2++; sc61860.ram[sc61860.p+1]=t2; sc61860.zero=t2==0; sc61860.carry=t2>=0x100; } INLINE void sc61860_sub(int reg, UINT8 value) { int t=sc61860.ram[reg]-value; sc61860.zero=(sc61860.ram[reg]=t)==0; sc61860.carry=t<0; } INLINE void sc61860_sub_carry(void) { int t=sc61860.ram[sc61860.p]-sc61860.ram[A]; if (sc61860.carry) t--; sc61860.zero=(sc61860.ram[sc61860.p]=t)==0; sc61860.carry=t<0; } INLINE void sc61860_sub_word(void) { int t=sc61860.ram[sc61860.p]-sc61860.ram[A],t2; sc61860.ram[sc61860.p]=t; t2=sc61860.ram[sc61860.p+1]-sc61860.ram[B]; if (t<0) t2--; sc61860.ram[sc61860.p+1]=t2; sc61860.zero=t2==0; sc61860.carry=t2<0; } INLINE void sc61860_cmp(int reg, UINT8 value) { int t=sc61860.ram[reg]-value; sc61860.zero=t==0; sc61860.carry=t<0; } INLINE void sc61860_pop(void) { sc61860.ram[A]=POP(); } INLINE void sc61860_push(void) { PUSH(sc61860.ram[A]); } INLINE void sc61860_prepare_table_call(void) { int adr; sc61860.ram[H]=READ_OP(); adr=READ_OP_ARG_WORD(); PUSH(adr>>8); PUSH(adr&0xff); } INLINE void sc61860_execute_table_call(void) { int i, v, adr; for (i=0; i<sc61860.ram[H]; i++) { v=READ_OP(); adr=READ_OP_ARG_WORD(); sc61860.zero=v==sc61860.ram[A]; if (sc61860.zero) { sc61860.pc=adr; change_pc(sc61860.pc); return; } } sc61860.pc=READ_OP_ARG_WORD(); change_pc(sc61860.pc); } INLINE void sc61860_call(UINT16 adr) { PUSH(sc61860.pc>>8); PUSH(sc61860.pc&0xff); sc61860.pc=adr; change_pc(sc61860.pc); } INLINE void sc61860_return(void) { UINT16 t=POP(); t|=POP()<<8; sc61860.pc=t; change_pc(sc61860.pc); } INLINE void sc61860_jump(bool yes) { UINT16 adr=READ_OP_ARG_WORD(); if (yes) { sc61860.pc=adr; change_pc(sc61860.pc); } } INLINE void sc61860_jump_rel_plus(bool yes) { UINT16 adr=sc61860.pc; adr+=READ_OP_ARG(); if (yes) { sc61860.pc=adr; change_pc(sc61860.pc); sc61860_icount-=3; } } INLINE void sc61860_jump_rel_minus(bool yes) { UINT16 adr=sc61860.pc; adr-=READ_OP_ARG(); if (yes) { sc61860.pc=adr; change_pc(sc61860.pc); sc61860_icount-=3; } } INLINE void sc61860_loop(void) { UINT16 adr=sc61860.pc; adr-=READ_OP_ARG(); sc61860.ram[sc61860.r]--; sc61860.zero=sc61860.ram[sc61860.r]==0; sc61860.carry=sc61860.ram[sc61860.r]==0xff; if (!sc61860.carry) { sc61860.pc=adr; adr=POP(); change_pc(sc61860.pc); sc61860_icount-=3; } } INLINE void sc61860_leave(void) { sc61860.ram[sc61860.r]=0; } INLINE void sc61860_wait(void) { int t=READ_OP(); sc61860_icount-=t; sc61860_icount-=t; sc61860_icount-=3; } INLINE void sc61860_set_carry(void) { sc61860.carry=1; sc61860.zero=1; } INLINE void sc61860_reset_carry(void) { sc61860.carry=0; sc61860.zero=1; } INLINE void sc61860_out_a(void) { sc61860.q=IA; if (sc61860.config&&sc61860.config->outa) sc61860.config->outa(sc61860.ram[IA]); } INLINE void sc61860_out_b(void) { sc61860.q=IB; if (sc61860.config&&sc61860.config->outb) sc61860.config->outb(sc61860.ram[IB]); } INLINE void sc61860_out_f(void) { sc61860.q=F0; /*sc61860.ram[F0]; */ } /* c0 display on c1 counter reset c2 cpu halt c3 computer off c4 beeper frequency (1 4khz, 0 2khz), or (c5=0) membran pos1/pos2 c5 beeper on c6 beeper steuerung*/ INLINE void sc61860_out_c(void) { sc61860.q=C; if (sc61860.config&&sc61860.config->outc) sc61860.config->outc(sc61860.ram[C]); } INLINE void sc61860_in_a(void) { int data=0; if (sc61860.config&&sc61860.config->ina) data=sc61860.config->ina(); sc61860.ram[A]=data; sc61860.zero=data==0; } INLINE void sc61860_in_b(void) { int data=0; if (sc61860.config&&sc61860.config->inb) data=sc61860.config->inb(); sc61860.ram[A]=data; sc61860.zero=data==0; } /* 0 systemclock 512ms 1 systemclock 2ms 2 ? 3 brk/on key 4 ? 5 ? 6 reset 7 cassette input */ INLINE void sc61860_test_special(void) { int t=0; if (sc61860.timer.t512ms) t|=1; if (sc61860.timer.t2ms) t|=2; if (sc61860.config&&sc61860.config->brk&&sc61860.config->brk()) t|=8; if (sc61860.config&&sc61860.config->reset&&sc61860.config->reset()) t|=0x40; sc61860.zero=(t&READ_OP())==0; } /************************************************************************************ "string" operations ***********************************************************************************/ INLINE void sc61860_add_bcd_a(void) { int i,t, v=sc61860.ram[A]; for (i=0; i<=sc61860.ram[I]; i++) { t=(sc61860.ram[sc61860.p]&0xf)+(v&0xf); if ((t&0xf)>9) t=t+0x10-10; t+=(sc61860.ram[sc61860.p]&0xf0)+(v&0xf0); if ((t&0xf0)>=0xa0) { t=t+0x100-0xa0; } sc61860.ram[sc61860.p--]=t; sc61860.zero=(t&0xff)==0; sc61860.carry=t>=0x100; v=(sc61860.carry)?1:0; sc61860_icount-=3; } } INLINE void sc61860_add_bcd(void) { int i,t,v=0; for (i=0; i<=sc61860.ram[I]; i++) { t=(sc61860.ram[sc61860.p]&0xf)+(sc61860.ram[sc61860.q]&0xf)+v; if (t>=10) t=t+0x10-10; t+=(sc61860.ram[sc61860.p]&0xf0)+(sc61860.ram[sc61860.q--]&0xf0); if ((t&0xf0)>=0xa0) { t=t+0x100-0xa0; } sc61860.ram[sc61860.p--]=t; sc61860.zero=(t&0xff)==0; sc61860.carry=t>=0x100; v=(sc61860.carry)?1:0; sc61860_icount-=3; } } INLINE void sc61860_sub_bcd_a(void) { int i,t, v=sc61860.ram[A]; for (i=0; i<=sc61860.ram[I]; i++) { t=(sc61860.ram[sc61860.p]&0xf)-(v&0xf); if (t<0) t=t-0x10+10; t+=(sc61860.ram[sc61860.p]&0xf0)-(v&0xf0); if (t<0) { t=t-0x100+0xa0; } sc61860.ram[sc61860.p--]=t; sc61860.zero=(t&0xff)==0; sc61860.carry=t<0; v=(sc61860.carry)?1:0; sc61860_icount-=3; } } INLINE void sc61860_sub_bcd(void) { int i,t,v=0; for (i=0; i<=sc61860.ram[I]; i++) { t=(sc61860.ram[sc61860.p]&0xf)-(sc61860.ram[sc61860.q]&0xf)-v; if (t<0) t=t-0x10+10; t+=(sc61860.ram[sc61860.p]&0xf0)-(sc61860.ram[sc61860.q--]&0xf0); if (t<0) { t=t-0x100+0xa0; } sc61860.ram[sc61860.p--]=t; sc61860.zero=(t&0xff)==0; sc61860.carry=t<0; v=(sc61860.carry)?1:0; sc61860_icount-=3; } } /* side effect p-i-1 -> p correct! */ INLINE void sc61860_shift_left_nibble(void) { int i,t=0; for (i=0; i<=sc61860.ram[I]; i++) { t|=sc61860.ram[sc61860.p]<<4; sc61860.ram[sc61860.p--]=t; t>>=8; sc61860_icount--; } } /* side effect p+i+1 -> p correct! */ INLINE void sc61860_shift_right_nibble(void) { int i,t=0; for (i=0; i<=sc61860.ram[I]; i++) { t|=sc61860.ram[sc61860.p]; sc61860.ram[sc61860.p++]=t>>4; t=(t<<8)&0xf00; sc61860_icount--; } } INLINE void sc61860_inc_load_dp(int reg) { if (++sc61860.ram[reg]==0) sc61860.ram[reg+1]++; sc61860.dp=sc61860.ram[reg]|(sc61860.ram[reg+1]<<8); } INLINE void sc61860_dec_load_dp(int reg) { if (--sc61860.ram[reg]==0xff) sc61860.ram[reg+1]--; sc61860.dp=sc61860.ram[reg]|(sc61860.ram[reg+1]<<8); } INLINE void sc61860_inc_load_dp_load(void) { if (++sc61860.ram[XL]==0) sc61860.ram[XH]++; sc61860.dp=sc61860.ram[XL]|(sc61860.ram[XH]<<8); sc61860.ram[A]=READ_BYTE(sc61860.dp); } INLINE void sc61860_dec_load_dp_load(void) { if (--sc61860.ram[XL]==0xff) sc61860.ram[XH]--; sc61860.dp=sc61860.ram[XL]|(sc61860.ram[XH]<<8); sc61860.ram[A]=READ_BYTE(sc61860.dp); } INLINE void sc61860_inc_load_dp_store(void) { if (++sc61860.ram[YL]==0) sc61860.ram[YH]++; sc61860.dp=sc61860.ram[YL]|(sc61860.ram[YH]<<8); WRITE_BYTE(sc61860.dp,sc61860.ram[A]); } INLINE void sc61860_dec_load_dp_store(void) { if (--sc61860.ram[YL]==0xff) sc61860.ram[YH]--; sc61860.dp=sc61860.ram[YL]|(sc61860.ram[YH]<<8); WRITE_BYTE(sc61860.dp,sc61860.ram[A]); } INLINE void sc61860_fill(void) { int i; for (i=0;i<=sc61860.ram[I];i++) { sc61860.ram[sc61860.p++]=sc61860.ram[A]; /* could be overwritten? */ sc61860_icount--; } } INLINE void sc61860_fill_ext(void) { int i; for (i=0;i<=sc61860.ram[I];i++) { WRITE_BYTE(sc61860.dp, sc61860.ram[A]); if (i!=sc61860.ram[I]) sc61860.dp++; sc61860_icount-=3; } } INLINE void sc61860_copy(int count) { int i; for (i=0; i<=count; i++) { sc61860.ram[sc61860.p++]=sc61860.ram[sc61860.q++]; sc61860_icount-=2; } } INLINE void sc61860_copy_ext(int count) { int i; for (i=0; i<=count; i++) { sc61860.ram[sc61860.p++]=READ_BYTE(sc61860.dp); if (i!=count) sc61860.dp++; sc61860_icount-=4; } } INLINE void sc61860_copy_int(int count) { int i; for (i=0; i<=count; i++) { sc61860.ram[sc61860.p++]= READ_BYTE((sc61860.ram[A]|(sc61860.ram[B]<<8)) ); /* internal rom! */ if (i!=count) { if (++sc61860.ram[A]==0) sc61860.ram[B]++; } sc61860_icount-=4; } } INLINE void sc61860_exchange(int count) { int i; UINT8 t; for (i=0; i<=count; i++) { t=sc61860.ram[sc61860.p]; sc61860.ram[sc61860.p++]=sc61860.ram[sc61860.q]; sc61860.ram[sc61860.q++]=t; sc61860_icount-=3; } } INLINE void sc61860_exchange_ext(int count) { int i; UINT8 t; for (i=0; i<=count; i++) { t=sc61860.ram[sc61860.p]; sc61860.ram[sc61860.p++]=READ_BYTE(sc61860.dp); WRITE_BYTE(sc61860.dp, t); if (i!=count) sc61860.dp++; sc61860_icount-=6; } }
19.15674
85
0.665276
gameblabla
0d1914c3d0d36c6153f28a6c46f332d285557125
1,185
cpp
C++
cpp/src/server/photos_handler/photo_item.cpp
ppearson/WebServe_partial
8fe5422d54c38c4a1865d1f1dca2d879f6dcd2d9
[ "Apache-2.0" ]
null
null
null
cpp/src/server/photos_handler/photo_item.cpp
ppearson/WebServe_partial
8fe5422d54c38c4a1865d1f1dca2d879f6dcd2d9
[ "Apache-2.0" ]
null
null
null
cpp/src/server/photos_handler/photo_item.cpp
ppearson/WebServe_partial
8fe5422d54c38c4a1865d1f1dca2d879f6dcd2d9
[ "Apache-2.0" ]
null
null
null
/* WebServe Copyright 2018-2022 Peter Pearson. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------- */ #include "photo_item.h" PhotoItem::PhotoItem() : m_sourceType(eSourceUnknown), m_itemType(eTypeUnknown), m_permissionType(ePermissionPublic), m_rating(0) { } void PhotoItem::setInfoFromEXIF(const EXIFInfoBasic& exifInfoBasic) { if (!exifInfoBasic.m_takenDateTime.empty()) { m_timeTaken.setFromString(exifInfoBasic.m_takenDateTime, DateTime::eDTIF_EXIFDATETIME); } } void PhotoItem::setBasicDate(const std::string& date) { m_timeTaken.setFromString(date, DateTime::eDTIF_DATE); } bool PhotoItem::operator<(const PhotoItem& rhs) const { return m_timeTaken < rhs.m_timeTaken; }
25.212766
89
0.771308
ppearson
0d1f7be63770563c00b8cb8a3467d62cee5ac926
7,489
hpp
C++
include/JDKSAvdeccMCU/ACMPTalker.hpp
DjFix/jdksavdecc-mcu
55d273bcc25aa857d564ece83b3fbd59de240abc
[ "MIT" ]
5
2015-03-26T18:43:44.000Z
2021-11-16T20:31:05.000Z
include/JDKSAvdeccMCU/ACMPTalker.hpp
DjFix/jdksavdecc-mcu
55d273bcc25aa857d564ece83b3fbd59de240abc
[ "MIT" ]
1
2015-03-13T15:53:41.000Z
2015-03-13T15:53:41.000Z
include/JDKSAvdeccMCU/ACMPTalker.hpp
jdkoftinoff/jdksavdecc-mcu
55d273bcc25aa857d564ece83b3fbd59de240abc
[ "MIT" ]
6
2018-02-03T12:04:25.000Z
2021-01-05T09:52:50.000Z
/* Copyright (c) 2015, J.D. Koftinoff Software, Ltd. 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 J.D. Koftinoff Software, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "JDKSAvdeccMCU/World.hpp" #include "JDKSAvdeccMCU/RawSocket.hpp" #include "JDKSAvdeccMCU/Helpers.hpp" #include "JDKSAvdeccMCU/Frame.hpp" #include "JDKSAvdeccMCU/Handler.hpp" #include "JDKSAvdeccMCU/ADPManager.hpp" #include "JDKSAvdeccMCU/Entity.hpp" #include "JDKSAvdeccMCU/EntityState.hpp" namespace JDKSAvdeccMCU { class ACMPTalkerEvents; struct ACMPTalkerListenerPair; struct ACMPTalkerStreamInfo; class ACMPTalkerHandlerBase; class ACMPTalkerEvents { public: virtual ~ACMPTalkerEvents() {} /// /// \brief talkerConnected /// /// Notification that ACMP Talker State Machine has successfully connected a /// stream /// /// \param entity /// \param talker_unique_id /// \param talker_handler /// \param stream_info /// \param listener_pair /// virtual void talkerConnected( Entity *entity, uint16_t talker_unique_id, ACMPTalkerHandlerBase const *talker_handler, ACMPTalkerStreamInfo const &stream_info, ACMPTalkerListenerPair const &listener_pair ) = 0; /// /// \brief talkerDisconnected /// /// Notification that ACMP Talker State Machine has successfully /// disconnected a stream /// /// \param entity /// \param talker_unique_id /// \param talker_handler /// \param stream_info /// \param listener_pair /// virtual void talkerDisconnected( Entity *entity, uint16_t talker_unique_id, ACMPTalkerHandlerBase const *talker_handler, ACMPTalkerStreamInfo const &stream_info, ACMPTalkerListenerPair const &listener_pair ) = 0; }; /// /// See IEEE Std 1722.1-2013 Clause 8.2.2.2.3 ListenerPair /// struct ACMPTalkerListenerPair { ACMPTalkerListenerPair() : m_listener_unique_id( 0 ) {} Eui64 m_listener_entity_id; uint16_t m_listener_unique_id; }; /// /// \brief The ACMPTalkerHandlerBase class /// /// Manages a single Talker unique_id state machine /// class ACMPTalkerHandlerBase { public: /// /// \brief ACMPTalkerHandlerBase /// /// See IEEE Std 1722.1-2013, "Clause 8.2.2.2.4 TalkerStreamInfo" and /// IEEE Std 1722.1-2013 "Clause 8.2.2.6 ACMP Talker State Machine" /// /// \param listener_pair_storage Pointer to an array of /// ACMPTalkerListenerPair objects, /// one for each listener /// /// \param max_connected_listeners Size of the array in count of objects /// ACMPTalkerHandlerBase( ACMPTalkerListenerPair *listener_pair_storage, uint16_t max_connected_listeners ) : m_connection_count( 0 ) , m_connected_listeners( listener_pair_storage ) , m_stream_vlan_id( 0 ) , m_max_connected_listeners( max_connected_listeners ) , m_state( STATE_WAITING ) { } virtual ~ACMPTalkerHandlerBase(); /// /// \brief tick /// /// \param entity /// \param unique_id /// \param eventTarget /// \param timestamp /// virtual void tick( Entity *entity, uint16_t unique_id, ACMPTalkerEvents *eventTarget, jdksavdecc_timestamp_in_milliseconds timestamp ); /// /// \brief receivedACMPDU /// \param entity /// \param unique_id /// \param eventTarget /// \param frame /// \return /// virtual uint8_t receivedACMPDU( Entity *entity, uint16_t unique_id, ACMPTalkerEvents *eventTarget, Frame &frame ); /// /// \brief packListeners /// void packListeners(); Eui64 m_stream_id; Eui48 m_stream_dest_mac; uint16_t m_connection_count; ACMPTalkerListenerPair *m_connected_listeners; uint16_t m_stream_vlan_id; uint16_t m_max_connected_listeners; enum State { STATE_WAITING, STATE_CONNECT, STATE_DISCONNECT, STATE_GET_STATE, STATE_GET_CONNECTION } m_state; }; template <uint16_t MaxListenersPerTalker> class ACMPTalkerHandler : public ACMPTalkerHandlerBase { public: ACMPTalkerHandler() : ACMPTalkerHandlerBase( &m_listener_pairs_storage[0], MaxListenersPerTalker ) {} protected: ACMPTalkerListenerPair m_listener_pairs_storage[MaxListenersPerTalker]; }; class ACMPTalkerGroupHandlerBase { public: ACMPTalkerGroupHandlerBase( Entity *entity, ACMPTalkerEvents *event_target ) : m_entity( entity ), m_event_target( event_target ) { } virtual void tick( jdksavdecc_timestamp_in_milliseconds timestamp ); virtual uint8_t receivedACMPDU( RawSocket *incoming_socket, const jdksavdecc_acmpdu &acmpdu, Frame &frame ); virtual ACMPTalkerHandlerBase *getTalkerHandler( uint16_t talker_unique_id ) = 0; virtual ACMPTalkerHandlerBase const *getTalkerHandler( uint16_t talker_unique_id ) const = 0; virtual uint16_t getTalkerStreamSourceCount() const = 0; protected: Entity *m_entity; ACMPTalkerEvents *m_event_target; }; template <uint16_t TalkerStreamSourceCount, uint16_t MaxListenersPerTalker> class ACMPTalkerGroupHandler : public ACMPTalkerGroupHandlerBase { public: ACMPTalkerGroupHandler( Entity *entity, ACMPTalkerEvents *event_target ) : ACMPTalkerGroupHandlerBase( entity, event_target ) {} virtual ACMPTalkerHandlerBase *getTalkerHandler( uint16_t talker_unique_id ) override { return &m_talkers_storage[talker_unique_id]; } virtual ACMPTalkerHandlerBase const *getTalkerHandler( uint16_t talker_unique_id ) const override { return &m_talkers_storage[talker_unique_id]; } virtual uint16_t getTalkerStreamSourceCount() const override { return TalkerStreamSourceCount; } private: ACMPTalkerHandler<MaxListenersPerTalker> m_talkers_storage[TalkerStreamSourceCount]; }; }
31.868085
132
0.702898
DjFix
0d20fec179a7a5d6af5b8d7811dddea21f533a44
3,554
cpp
C++
Apps/SDEditor/src/ContentBrowser.cpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
Apps/SDEditor/src/ContentBrowser.cpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
4
2021-12-10T05:01:49.000Z
2022-03-19T10:16:14.000Z
Apps/SDEditor/src/ContentBrowser.cpp
xubury/SDEngine
31e44fc5c78ce6b8f0c3b128fd5e0158150590e8
[ "BSD-3-Clause" ]
null
null
null
#include "ContentBrowser.hpp" #include "Resource/Resource.hpp" #include "ImGui/ImGuiWidget.hpp" #include "ImGui/FileDialog.hpp" #include "Utility/String.hpp" namespace SD { #define MODEL_CREATION "Model Creation" #define SCENE_CREATION "Scene Creation" #define TEXTURE_CREATION "Texture Creation" #define FONT_CREATION "Font Creation" const std::filesystem::path root_path = "assets"; ContentBrowser::ContentBrowser(TextureCache& textures) { m_file_icon = textures.Get("icon/file"); m_directory_icon = textures.Get("icon/directory"); m_current_directory = root_path; } void ContentBrowser::ImGui() { ImGui::Begin("Content Browser"); static const char* creation_str = nullptr; // Right-click on blank space if (ImGui::BeginPopupContextWindow(0, 1, false)) { if (ImGui::MenuItem("Create Texture Asset")) { m_open_creation = true; creation_str = TEXTURE_CREATION; } if (ImGui::MenuItem("Create Model Asset")) { m_open_creation = true; creation_str = MODEL_CREATION; } if (ImGui::MenuItem("Create Scene Asset")) { m_open_creation = true; creation_str = SCENE_CREATION; } if (ImGui::MenuItem("Create Font Asset")) { m_open_creation = true; creation_str = FONT_CREATION; } ImGui::EndPopup(); } if (m_current_directory != std::filesystem::path(root_path)) { if (ImGui::Button("<-")) { m_current_directory = m_current_directory.parent_path(); } } static float padding = 16.0f; static float thumbnail_size = 80.0f; const float cell_size = thumbnail_size + padding; const float panel_width = ImGui::GetContentRegionAvail().x; int column_cnt = std::floor(panel_width / cell_size); if (column_cnt < 1) column_cnt = 1; ImGui::Columns(column_cnt, 0, false); for (auto& entry : std::filesystem::directory_iterator(m_current_directory)) { const auto& path = entry.path(); const bool is_directory = entry.is_directory(); const std::string filename = path.filename().string(); auto icon = is_directory ? m_directory_icon : m_file_icon; ImGui::PushID(filename.c_str()); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); ImGui::ImageButton((ImTextureID)(intptr_t)icon->Handle(), {thumbnail_size, thumbnail_size}); if (!is_directory && ImGui::BeginDragDropSource()) { const std::string item_path = path.generic_string(); ImGui::SetDragDropPayload(DROP_ASSET_ITEM, item_path.c_str(), item_path.size() + 1); ImGui::TextUnformatted(item_path.c_str()); ImGui::EndDragDropSource(); } ImGui::PopStyleColor(); if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { if (entry.is_directory()) m_current_directory /= path.filename(); } ImGui::TextWrapped("%s", filename.c_str()); ImGui::NextColumn(); ImGui::PopID(); } ImGui::Columns(1); if (m_open_creation) { ImGui::OpenPopup(creation_str); } // DrawTextureCreation(); // DrawModelCreation(); // DrawSceneCreation(); // DrawFontCreation(); ImGui::SliderFloat("Thumbnail Size", &thumbnail_size, 16, 512); ImGui::SliderFloat("Padding", &padding, 0, 32); ImGui::End(); } } // namespace SD
31.175439
77
0.623804
xubury
0d24f8dfd3a1dda57b34d5fd1e825e6eaa985729
94
cpp
C++
src/server/cell.cpp
Foomf/Thimble
e3fb64597def12debb81d1bbe4ff52c539fe34e2
[ "Zlib" ]
null
null
null
src/server/cell.cpp
Foomf/Thimble
e3fb64597def12debb81d1bbe4ff52c539fe34e2
[ "Zlib" ]
11
2019-09-14T11:02:24.000Z
2019-09-19T04:54:25.000Z
src/server/cell.cpp
Foomf/Blyss
e3fb64597def12debb81d1bbe4ff52c539fe34e2
[ "Zlib" ]
null
null
null
#include "server/cell.hpp" namespace blyss::server { cell::cell() { } }
9.4
26
0.510638
Foomf
0d2790f707311a25147b85ded4174745d2728d8c
12,105
cpp
C++
code/Spark/source/codegen.tree.cpp
pospeselr/SiCKL
e6b3b022df168cb7b853e233967407ff28dd8d1b
[ "MIT" ]
null
null
null
code/Spark/source/codegen.tree.cpp
pospeselr/SiCKL
e6b3b022df168cb7b853e233967407ff28dd8d1b
[ "MIT" ]
null
null
null
code/Spark/source/codegen.tree.cpp
pospeselr/SiCKL
e6b3b022df168cb7b853e233967407ff28dd8d1b
[ "MIT" ]
null
null
null
#include "spark.hpp" // spark internal #include "node.hpp" #include "error.hpp" #include "text_utilities.hpp" const char* spark_nodetype_to_str(spark_nodetype_t val); using namespace spark; using namespace spark::lib; using namespace spark::shared; namespace spark { namespace lib { int32_t controlNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { return doSnprintf(buffer, buffer_size, written, "%s\n", spark_control_to_str(static_cast<spark_control_t>(node->_control))); } int32_t operatorNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { const auto dt = static_cast<spark_datatype_t>(node->_operator.type); const auto op = static_cast<spark_operator_t>(node->_operator.id); char datatypeBuffer[32]; return doSnprintf(buffer, buffer_size, written, "%s : %s\n", spark_operator_to_str(op), spark_datatype_to_str(dt, datatypeBuffer, sizeof(datatypeBuffer))); } int32_t functionNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { const auto dt = static_cast<spark_datatype_t>(node->_function.returnType); char datatypeBuffer[32]; return doSnprintf(buffer, buffer_size, written, "0x%x : function -> %s %s\n", (uint32_t)node->_function.id, spark_datatype_to_str(dt, datatypeBuffer, sizeof(datatypeBuffer)), node->_function.entrypoint ? "(entrypoint)" : ""); } int32_t symbolNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { const auto dt = static_cast<spark_datatype_t>(node->_symbol.type); char datatypeBuffer[32]; return doSnprintf(buffer, buffer_size, written, "0x%x : %s\n", (uint32_t)node->_symbol.id, spark_datatype_to_str(dt, datatypeBuffer, sizeof(datatypeBuffer))); } int32_t constantNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { const auto dt = node->_constant.type; const auto primitive = dt.GetPrimitive(); // primitive cannot be void SPARK_ASSERT(primitive != Primitive::Void); const auto components = dt.GetComponents();; const auto pointer = dt.GetPointer(); SPARK_ASSERT(pointer == false); int32_t componentCount = 1; switch(components) { case Components::None: componentCount = 0; break; case Components::Scalar: componentCount = 1; break; case Components::Vector2: componentCount = 2; break; case Components::Vector4: componentCount = 4; break; case Components::Vector8: componentCount = 8; break; case Components::Vector16: componentCount = 16; break; default: SPARK_ASSERT(false); } auto raw = node->_constant.buffer; SPARK_ASSERT(raw != nullptr); for(int32_t k = 0; k < componentCount; k++) { if(k > 0) { written = doSnprintf(buffer, buffer_size, written, ", "); } union { int64_t signed_integer; uint64_t unsigned_integer; double floating_point; }; switch(primitive) { case Primitive::Char: signed_integer = *((int8_t*)raw + k); break; case Primitive::UChar: unsigned_integer = *((uint8_t*)raw + k); break; case Primitive::Short: signed_integer = *((int16_t*)raw + k); break; case Primitive::UShort: unsigned_integer = *((uint16_t*)raw + k); break; case Primitive::Int: signed_integer = *((int32_t*)raw + k); break; case Primitive::UInt: unsigned_integer = *((uint32_t*)raw + k); break; case Primitive::Long: signed_integer = *((int64_t*)raw + k); break; case Primitive::ULong: unsigned_integer = *((uint64_t*)raw + k); break; case Primitive::Float: floating_point = *((float*)raw + k); break; case Primitive::Double: floating_point = *((double*)raw + k); break; default: SPARK_ASSERT(false); } switch(primitive) { case Primitive::Char: case Primitive::Short: case Primitive::Int: case Primitive::Long: written = doSnprintf(buffer, buffer_size, written, "%lli", signed_integer); break; case Primitive::UChar: case Primitive::UShort: case Primitive::UInt: case Primitive::ULong: written = doSnprintf(buffer, buffer_size, written, "%llu", unsigned_integer); break; case Primitive::Float: case Primitive::Double: written = doSnprintf(buffer, buffer_size, written, "%f", floating_point); break; default: SPARK_ASSERT(false); } } char datatypeBuffer[32]; written = doSnprintf(buffer, buffer_size, written, " : %s\n", spark_datatype_to_str(static_cast<spark_datatype_t>(dt), datatypeBuffer, sizeof(datatypeBuffer))); return written; } int32_t propertyNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { const auto prop = static_cast<spark_property_t>(node->_property.id); char propertyBuffer[8]; written = doSnprintf(buffer, buffer_size, written, "Property::%s\n", spark_property_to_str(prop, propertyBuffer, ruff::countof(propertyBuffer))); return written; } int32_t commentNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { written = doSnprintf(buffer, buffer_size, written, "NodeType::Comment : '%s'\n", node->_comment); return written; } int32_t vectorNodeToText(spark_node_t* node, char* buffer, int32_t buffer_size, int32_t written) { const auto dt = static_cast<spark_datatype_t>(node->_vector.type); char datatypeBuffer[32]; written = doSnprintf(buffer, buffer_size, written, "NodeType::Vector : '%s'\n", spark_datatype_to_str(dt, datatypeBuffer, sizeof(datatypeBuffer))); return written; } // if out_bufer is null int32_t nodeToText(spark_node_t* node, char* out_buffer, int32_t buffer_size, int32_t written, uint32_t bars, int32_t indentation) { SPARK_ASSERT(node != nullptr); SPARK_ASSERT((out_buffer == nullptr && buffer_size == 0) || (out_buffer != nullptr && buffer_size > 0)); // write graph lines for(int32_t k = 0; k < indentation; k++) { const bool printBar = (bars & (1 << k)); const bool printLeaf = (k == indentation - 1); const char* str = " "; if(printLeaf) { if(!printBar) { str = "└─"; } else { str = "├─"; } } else if(printBar) { str = "│ "; } written = doSnprintf(out_buffer, buffer_size, written, "%s", str); } // write node info const auto nodeType = node->_type; switch(nodeType) { case spark_nodetype::control: written = controlNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::operation: written = operatorNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::function: written = functionNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::symbol: written = symbolNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::constant: written = constantNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::property: written = propertyNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::comment: written = commentNodeToText(node, out_buffer, buffer_size, written); break; case spark_nodetype::vector: written = vectorNodeToText(node, out_buffer, buffer_size, written); break; default: written = doSnprintf(out_buffer, buffer_size, written, "%s\n", spark_nodetype_to_str(node->_type)); break; } // only 1 function node (no copy with just symbol id), so only print children if we're // defining the function bool printChildren = ((nodeType == spark_nodetype::function) && (indentation > 1)) ? false : true; if(printChildren) { // depth first traversal const size_t childCount = node->_children.size(); for(size_t k = 0; k < childCount; k++) { auto child = node->_children[k]; const uint32_t childBars = (k < childCount - 1) ? bars | (1 << indentation) : bars; const int32_t childIndentation = indentation + 1; written = nodeToText(child, out_buffer, buffer_size, written, childBars, childIndentation); } } // return characters written return written; } int32_t generateSourceTree(spark_node_t* node, char* out_buffer, int32_t buffer_size) { return nodeToText(node, out_buffer, buffer_size, 0, 0, 0) + 1; } } } RUFF_EXPORT int32_t spark_node_to_text(spark_node_t* node, char* out_buffer, int32_t buffer_size, spark_error_t** error) { return TranslateExceptions( error, [&] { return generateSourceTree(node, out_buffer, buffer_size); }); }
38.550955
159
0.49368
pospeselr
0d292c2955e904d03e1306cd46d7eb78ab5a26e7
448
cpp
C++
UI/room_info_dialog.cpp
tyouritsugun/janus-client-cplus
f478ddcf62d12f1b0efe213dd695ec022e793070
[ "MIT" ]
110
2020-10-27T02:15:35.000Z
2022-03-30T10:24:52.000Z
UI/room_info_dialog.cpp
tyouritsugun/janus-client-cplus
f478ddcf62d12f1b0efe213dd695ec022e793070
[ "MIT" ]
13
2021-02-02T05:32:42.000Z
2022-03-13T15:03:26.000Z
UI/room_info_dialog.cpp
tyouritsugun/janus-client-cplus
f478ddcf62d12f1b0efe213dd695ec022e793070
[ "MIT" ]
37
2020-11-13T15:44:23.000Z
2022-03-25T09:08:22.000Z
#include "room_info_dialog.h" #include "ui_room_info_dialog.h" RoomInfoDialog::RoomInfoDialog(QWidget *parent) : QDialog(parent), ui(new Ui::RoomInfoDialog) { ui->setupUi(this); } RoomInfoDialog::~RoomInfoDialog() { delete ui; } int64_t RoomInfoDialog::getRoomId() const { return ui->roomIdLineEdit->text().toLongLong(); } void RoomInfoDialog::on_buttonBox_accepted() { } void RoomInfoDialog::on_buttonBox_rejected() { }
14.933333
51
0.723214
tyouritsugun
0d29527e9f7220ae5f8a49c72a17c0df2da976a2
28,137
cpp
C++
Marlin-2.0.7_Stock_Board/Marlin/src/lcd/dogm/u8g_dev_tft_320x240_upscale_from_128x64.cpp
kristapsdravnieks/Anycubic-Predator
879ea2af0b9cafc27ea85d966f9bc4699b3e8e25
[ "MIT" ]
2
2021-01-11T19:43:50.000Z
2021-05-02T14:20:30.000Z
Marlin-2.0.7_Stock_Board/Marlin/src/lcd/dogm/u8g_dev_tft_320x240_upscale_from_128x64.cpp
kristapsdravnieks/Anycubic-Predator
879ea2af0b9cafc27ea85d966f9bc4699b3e8e25
[ "MIT" ]
null
null
null
Marlin-2.0.7_Stock_Board/Marlin/src/lcd/dogm/u8g_dev_tft_320x240_upscale_from_128x64.cpp
kristapsdravnieks/Anycubic-Predator
879ea2af0b9cafc27ea85d966f9bc4699b3e8e25
[ "MIT" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * u8g_dev_tft_320x240_upscale_from_128x64.cpp * * Universal 8bit Graphics Library * * Copyright (c) 2011, olikraus@gmail.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 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 "../../inc/MarlinConfig.h" #if HAS_MARLINUI_U8GLIB && (PIN_EXISTS(FSMC_CS) || ENABLED(SPI_GRAPHICAL_TFT)) #include "HAL_LCD_com_defines.h" #include "ultralcd_DOGM.h" #include <string.h> #if EITHER(LCD_USE_DMA_FSMC, LCD_USE_DMA_SPI) #define HAS_LCD_IO 1 #endif #if ENABLED(SPI_GRAPHICAL_TFT) #include HAL_PATH(../../HAL, tft/tft_spi.h) #elif ENABLED(FSMC_GRAPHICAL_TFT) #include HAL_PATH(../../HAL, tft/tft_fsmc.h) #endif TFT_IO tftio; #define WIDTH LCD_PIXEL_WIDTH #define HEIGHT LCD_PIXEL_HEIGHT #define PAGE_HEIGHT 8 #include "../scaled_tft.h" #define UPSCALE0(M) ((M) * (GRAPHICAL_TFT_UPSCALE)) #define UPSCALE(A,M) (UPSCALE0(M) + (A)) #define X_HI (UPSCALE(TFT_PIXEL_OFFSET_X, WIDTH) - 1) #define Y_HI (UPSCALE(TFT_PIXEL_OFFSET_Y, HEIGHT) - 1) // see https://ee-programming-notepad.blogspot.com/2016/10/16-bit-color-generator-picker.html #define COLOR_BLACK 0x0000 // #000000 #define COLOR_WHITE 0xFFFF // #FFFFFF #define COLOR_SILVER 0xC618 // #C0C0C0 #define COLOR_GREY 0x7BEF // #808080 #define COLOR_DARKGREY 0x4208 // #404040 #define COLOR_DARKGREY2 0x39E7 // #303030 #define COLOR_DARK 0x0003 // Some dark color #define COLOR_RED 0xF800 // #FF0000 #define COLOR_LIME 0x7E00 // #00FF00 #define COLOR_BLUE 0x001F // #0000FF #define COLOR_YELLOW 0xFFE0 // #FFFF00 #define COLOR_MAGENTA 0xF81F // #FF00FF #define COLOR_FUCHSIA 0xF81F // #FF00FF #define COLOR_CYAN 0x07FF // #00FFFF #define COLOR_AQUA 0x07FF // #00FFFF #define COLOR_MAROON 0x7800 // #800000 #define COLOR_GREEN 0x03E0 // #008000 #define COLOR_NAVY 0x000F // #000080 #define COLOR_OLIVE 0x8400 // #808000 #define COLOR_PURPLE 0x8010 // #800080 #define COLOR_TEAL 0x0410 // #008080 #define COLOR_ORANGE 0xFC00 // #FF7F00 #ifndef TFT_MARLINUI_COLOR #define TFT_MARLINUI_COLOR COLOR_WHITE #endif #ifndef TFT_MARLINBG_COLOR #define TFT_MARLINBG_COLOR COLOR_BLACK #endif #ifndef TFT_DISABLED_COLOR #define TFT_DISABLED_COLOR COLOR_DARK #endif #ifndef TFT_BTCANCEL_COLOR #define TFT_BTCANCEL_COLOR COLOR_RED #endif #ifndef TFT_BTARROWS_COLOR #define TFT_BTARROWS_COLOR COLOR_BLUE #endif #ifndef TFT_BTOKMENU_COLOR #define TFT_BTOKMENU_COLOR COLOR_RED #endif static uint32_t lcd_id = 0; #define ST7789V_CASET 0x2A /* Column address register */ #define ST7789V_RASET 0x2B /* Row address register */ #define ST7789V_WRITE_RAM 0x2C /* Write data to GRAM */ /* Mind the mess: with landscape screen orientation 'Horizontal' is Y and 'Vertical' is X */ #define ILI9328_HASET 0x20 /* Horizontal GRAM address register (0-255) */ #define ILI9328_VASET 0x21 /* Vertical GRAM address register (0-511)*/ #define ILI9328_WRITE_RAM 0x22 /* Write data to GRAM */ #define ILI9328_HASTART 0x50 /* Horizontal address start position (0-255) */ #define ILI9328_HAEND 0x51 /* Horizontal address end position (0-255) */ #define ILI9328_VASTART 0x52 /* Vertical address start position (0-511) */ #define ILI9328_VAEND 0x53 /* Vertical address end position (0-511) */ static void setWindow_ili9328(u8g_t *u8g, u8g_dev_t *dev, uint16_t Xmin, uint16_t Ymin, uint16_t Xmax, uint16_t Ymax) { #if HAS_LCD_IO tftio.DataTransferBegin(DATASIZE_8BIT); #define IO_REG_DATA(R,D) do { tftio.WriteReg(R); tftio.WriteData(D); }while(0) #else #define IO_REG_DATA(R,D) do { u8g_WriteByte(u8g, dev, R); u8g_WriteSequence(u8g, dev, 2, (uint8_t *)&D); }while(0) #endif #if NONE(LCD_USE_DMA_FSMC, LCD_USE_DMA_SPI) u8g_SetAddress(u8g, dev, 0); #endif IO_REG_DATA(ILI9328_HASTART, Ymin); IO_REG_DATA(ILI9328_HAEND, Ymax); IO_REG_DATA(ILI9328_VASTART, Xmin); IO_REG_DATA(ILI9328_VAEND, Xmax); IO_REG_DATA(ILI9328_HASET, Ymin); IO_REG_DATA(ILI9328_VASET, Xmin); #if HAS_LCD_IO tftio.WriteReg(ILI9328_WRITE_RAM); tftio.DataTransferEnd(); #else u8g_WriteByte(u8g, dev, ILI9328_WRITE_RAM); u8g_SetAddress(u8g, dev, 1); #endif } static void setWindow_st7789v(u8g_t *u8g, u8g_dev_t *dev, uint16_t Xmin, uint16_t Ymin, uint16_t Xmax, uint16_t Ymax) { #if HAS_LCD_IO tftio.DataTransferBegin(DATASIZE_8BIT); tftio.WriteReg(ST7789V_CASET); tftio.WriteData((Xmin >> 8) & 0xFF); tftio.WriteData(Xmin & 0xFF); tftio.WriteData((Xmax >> 8) & 0xFF); tftio.WriteData(Xmax & 0xFF); tftio.WriteReg(ST7789V_RASET); tftio.WriteData((Ymin >> 8) & 0xFF); tftio.WriteData(Ymin & 0xFF); tftio.WriteData((Ymax >> 8) & 0xFF); tftio.WriteData(Ymax & 0xFF); tftio.WriteReg(ST7789V_WRITE_RAM); tftio.DataTransferEnd(); #else u8g_SetAddress(u8g, dev, 0); u8g_WriteByte(u8g, dev, ST7789V_CASET); u8g_SetAddress(u8g, dev, 1); u8g_WriteByte(u8g, dev, (Xmin >> 8) & 0xFF); u8g_WriteByte(u8g, dev, Xmin & 0xFF); u8g_WriteByte(u8g, dev, (Xmax >> 8) & 0xFF); u8g_WriteByte(u8g, dev, Xmax & 0xFF); u8g_SetAddress(u8g, dev, 0); u8g_WriteByte(u8g, dev, ST7789V_RASET); u8g_SetAddress(u8g, dev, 1); u8g_WriteByte(u8g, dev, (Ymin >> 8) & 0xFF); u8g_WriteByte(u8g, dev, Ymin & 0xFF); u8g_WriteByte(u8g, dev, (Ymax >> 8) & 0xFF); u8g_WriteByte(u8g, dev, Ymax & 0xFF); u8g_SetAddress(u8g, dev, 0); u8g_WriteByte(u8g, dev, ST7789V_WRITE_RAM); u8g_SetAddress(u8g, dev, 1); #endif } static void setWindow_none(u8g_t *u8g, u8g_dev_t *dev, uint16_t Xmin, uint16_t Ymin, uint16_t Xmax, uint16_t Ymax) {} void (*setWindow)(u8g_t *u8g, u8g_dev_t *dev, uint16_t Xmin, uint16_t Ymin, uint16_t Xmax, uint16_t Ymax) = setWindow_none; #define ESC_REG(x) 0xFFFF, 0x00FF & (uint16_t)x #define ESC_DELAY(x) 0xFFFF, 0x8000 | (x & 0x7FFF) #define ESC_END 0xFFFF, 0x7FFF #define ESC_FFFF 0xFFFF, 0xFFFF #if HAS_LCD_IO void writeEscSequence(const uint16_t *sequence) { uint16_t data; for (;;) { data = *sequence++; if (data != 0xFFFF) { tftio.WriteData(data); continue; } data = *sequence++; if (data == 0x7FFF) return; if (data == 0xFFFF) { tftio.WriteData(data); } else if (data & 0x8000) { delay(data & 0x7FFF); } else if ((data & 0xFF00) == 0) { tftio.WriteReg(data); } } } #define WRITE_ESC_SEQUENCE(V) writeEscSequence(V) #define WRITE_ESC_SEQUENCE16(V) writeEscSequence(V) #else void writeEscSequence8(u8g_t *u8g, u8g_dev_t *dev, const uint16_t *sequence) { uint16_t data; u8g_SetAddress(u8g, dev, 1); for (;;) { data = *sequence++; if (data != 0xFFFF) { u8g_WriteByte(u8g, dev, data & 0xFF); continue; } data = *sequence++; if (data == 0x7FFF) return; if (data == 0xFFFF) { u8g_WriteByte(u8g, dev, data & 0xFF); } else if (data & 0x8000) { delay(data & 0x7FFF); } else if ((data & 0xFF00) == 0) { u8g_SetAddress(u8g, dev, 0); u8g_WriteByte(u8g, dev, data & 0xFF); u8g_SetAddress(u8g, dev, 1); } } } #define WRITE_ESC_SEQUENCE(V) writeEscSequence8(u8g, dev, V) void writeEscSequence16(u8g_t *u8g, u8g_dev_t *dev, const uint16_t *sequence) { uint16_t data; u8g_SetAddress(u8g, dev, 0); for (;;) { data = *sequence++; if (data != 0xFFFF) { u8g_WriteSequence(u8g, dev, 2, (uint8_t *)&data); continue; } data = *sequence++; if (data == 0x7FFF) return; if (data == 0xFFFF) { u8g_WriteSequence(u8g, dev, 2, (uint8_t *)&data); } else if (data & 0x8000) { delay(data & 0x7FFF); } else if ((data & 0xFF00) == 0) { u8g_WriteByte(u8g, dev, data & 0xFF); } } u8g_SetAddress(u8g, dev, 1); } #define WRITE_ESC_SEQUENCE16(V) writeEscSequence16(u8g, dev, V) #endif static const uint16_t st7789v_init[] = { ESC_REG(0x0010), ESC_DELAY(10), ESC_REG(0x0001), ESC_DELAY(200), ESC_REG(0x0011), ESC_DELAY(120), ESC_REG(0x0036), TERN(GRAPHICAL_TFT_ROTATE_180, 0x0060, 0x00A0), ESC_REG(0x003A), 0x0055, ESC_REG(0x002A), 0x0000, 0x0000, 0x0001, 0x003F, ESC_REG(0x002B), 0x0000, 0x0000, 0x0000, 0x00EF, ESC_REG(0x00B2), 0x000C, 0x000C, 0x0000, 0x0033, 0x0033, ESC_REG(0x00B7), 0x0035, ESC_REG(0x00BB), 0x001F, ESC_REG(0x00C0), 0x002C, ESC_REG(0x00C2), 0x0001, 0x00C3, ESC_REG(0x00C4), 0x0020, ESC_REG(0x00C6), 0x000F, ESC_REG(0x00D0), 0x00A4, 0x00A1, ESC_REG(0x0029), ESC_REG(0x0011), ESC_END }; static const uint16_t ili9328_init[] = { ESC_REG(0x0001), 0x0100, ESC_REG(0x0002), 0x0400, ESC_REG(0x0003), 0x1038, ESC_REG(0x0004), 0x0000, ESC_REG(0x0008), 0x0202, ESC_REG(0x0009), 0x0000, ESC_REG(0x000A), 0x0000, ESC_REG(0x000C), 0x0000, ESC_REG(0x000D), 0x0000, ESC_REG(0x000F), 0x0000, ESC_REG(0x0010), 0x0000, ESC_REG(0x0011), 0x0007, ESC_REG(0x0012), 0x0000, ESC_REG(0x0013), 0x0000, ESC_REG(0x0007), 0x0001, ESC_DELAY(200), ESC_REG(0x0010), 0x1690, ESC_REG(0x0011), 0x0227, ESC_DELAY(50), ESC_REG(0x0012), 0x008C, ESC_DELAY(50), ESC_REG(0x0013), 0x1500, ESC_REG(0x0029), 0x0004, ESC_REG(0x002B), 0x000D, ESC_DELAY(50), ESC_REG(0x0050), 0x0000, ESC_REG(0x0051), 0x00EF, ESC_REG(0x0052), 0x0000, ESC_REG(0x0053), 0x013F, ESC_REG(0x0020), 0x0000, ESC_REG(0x0021), 0x0000, ESC_REG(0x0060), 0x2700, ESC_REG(0x0061), 0x0001, ESC_REG(0x006A), 0x0000, ESC_REG(0x0080), 0x0000, ESC_REG(0x0081), 0x0000, ESC_REG(0x0082), 0x0000, ESC_REG(0x0083), 0x0000, ESC_REG(0x0084), 0x0000, ESC_REG(0x0085), 0x0000, ESC_REG(0x0090), 0x0010, ESC_REG(0x0092), 0x0600, ESC_REG(0x0007), 0x0133, ESC_REG(0x0022), ESC_END }; static const uint16_t ili9341_init[] = { ESC_REG(0x0010), ESC_DELAY(10), ESC_REG(0x0001), ESC_DELAY(200), ESC_REG(0x0036), TERN(GRAPHICAL_TFT_ROTATE_180, 0x0028, 0x00E8), ESC_REG(0x003A), 0x0055, ESC_REG(0x002A), 0x0000, 0x0000, 0x0001, 0x003F, ESC_REG(0x002B), 0x0000, 0x0000, 0x0000, 0x00EF, ESC_REG(0x00C5), 0x003E, 0x0028, ESC_REG(0x00C7), 0x0086, ESC_REG(0x00B1), 0x0000, 0x0018, ESC_REG(0x00C0), 0x0023, ESC_REG(0x00C1), 0x0010, ESC_REG(0x0029), ESC_REG(0x0011), ESC_DELAY(100), ESC_END }; static const uint16_t ili9488_init[] = { ESC_REG(0x00E0), 0x0000, 0x0007, 0x000F, 0x000D, 0x001B, 0x000A, 0x003C, 0x0078, 0x004A, 0x0007, 0x000E, 0x0009, 0x001B, 0x001E, 0x000F, ESC_REG(0x00E1), 0x0000, 0x0022, 0x0024, 0x0006, 0x0012, 0x0007, 0x0036, 0x0047, 0x0047, 0x0006, 0x000A, 0x0007, 0x0030, 0x0037, 0x000F, ESC_REG(0x00C0), 0x0010, 0x0010, ESC_REG(0x00C1), 0x0041, ESC_REG(0x00C5), 0x0000, 0x0022, 0x0080, ESC_REG(0x0036), TERN(GRAPHICAL_TFT_ROTATE_180, 0x00A8, 0x0068), ESC_REG(0x003A), 0x0055, ESC_REG(0x00B0), 0x0000, ESC_REG(0x00B1), 0x00B0, 0x0011, ESC_REG(0x00B4), 0x0002, ESC_REG(0x00B6), 0x0002, 0x0042, ESC_REG(0x00B7), 0x00C6, ESC_REG(0x00E9), 0x0000, ESC_REG(0x00F0), 0x00A9, 0x0051, 0x002C, 0x0082, ESC_REG(0x0029), ESC_REG(0x0011), ESC_DELAY(100), ESC_END }; static const uint16_t st7796_init[] = { ESC_REG(0x0010), ESC_DELAY(120), ESC_REG(0x0001), ESC_DELAY(120), ESC_REG(0x0011), ESC_DELAY(120), ESC_REG(0x00F0), 0x00C3, ESC_REG(0x00F0), 0x0096, ESC_REG(0x0036), TERN(GRAPHICAL_TFT_ROTATE_180, 0x00E8, 0x0028), ESC_REG(0x003A), 0x0055, ESC_REG(0x00B4), 0x0001, ESC_REG(0x00B7), 0x00C6, ESC_REG(0x00E8), 0x0040, 0x008A, 0x0000, 0x0000, 0x0029, 0x0019, 0x00A5, 0x0033, ESC_REG(0x00C1), 0x0006, ESC_REG(0x00C2), 0x00A7, ESC_REG(0x00C5), 0x0018, ESC_REG(0x00E0), 0x00F0, 0x0009, 0x000B, 0x0006, 0x0004, 0x0015, 0x002F, 0x0054, 0x0042, 0x003C, 0x0017, 0x0014, 0x0018, 0x001B, ESC_REG(0x00E1), 0x00F0, 0x0009, 0x000B, 0x0006, 0x0004, 0x0003, 0x002D, 0x0043, 0x0042, 0x003B, 0x0016, 0x0014, 0x0017, 0x001B, ESC_REG(0x00F0), 0x003C, ESC_REG(0x00F0), 0x0069, ESC_DELAY(120), ESC_REG(0x0029), ESC_REG(0x0011), ESC_DELAY(100), ESC_END }; #if HAS_TOUCH_XPT2046 static const uint8_t buttonD[] = { B01111111,B11111111,B11111111,B11111110, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00011100,B00000001, B10000000,B00000100,B00011100,B00000001, B10000000,B00001100,B00011100,B00000001, B10000000,B00011111,B11111100,B00000001, B10000000,B00111111,B11111100,B00000001, B10000000,B00011111,B11111100,B00000001, B10000000,B00001100,B00000000,B00000001, B10000000,B00000100,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B01111111,B11111111,B11111111,B11111110, }; #if ENABLED(REVERSE_MENU_DIRECTION) static const uint8_t buttonA[] = { B01111111,B11111111,B11111111,B11111110, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00111111,B11100001, B10000111,B11111100,B00111111,B11100001, B10000011,B11111000,B00000000,B00000001, B10000001,B11110000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B01000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B01111111,B11111111,B11111111,B11111110, }; static const uint8_t buttonB[] = { B01111111,B11111111,B11111111,B11111110, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B01100000,B00000010,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00001111,B10000001, B10000000,B01100000,B00011111,B11000001, B10000111,B11111110,B00111111,B11100001, B10000111,B11111110,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B01111111,B11111111,B11111111,B11111110, }; #else static const uint8_t buttonA[] = { B01111111,B11111111,B11111111,B11111110, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B01000000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000001,B11110000,B00000000,B00000001, B10000011,B11111000,B00000000,B00000001, B10000111,B11111100,B00111111,B11100001, B10000000,B11100000,B00111111,B11100001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B11100000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B01111111,B11111111,B11111111,B11111110, }; static const uint8_t buttonB[] = { B01111111,B11111111,B11111111,B11111110, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000111,B00000001, B10000111,B11111110,B00000111,B00000001, B10000111,B11111110,B00111111,B11100001, B10000000,B01100000,B00011111,B11000001, B10000000,B01100000,B00001111,B10000001, B10000000,B01100000,B00000111,B00000001, B10000000,B01100000,B00000010,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B01111111,B11111111,B11111111,B11111110, }; #endif static const uint8_t buttonC[] = { B01111111,B11111111,B11111111,B11111110, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00011000,B00110000,B00000001, B10000000,B00001100,B01100000,B00000001, B10000000,B00000110,B11000000,B00000001, B10000000,B00000011,B10000000,B00000001, B10000000,B00000011,B10000000,B00000001, B10000000,B00000110,B11000000,B00000001, B10000000,B00001100,B01100000,B00000001, B10000000,B00011000,B00110000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B10000000,B00000000,B00000000,B00000001, B01111111,B11111111,B11111111,B11111110, }; #define BUTTON_SIZE_X 32 #define BUTTON_SIZE_Y 20 // 14, 90, 166, 242, 185 are the original values upscaled 2x. #define BUTTOND_X_LO UPSCALE0(14 / 2) #define BUTTOND_X_HI (UPSCALE(BUTTOND_X_LO, BUTTON_SIZE_X) - 1) #define BUTTONA_X_LO UPSCALE0(90 / 2) #define BUTTONA_X_HI (UPSCALE(BUTTONA_X_LO, BUTTON_SIZE_X) - 1) #define BUTTONB_X_LO UPSCALE0(166 / 2) #define BUTTONB_X_HI (UPSCALE(BUTTONB_X_LO, BUTTON_SIZE_X) - 1) #define BUTTONC_X_LO UPSCALE0(242 / 2) #define BUTTONC_X_HI (UPSCALE(BUTTONC_X_LO, BUTTON_SIZE_X) - 1) #define BUTTON_Y_LO UPSCALE0(140 / 2) + 44 // 184 2x, 254 3x #define BUTTON_Y_HI (UPSCALE(BUTTON_Y_LO, BUTTON_SIZE_Y) - 1) void drawImage(const uint8_t *data, u8g_t *u8g, u8g_dev_t *dev, uint16_t length, uint16_t height, uint16_t color) { uint16_t buffer[BUTTON_SIZE_X * sq(GRAPHICAL_TFT_UPSCALE)]; if (length > BUTTON_SIZE_X) return; for (uint16_t i = 0; i < height; i++) { uint16_t k = 0; for (uint16_t j = 0; j < length; j++) { uint16_t v = TFT_MARLINBG_COLOR; if (*(data + (i * (length >> 3) + (j >> 3))) & (0x80 >> (j & 7))) v = color; else v = TFT_MARLINBG_COLOR; LOOP_L_N(n, GRAPHICAL_TFT_UPSCALE) buffer[k++] = v; } #if HAS_LCD_IO LOOP_S_L_N(n, 1, GRAPHICAL_TFT_UPSCALE) for (uint16_t l = 0; l < UPSCALE0(length); l++) buffer[l + n * UPSCALE0(length)] = buffer[l]; tftio.WriteSequence(buffer, length * sq(GRAPHICAL_TFT_UPSCALE)); #else for (uint8_t i = GRAPHICAL_TFT_UPSCALE; i--;) u8g_WriteSequence(u8g, dev, k << 1, (uint8_t*)buffer); #endif } } #endif // HAS_TOUCH_XPT2046 // Used to fill RGB565 (16bits) background inline void memset2(const void *ptr, uint16_t fill, size_t cnt) { uint16_t* wptr = (uint16_t*)ptr; for (size_t i = 0; i < cnt; i += 2) { *wptr = fill; wptr++; } } static bool preinit = true; static uint8_t page; uint8_t u8g_dev_tft_320x240_upscale_from_128x64_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) { u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem); #if HAS_LCD_IO static uint16_t bufferA[WIDTH * sq(GRAPHICAL_TFT_UPSCALE)], bufferB[WIDTH * sq(GRAPHICAL_TFT_UPSCALE)]; uint16_t* buffer = &bufferA[0]; #else uint16_t buffer[WIDTH * GRAPHICAL_TFT_UPSCALE]; // 16-bit RGB 565 pixel line buffer #endif switch (msg) { case U8G_DEV_MSG_INIT: dev->com_fn(u8g, U8G_COM_MSG_INIT, U8G_SPI_CLK_CYCLE_NONE, &lcd_id); tftio.DataTransferBegin(DATASIZE_8BIT); switch (lcd_id & 0xFFFF) { case 0x8552: // ST7789V WRITE_ESC_SEQUENCE(st7789v_init); setWindow = setWindow_st7789v; break; case 0x9328: // ILI9328 WRITE_ESC_SEQUENCE16(ili9328_init); setWindow = setWindow_ili9328; break; case 0x9341: // ILI9341 WRITE_ESC_SEQUENCE(ili9341_init); setWindow = setWindow_st7789v; break; case 0x8066: // Anycubic / TronXY TFTs (480x320) WRITE_ESC_SEQUENCE(ili9488_init); setWindow = setWindow_st7789v; break; case 0x7796: WRITE_ESC_SEQUENCE(st7796_init); setWindow = setWindow_st7789v; break; case 0x9488: WRITE_ESC_SEQUENCE(ili9488_init); setWindow = setWindow_st7789v; case 0x0404: // No connected display on FSMC lcd_id = 0; return 0; case 0xFFFF: // No connected display on SPI lcd_id = 0; return 0; default: setWindow = (lcd_id & 0xFF000000) ? setWindow_st7789v : setWindow_ili9328; break; } tftio.DataTransferEnd(); if (preinit) { preinit = false; return u8g_dev_pb8v1_base_fn(u8g, dev, msg, arg); } // Clear Screen setWindow(u8g, dev, 0, 0, (TFT_WIDTH) - 1, (TFT_HEIGHT) - 1); #if HAS_LCD_IO tftio.WriteMultiple(TFT_MARLINBG_COLOR, uint32_t(TFT_WIDTH) * (TFT_HEIGHT)); #else memset2(buffer, TFT_MARLINBG_COLOR, (TFT_WIDTH) / 2); for (uint16_t i = 0; i < (TFT_HEIGHT) * sq(GRAPHICAL_TFT_UPSCALE); i++) u8g_WriteSequence(u8g, dev, (TFT_WIDTH) / 2, (uint8_t *)buffer); #endif // Bottom buttons #if HAS_TOUCH_XPT2046 setWindow(u8g, dev, BUTTOND_X_LO, BUTTON_Y_LO, BUTTOND_X_HI, BUTTON_Y_HI); drawImage(buttonD, u8g, dev, 32, 20, TFT_BTOKMENU_COLOR); setWindow(u8g, dev, BUTTONA_X_LO, BUTTON_Y_LO, BUTTONA_X_HI, BUTTON_Y_HI); drawImage(buttonA, u8g, dev, 32, 20, TFT_BTARROWS_COLOR); setWindow(u8g, dev, BUTTONB_X_LO, BUTTON_Y_LO, BUTTONB_X_HI, BUTTON_Y_HI); drawImage(buttonB, u8g, dev, 32, 20, TFT_BTARROWS_COLOR); setWindow(u8g, dev, BUTTONC_X_LO, BUTTON_Y_LO, BUTTONC_X_HI, BUTTON_Y_HI); drawImage(buttonC, u8g, dev, 32, 20, TFT_BTCANCEL_COLOR); #endif // HAS_TOUCH_XPT2046 return 0; case U8G_DEV_MSG_STOP: preinit = true; break; case U8G_DEV_MSG_PAGE_FIRST: page = 0; setWindow(u8g, dev, TFT_PIXEL_OFFSET_X, TFT_PIXEL_OFFSET_Y, X_HI, Y_HI); break; case U8G_DEV_MSG_PAGE_NEXT: if (++page > (HEIGHT / PAGE_HEIGHT)) return 1; LOOP_L_N(y, PAGE_HEIGHT) { uint32_t k = 0; #if HAS_LCD_IO buffer = (y & 1) ? bufferB : bufferA; #endif for (uint16_t i = 0; i < (uint32_t)pb->width; i++) { const uint8_t b = *(((uint8_t *)pb->buf) + i); const uint16_t c = TEST(b, y) ? TFT_MARLINUI_COLOR : TFT_MARLINBG_COLOR; LOOP_L_N(n, GRAPHICAL_TFT_UPSCALE) buffer[k++] = c; } #if HAS_LCD_IO LOOP_S_L_N(n, 1, GRAPHICAL_TFT_UPSCALE) for (uint16_t l = 0; l < UPSCALE0(WIDTH); l++) buffer[l + n * UPSCALE0(WIDTH)] = buffer[l]; tftio.WriteSequence(buffer, COUNT(bufferA)); #else uint8_t* bufptr = (uint8_t*) buffer; for (uint8_t i = GRAPHICAL_TFT_UPSCALE; i--;) { LOOP_S_L_N(n, 0, GRAPHICAL_TFT_UPSCALE * 2) { u8g_WriteSequence(u8g, dev, WIDTH, &bufptr[WIDTH * n]); } } #endif } break; case U8G_DEV_MSG_SLEEP_ON: // Enter Sleep Mode (10h) return 1; case U8G_DEV_MSG_SLEEP_OFF: // Sleep Out (11h) return 1; } return u8g_dev_pb8v1_base_fn(u8g, dev, msg, arg); } static uint8_t msgInitCount = 2; // Ignore all messages until 2nd U8G_COM_MSG_INIT uint8_t u8g_com_hal_tft_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { if (msgInitCount) { if (msg == U8G_COM_MSG_INIT) msgInitCount--; if (msgInitCount) return -1; } static uint8_t isCommand; switch (msg) { case U8G_COM_MSG_STOP: break; case U8G_COM_MSG_INIT: u8g_SetPIOutput(u8g, U8G_PI_RESET); u8g_Delay(50); tftio.Init(); if (arg_ptr) { *((uint32_t *)arg_ptr) = tftio.GetID(); } isCommand = 0; break; case U8G_COM_MSG_ADDRESS: // define cmd (arg_val = 0) or data mode (arg_val = 1) isCommand = arg_val == 0 ? 1 : 0; break; case U8G_COM_MSG_RESET: u8g_SetPILevel(u8g, U8G_PI_RESET, arg_val); break; case U8G_COM_MSG_WRITE_BYTE: tftio.DataTransferBegin(DATASIZE_8BIT); if (isCommand) tftio.WriteReg(arg_val); else tftio.WriteData((uint16_t)arg_val); tftio.DataTransferEnd(); break; case U8G_COM_MSG_WRITE_SEQ: tftio.DataTransferBegin(DATASIZE_16BIT); for (uint8_t i = 0; i < arg_val; i += 2) tftio.WriteData(*(uint16_t *)(((uint32_t)arg_ptr) + i)); tftio.DataTransferEnd(); break; } return 1; } U8G_PB_DEV(u8g_dev_tft_320x240_upscale_from_128x64, WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_tft_320x240_upscale_from_128x64_fn, U8G_COM_HAL_TFT_FN); #endif // HAS_MARLINUI_U8GLIB && FSMC_CS
34.481618
144
0.690585
kristapsdravnieks
0d33b2f90174ea944c4bfc3100e4f5c06fd25a7d
5,590
cpp
C++
mlir/lib/Transforms/uplift_math.cpp
mshahneo/mlir-extensions
406748ae1d7902c37934313f7614c8bd1e4999fb
[ "Apache-2.0" ]
null
null
null
mlir/lib/Transforms/uplift_math.cpp
mshahneo/mlir-extensions
406748ae1d7902c37934313f7614c8bd1e4999fb
[ "Apache-2.0" ]
null
null
null
mlir/lib/Transforms/uplift_math.cpp
mshahneo/mlir-extensions
406748ae1d7902c37934313f7614c8bd1e4999fb
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mlir-extensions/Transforms/uplift_math.hpp" #include "mlir-extensions/Dialect/plier/dialect.hpp" #include "mlir-extensions/Transforms/rewrite_wrapper.hpp" #include <mlir/Dialect/Arithmetic/IR/Arithmetic.h> #include <mlir/Dialect/Func/IR/FuncOps.h> #include <mlir/Dialect/Math/IR/Math.h> #include <mlir/IR/PatternMatch.h> template <typename Op> static mlir::Operation *replaceOp1(mlir::OpBuilder &builder, mlir::Location loc, mlir::ValueRange args) { if (args.size() != 1) return nullptr; return builder.create<Op>(loc, args.front()); } template <typename Op> static mlir::Operation *replaceOp2(mlir::OpBuilder &builder, mlir::Location loc, mlir::ValueRange args) { if (args.size() != 2) return nullptr; return builder.create<Op>(loc, args[0], args[1]); } namespace { struct UpliftMathCalls : public mlir::OpRewritePattern<mlir::func::CallOp> { using OpRewritePattern::OpRewritePattern; mlir::LogicalResult matchAndRewrite(mlir::func::CallOp op, mlir::PatternRewriter &rewriter) const override { auto funcName = op.getCallee(); if (funcName.empty()) return mlir::failure(); auto isNotValidType = [](mlir::Type t) { return !t.isIntOrFloat(); }; if (llvm::any_of(op.getOperandTypes(), isNotValidType) || op.getNumResults() != 1 || llvm::any_of(op.getResultTypes(), isNotValidType)) return mlir::failure(); llvm::StringRef funcNameF = (funcName.front() == 'f' ? funcName.drop_front() : llvm::StringRef{}); using func_t = mlir::Operation *(*)(mlir::OpBuilder &, mlir::Location, mlir::ValueRange); const std::pair<llvm::StringRef, func_t> handlers[] = { {"log", &replaceOp1<mlir::math::LogOp>}, {"sqrt", &replaceOp1<mlir::math::SqrtOp>}, {"exp", &replaceOp1<mlir::math::ExpOp>}, {"sin", &replaceOp1<mlir::math::SinOp>}, {"cos", &replaceOp1<mlir::math::CosOp>}, {"erf", &replaceOp1<mlir::math::ErfOp>}, {"tanh", &replaceOp1<mlir::math::TanhOp>}, {"atan2", &replaceOp2<mlir::math::Atan2Op>}, }; for (auto &handler : handlers) { auto name = handler.first; if (name == funcName || name == funcNameF) { auto res = handler.second(rewriter, op.getLoc(), op.operands()); if (!res) return mlir::failure(); assert(res->getNumResults() == op->getNumResults()); rewriter.replaceOp(op, res->getResults()); return mlir::success(); } } return mlir::failure(); } }; struct UpliftFabsCalls : public mlir::OpRewritePattern<mlir::func::CallOp> { using OpRewritePattern::OpRewritePattern; mlir::LogicalResult matchAndRewrite(mlir::func::CallOp op, mlir::PatternRewriter &rewriter) const override { auto funcName = op.getCallee(); if (funcName.empty()) return mlir::failure(); if (funcName != "fabs" && funcName != "fabsf") return mlir::failure(); auto isNotValidType = [](mlir::Type t) { return !t.isa<mlir::FloatType>(); }; if (op.getNumResults() != 1 || op.getNumOperands() != 1 || llvm::any_of(op.getOperandTypes(), isNotValidType) || llvm::any_of(op.getResultTypes(), isNotValidType)) return mlir::failure(); rewriter.replaceOpWithNewOp<mlir::math::AbsOp>(op, op.operands()[0]); return mlir::success(); } }; struct UpliftFma : public mlir::OpRewritePattern<mlir::arith::AddFOp> { using OpRewritePattern::OpRewritePattern; mlir::LogicalResult matchAndRewrite(mlir::arith::AddFOp op, mlir::PatternRewriter &rewriter) const override { auto func = op->getParentOfType<mlir::func::FuncOp>(); if (!func || !func->hasAttr(plier::attributes::getFastmathName())) return mlir::failure(); mlir::Value c; mlir::arith::MulFOp ab; if ((ab = op.getLhs().getDefiningOp<mlir::arith::MulFOp>())) { c = op.getRhs(); } else if ((ab = op.getRhs().getDefiningOp<mlir::arith::MulFOp>())) { c = op.getLhs(); } else { return mlir::failure(); } auto a = ab.getLhs(); auto b = ab.getRhs(); rewriter.replaceOpWithNewOp<mlir::math::FmaOp>(op, a, b, c); return mlir::success(); } }; struct UpliftMathPass : public plier::RewriteWrapperPass< UpliftMathPass, void, plier::DependentDialectsList<mlir::func::FuncDialect, mlir::arith::ArithmeticDialect, mlir::math::MathDialect>, UpliftMathCalls, UpliftFabsCalls, UpliftFma> {}; } // namespace void plier::populateUpliftmathPatterns(mlir::MLIRContext &context, mlir::RewritePatternSet &patterns) { patterns.insert<UpliftMathCalls>(&context); } std::unique_ptr<mlir::Pass> plier::createUpliftMathPass() { return std::make_unique<UpliftMathPass>(); }
34.085366
80
0.631127
mshahneo
0d3611b86d5b554548c5aeab6993534d8c03142b
788
cpp
C++
Answer/ans_code_and_note/chapter2/sort.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
Answer/ans_code_and_note/chapter2/sort.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
Answer/ans_code_and_note/chapter2/sort.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; void display(vector<int> vec) { for (int ix = 0; ix < vec.size(); ++ix) { cout << vec[ix] << ' '; } cout << endl; } void swap(int *val1, int *val2) { int temp = *val1; * val1 = *val2; * val2 = temp; } void bubble_sort(vector<int> &vec) { for (int ix = 0; ix < vec.size(); ++ix) { for (int jx = ix + 1; jx < vec.size(); ++jx) { if (vec[ix] > vec[jx]) { swap(&vec[ix], &vec[jx]); } } } } int main(void) { int ia[8] = {8, 34, 3, 13, 1, 21, 5, 2}; vector<int> vec(ia, ia + 8); cout << "vector before sort:"; display(vec); bubble_sort(vec); cout << "vector after sort:"; display(vec); return 0; }
17.130435
54
0.474619
seanleecn
0d36a904192e4e5710e3c05ca542fe8feea4967b
4,667
cpp
C++
Iron/strategy/dragoonRush.cpp
biug/titan
aacb4e2dc4d55601abd45cb8321d8e5160851eec
[ "MIT" ]
null
null
null
Iron/strategy/dragoonRush.cpp
biug/titan
aacb4e2dc4d55601abd45cb8321d8e5160851eec
[ "MIT" ]
null
null
null
Iron/strategy/dragoonRush.cpp
biug/titan
aacb4e2dc4d55601abd45cb8321d8e5160851eec
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // // This file is part of Iron's source files. // Iron is free software, licensed under the MIT/X11 License. // A copy of the license is provided with the library in the LICENSE file. // Copyright (c) 2016, 2017, Igor Dimitrijevic // ////////////////////////////////////////////////////////////////////////// #include "dragoonRush.h" #include "strategy.h" #include "stone.h" #include "../units/him.h" #include "../units/my.h" #include "../behavior/mining.h" #include "../behavior/chasing.h" #include "../behavior/repairing.h" #include "../territory/stronghold.h" #include "../units/cc.h" #include "../Iron.h" namespace { auto & bw = Broodwar; } namespace iron { ////////////////////////////////////////////////////////////////////////////////////////////// // // // class DragoonRush // // ////////////////////////////////////////////////////////////////////////////////////////////// DragoonRush::DragoonRush() { } string DragoonRush::StateDescription() const { if (!m_detected) return "-"; if (m_detected) return "detected"; return "-"; } bool DragoonRush::ConditionToStartSecondShop() const { assert_throw(m_detected); return me().Units(Terran_Vulture).size() >= 4; } void DragoonRush::OnFrame_v() { if (ai()->GetStrategy()->Active<Stone>()) return Discard(); if (him().IsTerran() || him().IsZerg()) return Discard(); const vector<const Area *> & MyEnlargedArea = ext(me().GetArea())->EnlargedArea(); vector<const Area *> MyTerritory = MyEnlargedArea; for (const Area * area : MyEnlargedArea) for (const Area * neighbour : area->AccessibleNeighbours()) push_back_if_not_found(MyTerritory, neighbour); const int dragoonsNearMe = count_if(him().Units().begin(), him().Units().end(), [&MyTerritory](const unique_ptr<HisUnit> & u) { return u->Is(Protoss_Dragoon) && contains(MyTerritory, u->GetArea()) && groundDist(u->Pos(), me().StartingBase()->Center()) < 64*32; }); const bool detectedCondition = (dragoonsNearMe >= 1) && ((int)me().Units(Terran_Vulture).size() < dragoonsNearMe + 2); if (!detectedCondition) { if (me().CompletedUnits(Terran_Vulture) >= 4) return Discard(); if ((me().CompletedUnits(Terran_Vulture) >= 2) && me().HasResearched(TechTypes::Spider_Mines)) return Discard(); } if (m_detected) { // cancel second Machine Shop if there is a lack of vultures if (ai()->Frame() % 10 == 0) if (me().Buildings(Terran_Machine_Shop).size() == 2) if (!ConditionToStartSecondShop()) { MyBuilding * pSecondShop = nullptr; int maxTimeToComplete = numeric_limits<int>::min(); for (const auto & b : me().Buildings(Terran_Machine_Shop)) if (!b->Completed()) if (b->RemainingBuildTime() > maxTimeToComplete) { pSecondShop = b.get(); maxTimeToComplete = b->RemainingBuildTime(); } if (pSecondShop && (maxTimeToComplete > 150)) if (pSecondShop->CanAcceptCommand()) return pSecondShop->CancelConstruction(); } // recrut SCVs to defend the base if (Mining::Instances().size() >= 8) for (const auto & u : him().Units()) if (!u->InFog()) if (u->Is(Protoss_Dragoon)) if (u->GetArea() == me().GetArea()) if (u->Chasers().empty()) { multimap<int, My<Terran_SCV> *> Candidates; for (My<Terran_SCV> * pSCV : me().StartingVBase()->GetStronghold()->SCVs()) if (pSCV->Completed() && !pSCV->Loaded()) if (pSCV->Life() >= 51) if (!pSCV->GetBehavior()->IsConstructing()) if (!pSCV->GetBehavior()->IsChasing()) if (!pSCV->GetBehavior()->IsWalking()) if (!(pSCV->GetBehavior()->IsRepairing() && pSCV->GetBehavior()->IsRepairing()->TargetX() && pSCV->GetBehavior()->IsRepairing()->TargetX()->Is(Terran_Siege_Tank_Siege_Mode) )) Candidates.emplace(squaredDist(u->Pos(), pSCV->Pos()), pSCV); if (Candidates.size() >= 4) { auto end = Candidates.begin(); advance(end, 4); for (auto it = Candidates.begin() ; it != end ; ++it) it->second->ChangeBehavior<Chasing>(it->second, u.get(), bool("insist")); return; } } } else { if (detectedCondition) { // ai()->SetDelay(100); m_detected = true; m_detetedSince = ai()->Frame(); return; } } } } // namespace iron
29.16875
119
0.542104
biug
0d379247b97b73eac4abdc3d36592d60952b93f1
4,355
cpp
C++
network/server/main.cpp
jklim1253/code-draft
32ff5e7969f2bdcc6063fb978c7070629aa568f4
[ "MIT" ]
1
2015-12-14T12:02:04.000Z
2015-12-14T12:02:04.000Z
network/server/main.cpp
jklim1253/code-draft
32ff5e7969f2bdcc6063fb978c7070629aa568f4
[ "MIT" ]
null
null
null
network/server/main.cpp
jklim1253/code-draft
32ff5e7969f2bdcc6063fb978c7070629aa568f4
[ "MIT" ]
null
null
null
#define _WIN32_WINNT 0x0601 #include <list> #include <thread> #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #pragma pack(1) using namespace boost::asio; struct Header { unsigned long marker; unsigned long data_type; unsigned long data_size; }; struct Data { //unsigned long marker; //unsigned long data_type; std::shared_ptr<unsigned char> buffer; }; struct Packet { Header header; Data data; void encode() { header.marker = 0x01020304; //data.marker = 0x04030201; } bool is_valid() const { return header_valid(); } private : bool header_valid() const { unsigned long validation = 0x01020304; if (::memcmp(&header.marker, &validation, sizeof(unsigned long)) == 0) { return true; } return false; } }; struct Session { std::shared_ptr<ip::tcp::socket> socket; Packet packet; }; class Server { public : Server(io_service& ios) : ios_(ios), acceptor_(ios), BACKLOG(5) { } void open(const unsigned short& port_num) { // requirement of server open // endpoint - host, all-ip, specific-port // socket // acceptor ip::tcp::endpoint ep(ip::tcp::v4(), port_num); acceptor_.open(ep.protocol()); acceptor_.bind(ep); acceptor_.listen(BACKLOG); std::cout << acceptor_.local_endpoint().address().to_string() << ":" << acceptor_.local_endpoint().port() << " listening..." << std::endl; accept(); } void run() { ios_.run(); } void close() { } private : void accept() { std::shared_ptr<Session> session(std::make_shared<Session>()); std::shared_ptr<ip::tcp::socket> socket(std::make_shared<ip::tcp::socket>(ios_)); session->socket = socket; acceptor_.async_accept(*socket, boost::bind(&Server::accept_handler, this, boost::placeholders::_1, session)); } void receive(std::shared_ptr<Session>& session) { ip::tcp::socket& socket = *(session->socket); // asynchronously receive header. socket.async_receive(buffer((char*)&session->packet.header, sizeof(Packet)), boost::bind(&Server::receive_header_handler, this, boost::placeholders::_1, boost::placeholders::_2, session)); } void send(std::shared_ptr<Session>& session) { } void accept_handler(const boost::system::error_code& e, std::shared_ptr<Session>& session) { if (e.value() != 0) { std::cerr << "ACCEPT ERROR[" << e.value() << "] " << e.message() << std::endl; return; } const ip::tcp::endpoint& remote = session->socket->remote_endpoint(); std::cout << remote.address().to_string() << ":" << remote.port() << " connected." << std::endl; sessionlist.push_back(session); receive(session); accept(); } void receive_header_handler(const boost::system::error_code& e, std::size_t read_size, std::shared_ptr<Session>& session) { if (e.value() != 0) { std::cerr << "RECEIVE HEADER ERROR[" << e.value() << "] " << e.message() << std::endl; return; } // check marker of header. if (!session->packet.is_valid()) { std::cerr << "INVALID MARKER" << std::endl; return; } // check data type. (not yet) // prepare buffer. session->packet.data.buffer = std::shared_ptr<unsigned char>(new unsigned char[session->packet.header.data_size], std::default_delete<unsigned char[]>()); // asynchronously receive data session->socket->async_receive(boost::asio::buffer((char*)session->packet.data.buffer.get(), session->packet.header.data_size), boost::bind(&Server::receive_data_handler, this, boost::placeholders::_1, boost::placeholders::_2, session)); } void receive_data_handler(const boost::system::error_code& e, std::size_t read_size, std::shared_ptr<Session>& session) { if (e.value() != 0) { std::cerr << "RECEIVE DATA ERROR[" << e.value() << "] " << e.message() << std::endl; return; } // notify. const ip::tcp::endpoint& remote = session->socket->remote_endpoint(); std::string msg(session->packet.data.buffer.get(), session->packet.data.buffer.get() + session->packet.header.data_size); std::cout << remote.address().to_string() << ":" << remote.port() << " > " << msg << std::endl; receive(session); } private : boost::asio::io_service& ios_; boost::asio::ip::tcp::acceptor acceptor_; int BACKLOG; std::list<std::shared_ptr<Session>> sessionlist; }; int main(void) { boost::asio::io_service ios; Server server(ios); unsigned short port_num(33333); server.open(port_num); server.run(); return 0; }
28.279221
156
0.671871
jklim1253
0d3956eac9a46d6b369a00c353fcda350ac0c465
24,993
cpp
C++
src/mainwindow.cpp
mguludag/GUI-for-GoodbyeDPI
e0c8201422dc231a13a09b1d649f5771a53bde3f
[ "MIT" ]
22
2019-12-21T07:54:46.000Z
2022-03-18T16:54:34.000Z
src/mainwindow.cpp
mguludag/GUI-for-GoodbyeDPI
e0c8201422dc231a13a09b1d649f5771a53bde3f
[ "MIT" ]
3
2019-12-06T17:31:48.000Z
2020-09-29T14:12:25.000Z
src/mainwindow.cpp
cheytacllc/GUI-for-GoodbyeDPI
e0c8201422dc231a13a09b1d649f5771a53bde3f
[ "MIT" ]
3
2018-10-30T14:46:22.000Z
2019-05-15T10:46:13.000Z
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QFile> #include <QFileInfo> #include <QFileInfoList> #include <QDirIterator> #include <QListIterator> #include <memory> #include <QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QSslConfiguration> #include <QDesktopServices> MainWindow::MainWindow(QStringList arguments, QWidget *parent) : QMainWindow(parent), ayarlar(new Settings()), settings(new QSettings("HexOpenSource", "GBDPI-GUI", this)), trayIcon(new QSystemTrayIcon(this)), trayMenu(new QMenu(this)), hideAction(new QAction(tr("Gizle"), this)), showAction(new QAction(tr("Göster"), this)), closeAction(new QAction(tr("Çıkış"), this)), startAction(new QAction(QIcon(":/images/images/play-button.png"), tr("Başlat"), this)), stopAction(new QAction(QIcon(":/images/images/stop-button.png"), tr("Durdur"), this)), settingsAction(new QAction(QIcon(":/images/images/256-256-setings-configuration.png"), tr("Ayarlar"), this)), updateAction(new QAction(QIcon(":/images/images/download-2-icon.png"), tr("Yeni sürüm bulundu!"), this)), tmpDir(new QTemporaryDir()), proc(new QProcess(this)), ui(new Ui::MainWindow) { ui->setupUi(this); QApplication::setApplicationVersion("1.1.9"); restoreGeometry(mySettings::readSettings("System/Geometry/Main").toByteArray()); restoreState(mySettings::readSettings("System/WindowState/Main").toByteArray()); mySettings::setTheme(mySettings::loadTheme()); setWindowTitle("GoodByeDPI GUI "+QApplication::applicationVersion()); setWindowIcon(QIcon(":/images/images/icon.ico")); trayIcon->setIcon(QIcon(":/images/images/stopped_icon.ico")); setWindowIcon(QIcon(":/images/images/stopped_icon.ico")); trayIcon->setToolTip("GoodByeDPI GUI "+QApplication::applicationVersion()); trayIcon->setVisible(true); trayIcon->show(); ui->labelParameters->setWordWrap(true); mySettings::writeSettings("Dir",QApplication::applicationDirPath()); //For using lambda functions with traymenu auto& traymn = trayMenu; //Setting traymenu actions. connect(startAction, &QAction::triggered, this, &MainWindow::procStart); connect(stopAction, &QAction::triggered, this, &MainWindow::procStop); connect(closeAction, &QAction::triggered, [this](){ QCoreApplication::quit(); }); connect(hideAction, &QAction::triggered, [this, traymn](){ this->hide(); traymn->actions().at(5)->setEnabled(false); traymn->actions().at(4)->setEnabled(true); }); connect(settingsAction, &QAction::triggered, this, &MainWindow::onActionAyarlar); connect(showAction, &QAction::triggered, [this, traymn](){ this->show(); traymn->actions().at(5)->setEnabled(true); traymn->actions().at(4)->setEnabled(false); }); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(RestoreWindowTrigger(QSystemTrayIcon::ActivationReason))); QList<QAction*> actionList; actionList << startAction << stopAction << settingsAction << showAction << hideAction << closeAction; trayMenu->addActions(actionList); trayMenu->insertSeparator(showAction); trayIcon->setContextMenu(trayMenu); trayIcon->show(); //Set false Stop and Hide actions trayMenu->actions().at(4)->setEnabled(false); trayMenu->actions().at(1)->setEnabled(false); connect(ui->actionAyarlar, &QAction::triggered, this, &MainWindow::onActionAyarlar); connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::onActionAbout); //Checking if default parameters enabled or not due to enable/disable parameters combo box. if(!settings->value("Parametre/defaultParam").toBool()) { ui->comboParametre->setEnabled(false); } if(settings->value("Version").toString().isEmpty()) { settings->setValue("Version",QApplication::applicationVersion()); } //Capturing state of default parameters checkbox for enable/disable parameters combo box. connect(ayarlar, &Settings::defaultParamStateChanged, this, &MainWindow::onDefaultParamCheckState, Qt::QueuedConnection); connect(ui->btnStart, &QPushButton::clicked, this, &MainWindow::procStart); connect(ui->btnStop, &QPushButton::clicked, this, &MainWindow::procStop); connect(proc, &QProcess::stateChanged, this, &MainWindow::handleState); ui->comboParametre->addItem("russia_blacklist", QVariant("-1 --blacklist blacklist.txt")); ui->comboParametre->addItem("russia_blacklist_dnsredir", QVariant("-1 --dns-addr 1.1.1.1 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253 --blacklist blacklist.txt")); ui->comboParametre->addItem("all", QVariant("-1")); ui->comboParametre->addItem(tr("all_dnsredir (Tavsiye Edilen)"), QVariant("-1 --dns-addr 1.1.1.1 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253")); ui->comboParametre->addItem("all_dnsredir_hardcore", QVariant("-1 -a -m --dns-addr 1.1.1.1 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253")); ui->comboParametre->setCurrentIndex(3); ui->btnStop->setEnabled(false); connect(ui->comboParametre, QOverload<int>::of(&QComboBox::currentIndexChanged), [this]() { prepareParameters(true); }); //Capturing ouput of goodbyedpi.exe connect(proc, &QProcess::readyReadStandardOutput, this, &MainWindow::processOutput); connect(proc, &QProcess::readyReadStandardError, this, &MainWindow::processError); if(settings->value("Parametre/defaultParam").toBool()) prepareParameters(true); else prepareParameters(false); if(!this->isVisible()) { hideAction->setEnabled(false); showAction->setEnabled(true); } connect(proc, &QProcess::errorOccurred, this, &MainWindow::catchError); if(settings->value("System/dnsMethod", "Registry").toString()=="Registry") { changeDns("", 0); } else { changeDns("dhcp.bat", 1); } timer(); ui->actionUpdate->setVisible(false); if(settings->value("System/UpdateCheck",true).toBool()) { QTimer::singleShot(500, this, SLOT(checkUpdate())); } taskKill("dnscrypt-proxy.exe"); taskKill("goodbyedpi.exe"); } MainWindow::~MainWindow() { if(proc->state()==QProcess::Running) procStop(); mySettings::writeSettings("System/Geometry/Main", saveGeometry()); mySettings::writeSettings("System/WindowState/Main", saveState()); delete ui; proc->kill(); } void MainWindow::closeEvent(QCloseEvent *event) { event->ignore(); MyMessageBox *msgBox=new MyMessageBox(); QPushButton *tray=msgBox->addButton(tr("Sistem Tepsisine Küçült"),QMessageBox::ActionRole); QPushButton *close=msgBox->addButton(tr("Kapat"),QMessageBox::ActionRole); QCheckBox *dontAsk = new QCheckBox(tr("Tekrar sorma"),this); msgBox->setIcon(QMessageBox::Information); msgBox->setText(tr("Programdan çıkmak ya da sistem tepsisine küçültmek mi istiyorsunuz?")); msgBox->setCheckBox(dontAsk); if(settings->value("System/dontAsk").isNull()) settings->setValue("System/dontAsk",false); if(settings->value("System/dontAsk").toBool()) { settings->setValue("System/dontAsk",true); if(settings->value("System/systemTray").toString() == "true" && (this->isTopLevel() || this->isVisible())) { this->hide(); trayIcon->show(); trayMenu->actions().at(4)->setEnabled(true); trayMenu->actions().at(5)->setEnabled(false); if(!settings->value("System/disableNotifications").toBool()) { qDebug() << "Message will shown"; QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(QSystemTrayIcon::Information); trayIcon->showMessage("GoodByeDPI GUI", tr("Arka planda çalışıyor."), icon, 1000); } } else { if(proc->state()==QProcess::Running) procStop(); ayarlar->close(); hakkinda.close(); event->accept(); } } else { msgBox->exec(); if(dontAsk->isChecked()) settings->setValue("System/dontAsk",true); if(msgBox->clickedButton()==tray) { settings->setValue("System/systemTray",true); this->hide(); trayIcon->show(); trayMenu->actions().at(4)->setEnabled(true); trayMenu->actions().at(5)->setEnabled(false); if(!settings->value("System/disableNotifications").toBool()) { qDebug() << "Message will shown"; QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(QSystemTrayIcon::Information); trayIcon->showMessage("GoodByeDPI GUI", tr("Arka planda çalışıyor."), icon, 1000); } } else { settings->setValue("System/systemTray",false); if(proc->state()==QProcess::Running) procStop(); ayarlar->close(); hakkinda.close(); event->accept(); } } } void MainWindow::timer() { QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(checkTime())); timer->start(10000); } void MainWindow::addItemListWidget() { int count=0; QString line; //ui->listWidget_2->addItem(QString(procDnsCrypt.readAll())); //ui->listWidget_2->addItem(QString::fromLocal8Bit(procDnsCrypt.readAll()).trimmed()); ui->listWidget_2->scrollToBottom(); line=QString::fromLocal8Bit(procDnsCrypt.readLine()).trimmed(); if(line.length()>10&&count<1) //.contains("live servers", Qt::CaseInsensitive) { ui->listWidget_2->addItem(line); // } else if(count>=30) { logtimer->stop(); //ui->listWidget_2->addItem(" "); } else { count++; } if(line.contains("FATAL", Qt::CaseInsensitive)) { taskKill("dnscrypt-proxy.exe"); taskKill("goodbyedpi.exe"); logtimer->stop(); procStop(); procStart(); } //if(ui->listWidget_2->item(ui->listWidget_2->count()-1)->text().contains("live servers", Qt::CaseInsensitive)) // logtimer->stop(); } void MainWindow::changeDns(QString dns, int control) { switch (control) { case 0: { for(int i=0; i<100; i++) { QSettings findAdapter("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards",QSettings::NativeFormat); if(!findAdapter.value(QString::number(i)+"/ServiceName").toString().isEmpty()) { QSettings dnsReg("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\"+findAdapter.value(QString::number(i)+"/ServiceName").toString().toLower(),QSettings::NativeFormat); if(!dnsReg.value("DhcpDefaultGateway").toString().isEmpty()) dnsReg.setValue("NameServer",dns); } } QProcess ipconfig; ipconfig.start("ipconfig /flushdns",QProcess::ReadOnly); ipconfig.waitForFinished(500); ipconfig.start("ipconfig /registerdns",QProcess::ReadOnly); ipconfig.waitForFinished(500); // ipconfig.close(); break; } case 1: { QProcess procDns; procDns.setNativeArguments("start /min "+QApplication::applicationDirPath()+"/dnscrypt-proxy/"+dns); procDns.start("cmd.exe /c ",QProcess::ReadOnly); procDns.waitForFinished(500); // procDns.close(); break; } default: break; } } void MainWindow::dnsCrypt(QString arg) { procDnsCrypt.setNativeArguments(arg); procDnsCrypt.setProcessChannelMode(QProcess::MergedChannels); procDnsCrypt.start(QApplication::applicationDirPath()+"/dnscrypt-proxy/"+QSysInfo::currentCpuArchitecture()+"/dnscrypt-proxy.exe",QProcess::ReadOnly); procDnsCrypt.waitForReadyRead(); //connect(this,SIGNAL(procDnsCrypt.readyRead()),SLOT(addItemListWidget())); } void MainWindow::procStart() { proc->setArguments(prepareParameters(ui->comboParametre->isEnabled())); proc->setProcessChannelMode(QProcess::MergedChannels); //ui->debugArea->appendPlainText("[*] " + ui->comboParametre->currentText()); //ui->debugArea->appendPlainText("Exe Path: " + QDir::currentPath() + "/goodbyedpi/goodbyedpi.exe"); proc->start(QApplication::applicationDirPath()+"/goodbyedpi/"+QSysInfo::currentCpuArchitecture()+"/goodbyedpi.exe", QProcess::ReadOnly); proc->waitForStarted(1000); if(!settings->value("System/disableNotifications").toBool()) { qDebug() << "Message will shown"; QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(QSystemTrayIcon::Information); trayIcon->showMessage("GoodByeDPI GUI", tr("Başlatıldı."), icon, 1000); } setWindowIcon(QIcon(":/images/images/icon.ico")); trayIcon->setIcon(QIcon(":/images/images/icon.ico")); if(settings->value("System/dnsMethod", "Registry").toString()=="Registry") { changeDns("127.0.0.1", 0); } else { changeDns("localhost.bat", 1); } dnsCrypt(""); } void MainWindow::procStop() { proc->close(); proc->waitForFinished(2000); if(!settings->value("System/disableNotifications").toBool()) { qDebug() << "Message will shown"; QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(QSystemTrayIcon::Information); trayIcon->showMessage("GoodByeDPI GUI", tr("Durduruldu."), icon, 1000); } trayIcon->setIcon(QIcon(":/images/images/stopped_icon.ico")); setWindowIcon(QIcon(":/images/images/stopped_icon.ico")); // dnsCrypt(" -service stop"); // dnsCrypt(" -service uninstall"); QProcess stopWinDivert; //stopWinDivert.setNativeArguments("sc stop windivert1.3"); stopWinDivert.start("sc stop windivert1.3", QProcess::ReadOnly); stopWinDivert.waitForFinished(500); procDnsCrypt.close(); if(settings->value("System/dnsMethod", "Registry").toString()=="Registry") { changeDns("", 0); } else { changeDns("dhcp.bat", 1); } ui->listWidget->scrollToBottom(); } void MainWindow::checkTime() { if(settings->value("System/systemSchedule").toBool()) { if(settings->value("System/D"+QString::number(QDate::currentDate().dayOfWeek())+"/Enabled").toBool()) { if((QTime::fromString(settings->value("System/D"+QString::number(QDate::currentDate().dayOfWeek())+"/systemScheduleStart").toString()).hour()<=QTime::currentTime().hour()&&QTime::fromString(settings->value("System/D"+QString::number(QDate::currentDate().dayOfWeek())+"/systemScheduleStart").toString()).minute()<=QTime::currentTime().minute())&&(QTime::fromString(settings->value("System/D"+QString::number(QDate::currentDate().dayOfWeek())+"/systemScheduleEnd").toString()).hour()>=QTime::currentTime().hour()&&QTime::fromString(settings->value("System/D"+QString::number(QDate::currentDate().dayOfWeek())+"/systemScheduleEnd").toString()).minute()>=QTime::currentTime().minute())) { if(proc->state()==QProcess::NotRunning) ui->btnStart->click(); } else if(proc->state()==QProcess::Running) ui->btnStop->click(); } } } void MainWindow::processOutput() { //proc->setReadChannel(QProcess::StandardOutput); QString output = proc->readAll(); if(!output.isEmpty()) { ui->listWidget->addItem(output); } ui->listWidget->scrollToBottom(); logtimer = new QTimer(this); logtimer->start(100); connect(logtimer, SIGNAL(timeout()), this, SLOT(addItemListWidget())); } void MainWindow::processError() { proc->setReadChannel(QProcess::StandardError); QString errout = proc->readAllStandardError(); if(!errout.isEmpty()) { ui->listWidget->addItem(proc->errorString()); } ui->listWidget->scrollToBottom(); } void MainWindow::handleState() { if(proc->state() == QProcess::NotRunning) { ui->listWidget->addItem(tr("[-] Durduruldu")); ui->btnStart->setEnabled(true); ui->btnStop->setEnabled(false); trayMenu->actions().at(1)->setEnabled(false); trayMenu->actions().at(0)->setEnabled(true); } else if(proc->state() == QProcess::Running) { ui->listWidget->addItem(tr("[+] Başlatıldı\n[+] PID:") + QString::number(proc->processId())); ui->btnStart->setEnabled(false); ui->btnStop->setEnabled(true); trayMenu->actions().at(0)->setEnabled(false); trayMenu->actions().at(1)->setEnabled(true); } ui->listWidget->scrollToBottom(); } void MainWindow::RestoreWindowTrigger(QSystemTrayIcon::ActivationReason RW) { if(RW == QSystemTrayIcon::DoubleClick) { if(this->isHidden()) { this->show(); this->activateWindow(); trayMenu->actions().at(5)->setEnabled(true); trayMenu->actions().at(4)->setEnabled(false); } else { this->hide(); trayMenu->actions().at(5)->setEnabled(false); trayMenu->actions().at(4)->setEnabled(true); } } } void MainWindow::onActionAyarlar() { ayarlar->show(); } void MainWindow::onActionAbout() { hakkinda.exec(); } void MainWindow::checkUpdate() { QString url = "https://cheytacllc.github.io/GUI-for-GoodbyeDPI/version.html"; QNetworkAccessManager manager; QNetworkRequest request; request.setSslConfiguration(QSslConfiguration::defaultConfiguration()); request.setUrl(QUrl(url)); QNetworkReply *response = manager.get(request); QEventLoop event; connect(response, SIGNAL(finished()), &event, SLOT(quit())); event.exec(); content = response->readAll(); if(content.trimmed()!=QApplication::applicationVersion()&&content.trimmed()!="") { ui->actionUpdate->setVisible(true); ui->actionUpdate->setText(ui->actionUpdate->text()+" v"+content.trimmed()); if(!settings->value("System/disableNotifications").toBool()) { qDebug() << "Message will shown"; QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(QSystemTrayIcon::Information); trayIcon->showMessage("GoodByeDPI GUI", tr("Yeni sürüm bulundu!")+" v"+content.trimmed(), icon, 1000); } } else { QTimer::singleShot(60000, this, SLOT(checkUpdate())); } //QTimer::singleShot(60000, this, SLOT(checkUpdate())); //QMessageBox::information(this,"New version found","<body><html><a href='https://github.com/cheytacllc/GUI-for-GoodbyeDPI/releases/download/"+content.trimmed()+"/GoodByeDPI_GUI.zip'>Click here to download new version</a></body></html>"); } void MainWindow::onDefaultParamCheckState(Qt::CheckState state) { if(state == Qt::Checked) { ui->comboParametre->setEnabled(true); prepareParameters(true); } else { ui->comboParametre->setEnabled(false); prepareParameters(false); } } void MainWindow::taskKill(QString arg) { QProcess killDns; killDns.start("TASKKILL /F /IM "+arg); //dnscrypt-proxy.exe killDns.waitForFinished(500); //goodbyedpi.exe killDns.close(); } QStringList MainWindow::prepareParameters(bool isComboParametreEnabled) { QStringList defaultparameters; QStringList customParameters; QStringList quickParameters; QStringList param2Box; QStringList param1Box; //PARAMBOX1 if(settings->value("Parametre/paramP").toBool()) param1Box << "-p"; if(settings->value("Parametre/paramR").toBool()) param1Box << "-r"; if(settings->value("Parametre/paramS").toBool()) param1Box << "-s"; if(settings->value("Parametre/paramM").toBool()) param1Box << "-m"; if(settings->value("Parametre/paramF").toString() != "false") param1Box << settings->value("Parametre/paramF").toString(); if(settings->value("Parametre/paramK").toString() != "false") param1Box << settings->value("Parametre/paramK").toString(); if(settings->value("Parametre/paramN").toBool()) param1Box << "-n"; if(settings->value("Parametre/paramE").toString() != "false") param1Box << settings->value("Parametre/paramE").toString(); if(settings->value("Parametre/paramA").toBool()) param1Box << "-a"; if(settings->value("Parametre/paramW").toBool()) param1Box << "-w"; if(settings->value("Parametre/paramPort").toString() != "false") param1Box << settings->value("Parametre/paramPort").toString(); if(settings->value("Parametre/paramIpId").toString() != "false") param1Box << settings->value("Parametre/paramIpId").toString(); //PARAMBOX2 if(settings->value("Parametre/paramDnsAddr").toString() != "false") param2Box << settings->value("Parametre/paramDnsAddr").toString(); if(settings->value("Parametre/paramDnsPort").toString() != "false") param2Box << settings->value("Parametre/paramDnsPort").toString(); if(settings->value("Parametre/paramDnsPort").toString() != "false") param2Box << settings->value("Parametre/paramDnsPort").toString(); if(settings->value("Parametre/paramDnsv6Addr").toString() != "false") param2Box << settings->value("Parametre/paramDnsv6Addr").toString(); if(settings->value("Parametre/paramDnsv6Port").toString() != "false") param2Box << settings->value("Parametre/paramDnsv6Port").toString(); if(settings->value("Parametre/paramBlacklist").toString() != "false") param2Box << "--blacklist blacklist.txt"; //QUICKSETTINGS if(settings->value("Parametre/paramQuick").toString() == "-1") quickParameters << "-p -r -s -f 2 -k 2 -n -e 2" << param2Box; if(settings->value("Parametre/paramQuick").toString() == "-2") quickParameters << "-p -r -s -f 2 -k 2 -n -e 40" << param2Box; else if(settings->value("Parametre/paramQuick").toString() == "-3") quickParameters << "-p -r -s -e 40" << param2Box; else if(settings->value("Parametre/paramQuick").toString() == "-4") quickParameters << "-p -r -s" << param2Box; //DEFAULTPARAMETERS switch (ui->comboParametre->currentIndex()) { case 0: defaultparameters << "-1 --blacklist blacklist.txt"; break; case 1: defaultparameters << "-1 --dns-addr 1.1.1.1 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253 --blacklist blacklist.txt"; break; case 2: defaultparameters << "-1"; break; case 3: defaultparameters << "-1 --dns-addr 1.1.1.1 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253"; break; case 4: defaultparameters << "-1 -a -m --dns-addr 1.1.1.1 --dns-port 1253 --dnsv6-addr 2a02:6b8::feed:0ff --dnsv6-port 1253"; } //CUSTOMPARAMETERS customParameters << param1Box << param2Box; //UPDATE Parameter Label if(isComboParametreEnabled) { ui->labelParameters->setText("goodbyedpi.exe " + defaultparameters.join(" ")); return defaultparameters; } else if(settings->value("Parametre/customParam").toString() == "true" && settings->value("Parametre/quickSettings").toString() == "false") { ui->labelParameters->setText("goodbyedpi.exe " + customParameters.join(" ")); return customParameters; } else if(settings->value("Parametre/customParam").toString() == "false" && settings->value("Parametre/quickSettings").toString() == "false") { ui->labelParameters->setText("goodbyedpi.exe"); return QStringList(); } else if(settings->value("Parametre/customParam").toString() == "true" && settings->value("Parametre/quickSettings").toString() == "true") { ui->labelParameters->setText("goodbyedpi.exe" + quickParameters.join(" ")); return QStringList(); } else { ui->labelParameters->setText("goodbyedpi.exe " + quickParameters.join(" ")); return quickParameters; } } void MainWindow::catchError(QProcess::ProcessError err) { ui->listWidget->addItem(proc->errorString()); ui->listWidget->scrollToBottom(); } void MainWindow::on_actionUpdate_triggered() { QProcess::startDetached("\"Updater.exe"); procStop(); QApplication::quit(); //this->close(); //QDesktopServices::openUrl(QUrl("https://github.com/cheytacllc/GUI-for-GoodbyeDPI/releases/download/"+content.trimmed()+"/GoodByeDPI_GUI.zip")); }
37.136701
694
0.639779
mguludag
0d3dfafef73f694ff40c8db169a0e4ac5a3fe371
4,300
cpp
C++
IvyProjects/IvyEngine/gl/GLMesh.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/IvyEngine/gl/GLMesh.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/IvyEngine/gl/GLMesh.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////// /// /// Ivy Engine /// /// Copyright 2012, Brandon Light /// All rights reserved. /// /////////////////////////////////////////////////////////////////////////////////////////////////// #include "GLMesh.h" #include "IvyGL.h" #include "GLShader.h" using namespace Ivy; /////////////////////////////////////////////////////////////////////////////////////////////////// /// GLMesh::GLMesh /////////////////////////////////////////////////////////////////////////////////////////////////// GLMesh::GLMesh() : m_glVertexBufferId(0), m_numVertices(0), m_glIndexBufferId(0), m_numIndices(0) { } /////////////////////////////////////////////////////////////////////////////////////////////////// /// GLMesh::~GLMesh /////////////////////////////////////////////////////////////////////////////////////////////////// GLMesh::~GLMesh() { } /////////////////////////////////////////////////////////////////////////////////////////////////// /// GLMesh::Create /////////////////////////////////////////////////////////////////////////////////////////////////// GLMesh* GLMesh::Create( IvyMeshCreateInfo* pMeshCreateInfo) ///< Mesh create info { GLuint vbId = 0; glGenBuffers(1, &vbId); glBindBuffer(GL_ARRAY_BUFFER, vbId); glBufferData(GL_ARRAY_BUFFER, pMeshCreateInfo->vertexSizeInBytes * pMeshCreateInfo->numVertices, pMeshCreateInfo->pVertexData, GL_STATIC_DRAW); GLMesh* pMesh = new GLMesh(); pMesh->m_glVertexBufferId = vbId; pMesh->m_numVertices = pMeshCreateInfo->numVertices; if (pMeshCreateInfo->numIndicies > 0 && pMeshCreateInfo->pIndexData) { GLuint ibId = 0; glGenBuffers(1, &ibId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, pMeshCreateInfo->numIndicies * 4, pMeshCreateInfo->pIndexData, GL_STATIC_DRAW); pMesh->m_glIndexBufferId = ibId; pMesh->m_numIndices = pMeshCreateInfo->numIndicies; } return pMesh; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// GLMesh::Destroy /////////////////////////////////////////////////////////////////////////////////////////////////// void GLMesh::Destroy() { if (m_glVertexBufferId > 0) { glDeleteBuffers(1, &m_glVertexBufferId); } delete this; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// GLMesh::Bind /////////////////////////////////////////////////////////////////////////////////////////////////// void GLMesh::Bind( GLProgram* pProgram) ///< Bind the mesh to the current program { ///@todo Need to invert the relationship of the GLMesh and the GLProgram GLint positionAttribLoc = glGetAttribLocation(pProgram->ProgramId(), "in_Position"); GLint colorAttribLoc = glGetAttribLocation(pProgram->ProgramId(), "in_Color"); GLint texAttribLoc = glGetAttribLocation(pProgram->ProgramId(), "in_Tex"); glBindAttribLocation(pProgram->ProgramId(), positionAttribLoc, "in_Position"); glBindAttribLocation(pProgram->ProgramId(), colorAttribLoc, "in_Color"); glBindAttribLocation(pProgram->ProgramId(), texAttribLoc, "in_Tex"); glVertexAttribPointer(positionAttribLoc, 3, GL_FLOAT, FALSE, sizeof(VertexPTN), 0); glEnableVertexAttribArray(positionAttribLoc); GLuint offset = 3*4; glVertexAttribPointer(texAttribLoc, 2, GL_FLOAT, FALSE, sizeof(VertexPTN), (const GLvoid*)offset); glEnableVertexAttribArray(texAttribLoc); offset = 5*4; glVertexAttribPointer(colorAttribLoc, 4, GL_FLOAT, FALSE, sizeof(VertexPTN), (const GLvoid*)offset); glEnableVertexAttribArray(colorAttribLoc); } /////////////////////////////////////////////////////////////////////////////////////////////////// /// GLMesh::Draw /////////////////////////////////////////////////////////////////////////////////////////////////// void GLMesh::Draw() { if (m_glIndexBufferId > 0) { glDrawElements(GL_TRIANGLES, m_numIndices, GL_UNSIGNED_INT, NULL); } else { glDrawArrays(GL_TRIANGLES, 0, m_numVertices); } }
33.59375
125
0.460465
endy
0d3e542dc3637bf63d2636f433af4984ec872b82
2,562
cpp
C++
src/FastRoundStart.cpp
MrElectrify/BetteRCon
ecec11174c2aa90a142ef0169b00ad97af9a1068
[ "MIT" ]
2
2019-12-13T04:10:25.000Z
2021-10-29T21:26:07.000Z
src/FastRoundStart.cpp
MrElectrify/BetteRCon
ecec11174c2aa90a142ef0169b00ad97af9a1068
[ "MIT" ]
2
2019-12-26T05:31:46.000Z
2020-01-18T23:26:46.000Z
src/FastRoundStart.cpp
MrElectrify/BetteRCon
ecec11174c2aa90a142ef0169b00ad97af9a1068
[ "MIT" ]
null
null
null
#include <BetteRCon/Plugin.h> #ifdef _WIN32 // Windows stuff #include <Windows.h> #endif // Fast Round Start start the next round 30 seconds after the end of the last round class FastRoundStart : public BetteRCon::Plugin { public: FastRoundStart(BetteRCon::Server* pServer) : Plugin(pServer) { // every time server.onRoudOver fires, start a timer for 30 seconds later that will start the next round RegisterHandler("server.onRoundOver", std::bind(&FastRoundStart::HandleRoundOver, this, std::placeholders::_1)); // if the next level starts for some other reason (like an admin starts it) then cancel the current request RegisterHandler("server.onLevelLoaded", std::bind(&FastRoundStart::HandleLevelLoaded, this, std::placeholders::_1)); } virtual std::string_view GetPluginAuthor() const { return "MrElectrify"; } virtual std::string_view GetPluginName() const { return "FastRoundStart"; } virtual std::string_view GetPluginVersion() const { return "v1.0.1"; } void HandleRoundOver(const std::vector<std::string>& eventWords) { // unused (void)eventWords; m_cancelNextLevel = false; BetteRCon::Internal::g_stdOutLog << "[FastRoundStart]: Round is over. Scheduling command for 30 seconds from now\n"; // schedule the command for 30 seconds from now ScheduleAction( [this] { // the next round was started! abort! if (m_cancelNextLevel == true) return; SendCommand({ "mapList.runNextRound" }, [](const BetteRCon::Server::ErrorCode_t& ec, const std::vector<std::string>& responseWords) { if (ec) { BetteRCon::Internal::g_stdErrLog << "[FastRoundStart]: Error running next round: " << ec.message() << '\n'; return; } if (responseWords.front() != "OK") { BetteRCon::Internal::g_stdErrLog << "[FastRoundStart]: Bad response while running next round: " << responseWords.front() << '\n'; return; } BetteRCon::Internal::g_stdOutLog << "[FastRoundStart]: Ran next round successfully\n"; }); }, 11000); } void HandleLevelLoaded(const std::vector<std::string>& eventWords) { // unused (void)eventWords; // cancel any in-progress timer m_cancelNextLevel = true; } virtual ~FastRoundStart() {} private: bool m_cancelNextLevel; }; PLUGIN_EXPORT FastRoundStart* CreatePlugin(BetteRCon::Server* pServer) { return new FastRoundStart(pServer); } PLUGIN_EXPORT void DestroyPlugin(FastRoundStart* pPlugin) { delete pPlugin; } #ifdef _WIN32 BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReserved, LPVOID lpReserved) { return TRUE; } #endif
27.548387
134
0.712334
MrElectrify
0d42ea9256d7ab1c5a0a196ca8f8e81d5ee7361d
2,815
cpp
C++
Algorithm_C/Algorithm_C/First/MaxValueOfGifts/MaxValueOfGifts.cpp
chm994483868/HMDailyLearningRecord
95ff0a5347927ce4527bcdd70374e5be22bfc60d
[ "MIT" ]
2
2021-06-26T08:07:04.000Z
2021-08-03T06:05:40.000Z
Algorithm_C/Algorithm_C/First/MaxValueOfGifts/MaxValueOfGifts.cpp
chm994483868/HMDailyLearningRecord
95ff0a5347927ce4527bcdd70374e5be22bfc60d
[ "MIT" ]
null
null
null
Algorithm_C/Algorithm_C/First/MaxValueOfGifts/MaxValueOfGifts.cpp
chm994483868/HMDailyLearningRecord
95ff0a5347927ce4527bcdd70374e5be22bfc60d
[ "MIT" ]
null
null
null
// // MaxValueOfGifts.cpp // Algorithm_C // // Created by CHM on 2020/7/23. // Copyright © 2020 CHM. All rights reserved. // #include "MaxValueOfGifts.hpp" int getMaxValue_Solution1(const int* values, int rows, int cols) { if (values == nullptr || rows <= 0 || cols <= 0) { return 0; } int** maxValues = new int*[rows]; for (int i = 0; i < rows; ++i) { maxValues[i] = new int[cols]; } for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { int left = 0; int up = 0; if (i > 0) { up = maxValues[i - 1][j]; } if (j > 0) { left = maxValues[i][j - 1]; } // 用 maxValues[i][j] 来记录 [i][j] 节点,从 up 或 left 过来时和的最大值 maxValues[i][j] = std::max(left, up) + values[i * cols + j]; } } int maxValue = maxValues[rows - 1][cols - 1]; for (int i = 0; i < rows; ++i) { delete [] maxValues[i]; } delete [] maxValues; return maxValue; } int getMaxValue_Solution2(const int* values, int rows, int cols) { if (values == nullptr || rows <= 0 || cols <= 0) { return 0; } int* maxValues = new int[cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { int left = 0; int up = 0; if (i > 0) { up = maxValues[j]; } if (j > 0) { left = maxValues[j - 1]; } maxValues[j] = std::max(left, up) + values[i * cols + j]; } } int maxValue = maxValues[cols - 1]; delete [] maxValues; return maxValue; } namespace MaxValueOfGifts_Review { int getMaxValue_solution1(const int* values, int rows, int cols) { if (values == nullptr || rows <= 0 || cols <= 0) { return 0; } // 记录每个节点 从 up 和 left 过来时和当前节点的和的最大值 int** maxValues = new int*[rows]; for (int i = 0; i < rows; ++i) { maxValues[i] = new int[cols]; } for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { int left = 0; int up = 0; // 当前的节点的上面节点 if (i > 0) { up = maxValues[i - 1][j]; } // 当前节点的左面节点 if (j > 0) { left = maxValues[i][j - 1]; } maxValues[i][j] = std::max(left, up) + values[i * cols + j]; } } int maxValue = maxValues[rows - 1][cols - 1]; for (int i = 0; i < rows; ++i) { delete [] maxValues[i]; } delete [] maxValues; return maxValue; } }
23.655462
72
0.419183
chm994483868
0d42fabaacaf1f325308e1d3623c8bec86a09f73
1,560
cpp
C++
src/Hola_DX12/src/Base/ResourceViewHeaps.cpp
dfnzhc/Hola
d0fd46e9966baafd03c994e49efaa3dd8057309e
[ "MIT" ]
null
null
null
src/Hola_DX12/src/Base/ResourceViewHeaps.cpp
dfnzhc/Hola
d0fd46e9966baafd03c994e49efaa3dd8057309e
[ "MIT" ]
null
null
null
src/Hola_DX12/src/Base/ResourceViewHeaps.cpp
dfnzhc/Hola
d0fd46e9966baafd03c994e49efaa3dd8057309e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ResourceViewHeaps.h" #include "Device.h" namespace HOLA_DX12 { //-------------------------------------------------------------------------------------- // OnCreate //-------------------------------------------------------------------------------------- void StaticResourceViewHeap::OnCreate(Device* pDevice, D3D12_DESCRIPTOR_HEAP_TYPE heapType, uint32_t descriptorCount, bool forceCPUVisible) { m_descriptorCount = descriptorCount; m_index = 0; m_descriptorElementSize = pDevice->GetDevice()->GetDescriptorHandleIncrementSize(heapType); D3D12_DESCRIPTOR_HEAP_DESC descHeap; descHeap.NumDescriptors = descriptorCount; descHeap.Type = heapType; descHeap.Flags = ((heapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV) || (heapType == D3D12_DESCRIPTOR_HEAP_TYPE_DSV)) ? D3D12_DESCRIPTOR_HEAP_FLAG_NONE : D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; if (forceCPUVisible) { descHeap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; } descHeap.NodeMask = 0; ThrowIfFailed( pDevice->GetDevice()->CreateDescriptorHeap(&descHeap, IID_PPV_ARGS(&m_pHeap)) ); SetName(m_pHeap, "StaticHeapDX12"); } //-------------------------------------------------------------------------------------- // OnDestroy //-------------------------------------------------------------------------------------- void StaticResourceViewHeap::OnDestroy() { m_pHeap->Release(); } }
38.04878
198
0.521154
dfnzhc
0d4d1bb373485c691d815ec0056e0e4dec0cfb70
434
cpp
C++
Build/src/src/Utils/VertexArray.cpp
maz8569/OpenGLPAG
3c470a6824c0d3169fdc65691f697c2af39a6442
[ "MIT" ]
null
null
null
Build/src/src/Utils/VertexArray.cpp
maz8569/OpenGLPAG
3c470a6824c0d3169fdc65691f697c2af39a6442
[ "MIT" ]
null
null
null
Build/src/src/Utils/VertexArray.cpp
maz8569/OpenGLPAG
3c470a6824c0d3169fdc65691f697c2af39a6442
[ "MIT" ]
null
null
null
#include "Utils/VertexArray.h" using namespace GameEngine; GameEngine::VertexArray::VertexArray() { this->array_id = 0; glGenVertexArrays(1, &(this->array_id)); this->Bind(); } GameEngine::VertexArray::~VertexArray() { glDeleteVertexArrays(1, &(this->array_id)); this->Unbind(); } void GameEngine::VertexArray::Bind() { glBindVertexArray(this->array_id); } void GameEngine::VertexArray::Unbind() { glBindVertexArray(0); }
16.074074
44
0.721198
maz8569
0d4ecab757baafd25e2a8ec66095e23486a0a406
4,833
cpp
C++
dlls/asheep/baseweaponwiththrowablemonster.cpp
malortie/hl-asheep
58a402d5e1982b1b7b9476108d04856d0fdeb8b8
[ "Apache-2.0" ]
null
null
null
dlls/asheep/baseweaponwiththrowablemonster.cpp
malortie/hl-asheep
58a402d5e1982b1b7b9476108d04856d0fdeb8b8
[ "Apache-2.0" ]
6
2021-11-28T06:39:56.000Z
2021-12-31T13:59:26.000Z
dlls/asheep/baseweaponwiththrowablemonster.cpp
malortie/hl-asheep
58a402d5e1982b1b7b9476108d04856d0fdeb8b8
[ "Apache-2.0" ]
null
null
null
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "weapons.h" #include "nodes.h" #include "player.h" #include "soundent.h" #include "gamerules.h" void CBaseWeaponWithThrowableMonster::Spawn( ) { Precache( ); m_iId = GetWeaponID(); SetModel(); FallInit();//get ready to fall down. GiveFirstTimeSpawnDefaultAmmo(); pev->sequence = 1; pev->animtime = gpGlobals->time; pev->framerate = 1.0; } void CBaseWeaponWithThrowableMonster::Precache( void ) { PrecacheModels(); PrecacheSounds(); PrecacheEvents(); UTIL_PrecacheOther( GetClassnameOfMonsterToThrow() ); } int CBaseWeaponWithThrowableMonster::GetItemInfo(ItemInfo *p) { p->pszName = STRING(pev->classname); p->pszAmmo1 = "Snarks"; p->iMaxAmmo1 = SNARK_MAX_CARRY; p->pszAmmo2 = NULL; p->iMaxAmmo2 = -1; p->iMaxClip = WEAPON_NOCLIP; p->iSlot = 4; p->iPosition = 3; p->iId = m_iId = GetWeaponID(); p->iWeight = SNARK_WEIGHT; p->iFlags = ITEM_FLAG_LIMITINWORLD | ITEM_FLAG_EXHAUSTIBLE; return 1; } BOOL CBaseWeaponWithThrowableMonster::Deploy( ) { // play hunt sound PlayDeploySound(); m_pPlayer->m_iWeaponVolume = QUIET_GUN_VOLUME; return DefaultDeploy((char*)GetViewModel(), (char*)GetThirdpersonModel(), GetDeploySequence(), "squeak" ); } void CBaseWeaponWithThrowableMonster::Holster( int skiplocal /* = 0 */ ) { m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.5; if ( !m_pPlayer->m_rgAmmo[ m_iPrimaryAmmoType ] ) { m_pPlayer->pev->weapons &= ~(1<<GetWeaponID()); SetThink( &CBaseWeaponWithThrowableMonster::DestroyItem ); pev->nextthink = gpGlobals->time + 0.1; return; } DefaultHolster(GetHolsterSequence(), GetHolsterSequenceDuration(), skiplocal, 0); EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_WEAPON, "common/null.wav", 1.0, ATTN_NORM); } void CBaseWeaponWithThrowableMonster::PrimaryAttack() { if ( m_pPlayer->m_rgAmmo[ m_iPrimaryAmmoType ] ) { UTIL_MakeVectors( m_pPlayer->pev->v_angle ); TraceResult tr; Vector trace_origin; // HACK HACK: Ugly hacks to handle change in origin based on new physics code for players // Move origin up if crouched and start trace a bit outside of body ( 20 units instead of 16 ) trace_origin = m_pPlayer->pev->origin; if ( m_pPlayer->pev->flags & FL_DUCKING ) { trace_origin = trace_origin - ( VEC_HULL_MIN - VEC_DUCK_HULL_MIN ); } // find place to toss monster UTIL_TraceLine( trace_origin + gpGlobals->v_forward * 20, trace_origin + gpGlobals->v_forward * 64, dont_ignore_monsters, NULL, &tr ); int flags; #ifdef CLIENT_WEAPONS flags = FEV_NOTHOST; #else flags = 0; #endif PLAYBACK_EVENT_FULL( flags, m_pPlayer->edict(), GetThrowEvent(), 0.0, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0 ); if ( tr.fAllSolid == 0 && tr.fStartSolid == 0 && tr.flFraction > 0.25 ) { // player "shoot" animation m_pPlayer->SetAnimation( PLAYER_ATTACK1 ); #ifndef CLIENT_DLL CBaseEntity *pSqueak = CBaseEntity::Create((char*)GetClassnameOfMonsterToThrow(), tr.vecEndPos, m_pPlayer->pev->v_angle, m_pPlayer->edict() ); pSqueak->pev->velocity = gpGlobals->v_forward * GetTossVelocity() + m_pPlayer->pev->velocity; #endif // play hunt sound PlayHuntSound(); m_pPlayer->m_iWeaponVolume = QUIET_GUN_VOLUME; m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType]--; m_fJustThrown = 1; m_flNextPrimaryAttack = GetNextAttackDelay(GetFireRate()); m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + GetNextIdleAfterThrow(); } } } void CBaseWeaponWithThrowableMonster::SecondaryAttack( void ) { } void CBaseWeaponWithThrowableMonster::WeaponIdle( void ) { if ( m_flTimeWeaponIdle > UTIL_WeaponTimeBase() ) return; if (m_fJustThrown) { m_fJustThrown = 0; if ( !m_pPlayer->m_rgAmmo[PrimaryAmmoIndex()] ) { RetireWeapon(); return; } SendWeaponAnim( GetDeploySequence() ); m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + UTIL_SharedRandomFloat( m_pPlayer->random_seed, 10, 15 ); return; } float animDuration = PlayIdleAnimation(); m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + animDuration; } void CBaseWeaponWithThrowableMonster::SetModel() { SET_MODEL(ENT(pev), GetWorldModel()); } CBasePlayerWeaponUtil* CBaseWeaponWithThrowableMonster::GetSharedUtils() { static CBasePlayerWeaponUtil utilitySingleton; return &utilitySingleton; }
25.571429
145
0.725429
malortie
0d55431efaad4f2c47909f2b452ea860cacf8e4b
10,769
hpp
C++
ndn-cxx/util/time.hpp
Pesa/ndn-cxx
0249d71d97b2f1f5313f24cec7c84450a795f2ca
[ "OpenSSL" ]
106
2015-01-06T10:08:29.000Z
2022-02-27T13:40:16.000Z
ndn-cxx/util/time.hpp
Pesa/ndn-cxx
0249d71d97b2f1f5313f24cec7c84450a795f2ca
[ "OpenSSL" ]
6
2015-10-15T23:21:06.000Z
2016-12-20T19:03:10.000Z
ndn-cxx/util/time.hpp
Pesa/ndn-cxx
0249d71d97b2f1f5313f24cec7c84450a795f2ca
[ "OpenSSL" ]
147
2015-01-15T15:07:29.000Z
2022-02-03T13:08:43.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013-2021 Regents of the University of California. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #ifndef NDN_CXX_UTIL_TIME_HPP #define NDN_CXX_UTIL_TIME_HPP #include "ndn-cxx/detail/common.hpp" #include <boost/asio/wait_traits.hpp> #include <boost/chrono.hpp> namespace ndn { namespace time { template<typename Rep, typename Period> using duration = boost::chrono::duration<Rep, Period>; using boost::chrono::duration_cast; // C++20 using days = duration<int_fast32_t, boost::ratio<86400>>; using weeks = duration<int_fast32_t, boost::ratio<604800>>; using months = duration<int_fast32_t, boost::ratio<2629746>>; using years = duration<int_fast32_t, boost::ratio<31556952>>; // C++11 using hours = boost::chrono::hours; using minutes = boost::chrono::minutes; using seconds = boost::chrono::seconds; using milliseconds = boost::chrono::milliseconds; using microseconds = boost::chrono::microseconds; using nanoseconds = boost::chrono::nanoseconds; /** \return the absolute value of the duration d * \note The function does not participate in the overload resolution * unless std::numeric_limits<Rep>::is_signed is true. */ template<typename Rep, typename Period, typename = std::enable_if_t<std::numeric_limits<Rep>::is_signed>> constexpr duration<Rep, Period> abs(duration<Rep, Period> d) { return d >= d.zero() ? d : -d; } } // namespace time inline namespace literals { inline namespace time_literals { constexpr time::days operator "" _day(unsigned long long days) { return time::days{days}; } constexpr time::duration<long double, time::days::period> operator "" _day(long double days) { return time::duration<long double, time::days::period>{days}; } constexpr time::days operator "" _days(unsigned long long days) { return time::days{days}; } constexpr time::duration<long double, time::days::period> operator "" _days(long double days) { return time::duration<long double, time::days::period>{days}; } constexpr time::hours operator "" _h(unsigned long long hrs) { return time::hours{hrs}; } constexpr time::duration<long double, time::hours::period> operator "" _h(long double hrs) { return time::duration<long double, time::hours::period>{hrs}; } constexpr time::minutes operator "" _min(unsigned long long mins) { return time::minutes{mins}; } constexpr time::duration<long double, time::minutes::period> operator "" _min(long double mins) { return time::duration<long double, time::minutes::period>{mins}; } constexpr time::seconds operator "" _s(unsigned long long secs) { return time::seconds{secs}; } constexpr time::duration<long double, time::seconds::period> operator "" _s(long double secs) { return time::duration<long double, time::seconds::period>{secs}; } constexpr time::milliseconds operator "" _ms(unsigned long long msecs) { return time::milliseconds{msecs}; } constexpr time::duration<long double, time::milliseconds::period> operator "" _ms(long double msecs) { return time::duration<long double, time::milliseconds::period>{msecs}; } constexpr time::microseconds operator "" _us(unsigned long long usecs) { return time::microseconds{usecs}; } constexpr time::duration<long double, time::microseconds::period> operator "" _us(long double usecs) { return time::duration<long double, time::microseconds::period>{usecs}; } constexpr time::nanoseconds operator "" _ns(unsigned long long nsecs) { return time::nanoseconds{nsecs}; } constexpr time::duration<long double, time::nanoseconds::period> operator "" _ns(long double nsecs) { return time::duration<long double, time::nanoseconds::period>{nsecs}; } } // inline namespace time_literals } // inline namespace literals namespace time { using namespace literals::time_literals; /** * \brief System clock * * System clock represents the system-wide real time wall clock. * * It may not be monotonic: on most systems, the system time can be * adjusted at any moment. It is the only clock that has the ability * to be displayed and converted to/from UNIX timestamp. * * To get the current time: * * <code> * const auto now = system_clock::now(); * </code> * * To convert a time_point to/from UNIX timestamp: * * <code> * system_clock::time_point time = ...; * uint64_t timestampInMilliseconds = toUnixTimestamp(time).count(); * system_clock::time_point time2 = fromUnixTimestamp(milliseconds(timestampInMilliseconds)); * </code> */ class system_clock { public: using duration = boost::chrono::system_clock::duration; using rep = duration::rep; using period = duration::period; using time_point = boost::chrono::time_point<system_clock>; static constexpr bool is_steady = boost::chrono::system_clock::is_steady; using TimePoint = time_point; using Duration = duration; static time_point now() noexcept; static std::time_t to_time_t(const time_point& t) noexcept; static time_point from_time_t(std::time_t t) noexcept; }; /** * \brief Steady clock * * Steady clock represents a monotonic clock. The time points of this * clock cannot decrease as physical time moves forward. This clock is * not related to wall clock time, and is best suitable for measuring * intervals. */ class steady_clock { public: using duration = boost::chrono::steady_clock::duration; using rep = duration::rep; using period = duration::period; using time_point = boost::chrono::time_point<steady_clock>; static constexpr bool is_steady = true; using TimePoint = time_point; using Duration = duration; static time_point now() noexcept; private: /** * \brief Trait function used in detail::SteadyTimer to select proper waiting time * * Mock time implementations should return the minimum value to ensure * that Boost.Asio doesn't perform any waiting on mock timers. * * @sa http://blog.think-async.com/2007/08/time-travel.html */ static duration to_wait_duration(duration d); friend struct boost::asio::wait_traits<steady_clock>; // see steady-timer.hpp }; /** * \brief Return a system_clock::time_point representing the UNIX time epoch, * i.e., 00:00:00 UTC on 1 January 1970. */ const system_clock::time_point& getUnixEpoch(); /** * \brief Convert system_clock::time_point to UNIX timestamp */ milliseconds toUnixTimestamp(const system_clock::time_point& point); /** * \brief Convert UNIX timestamp to system_clock::time_point */ system_clock::time_point fromUnixTimestamp(milliseconds duration); /** * \brief Convert to the ISO 8601 string representation, basic format (`YYYYMMDDTHHMMSS,fffffffff`). * * If \p timePoint does not contain any fractional seconds, the output format is `YYYYMMDDTHHMMSS`. * * Examples: * * - with fractional nanoseconds: 20020131T100001,123456789 * - with fractional microseconds: 20020131T100001,123456 * - with fractional milliseconds: 20020131T100001,123 * - without fractional seconds: 20020131T100001 */ std::string toIsoString(const system_clock::time_point& timePoint); /** * \brief Convert from the ISO 8601 basic string format (`YYYYMMDDTHHMMSS,fffffffff`) * to the internal time format. * * Examples of accepted strings: * * - with fractional nanoseconds: 20020131T100001,123456789 * - with fractional microseconds: 20020131T100001,123456 * - with fractional milliseconds: 20020131T100001,123 * - without fractional seconds: 20020131T100001 */ system_clock::time_point fromIsoString(const std::string& isoString); /** * \brief Convert to the ISO 8601 string representation, extended format (`YYYY-MM-DDTHH:MM:SS,fffffffff`). */ std::string toIsoExtendedString(const system_clock::time_point& timePoint); /** * \brief Convert from the ISO 8601 extended string format (`YYYY-MM-DDTHH:MM:SS,fffffffff`) * to the internal time format. */ system_clock::time_point fromIsoExtendedString(const std::string& isoString); /** * \brief Convert time point to string with specified format. * * By default, `%Y-%m-%d %H:%M:%S` is used, producing dates like * `2014-04-10 22:51:00` * * \param timePoint time point of system_clock * \param format desired output format (default: `%Y-%m-%d %H:%M:%S`) * \param locale desired locale (default: "C" locale) * * \sa https://www.boost.org/doc/libs/1_65_1/doc/html/date_time/date_time_io.html#date_time.format_flags * describes possible formatting flags **/ std::string toString(const system_clock::time_point& timePoint, const std::string& format = "%Y-%m-%d %H:%M:%S", const std::locale& locale = std::locale("C")); /** * \brief Convert from string of specified format into time point. * * By default, `%Y-%m-%d %H:%M:%S` is used, accepting dates like * `2014-04-10 22:51:00` * * \param timePointStr string representing time point * \param format input output format (default: `%Y-%m-%d %H:%M:%S`) * \param locale input locale (default: "C" locale) * * \sa https://www.boost.org/doc/libs/1_65_1/doc/html/date_time/date_time_io.html#date_time.format_flags * describes possible formatting flags */ system_clock::time_point fromString(const std::string& timePointStr, const std::string& format = "%Y-%m-%d %H:%M:%S", const std::locale& locale = std::locale("C")); } // namespace time } // namespace ndn namespace boost { namespace chrono { template<typename CharT> struct clock_string<ndn::time::system_clock, CharT> { static std::basic_string<CharT> since(); }; template<typename CharT> struct clock_string<ndn::time::steady_clock, CharT> { static std::basic_string<CharT> since(); }; extern template struct clock_string<ndn::time::system_clock, char>; extern template struct clock_string<ndn::time::steady_clock, char>; } // namespace chrono } // namespace boost #endif // NDN_CXX_UTIL_TIME_HPP
28.489418
107
0.72263
Pesa
0d583f2e92779d3d274bb6a86a07288cbb8d1cb2
4,598
hpp
C++
Lib/Chip/STM32F469.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/STM32F469.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/STM32F469.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> #include <Chip/CM4/STMicro/STM32F469/RNG.hpp> #include <Chip/CM4/STMicro/STM32F469/HASH.hpp> #include <Chip/CM4/STMicro/STM32F469/CRYP.hpp> #include <Chip/CM4/STMicro/STM32F469/DCMI.hpp> #include <Chip/CM4/STMicro/STM32F469/FMC.hpp> #include <Chip/CM4/STMicro/STM32F469/DBG.hpp> #include <Chip/CM4/STMicro/STM32F469/DMA2.hpp> #include <Chip/CM4/STMicro/STM32F469/DMA1.hpp> #include <Chip/CM4/STMicro/STM32F469/RCC.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOK.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOJ.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOI.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOH.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOG.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOF.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOE.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOD.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOC.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOB.hpp> #include <Chip/CM4/STMicro/STM32F469/GPIOA.hpp> #include <Chip/CM4/STMicro/STM32F469/SYSCFG.hpp> #include <Chip/CM4/STMicro/STM32F469/SPI1.hpp> #include <Chip/CM4/STMicro/STM32F469/SPI2.hpp> #include <Chip/CM4/STMicro/STM32F469/SPI3.hpp> #include <Chip/CM4/STMicro/STM32F469/I2S2ext.hpp> #include <Chip/CM4/STMicro/STM32F469/I2S3ext.hpp> #include <Chip/CM4/STMicro/STM32F469/SPI4.hpp> #include <Chip/CM4/STMicro/STM32F469/SPI5.hpp> #include <Chip/CM4/STMicro/STM32F469/SPI6.hpp> #include <Chip/CM4/STMicro/STM32F469/SDIO.hpp> #include <Chip/CM4/STMicro/STM32F469/ADC1.hpp> #include <Chip/CM4/STMicro/STM32F469/ADC2.hpp> #include <Chip/CM4/STMicro/STM32F469/ADC3.hpp> #include <Chip/CM4/STMicro/STM32F469/USART6.hpp> #include <Chip/CM4/STMicro/STM32F469/USART1.hpp> #include <Chip/CM4/STMicro/STM32F469/USART2.hpp> #include <Chip/CM4/STMicro/STM32F469/USART3.hpp> #include <Chip/CM4/STMicro/STM32F469/UART7.hpp> #include <Chip/CM4/STMicro/STM32F469/UART8.hpp> #include <Chip/CM4/STMicro/STM32F469/DAC.hpp> #include <Chip/CM4/STMicro/STM32F469/PWR.hpp> #include <Chip/CM4/STMicro/STM32F469/IWDG.hpp> #include <Chip/CM4/STMicro/STM32F469/WWDG.hpp> #include <Chip/CM4/STMicro/STM32F469/RTC.hpp> #include <Chip/CM4/STMicro/STM32F469/UART4.hpp> #include <Chip/CM4/STMicro/STM32F469/UART5.hpp> #include <Chip/CM4/STMicro/STM32F469/C_ADC.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM1.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM8.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM2.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM3.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM4.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM5.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM9.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM12.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM10.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM13.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM14.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM11.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM6.hpp> #include <Chip/CM4/STMicro/STM32F469/TIM7.hpp> #include <Chip/CM4/STMicro/STM32F469/Ethernet_MAC.hpp> #include <Chip/CM4/STMicro/STM32F469/Ethernet_MMC.hpp> #include <Chip/CM4/STMicro/STM32F469/Ethernet_PTP.hpp> #include <Chip/CM4/STMicro/STM32F469/Ethernet_DMA.hpp> #include <Chip/CM4/STMicro/STM32F469/CRC.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_FS_GLOBAL.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_FS_HOST.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_FS_DEVICE.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_FS_PWRCLK.hpp> #include <Chip/CM4/STMicro/STM32F469/CAN1.hpp> #include <Chip/CM4/STMicro/STM32F469/CAN2.hpp> #include <Chip/CM4/STMicro/STM32F469/NVIC.hpp> #include <Chip/CM4/STMicro/STM32F469/FLASH.hpp> #include <Chip/CM4/STMicro/STM32F469/EXTI.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_HS_GLOBAL.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_HS_HOST.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_HS_DEVICE.hpp> #include <Chip/CM4/STMicro/STM32F469/OTG_HS_PWRCLK.hpp> #include <Chip/CM4/STMicro/STM32F469/LTDC.hpp> #include <Chip/CM4/STMicro/STM32F469/SAI.hpp> #include <Chip/CM4/STMicro/STM32F469/DMA2D.hpp> #include <Chip/CM4/STMicro/STM32F469/I2C3.hpp> #include <Chip/CM4/STMicro/STM32F469/I2C2.hpp> #include <Chip/CM4/STMicro/STM32F469/I2C1.hpp> #include <Chip/CM4/STMicro/STM32F469/DSIHOST.hpp> #include <Chip/CM4/STMicro/STM32F469/QUADSPI.hpp> #include <Chip/CM4/STMicro/STM32F469/FPU.hpp> #include <Chip/CM4/STMicro/STM32F469/MPU.hpp> #include <Chip/CM4/STMicro/STM32F469/STK.hpp> #include <Chip/CM4/STMicro/STM32F469/SCB.hpp> #include <Chip/CM4/STMicro/STM32F469/NVIC_STIR.hpp> #include <Chip/CM4/STMicro/STM32F469/FPU_CPACR.hpp> #include <Chip/CM4/STMicro/STM32F469/SCB_ACTRL.hpp>
47.402062
55
0.793606
operativeF
0d5b14bd20b994875f7dd630688af9003a33790e
2,621
cpp
C++
state_feedback/src/encoder_data_to_omega.cpp
aslResearch/aslRover
eec6a772b90d18a38ac036773651c5b95eb4f22e
[ "BSD-3-Clause" ]
9
2017-09-22T06:31:47.000Z
2021-09-09T23:06:56.000Z
state_feedback/src/encoder_data_to_omega.cpp
aslResearch/aslRover
eec6a772b90d18a38ac036773651c5b95eb4f22e
[ "BSD-3-Clause" ]
null
null
null
state_feedback/src/encoder_data_to_omega.cpp
aslResearch/aslRover
eec6a772b90d18a38ac036773651c5b95eb4f22e
[ "BSD-3-Clause" ]
7
2018-09-12T10:36:05.000Z
2021-09-22T08:11:58.000Z
/** * @brief Encoder data to Angular velocity of wheel node * @file encoder_data_to_omega.cpp * @author Murali VNV <muralivnv@gmail.com> */ /* * Copyright (c) 2017, muralivnv * * This file is part of the asl_gremlin_package and subject to the license terms * in the top-level LICENSE file of the asl_gremlin_pkg repository. * https://github.com/muralivnv/asl_gremlin_pkg/blob/master/LICENSE */ #include <ros/ros.h> #include <std_msgs/Bool.h> #include <state_feedback/EncoderDataToOmega.h> #include <asl_gremlin_msgs/MotorAngVel.h> #include <asl_gremlin_pkg/SubscribeTopic.h> #include <cmath> #include <string> using namespace state_feedback; int main(int argc, char** argv) { ros::init(argc, argv, "encoder_data_to_omega"); ros::NodeHandle enco2w_nh; std::string actual_w_topic; if(!enco2w_nh.getParam("state_feedback/encoder/ang_vel_topic", actual_w_topic)) { actual_w_topic = "state_feedback/encoder/actual_ang_vel"; } ros::Publisher enco2w_pub = enco2w_nh.advertise<asl_gremlin_msgs::MotorAngVel>(actual_w_topic, 100); asl_gremlin_pkg::SubscribeTopic < std_msgs::Bool > sim(enco2w_nh, "start_sim"); EncoderDataToOmega encoder_data_to_omega(enco2w_nh); asl_gremlin_msgs::MotorAngVel motor_ang_vel; motor_ang_vel.header.frame_id = "none"; double rate = 10.0; if (!enco2w_nh.getParam("sim/rate", rate)) { ROS_WARN("Unable access parameter /%s/sim/rate, setting rate as 10Hz", ros::this_node::getNamespace().c_str()); } ros::Rate loop_rate(rate); int msg_count = 0; bool initiated = false; ROS_INFO("\033[1;32mInitialized\033[0;m:= %s",ros::this_node::getName().c_str()); while(ros::ok()) { if ( !initiated && (sim.get_data())->data ) { encoder_data_to_omega.update_encoder_starting_values(); ROS_INFO("\033[1;32mStarted\033[0;m:= Converting encoder ticks to angular velocity"); initiated = true; } if ( !(sim.get_data())->data && initiated) { ROS_INFO("\033[1;31mStopped\033[0;m:= Converting encoder ticks to angular velocity"); initiated = false; } encoder_data_to_omega.calculate_angular_velocities(); motor_ang_vel.wl = encoder_data_to_omega.get_left_wheel_angular_vel(); motor_ang_vel.wr = encoder_data_to_omega.get_right_wheel_angular_vel(); motor_ang_vel.header.seq = msg_count; motor_ang_vel.header.stamp = ros::Time::now(); enco2w_pub.publish(motor_ang_vel); ros::spinOnce(); loop_rate.sleep(); } }
32.7625
104
0.680275
aslResearch
0d5c153c0ec68340b2d7307d105924125396f2b7
3,786
hpp
C++
src/Switch.System.Windows.Forms/include/Switch/System/Windows/Forms/FileDialogCustomPlace.hpp
victor-timoshin/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
4
2020-02-11T13:22:58.000Z
2022-02-24T00:37:43.000Z
src/Switch.System.Windows.Forms/include/Switch/System/Windows/Forms/FileDialogCustomPlace.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
src/Switch.System.Windows.Forms/include/Switch/System/Windows/Forms/FileDialogCustomPlace.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
/// @file /// @brief Contains Switch::System::Windows::Forms::DragEventArgs class. #pragma once #include <Switch/System/Guid.hpp> #include "../../../SystemWindowsFormsExport.hpp" /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The Switch::System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The Switch::System::Windows namespaces including animation clients, user interface controls, data binding, and type conversion. Switch::System::Windows::Forms and its child namespaces are used for developing Windows Forms applications. namespace Windows { /// @brief The Switch::System::Windows::Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system, Apple macOS and Linux like Ubuntu operating system. namespace Forms { /// @brief Represents an entry in a FileDialog custom place collection for Windows Vista. /// @par Library /// Switch.System.Windows.Forms /// @remarks The default open and save dialog boxes on Windows Vista have an area on the left side of the dialog box titled Favorite Links. This area is called custom places. This class represents a custom place. /// @remarks On macOS, Linux, Windows XP and Windows Server 2003, this class does not have any effect. class system_windows_forms_export_ FileDialogCustomPlace : public object { public: /// @cond FileDialogCustomPlace() {} FileDialogCustomPlace(const FileDialogCustomPlace& fileDialogCustomPlace) : knownFolderGuid(fileDialogCustomPlace.knownFolderGuid), path(fileDialogCustomPlace.path) {} FileDialogCustomPlace& operator=(const FileDialogCustomPlace& fileDialogCustomPlace) = default; /// @endcond /// @brief Initializes a new instance of the FileDialogCustomPlace class with a custom place identified by a Windows Vista Known Folder GUID. /// @param knownFolderGuid A Guid that represents a Windows Vista Known Folder. explicit FileDialogCustomPlace(const Guid& knownFolderGuid) : knownFolderGuid(knownFolderGuid) {} /// @brief Initializes a new instance of the FileDialogCustomPlace class. with a specified folder path to a custom place. /// @param path A folder path to the custom place. explicit FileDialogCustomPlace(const string& path) : path(path) {} /// @brief Gets or sets the Windows Vista Known Folder GUID for the custom place. /// @return Guid A Guid that indicates the Windows Vista Known Folder for the custom place. If the custom place was specified with a folder path, then an empty GUID is returned. For a list of the available Windows Vista Known Folders, see Known Folder GUIDs for File Dialog Custom Places or the KnownFolders.h file in the Windows SDK. property_<Guid> KnownFolderGuid { get_ {return this->knownFolderGuid;}, set_ {this->knownFolderGuid = value;} }; /// @brief Gets or sets the folder path to the custom place. /// @return string A folder path to the custom place. If the custom place was specified with a Windows Vista Known Folder GUID, then an empty string is returned. property_<string> Path { get_ {return this->path;}, set_ {this->path = value;} }; private: Guid knownFolderGuid; string path; }; } } } }
63.1
344
0.709984
victor-timoshin
0d60fb458e5fc98ff249e0802beaf8d4bfeb56b4
1,484
hpp
C++
source/problem/SWE/discretization_EHDG/data_structure/ehdg_swe_data_slope_limit.hpp
elenabac/dgswemv2
ecc776811de304cbae7bfa696b3d22c513e7d4de
[ "MIT" ]
null
null
null
source/problem/SWE/discretization_EHDG/data_structure/ehdg_swe_data_slope_limit.hpp
elenabac/dgswemv2
ecc776811de304cbae7bfa696b3d22c513e7d4de
[ "MIT" ]
null
null
null
source/problem/SWE/discretization_EHDG/data_structure/ehdg_swe_data_slope_limit.hpp
elenabac/dgswemv2
ecc776811de304cbae7bfa696b3d22c513e7d4de
[ "MIT" ]
null
null
null
#ifndef EHDG_SWE_DATA_SLOPE_LIMIT_HPP #define EHDG_SWE_DATA_SLOPE_LIMIT_HPP namespace SWE { namespace EHDG { struct SlopeLimit { SlopeLimit() = default; SlopeLimit(const uint nvrtx, const uint nbound) : surface_normal(nbound), midpts_coord(nbound), baryctr_coord_neigh(nbound), alpha_1(nbound), alpha_2(nbound), r_sq(nbound), q_lin(SWE::n_variables, nvrtx), q_at_vrtx(SWE::n_variables, nvrtx), q_at_midpts(SWE::n_variables, nbound), bath_at_vrtx(nvrtx), bath_at_midpts(nbound), wet_neigh(nbound), q_at_baryctr_neigh(nbound), delta(SWE::n_variables, nbound) {} AlignedVector<StatVector<double, SWE::n_dimensions>> surface_normal; Point<2> baryctr_coord; std::vector<Point<2>> midpts_coord; std::vector<Point<2>> baryctr_coord_neigh; std::vector<double> alpha_1; std::vector<double> alpha_2; std::vector<double> r_sq; HybMatrix<double, SWE::n_variables> q_lin; StatVector<double, SWE::n_variables> q_at_baryctr; HybMatrix<double, SWE::n_variables> q_at_vrtx; HybMatrix<double, SWE::n_variables> q_at_midpts; double bath_at_baryctr; DynRowVector<double> bath_at_vrtx; DynRowVector<double> bath_at_midpts; std::vector<bool> wet_neigh; AlignedVector<StatVector<double, SWE::n_variables>> q_at_baryctr_neigh; HybMatrix<double, SWE::n_variables> delta; }; } } #endif
28
75
0.680593
elenabac
0d6c177c8d14f1a74e08949c568d8fbec75343c9
1,148
hpp
C++
ArgumentProcessor/ArgumentProcessor.hpp
parsashahzeidi/Alton
f60e6898e7daf81d4e551a637475a5b21f62b1af
[ "BSL-1.0" ]
null
null
null
ArgumentProcessor/ArgumentProcessor.hpp
parsashahzeidi/Alton
f60e6898e7daf81d4e551a637475a5b21f62b1af
[ "BSL-1.0" ]
3
2020-02-26T20:39:03.000Z
2020-03-01T13:18:48.000Z
ArgumentProcessor/ArgumentProcessor.hpp
parsashahzeidi/Alton
f60e6898e7daf81d4e551a637475a5b21f62b1af
[ "BSL-1.0" ]
null
null
null
# pragma once # include <ETC/BareboneMacros.hpp> # include <ArgumentProcessor/arg_id.hpp> # include <ArgumentProcessor/Argument.hpp> # include <ArgumentProcessor/ArgumentState.hpp> # include <ArgumentProcessor/ArgumentHelper.hpp> namespace Alton { namespace ArgumentProcessor { class ArgumentProcessor { // --- Head private: ArgumentHelper h; // --- Body private: /** * BRIEF: Gets the arguments from argc and argv. */ ArgumentList _get_args(); /** * BRIEF: Reformats an ArgumentList into an ArgumentState * * The reason for not making ArgumentState-s in the first * place is that if some arguments have order-specialities, * we can easily find them by using _get_args. */ ArgumentState _reformat(ArgumentList in); public: /** * BRIEF: Processes the arguments in argv */ ArgumentState process(); // --- CTOR ~ DTOR public: // --- Constructor --- // -- Default constructor -- ArgumentProcessor() = delete; ArgumentProcessor(char** _argv, Natural argc); // --- Destructor --- // -- Default destructor -- ~ArgumentProcessor(); }; } }
20.5
63
0.659408
parsashahzeidi
0d73002a25983198f360a176d730202f30fb3c38
5,801
cpp
C++
slides/number-string/benchmarks/dtoa-random.cpp
dvirtz/slides
b69d6b74ee3dc9d1461297309e68bb387f571fe6
[ "MIT" ]
null
null
null
slides/number-string/benchmarks/dtoa-random.cpp
dvirtz/slides
b69d6b74ee3dc9d1461297309e68bb387f571fe6
[ "MIT" ]
null
null
null
slides/number-string/benchmarks/dtoa-random.cpp
dvirtz/slides
b69d6b74ee3dc9d1461297309e68bb387f571fe6
[ "MIT" ]
null
null
null
#include <benchmark/benchmark.h> #include <random> #include <algorithm> #include <fmt/format.h> #include <scn/scn.h> #if __has_include(<charconv>) #define HAS_X_CHARS #include <charconv> #endif #include <cmath> #include <cstdlib> #include <cstring> #include <iomanip> #include <sstream> #include <string_view> namespace imp { // https://github.com/dspinellis/unix-history-repo/blob/Research-V6/usr/source/iolib/ftoa.c void ftoa(double x, char* str, int prec, int format) { /* converts a floating point number to an ascii string */ /* x is stored into str, which should be at least 30 chars long */ int ie, i, k, ndig, fstyle; double y; // if (nargs() != 7) // IEHzap("ftoa "); ndig = (prec <= 0) ? 7 : (prec > 22 ? 23 : prec + 1); if (format == 'f' || format == 'F') fstyle = 1; else fstyle = 0; /* print in e format unless last arg is 'f' */ ie = 0; /* if x negative, write minus and reverse */ if (x < 0) { *str++ = '-'; x = -x; } /* put x in range 1 <= x < 10 */ if (x > 0.0) while (x < 1.0) { x *= 10.0; ie--; } while (x >= 10.0) { x = x / 10.0; ie++; } /* in f format, number of digits is related to size */ if (fstyle) ndig += ie; /* round. x is between 1 and 10 and ndig will be printed to right of decimal point so rounding is ... */ for (y = i = 1; i < ndig; i++) y = y / 10.; x += y / 2.; if (x >= 10.0) { x = 1.0; ie++; } /* repair rounding disasters */ /* now loop. put out a digit (obtain by multiplying by 10, truncating, subtracting) until enough digits out */ /* if fstyle, and leading zeros, they go out special */ if (fstyle && ie < 0) { *str++ = '0'; *str++ = '.'; if (ndig < 0) ie = ie - ndig; /* limit zeros if underflow */ for (i = -1; i > ie; i--) *str++ = '0'; } for (i = 0; i < ndig; i++) { k = x; *str++ = k + '0'; if (i == (fstyle ? ie : 0)) /* where is decimal point */ *str++ = '.'; x -= (y = k); x *= 10.0; } /* now, in estyle, put out exponent if not zero */ if (!fstyle && ie != 0) { *str++ = 'E'; if (ie < 0) { ie = -ie; *str++ = '-'; } for (k = 100; k > ie; k /= 10) ; for (; k > 0; k /= 10) { *str++ = ie / k + '0'; ie = ie % k; } } *str = '\0'; return; } struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { ftoa(d, result, precision, 'f'); } } dtoa; struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { [[maybe_unused]] auto res = ::gcvt(d, precision, result); } } gcvt; struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { std::snprintf(result, N, "%.*lf", precision, d); } } sprintf; struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { std::stringstream out; out.rdbuf()->pubsetbuf(result, N); out << std::setprecision(precision) << std::fixed << d; } } ostringstream; struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { std::ostringstream sst; sst << std::setprecision(static_cast<int>(precision)) << std::fixed; using Facet = std::num_put<char, char*>; static std::locale loc{std::locale::classic(), new Facet}; std::use_facet<Facet>(loc).put(result, sst, sst.fill(), d); } } num_put; struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { std::to_string(d).copy(result, N); } } to_string; #ifdef HAS_X_CHARS struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { std::to_chars(std::begin(result), std::end(result), d, std::chars_format::fixed, precision); } } to_chars; #endif struct { template<size_t N> void operator()(double d, char (&result)[N], int precision) { fmt::format_to(result, "{:.{}f}", d, precision); } } fmt; } const unsigned kVerifyRandomCount = 100000; const unsigned kIterationForRandom = 100; const unsigned kIterationPerDigit = 10; const unsigned kTrial = 10; const unsigned kPrecision = 17; template<typename T> class Rng { public: explicit Rng(unsigned seed = 0) : gen_{seed} {} T operator()() { return dist_(gen_); } private: std::mt19937 gen_; using dist = std::conditional_t<std::is_integral_v<T>, std::uniform_int_distribution<T>, std::uniform_real_distribution<T>>; dist dist_; }; class RandomData { public: static auto GetData() { static RandomData singleton; return singleton.mData; } static const size_t kCount = 1000; private: RandomData() { Rng<double> r; mData.reserve(kCount); std::generate_n(std::back_inserter(mData), kCount, [&r]{ double d; do { d = r(); } while (std::isnan(d) || std::isinf(d)); return d; }); } std::vector<double> mData; }; template<typename F> void BenchRandom(benchmark::State& state, F f, const std::string_view fname) { char buffer[256]; const auto data = RandomData::GetData(); size_t n = RandomData::kCount; for (auto&& _ : state) { for (auto&& d : data) { f(d, buffer, state.range(0)); } } } void Precision(benchmark::internal::Benchmark* b) { for (int64_t precision = 1; precision <= 17; precision++) { b->Arg(precision); } } #define BENCHMARK_RANDOM(Func) BENCHMARK_CAPTURE(BenchRandom, Func, imp::Func, #Func)->Name(#Func)->Apply(Precision) BENCHMARK_RANDOM(dtoa); BENCHMARK_RANDOM(gcvt); BENCHMARK_RANDOM(sprintf); BENCHMARK_RANDOM(ostringstream); BENCHMARK_RANDOM(num_put); BENCHMARK_RANDOM(to_string); #ifdef HAS_X_CHARS BENCHMARK_RANDOM(to_chars); #endif BENCHMARK_RANDOM(fmt); static void Noop(benchmark::State& state) { for (auto _ : state) benchmark::DoNotOptimize(0); } BENCHMARK(Noop); BENCHMARK_MAIN()`;
23.204
127
0.609895
dvirtz