blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
ea8c800d42321ed21b45649a3041d0382294cadc
6f05f7d5a67b6bb87956a22b988067ec772ba966
/data/test/cpp/6e0bc488c9dbd3144a9d4ab24420a3dd368dd88cAudioClip.cpp
6e0bc488c9dbd3144a9d4ab24420a3dd368dd88c
[ "MIT" ]
permissive
harshp8l/deep-learning-lang-detection
93b6d24a38081597c610ecf9b1f3b92c7d669be5
2a54293181c1c2b1a2b840ddee4d4d80177efb33
refs/heads/master
2020-04-07T18:07:00.697994
2018-11-29T23:21:23
2018-11-29T23:21:23
158,597,498
0
0
MIT
2018-11-21T19:36:42
2018-11-21T19:36:41
null
UTF-8
C++
false
false
1,757
cpp
6e0bc488c9dbd3144a9d4ab24420a3dd368dd88cAudioClip.cpp
#include "AudioClip.h" #include <format.h> using std::invalid_argument; TimeRange AudioClip::getTruncatedRange() const { return TimeRange(0_cs, centiseconds(100 * size() / getSampleRate())); } class SafeSampleReader { public: SafeSampleReader(SampleReader unsafeRead, AudioClip::size_type size); AudioClip::value_type operator()(AudioClip::size_type index); private: SampleReader unsafeRead; AudioClip::size_type size; AudioClip::size_type lastIndex = -1; AudioClip::value_type lastSample = 0; }; SafeSampleReader::SafeSampleReader(SampleReader unsafeRead, AudioClip::size_type size) : unsafeRead(unsafeRead), size(size) {} inline AudioClip::value_type SafeSampleReader::operator()(AudioClip::size_type index) { if (index < 0) { throw invalid_argument(fmt::format("Cannot read from sample index {}. Index < 0.", index)); } if (index >= size) { throw invalid_argument(fmt::format("Cannot read from sample index {}. Clip size is {}.", index, size)); } if (index == lastIndex) { return lastSample; } lastIndex = index; lastSample = unsafeRead(index); return lastSample; } SampleReader AudioClip::createSampleReader() const { return SafeSampleReader(createUnsafeSampleReader(), size()); } AudioClip::iterator AudioClip::begin() const { return SampleIterator(*this, 0); } AudioClip::iterator AudioClip::end() const { return SampleIterator(*this, size()); } std::unique_ptr<AudioClip> operator|(std::unique_ptr<AudioClip> clip, AudioEffect effect) { return effect(std::move(clip)); } SampleIterator::SampleIterator() : sampleIndex(0) {} SampleIterator::SampleIterator(const AudioClip& audioClip, size_type sampleIndex) : sampleReader([&audioClip] { return audioClip.createSampleReader(); }), sampleIndex(sampleIndex) {}
90e0ded3f25d8591d74d9baa7436b595465badb3
61eeece81800c3e71d1dd717569524ce92d9ef8a
/Arduino/Scott Marley/6. Noise/prettyFill/prettyFill.ino
6ce8d69b647318005f6dcbc33b00b9b0c33d6e0f
[ "MIT" ]
permissive
j1fvandenbosch/IOT-WorkArea-Storage
db775e187512f40165866e529fec80c3d4fadbfb
3232f1e9afc3d8d05828de11fc85c226ef46a716
refs/heads/main
2023-06-02T10:52:00.175772
2021-06-20T22:54:03
2021-06-20T22:54:03
378,742,805
0
0
null
null
null
null
UTF-8
C++
false
false
570
ino
prettyFill.ino
#include <FastLED.h> #define NUM_LEDS 40 #define LED_PIN 13 CRGB leds[NUM_LEDS]; void setup() { FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS); FastLED.setBrightness(100); Serial.begin(9600); } void loop() { uint8_t octaves = 1; uint16_t x = 0; int scale = 100; uint8_t hue_octaves = 1; uint16_t hue_x = 1; int hue_scale = 50; uint16_t ntime = millis() / 3; uint8_t hue_shift = 5; fill_noise16 (leds, NUM_LEDS, octaves, x, scale, hue_octaves, hue_x, hue_scale, ntime, hue_shift); FastLED.show(); }
858eb932b7e82b22fdc455ef4aa635e8157ca7e8
68beba3c7108dd601ffbdf9230d3fb1621bb1c82
/Wegscheider/Ex1/ex1.cpp
8f28bef8e04e3c93ab4e2d5c84a8276db3d541ad
[ "MIT" ]
permissive
sepidehsaran/appfs
f67967cd634c3d0a9d9650a2258c1405b2ca44f7
8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3
refs/heads/master
2023-04-01T23:38:20.830092
2017-08-01T13:40:56
2017-08-01T13:40:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,397
cpp
ex1.cpp
/** * @file ex1.cpp * @author Fabian Wegscheider * @date 1.5.17 */ #include <iostream> #include <fstream> #include <math.h> #include <vector> using namespace std; /** * The main function. Reads a csv file from the command line that contains * measured data from two locations in a specific format. Then the number of * valid lines as well as the geometric means of the two data sets are printed * to the standard output. * @param numargs number of inputs on command line * @param args array of inputs on command line * @return whether the file was read successfully */ int main(int numargs, char *args[]) { if (numargs != 2) { cerr << "Usage: " << args[0] << " filename" << endl; exit(EXIT_FAILURE); } ifstream inputFile; inputFile.open(args[1]); if (inputFile.fail()) { cerr << "file could not be read" << endl; exit(EXIT_FAILURE); } string line; vector<double> values[2]; double geoMean[2] {.0, .0}; int nLoc[2] {0, 0}; long nLines = 0; int err = 0; int seqNum = 0; int prevSeqNum = 0; int location = 0; double value = 0; while (getline(inputFile, line)) { nLines++; if (line.empty()) { // empty lines are ignored continue; } size_t foundComment = line.find("#"); if (foundComment == 0) { // comment lines are ignored continue; } if (foundComment != string::npos) { // anything after # is ignored line = line.substr(0, foundComment); } size_t pos1 = line.find(";"); if (pos1 == string::npos) { err++; continue; } // test if line contains two ';' size_t pos2 = line.find(";", pos1+1); if (pos2 == string::npos) { err++; continue; } try { string parts[] = {"","",""}; parts[0] = line.substr(0, pos1); parts[1] = line.substr(pos1+1, pos2-pos1-1); // split line at ';' and trim parts[2] = line.substr(pos2+1, line.length()-pos2-1); // the parts bool foundSpace = false; for (int i = 0; i < 3; i++) { size_t first = parts[i].find_first_not_of(' '); // if one part still contains size_t last = parts[i].find_last_not_of(' '); // a whitespace, the line is parts[i] = parts[i].substr(first, last-first+1); // treated as an error if (parts[i].find(' ') != string::npos) { foundSpace = true; } } if (foundSpace) { err++; continue; } seqNum = stoi(parts[0]); location = stoi(parts[1]); // if parsing fails, exception is thrown and caught value = stod(parts[2]); } catch (...) { prevSeqNum = seqNum; err++; continue; } if (seqNum != prevSeqNum+1) { // test for consecutive sequence numbers err++; prevSeqNum = seqNum; continue; } prevSeqNum = seqNum; if (location < 1 || location > 2 || !isnormal(value) || value <= 0. ) { // value must be positive err++; continue; } // here the values are stored values[--location].push_back(value); geoMean[location] += log(value); nLoc[location]++; } // geometric means are calculated for (int i = 0; i < 2; i++) { if (nLoc[i] > 0) { geoMean[i] = exp(geoMean[i] / (double)nLoc[i]); } } // writing output cout << "File: " << args[1] << " with " << nLines << " lines" << endl; for (int i = 0; i < 2; i++) { cout << "Valid values Loc" << (i+1) << ": " << nLoc[i] << " with GeoMean " << geoMean[i] << endl; } cout << "Number of errors in the file: " << err << endl; exit(EXIT_SUCCESS); }
b60514ced1c88b6232379c621fb97e77ad3b1de5
ae6afef817813f4d92d041bf135bf1a9e0948df3
/src/system/move_event.cpp
f808240ac9b9da6c365b37151afa6da31b419c55
[ "MIT" ]
permissive
jktjkt/CPPurses
1ea5429d24ddaf8ddb2e8f509445faa830c27373
652d702258db8fab55ae945f7bb38e0b7c29521b
refs/heads/master
2020-03-29T23:58:42.332998
2018-09-19T17:48:08
2018-09-19T17:48:08
150,499,046
0
0
MIT
2018-09-26T22:51:29
2018-09-26T22:51:29
null
UTF-8
C++
false
false
1,559
cpp
move_event.cpp
#include <cppurses/system/events/move_event.hpp> #include <cppurses/painter/detail/screen_descriptor.hpp> #include <cppurses/painter/detail/screen_mask.hpp> #include <cppurses/painter/detail/screen_state.hpp> #include <cppurses/system/event.hpp> #include <cppurses/widget/point.hpp> #include <cppurses/widget/widget.hpp> namespace cppurses { Move_event::Move_event(Widget* receiver, Point new_position, Point old_position) : Event{Event::Move, receiver}, new_position_{new_position}, old_position_{old_position} {} bool Move_event::send() const { if (receiver_->x() != new_position_.x || receiver_->y() != new_position_.y) { receiver_->screen_state().optimize.moved = true; // Create and set move_mask in receiver_->screen_state() receiver_->screen_state().optimize.move_mask = detail::Screen_mask(*receiver_); receiver_->screen_state() .tiles.clear(); // TODO remove this once opt impl. old_position_.x = receiver_->x(); old_position_.y = receiver_->y(); receiver_->set_x(new_position_.x); receiver_->set_y(new_position_.y); return receiver_->move_event(new_position_, old_position_); } return true; } bool Move_event::filter_send(Widget* filter) const { if (receiver_->x() != new_position_.x || receiver_->y() != new_position_.y) { return filter->move_event_filter(receiver_, new_position_, old_position_); } return true; } } // namespace cppurses
9b92af02eab2a9cf04c96ddd1528e2afa9cfa464
54b9ee00bcd582d56853ddb90be5cfeb0c29ba29
/src/platform/toft_system_threading_thread_types.cc
fa21b9ee6b6deffbe5f76c03a01db1b20c1661a5
[ "BSD-3-Clause" ]
permissive
pengdu/bubblefs
8f4deb8668831496bb0cd8b7d9895900b1442ff1
9b27e191a287b3a1d012adfd3bab6a30629a5f33
refs/heads/master
2020-04-04T19:32:11.311925
2018-05-02T11:20:18
2018-05-02T11:20:18
156,210,664
2
0
null
2018-11-05T11:57:22
2018-11-05T11:57:21
null
UTF-8
C++
false
false
1,377
cc
toft_system_threading_thread_types.cc
// Copyright (c) 2011, The Toft Authors. // All rights reserved. // // Author: CHEN Feng <chen3feng@gmail.com> // Created: 05/31/11 // toft/system/threading/thread_types.cpp #include "platform/toft_system_threading_thread_types.h" #include <string> #include "platform/toft_system_check_error.h" namespace bubblefs { namespace mytoft { ThreadAttributes& ThreadAttributes::SetName(const std::string& name) { m_name = name; return *this; } ThreadAttributes::ThreadAttributes() { MYTOFT_CHECK_PTHREAD_ERROR(pthread_attr_init(&m_attr)); } ThreadAttributes::~ThreadAttributes() { MYTOFT_CHECK_PTHREAD_ERROR(pthread_attr_destroy(&m_attr)); } ThreadAttributes& ThreadAttributes::SetStackSize(size_t size) { MYTOFT_CHECK_PTHREAD_ERROR(pthread_attr_setstacksize(&m_attr, size)); return *this; } ThreadAttributes& ThreadAttributes::SetDetached(bool detached) { int state = detached ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE; MYTOFT_CHECK_PTHREAD_ERROR(pthread_attr_setdetachstate(&m_attr, state)); return *this; } ThreadAttributes& ThreadAttributes::SetPriority(int priority) { return *this; } bool ThreadAttributes::IsDetached() const { int state = 0; MYTOFT_CHECK_PTHREAD_ERROR(pthread_attr_getdetachstate(&m_attr, &state)); return state == PTHREAD_CREATE_DETACHED; } } // namespace mutoft } // namespace bubblefs
b387b9fc9ef66ef5808b1ad3ce64e7441cb01e52
4563ea8c1abf11662af72e70d01dcd100c86731a
/libcb-CPP/include/libcb/graph.h
fdeb9d28fc1390335c84a36e7364411652db9438
[]
no_license
yuxjiang/ASD_Hum_Genet
559f9acdda38713527532014f085aed393cec38d
23f26d5f74fe4054b42dc8e2be0440235693240b
refs/heads/main
2023-06-24T10:19:55.316800
2021-07-25T17:12:10
2021-07-25T17:12:10
387,857,048
0
0
null
null
null
null
UTF-8
C++
false
false
26,774
h
graph.h
//! libcb/graph.h #ifndef _LIBCB_GRAPH_H_ #define _LIBCB_GRAPH_H_ // C library #include <cmath> #include <cstdint> #include <cstring> // I/O #include <iostream> #include <fstream> #include <sstream> // container #include <vector> // other #include <unordered_map> #include <algorithm> #include <random> #include <tuple> #include <utility> #include <chrono> #include "util.h" //! Length of the adjacency matrix of a simple graph #define LEN_ADJMAT(n) (((n)*(n)-(n))>>1) /** * @brief a class of @a simple @a graph. That is, an undirected graph with * neither "self-loops" nor "multi-edges". * * @pre vertex type must meet the following requirements: * @arg A default constructor. * @arg A properly defined @a assign operator (i.e., operator=). * @arg A pair of member functions (de)serialize to handle binary file I/O. * * @remark Edges are indicated by a positive float number, any value <= 0 * indicates the pair of vertices are disconnected. */ template<typename T> class SGraph { public: //! member types using vertex_type = T; using weight_type = float; using edge_type = std::pair<index_t, index_t>; using weighted_edge_type = std::tuple<index_t, index_t, weight_type>; //! simple graph merging schemes enum merge_scheme { maximum, ///< the maximum of the two edges minimum, ///< the minimum of the two edges addition ///< the sum of the two edges }; private: //! A vector of vertices of type T. std::vector<vertex_type> m_vertices; //! A block of 1D vector to store edge weights. /** * @remark For the sake of "simple graph", `m_adjmat` does not store * self-loop edge weights, thus, it has precisely `n*(n-1)/2` entreis as the * size of the upper triangluar matrix, where `n` is the number of vertices. */ weight_type* m_adjmat; //! The number of (positive) edges. index_t m_number_of_edges; public: /** * @brief The default constructor. * * @param n the number of vertices. */ SGraph(index_t n = 0) { if (n == 0) { m_number_of_edges = 0; m_adjmat = nullptr; return; } index_t amlen = LEN_ADJMAT(n); m_vertices.resize(n); m_number_of_edges = 0; m_adjmat = new weight_type[amlen]; memset(m_adjmat, 0, amlen * sizeof(weight_type)); } /** * @brief A constructor with vertices only. * * @param vertices a vector of vertices. */ SGraph(const std::vector<vertex_type>& vertices) { m_vertices = vertices; index_t n = number_of_vertices(); index_t amlen = LEN_ADJMAT(n); m_adjmat = new weight_type[amlen]; memset(m_adjmat, 0, amlen * sizeof(weight_type)); m_number_of_edges = 0; } /** * @brief A constructor with vertices and edges (i.e. V, E). * * @param vertices a vector of vertices. * @param weightedEdges a vector of weighted edges. */ SGraph( const std::vector<vertex_type>& vertices, const std::vector<weighted_edge_type>& weightedEdges) { m_vertices = vertices; index_t n = number_of_vertices(); index_t amlen = LEN_ADJMAT(n); m_adjmat = new weight_type[amlen]; memset(m_adjmat, 0, amlen * sizeof(weight_type)); m_number_of_edges = 0; index_t u, v; weight_type w; for (const auto& weightedEdge : weightedEdges) { std::tie(u, v, w) = weightedEdge; set_edge_weight(u, v, w); } } /** * @brief A copy constructor. * * @param g another SGraph<vertex_type> object. */ SGraph(const SGraph& g) { index_t n = g.number_of_vertices(); index_t amlen = LEN_ADJMAT(n); m_vertices = g.m_vertices; m_number_of_edges = g.m_number_of_edges; m_adjmat = new weight_type[amlen]; memcpy(m_adjmat, g.m_adjmat, amlen * sizeof(weight_type)); } /** * @brief The destructor. */ virtual ~SGraph() { m_vertices.clear(); m_number_of_edges = 0; if (m_adjmat != nullptr) { delete[] m_adjmat; } } /** * @brief An assign operator. * * @param g another SGraph<vertex_type> object. * * @return A constant reference to itself. */ const SGraph& operator=(const SGraph& g) { if (this != &g) { index_t n = g.number_of_vertices(); index_t amlen = LEN_ADJMAT(n); if (number_of_vertices() != n) { // reallocate memory for [m_adjmat] if necessary if (m_adjmat != nullptr) { delete[] m_adjmat; } m_adjmat = new weight_type[amlen]; } m_vertices = g.m_vertices; m_number_of_edges = g.m_number_of_edges; memcpy(m_adjmat, g.m_adjmat, amlen * sizeof(weight_type)); } return *this; } /** * @brief Resizes the graph (with the number of vertices). * * @param n the number of vertices. */ void resize(index_t n) { index_t amlen = LEN_ADJMAT(n); if (number_of_vertices() != n) { m_vertices.resize(n); if (m_adjmat != nullptr) { delete[] m_adjmat; } m_adjmat = new weight_type[amlen]; } m_number_of_edges = 0; memset(m_adjmat, 0, amlen * sizeof(weight_type)); } /** * @brief Remove all edges in the networl. * * @sa remove_edge() */ void remove_all_edges() { index_t n = number_of_vertices(); index_t amlen = LEN_ADJMAT(n); m_number_of_edges = 0; memset(m_adjmat, 0, amlen * sizeof(weight_type)); } /** * @brief Update vertices. * * @param vertices a vector of vertices. */ void set_vertices(std::vector<vertex_type>& vertices) { resize(vertices.size()); m_vertices = vertices; } /** * @brief Gets a vector of neighbor indices. * * @param v the index of a vertex. * * @return A vector of indices. */ std::vector<index_t> neighbor_of(index_t v) const { index_t n = number_of_vertices(); if (v >= n) { error_and_exit(__PRETTY_FUNCTION__, "Index out of range."); } std::vector<index_t> neighbors; for (index_t i = 0; i < v; ++i) { if (m_adjmat[_edge_index_no_check(i, v)] > 0) { neighbors.push_back(i); } } for (index_t i = v + 1; i < n; ++i) { if (m_adjmat[_edge_index_no_check(v, i)] > 0) { neighbors.push_back(i); } } return neighbors; } /** * @brief Gets the degree of a vertex. * * @param v the index of a vertex. * * @return The degree count. */ index_t degree_of(index_t v) const { index_t n = number_of_vertices(); if (v >= n) { error_and_exit(__PRETTY_FUNCTION__, "Index out of range."); } index_t degree = 0; for (index_t i = 0; i < v; ++i) { if (m_adjmat[_edge_index_no_check(i, v)] > 0) { ++degree; } } for (index_t i = v + 1; i < n; ++i) { if (m_adjmat[_edge_index_no_check(v, i)] > 0) { ++degree; } } return degree; } /** * @brief Gets the number of vertices in the SGraph<vertex_type>. * * @return The degree count. */ index_t number_of_vertices() const { return m_vertices.size(); } /** * @brief Gets the number of non-zero weighted edges in the graph. * * @return The total number of non-zero edges. */ index_t number_of_edges() const { return m_number_of_edges; } /** * @brief Gets the number of connected component. * * @return The number of connected component. */ index_t number_of_connected_component() const { index_t n = number_of_vertices(); std::vector<index_t> parent(n); for (index_t i = 0; i < n; ++i) { parent[i] = i; // initialization } std::vector<edge_type> edges = get_edges(); for (const auto& edge : edges) { _uf_union(parent, edge.first, edge.second); } std::set<index_t> cc_index; for (index_t i = 0; i < n; ++i) { cc_index.insert(_uf_find_and_flatten(parent, i)); } return static_cast<index_t>(cc_index.size()); } /** * @brief Gets the number of singletons. * * @return The number of singletons. */ index_t number_of_singletons() const { index_t n = number_of_vertices(); index_t res = 0; for (index_t i = 0; i < n; ++i) { if (degree_of(i) == 0) { ++res; } } return res; } /** * @brief Filters edges whose weight is below a cutoff. * * @param tau a cutoff threshold. */ void filter_edges(weight_type tau) { if (tau <= 0.0) return; index_t n = number_of_vertices(); index_t amlen = LEN_ADJMAT(n); for (index_t i = 0; i < amlen; ++i) { if (m_adjmat[i] > 0.0 && m_adjmat[i] < tau) { m_adjmat[i] = 0.0; --m_number_of_edges; } } } /** * @brief Gets a full adjacency matrix by normalizing incoming degrees. * * @return A full adjacency matrix. */ std::vector<std::vector<float>> in_degree_normalized_adjacency_matrix() const { index_t n = number_of_vertices(); // matrix initialization std::vector<std::vector<float>> full_adjmat(n); for (auto& row : full_adjmat) { row.resize(n); } std::vector<weight_type> wsum(n, 0.0); for (index_t i = 0; i < n; ++i) { for (index_t r = 0; r < i; ++r) { wsum[i] += m_adjmat[_edge_index_no_check(r, i)]; } for (index_t c = i + 1; c < n; ++c) { wsum[i] += m_adjmat[_edge_index_no_check(i, c)]; } } for (index_t r = 0; r < n; ++r) { for (index_t c = 0; c < n; ++c) { if (r == c) { full_adjmat[r][c] = 0; } else { full_adjmat[r][c] = static_cast<weight_type>(get_edge_weight(r, c) / wsum[c]); } } } return full_adjmat; } /** * @brief Gets a full adjacency matrix by normalizing outgoing degrees. * * @return A full adjacency matrix. */ std::vector<std::vector<float>> out_degree_normalized_adjacency_matrix() const { index_t n = number_of_vertices(); // matrix initialization std::vector<std::vector<float>> full_adjmat(n); for (auto& row : full_adjmat) { row.resize(n); } std::vector<weight_type> wsum(n, 0.0); for (index_t i = 0; i < n; ++i) { for (index_t r = 0; r < i; ++r) { wsum[i] += m_adjmat[_edge_index_no_check(r, i)]; } for (index_t c = i + 1; c < n; ++c) { wsum[i] += m_adjmat[_edge_index_no_check(i, c)]; } } for (index_t r = 0; r < n; ++r) { for (index_t c = 0; c < n; ++c) { if (r == c) { full_adjmat[r][c] = 0; } else { full_adjmat[r][c] = static_cast<weight_type>(get_edge_weight(r, c) / wsum[r]); } } } return full_adjmat; } /** * @brief Gets a vector of vertex objects. * * @return A vector of vertex objects. * * @sa get_edges() */ std::vector<vertex_type> get_vertices() const { return m_vertices; } /** * @brief Gets a vector of edges. * * @return A vector of edge tuples (src_index, dst_index, weight). * * @sa get_vertices(), get_edges() */ std::vector<weighted_edge_type> get_weighted_edges() const { index_t n = number_of_vertices(); std::vector<weighted_edge_type> weightedEdges; for (index_t r = 0; r < n; ++r) { for (index_t c = r + 1; c < n; ++c) { weight_type w = m_adjmat[_edge_index_no_check(r, c)]; if (w > 0) { weightedEdges.emplace_back(r, c, w); } } } return weightedEdges; } /** * @brief Gets a vector of edges, as index pairs. * * @return A vector of edge pairs (src_index, dst_index). * * @sa set_edges() */ std::vector<edge_type> get_edges() const { index_t n = number_of_vertices(); std::vector<edge_type> edges; for (index_t r = 0; r < n; ++r) { for (index_t c = r + 1; c < n; ++c) { weight_type w = m_adjmat[_edge_index_no_check(r, c)]; if (w > 0) { edges.emplace_back(r, c); } } } return edges; } /** * @brief Gets a vector of indices of top [k] hubs. * * @param k the number of hubs. * * @return A vector of vertex ID. */ std::vector<index_t> get_hubs(index_t k = 1) const { index_t n = number_of_vertices(); if (k > n) { error_and_exit(__PRETTY_FUNCTION__, "K is more than the number of vertices."); } std::vector<index_t> hubs; arma::Col<index_t> degrees(n); for (index_t i = 0; i < n; ++i) { degrees(i) = degree_of(i); } arma::uvec indices = arma::sort_index(degrees, "descend"); // [d]: the degree of k-th hub. // Outputs indices of all hubs that have degree at least [d]. index_t d = degrees(indices(k - 1)); for (index_t i = 0; i < n; ++i) { if (degrees(indices(i)) < d) break; hubs.push_back(indices(i)); } return hubs; } /** * @brief Creates a vertex-induced sub-graph. * * @param indices a vector of vertex indices. * * @return A SGraph<vertex_type> subgraph. */ SGraph subgraph(const std::vector<index_t>& indices) const { // make a vector of vertices std::vector<vertex_type> vertices(indices.size()); for (size_t i = 0; i < indices.size(); ++i) { if (indices[i] >= number_of_vertices()) { error_and_exit(__PRETTY_FUNCTION__, "Index out of range."); } vertices[i] = m_vertices[indices[i]]; } SGraph g(vertices); // initialize the subgraph. index_t n = g.number_of_vertices(); // copy edge weights for (index_t i = 0; i < n; ++i) { for (index_t j = i + 1; j < n; ++j) { weight_type w = get_edge_weight(indices[i], indices[j]); g.set_edge_weight(i, j, w); } } return g; } /** * @brief Creates a vertex-induced graph. * * @remark Vertices in the new graph do not need to be a subset of the * current one. * * @param vertices a vector of vertices of vertex_type. * * @return A SGraph<vertex_type> newgraph. */ SGraph project(const std::vector<vertex_type>& vertices) const { SGraph g(vertices); std::unordered_map<vertex_type, index_t> vertexIndex; for (size_t i = 0; i < vertices.size(); ++i) { vertexIndex[vertices[i]] = i; } index_t u, v; weight_type w; std::vector<vertex_type> verticesSelf = get_vertices(); std::vector<weighted_edge_type> weightedEdges = get_weighted_edges(); for (const auto& weightedEdge : weightedEdges) { std::tie(u, v, w) = weightedEdge; if (CONTAINS(vertexIndex, verticesSelf[u]) && CONTAINS(vertexIndex, verticesSelf[v])) { g.set_edge_weight(vertexIndex.at(verticesSelf[u]), vertexIndex.at(verticesSelf[v]), w); } } return g; } /** * @brief Gets edge weight. * * @param src the source vertex index. * @param dst the destination vertex index. * * @return The weight on edge (src, dst). * * @sa set_edge_weight(). */ weight_type get_edge_weight(index_t src, index_t dst) const { index_t ai = _adjmat_index(src, dst); index_t n = number_of_vertices(); return ai >= LEN_ADJMAT(n) ? 0.0 : m_adjmat[ai]; } /** * @brief Sets the weight of an edge. * * @param src the source vertex index. * @param dst the destination vertex index. * @param w the weight. * * @sa get_edge_weight(). */ void set_edge_weight( index_t src, index_t dst, weight_type w) { index_t ai = _adjmat_index(src, dst); index_t n = number_of_vertices(); if (ai >= LEN_ADJMAT(n)) return; // skip invalid edge indices _set_edge_weight_with_adjmat_index(ai, w); } /** * @brief Checks if an edge (weight > 0) exists. * * @param src the source vertex index. * @param dst the destination vertex index. * * @return True or False. */ bool has_edge(index_t src, index_t dst) const { index_t ai = _adjmat_index(src, dst); index_t n = number_of_vertices(); if (ai >= LEN_ADJMAT(n)) { return false; } else { return m_adjmat[ai] > 0; } } /** * @brief Removes an edge. * * @param src the @a source vertex index. * @param dst the @a destination vertex index. * * @sa set_edge_weight(), remove_all_edges() */ void remove_edge(index_t src, index_t dst) { set_edge_weight(src, dst, 0); } /** * @brief Swaps two edges. * In particular, it swaps two edges (a, b), (c, d) to be (a, d), (c, b). * * @param eab an edge (a, b). * @param ecd an edge (c, d). */ void swap_edges(const edge_type& eab, const edge_type& ecd) { index_t a, b, c, d; // vertex index std::tie(a, b) = eab; std::tie(c, d) = ecd; weight_type wi = get_edge_weight(a, b); weight_type wj = get_edge_weight(c, d); remove_edge(a, b); remove_edge(c, d); set_edge_weight(a, d, wi); set_edge_weight(c, b, wj); } /** * @brief Disconnets a given vertex from the rest of the graph. * * @param v the index of a vertex. */ void disconnect(index_t v) { std::vector<index_t> neighbors = neighbor_of(v); for (const auto& u : neighbors) { remove_edge(u, v); } } /** * @brief Removes singletons from the graph. */ void remove_singletons() { index_t n = number_of_vertices(); std::vector<index_t> non_singletons; for (index_t i = 0; i < n; ++i) { if (degree_of(i) > 0) { non_singletons.push_back(i); } } (*this) = subgraph(non_singletons); } /** * @brief Merges with another graph. * * @param other another SGraph object. * @param sch a merging scheme. * * @return A merged SGraph object. */ SGraph merge(const SGraph& other, merge_scheme sch = SGraph::minimum) const { // get the union of vertices and their back indices. std::vector<index_t> ia, ib; std::vector<vertex_type> vertices = vector_union<vertex_type>(m_vertices, other.m_vertices, ia, ib); // converts two vector of edge indices, and makes two graphs std::vector<weighted_edge_type> wes_self = get_weighted_edges(); // weighted edge from self std::vector<weighted_edge_type> wes_other = other.get_weighted_edges(); // weighted edge from other index_t u, v; weight_type w; for (auto& we : wes_self) { std::tie(u, v, w) = we; we = std::make_tuple(ia[u], ia[v], w); // conversion } for (auto& we : wes_other) { std::tie(u, v, w) = we; we = std::make_tuple(ib[u], ib[v], w); } // merge [other] into [self] SGraph g(vertices, wes_self); SGraph g_other(vertices, wes_other); index_t n = vertices.size(); index_t amlen = LEN_ADJMAT(n); switch(sch) { case SGraph::minimum: for (index_t i = 0; i < amlen; ++i) { g._set_edge_weight_with_adjmat_index(i, std::min(g.m_adjmat[i], g_other.m_adjmat[i])); } break; case SGraph::maximum: for (index_t i = 0; i < amlen; ++i) { g._set_edge_weight_with_adjmat_index(i, std::max(g.m_adjmat[i], g_other.m_adjmat[i])); } break; case SGraph::addition: for (index_t i = 0; i < amlen; ++i) { g._set_edge_weight_with_adjmat_index(i, g.m_adjmat[i] + g_other.m_adjmat[i]); } break; default: error_and_exit(__PRETTY_FUNCTION__, "Unknown merging scheme."); } return g; } /** * @brief Writes the object to a binary file. * * @param out an output stream. */ void serialize(std::ostream& out) const { uint32_t n = static_cast<uint32_t>(number_of_vertices()); out.write((char*)(&n), sizeof(uint32_t)); for (uint32_t i = 0; i < n; ++i) { m_vertices[i].serialize(out); } uint32_t ne = static_cast<uint32_t>(m_number_of_edges); out.write((char*)(&ne), sizeof(uint32_t)); out.write((char*)m_adjmat, (LEN_ADJMAT(n) * sizeof(weight_type))); } /** * @brief Reads an Graph object from a binary file. * * @param in an input stream. */ void deserialize(std::istream& in) { uint32_t data; in.read((char*)(&data), sizeof(uint32_t)); // read the number of vertices index_t n = static_cast<index_t>(data); resize(n); for (index_t i = 0; i < n; ++i) { m_vertices[i].deserialize(in); // read each vertex object } // load weight matrix index_t amlen = LEN_ADJMAT(n); in.read((char*)(&data), sizeof(uint32_t)); m_number_of_edges = static_cast<index_t>(data); in.read((char*)m_adjmat, amlen * sizeof(weight_type)); } // TODO // ---- //! Shuffles vertices in the simple graph. /*! * \param pairsToSwap the number of vertex swaps. */ void shuffle_vertices(int pairsToSwap); //! Returns the largest connected component. SGraph largest_connected_component() const; //! Gets the diameter of the graph. index_t diameter() const; protected: /** * @brief Converts (src, dst) index pair to internal data block index into * `m_adjmat`. * * @param src the source vertex index. * @param dst the destination vertex index. * * @return The index into `m_adjmat`. */ index_t _adjmat_index(index_t src, index_t dst) const { if (src > dst) { std::swap(src, dst); } index_t n = number_of_vertices(); if (src >= n || dst >= n) { return LEN_ADJMAT(n);; } else if (src == dst) { return LEN_ADJMAT(n);; } return _edge_index_no_check(src, dst); } /** * @brief Converts index without boundary check. * * @param src the source vertex index. * @param dst the destination vertex index. * * @return The index into `m_adjmat`. * * @sa _adjmat_index() */ index_t _edge_index_no_check( index_t src, index_t dst) const { return (number_of_vertices() * src - (((src + 3) * src) >> 1) + dst - 1); } /** * @brief Sets an edge weight given index into the internal `m_adjmat`. * * @param ai an index into `m_adjmat`. * @param w an edge weight of type `weight_type`. */ void _set_edge_weight_with_adjmat_index( index_t ai, weight_type w) { if (w > 0) { if (m_adjmat[ai] <= 0) { // old w <= 0, new w > 0 ++m_number_of_edges; } } else if (m_adjmat[ai] > 0) { // old w > 0, new w <= 0 --m_number_of_edges; } m_adjmat[ai] = w; } /** * @brief unions two groups, part of "union-find" algorithm. * * @param parent the parent vertex. * @param src the source vertex index. * @param dst the destination vertex index. * * @sa _uf_find_and_flattern() */ void _uf_union( std::vector<index_t>& parent, index_t src, index_t dst) const { index_t src_root = _uf_find_and_flatten(parent, src); index_t dst_root = _uf_find_and_flatten(parent, dst); parent[parent[dst_root]] = src_root; } /** * @brief finds the group ancestor, part of "union-find" algorithm. * * @param parent the parent vertex. * @param index the vertex index. * * @return The ancestor of this group. * * @sa _uf_union() */ index_t _uf_find_and_flatten( std::vector<index_t>& parent, index_t index) const { index_t i = index; while (parent[i] != i) { i = parent[i]; } // find root -> i index_t root = i; i = index; while (parent[i] != i) { i = parent[i]; parent[i] = root; } return root; } }; /** * @brief Randomly rewires an amount of pairs of edges while preserving its * degree distribution. * * @tparam T vertex type. * @param g an SGraph<T> object. * @param swapTarget the number of pairs of edges to rewire. * * @return A rewired SGraph<T> object. */ template<typename T> SGraph<T> degree_preserving_edge_rewire(const SGraph<T>& g, int swapTarget) { SGraph<T> newGraph = g; int edgeCount = newGraph.number_of_edges(); int scale = 100; // maximum trials = scale * |E| unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); std::uniform_int_distribution<int> udist(0, edgeCount - 1); std::vector<typename SGraph<T>::edge_type> edges = newGraph.get_edges(); index_t ei, ej; // index of edges index_t a, b, c, d; // vertex indices, (a, b) and (c, d) int swapCount = 0; for (int i = 0; i < scale * edgeCount; ++i) { // Draw two edges at random, and try to swap ei = udist(generator); ej = udist(generator); if (ei == ej) continue; // Check if the two edges involve 4 distinct vertices. // Note that it's guaranteed: a =/= b, c =/= d std::tie(a, b) = edges[ei]; std::tie(c, d) = edges[ej]; if (a == c || a == d || b == c || b == d) continue; // check if the two target edges exist. if (newGraph.has_edge(a, d) || newGraph.has_edge(c, b)) continue; newGraph.swap_edges(edges[ei], edges[ej]); // update edge indicies edges[ei] = std::make_pair(a, d); // (a, b) -> (a, d) edges[ej] = std::make_pair(c, b); // (c, d) -> (c, b) if (++swapCount >= swapTarget) break; } if (swapCount < swapTarget) { warn(__PRETTY_FUNCTION__, "Reached the maximum number of swaps."); } return newGraph; } #endif // _LIBCB_GRAPH_H_ // ------------- // Yuxiang Jiang (yuxjiang@indiana.edu) // Department of Computer Science // Indiana University, Bloomington // Last modified: Tue 25 Jun 2019 11:27:58 PM P
8bb6ab48af6fc4f8da4a08ddcf00b548beb9f255
ebf7654231c1819cef2097f60327c968b2fa6daf
/server/logic_server/player/module/fighter/Logic_Fighter.h
112cbbc1268e7b700fefb4538da0b11a3e74760f
[]
no_license
hdzz/game-server
71195bdba5825c2c37cb682ee3a25981237ce2ee
0abf247c107900fe36819454ec6298f3f1273e8b
refs/heads/master
2020-12-30T09:15:17.606172
2015-07-29T07:40:01
2015-07-29T07:40:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,010
h
Logic_Fighter.h
/* * Fighter.h * * Created on: Jan 21, 2014 * Author: ti * * 新模块例子 */ #ifndef LOGIC_FIGHTER_H_ #define LOGIC_FIGHTER_H_ #include "Logic_Player_Base.h" #include "fighter/Fighter_Def.h" #include "pack/Pack_Struct.h" class Tasker; struct Fighter_Detail; struct Skill_DB_Info; struct Skill_Detail; struct Player_Init_Cache; struct Prop_Setter; struct Skill_Info; struct Exp_All; class Logic_Fighter : virtual public Tasker { public: Logic_Fighter(void); virtual ~Logic_Fighter(); void reset(void); // 创建角色时初始化 static int create_init(Fighter_Detail &detail); // 登录时detail赋值 void load_detail(Fighter_Detail &detail); // 保存时detail赋值 void save_detail(Fighter_Detail &data); void serialize_fighter_detail(Block_Buffer& buf); Fighter_Detail const &fighter_detail(void) const; // 登录或转场景同步逻辑信息到场景 int sync_scene_module_info(Block_Buffer &buf); // 每天0点刷新 int trigger_daily_zero(const Time_Value &now, bool logic_check = false); // 每天6点刷新 int trigger_daily_six(const Time_Value &now, bool logic_check = false); // 登录时module初始化 void module_init(void); // 登录后调用 void sign_in(void); // 登出前调用 void sign_out(void); // 初始化外部获得的被动技能 void init_be_skill_extra(int skill_id, int skill_lv); int fight_basic_prop_modify(Property_Type pen, Addition_Type aen, Operate_Type oen, double basic, int from = 0); int fight_fixed_prop_modify(Property_Type pen, Addition_Type aen, Operate_Type oen, double fixed, int from = 0); int fight_percent_prop_modify(Property_Type pen, Addition_Type aen, Operate_Type oen, double percent, int from = 0); int fight_prop_modify(Property_Type pen, Addition_Type aen, Operate_Type oen, double basic, double fixed, double percent, int from = 0); int fight_prop_modify(const std::vector<Prop_Setter> &setter_vec, int from); const Exp_All modify_experience_inter(int exp, const bool check_vip = false, const bool check_buff = false, const bool check_vip_team = false, const bool check_world_level = true, const int double_exp = 1, const int scene_id = 0, Operate_Type oen = O_ADD); int modify_experience(int exp, Operate_Type oen = O_ADD, int from = 300); void reset_current_prop(void); int addition_prop_refresh(Addition_Type addi_type, Prop_Setter_Type pst, const std::map<int, double> &pro_val_map, int from); ////////////////////////////////////////////////////////////////////////////////////////////////////// void refresh_fighter_detail(Block_Buffer &detail_buf); // 等级改变监听 virtual void hook_fighter_level(const int new_level, const int src_level); // 杀人监听 void hook_kill_player(role_id_t role_id); // 杀怪监听 void hook_kill_monster(int monster_type, int amount); // 杀点怪监听 void hook_kill_monster_point(int scene_id, int row); // 杀怪点监听 void hook_kill_monster_group(int scene_id, int id); // 场景目标完成监听 void hook_compelte_scene(int scene_id); // 获取所有已学习技能 int get_all_learned_skills(int talent_id = 0); // 学习技能 int manual_learn_skill( int talent_id, int skill_id, int skill_lv); int learn_skill(int talent_id, const Skill_Detail &detail); int learn_skill_cost_item(int skill_id, int skill_lv); int erase_skill(int talent_id, int tye); int move_skill(int skill_id, int new_loc, int talent_id); int open_a_skill_talent(int page_id, int talent_id); int open_a_talent_page(int talent_id); int use_a_talent_page(int talent_id); int skill_cost(int type, int arg1, int arg2, int cost); int add_be_skills(const std::vector<Skill_Info> &skill_infos); // int module_init_add_be_skills(const std::vector<Skill_Info> &skill_infos); int remove_be_skills(const std::vector<Skill_Info> &skill_infos); int add_skill_pointer(const int skill_points); void sync_phy_power_info(uint16_t cur, int32_t recover_time, uint8_t buy_times); int restore_full_prop(int32_t type, int32_t per = 1); void set_phy_power_recover_time(int time); void set_phy_power(double value); void sync_phy_power_to_client(void); // 消耗体力 int cost_strength(int value, bool to_scene = true); void update_force_by_sync_data(int force); int get_player_force(void); int get_ttl_force(void); int get_highest_force(void); private: // 学习技能条件检查 int normal_check(int career, int talent_id, int series, const Skill_Detail& config_detail); int manual_learn_checker(int career, int talent_id, int series, const Skill_Detail& config_detail); void init_skill(const Player_Init_Cache& init_config); void init_phy_power(void); private: Fighter_Detail *fighter_detail_; double sign_current_blood_; double sign_current_morale_; double sign_current_strength_; double sign_current_blood_pool_; }; inline Fighter_Detail const &Logic_Fighter::fighter_detail(void) const{ return *fighter_detail_; } #endif /* LOGIC_FIGHTER_H_ */
d8271918586dd8bf00cda82186e2f68181c26277
5b9fc8f4122175176f50f4a00d80fc2102a60adb
/src/matrix.cpp
a9f2a62fb8a180d312cbad3a18aa37d455f4f3a3
[]
no_license
timpostuvan/biclustering
02a1e85579974ee3293858b8e310918be507e21a
a8c865d86edcd952632decf3d380a6245a761e64
refs/heads/master
2022-10-26T13:56:18.887374
2020-03-11T08:59:36
2020-03-11T08:59:36
219,859,731
0
0
null
null
null
null
UTF-8
C++
false
false
5,707
cpp
matrix.cpp
#include <vector> #include <string> #include <fstream> #include <functional> #include <algorithm> #include <random> #include <iomanip> #include <iostream> #include <cstdlib> #include "matrix.h" using namespace std; mt19937 gen(time(NULL)); long double my_rand(){ long long r = gen() % 100000001; long double ret = 1.0 * r / 100000000.0; return ret; } vector<vector<long double>> generate_binary_matrix(int n, int m){ vector<vector<long double>> matrix; matrix.resize(n); for(int i = 0; i < n; i++){ matrix[i].resize(m); for(int j = 0; j < m; j++){ matrix[i][j] = gen() % 2; } } return matrix; } vector<vector<long double>> generate_random_matrix(int n, int m, bool sign){ vector<vector<long double>> matrix; matrix.resize(n); for(int i = 0; i < n; i++){ matrix[i].resize(m); for(int j = 0; j < m; j++){ matrix[i][j] = my_rand(); if(sign == true && gen() % 2 == 0){ matrix[i][j] *= -1.0; } } } return matrix; } vector<vector<long double>> random_submatrix(vector<vector<long double>> matrix, int size_x, int size_y){ int n = matrix.size(); int m = matrix[0].size(); if(n < size_x || m < size_y){ return {}; } int x = gen() % (n - size_x + 1); int y = gen() % (m - size_y + 1); vector<vector<long double>> ret; ret.resize(size_x); for(int i = 0; i < size_x; i++){ for(int j = 0; j < size_y; j++){ ret[i].push_back(matrix[x + i][y + j]); } } return ret; } vector<vector<long double>> read_matrix(){ int n, m; cin >> n >> m; vector<vector<long double>> matrix; matrix.resize(n); for(int i = 0; i < n; i++){ matrix[i].resize(m); for(int j = 0; j < m; j++){ cin >> matrix[i][j]; } } return matrix; } vector<vector<long double>> read_matrix_file(string path){ ifstream input(path); int n, m; input >> n >> m; vector<vector<long double>> matrix; matrix.resize(n); for(int i = 0; i < n; i++){ matrix[i].resize(m); for(int j = 0; j < m; j++){ input >> matrix[i][j]; } } input.close(); return matrix; } void output_matrix(vector<vector<long double>> &matrix){ int n = matrix.size(); int m = matrix[0].size(); cout << n << " " << m << "\n"; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cout << fixed << setprecision(6) << matrix[i][j] << " "; } cout << "\n"; } } void output_matrix_file(string path, vector<vector<long double>> &matrix){ ofstream output(path); int n = matrix.size(); int m = matrix[0].size(); output << n << " " << m << "\n"; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ output << matrix[i][j] << " "; } output << "\n"; } output.flush(); output.close(); } void print_matrix(vector<vector<long double>> &matrix){ for(int i = 0; i < matrix.size(); i++){ for(int j = 0; j < matrix[i].size(); j++){ cout << matrix[i][j] << " "; } cout << "\n"; } } vector<vector<long double>> apply_permutation_columns(vector<vector<long double>> &matrix, vector<int> &permutation){ int n = matrix.size(); int m = matrix[0].size(); vector<vector<long double>> new_matrix = matrix; for(int j = 0; j < m; j++){ for(int i = 0; i < n; i++){ new_matrix[i][j] = matrix[i][permutation[j]]; } } return new_matrix; } vector<vector<long double>> apply_random_permutation_columns(vector<vector<long double>> &matrix){ int n = matrix.size(); int m = matrix[0].size(); vector<int> permutation; for(int i = 0; i < m; i++){ permutation.push_back(i); } srand(time(NULL)); random_shuffle(permutation.begin(), permutation.end()); return apply_permutation_columns(matrix, permutation); } vector<vector<long double>> apply_random_permutation_rows(vector<vector<long double>> &matrix){ int n = matrix.size(); int m = matrix[0].size(); vector<int> permutation; for(int i = 0; i < n; i++){ permutation.push_back(i); } srand(time(NULL)); random_shuffle(permutation.begin(), permutation.end()); return apply_permutation_rows(matrix, permutation); } vector<vector<long double>> apply_permutation_rows(vector<vector<long double>> &matrix, vector<int> &permutation){ int n = matrix.size(); int m = matrix[0].size(); vector<vector<long double>> new_matrix = matrix; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ new_matrix[i][j] = matrix[permutation[i]][j]; } } return new_matrix; } vector<vector<long double>> distance_matrix_columns(vector<vector<long double>> &matrix, function<long double(vector<vector<long double>>&)> cost_function){ int n = matrix.size(); int m = matrix[0].size(); vector<vector<long double>> dist_matrix; dist_matrix.resize(m); for(int i = 0; i < m; i++){ dist_matrix[i].resize(m); dist_matrix[i][i] = 0.0; for(int j = 0; j < i; j++){ vector<vector<long double>> v; v.resize(2); v[0].resize(n); v[1].resize(n); for(int k = 0; k < n; k++){ v[0][k] = matrix[k][i]; } for(int k = 0; k < n; k++){ v[1][k] = matrix[k][j]; } dist_matrix[i][j] = dist_matrix[j][i] = cost_function(v); } } return dist_matrix; } vector<vector<long double>> distance_matrix_rows(vector<vector<long double>> &matrix, function<long double(vector<vector<long double>>&)> cost_function){ int n = matrix.size(); int m = matrix[0].size(); vector<vector<long double>> dist_matrix; dist_matrix.resize(n); for(int i = 0; i < n; i++){ dist_matrix[i].resize(n); dist_matrix[i][i] = 0.0; for(int j = 0; j < i; j++){ vector<vector<long double>> v; v.resize(2); v[0].resize(m); v[1].resize(m); for(int k = 0; k < m; k++){ v[0][k] = matrix[i][k]; } for(int k = 0; k < m; k++){ v[1][k] = matrix[j][k]; } dist_matrix[i][j] = dist_matrix[j][i] = cost_function(v); } } return dist_matrix; }
4a9aee3eece825783e9be2f51ecb8f38ec5056a8
61456f36bc796cd8b4e5ebe489bc6e4c019363ad
/CompuCell3D/core/pyinterface/PlayerPythonNew/FieldExtractorCML.h
eed4ee401a762e32f468c059cc9e3d258acd859c
[]
no_license
insafbk/CompuCell3D
f3556be82d10e71b6993a68e9a3fee552d10eb16
4c8b3b38f6fb9b96de7b7c13575ef0738f53dbc0
refs/heads/master
2023-01-03T08:55:37.934247
2020-08-22T18:13:13
2020-08-22T18:13:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,517
h
FieldExtractorCML.h
#ifndef FIELDEXTRACTORCML_H #define FIELDEXTRACTORCML_H #include <vector> #include <map> #include <string> #include <Utils/Coordinates3D.h> //#include "FieldStorage.h" #include <CompuCell3D/Field3D/Point3D.h> #include <CompuCell3D/Field3D/Dim3D.h> //#include <CompuCell3D/Potts3D/Cell.h> #include "FieldExtractorBase.h" #include "FieldExtractorDLLSpecifier.h" class FieldStorage; class vtkIntArray; class vtkDoubleArray; class vtkFloatArray; class vtkPoints; class vtkCellArray; class vtkStructuredPoints; class vtkStructuredPointsReader; class vtkObject; //Notice one can speed up filling up of the Hex lattice data by allocating e.g. hexPOints ot cellType arrays //instead of inserting values. Inserting causes reallocations and this slows down the task completion namespace CompuCell3D{ //have to declare here all the classes that will be passed to this class from Python //class Potts3D; //class Simulator; /*class Dim3D;*/ class FIELDEXTRACTOR_EXPORT FieldExtractorCML:public FieldExtractorBase{ public: FieldExtractorCML(); ~FieldExtractorCML(); virtual void fillCellFieldData2D(vtk_obj_addr_int_t _cellTypeArrayAddr , std::string _plane , int _pos); virtual void fillCellFieldData2DHex(vtk_obj_addr_int_t _cellTypeArrayAddr,vtk_obj_addr_int_t _hexCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr, std::string _plane , int _pos); virtual void fillCellFieldData2DCartesian(vtk_obj_addr_int_t _cellTypeArrayAddr, vtk_obj_addr_int_t _cellsArrayAddr, vtk_obj_addr_int_t _pointsArrayAddr, std::string _plane, int _pos); virtual void fillBorder2D(const char* arrayName, vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual void fillBorder2DHex(const char* arrayName, vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual void fillBorderData2D(vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual void fillBorderData2DHex(vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual void fillClusterBorderData2D(vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual void fillClusterBorderData2DHex(vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual void fillCentroidData2D(vtk_obj_addr_int_t _pointArrayAddr ,vtk_obj_addr_int_t _linesArrayAddr, std::string _plane , int _pos); virtual bool fillConFieldData2D(vtk_obj_addr_int_t _conArrayAddr,std::string _conFieldName, std::string _plane , int _pos); virtual bool fillConFieldData2DHex(vtk_obj_addr_int_t _conArrayAddr,vtk_obj_addr_int_t _hexCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr , std::string _conFieldName , std::string _plane ,int _pos); virtual bool fillConFieldData2DCartesian(vtk_obj_addr_int_t _conArrayAddr,vtk_obj_addr_int_t _cartesianCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr , std::string _conFieldName , std::string _plane ,int _pos); virtual bool fillScalarFieldData2D(vtk_obj_addr_int_t _conArrayAddr,std::string _conFieldName, std::string _plane , int _pos); virtual bool fillScalarFieldData2DHex(vtk_obj_addr_int_t _conArrayAddr,vtk_obj_addr_int_t _hexCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr , std::string _conFieldName , std::string _plane ,int _pos); virtual bool fillScalarFieldData2DCartesian(vtk_obj_addr_int_t _conArrayAddr,vtk_obj_addr_int_t _cartesianCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr , std::string _conFieldName , std::string _plane ,int _pos); virtual bool fillScalarFieldCellLevelData2D(vtk_obj_addr_int_t _conArrayAddr,std::string _conFieldName, std::string _plane , int _pos); virtual bool fillScalarFieldCellLevelData2DHex(vtk_obj_addr_int_t _conArrayAddr,vtk_obj_addr_int_t _hexCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr , std::string _conFieldName , std::string _plane ,int _pos); virtual bool fillScalarFieldCellLevelData2DCartesian(vtk_obj_addr_int_t _conArrayAddr,vtk_obj_addr_int_t _cartesianCellsArrayAddr ,vtk_obj_addr_int_t _pointsArrayAddr , std::string _conFieldName , std::string _plane ,int _pos); virtual bool fillVectorFieldData2D(vtk_obj_addr_int_t _pointsArrayIntAddr,vtk_obj_addr_int_t _vectorArrayIntAddr,std::string _fieldName, std::string _plane , int _pos); virtual bool fillVectorFieldData2DHex(vtk_obj_addr_int_t _pointsArrayIntAddr,vtk_obj_addr_int_t _vectorArrayIntAddr,std::string _fieldName, std::string _plane , int _pos); virtual bool fillVectorFieldData3D(vtk_obj_addr_int_t _pointsArrayIntAddr,vtk_obj_addr_int_t _vectorArrayIntAddr,std::string _fieldName); virtual bool fillVectorFieldCellLevelData2D(vtk_obj_addr_int_t _pointsArrayIntAddr,vtk_obj_addr_int_t _vectorArrayIntAddr,std::string _fieldName, std::string _plane , int _pos); virtual bool fillVectorFieldCellLevelData2DHex(vtk_obj_addr_int_t _pointsArrayIntAddr,vtk_obj_addr_int_t _vectorArrayIntAddr,std::string _fieldName, std::string _plane , int _pos); virtual bool fillVectorFieldCellLevelData3D(vtk_obj_addr_int_t _pointsArrayIntAddr,vtk_obj_addr_int_t _vectorArrayIntAddr,std::string _fieldName); virtual bool fillScalarFieldData3D(vtk_obj_addr_int_t _conArrayAddr ,vtk_obj_addr_int_t _cellTypeArrayAddr, std::string _conFieldName,std::vector<int> * _typesInvisibeVec); virtual bool fillScalarFieldCellLevelData3D(vtk_obj_addr_int_t _conArrayAddr ,vtk_obj_addr_int_t _cellTypeArrayAddr, std::string _conFieldName,std::vector<int> * _typesInvisibeVec); virtual std::vector<int> fillCellFieldData3D(vtk_obj_addr_int_t _cellTypeArrayAddr, vtk_obj_addr_int_t _cellIdArrayAddr); virtual bool fillConFieldData3D(vtk_obj_addr_int_t _conArrayAddr ,vtk_obj_addr_int_t _cellTypeArrayAddr, std::string _conFieldName,std::vector<int> * _typesInvisibeVec); virtual bool readVtkStructuredPointsData(vtk_obj_addr_int_t _structuredPointsReaderAddr); void setFieldDim(Dim3D _dim); Dim3D getFieldDim(); void setSimulationData(vtk_obj_addr_int_t _structuredPointsAddr); long pointIndex(short _x,short _y,short _z); long indexPoint3D(Point3D pt); private: Dim3D fieldDim; int zDimFactor,yDimFactor; vtkStructuredPoints * lds; }; }; #endif
4907a60fef29b2fd5f9871af0fb33088168da214
4bfe0eec8feae8d59ef9d623501fd00ac0fa5db3
/media-server/src/db.cpp
9bf9abc070a7eaf56d38cdb5cda584c2238f2ce4
[ "MIT" ]
permissive
wozio/home-system
8b23d175a554aed060bb0b3cba97fcb02e4fac80
16b3673a00aa67f1a85d724ada13b03db6f5c146
refs/heads/master
2021-05-22T08:49:47.026886
2015-12-28T08:01:31
2015-12-28T08:01:31
17,995,115
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
db.cpp
#include "db.h" #include <Poco/Data/SQLite/Connector.h> using namespace Poco::Data; using namespace Poco; namespace home_system { namespace media { db& db::instance() { static db i; return i; } db::db() { SQLite::Connector::registerConnector(); // ensure that main table exist in database session() << "CREATE TABLE IF NOT EXISTS media (id INTEGER PRIMARY KEY, parent INTEGER, type INTEGER)", now; } db::~db() { SQLite::Connector::unregisterConnector(); } Session db::session() { static Session session(SQLite::Connector::KEY, "media.db"); return session; } } }
d7d68e3623bee552ac2d5f820e5445e4233059ae
b74be8fe9057eb06b4358397c3f6e221637c0ea7
/GraficasComputacionales/Exam1/Player.cpp
47b488ef3e315f11d54543a3d0363310cda495cf
[]
no_license
quiin/GraficasComputacionales
5ec9e7598a5e8f8d9f8ddd576df864b1281478e0
b54a99abdc484259ad3d9d20dfaaa1d5535f444e
refs/heads/master
2020-04-18T11:09:48.231608
2016-09-12T22:48:45
2016-09-12T22:48:45
67,860,007
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
Player.cpp
#include "Player.h" #include <stdio.h> #include <string.h> Player::Player() { this->incrementer = 0; this->decrementer = 0; this -> speed = 1; this->x = 0.0f; this->lifes = 5; this->itemsCollected = 0; this->radius = 0.5; MAX_INCREMENT = 0.25; MAX_DECREMENT = 0.25; INCREMENT_STEP = 0.02; DECREMENT_STEP = 0.03; } bool Player::isAlive() { return this->lifes > 0; } void Player::increaseSpeed() { if (incrementer + INCREMENT_STEP < MAX_INCREMENT) { incrementer += DECREMENT_STEP; speed = speed + speed * incrementer; } } void Player::decreaseSpeed() { if (decrementer + DECREMENT_STEP < MAX_DECREMENT) { decrementer += DECREMENT_STEP; speed = speed - speed * decrementer; } } void Player::toString() { printf("Lifes: %d\n", lifes); printf("Incrementer: %.2f\n", incrementer); printf("Decrementer: %.2f\n", decrementer); printf("Speed: %.2f\n", speed); printf("Collected: %d\n\n\n", itemsCollected); }
2b7c3d0f48eba3336a8b34c609854be242b44c2f
674826516f037601155f727833823078435fb015
/leetcode_romanToInt.cpp
dd3208bba0c908b93d92002d37daba5f0cb66af6
[]
no_license
smy-10/leetcode
1fd89f371600e33a64abd5768c57067f1b2b57d3
1cd286d224ef4047583d78d1d7c98ef36dc8f993
refs/heads/main
2023-09-05T18:32:40.511990
2021-11-11T06:12:30
2021-11-11T06:12:30
391,800,624
0
0
null
null
null
null
UTF-8
C++
false
false
1,511
cpp
leetcode_romanToInt.cpp
// leetcode.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <vector> using namespace std; std::string replace(const std::string& str, const std::string& curStr, const std::string& toStr) { std::string s = str; for (auto i = 0; i < s.size(); i++) { auto pos = s.find(curStr, i); if (pos != std::string::npos) { s = s.replace(pos, curStr.size(), toStr); } else { break;; } } return s; } int romanToInt(std::string s) { if (s.empty()) { return 0; } s = replace(s, "IV", "a"); s = replace(s, "IX", "b"); s = replace(s, "XL", "c"); s = replace(s, "XC", "d"); s = replace(s, "CD", "e"); s = replace(s, "CM", "f"); int value = 0; for (auto i = 0; i < s.size(); i++) { char c = s[i]; if (c == 'I') value += 1; else if (c == 'V') value += 5; else if (c == 'X') value += 10; else if (c == 'L') value += 50; else if (c == 'C') value += 100; else if (c == 'D') value += 500; else if (c == 'M') value += 1000; else if (c == 'a') value += 4; else if (c == 'b') value += 9; else if (c == 'c') value += 40; else if (c == 'd') value += 90; else if (c == 'e') value += 400; else if (c == 'f') value += 900; } return value; } int main() { std::cout << "Hello World!\n"; system("pause"); }
058510ea04165c6f75a228706bbc6c1dfcd7486c
ca04a2ea63e047d29c3c55e3086a9a67dadfbff3
/Source/servers/Shared/Utility/ObjPool.cpp
35a0868dc0aa705bfe990df8346a066da9627427
[]
no_license
brucelevis/HMX-Server
0eebb7d248c578d6c930c15670927acaf4f13c3d
7b9e21c0771ee42db2842bb17d85d219c8e668d7
refs/heads/master
2020-08-03T17:37:44.209223
2016-06-13T08:49:39
2016-06-13T08:49:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
75
cpp
ObjPool.cpp
#include "ObjPool.h" UsingBlocksSet ManageInfoUsingBlocks::s_setBlocks;
727174092bd755faf57634ccde9b988520604aa8
a6583bbb97528be27123449aa2dbd052cd251ac8
/utils.cpp
a038a1340c5e78aba9489c8f52105c96191e8065
[]
no_license
FrancoPinoC/InfoRetrieval-Hw1
88b331c06abf666a34fb166816080b9dfb17bcb2
733756abc4a9fcaeb3c88f30a74d2c746458aa58
refs/heads/master
2020-04-01T08:55:08.384666
2018-10-22T20:07:12
2018-10-22T20:07:12
153,052,083
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cpp
utils.cpp
#include "utils.h" #include <iostream> #include <vector> #include <opencv2/opencv.hpp> // With thanks to https://stackoverflow.com/a/4430900/4192226 std::string extractNameFromPath(const std::string &fullPath) { // To be file name with the extension (if it has one) std::string filename; // Only the name without the extension std::string name; size_t sep = fullPath.find_last_of("\\/"); if(sep != std::string::npos) { filename = fullPath.substr(sep + 1, fullPath.size() - sep - 1); } size_t dot = filename.find_last_of('.'); if (dot != std::string::npos) {name = filename.substr(0, dot);} else {name = filename;} return name; } unsigned long amountSampled(unsigned long totalFrames, int sampleRate) { return (((totalFrames - 1)/ sampleRate) + 1); } // Euclidean distance func (without square-rooting) long euclideanDist(std::vector<int> &a, std::vector<int> &b) { long res = 0; // Assumes they're both the same size for(unsigned long i = 0; i < a.size(); i++){ long diff = a[i] - b[i]; res += diff*diff; } return res; } // Euclidian distance, but one argument is a Mat that we are gonna treat as a vector and the other actually a vector. long matVectEuclideanDist(cv::Mat &frame, std::vector<int> &desc) { // Because I mean, why go over that Mat twice (once to make it a vect, another to caluclate dist)? long res = 0; unsigned long vecIndex = 0; for(int row = 0; row < frame.rows; row++){ for(int col = 0; col < frame.cols; col++) { long diff = (int)frame.at<uchar>(row, col) - desc[vecIndex++]; res += diff*diff; } } return res; } // In case I actually end up just keeping everything in memory all the time long matMatEcuclideanDist(cv::Mat &a, cv::Mat &b) { // Because I mean, why go over that Mat twice (once to make it a vect, another to caluclate dist)? long res = 0; unsigned long vecIndex = 0; for(int row = 0; row < a.rows; row++){ for(int col = 0; col < a.cols; col++) { long diff = (int)a.at<uchar>(row, col) - (int)b.at<uchar>(row, col); res += diff*diff; } } return res; }
e5784e822725818c41fb7f3d703d517538a7f271
21c0a8588978cf4ecc31d827d4e5b778401f9eee
/codeforces/100625J.cpp
a8aa4d2b3805bcbb266cfaed233c0c75f19bf678
[ "MIT" ]
permissive
cosmicray001/Online_judge_Solutions
c082faa9cc8c9448fa7be8504a150a822d0d5b8a
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
refs/heads/master
2022-03-01T12:35:28.985743
2022-02-07T10:29:16
2022-02-07T10:29:16
116,611,495
3
1
null
null
null
null
UTF-8
C++
false
false
1,596
cpp
100625J.cpp
#include <bits/stdc++.h> #define le 102 using namespace std; char n[le][le], pa[le][le]; int ans, dis[le][le]; bool vis[le][le]; int fx[] = {1, -1, 0, 0}, fy[] = {0, 0, 1, -1}; int bfs(int a, int b, int r, int c){ for(int i = 0; i < r; i++) for(int j = 0; j < c; vis[i][j] = false, pa[i][j] = n[i][j], dis[i][j] = 0, j++); vis[a][b] = true; pa[a][b] = n[a][b]; dis[a][b] = 0; deque<pair<int, int> > de; de.push_back(make_pair(a, b)); while(!de.empty()){ pair<int, int> p = de.front(); de.pop_back(); int a = p.first, b = p.second; for(int i = 0; i < 4; i++){ int px = b + fx[i], py = a + fy[i]; if(py >= 0 && py < r && px >= 0 && px < c && vis[py][px] == false && n[py][px] != '*'){ vis[py][px] = true; if(n[py][px] == '#'){ dis[py][px] = 1 + dis[a][b]; de.push_back(make_pair(py, px)); } else{ dis[py][px] = dis[a][b]; de.push_front(make_pair(py, px)); } if(py == 0 || py == r - 1 || px == 0 || px == c - 1) return dis[py][px]; } } } return 0; } int main(){ int t, r, c; string s; vector<pair<int, int> > pnt; for(scanf("%d", &t); t--; ){ scanf("%d %d", &r, &c); for(int i = 0; i < r; i++){ cin >> s; for(int j = 0; j < c; j++){ n[i][j] = s[j]; if(s[j] == '$') pnt.push_back(make_pair(i, j)); } } ans = 0; for(int i = 0; i < pnt.size(); i++){ int a = pnt[i].first, b = pnt[i].second; if(!eck[a][b]) ans += bfs(a, b, r, c); } printf("%d\n", ans); pnt.clear(); } }
2196411b0698df95503029ad92e3aa84a582df16
f0ae208cb9540b1ad918c4fa104eea34d5dd4712
/whiteblack/Top/Top.h
3373fce0586d2e744aa421b2d16dfbba801f0047
[]
no_license
flat0531/blackwhite
9b1a7038cbd639c9529bb707c2073d8b7579e22f
da8d8161f1fe6ff7e270c6b24bcb2abde9deebeb
refs/heads/master
2020-12-26T03:55:30.436259
2016-01-06T07:59:44
2016-01-06T07:59:44
47,870,330
0
0
null
2016-01-06T07:59:44
2015-12-12T08:20:59
C++
SHIFT_JIS
C++
false
false
1,101
h
Top.h
#pragma once #include "星名.h" #include "GamePad.h" //向き //使うときは型指定をしてあげる enum class DIRECTION { UP, DOWN, LEFT, RIGHT, NON }; //ブロックの大きさ enum class BLOCKSIZE { WIDTH = 100, HEIGHT = 100 }; //画面大きさ enum WINDOW { WIDTH = 1920, HEIGHT = 1080, }; ///シーン enum class SCENE { TITLE, STAGESELECT, GAME, }; //ブロックの種類 enum class BLOCK { NORMAL = 1, MOVE, FALL, DOUBLE, PLAYER_START_POS =10 }; //プレイヤーの状態 enum class CONDITION{ BLACK, WHITE, STRIPE, NONE }; //位置 //大きさ //移動量 struct Object { Vec2f pos; Vec2f size; Vec2f vec; }; //envのシングルトン class App { public: static AppEnv& get() { static AppEnv env(WIDTH, HEIGHT, false, true); return env; } }; #define env App::get() //ランダムのシングルトン class _Random { public: static Random& get() { static Random rand; return rand; } }; #define random _Random::get()
60b0f42470fb09cdb520bd605ceca78a94e808c7
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/3enraya/3enraya/cboard.cpp
fca45b581ae957abf14ba3d1d6fd18d4113ce63c
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
2,781
cpp
cboard.cpp
// Class automatically generated by Dev-C++ New Class wizard #include "cboard.h" // class's header file #include <sstream> // class constructor CBoard::CBoard() { Init(); } // class destructor CBoard::~CBoard() { } void CBoard::getDimension(int *x,int *y) const { *x=*y=3; } void CBoard::Init() { int xdim,ydim; getDimension(&xdim,&ydim); for (int y=0;y<ydim;y++) for (int x=0;x<xdim;x++) m_Ficha[y][x]=NOTHING; } void CBoard::verifDimension(int x,int y) const throw(string) { int xdim,ydim; getDimension(&xdim,&ydim); if (x<=0 || x>xdim) { ostringstream outs; outs << "coordenada x incorrecta, ponga un valor desde 1 hasta " << xdim; throw outs.str(); } if (y<=0 || y>ydim) { ostringstream outs; outs << "coordenada y incorrecta, ponga un valor desde 1 hasta " << ydim; throw outs.str(); } } void CBoard::set(EFicha ficha,int x,int y) throw(string) { EFicha fpos=get(x,y); if (fpos!=CBoard::NOTHING) { ostringstream outs; outs << "la posición (" << x << "," << y << ") esta ocupada" << ends; throw outs.str(); } m_Ficha[y-1][x-1]=ficha; } enum CBoard::EFicha CBoard::get(int x,int y) const throw(string) { verifDimension(x,y); return m_Ficha[y-1][x-1]; } CBoard::SEstado CBoard::isFinish() const { SEstado estado={false,false,NOTHING}; int xdim,ydim; getDimension(&xdim,&ydim); estado.isfinish=true; for (int y=1;y<=ydim;y++) for (int x=1;x<=xdim;x++) if (get(x,y)==NOTHING) estado.isfinish=false; estado.winer=winer(); if (estado.isfinish && estado.winer==NOTHING) estado.isempate=true; else if (estado.winer!=NOTHING) estado.isfinish=true; return estado; } CBoard::EFicha CBoard::winer() const { int xdim,ydim; getDimension(&xdim,&ydim); EFicha w=winer(1,1,1,1); if (w!=NOTHING) return w; w=winer(xdim,1,-1,1); if (w!=NOTHING) return w; for (int y=1;y<=ydim;y++) { w=winer(1,y,1,0); if (w!=NOTHING) return w; } for (int x=1;x<=xdim;x++) { w=winer(x,1,0,1); if (w!=NOTHING) return w; } return NOTHING; } CBoard::EFicha CBoard::winer(int x,int y,int dx,int dy) const { EFicha w=get(x,y); int xdim,ydim; if (w==NOTHING) return NOTHING; getDimension(&xdim,&ydim); for (;x>=1 && x<=xdim && y>=1 && y<=ydim; x+= dx,y+= dy) if (get(x,y)!=w) return NOTHING; return w; }
b929ba39c6b95973f35fe2fc843d45645273df45
6f56e75e15fe7422288a2579f724986cc29f38d7
/Hydra/Hydra/Render/View/ViewPort.h
11df60063f3ca630ae793d821f53b35df6477332
[]
no_license
SamCZ/Hydra
1d979e817f35e70f38227d50300c8c7609c20ba4
6b1ba454ac91924f5b16218e4db0ce3864603fab
refs/heads/master
2022-05-06T23:18:21.532030
2022-04-02T13:02:40
2022-04-02T13:02:40
171,286,292
14
2
null
2020-04-08T14:24:16
2019-02-18T13:09:12
C++
UTF-8
C++
false
false
592
h
ViewPort.h
#pragma once #include "Hydra/Core/Delegate.h" #include "Hydra/Render/View/SceneView.h" class FViewPort { private: int _Width; int _Height; bool _IsSizeValid; FSceneView* _SceneView; DelegateEvent<void, int, int> _OnResizeEvent; public: FViewPort(); FViewPort(int width, int height); void SetSceneView(FSceneView* view); FSceneView* GetSceneView(); void Resize(int width, int height); int GetWidth() const; int GetHeight() const; bool IsValid() const; void AddResizeListener(const NammedDelegate<void, int, int>& Event); void RemoveListener(const String& EventName); };
5cc7275a46d8404516fe673f49637030c3b6886c
7f1a4ca6e2e51c560e27e84b52908cae77c2eac6
/Code Forces Gym/ACPC 18/a.cpp
ecbaaf3b0ef756c9960cf3ee60275dc66319b4b4
[]
no_license
gabrielmorete/Competitive-Programming
ebab7d03c341c5a90b4536564122feb8183d2923
724771c6f3cf20758bfd417f1138f02ae230e88b
refs/heads/master
2023-03-04T14:09:43.768784
2023-02-25T22:53:14
2023-02-25T22:53:14
206,603,364
5
0
null
null
null
null
UTF-8
C++
false
false
2,571
cpp
a.cpp
#include "bits/stdc++.h" using namespace std; #define pb push_back #define fst first #define snd second #define fr(i,n) for (int i = 0; i < n; i++) #define frr(i,n) for (int i = 1; i <= n; i++) #define endl '\n' #define gnl cout << endl #define chapa cout << "oi meu chapa" << endl #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL) //cout << setprecision(9)<<fixed; #define dbg(x) cout << #x << " = " << x << endl #define all(x) x.begin(),x.end() typedef long long int ll; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector<pii> vii; const int INF = 0x3f3f3f3f; const ll llINF = (long long)(1e18) + 100; const int MAXN = 5e5 + 10; ll n, m; ll t[2 * MAXN]; void modify(int p, int value) { for (t[p += n] += value; p > 1; p >>= 1) t[p>>1] = t[p] + t[p^1]; } ll query(int l, int r) { // sum on interval [l, r) ll res = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) res += t[l++]; if (r&1) res += t[--r]; } return res; } int sz[MAXN], dep[MAXN], in[MAXN], out[MAXN], rt[MAXN], clk; vi adj[MAXN]; void dfs_sz(int v, int p = -1){ sz[v] = 1; in[v] = clk; rt[clk++] = v; for (auto &x : adj[v]){ if (x != p){ dep[x] = dep[v] + 1; dfs_sz(x, v); sz[v] += sz[x]; if (sz[x] > sz[adj[v][0]] or adj[v][0] == p) // adj[v][0] é sempre o filho pesado swap(x, adj[v][0]); } } out[v] = clk - 1; } ll dfs(int v, int p, int val, bool keep = 0){ int bc = adj[v].size() > 1 ? adj[v][0] : -1; ll ans = 0; for (int u : adj[v]){ if (u != p and u != bc) ans += dfs(u, v, val); } if (bc != -1) ans += dfs(bc, v, val, 1); for (auto u : adj[v]) if (u != p and u != bc){ for(int x = in[u]; x <= out[u]; x++){ int k = rt[x]; if (val + (2 * dep[v]) - dep[k] > 0) ans += query(0, val + (2 * dep[v]) - dep[k] + 1); } for(int x = in[u]; x <= out[u]; x++){ int k = rt[x]; modify(dep[k], 1); } } ans += query(0, val + dep[v] + 1); modify(dep[v], 1); if (!keep){ for(int x = in[v]; x <= out[v]; x++){ int k = rt[x]; modify(dep[k], -1); // diminui uma cor nessa freq } } return ans; } void solve(){ int l, r; cin>>n>>l>>r; fr(i, n + 10) adj[i].clear(); int x, y; fr(i, n - 1){ cin>>x>>y; adj[x].pb(y); adj[y].pb(x); } dep[1] = clk = 0; dfs_sz(1); memset(t, 0, sizeof t); ll ans = dfs(1, 1, n - l - 1, 0); ans -= dfs(1, 1, n - r - 2, 0); cout<<ans<<endl; } int32_t main(){ fastio; freopen("awesome.in", "r", stdin); int T; cin>>T; while (T--) solve(); }
8dea290f741065d140ce3d64a68f1da23a5dbdc8
a88f9ad517ad4dd943507824a94c1d1d8d402f35
/parallelManagers/PetscParallelManager.h
f52f7ce90150dc91bf432de6cf577de00c087266
[]
no_license
szymak/TurbulentFlowInHPC_Project
b6a05559a76d39eb8c0a950d6a1c2ba775fc914c
cff1169fd52f469e0309a260e7f2385ebaca3d49
refs/heads/master
2021-01-10T02:47:17.805666
2016-01-27T13:46:10
2016-01-27T13:46:10
49,265,068
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
h
PetscParallelManager.h
#ifndef __PETSC_PARALLEL_MANAGER_H__ #define __PETSC_PARALLEL_MANAGER_H__ #include "../FlowField.h" #include "../Parameters.h" #include "../Iterators.h" #include "../stencils/PressureBufferFillStencil.h" #include "../stencils/PressureBufferReadStencil.h" #include "../stencils/VelocityBufferFillStencil.h" #include "../stencils/VelocityBufferReadStencil.h" class PetscParallelManager { protected: int _cellsX; int _cellsY; int _cellsZ; // Set to 1 for 2D case // Number of elements in the parallel boundaries int _cellsLeftRight; int _cellsTopBottom; int _cellsFrontBack; Parameters &_parameters; FlowField &_flowField; // Buffers FLOAT *_pressureSendBufferLeftWall; FLOAT *_pressureRecvBufferLeftWall; FLOAT *_pressureSendBufferRightWall; FLOAT *_pressureRecvBufferRightWall; FLOAT *_pressureSendBufferTopWall; FLOAT *_pressureRecvBufferTopWall; FLOAT *_pressureSendBufferBottomWall; FLOAT *_pressureRecvBufferBottomWall; FLOAT *_pressureSendBufferFrontWall; FLOAT *_pressureRecvBufferFrontWall; FLOAT *_pressureSendBufferBackWall; FLOAT *_pressureRecvBufferBackWall; FLOAT *_velocitySendBufferLeftWall; FLOAT *_velocityRecvBufferLeftWall; FLOAT *_velocitySendBufferRightWall; FLOAT *_velocityRecvBufferRightWall; FLOAT *_velocitySendBufferTopWall; FLOAT *_velocityRecvBufferTopWall; FLOAT *_velocitySendBufferBottomWall; FLOAT *_velocityRecvBufferBottomWall; FLOAT *_velocitySendBufferFrontWall; FLOAT *_velocityRecvBufferFrontWall; FLOAT *_velocitySendBufferBackWall; FLOAT *_velocityRecvBufferBackWall; // Stencils PressureBufferFillStencil _pressureBufferFillStencil; PressureBufferReadStencil _pressureBufferReadStencil; VelocityBufferFillStencil _velocityBufferFillStencil; VelocityBufferReadStencil _velocityBufferReadStencil; // Iterators ParallelBoundaryIterator<FlowField> _pressureBufferFillIterator; ParallelBoundaryIterator<FlowField> _pressureBufferReadIterator; ParallelBoundaryIterator<FlowField> _velocityBufferFillIterator; ParallelBoundaryIterator<FlowField> _velocityBufferReadIterator; public: PetscParallelManager(FlowField &flowField, Parameters &parameters); ~PetscParallelManager(); void communicatePressure(); void communicateVelocity(); void sendReceive(FLOAT *sendBuffer, int sendTo, FLOAT *receiveBuffer, int receiveFrom, int size); }; #endif
c6404071e013e3102ddf4bdb24d73dd59b7f0c13
150c9a12b0911d9747b052cbbfe6e49f4faa75e5
/Linked List/Implement Queue using LL__ Sankalp.cpp
b5d3dfca830087e555b3eeeef46b44de54d75f4f
[]
no_license
theorangeguy1999/GFG-Must-do
f052f7bd04cd703c1b2c783711e53115b36f2663
a17ff934d058c45c6ac5807bacf9df36c402c245
refs/heads/master
2023-06-19T23:48:32.253384
2021-07-21T14:04:05
2021-07-21T14:04:05
281,478,682
8
11
null
2021-07-21T11:36:46
2020-07-21T18:50:56
C++
UTF-8
C++
false
false
776
cpp
Implement Queue using LL__ Sankalp.cpp
void MyQueue:: push(int x) { QueueNode *temp = new QueueNode(x); // Your Code if(front == NULL) { front = temp; rear = temp; } else { rear->next = temp; rear = temp; } } /*The method pop which return the element poped out of the queue*/ int MyQueue :: pop() { if(front == NULL) return -1; if(front == rear) { QueueNode *temp = front; int tempdata = temp ->data; front = rear = NULL; delete(temp); return tempdata; } else { QueueNode *temp = front; int tempdata = temp -> data; front = front -> next; delete(temp); return tempdata; } }
b935f2a43dc47ad3c2d8f7dacbfd5328fc14d7c4
cc2720c268fd9621077d1330efa1d4c5554357bd
/jump_step/test1.cc
a60cc3a49983b4855d2866df04a20f32d6484dbd
[]
no_license
xjhahah/Sword_for_offer
1e7cc01ff2b3b3d32257d9b206a05c0c4623acb9
c327af2aaa8337de83cfb9259d98627009a710d7
refs/heads/master
2020-04-18T06:30:04.022870
2019-01-24T09:12:59
2019-01-24T09:12:59
167,323,466
0
0
null
null
null
null
UTF-8
C++
false
false
590
cc
test1.cc
#include <iostream> using namespace std; //跳台阶 class Solution { public: Solution() {} ~Solution() {} int jumpFloor(int number) { int first = 1; int second =2; int result = 0; if(number>=0 && number <=1) return number; else if(number == 2) return 2; else { for(int i=3 ;i<=number ; ++i) { result = first + second; first = second; second = result; } } return result; } }; int main() { Solution s; cout<<s.jumpFloor(10)<<endl; return 0; }
1cbaea494ef316cfa5c4e7d23e9ba0131c0de5fa
fdf6b097f635a861e89323f1d7c9a40ecf788a88
/include/chips/menu/menu_handler.hpp
7673f524378185d471beb4fd27c34bc0f586e7dc
[]
no_license
EricWF/chips
db1057670b5297988ea7323fac35cd5919a0b8d8
3e5dadb7055ae69baa28e6df95920394439dafce
refs/heads/master
2020-06-01T19:45:02.790868
2014-06-17T06:13:13
2014-06-17T06:13:13
16,317,898
10
0
null
null
null
null
UTF-8
C++
false
false
994
hpp
menu_handler.hpp
#ifndef CHIPS_MENU_MENU_HANDLER_HPP #define CHIPS_MENU_MENU_HANDLER_HPP # include "chips/menu/core.hpp" # include "chips/menu/text_button.hpp" # include <elib/aux.hpp> # include <SFML/Graphics.hpp> # include <vector> namespace chips { class menu_handler { public: //ELIB_DEFAULT_CLASS(menu_handler); menu_handler(); void set_menu(sf::RenderWindow const &, std::vector<button_info> const &); menu_item_id handle_event(sf::RenderWindow &); void draw(sf::RenderWindow & to); private: menu_item_id m_handle_mouse_click( sf::RenderWindow const & , sf::Event const & ); void m_handle_mouse_move( sf::RenderWindow const & , sf::Event const & ); std::vector<text_button> m_buttons; sf::Text m_title; }; } // namespace chips #endif /* CHIPS_MENU_MENU_HANDLER_HPP */
45c576b9880b58ab2198080a93f7f2905db59921
a148aadf35d7976a690ff13cdd284dd901ef076b
/src/adapt/AAdapt_Erosion.cpp
8182b0335bf3f84b115527ecd3919ba6905caeaa
[ "BSD-2-Clause" ]
permissive
kel85uk/Albany
51d1f664c7956e80e61f03bf04caccb3c94ec869
75bcde010070fa55bfe5411169794e4017a128e2
refs/heads/master
2020-04-29T03:37:46.647821
2019-06-04T18:37:30
2019-06-04T18:37:30
175,817,526
0
0
NOASSERTION
2019-03-15T12:36:55
2019-03-15T12:36:53
null
UTF-8
C++
false
false
3,016
cpp
AAdapt_Erosion.cpp
//*****************************************************************// // Albany 3.0: Copyright 2016 Sandia Corporation // // This Software is released under the BSD license detailed // // in the file "license.txt" in the top-level Albany directory // //*****************************************************************// #include <Teuchos_TimeMonitor.hpp> #include <stk_util/parallel/ParallelReduce.hpp> #include "AAdapt_Erosion.hpp" #include "LCM/utils/topology/Topology_FailureCriterion.h" namespace AAdapt { // // // AAdapt::Erosion::Erosion( Teuchos::RCP<Teuchos::ParameterList> const& params, Teuchos::RCP<ParamLib> const& param_lib, Albany::StateManager const& state_mgr, Teuchos::RCP<Teuchos_Comm const> const& comm) : AAdapt::AbstractAdapter(params, param_lib, state_mgr, comm), remesh_file_index_(1) { discretization_ = state_mgr_.getDiscretization(); stk_discretization_ = static_cast<Albany::STKDiscretization*>(discretization_.get()); stk_mesh_struct_ = stk_discretization_->getSTKMeshStruct(); bulk_data_ = stk_mesh_struct_->bulkData; meta_data_ = stk_mesh_struct_->metaData; num_dim_ = stk_mesh_struct_->numDim; // Save the initial output file name base_exo_filename_ = stk_mesh_struct_->exoOutFile; topology_ = Teuchos::rcp(new LCM::Topology(discretization_)); std::string const fail_indicator_name = "ACE Failure Indicator"; failure_criterion_ = Teuchos::rcp( new LCM::BulkFailureCriterion(*topology_, fail_indicator_name)); topology_->set_failure_criterion(failure_criterion_); } // // // bool AAdapt::Erosion::queryAdaptationCriteria(int) { return topology_->there_are_failed_cells(); } // // // bool AAdapt::Erosion::adaptMesh() { *output_stream_ << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" << "Adapting mesh using AAdapt::Erosion method \n" << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; // Save the current results and close the exodus file // Create a remeshed output file naming convention by // adding the remesh_file_index_ ahead of the period std::ostringstream ss; std::string str = base_exo_filename_; ss << "_" << remesh_file_index_ << "."; str.replace(str.find('.'), 1, ss.str()); *output_stream_ << "Remeshing: renaming output file to - " << str << '\n'; // Open the new exodus file for results stk_discretization_->reNameExodusOutput(str); remesh_file_index_++; // Start the mesh update process topology_->erodeFailedElements(); // Throw away all the Albany data structures and re-build them from the mesh stk_discretization_->updateMesh(); return true; } // // // Teuchos::RCP<Teuchos::ParameterList const> AAdapt::Erosion::getValidAdapterParameters() const { Teuchos::RCP<Teuchos::ParameterList> valid_pl_ = this->getGenericAdapterParams("ValidErosionParams"); return valid_pl_; } } // namespace AAdapt
5688ac2d723e71f275cb5acf69cbfab6be8609c2
3b984fb1a0f84bfe6dc0b4ec34a042581cb53812
/OptionsPane.h
de1bc78a2e9ae3b9eb96ea3423cfa8a2571b8238
[]
no_license
mackthehobbit/MCPE-Headers
78cf741bc1081471fab4506cdda4808b0c8417cc
adf073d666cc63dbc640a455c4907da522929307
refs/heads/master
2021-01-17T09:35:08.454693
2016-08-29T03:28:45
2016-08-29T03:28:45
66,353,700
0
0
null
2016-08-23T09:36:05
2016-08-23T09:36:04
null
UTF-8
C++
false
false
284
h
OptionsPane.h
#pragma once #include "PackedScrollContainer.h" class OptionsGroup; class OptionsPane : public PackedScrollContainer { public: virtual ~OptionsPane(); virtual void setupPositions(); virtual void suppressInput(); OptionsGroup *createOptionsGroup(std::string const &, bool); };
5622effa205f600c31861af715505fa6a8c50ae1
4f5d5dbd7a4291cc83ee55c1972295e885ed5056
/Arduino codes/Motors.ino
c4cbe3c8d88c8281bfdba8b266d5842f6ea4ad13
[]
no_license
chl64/self-balancing-robot
a5790bd49cd3516b9d324e4d9ea263d4aa4bd3bc
ead6a8b74343d9c671edc1db0a0a108c5147c421
refs/heads/master
2020-04-11T09:20:46.805913
2019-12-28T11:02:54
2019-12-28T11:02:54
161,674,363
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
ino
Motors.ino
//UNO to MC pins /*All pins can produce PWM. pins 5 and 6 are not chosen because they use the same clock as other features so generate higher-than-expected duty cycles when duty-cycle is low (or zero).*/ //A is left wheel, B is right wheel. const int A1IN = 3; const int A2IN = 9; const int B2IN = 10; const int B1IN = 11; void MotorsSetup() { pinMode(A1IN, OUTPUT); pinMode(A2IN, OUTPUT); pinMode(B2IN, OUTPUT); pinMode(B1IN, OUTPUT); } void MotorsMoveByPID(int output) { if (output >= 0) { MotorsMoveForward(output); } else { MotorsMoveBackward(-output); } } void MotorsMoveForward(int PWMspeed) { //Forward left wheel. analogWrite(A1IN, PWMspeed); analogWrite(A2IN, 0); //Reverse right wheel to go forward. analogWrite(B1IN, 0); analogWrite(B2IN, PWMspeed); } void MotorsMoveBackward(int PWMspeed) { //Reverse left wheel. analogWrite(A1IN, 0); analogWrite(A2IN, PWMspeed); //Forward right wheel to reverse. analogWrite(B1IN, PWMspeed); analogWrite(B2IN, 0); } void MotorsBrake() { analogWrite(A1IN, 255); analogWrite(A2IN, 255); analogWrite(B1IN, 255); analogWrite(B2IN, 255); } void MotorsCoast() { analogWrite(A1IN, 0); analogWrite(A2IN, 0); analogWrite(B1IN, 0); analogWrite(B2IN, 0); }
a607ff76e188ace4221b8554b2f9ab288c52cccc
183beca53e835a7a2811c138d8a43a0782efb3c3
/oneflow/user/kernels/elementwise_maximum_minimum_kernel.cpp
73c963c2a8cf5875c28bc84746879c8d956429fa
[ "Apache-2.0" ]
permissive
WhatAboutMyStar/oneflow
fa8b837e5d3d96a6bff068ee9a5c9aa43d6725a0
41e3539247e51416d4799a3a3970df7efefe263b
refs/heads/master
2023-02-15T12:36:42.616433
2021-01-16T08:35:01
2021-01-16T08:35:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,380
cpp
elementwise_maximum_minimum_kernel.cpp
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/common/util.h" #include "oneflow/core/framework/framework.h" #include "oneflow/core/kernel/kernel_util.h" namespace oneflow { namespace user_op { template<template<typename> class Functor, typename T> class CpuElementwiseMaximumMinimumKernel final : public user_op::OpKernel { public: CpuElementwiseMaximumMinimumKernel() = default; ~CpuElementwiseMaximumMinimumKernel() = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const user_op::Tensor* tensor_x = ctx->Tensor4ArgNameAndIndex("x", 0); const user_op::Tensor* tensor_y = ctx->Tensor4ArgNameAndIndex("y", 0); user_op::Tensor* tensor_z = ctx->Tensor4ArgNameAndIndex("z", 0); const T* x = tensor_x->dptr<T>(); const T* y = tensor_y->dptr<T>(); T* z = tensor_z->mut_dptr<T>(); int64_t n = tensor_x->shape().elem_cnt(); FOR_RANGE(int64_t, i, 0, n) { z[i] = Functor<T>::Forward(x[i], y[i]); } } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; template<template<typename> class Functor, typename T> class CpuElementwiseMaximumMinimumBackwardKernel final : public user_op::OpKernel { public: CpuElementwiseMaximumMinimumBackwardKernel() = default; ~CpuElementwiseMaximumMinimumBackwardKernel() = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { user_op::Tensor* tensor_dz = ctx->Tensor4ArgNameAndIndex("dz", 0); user_op::Tensor* tensor_x = ctx->Tensor4ArgNameAndIndex("x", 0); user_op::Tensor* tensor_y = ctx->Tensor4ArgNameAndIndex("y", 0); user_op::Tensor* tensor_dx = ctx->Tensor4ArgNameAndIndex("dx", 0); user_op::Tensor* tensor_dy = ctx->Tensor4ArgNameAndIndex("dy", 0); const T* dptr_dz = tensor_dz->dptr<T>(); const T* dptr_x = tensor_x->dptr<T>(); const T* dptr_y = tensor_y->dptr<T>(); T* dptr_dx = tensor_dx ? tensor_dx->mut_dptr<T>() : nullptr; T* dptr_dy = tensor_dy ? tensor_dy->mut_dptr<T>() : nullptr; size_t bytes_size = tensor_dz->shape().elem_cnt() * GetSizeOfDataType(tensor_dz->data_type()); if (dptr_x) { Memset<DeviceType::kCPU>(ctx->device_ctx(), dptr_dx, 0, bytes_size); } if (dptr_y) { Memset<DeviceType::kCPU>(ctx->device_ctx(), dptr_dy, 0, bytes_size); } Functor<T>::Backward(tensor_dz->shape().elem_cnt(), dptr_dz, dptr_x, dptr_y, dptr_dx, dptr_dy); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_FORWARD_CPU_KERNEL(op_type_name, functor, dtype) \ REGISTER_USER_KERNEL(op_type_name) \ .SetCreateFn<CpuElementwiseMaximumMinimumKernel<functor, dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == DeviceType::kCPU) \ & (user_op::HobDataType("x", 0) == GetDataType<dtype>::value) \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value)); #define REGISTER_BACKWARD_CPU_KERNEL(op_type_name, functor, dtype) \ REGISTER_USER_KERNEL(std::string("") + op_type_name + "_backward") \ .SetCreateFn<CpuElementwiseMaximumMinimumBackwardKernel<functor, dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == DeviceType::kCPU) \ & (user_op::HobDataType("dz", 0) == GetDataType<dtype>::value)); #define REGISTER_FORWARD_BACKWARD_KERNELS(op_type_name, functor, dtype) \ REGISTER_FORWARD_CPU_KERNEL(op_type_name, functor, dtype); \ REGISTER_BACKWARD_CPU_KERNEL(op_type_name, functor, dtype); namespace { template<typename T> struct CpuMaximumFunctor { static T Forward(const T x, const T y) { return x > y ? x : y; } static void Backward(const int64_t n, const T* dz, const T* x, const T* y, T* dx, T* dy) { FOR_RANGE(int64_t, idx, 0, n) { if (x[idx] > y[idx]) { if (dx) { dx[idx] = dz[idx]; } } else { if (dy) { dy[idx] = dz[idx]; } } } } }; template<typename T> struct CpuMinimumFunctor { static T Forward(const T x, const T y) { return x < y ? x : y; } static void Backward(const int64_t n, const T* dz, const T* x, const T* y, T* dx, T* dy) { FOR_RANGE(int64_t, idx, 0, n) { if (x[idx] < y[idx]) { if (dx) { dx[idx] = dz[idx]; } } else { if (dy) { dy[idx] = dz[idx]; } } } } }; } // namespace REGISTER_FORWARD_BACKWARD_KERNELS("elementwise_maximum", CpuMaximumFunctor, float); REGISTER_FORWARD_BACKWARD_KERNELS("elementwise_maximum", CpuMaximumFunctor, double); REGISTER_FORWARD_BACKWARD_KERNELS("elementwise_minimum", CpuMinimumFunctor, float); REGISTER_FORWARD_BACKWARD_KERNELS("elementwise_minimum", CpuMinimumFunctor, double); } // namespace user_op } // namespace oneflow
efe423afdbcdfdda636f945ed8d7c0aa9aecc904
c10dfdfb24c9b6505ca63131938d7fc65b9063f2
/src/cocCirclePacker.h
4feb7f69899af7f83618cd6289b00887ac8ef0c0
[ "MIT" ]
permissive
codeoncanvas/coc-circlepacker
fc214e1eaee27c96efa5117172fa46e101c5e02c
de630a0df15a45fac9e4f7256126ddbffb85db03
refs/heads/master
2020-04-18T14:55:38.656565
2017-03-06T03:31:26
2017-03-06T03:31:26
66,892,602
0
0
null
null
null
null
UTF-8
C++
false
false
2,733
h
cocCirclePacker.h
/** * * ┌─┐╔═╗┌┬┐┌─┐ * │ ║ ║ ││├┤ * └─┘╚═╝─┴┘└─┘ * ┌─┐┌─┐╔╗╔┬ ┬┌─┐┌─┐ * │ ├─┤║║║└┐┌┘├─┤└─┐ * └─┘┴ ┴╝╚╝ └┘ ┴ ┴└─┘ * * Copyright (c) 2016 Code on Canvas Pty Ltd, http://CodeOnCanvas.cc * * This software is distributed under the MIT license * https://tldrlegal.com/license/mit-license * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code * **/ #pragma once #include "cocCore.h" namespace coc { //-------------------------------------------------------------- class CirclePacker; typedef std::shared_ptr<CirclePacker> CirclePackerRef; class CirclePacker { public: static CirclePackerRef create() { return CirclePackerRef(new CirclePacker()); } //---------------------------------------------------------- class Circle; typedef std::shared_ptr<Circle> CircleRef; class Circle { public: Circle(): uid(0), pos(0, 0), radius(0), radiusMin(0), radiusMax(0), radiusGrowth(0), gap(0), count(0), bAlive(true) { // } float getRadius() const { return radius + gap; } float getRadiusNext() const { return radius + radiusGrowth + gap; } float getRadiusMax() const { return radiusMax + gap; } unsigned int uid; // unique id. glm::vec2 pos; float radius; float radiusMin; float radiusMax; float radiusGrowth; float gap; int count; bool bAlive; std::vector<CircleRef> neighbours; }; //---------------------------------------------------------- virtual CircleRef initCircle() const { return CircleRef(new Circle()); } void reset(); CircleRef & addCircle(const CircleRef & circle); CircleRef & addCircle(float x, float y, float radius, float gap=0); CircleRef & addCircle(float x, float y, float radiusMin, float radiusMax, float radiusGrowth, float gap=0); CircleRef & addCircleToRandomPositionWithinBounds(float radius, const coc::Rect & bounds, float gap=0); CircleRef & addCircleToRandomPositionWithinBounds(float radiusMin, float radiusMax, float radiusGrowth, const coc::Rect & bounds, float gap=0); std::vector<CircleRef> & getCircles() { return circles; } virtual void update(float timeDelta=0); virtual void draw() const {} protected: std::vector<CircleRef> circles; std::vector<CircleRef> circlesToAdd; }; }
c6e2c75ee42f4f6eb7bb2c88812182541e320c84
f148b0348c5c97fc28d869892960f4721f4534bc
/JRTestPassword/WBLoginSDK/Dependence/TencentSDK/rapidnet_ios.framework/Headers/rpd_reshuffle_channel.h
89515c15c78c3a8fb8414854a59aa0529e818f7b
[]
no_license
GG-beyond/JRTestPassword
b2e8629cbbad23b9b5d23a9b13782162be684eb5
9a5db3be7abc619833ee3cde5d2db000b7e40eb1
refs/heads/master
2020-04-12T14:18:27.197164
2018-12-20T11:45:53
2018-12-20T11:45:53
162,548,331
0
0
null
null
null
null
UTF-8
C++
false
false
2,419
h
rpd_reshuffle_channel.h
#ifndef RAPIDNET_UTILS_RPD_RESHUFFLE_CHANNEL_H_ #define RAPIDNET_UTILS_RPD_RESHUFFLE_CHANNEL_H_ #include <string.h> #include "shared_blob.h" #include "rpdblob.h" namespace rpdnet{ template<class T> void nchw_2_nhwc(T* data, T* buffer, int num, int channel, int height, int width) { bool is_buffer_ready = true; if(buffer == NULL) { is_buffer_ready = false; buffer = (T*) malloc(num*channel*height*width*sizeof(T)); } for(int n=0; n<num; ++n) { for(int c=0; c<channel; ++c) { for(int h=0; h<height; ++h) { for(int w=0; w<width; ++w) { buffer[n*height*width*channel + h*width*channel + w*channel + c] = data[n*channel*height*width + c*height*width + h*width + w]; } } } } memcpy(data, buffer, num*height*width*channel*sizeof(T)); if(!is_buffer_ready) { free(buffer); } } template<class T> void nchw_2_nhwc(rpd_blob<T>& blob, T* buffer) { nchw_2_nhwc(blob.data(), buffer, blob.num(), blob.channel(), blob.height(), blob.width()); } template<class T> void nchw_2_nhwc(SharedBlob<T>& blob, T* buffer) { nchw_2_nhwc(blob.data(), buffer, blob.num(), blob.channel(), blob.height(), blob.width()); } template<class T> void nhwc_2_nchw(T* data, T* buffer, int num, int channel, int height, int width) { bool is_buffer_ready = true; if(buffer == NULL) { is_buffer_ready = false; buffer = (T*) malloc(num*channel*height*width*sizeof(T)); } for(int n=0; n<num; ++n) { for(int c=0; c<channel; ++c) { for(int h=0; h<height; ++h) { for(int w=0; w<width; ++w) { buffer[n*channel*height*width + c*height*width + h*width + w] = data[n*height*width*channel + h*width*channel + w*channel + c]; } } } } memcpy(data, buffer, num*height*width*channel*sizeof(T)); if(!is_buffer_ready) { free(buffer); } } template<class T> void nhwc_2_nchw(rpd_blob<T>& blob, T* buffer) { nhwc_2_nchw(blob.data(), buffer, blob.num(), blob.channel(), blob.height(), blob.width()); } template<class T> void nhwc_2_nchw(SharedBlob<T>& blob, T* buffer) { nhwc_2_nchw(blob.data(), buffer, blob.num(), blob.channel(), blob.height(), blob.width()); } } #endif
b29a7063a77db9e4d5411ad81e677fe5022b4453
b7d2fec08ee56858c07434a28f948568cfaebf60
/wrappers/gl/ConvexShape.hpp
40a72f4053ca59a0ada667249ceab8e043ae4f58
[]
no_license
Eren121/OpenGLTransformations
22f8c63e65b95466871122634be7d6e51d06b60a
703e2a680b477bd512bfc73bd1a7d89ef61b3a83
refs/heads/master
2023-06-25T08:07:40.767471
2021-07-29T14:16:09
2021-07-29T14:16:09
390,737,675
1
0
null
null
null
null
UTF-8
C++
false
false
884
hpp
ConvexShape.hpp
#pragma once #include "Shape.hpp" /// @brief Convex Shape. /// @details In details, the only difference between Shape is ConvexShape is that ConvexShape has public writable /// vertices. But, in theory, Shape is also convex. This simple naming convention is better, has the user does not /// need to know the Shape is concave because he will use child classes. This is somehow a different convention /// from SFML: sf::ConvexShape == Shape, sf::VertexArray = ConvexShape. /// @remarks /// If the shape is not filled or rendered with GL_LINES or GL_POINTS, then the shape can be not convex. class ConvexShape : public Shape { public: std::size_t getVerticesCount() const override; Vertex getVertex(int index) const override; void setVerticesCount(std::size_t count); void setVertex(int index, const Vertex& vertex); private: std::vector<Vertex> m_vertices; };
4b69ed9bd3b0cfc548d86fbfdd174304c8031186
5f7c5cb0eb2869f4fb3ffbd3844a16f69e2a93d4
/未命名2.cpp
8b1a643426efc560a4e82bd626c90d2369b8c715
[]
no_license
liu228979/code
a12ba33a31825cc69ba7e7450c7b99895d1b49ea
0ae69c5857f209a5e67be443bb996be41d5c960f
refs/heads/master
2023-01-23T19:40:59.859228
2020-12-01T10:16:02
2020-12-01T10:16:02
316,206,442
0
0
null
null
null
null
GB18030
C++
false
false
539
cpp
未命名2.cpp
# include<stdio.h> # include<malloc.h> void edit(int *a,int b) { int i; int j=9; for(i=0;i<b;i++) { *a+=j; a++; } // free(a); } int main(void) { int len; printf("输入数组长度\n",len); scanf("%d",&len); int j=0; int *arr = (int*)malloc(4*len); int i; for(i=0;i<len;i++) { arr[i]=j; j++; } for(i=0;i<len;i++) { printf("%d\n",arr[i]); } printf("\n\n\n"); edit(arr,len); for(i=0;i<len;i++) { printf("%d\n",arr[i]); } return 0; }
e410754bbc3a840a677a5803730f00af6f4083d3
8bc30e8e39349d679511abdbb46eef1ffbba52e0
/comuactiv/proto/src/messages/HeartbeatMsg.hpp
4ef0e0a06b3fb4a42f2e756dfa5433056bac2317
[]
no_license
WiolaK/TIN---COMUACTIV
c5b526029793ad82f76241e6108dd026fd8b391a
0db74004ad87c77ab805474038dac7c6eadc1f30
refs/heads/master
2016-08-08T04:39:51.109103
2015-06-09T12:01:07
2015-06-09T12:01:07
34,416,189
0
0
null
null
null
null
UTF-8
C++
false
false
681
hpp
HeartbeatMsg.hpp
/* * HeartbeatMsg.hpp * * Created on: 10 May 2015 * Author: Jan Kumor */ #ifndef PROTO_SRC_MESSAGES_HEARTBEATMSG_HPP_ #define PROTO_SRC_MESSAGES_HEARTBEATMSG_HPP_ #include <memory> #include "Message.hpp" #include "RawMessage.hpp" namespace comuactiv { namespace proto { namespace messages { class HeartbeatMsg: public Message { public: const static MsgCode defaultCode = HEARTBEAT; HeartbeatMsg(pRawMessage raw); virtual ~HeartbeatMsg(); static pMessage create(pRawMessage raw) { return pMessage(new HeartbeatMsg(raw)); } }; } /* namespace messages */ } /* namespace proto */ } /* namespace comuactiv */ #endif /* PROTO_SRC_MESSAGES_HEARTBEATMSG_HPP_ */
dcb9158ea2ce2cb407afceba2a59e9488cf77d5e
8f2ea5bb8e882143e75666f6ec66e50ad3aaaf44
/算法初步/贪心/A1067.cpp
491ef3ef36b42927bb23c04678e79e5114116b78
[]
no_license
HandsomeBoy2/PATAdvance
ff34c95b1f4b94348eb6747369266a5a56a44670
34d7b26d04021d9fe7072026985e7e843b628b59
refs/heads/master
2021-05-11T10:56:23.158820
2019-03-03T14:58:53
2019-03-03T14:58:53
118,116,765
0
0
null
null
null
null
UTF-8
C++
false
false
505
cpp
A1067.cpp
#include <cstdio> #include <algorithm> using namespace std; int a[100010]; int main(){ int n; scanf("%d", &n); int num, left = 0; for(int i = 0; i < n; i++){ scanf("%d", &num); a[num] = i; if(num != i && i > 0) left++; } int ans = 0, k = 1; while(left > 0){ if(a[0] == 0){ while(k < n){ if(a[k] != k){ swap(a[0], a[k]); ans++; break; } k++; } } while(a[0] != 0){ swap(a[0], a[a[0]]); ans++; left--; } } printf("%d", ans); return 0; }
a9f7620344f1256713ee5db2c21af2168d3f852e
01ed149e0d30128a9a95d8af3f81e92be1637ec8
/srook/type_traits/is_assignable.hpp
abf551ad577a38099fe56b762f0ae5d774f7ba0c
[ "MIT" ]
permissive
falgon/SrookCppLibraries
59e1fca9fb8ed26aba0e3bf5677a52bbd4605669
ebcfacafa56026f6558bcd1c584ec774cc751e57
refs/heads/master
2020-12-25T14:40:34.979476
2020-09-25T11:46:45
2020-09-25T11:46:45
66,266,655
1
1
MIT
2018-12-31T15:04:38
2016-08-22T11:23:24
C++
UTF-8
C++
false
false
1,675
hpp
is_assignable.hpp
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_TYPE_TRAITS_IS_ASSIGNABLE_HPP #define INCLUDED_SROOK_TYPE_TRAITS_IS_ASSIGNABLE_HPP #include <srook/config/cpp_predefined/feature_testing.hpp> #include <srook/config/feature.hpp> #include <srook/type_traits/detail/sfinae_types.hpp> #include <srook/type_traits/bool_constant.hpp> #include <srook/utility/declval.hpp> #ifdef __GNUC__ # if __GNUC__ >= 8 # define SROOK_HAS_GLIBCXX_INTRINSICS_IS_ASSIGNABLE 1 // see also: https://github.com/gcc-mirror/gcc/blob/da8dff89fa9398f04b107e388cb706517ced9505/libstdc%2B%2B-v3/ChangeLog-2017#L2546 # endif #endif namespace srook { namespace type_traits { SROOK_INLINE_NAMESPACE(v1) namespace detail { template <class T, class U> class is_assignable_impl : public sfinae_types { template <class T1, class U1> static SROOK_DECLTYPE((srook::declval<T1>() = srook::declval<U1>(), one())) test(int); template <class, class> static two test(...); public: static SROOK_CONSTEXPR_OR_CONST bool value = sizeof(test<T, U>(0)) == 1; }; } // namespace detail #ifdef SROOK_HAS_GLIBCXX_INTRINSICS_IS_ASSIGNABLE template <class T, class U> struct is_assignable : public bool_constant <__is_assignable(T, U)> {}; #else template <class T, class U> struct is_assignable : public bool_constant<detail::is_assignable_impl<T, U>::value> {}; #endif SROOK_INLINE_NAMESPACE_END } // namespace type_traits using type_traits::is_assignable; #if SROOK_CPP_VARIABLE_TEMPLATES template <class T, class U> static SROOK_INLINE_VARIABLE SROOK_CONSTEXPR bool is_assignable_v = is_assignable<T, U>::value; #endif } // namespace srook #endif
51e264af6fdd928b789dcd370d594fcb975cadd4
bb21426a84061dee81cd5f6824cea13d9be3e192
/ws4/chapter_function_syntax/lifetime.cpp
857207db66d4a563830cfcd2a9b7dd465625a037
[]
no_license
PeterSommerlad/Prog3
bd78d91632d9f8acf61cbf7697715b9658036894
d33d1ec56f1387d5eb8c757fe8708a596a23d87e
refs/heads/master
2021-01-25T04:09:02.220218
2014-09-21T09:18:13
2014-09-21T09:18:13
5,809,983
2
0
null
2012-12-27T17:55:34
2012-09-14T14:00:58
C++
UTF-8
C++
false
false
580
cpp
lifetime.cpp
// file to demonstrate lifetime issues of variables #include <iostream> int & doNeverDoThis_ReturnReferenceToLocalVariable(){ int number{42}; return number; } void showScopingRules(int i, double d){ unsigned j{1}; // can not use name i instead of j std::cout << i<< "\n"; { char i{'d'}; // shadows parameter i // parameter i not accessible but d is std::cout << i << " " << d << "\n"; } ++i; // that is the parameter no longer shadowed for (unsigned i=0;i<j;++i){ // another i std::cout << i<< "\n"; } std::cout << i << "\n"; // parameter i again }
14f9d2bf9c9b5ec995db1b73b2bbc1a972f05403
1f8d7e70087a68a60f7408fc476e74bd2107e832
/Static.cpp
b58e22521b3fde5ec4f33f6126e53977ec36107c
[]
no_license
jasonchang0/C-Basics
45a6315d571fcbd0bff82aeec643b928c33230ab
6b340180a640daf822fafe261d65d9acb33cdfaf
refs/heads/master
2020-04-01T23:28:08.910022
2019-02-01T08:17:13
2019-02-01T08:17:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
Static.cpp
// // Created by Jason Chang on 11/16/18. // #include <iostream> #include "Static.h" /* Static variables are only defined * in one translational unit */ // Define static class variables with specific scope int Entity::x; int Entity::y; Singleton* Singleton::s_Instance = nullptr; int s_var = 5; void Function() { static int i = 0; int j = 0; i += 1; j += 2; std::cout << "i = " << i << std::endl; std::cout << "j = " << j << std::endl; }
39537b877701fa76d990ee95cb825fd8bd51950c
1a45fba171e386670b32df2c08877483a152c997
/TUBtestQt4/TUBTest/include/SearchDevices.h
7ee240a6d4e5cfdd40d1510dfc4c4a9ca7688163
[]
no_license
Automation-group/TUBtest
fa293272ca9434dac32d8996940682dc315b458e
84f83252ba9f0104aa17652ee2a96dde5047a177
refs/heads/master
2016-09-01T09:25:05.868629
2016-03-03T13:45:50
2016-03-03T13:45:50
51,078,025
0
0
null
null
null
null
UTF-8
C++
false
false
296
h
SearchDevices.h
#ifndef SEARCHDEVICES_H_ #define SEARCHDEVICES_H_ #include <QString> #include <QlfTUB.h> class SearchDevices { public: void SearchDev(QString *portTUB); private: QlfTUB* tub; protected: bool SearchTUB(QString port); QString osName(); }; #endif /*SEARCHDEVICES_H_*/
278ebdcaa16ae17641103e90793cfad52551a232
d44751f35f8cec7f7c06a699e1b25f8e63d0ffc6
/DS/Queue.cpp
b63acf7c80a88e6e3ed388b044b9774bb7c87bbd
[]
no_license
koo5590/Algorithms
3b4d7045ca106b49aa2bc388db68ec4f7418437a
fa5fb4ac459ba94623f829c080739cf305101ecc
refs/heads/master
2022-12-02T03:49:53.588136
2020-08-14T05:40:15
2020-08-14T05:40:15
256,975,500
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
Queue.cpp
// // Created by Hyunjung Kim on 2020-04-19. // #include "Queue.h" #include <iostream> /** constructor **/ template <typename T> Queue<T>::Queue():Queue(8){ } template <typename T> Queue<T>::Queue(int n){ size = 0; capacity = n; data = new T[n]; front = 0; back = 0; } /** destructor **/ template <typename T> Queue<T>::~Queue(){ delete[] data; } template <typename T> bool Queue<T>::isEmpty(){ return size==0; } /** push **/ template <typename T> void Queue<T>::push(T element){ if(size==capacity){ capacity *= 2; int j = 0; T temp[size]; for(int i=front; i<size; i++) temp[j++] = data[i]; for(int i=0; i<front; i++) temp[j++] = data[i]; delete[] data; data = new T[capacity]; for(int i=0; i<size; i++) data[i] = temp[i]; front = 0; back = size; } data[back] = element; back = (back+1)%capacity; size++; } /** pop **/ template <typename T> T Queue<T>::pop(){ if(size==0) return (T)NULL; T temp = data[front]; front = (front+1)%capacity; size--; return temp; }
f594bc15859e4bf6633e372d68450dfee669cc07
1605408342b2ada130d73056c8ef800f57e42879
/extlibs/libELL/include/ell/BinaryNodes.h
c91cbdc241f5b55bd965f113614aab2f88398d81
[ "LGPL-3.0-only", "Zlib", "LicenseRef-scancode-public-domain", "Bitstream-Vera" ]
permissive
TankOs/SFGUI
7c6e269f8024a3cc5883116951cead7f6de34e0c
83471599284b2a23027b9ab4514684a6eeb08a19
refs/heads/master
2023-08-30T10:52:26.256596
2022-04-15T21:52:01
2022-04-16T10:24:51
13,435,050
461
124
Zlib
2022-04-16T10:24:52
2013-10-09T06:44:33
C++
UTF-8
C++
false
false
11,017
h
BinaryNodes.h
// This file is part of Ell library. // // Ell 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. // // Ell 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 a copy of the GNU Lesser General Public License // along with Ell library. If not, see <http://www.gnu.org/licenses/>. #ifndef INCLUDED_ELL_BINARY_NODES_H #define INCLUDED_ELL_BINARY_NODES_H #include <ell/BinaryNode.h> #include <ell/Parser.h> namespace ell { /// Alternative, left first match template <typename Token, typename Left, typename Right> struct Alt : public BinaryNode<Token, Alt<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, Alt<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; Alt(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "alternative"; } using Base::parse; template <typename V> bool parse(Parser<Token> * parser, Storage<V> & s) const { ELL_BEGIN_PARSE match = left.parse(parser, s) || right.parse(parser, s); ELL_END_PARSE } }; /// Longest alternative template <typename Token, typename Left, typename Right> struct LAl : public BinaryNode<Token, LAl<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, LAl<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; LAl(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "longest"; } using Base::parse; template <typename V> bool parse(Parser<Token> * parser, Storage<V> & s) const { ELL_BEGIN_PARSE typename Parser<Token>::Context sav_pos(parser); size_t left_s = 0; size_t right_s = 0; // Parse a first time to find length { SafeModify<> no_actions(parser->flags.action, false); if (left.parse(parser, s)) left_s = parser->measure(sav_pos); sav_pos.restore(parser); if (right.parse(parser, s)) right_s = parser->measure(sav_pos); sav_pos.restore(parser); } if ((left_s != 0) | (right_s != 0)) { // Reparse the right one with actions if (left_s >= right_s) match = left.parse(parser, s); else match = right.parse(parser, s); } ELL_END_PARSE } }; /// Combination (equivalent to a >> b | b >> a) template <typename Token, typename Left, typename Right> struct Asc : public BinaryNode<Token, Asc<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, Asc<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; Asc(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "combination"; } using Base::parse; template <typename T> bool parse(Parser<Token> * parser, Storage<T> & s) const { ELL_BEGIN_PARSE s.clear(); typename Storage<T>::Unit se; if (left.parse(parser, se)) { s.enqueue(se); if (right.parse(parser, se)) { s.enqueue(se); match = true; } } else if (right.parse(parser, se)) { s.enqueue(se); if (left.parse(parser, se)) { s.enqueue(se); match = true; } } ELL_END_PARSE } }; /// Aggregation (sequence) template <typename Token, typename Left, typename Right> struct Agg : public BinaryNode<Token, Agg<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, Agg<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; Agg(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "aggregation"; } using Base::parse; template <typename V> bool parse(Parser<Token> * parser, Storage<V> & s) const { ELL_BEGIN_PARSE typename Parser<Token>::Context sav_pos(parser); typename Storage<V>::Unit s1; if (left.parse(parser, s1)) { parser->skip(); typename Storage<V>::Unit s2; if (right.parse(parser, s2)) { s.enqueue(s1); s.enqueue(s2); match=true; } else { if (not parser->flags.look_ahead) parser->mismatch(right); sav_pos.restore(parser); } } else sav_pos.restore(parser); ELL_END_PARSE } }; template <typename Token, typename Left, typename Right> struct Dif : public BinaryNode<Token, Dif<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, Dif<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; Dif(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "exclusion"; } using Base::parse; template <typename V> bool parse(Parser<Token> * parser, Storage<V> & s) const { ELL_BEGIN_PARSE typename Parser<Token>::Context sav_pos(parser); if (right.parse(parser)) sav_pos.restore(parser); else match = left.parse(parser, s); ELL_END_PARSE } }; template <typename Token, typename Left, typename Right> struct Lst : public BinaryNode<Token, Lst<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, Lst<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; Lst(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "list"; } using Base::parse; template <typename T> bool parse(Parser<Token> * parser, Storage<T> & s) const { ELL_BEGIN_PARSE typename Parser<Token>::Context sav_pos(parser); typename Storage<T>::Unit se; s.clear(); while (left.parse(parser, se)) { s.enqueue(se); match = true; parser->skip(); sav_pos = typename Parser<Token>::Context(parser); if (! right.parse(parser)) break; parser->skip(); } sav_pos.restore(parser); ELL_END_PARSE } }; /// Bound repetition, equivalent to `* (left - right) >> right` template <typename Token, typename Left, typename Right> struct BRp : public BinaryNode<Token, BRp<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, BRp<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; BRp(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "bound-repetition"; } using Base::parse; template <typename T> bool parse(Parser<Token> * parser, Storage<T> & s) const { ELL_BEGIN_PARSE s.clear(); typename Storage<T>::Unit se; while (1) { match = right.parse(parser); if (match || not left.parse(parser, se)) break; s.enqueue(se); parser->skip(); } ELL_END_PARSE } }; /// No suffix template <typename Token, typename Left, typename Right> struct NSx : public BinaryNode<Token, NSx<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, NSx<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; NSx(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "no-suffix"; } using Base::parse; template <typename T> bool parse(Parser<Token> * parser, Storage<T> & s) const { ELL_BEGIN_PARSE SafeModify<> m1(parser->flags.look_ahead, true); typename Parser<Token>::Context sav_pos(parser); match = left.parse(parser, s); if (match && right.parse(parser)) { sav_pos.restore(parser); match = false; } ELL_END_PARSE } }; /// Skipper enabling directive, like the skip() directive, but taking the skipper to use as a second parameter. template <typename Token, typename Left, typename Right> struct SSk : public BinaryNode<Token, SSk<Token, Left, Right>, Left, Right> { typedef BinaryNode<Token, SSk<Token, Left, Right>, Left, Right> Base; using Base::right; using Base::left; SSk(const Left & left, const Right & right) : Base(left, right) { } std::string get_kind() const { return "with-skipper"; } using Base::parse; template <typename T> bool parse(Parser<Token> * parser, Storage<T> & s) const { ELL_BEGIN_PARSE typename Parser<Token>::Context sav_pos(parser); { SafeModify<const Node<Token> *> m1(parser->skipper, &right); SafeModify<> m2(parser->flags.skip, true); parser->skip(); match = left.parse(parser, s); } if (match) { parser->skip(); // Advance with restored skipper } else { sav_pos.restore(parser); } ELL_END_PARSE } }; } #endif // INCLUDED_ELL_BINARY_NODES_H
53a8473a373880572a881983bd58ae751eaf23c6
d8d5e200bbb3a410325a91da570fb49642e87b88
/gameMannager/square.h
c5fddf084f3541f9b8bd3e2c42c931d790316060
[]
no_license
shahafby/FutureYou
db8d8658db03dbad19058b961e7996e70b5c6c7f
418aac73a82f20742ef891eff97dbe2caabf1659
refs/heads/master
2020-03-15T19:37:11.013277
2018-06-08T12:57:50
2018-06-08T12:57:50
132,313,123
0
1
null
null
null
null
UTF-8
C++
false
false
442
h
square.h
#include "FutureYou/gameMannager/question.h" #include "FutureYou/gameMannager/record.h" #include "FutureYou/gameMannager/player.h" #include <string> class Square { public: int pinID; // 0 = not taken ; 1 = player 1 ; 2 = player 2 int taken; string owendBy; Question[] questions; Square(Question[] questionsForSquares, int pin){ taken = 0; questions = questionsForSquares; pinID = pin; } };
069f8bfbaa1b751b82ffabe365bc9e431230fb95
8f888a102d2eefae470d150471f6c5ce013b7cdd
/clasificador_guloso/AriaDLL/ArThread.cpp
f3ec6aeffb7db75c5a70404e27fc0377cdd8fb4e
[]
no_license
eilo/Evolucion-Artificial-y-Robotica-Autonoma-en-Robots-Pioneer-P3-DX
9dfb0c54edbc1bbefb7dd3ddc5f0934e80e1ca65
01ddefcbdb1122aa21566b0a8da465ac30142abe
refs/heads/master
2021-01-23T14:58:29.275506
2012-04-30T15:01:38
2012-04-30T15:01:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,593
cpp
ArThread.cpp
#include "ArExport.h" // ArThread.cc -- Thread classes #include "ariaOSDef.h" #include <errno.h> #include <list> #include "ArThread.h" #include "ArLog.h" ArMutex ArThread::ourThreadsMutex; ArThread::MapType ArThread::ourThreads; #ifdef WIN32 std::map<HANDLE, ArThread *> ArThread::ourThreadHandles; #endif AREXPORT ArLog::LogLevel ArThread::ourLogLevel = ArLog::Verbose; // todo, instead of AREXPORT move accessors into .cpp? std::string ArThread::ourUnknownThreadName = "unknown"; AREXPORT void ArThread::stopAll() { MapType::iterator iter; ourThreadsMutex.lock(); for (iter=ourThreads.begin(); iter != ourThreads.end(); ++iter) (*iter).second->stopRunning(); ourThreadsMutex.unlock(); } AREXPORT void ArThread::joinAll() { MapType::iterator iter; ArThread *thread; thread=self(); ourThreadsMutex.lock(); for (iter=ourThreads.begin(); iter != ourThreads.end(); ++iter) { if ((*iter).second->getJoinable() && thread && (thread != (*iter).second)) { (*iter).second->doJoin(); } } ourThreads.clear(); // MPL BUG I'm not to sure why this insert was here, as far as I can // tell all it would do is make it so you could join the threads // then start them all up again, but I don't see much utility in // that so I'm not going to worry about it now //ourThreads.insert(MapType::value_type(thread->myThread, thread)); ourThreadsMutex.unlock(); } AREXPORT ArThread::ArThread(bool blockAllSignals) : myRunning(false), myJoinable(false), myBlockAllSignals(blockAllSignals), myStarted(false), myFinished(false), myFunc(0), myThread(), myStrMap() { } AREXPORT ArThread::ArThread(ThreadType thread, bool joinable, bool blockAllSignals) : myRunning(false), myJoinable(joinable), myBlockAllSignals(blockAllSignals), myStarted(false), myFinished(false), myFunc(0), myThread(thread), myStrMap() { } AREXPORT ArThread::ArThread(ArFunctor *func, bool joinable, bool blockAllSignals) : myRunning(false), myJoinable(false), myBlockAllSignals(blockAllSignals), myStarted(false), myFinished(false), myFunc(func), myThread(), myStrMap() { create(func, joinable); } #ifndef WIN32 AREXPORT ArThread::~ArThread() { // Just make sure the thread is no longer in the map. ourThreadsMutex.lock(); MapType::iterator iter = ourThreads.find(myThread); if (iter != ourThreads.end()) { ourThreads.erase(iter); } ourThreadsMutex.unlock(); } #endif AREXPORT int ArThread::join(void **iret) { int ret; ret=doJoin(iret); if (ret) return(ret); ourThreadsMutex.lock(); ourThreads.erase(myThread); ourThreadsMutex.unlock(); return(0); } AREXPORT void ArThread::setThreadName(const char *name) { myName = name; std::string mutexLogName; mutexLogName = name; mutexLogName += "ThreadMutex"; myMutex.setLogName(mutexLogName.c_str()); } AREXPORT bool ArThread::isThreadStarted() const { return myStarted; } AREXPORT bool ArThread::isThreadFinished() const { return myFinished; } AREXPORT const char *ArThread::getThisThreadName(void) { ArThread *self; if ((self = ArThread::self()) != NULL) return self->getThreadName(); else return ourUnknownThreadName.c_str(); } AREXPORT const ArThread::ThreadType * ArThread::getThisThread(void) { ArThread *self; if ((self = ArThread::self()) != NULL) return self->getThread(); else return NULL; } AREXPORT ArThread::ThreadType ArThread::getThisOSThread(void) { ArThread *self; if ((self = ArThread::self()) != NULL) return self->getOSThread(); else return 0; }
b88ec37178adab71302475a193647f241c12a590
ded222830b0c98624ce906d351b7aa6fa89736ce
/9/9_2/main.cpp
eb166d5d74cff19abe365cd252f453cd8f1a9396
[]
no_license
Bot8/eletskiy_HT_CPP
ce9b38e40d15a3da82db3568bcc329145c14d518
bf8ff3fc46eea15288045c18f88ee3d4ce5a1df7
refs/heads/master
2021-01-15T11:29:09.998383
2015-01-10T21:36:44
2015-01-10T21:36:44
28,778,480
0
0
null
null
null
null
UTF-8
C++
false
false
2,503
cpp
main.cpp
#include <iostream> #include <cmath> using namespace std; /* Printing a equation segment variable - value, first - flag if printing + before variable condition - flag of printing 1 (before x not print, alone prints) */ template <typename T> bool printVar(T variable, bool first = false, bool condition = false) { bool result = false; if(variable!=0) { T absVariable = abs(variable); if (variable>=0 && !first) { cout << "+"; } if (variable<0) { cout << "-"; } if(variable!=1 || !condition) { cout << absVariable; } result = true; } /* if 0 skip */ return result; } template <typename T1, typename T2> double solveLinear(T1 a, T2 b){ if(a==0){ /* division by zero */ cout << "Invalid a"; } else { cout << "Solving linear"<< endl; double result = (double)(b*(-1))/a; if(printVar(a, true)) { cout << "x"; } printVar(b); cout << "=0" << endl; cout << "x=" << result<< endl; } } template <typename T1, typename T2, typename T3> void solveSquare(T1 a, T2 b, T3 c) { bool first = true; if(a==0) { if(b==0) { cout << "Invalid a and b"; } else { /* it is linear */ solveLinear(b,c); } return; } cout << "Solving square"<< endl; double d = b*b - 4 * a * c; if(printVar(a, first, true)){ first = false; cout << "x^2"; } if(printVar(b, first, true)) { cout << "x"; } printVar(c); cout << "=0" << endl; if(d == 0) { cout << "x1=x2=" << ((-1)*b)/(2*a); } else if(d>0){ d = sqrt(d); cout << "x1=" << ((-1)*b+d)/(2*a); cout << endl; cout << "x2=" << ((-1)*b-d)/(2*a); } else { cout << "No solutions"; } } int main() { double a,b,c; cout << endl << "Lets solve linear equation like" << endl; cout << "ax+b=0"<<endl; cout << "Enter a: "; cin>> a; cout << "Enter b: "; cin>> b; cout << endl; solveLinear(a, b); cout << endl << "Lets solve linear equation like" << endl; cout << "ax^2+bx+c=0" << endl; cout << "Enter a: "; cin>> a; cout << "Enter b: "; cin>> b; cout << "Enter c: "; cin>> c; cout << endl; solveSquare(a, b, c); return 0; }
0a25af1b90ed30d2fda76b357927f6884c4358cf
a31e33360bd4e8ad6f18c6001e1b66afc2efbab1
/CurveEditor/Source/CurveEditor/Tools/CurveEditorKnotRemoverTool.cpp
69b8dac278386b0b6111c332f0a4f1b4f993e6d0
[]
no_license
MaxGarden/CurveEditor
4a8ad67059ed94b588bd7be5a086aa3bcfeca4e8
d979648808d9b4b6fe11f8a27ee91c72e12e5768
refs/heads/master
2021-03-27T16:45:12.688580
2018-06-18T07:21:57
2018-06-18T07:22:03
122,730,919
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
CurveEditorKnotRemoverTool.cpp
#include "pch.h" #include "CurveEditorKnotRemoverTool.h" #include "Components/SplinesComponent.h" #include "KnotViewComponent.h" CCurveEditorKnotRemoverTool::CCurveEditorKnotRemoverTool(ECurveEditorMouseButton removeButton /* = ECurveEditorMouseButton::Left */) : m_RemoveButton(removeButton) { } void CCurveEditorKnotRemoverTool::OnAcquired(const CCurveEditorToolEvent& event) { m_SpinesViewComponent = GetViewComponent<ICurveEditorSplinesViewComponent>(event.GetEditorView()); EDITOR_ASSERT(!m_SpinesViewComponent.expired()); } void CCurveEditorKnotRemoverTool::OnReleased(const CCurveEditorToolEvent&) { m_SpinesViewComponent.reset(); } void CCurveEditorKnotRemoverTool::OnClickUp(const CCurveEditorToolMouseButtonEvent& event) { if (event.GetMouseButton() != m_RemoveButton) return; const auto knotView = GetKnotViewAtPosition(event.GetMousePosition()); if (!knotView || !knotView->CanBeRemoved()) return; const auto result = knotView->Remove(); EDITOR_ASSERT(result); } ICurveEditorKnotView * CCurveEditorKnotRemoverTool::GetKnotViewAtPosition(const ax::pointf& position) const noexcept { const auto splinesViewComponent = m_SpinesViewComponent.lock(); EDITOR_ASSERT(splinesViewComponent); if (!splinesViewComponent) return nullptr; const auto splineViewComponent = splinesViewComponent->GetSplineComponentAt(position); if (!splineViewComponent || splineViewComponent->GetType() != ECurveEditorSplineComponentType::Knot) return nullptr; const auto result = dynamic_cast<ICurveEditorKnotView*>(splineViewComponent); EDITOR_ASSERT(result); return result; }
40f9bba838e9e40ba98381a8850b7ca6fc0d54fb
cb5e379fa9047e88ea093cb60dbf404ab6878b0f
/source/Paxos/StateMachine.h
85d2a8028e32ec33668387959963974e93471647
[]
no_license
zhaoyaogit/rong
7aa16f4d936db6af6eb83556bf0c972a338ed0d8
15e0e15c064ebcff6f3a04e6f444c0e0f25c89dd
refs/heads/master
2022-02-06T19:37:50.382764
2019-07-22T14:17:07
2019-07-22T14:17:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,265
h
StateMachine.h
/*- * Copyright (c) 2019 TAO Zhijiang<taozhijiang@gmail.com> * * Licensed under the BSD-3-Clause license, see LICENSE for full information. * */ #ifndef __PAXOS_STATE_MACHINE__ #define __PAXOS_STATE_MACHINE__ #include <xtra_rhel.h> #include <mutex> #include <string> #include <thread> #include <Paxos/LogIf.h> #include <Paxos/StoreIf.h> #include <Protocol/gen-cpp/Paxos.pb.h> // 简易的KV存储支撑 namespace rong { enum class SnapshotProgress : uint8_t { kBegin = 1, kProcessing = 2, kDone = 3, }; class RaftConsensus; typedef Paxos::Entry EntryType; typedef Paxos::ApplyResponse ApplyResponseType; class StateMachine { __noncopyable__(StateMachine) public: StateMachine(PaxosConsensus& paxos_consensus, std::unique_ptr<LogIf>& log_meta, std::unique_ptr<StoreIf>& kv_store); ~StateMachine() = default; bool init(); void notify_state_machine() { apply_notify_.notify_all(); } void state_machine_loop(); // 本地快照的创建和加载 bool create_snapshot(uint64_t& last_included_index, uint64_t& last_included_term); bool load_snapshot(std::string& content, uint64_t& last_included_index, uint64_t& last_included_term); bool apply_snapshot(const Snapshot::SnapshotContent& snapshot); uint64_t apply_instance_id() const { return apply_instance_id_; } void set_apply_instance_id(uint64_t instance_id) { apply_instance_id_ = instance_id; } bool fetch_response_msg(uint64_t instance_id, ApplyResponseType& content); private: int do_apply(LogIf::EntryPtr entry, std::string& content_out); PaxosConsensus& paxos_consensus_; std::unique_ptr<LogIf>& log_meta_; std::unique_ptr<StoreIf>& kv_store_; // 其下一条就是要执行的指令,初始化值为0 uint64_t apply_instance_id_; // 是否正在执行快照操作 SnapshotProgress snapshot_progress_; std::mutex apply_mutex_; std::condition_variable apply_notify_; // 保存状态机的执行结果 std::mutex apply_rsp_mutex_; std::map<uint64_t, ApplyResponseType> apply_rsp_; bool main_executor_stop_; std::thread main_executor_; }; } // end namespace rong #endif // __PAXOS_STATE_MACHINE__
6ebed492adfafddd34e2b1422ace7f39179b6cae
6e2f15b0e9530c3270932f3a453b0f2cd3d6d1d8
/BoundingRect.h
32f3ed7fbb412581c84311195eec634b3a2e074f
[]
no_license
ExXidad/CDE
98aa4cea198373c5912b47f8852dbcf6b7370bfb
8f586004472c42a57a2f5ca7ef81db2e87bd89c0
refs/heads/master
2022-12-27T13:12:17.497481
2020-09-22T23:04:33
2020-09-22T23:04:33
297,733,934
0
0
null
null
null
null
UTF-8
C++
false
false
573
h
BoundingRect.h
// // Created by mi on 22.09.2020. // #ifndef CDE_BOUNDINGRECT_H #define CDE_BOUNDINGRECT_H #include <vector> class BoundingRect { private: std::vector<std::vector<double>> size = std::vector<std::vector<double>>(2, std::vector<double>(2, 0)); public: const std::vector<std::vector<double>> &getSize() const; void setSize(const std::vector<std::vector<double>> &size); double getXSize(); double getYSize(); public: BoundingRect(const double &xmin, const double &xmax, const double &ymin, const double &ymax); }; #endif //CDE_BOUNDINGRECT_H
71ec63c3690f183d69c2c5c56435fb06a91899fd
4c25432a6d82aaebd82fd48e927317b15a6bf6ab
/data/dataset_2017/dataset_2017_8/JAYS/3264486_5633382285312000_JAYS.cpp
98d6594c1b850699ed8b7c774b3065a553c32e04
[]
no_license
wzj1988tv/code-imitator
dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933
07a461d43e5c440931b6519c8a3f62e771da2fc2
refs/heads/master
2020-12-09T05:33:21.473300
2020-01-09T15:29:24
2020-01-09T15:29:24
231,937,335
1
0
null
2020-01-05T15:28:38
2020-01-05T15:28:37
null
UTF-8
C++
false
false
500
cpp
3264486_5633382285312000_JAYS.cpp
#include <cstdio> #include <cstring> int N; bool verdict(int n) { char m[11]; sprintf(m, "%d", n); int l = strlen(m); for (int i = l-1; i > 0; i--) if (m[i-1] > m[i]) return false; return true; } int solve() { for (int n = N; n >= 1; n--) if (verdict(n)) return n; return 1; } int main() { int T; scanf("%d", &T); for (int t = 1; t <= T; t++) { scanf("%d", &N); int ans = solve(); printf("Case #%d: %d\n", t, ans); } return 0; }
831a79dd34b358e68d9477413dfff7a226d7c387
ce8a4217e20b57b280fe48f9ae865c875c237f8c
/Plugins/private/Party/Party_Impl.cpp
47d418f946c977f1aa5473a84c9c967c39a8d081
[]
no_license
robinhood90/stormancer-sdk-cpp
60060d786ae52817e63aca429f3d20acb7c22d15
10997b58ae0fd89011ab28d6a9b20f7689472486
refs/heads/master
2022-03-10T13:58:31.350124
2019-09-26T09:31:40
2019-09-26T09:31:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,252
cpp
Party_Impl.cpp
#if defined(STORMANCER_CUSTOM_PCH) #include STORMANCER_CUSTOM_PCH #endif #include "Party_Impl.h" #include "PartyService.h" #include "PartyContainer.h" #include "GameFinder/GameFinder_Impl.h" #include "stormancer/Exceptions.h" namespace Stormancer { Party_Impl::Party_Impl(std::weak_ptr<AuthenticationService> auth, std::weak_ptr<ILogger> logger, std::weak_ptr<GameFinder> gameFinder) :ClientAPI(auth) { _logger = logger; _gameFinder = gameFinder; } void Party_Impl::initialize() { auto wThat = this->weak_from_this(); _auth.lock()->SetOperationHandler("party.invite", [wThat](OperationCtx& ctx) { Serializer serializer; auto senderId = ctx.originId; auto sceneId = serializer.deserializeOne<std::string>(ctx.request->inputStream()); auto that = wThat.lock(); if (!that) { throw std::runtime_error("client can't accept invitations"); } auto invitation = that->invitations.ReceivePartyInvitation(senderId, sceneId); pplx::task_completion_event<void> tce; auto subscription = invitation->onAnswer.subscribe([tce, ctx](bool /*answer*/) { ctx.request->sendValue([](obytestream&) {}); tce.set(); }); ctx.request->cancellationToken().register_callback([wThat, senderId]() { auto that = wThat.lock(); if (that) { that->invitations.RemovePartyInvitation(senderId); } }); //capture subscription to keep it alive as long as the async operation is not complete return pplx::create_task(tce, ctx.request->cancellationToken()).then([subscription]() {}); }); } pplx::task<std::shared_ptr<PartyContainer>> Party_Impl::createParty(const PartyRequestDto& partySettings) { if (_party) { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("party.alreadyInParty")); } auto auth = _auth.lock(); if (!auth) { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("destroyed")); } auto wThat = this->weak_from_this(); return getPartyManagementService().then([partySettings](std::shared_ptr<Stormancer::PartyManagementService> partyManagement) { return partyManagement->createParty(partySettings); }).then([wThat, partySettings](pplx::task<std::string> task) { auto that = wThat.lock(); if (!that) { throw std::runtime_error("destroyed"); } auto sceneToken = task.get(); return that->joinPartySceneByConnectionToken(sceneToken); }).then([](std::shared_ptr<PartyContainer> party) { return party; }); } pplx::task<std::shared_ptr<PartyContainer>> Party_Impl::joinPartySceneByPlatformSessionId(const std::string uniqueOnlinePartyName) { if (_party) { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("party.alreadyInParty")); } auto wPartyManagement = this->weak_from_this(); auto t = leaveParty().then([wPartyManagement, uniqueOnlinePartyName]() { auto partyManagment = wPartyManagement.lock(); if (partyManagment) { return partyManagment->getPartySceneByOnlinePartyName(uniqueOnlinePartyName); } else { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("An error occured when client try to retrieve party scene")); } }).then([wPartyManagement](pplx::task<std::shared_ptr<PartyContainer>> t2) { try { auto p = t2.get(); if (auto that = wPartyManagement.lock()) { that->_onJoinedParty(); //that->_onUpdatedPartyMembers(p->members()); //that->_onUpdatedPartySettings(p->settings()); } return p; } catch (std::exception& ex) { if (auto that = wPartyManagement.lock()) { if (auto logger = that->_logger.lock()) { logger->log(LogLevel::Error, "PartyManagement", "Failed to get the party scene.", ex.what()); } that->_party = nullptr; } throw; } }); this->_party = std::make_shared<pplx::task<std::shared_ptr<PartyContainer>>>(t); return t; } pplx::task<std::shared_ptr<PartyContainer>> Party_Impl::joinPartySceneByConnectionToken(const std::string& token) { if (_party) { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("party.alreadyInParty")); } auto wPartyManagement = this->weak_from_this(); auto t = leaveParty().then([wPartyManagement, token]() { auto partyManagment = wPartyManagement.lock(); if (partyManagment) { return partyManagment->getPartySceneByToken(token); } else { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("An error occured when client try to retrieve party scene")); } }).then([wPartyManagement](pplx::task<std::shared_ptr<PartyContainer>> t2) { try { auto p = t2.get(); if (auto that = wPartyManagement.lock()) { that->_onJoinedParty(); that->_onUpdatedPartyMembers(p->members()); that->_onUpdatedPartySettings(p->settings()); } return p; } catch (std::exception& ex) { if (auto that = wPartyManagement.lock()) { if (auto logger = that->_logger.lock()) { logger->log(LogLevel::Error, "PartyManagement", "Failed to get the party scene.", ex.what()); } that->_party = nullptr; } throw; } }); this->_party = std::make_shared<pplx::task<std::shared_ptr<PartyContainer>>>(t); return t; } pplx::task<std::shared_ptr<PartyManagementService>> Party_Impl::getPartyManagementService() { return this->getService<PartyManagementService>("stormancer.plugins.partyManagement"); } pplx::task<void> Party_Impl::leaveParty() { if (!_party) { if (auto logger = _logger.lock()) { logger->log(LogLevel::Warn, "PartyManagement", "Client not connected on party", ""); } return pplx::task_from_result(); } auto party = *_party; std::weak_ptr<Party_Impl> wpartyManagement = this->weak_from_this(); auto wGameFinder = this->_gameFinder; return party.then([wpartyManagement](std::shared_ptr<PartyContainer> party) { auto partyManagement = wpartyManagement.lock(); if (!partyManagement) { throw std::runtime_error("destroyed"); } party->getScene()->disconnect(); // FIXME: [mstorch] Not sure if this leaves some things not cleaned up??? Fixes race condition where leaving a party // during a party invitation acceptance caused "party.alreadyInParty" error to be returned. partyManagement->_party = nullptr; }); } pplx::task<std::shared_ptr<PartyContainer>> Party_Impl::getParty() { if (_party) { return *_party; } else { return pplx::task_from_exception<std::shared_ptr<PartyContainer>>(std::runtime_error("party.notInParty")); } } pplx::task<void> Party_Impl::updatePlayerStatus(PartyUserStatus playerStatus) { return getParty().then([playerStatus](std::shared_ptr<PartyContainer> party) { auto partyService = party->getScene()->dependencyResolver().resolve<PartyService>(); return partyService->updatePlayerStatus(playerStatus); }); } pplx::task<void> Party_Impl::updatePartySettings(PartySettingsDto partySettingsDto) { if (partySettingsDto.customData == "") { partySettingsDto.customData = "{}"; } return getParty().then([partySettingsDto](std::shared_ptr<PartyContainer> party) { std::shared_ptr<PartyService> partyService = party->getScene()->dependencyResolver().resolve<PartyService>(); return partyService->updatePartySettings(partySettingsDto); }); } pplx::task<void> Party_Impl::updatePlayerData(std::string data) { return getParty().then([data](std::shared_ptr<PartyContainer> party) { std::shared_ptr<PartyService> partyService = party->getScene()->dependencyResolver().resolve<PartyService>(); partyService->updatePlayerData(data); }); } pplx::task<bool> Party_Impl::PromoteLeader(std::string userId) { return getParty().then([userId](std::shared_ptr<PartyContainer> party) { std::shared_ptr<PartyService> partyService = party->getScene()->dependencyResolver().resolve<Stormancer::PartyService>(); return partyService->PromoteLeader(userId); }); } pplx::task<bool> Party_Impl::kickPlayer(std::string userId) { return getParty().then([userId](std::shared_ptr<PartyContainer> party) { std::shared_ptr<PartyService> partyService = party->getScene()->dependencyResolver().resolve<Stormancer::PartyService>(); return partyService->KickPlayer(userId); }); } pplx::task<std::shared_ptr<PartyContainer>> Party_Impl::getPartySceneByOnlinePartyName(const std::string uniqueOnlinePartyName) { auto auth = _auth.lock(); auto wPartyManagement = this->weak_from_this(); return auth->getSceneForService("stormancer.plugins.party", uniqueOnlinePartyName).then([wPartyManagement](std::shared_ptr<Scene> scene) { auto pManagement = wPartyManagement.lock(); if (!pManagement) { throw PointerDeletedException("partyManagement"); } return pManagement->initPartyFromScene(scene); }); } pplx::task<std::shared_ptr<PartyContainer>> Party_Impl::getPartySceneByToken(const std::string& token) { auto auth = _auth.lock(); auto wPartyManagement = this->weak_from_this(); return auth->connectToPrivateSceneByToken(token).then([wPartyManagement](std::shared_ptr<Scene> scene) { auto pManagement = wPartyManagement.lock(); if (!pManagement) { throw PointerDeletedException("partyManagement"); } return pManagement->initPartyFromScene(scene); }); } std::shared_ptr<PartyContainer> Party_Impl::initPartyFromScene(std::shared_ptr<Scene> scene) { try { std::weak_ptr<Party_Impl> wPartyManagement = this->shared_from_this(); auto partyService = scene->dependencyResolver().resolve<PartyService>(); this->_partySceneConnectionStateSubscription = scene->getConnectionStateChangedObservable().subscribe([wPartyManagement](ConnectionState state) { if (auto that = wPartyManagement.lock()) { if (state == ConnectionState::Disconnected) { that->_onLeftParty(); if (that->_partySceneConnectionStateSubscription.is_subscribed()) { that->_partySceneConnectionStateSubscription.unsubscribe(); } } } }); auto party = std::make_shared<PartyContainer>(scene, partyService->JoinedParty.subscribe([wPartyManagement]() { if (auto partyManagement = wPartyManagement.lock()) { partyManagement->_onJoinedParty(); } }), partyService->KickedFromParty.subscribe([wPartyManagement]() { if (auto partyManagement = wPartyManagement.lock()) { partyManagement->_onKickedFromParty(); } }), partyService->LeftParty.subscribe([wPartyManagement]() { if (auto partyManagement = wPartyManagement.lock()) { if (partyManagement->_party) { partyManagement->_party->then([wPartyManagement](std::shared_ptr<PartyContainer> party) { if (auto partyManagement = wPartyManagement.lock()) { auto gameFinderName = party->settings().gameFinderName; partyManagement->_party = nullptr; if (auto gf = partyManagement->_gameFinder.lock()) { return gf->disconnectFromGameFinder(gameFinderName); } } return pplx::task_from_result(); }).then([wPartyManagement](pplx::task<void> t) { try { if (auto partyManagement = wPartyManagement.lock()) { t.get(); partyManagement->_onLeftParty(); } } catch (...) {} }); } } }), partyService->UpdatedPartyMembers.subscribe([wPartyManagement](std::vector<PartyUserDto> partyUsers) { if (auto partyManagement = wPartyManagement.lock()) { partyManagement->_onUpdatedPartyMembers(partyUsers); } }), partyService->UpdatedPartyUserData.subscribe([wPartyManagement](PartyUserData partyUserUpdatedData) { if (auto partyManagement = wPartyManagement.lock()) { partyManagement->_onUpdatedUserData(partyUserUpdatedData); } }), partyService->UpdatedPartySettings.subscribe([wPartyManagement](Stormancer::PartySettings settings) { if (auto partyManagement = wPartyManagement.lock()) { partyManagement->_onUpdatedPartySettings(settings); } })); return party; } catch (const std::exception& ex) { throw std::runtime_error(std::string("Party scene not found : ") + ex.what()); } } pplx::task<void> Party_Impl::sendInvitation(const std::string& recipient) { auto wAuth = _auth; auto wThat = this->weak_from_this(); return getParty().then([wAuth, wThat, recipient](std::shared_ptr<PartyContainer> party) { auto auth = wAuth.lock(); auto that = wThat.lock(); if (!auth || !that) { return pplx::task_from_exception<void>(std::runtime_error("destroyed")); } auto senderId = auth->userId(); auto partyId = party->id(); pplx::cancellation_token_source cts; that->invitations.SendPartyRequest(recipient, cts); return auth->sendRequestToUser<void>(recipient, "party.invite", cts.get_token(), senderId, partyId); }).then([wThat, recipient]() { auto that = wThat.lock(); if (!that) { throw std::runtime_error("destroyed"); } that->invitations.ClosePartyRequest(recipient); }); } Event<PartySettings>::Subscription Party_Impl::subscribeOnUpdatedPartySettings(std::function<void(PartySettings)> callback) { return _onUpdatedPartySettings.subscribe(callback); } Event<std::vector<PartyUserDto>>::Subscription Party_Impl::subscribeOnUpdatedPartyMembers(std::function<void(std::vector<PartyUserDto>)> callback) { return _onUpdatedPartyMembers.subscribe(callback); } Event<PartyUserData>::Subscription Party_Impl::subscribeOnUpdatedUserData(std::function<void(PartyUserData)> callback) { return _onUpdatedUserData.subscribe(callback); } Event<void>::Subscription Party_Impl::subscribeOnJoinedParty(std::function<void()> callback) { return _onJoinedParty.subscribe(callback); } Event<void>::Subscription Party_Impl::subscribeOnKickedFromParty(std::function<void()> callback) { return _onKickedFromParty.subscribe(callback); } Event<void>::Subscription Party_Impl::subscribeOnLeftParty(std::function<void()> callback) { return _onLeftParty.subscribe(callback); } }
d76ec944ab9e92d34936b120648976b82d195549
2ee74a3661f0baf8e8a18225349f92484b028b9b
/DataStructures/Tree/BinarySearchTree.cpp
1bec134d1ab47f939fdd32f986dbaacba6c3891a
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
anantdhok/ComputerScience
fde83ff28ec1d725ae991ddb8fee753ec8bf6539
03939dc2cd56d0ef32d929f7f19f50dcf7573cd9
refs/heads/main
2023-04-24T10:30:28.661992
2021-05-13T14:51:21
2021-05-13T14:51:21
325,354,115
1
0
null
null
null
null
UTF-8
C++
false
false
3,731
cpp
BinarySearchTree.cpp
#include<bits/stdc++.h> #include<conio.h> using namespace std; struct node { int data; struct node *left; struct node *right; } *root, *current; struct node *minimum(struct node *head) { while (head->left != NULL) head = head->left; return head; } struct node *create() { struct node *newnode = (struct node *)malloc(sizeof(struct node)); cout << "\n Enter the data : "; cin >> newnode->data; newnode->left = NULL; newnode->right = NULL; return newnode; } struct node *insert(struct node *head, struct node *node) { if (head == NULL) return node; else if (head->data > node->data) head->left = insert(head->left, node); else if (head->data < node->data) head->right = insert(head->right, node); return head; } struct node *remove(struct node *head, int key) { if (head->data == key) { if (head->left == NULL) { current = head->right; free(head); return current; } else if (head->right == NULL) { current = head->left; free(head); return current; } current = minimum(head->right); head->data = current->data; head->right = remove(head->right, current->data); } else if (head->data > key) head->left = remove(head->left, key); else if (head->data < key) head->right = remove(head->right, key); return head; } struct node *search(struct node *head, int key) { if (head->data > key) return search(head->left, key); else if (head->data < key) return search(head->right, key); else return head; } void inorder(struct node *head) { if (head != NULL) { inorder(head->left); cout << " " << head->data; inorder(head->right); } } void preorder(struct node *head) { if (head != NULL) { cout << " " << head->data; preorder(head->left); preorder(head->right); } } void postorder(struct node *head) { if (head != NULL) { postorder(head->left); postorder(head->right); cout << " " << head->data; } } int main() { int c = 0, d = 0; while (true) { lb: system("cls"); cout << "\n Binary Search Tree \n 1.Insert Node \n 2.Remove Node \n 3.Search Node \n 4.Display Inorder \n 5.Display Preorder \n 6.Display Postorder \n 7.Exit \n Enter the Choice : "; cin >> c; switch (c) { case 1: current = create(); root = insert(root, current); break; case 2: cout << "\n Enter the data to be removed : "; cin >> d; if (root != NULL) root = remove(root, d); else { cout << "\n Tree is Empty."; getch(); } break; case 3: cout << "\n Enter the data to search : "; cin >> d; if (root != NULL) (search(root, d) != NULL) ? cout << "\n Data present in Tree." : cout << "\n Data not present in Tree."; else cout << "\n Tree is Empty."; getch(); break; case 4: if (root != NULL) inorder(root); else cout << "\n Tree is Empty."; getch(); break; case 5: if (root != NULL) preorder(root); else cout << "\n Tree is Empty."; getch(); break; case 6: if (root != NULL) postorder(root); else cout << "\n Tree is Empty."; getch(); break; case 7: exit(0); default: goto lb; } } return 0; }
6b96372713449393f0c7069cd13a097c07abd04b
635c344550534c100e0a86ab318905734c95390d
/wpilibc/src/main/native/include/frc/simulation/AnalogTriggerSim.h
019a9a95ae8be7b3aaa0c04a1163d0fa3001e019
[ "BSD-3-Clause" ]
permissive
wpilibsuite/allwpilib
2435cd2f5c16fb5431afe158a5b8fd84da62da24
8f3d6a1d4b1713693abc888ded06023cab3cab3a
refs/heads/main
2023-08-23T21:04:26.896972
2023-08-23T17:47:32
2023-08-23T17:47:32
24,655,143
986
769
NOASSERTION
2023-09-14T03:51:22
2014-09-30T20:51:33
C++
UTF-8
C++
false
false
3,599
h
AnalogTriggerSim.h
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include <memory> #include "frc/simulation/CallbackStore.h" namespace frc { class AnalogTrigger; namespace sim { /** * Class to control a simulated analog trigger. */ class AnalogTriggerSim { public: /** * Constructs from an AnalogTrigger object. * * @param analogTrigger AnalogTrigger to simulate */ explicit AnalogTriggerSim(const AnalogTrigger& analogTrigger); /** * Creates an AnalogTriggerSim for an analog input channel. * * @param channel analog input channel * @return Simulated object * @throws std::out_of_range if no AnalogTrigger is configured for that * channel */ static AnalogTriggerSim CreateForChannel(int channel); /** * Creates an AnalogTriggerSim for a simulated index. * The index is incremented for each simulated AnalogTrigger. * * @param index simulator index * @return Simulated object */ static AnalogTriggerSim CreateForIndex(int index); /** * Register a callback on whether the analog trigger is initialized. * * @param callback the callback that will be called whenever the analog * trigger is initialized * @param initialNotify if true, the callback will be run on the initial value * @return the CallbackStore object associated with this callback */ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback( NotifyCallback callback, bool initialNotify); /** * Check if this analog trigger has been initialized. * * @return true if initialized */ bool GetInitialized() const; /** * Change whether this analog trigger has been initialized. * * @param initialized the new value */ void SetInitialized(bool initialized); /** * Register a callback on the lower bound. * * @param callback the callback that will be called whenever the lower bound * is changed * @param initialNotify if true, the callback will be run on the initial value * @return the CallbackStore object associated with this callback */ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterTriggerLowerBoundCallback( NotifyCallback callback, bool initialNotify); /** * Get the lower bound. * * @return the lower bound */ double GetTriggerLowerBound() const; /** * Change the lower bound. * * @param triggerLowerBound the new lower bound */ void SetTriggerLowerBound(double triggerLowerBound); /** * Register a callback on the upper bound. * * @param callback the callback that will be called whenever the upper bound * is changed * @param initialNotify if true, the callback will be run on the initial value * @return the CallbackStore object associated with this callback */ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterTriggerUpperBoundCallback( NotifyCallback callback, bool initialNotify); /** * Get the upper bound. * * @return the upper bound */ double GetTriggerUpperBound() const; /** * Change the upper bound. * * @param triggerUpperBound the new upper bound */ void SetTriggerUpperBound(double triggerUpperBound); /** * Reset all simulation data for this object. */ void ResetData(); private: explicit AnalogTriggerSim(int index) : m_index{index} {} int m_index; }; } // namespace sim } // namespace frc
0b9a9a568f659b75a608f1dbbf5e52c3ec8c14a3
8ea067554e8b1e337771a940663bdaf821f6e643
/Assignment8/RepositoryCSV.cpp
4731665e4af239987a5ccba2e29561d7207f3c29
[]
no_license
LeVoMihalcea/assignment8
041cca7130c8bbd4357e115c438a0607f0e6f7e5
b2549eeeee927addb2f85be62ad0b35dac220cf2
refs/heads/master
2020-05-17T04:04:59.227758
2019-05-15T06:23:46
2019-05-15T06:23:46
183,498,755
1
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
RepositoryCSV.cpp
#include "RepositoryCSV.h" RepositoryCSV::RepositoryCSV(string path) : RepositoryTXT{path} { this->path = path; } RepositoryCSV::~RepositoryCSV() { } bool RepositoryCSV::save() { RepositoryTXT::save(); return true; } bool RepositoryCSV::load() { RepositoryTXT::load(this->path); return true; } string RepositoryCSV::getPath() { return this->path; }
80727d7eb2b776f8d6fb2b33208fdd95ebedc01e
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/multimedia/dshow/vidctl/msvidctl/analogtvcp.h
23111ce9af8d0f5aa703bedea1fceb9344925564
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
390
h
analogtvcp.h
// Copyright (c) 2001 Microsoft Corporation. All Rights Reserved. #ifndef _MSVIDANALOGTUNERCP_H_ #define _MSVIDANALOGTUNERCP_H_ template <class T> class CProxy_IMSVidAnalogTuner : public CProxy_Tuner<T, &IID_IMSVidAnalogTunerEvent, CComDynamicUnkArray> { //Warning this class may be recreated by the wizard. public: // TODO: add fileplayback specific events here }; #endif
eba2dc468db8cbc6572b6ee8f39da2168d87d0ee
6608495bb062b036eae60260c4594ddc1b0a2945
/DrawingUI.h
781fd2ccc6e43b722bf40b809bf5ca72d0d039d7
[]
no_license
OC-MCS/drawing-01-SeanJennings15
f180de70cedce55a720b15945f855f269ea5b6d9
f44a88563073e310af588729ba3d40ae595f8982
refs/heads/master
2020-05-01T19:44:12.309685
2019-03-29T06:32:41
2019-03-29T06:32:41
177,656,182
0
0
null
null
null
null
UTF-8
C++
false
false
2,223
h
DrawingUI.h
#pragma once #include <SFML/Graphics.hpp> #include <iostream> using namespace std; using namespace sf; #include "ShapeMgr.h" class DrawingUI { private: RectangleShape drawingArea; //this is the drawing canvas const int canvasLength = 500; //length for each side of the square canvas const int canvasX = 250; //X value of the canvas const int canvasY = 25; //Y value of the canvas const int drawingCanvasX = canvasX - 8 + canvasLength; //max X value that can be drawn on in the canvas const int drawingCanvasY = canvasY - 8 + canvasLength; //max Y value that can be drawn on in the canvas public: //====================================================== // DrawingUI(Vector2f p): this is the constructor for DrawingUI, only draws the canvas // parameters: coordinates for the canvas position // return type: none //====================================================== DrawingUI(Vector2f p) { drawingArea.setSize(Vector2f(canvasLength, canvasLength)); drawingArea.setPosition(p); drawingArea.setOutlineThickness(2); drawingArea.setOutlineColor(Color::White); drawingArea.setFillColor(Color::White); } //====================================================== // draw(RenderWindow& win, ShapeMgr *mgr): draws each shape to the screen from the vector // parameters: the window for drawing in and the ptr to a ShapeMgr in order to acces the drawing vector // return type: void //====================================================== void draw(RenderWindow& win, ShapeMgr *mgr) { win.draw(drawingArea); for (int i = 0; i < mgr->getVector().size(); i++) { mgr->getVector()[i]->drawShape(win); } } //====================================================== // isMouseInCanvas(Vector2f mousePos): checks to see if the mouse is in the drawing canvas // parameters: the mouses position // return type: bool; true if mouse is in the canvas else false //====================================================== bool isMouseInCanvas(Vector2f mousePos) { bool isInCanvas; if (drawingArea.getGlobalBounds().contains(mousePos) && mousePos.x < (drawingCanvasX) && mousePos.y < (drawingCanvasY)) isInCanvas = true; else isInCanvas = false; return isInCanvas; } };
faeb59ac4b15da1cc0973dae7cf90c284884712b
05a85f5e782be00fee2fd8f8e4083af6850d62cd
/Codigos_Arduino/libraries/HCSR04/HCSR04.cpp
da01c5c58fc05176a1879a56b8bee314bf4785df
[]
no_license
alanjurnetb/Plataforma-inteligente
abe7c1294bcb256bfce134748193a3195eae089e
aab195b77c6794d2797b7c4b587127f8ed81e555
refs/heads/master
2020-03-24T01:19:18.323079
2018-11-01T03:09:36
2018-11-01T03:09:36
142,331,086
0
0
null
null
null
null
UTF-8
C++
false
false
1,814
cpp
HCSR04.cpp
#include "HCSR04.h" ultraSensor::ultraSensor(char t_pin, char e_pin){ trigger_pin=t_pin; echo_pin=e_pin; sensor_status=IDLE; pinMode(t_pin, OUTPUT); /*activación del pin 9 como salida: para el pulso ultrasónico*/ pinMode(e_pin, INPUT); /*activación del pin 8 como entrada: tiempo del rebote del ultrasonido*/ }; void ultraSensor::sense(){ digitalWrite(trigger_pin,LOW); /* Por cuestión de estabilización del sensor*/ delayMicroseconds(5); digitalWrite(trigger_pin, HIGH); /* envío del pulso ultrasónico*/ delayMicroseconds(10); measured_time=pulseIn(echo_pin, HIGH); /* Función para medir la longitud del pulso entrante. Mide el tiempo que transcurrido entre el envío del pulso ultrasónico y cuando el sensor recibe el rebote, es decir: desde que el pin 12 empieza a recibir el rebote, HIGH, hasta que deja de hacerlo, LOW, la longitud del pulso entrante*/ distance= int(0.017*measured_time); } void ultraSensor::start_measure(void){ if(micros()-last_measure>DELTA_BEWTWEEN_MEASURES){ ultraSensor::trigger_sensor(); } } void ultraSensor::trigger_sensor(void){ if(sensor_status==IDLE){ digitalWrite(trigger_pin,LOW); /* Por cuestión de estabilización del sensor*/ delayMicroseconds(5); digitalWrite(trigger_pin, HIGH); /* envío del pulso ultrasónico*/ delayMicroseconds(10); sensor_status=TRIGGERED_S; } }; void ultraSensor::update_measure(){ if (digitalRead(echo_pin)==1 && sensor_status==TRIGGERED_S){ sensor_status=MEASURING_ECHO; trigger_time=micros(); }else if(digitalRead(echo_pin)== 0 && sensor_status==MEASURING_ECHO){ measured_time=reading_time-trigger_time; distance= int(0.017*measured_time); sensor_status=IDLE; last_measure=micros(); } reading_time=micros(); }; float ultraSensor::get_distance(void){ return(distance); };
a670df6ff6dc40e7f6d6c5296e2f93935d31353d
8dca0161781b25561f58ba871294f82bda5aac72
/even_tree.cpp
2cc093dff6326ef21ec4b5a706f7335ea2d86954
[]
no_license
atif93/hackerrank
87128dd04e1b227e22971526ecb7bd02c7117fc1
d44393c1a7b37e7f944e6d9521905951f436505c
refs/heads/master
2020-07-29T07:47:01.620230
2018-01-14T23:53:46
2018-01-14T23:53:46
73,678,445
0
0
null
null
null
null
UTF-8
C++
false
false
2,141
cpp
even_tree.cpp
/* Even Tree https://www.hackerrank.com/challenges/even-tree */ #include <iostream> #include <list> #include <stack> using namespace std; // implementing as tree takes a lot of time for insertion // (find the parent in the tree and then add the child) // if implemented as a graph, then adjacency list is nothing but the children + parent // Also, DFS in this graph will be DFS traversal of the tree class Tree { int nVertices; list<int> * children; public: Tree(int _nVertices); // contructor void addEdge(int node1, int node2); void DFS(int startingNode); }; Tree::Tree (int _nVertices) { nVertices = _nVertices; children = new list<int>[nVertices]; } void Tree::addEdge(int node1, int node2) { children[node1].push_back(node2); children[node2].push_back(node1); } void Tree::DFS(int startingNode) { stack<int> stack, stack2; int ans = 0; bool * visited = new bool[nVertices](); int * size = new int[nVertices](); stack.push(startingNode); stack2.push(startingNode); // stack2 is being maintained for reverse BFS of the tree and calculating the size of subtrees in the process visited[startingNode] = true; while(!stack.empty()) { int s = stack.top(); stack.pop(); for(list<int>::reverse_iterator i = children[s].rbegin(); i != children[s].rend(); i++) { if(!visited[*i]) { stack.push(*i); stack2.push(*i); visited[*i] = true; } } } // tracing back the tree (reverse BFS) and calculating the size of subtrees // if the size of the subtree is even then it can be separated while(!stack2.empty()) { int s = stack2.top(); size[s] = 1; // counting the root itself in the subtree size for(list<int>::iterator i = children[s].begin(); i != children[s].end(); i++) { if(size[*i] != 0) { // don't count the parent size[s] = size[s] + size[*i]; } } if(size[s] % 2 == 0 && s != 0) { ans++; } stack2.pop(); } cout << ans; delete [] children; delete [] size; } int main() { int N, M; int node1, node2; cin >> N >> M; Tree tree(N); while(M--) { cin >> node1 >> node2; tree.addEdge(node1-1, node2-1); } tree.DFS(0); return 0; }
647c7224980b84fb17ee212730939af8e097dfeb
31757afb2a88b029777d90b2421a9f739c57d9ea
/MyDirectXLib/Project1/Source/Device/Resource/Mesh.cpp
0aed95a390b166515c9b9926a5213caf05259a52
[]
no_license
TsurumiMasayuki/MyDirectXLib
14d6a8c8057db1aa6631680c0d34e6f9843842a8
004d4f9bea7cd4d7a25ebc87edca843a61033bc0
refs/heads/master
2020-09-28T10:59:42.106028
2020-05-21T04:18:05
2020-05-21T04:18:05
226,764,165
1
1
null
null
null
null
SHIFT_JIS
C++
false
false
4,510
cpp
Mesh.cpp
#include "Mesh.h" #include <fbxsdk.h> #include "Device\DirectXManager.h" #include "Device\Base\MeshVertex.h" #include "Device\Buffer\VertexBuffer.h" #include "Device\Buffer\IndexBuffer.h" #include "Device\Resource\TextureManager.h" #include "Utility\StringUtility.h" #include <vector> #include <cassert> Mesh::Mesh() : m_pVertexBuffer(nullptr), m_pIndexBuffer(nullptr) { } Mesh::~Mesh() { delete m_pVertexBuffer; delete m_pIndexBuffer; } void Mesh::init(const std::string filePath, const std::wstring textureName) { m_TextureName = StringUtility::toString(textureName); if (textureName != L"Default") { TextureManager::loadTexture(textureName.c_str(), m_TextureName); } //Fbx系の管理オブジェクトを作成 FbxManager* pFbxManager = FbxManager::Create(); //入出力設定 FbxIOSettings* pIOSetting = FbxIOSettings::Create(pFbxManager, IOSROOT); pFbxManager->SetIOSettings(pIOSetting); //インポーター FbxImporter* pImporter = FbxImporter::Create(pFbxManager, ""); //fbxをインポート bool isLoaded = pImporter->Initialize(filePath.c_str(), -1, pFbxManager->GetIOSettings()); #ifdef _DEBUG //失敗したらfalseが返るのでエラー処理 assert(isLoaded); #endif //シーンの作成とインポート FbxScene* pFbxScene = FbxScene::Create(pFbxManager, "myScene"); pImporter->Import(pFbxScene); //インポートが終わったので破棄 pImporter->Destroy(); //メッシュデータ FbxMesh* pMesh = nullptr; //メッシュデータの取得 for (int i = 0; i < pFbxScene->GetRootNode()->GetChildCount(); ++i) { //シーン内のノードを一個ずつ取得 FbxNode* pChildNode = pFbxScene->GetRootNode()->GetChild(i); //ノードの種類がメッシュ用ならメッシュを取得 if (pChildNode->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eMesh) { pMesh = pChildNode->GetMesh(); break; } } initVertices(pMesh); pIOSetting->Destroy(); pFbxManager->Destroy(); } const VertexBuffer & Mesh::getVertexBuffer() { return *m_pVertexBuffer; } const IndexBuffer & Mesh::getIndexBuffer() { return *m_pIndexBuffer; } int Mesh::getVertexCount() { return m_VertexCount; } void Mesh::initVertices(FbxMesh* pMesh) { FbxStringList uvSetList; pMesh->GetUVSetNames(uvSetList); auto uvElem = pMesh->GetElementUV(uvSetList.GetStringAt(0)); //UV座標の数で配列生成 MeshVertex* vertices = new MeshVertex[pMesh->GetPolygonVertexCount()]; int* indices = new int[pMesh->GetPolygonVertexCount()]; //頂点バッファ用の情報を取得 int vertexCount = pMesh->GetPolygonVertexCount() - 1; for (int i = 0; i < pMesh->GetPolygonCount(); ++i) { for (int j = 0; j < pMesh->GetPolygonSize(i); ++j) { int vertexIndex = pMesh->GetPolygonVertex(i, j); indices[vertexCount] = vertexCount; vertices[vertexCount].m_Pos.x = -(float)pMesh->GetControlPointAt(vertexIndex)[0]; //頂点のX成分を取得 vertices[vertexCount].m_Pos.y = (float)pMesh->GetControlPointAt(vertexIndex)[1]; //頂点のY成分を取得 vertices[vertexCount].m_Pos.z = (float)pMesh->GetControlPointAt(vertexIndex)[2]; //頂点のZ成分を取得 FbxVector4 normal; pMesh->GetPolygonVertexNormal(i, j, normal); vertices[vertexCount].m_Normal.x = -(float)normal[0]; //法線のX成分を取得 vertices[vertexCount].m_Normal.y = (float)normal[1]; //法線のY成分を取得 vertices[vertexCount].m_Normal.z = (float)normal[2]; //法線のZ成分を取得 FbxVector2 uv; bool isUnMapped = true; pMesh->GetPolygonVertexUV(i, j, uvSetList.GetStringAt(0), uv, isUnMapped); vertices[vertexCount].m_UV.x = (float)uv[0]; //UVのX成分を取得 vertices[vertexCount].m_UV.y = 1 - (float)uv[1]; //UVのY成分を取得 vertexCount--; } } auto pDevice = DirectXManager::getDevice(); //頂点バッファの作成 if (m_pVertexBuffer != nullptr) delete m_pVertexBuffer; m_pVertexBuffer = new VertexBuffer(); m_pVertexBuffer->init(pDevice, sizeof(MeshVertex) * uvElem->GetIndexArray().GetCount(), vertices); //不要になったので頂点データを解放 delete[] vertices; //インデックスバッファの作成 if (m_pIndexBuffer != nullptr) delete m_pIndexBuffer; m_pIndexBuffer = new IndexBuffer(); m_pIndexBuffer->init(pDevice, sizeof(int) * uvElem->GetIndexArray().GetCount(), indices); //不要になったのでインデックスデータを解放 delete[] indices; //頂点数を取得 m_VertexCount = uvElem->GetIndexArray().GetCount(); }
13c15ed05211e0c27a17018f58a120a27032c21f
194e716d0e66520e045b1435b3308b7dd7217d4b
/1st_course/1st_semester/5th_homework/task_3/task5.3.cpp
0ab17954fe32e2d7357c318f14c88aabcd95744a
[]
no_license
ilya-nozhkin/Homework-SPbU
3a9db38d374556c2586187a66cc0be941aabcd86
530b20aef3a24b978bf849b9ac9f55b4d88e06c5
refs/heads/master
2021-01-12T10:45:56.238452
2018-06-05T13:30:22
2018-06-05T13:30:22
72,679,644
6
1
null
2018-06-05T13:30:23
2016-11-02T20:42:59
C++
UTF-8
C++
false
false
1,926
cpp
task5.3.cpp
#include <iostream> #include <fstream> using namespace std; void inputString(char *buffer, const char *what) { cout << "Enter " << what << ":" << endl; cin >> buffer; } void printLineFromFile(ifstream &file) { const int bufferSize = 512; char buffer[bufferSize] = {'\0'}; file.getline(buffer, bufferSize); cout << buffer << endl; } void processFile(ifstream &file) { bool comment = false; bool quotes = false; while (!file.eof()) { char current = 0; file >> current; if (!quotes && !comment) { if (current == '"') quotes = true; else if (current == '/') { if (!file.eof()) { char next = 0; file >> next; if (next == '*') comment = true; else if (next == '/') { cout << "//"; printLineFromFile(file); } } } } else { if (current == '"' && quotes) quotes = false; else if (current == '*' && comment) { if (!file.eof()) { char next = 0; file >> next; if (next == '/') comment = false; } } } } } int main() { const int filenameSize = 256; char filename[filenameSize] = {'\0'}; inputString(filename, "the file name"); ifstream file(filename); if (!file.is_open()) { cout << "couldn't open the file" << endl; return 1; } processFile(file); file.close(); return 0; }
31568bd152960cfa7c611b65efb5d5af73b5bbdd
f131f99c2410c2c84bfa8cd3ae1bc035048ebe48
/axe.mod/v8.mod/src/ia32/builtins-ia32.cpp
7793e492657031ddbf854fb175758753aa55fd9c
[ "BSD-3-Clause", "MIT" ]
permissive
nitrologic/mod
b2a81e44db5ef85a573187c27b634eb393c1ca0c
f4f1e3c5e6af0890dc9b81eea17513e9a2f29916
refs/heads/master
2021-05-15T01:39:21.181554
2018-03-16T21:16:56
2018-03-16T21:16:56
38,656,465
2
2
null
null
null
null
UTF-8
C++
false
false
26,612
cpp
builtins-ia32.cpp
// Copyright 2006-2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. 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. #include "v8.h" #include "codegen-inl.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void Builtins::Generate_Adaptor(MacroAssembler* masm, CFunctionId id) { // TODO(428): Don't pass the function in a static variable. ExternalReference passed = ExternalReference::builtin_passed_function(); __ mov(Operand::StaticVariable(passed), edi); // The actual argument count has already been loaded into register // eax, but JumpToBuiltin expects eax to contain the number of // arguments including the receiver. __ inc(eax); __ JumpToBuiltin(ExternalReference(id)); } void Builtins::Generate_JSConstructCall(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- eax: number of arguments // -- edi: constructor function // ----------------------------------- Label non_function_call; // Check that function is not a smi. __ test(edi, Immediate(kSmiTagMask)); __ j(zero, &non_function_call); // Check that function is a JSFunction. __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx); __ j(not_equal, &non_function_call); // Jump to the function-specific construct stub. __ mov(ebx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset)); __ mov(ebx, FieldOperand(ebx, SharedFunctionInfo::kConstructStubOffset)); __ lea(ebx, FieldOperand(ebx, Code::kHeaderSize)); __ jmp(Operand(ebx)); // edi: called object // eax: number of arguments __ bind(&non_function_call); // Set expected number of arguments to zero (not changing eax). __ Set(ebx, Immediate(0)); __ GetBuiltinEntry(edx, Builtins::CALL_NON_FUNCTION_AS_CONSTRUCTOR); __ jmp(Handle<Code>(builtin(ArgumentsAdaptorTrampoline)), RelocInfo::CODE_TARGET); } void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) { // Enter a construct frame. __ EnterConstructFrame(); // Store a smi-tagged arguments count on the stack. __ shl(eax, kSmiTagSize); __ push(eax); // Push the function to invoke on the stack. __ push(edi); // Try to allocate the object without transitioning into C code. If any of the // preconditions is not met, the code bails out to the runtime call. Label rt_call, allocated; if (FLAG_inline_new) { Label undo_allocation; #ifdef ENABLE_DEBUGGER_SUPPORT ExternalReference debug_step_in_fp = ExternalReference::debug_step_in_fp_address(); __ cmp(Operand::StaticVariable(debug_step_in_fp), Immediate(0)); __ j(not_equal, &rt_call); #endif // Verified that the constructor is a JSFunction. // Load the initial map and verify that it is in fact a map. // edi: constructor __ mov(eax, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset)); // Will both indicate a NULL and a Smi __ test(eax, Immediate(kSmiTagMask)); __ j(zero, &rt_call); // edi: constructor // eax: initial map (if proven valid below) __ CmpObjectType(eax, MAP_TYPE, ebx); __ j(not_equal, &rt_call); // Check that the constructor is not constructing a JSFunction (see comments // in Runtime_NewObject in runtime.cc). In which case the initial map's // instance type would be JS_FUNCTION_TYPE. // edi: constructor // eax: initial map __ CmpInstanceType(eax, JS_FUNCTION_TYPE); __ j(equal, &rt_call); // Now allocate the JSObject on the heap. // edi: constructor // eax: initial map __ movzx_b(edi, FieldOperand(eax, Map::kInstanceSizeOffset)); __ shl(edi, kPointerSizeLog2); __ AllocateObjectInNewSpace(edi, ebx, edi, no_reg, &rt_call, NO_ALLOCATION_FLAGS); // Allocated the JSObject, now initialize the fields. // eax: initial map // ebx: JSObject // edi: start of next object __ mov(Operand(ebx, JSObject::kMapOffset), eax); __ mov(ecx, Factory::empty_fixed_array()); __ mov(Operand(ebx, JSObject::kPropertiesOffset), ecx); __ mov(Operand(ebx, JSObject::kElementsOffset), ecx); // Set extra fields in the newly allocated object. // eax: initial map // ebx: JSObject // edi: start of next object { Label loop, entry; __ mov(edx, Factory::undefined_value()); __ lea(ecx, Operand(ebx, JSObject::kHeaderSize)); __ jmp(&entry); __ bind(&loop); __ mov(Operand(ecx, 0), edx); __ add(Operand(ecx), Immediate(kPointerSize)); __ bind(&entry); __ cmp(ecx, Operand(edi)); __ j(less, &loop); } // Add the object tag to make the JSObject real, so that we can continue and // jump into the continuation code at any time from now on. Any failures // need to undo the allocation, so that the heap is in a consistent state // and verifiable. // eax: initial map // ebx: JSObject // edi: start of next object __ or_(Operand(ebx), Immediate(kHeapObjectTag)); // Check if a non-empty properties array is needed. // Allocate and initialize a FixedArray if it is. // eax: initial map // ebx: JSObject // edi: start of next object // Calculate the total number of properties described by the map. __ movzx_b(edx, FieldOperand(eax, Map::kUnusedPropertyFieldsOffset)); __ movzx_b(ecx, FieldOperand(eax, Map::kPreAllocatedPropertyFieldsOffset)); __ add(edx, Operand(ecx)); // Calculate unused properties past the end of the in-object properties. __ movzx_b(ecx, FieldOperand(eax, Map::kInObjectPropertiesOffset)); __ sub(edx, Operand(ecx)); // Done if no extra properties are to be allocated. __ j(zero, &allocated); __ Assert(positive, "Property allocation count failed."); // Scale the number of elements by pointer size and add the header for // FixedArrays to the start of the next object calculation from above. // ebx: JSObject // edi: start of next object (will be start of FixedArray) // edx: number of elements in properties array __ AllocateObjectInNewSpace(FixedArray::kHeaderSize, times_pointer_size, edx, edi, ecx, no_reg, &undo_allocation, RESULT_CONTAINS_TOP); // Initialize the FixedArray. // ebx: JSObject // edi: FixedArray // edx: number of elements // ecx: start of next object __ mov(eax, Factory::fixed_array_map()); __ mov(Operand(edi, JSObject::kMapOffset), eax); // setup the map __ mov(Operand(edi, Array::kLengthOffset), edx); // and length // Initialize the fields to undefined. // ebx: JSObject // edi: FixedArray // ecx: start of next object { Label loop, entry; __ mov(edx, Factory::undefined_value()); __ lea(eax, Operand(edi, FixedArray::kHeaderSize)); __ jmp(&entry); __ bind(&loop); __ mov(Operand(eax, 0), edx); __ add(Operand(eax), Immediate(kPointerSize)); __ bind(&entry); __ cmp(eax, Operand(ecx)); __ j(below, &loop); } // Store the initialized FixedArray into the properties field of // the JSObject // ebx: JSObject // edi: FixedArray __ or_(Operand(edi), Immediate(kHeapObjectTag)); // add the heap tag __ mov(FieldOperand(ebx, JSObject::kPropertiesOffset), edi); // Continue with JSObject being successfully allocated // ebx: JSObject __ jmp(&allocated); // Undo the setting of the new top so that the heap is verifiable. For // example, the map's unused properties potentially do not match the // allocated objects unused properties. // ebx: JSObject (previous new top) __ bind(&undo_allocation); __ UndoAllocationInNewSpace(ebx); } // Allocate the new receiver object using the runtime call. __ bind(&rt_call); // Must restore edi (constructor) before calling runtime. __ mov(edi, Operand(esp, 0)); // edi: function (constructor) __ push(edi); __ CallRuntime(Runtime::kNewObject, 1); __ mov(ebx, Operand(eax)); // store result in ebx // New object allocated. // ebx: newly allocated object __ bind(&allocated); // Retrieve the function from the stack. __ pop(edi); // Retrieve smi-tagged arguments count from the stack. __ mov(eax, Operand(esp, 0)); __ shr(eax, kSmiTagSize); // Push the allocated receiver to the stack. We need two copies // because we may have to return the original one and the calling // conventions dictate that the called function pops the receiver. __ push(ebx); __ push(ebx); // Setup pointer to last argument. __ lea(ebx, Operand(ebp, StandardFrameConstants::kCallerSPOffset)); // Copy arguments and receiver to the expression stack. Label loop, entry; __ mov(ecx, Operand(eax)); __ jmp(&entry); __ bind(&loop); __ push(Operand(ebx, ecx, times_4, 0)); __ bind(&entry); __ dec(ecx); __ j(greater_equal, &loop); // Call the function. ParameterCount actual(eax); __ InvokeFunction(edi, actual, CALL_FUNCTION); // Restore context from the frame. __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset)); // If the result is an object (in the ECMA sense), we should get rid // of the receiver and use the result; see ECMA-262 section 13.2.2-7 // on page 74. Label use_receiver, exit; // If the result is a smi, it is *not* an object in the ECMA sense. __ test(eax, Immediate(kSmiTagMask)); __ j(zero, &use_receiver, not_taken); // If the type of the result (stored in its map) is less than // FIRST_JS_OBJECT_TYPE, it is not an object in the ECMA sense. __ mov(ecx, FieldOperand(eax, HeapObject::kMapOffset)); __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset)); __ cmp(ecx, FIRST_JS_OBJECT_TYPE); __ j(greater_equal, &exit, not_taken); // Throw away the result of the constructor invocation and use the // on-stack receiver as the result. __ bind(&use_receiver); __ mov(eax, Operand(esp, 0)); // Restore the arguments count and leave the construct frame. __ bind(&exit); __ mov(ebx, Operand(esp, kPointerSize)); // get arguments count __ LeaveConstructFrame(); // Remove caller arguments from the stack and return. ASSERT(kSmiTagSize == 1 && kSmiTag == 0); __ pop(ecx); __ lea(esp, Operand(esp, ebx, times_2, 1 * kPointerSize)); // 1 ~ receiver __ push(ecx); __ IncrementCounter(&Counters::constructed_objects, 1); __ ret(0); } static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm, bool is_construct) { // Clear the context before we push it when entering the JS frame. __ xor_(esi, Operand(esi)); // clear esi // Enter an internal frame. __ EnterInternalFrame(); // Load the previous frame pointer (ebx) to access C arguments __ mov(ebx, Operand(ebp, 0)); // Get the function from the frame and setup the context. __ mov(ecx, Operand(ebx, EntryFrameConstants::kFunctionArgOffset)); __ mov(esi, FieldOperand(ecx, JSFunction::kContextOffset)); // Push the function and the receiver onto the stack. __ push(ecx); __ push(Operand(ebx, EntryFrameConstants::kReceiverArgOffset)); // Load the number of arguments and setup pointer to the arguments. __ mov(eax, Operand(ebx, EntryFrameConstants::kArgcOffset)); __ mov(ebx, Operand(ebx, EntryFrameConstants::kArgvOffset)); // Copy arguments to the stack in a loop. Label loop, entry; __ xor_(ecx, Operand(ecx)); // clear ecx __ jmp(&entry); __ bind(&loop); __ mov(edx, Operand(ebx, ecx, times_4, 0)); // push parameter from argv __ push(Operand(edx, 0)); // dereference handle __ inc(Operand(ecx)); __ bind(&entry); __ cmp(ecx, Operand(eax)); __ j(not_equal, &loop); // Get the function from the stack and call it. __ mov(edi, Operand(esp, eax, times_4, +1 * kPointerSize)); // +1 ~ receiver // Invoke the code. if (is_construct) { __ call(Handle<Code>(Builtins::builtin(Builtins::JSConstructCall)), RelocInfo::CODE_TARGET); } else { ParameterCount actual(eax); __ InvokeFunction(edi, actual, CALL_FUNCTION); } // Exit the JS frame. Notice that this also removes the empty // context and the function left on the stack by the code // invocation. __ LeaveInternalFrame(); __ ret(1 * kPointerSize); // remove receiver } void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, false); } void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) { Generate_JSEntryTrampolineHelper(masm, true); } void Builtins::Generate_FunctionCall(MacroAssembler* masm) { // 1. Make sure we have at least one argument. { Label done; __ test(eax, Operand(eax)); __ j(not_zero, &done, taken); __ pop(ebx); __ push(Immediate(Factory::undefined_value())); __ push(ebx); __ inc(eax); __ bind(&done); } // 2. Get the function to call from the stack. { Label done, non_function, function; // +1 ~ return address. __ mov(edi, Operand(esp, eax, times_4, +1 * kPointerSize)); __ test(edi, Immediate(kSmiTagMask)); __ j(zero, &non_function, not_taken); __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx); __ j(equal, &function, taken); // Non-function called: Clear the function to force exception. __ bind(&non_function); __ xor_(edi, Operand(edi)); __ jmp(&done); // Function called: Change context eagerly to get the right global object. __ bind(&function); __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset)); __ bind(&done); } // 3. Make sure first argument is an object; convert if necessary. { Label call_to_object, use_global_receiver, patch_receiver, done; __ mov(ebx, Operand(esp, eax, times_4, 0)); __ test(ebx, Immediate(kSmiTagMask)); __ j(zero, &call_to_object); __ cmp(ebx, Factory::null_value()); __ j(equal, &use_global_receiver); __ cmp(ebx, Factory::undefined_value()); __ j(equal, &use_global_receiver); __ mov(ecx, FieldOperand(ebx, HeapObject::kMapOffset)); __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset)); __ cmp(ecx, FIRST_JS_OBJECT_TYPE); __ j(less, &call_to_object); __ cmp(ecx, LAST_JS_OBJECT_TYPE); __ j(less_equal, &done); __ bind(&call_to_object); __ EnterInternalFrame(); // preserves eax, ebx, edi // Store the arguments count on the stack (smi tagged). ASSERT(kSmiTag == 0); __ shl(eax, kSmiTagSize); __ push(eax); __ push(edi); // save edi across the call __ push(ebx); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ mov(ebx, eax); __ pop(edi); // restore edi after the call // Get the arguments count and untag it. __ pop(eax); __ shr(eax, kSmiTagSize); __ LeaveInternalFrame(); __ jmp(&patch_receiver); // Use the global receiver object from the called function as the receiver. __ bind(&use_global_receiver); const int kGlobalIndex = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize; __ mov(ebx, FieldOperand(esi, kGlobalIndex)); __ mov(ebx, FieldOperand(ebx, GlobalObject::kGlobalReceiverOffset)); __ bind(&patch_receiver); __ mov(Operand(esp, eax, times_4, 0), ebx); __ bind(&done); } // 4. Shift stuff one slot down the stack. { Label loop; __ lea(ecx, Operand(eax, +1)); // +1 ~ copy receiver too __ bind(&loop); __ mov(ebx, Operand(esp, ecx, times_4, 0)); __ mov(Operand(esp, ecx, times_4, kPointerSize), ebx); __ dec(ecx); __ j(not_zero, &loop); } // 5. Remove TOS (copy of last arguments), but keep return address. __ pop(ebx); __ pop(ecx); __ push(ebx); __ dec(eax); // 6. Check that function really was a function and get the code to // call from the function and check that the number of expected // arguments matches what we're providing. { Label invoke; __ test(edi, Operand(edi)); __ j(not_zero, &invoke, taken); __ xor_(ebx, Operand(ebx)); __ GetBuiltinEntry(edx, Builtins::CALL_NON_FUNCTION); __ jmp(Handle<Code>(builtin(ArgumentsAdaptorTrampoline)), RelocInfo::CODE_TARGET); __ bind(&invoke); __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset)); __ mov(ebx, FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset)); __ mov(edx, FieldOperand(edx, SharedFunctionInfo::kCodeOffset)); __ lea(edx, FieldOperand(edx, Code::kHeaderSize)); __ cmp(eax, Operand(ebx)); __ j(not_equal, Handle<Code>(builtin(ArgumentsAdaptorTrampoline))); } // 7. Jump (tail-call) to the code in register edx without checking arguments. ParameterCount expected(0); __ InvokeCode(Operand(edx), expected, expected, JUMP_FUNCTION); } void Builtins::Generate_FunctionApply(MacroAssembler* masm) { __ EnterInternalFrame(); __ push(Operand(ebp, 4 * kPointerSize)); // push this __ push(Operand(ebp, 2 * kPointerSize)); // push arguments __ InvokeBuiltin(Builtins::APPLY_PREPARE, CALL_FUNCTION); if (FLAG_check_stack) { // We need to catch preemptions right here, otherwise an unlucky preemption // could show up as a failed apply. ExternalReference stack_guard_limit = ExternalReference::address_of_stack_guard_limit(); Label retry_preemption; Label no_preemption; __ bind(&retry_preemption); __ mov(edi, Operand::StaticVariable(stack_guard_limit)); __ cmp(esp, Operand(edi)); __ j(above, &no_preemption, taken); // Preemption! // Because builtins always remove the receiver from the stack, we // have to fake one to avoid underflowing the stack. __ push(eax); __ push(Immediate(Smi::FromInt(0))); // Do call to runtime routine. __ CallRuntime(Runtime::kStackGuard, 1); __ pop(eax); __ jmp(&retry_preemption); __ bind(&no_preemption); Label okay; // Make ecx the space we have left. __ mov(ecx, Operand(esp)); __ sub(ecx, Operand(edi)); // Make edx the space we need for the array when it is unrolled onto the // stack. __ mov(edx, Operand(eax)); __ shl(edx, kPointerSizeLog2 - kSmiTagSize); __ cmp(ecx, Operand(edx)); __ j(greater, &okay, taken); // Too bad: Out of stack space. __ push(Operand(ebp, 4 * kPointerSize)); // push this __ push(eax); __ InvokeBuiltin(Builtins::APPLY_OVERFLOW, CALL_FUNCTION); __ bind(&okay); } // Push current index and limit. const int kLimitOffset = StandardFrameConstants::kExpressionsOffset - 1 * kPointerSize; const int kIndexOffset = kLimitOffset - 1 * kPointerSize; __ push(eax); // limit __ push(Immediate(0)); // index // Change context eagerly to get the right global object if // necessary. __ mov(edi, Operand(ebp, 4 * kPointerSize)); __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset)); // Compute the receiver. Label call_to_object, use_global_receiver, push_receiver; __ mov(ebx, Operand(ebp, 3 * kPointerSize)); __ test(ebx, Immediate(kSmiTagMask)); __ j(zero, &call_to_object); __ cmp(ebx, Factory::null_value()); __ j(equal, &use_global_receiver); __ cmp(ebx, Factory::undefined_value()); __ j(equal, &use_global_receiver); // If given receiver is already a JavaScript object then there's no // reason for converting it. __ mov(ecx, FieldOperand(ebx, HeapObject::kMapOffset)); __ movzx_b(ecx, FieldOperand(ecx, Map::kInstanceTypeOffset)); __ cmp(ecx, FIRST_JS_OBJECT_TYPE); __ j(less, &call_to_object); __ cmp(ecx, LAST_JS_OBJECT_TYPE); __ j(less_equal, &push_receiver); // Convert the receiver to an object. __ bind(&call_to_object); __ push(ebx); __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); __ mov(ebx, Operand(eax)); __ jmp(&push_receiver); // Use the current global receiver object as the receiver. __ bind(&use_global_receiver); const int kGlobalOffset = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize; __ mov(ebx, FieldOperand(esi, kGlobalOffset)); __ mov(ebx, FieldOperand(ebx, GlobalObject::kGlobalReceiverOffset)); // Push the receiver. __ bind(&push_receiver); __ push(ebx); // Copy all arguments from the array to the stack. Label entry, loop; __ mov(eax, Operand(ebp, kIndexOffset)); __ jmp(&entry); __ bind(&loop); __ mov(ecx, Operand(ebp, 2 * kPointerSize)); // load arguments __ push(ecx); __ push(eax); // Use inline caching to speed up access to arguments. Handle<Code> ic(Builtins::builtin(Builtins::KeyedLoadIC_Initialize)); __ call(ic, RelocInfo::CODE_TARGET); // It is important that we do not have a test instruction after the // call. A test instruction after the call is used to indicate that // we have generated an inline version of the keyed load. In this // case, we know that we are not generating a test instruction next. // Remove IC arguments from the stack and push the nth argument. __ add(Operand(esp), Immediate(2 * kPointerSize)); __ push(eax); // Update the index on the stack and in register eax. __ mov(eax, Operand(ebp, kIndexOffset)); __ add(Operand(eax), Immediate(1 << kSmiTagSize)); __ mov(Operand(ebp, kIndexOffset), eax); __ bind(&entry); __ cmp(eax, Operand(ebp, kLimitOffset)); __ j(not_equal, &loop); // Invoke the function. ParameterCount actual(eax); __ shr(eax, kSmiTagSize); __ mov(edi, Operand(ebp, 4 * kPointerSize)); __ InvokeFunction(edi, actual, CALL_FUNCTION); __ LeaveInternalFrame(); __ ret(3 * kPointerSize); // remove this, receiver, and arguments } static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) { __ push(ebp); __ mov(ebp, Operand(esp)); // Store the arguments adaptor context sentinel. __ push(Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR))); // Push the function on the stack. __ push(edi); // Preserve the number of arguments on the stack. Must preserve both // eax and ebx because these registers are used when copying the // arguments and the receiver. ASSERT(kSmiTagSize == 1); __ lea(ecx, Operand(eax, eax, times_1, kSmiTag)); __ push(ecx); } static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) { // Retrieve the number of arguments from the stack. __ mov(ebx, Operand(ebp, ArgumentsAdaptorFrameConstants::kLengthOffset)); // Leave the frame. __ leave(); // Remove caller arguments from the stack. ASSERT(kSmiTagSize == 1 && kSmiTag == 0); __ pop(ecx); __ lea(esp, Operand(esp, ebx, times_2, 1 * kPointerSize)); // 1 ~ receiver __ push(ecx); } void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- eax : actual number of arguments // -- ebx : expected number of arguments // -- edx : code entry to call // ----------------------------------- Label invoke, dont_adapt_arguments; __ IncrementCounter(&Counters::arguments_adaptors, 1); Label enough, too_few; __ cmp(eax, Operand(ebx)); __ j(less, &too_few); __ cmp(ebx, SharedFunctionInfo::kDontAdaptArgumentsSentinel); __ j(equal, &dont_adapt_arguments); { // Enough parameters: Actual >= expected. __ bind(&enough); EnterArgumentsAdaptorFrame(masm); // Copy receiver and all expected arguments. const int offset = StandardFrameConstants::kCallerSPOffset; __ lea(eax, Operand(ebp, eax, times_4, offset)); __ mov(ecx, -1); // account for receiver Label copy; __ bind(&copy); __ inc(ecx); __ push(Operand(eax, 0)); __ sub(Operand(eax), Immediate(kPointerSize)); __ cmp(ecx, Operand(ebx)); __ j(less, &copy); __ jmp(&invoke); } { // Too few parameters: Actual < expected. __ bind(&too_few); EnterArgumentsAdaptorFrame(masm); // Copy receiver and all actual arguments. const int offset = StandardFrameConstants::kCallerSPOffset; __ lea(edi, Operand(ebp, eax, times_4, offset)); __ mov(ecx, -1); // account for receiver Label copy; __ bind(&copy); __ inc(ecx); __ push(Operand(edi, 0)); __ sub(Operand(edi), Immediate(kPointerSize)); __ cmp(ecx, Operand(eax)); __ j(less, &copy); // Fill remaining expected arguments with undefined values. Label fill; __ bind(&fill); __ inc(ecx); __ push(Immediate(Factory::undefined_value())); __ cmp(ecx, Operand(ebx)); __ j(less, &fill); // Restore function pointer. __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset)); } // Call the entry point. __ bind(&invoke); __ call(Operand(edx)); // Leave frame and return. LeaveArgumentsAdaptorFrame(masm); __ ret(0); // ------------------------------------------- // Dont adapt arguments. // ------------------------------------------- __ bind(&dont_adapt_arguments); __ jmp(Operand(edx)); } #undef __ } } // namespace v8::internal
1be71f6dd9434ad130f9c072d48621595292ce3e
4f9c273b4345c9f4c709a84be424d49be24877a1
/Loewenherz-clientside/altis_life_loewenherz.altis/GUI/dialogs.hpp
0091d940da6dbfa8ee15898dea79dfcff0453a6b
[]
no_license
ArmALeakTeam/Loewenherz
92d4460d78d9296875626d125fd699e3e32734b3
8cd7aa0e3cf22102125c6c7151914a3bcaafe4ee
refs/heads/master
2018-03-20T19:02:46.908592
2016-08-28T01:12:14
2016-08-28T01:12:14
66,742,457
3
1
null
null
null
null
UTF-8
C++
false
false
2,426
hpp
dialogs.hpp
// Color macros #include "templates\colors.hpp" // Common layer with all classes #include "templates\common.hpp" #include "dialogs\lhm_NewsFlash.hpp" #include "dialogs\shop_items.hpp" #include "dialogs\player_inv.hpp" #include "dialogs\gang.hpp" #include "dialogs\key_chain.hpp" #include "dialogs\impound.hpp" #include "dialogs\bank.hpp" #include "dialogs\veh_shop.hpp" #include "dialogs\shops.hpp" #include "dialogs\admin_menu.hpp" #include "dialogs\cell_phone.hpp" #include "dialogs\wanted_list.hpp" #include "dialogs\ticket.hpp" #include "dialogs\clothing.hpp" #include "dialogs\trunk.hpp" #include "dialogs\spawnSelection.hpp" #include "dialogs\chop_shop.h" #include "dialogs\pInteraction.h" #include "dialogs\deathScreen.h" #include "dialogs\vehicleShop.h" #include "dialogs\settings.h" #include "dialogs\federalReserve.h" #include "dialogs\prof.hpp" #include "dialogs\interactionmenu.hpp" #include "dialogs\vvs_menu.h" #include "dialogs\vas_menu.hpp" #include "dialogs\gambling.hpp" #include "dialogs\emp_menu.hpp" #include "dialogs\speedtrap.hpp" #include "dialogs\smartphone.hpp" #include "dialogs\veh_repaint.hpp" #include "dialogs\lhm_itemshop.hpp" #include "dialogs\common_EditorWrapper.hpp" #include "dialogs\market.hpp" #include "dialogs\fuelstation.hpp" #include "dialogs\ObjectBuilder.hpp" #include "dialogs\don_shops.hpp" #include "dialogs\don_vehicleShop.h" #include "dialogs\bank_group_menu.hpp" #include "dialogs\explosivePad.hpp" #include "dialogs\AF_KP_dialogs.hpp" #include "dialogs\GetInMenu.hpp" #include "dialogs\infomenu.h" #include "dialogs\Wled_menu.hpp" #include "dialogs\jail_combatlog.hpp" #include "dialogs\licenses.hpp" #include "dialogs\bank_group_mode.hpp" #include "dialogs\bank_chat_Dialog.hpp" #include "dialogs\BA_dialog_interaction_menu.hpp" #include "dialogs\LHM_Admin_Menu.hpp" #include "dialogs\Cop_classification.hpp" #include "dialogs\terminal.hpp" #include "dialogs\cop_build_dialog.h" #include "dialogs\Map_Marker_Menu.hpp" #include "dialogs\LHM_BANK_STATUS.hpp" #include "dialogs\crafting_menu.h" #include "dialogs\injection.hpp" #include "dialogs\cop_sound_menu.hpp" #include "dialogs\LHM_fuelstations.hpp" #include "dialogs\BA_Scripting_console.hpp" #include "dialogs\admin_menu_extended.hpp" #include "dialogs\admin_menu_extended_save_code.hpp" #include "dialogs\Radar_heli.hpp" #include "dialogs\tablet_abzeichen.hpp" #include "dialogs\AWS.hpp" #include "dialogs\base.hpp"
7e8cca0e1c9ef920250b80585990d088cfd1bdb4
a7764174fb0351ea666faa9f3b5dfe304390a011
/src/BRep/BRep_PointsOnSurface.cxx
2e79bf7fa981636bcb80e8ef2d736ba43b486109
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
1,153
cxx
BRep_PointsOnSurface.cxx
// File: BRep_PointsOnSurface.cxx // Created: Tue Aug 10 14:44:35 1993 // Author: Remi LEQUETTE // <rle@phylox> #include <BRep_PointsOnSurface.ixx> //======================================================================= //function : BRep_PointsOnSurface //purpose : //======================================================================= BRep_PointsOnSurface::BRep_PointsOnSurface(const Standard_Real P, const Handle(Geom_Surface)& S, const TopLoc_Location& L) : BRep_PointRepresentation(P,L), mySurface(S) { } //======================================================================= //function : Surface //purpose : //======================================================================= const Handle(Geom_Surface)& BRep_PointsOnSurface::Surface()const { return mySurface; } //======================================================================= //function : Surface //purpose : //======================================================================= void BRep_PointsOnSurface::Surface(const Handle(Geom_Surface)& S) { mySurface = S; }
4a347c161ffe31f35e4690c99c3a73d3ae904d39
c1a8682ef39fcaa539188281a334fb7bb614cabe
/src/timer.cpp
bbc5920955f58fedeccc44ac406f9ea82617bf67
[]
no_license
Theatrekaz/bigpiano
5c5841be98a2cacb0fbfe93ded63e1a66310f011
3283b23b0353d654b54584c237fd3a08246dc486
refs/heads/master
2020-12-30T17:19:10.023464
2014-06-03T16:38:07
2014-06-03T16:38:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
cpp
timer.cpp
//----------------------------------------------------------------------------- /* Timer Functions Provide a simple timer using the 16-bit timer 1 of the ATmega328P. */ //----------------------------------------------------------------------------- #include <stdint.h> #include <avr/io.h> #include <util/atomic.h> #include "timer.h" //----------------------------------------------------------------------------- static uint32_t timer_ovf_count; void timer_ovf_isr(void) { timer_ovf_count ++; } //----------------------------------------------------------------------------- // return the time since boot in milliseconds uint32_t timer_get_msec(void) { // ticks_per_millisecond = F_CPU /(1000 * TIMER_DIV) = 15.625 // Approximate this as 16 to create a millsecond count using bit shifts. uint32_t msec; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { msec = timer_ovf_count << 12; msec |= TCNT1 >> 4; } return msec; } //----------------------------------------------------------------------------- // delay n milliseconds void timer_delay_msec(int n) { uint32_t timeout = timer_get_msec() + n; while(timer_get_msec() < timeout); } void timer_delay_msec_poll(int n, void (*poll)(void)) { uint32_t timeout = timer_get_msec() + n; while(timer_get_msec() < timeout) { if (poll) { poll(); } } } //----------------------------------------------------------------------------- // delay until a specific time void timer_delay_until(uint32_t time) { while(timer_get_msec() < time); } //----------------------------------------------------------------------------- int timer_init(void) { timer_ovf_count = 0; // using the 16 bit timer 1 for a tick counter // clock the counter at F_CPU / 1024 = 15625 Hz // increment an overflow counter every 2^16 / 15625 = 4.2 seconds TCCR1A = 0; TCCR1B = DIVIDE_BY_1024; TCCR1C = 0; OCR1A = 0; OCR1B = 0; ICR1 = 0; TIMSK1 = (1 << TOIE1); TIFR1 = (1 << TOV1); return 0; } //----------------------------------------------------------------------------- #if defined(ARDUINO) unsigned long millis(void) { return timer_get_msec(); } void delay(unsigned long ms) { timer_delay_msec((int)ms); } #endif // ARDUINO //-----------------------------------------------------------------------------
acce018803fe63fa6a9adc1fb72f726d883918b4
acf30fa254f72c282fce77b22dced66b21f8277d
/src/commands/importcertificatefromdatacommand.cpp
fe8111d6deab998c1e13024ef116c7f80cecc56d
[ "CC0-1.0", "BSD-3-Clause" ]
permissive
KDE/kleopatra
fc879c3d1f9fa4e7f54ebcb825eaea8705386d72
3e6db6e439bbb62886dd58cfc4239f256fec5415
refs/heads/master
2023-08-18T04:37:13.963770
2023-08-16T21:17:25
2023-08-16T21:17:34
53,312,712
84
16
null
2020-12-29T18:58:39
2016-03-07T09:27:39
C++
UTF-8
C++
false
false
2,164
cpp
importcertificatefromdatacommand.cpp
/* -*- mode: c++; c-basic-offset:4 -*- importcertificatefromdatacommand.cpp This file is part of Kleopatra, the KDE keymanager SPDX-FileCopyrightText: 2007 Klarälvdalens Datakonsult AB SPDX-License-Identifier: GPL-2.0-or-later */ #include <config-kleopatra.h> #include "importcertificatefromdatacommand.h" #include "importcertificatescommand_p.h" #include <KLocalizedString> #include <memory> using namespace GpgME; using namespace Kleo; using namespace QGpgME; class ImportCertificateFromDataCommand::Private : public ImportCertificatesCommand::Private { friend class ::ImportCertificateFromDataCommand; ImportCertificateFromDataCommand *q_func() const { return static_cast<ImportCertificateFromDataCommand *>(q); } public: explicit Private(ImportCertificateFromDataCommand *qq, const QByteArray &data, GpgME::Protocol proto, const QString &id); ~Private() override; private: QByteArray mData; GpgME::Protocol mProto; QString mId; }; ImportCertificateFromDataCommand::Private *ImportCertificateFromDataCommand::d_func() { return static_cast<Private *>(d.get()); } const ImportCertificateFromDataCommand::Private *ImportCertificateFromDataCommand::d_func() const { return static_cast<const Private *>(d.get()); } ImportCertificateFromDataCommand::Private::Private(ImportCertificateFromDataCommand *qq, const QByteArray &data, GpgME::Protocol proto, const QString &id) : ImportCertificatesCommand::Private(qq, nullptr) , mData(data) , mProto(proto) , mId(id) { } ImportCertificateFromDataCommand::Private::~Private() { } #define d d_func() #define q q_func() ImportCertificateFromDataCommand::ImportCertificateFromDataCommand(const QByteArray &data, GpgME::Protocol proto, const QString &id) : ImportCertificatesCommand(new Private(this, data, proto, id)) { } ImportCertificateFromDataCommand::~ImportCertificateFromDataCommand() { } void ImportCertificateFromDataCommand::doStart() { d->setWaitForMoreJobs(true); d->startImport(d->mProto, d->mData, d->mId.isEmpty() ? i18n("Notepad") : d->mId); d->setWaitForMoreJobs(false); } #undef d #undef q
42e530e8cc70acbb916856c092864ff126a125e3
fccdc44d81f152de9867b6c5a8047d62d8dcfff4
/202-happy-number/happy-number_[AC1_3ms].cpp
cadcbcf5ba8d00e98d67cdcaaf8f71c93cbb3b2c
[ "MIT" ]
permissive
NiceVinke/LeetCode
fc56d115cd69333127b82c2c41deaa1fbd92872c
9b15114b7a3de8638d44b3030edb72f41d9a274e
refs/heads/master
2021-06-24T22:39:19.292170
2017-09-05T13:07:25
2017-09-05T13:07:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
happy-number_[AC1_3ms].cpp
// Write an algorithm to determine if a number is "happy". // // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. // // Example:&nbsp;19 is a happy number // // // 12 + 92 = 82 // 82 + 22 = 68 // 62 + 82 = 100 // 12 + 02 + 02 = 1 // // // Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases. class Solution { public: bool isHappy(int n) { int num=0; while(n!=1&&n!=4) { while(n) { num += pow(n%10, 2); n/=10; } n=num; num=0; } return 1==n; } };
b3be39134cc50cfd9df9318da4a35fc973187419
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-8/android/test/RenamingDelegatingContext.hpp
64f909e0c7e003da69d2432807f76b6f84ca165f
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
14,838
hpp
RenamingDelegatingContext.hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.test.RenamingDelegatingContext ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_TEST_RENAMINGDELEGATINGCONTEXT_HPP_DECL #define J2CPP_ANDROID_TEST_RENAMINGDELEGATINGCONTEXT_HPP_DECL namespace j2cpp { namespace android { namespace database { namespace sqlite { class SQLiteDatabase; } } } } namespace j2cpp { namespace android { namespace database { namespace sqlite { namespace SQLiteDatabase_ { class CursorFactory; } } } } } namespace j2cpp { namespace android { namespace content { class ContentProvider; } } } namespace j2cpp { namespace android { namespace content { class ContextWrapper; } } } namespace j2cpp { namespace android { namespace content { class Context; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Class; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace io { class File; } } } namespace j2cpp { namespace java { namespace io { class FileOutputStream; } } } namespace j2cpp { namespace java { namespace io { class FileInputStream; } } } #include <android/content/ContentProvider.hpp> #include <android/content/Context.hpp> #include <android/content/ContextWrapper.hpp> #include <android/database/sqlite/SQLiteDatabase.hpp> #include <java/io/File.hpp> #include <java/io/FileInputStream.hpp> #include <java/io/FileOutputStream.hpp> #include <java/lang/Class.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace android { namespace test { class RenamingDelegatingContext; class RenamingDelegatingContext : public object<RenamingDelegatingContext> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) explicit RenamingDelegatingContext(jobject jobj) : object<RenamingDelegatingContext>(jobj) { } operator local_ref<android::content::ContextWrapper>() const; operator local_ref<android::content::Context>() const; operator local_ref<java::lang::Object>() const; RenamingDelegatingContext(local_ref< android::content::Context > const&, local_ref< java::lang::String > const&); RenamingDelegatingContext(local_ref< android::content::Context > const&, local_ref< android::content::Context > const&, local_ref< java::lang::String > const&); static local_ref< android::content::ContentProvider > providerWithRenamedContext(local_ref< java::lang::Class > const&, local_ref< android::content::Context > const&, local_ref< java::lang::String > const&); static local_ref< android::content::ContentProvider > providerWithRenamedContext(local_ref< java::lang::Class > const&, local_ref< android::content::Context > const&, local_ref< java::lang::String > const&, jboolean); void makeExistingFilesAndDbsAccessible(); local_ref< java::lang::String > getDatabasePrefix(); local_ref< android::database::sqlite::SQLiteDatabase > openOrCreateDatabase(local_ref< java::lang::String > const&, jint, local_ref< android::database::sqlite::SQLiteDatabase_::CursorFactory > const&); jboolean deleteDatabase(local_ref< java::lang::String > const&); local_ref< java::io::File > getDatabasePath(local_ref< java::lang::String > const&); local_ref< array< local_ref< java::lang::String >, 1> > databaseList(); local_ref< java::io::FileInputStream > openFileInput(local_ref< java::lang::String > const&); local_ref< java::io::FileOutputStream > openFileOutput(local_ref< java::lang::String > const&, jint); local_ref< java::io::File > getFileStreamPath(local_ref< java::lang::String > const&); jboolean deleteFile(local_ref< java::lang::String > const&); local_ref< array< local_ref< java::lang::String >, 1> > fileList(); local_ref< java::io::File > getCacheDir(); }; //class RenamingDelegatingContext } //namespace test } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_TEST_RENAMINGDELEGATINGCONTEXT_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_TEST_RENAMINGDELEGATINGCONTEXT_HPP_IMPL #define J2CPP_ANDROID_TEST_RENAMINGDELEGATINGCONTEXT_HPP_IMPL namespace j2cpp { android::test::RenamingDelegatingContext::operator local_ref<android::content::ContextWrapper>() const { return local_ref<android::content::ContextWrapper>(get_jobject()); } android::test::RenamingDelegatingContext::operator local_ref<android::content::Context>() const { return local_ref<android::content::Context>(get_jobject()); } android::test::RenamingDelegatingContext::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::test::RenamingDelegatingContext::RenamingDelegatingContext(local_ref< android::content::Context > const &a0, local_ref< java::lang::String > const &a1) : object<android::test::RenamingDelegatingContext>( call_new_object< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(0), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(0) >(a0, a1) ) { } android::test::RenamingDelegatingContext::RenamingDelegatingContext(local_ref< android::content::Context > const &a0, local_ref< android::content::Context > const &a1, local_ref< java::lang::String > const &a2) : object<android::test::RenamingDelegatingContext>( call_new_object< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(1), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(1) >(a0, a1, a2) ) { } local_ref< android::content::ContentProvider > android::test::RenamingDelegatingContext::providerWithRenamedContext(local_ref< java::lang::Class > const &a0, local_ref< android::content::Context > const &a1, local_ref< java::lang::String > const &a2) { return call_static_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(2), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(2), local_ref< android::content::ContentProvider > >(a0, a1, a2); } local_ref< android::content::ContentProvider > android::test::RenamingDelegatingContext::providerWithRenamedContext(local_ref< java::lang::Class > const &a0, local_ref< android::content::Context > const &a1, local_ref< java::lang::String > const &a2, jboolean a3) { return call_static_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(3), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(3), local_ref< android::content::ContentProvider > >(a0, a1, a2, a3); } void android::test::RenamingDelegatingContext::makeExistingFilesAndDbsAccessible() { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(4), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(4), void >(get_jobject()); } local_ref< java::lang::String > android::test::RenamingDelegatingContext::getDatabasePrefix() { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(5), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(5), local_ref< java::lang::String > >(get_jobject()); } local_ref< android::database::sqlite::SQLiteDatabase > android::test::RenamingDelegatingContext::openOrCreateDatabase(local_ref< java::lang::String > const &a0, jint a1, local_ref< android::database::sqlite::SQLiteDatabase_::CursorFactory > const &a2) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(6), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(6), local_ref< android::database::sqlite::SQLiteDatabase > >(get_jobject(), a0, a1, a2); } jboolean android::test::RenamingDelegatingContext::deleteDatabase(local_ref< java::lang::String > const &a0) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(7), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(7), jboolean >(get_jobject(), a0); } local_ref< java::io::File > android::test::RenamingDelegatingContext::getDatabasePath(local_ref< java::lang::String > const &a0) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(8), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(8), local_ref< java::io::File > >(get_jobject(), a0); } local_ref< array< local_ref< java::lang::String >, 1> > android::test::RenamingDelegatingContext::databaseList() { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(9), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(9), local_ref< array< local_ref< java::lang::String >, 1> > >(get_jobject()); } local_ref< java::io::FileInputStream > android::test::RenamingDelegatingContext::openFileInput(local_ref< java::lang::String > const &a0) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(10), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(10), local_ref< java::io::FileInputStream > >(get_jobject(), a0); } local_ref< java::io::FileOutputStream > android::test::RenamingDelegatingContext::openFileOutput(local_ref< java::lang::String > const &a0, jint a1) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(11), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(11), local_ref< java::io::FileOutputStream > >(get_jobject(), a0, a1); } local_ref< java::io::File > android::test::RenamingDelegatingContext::getFileStreamPath(local_ref< java::lang::String > const &a0) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(12), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(12), local_ref< java::io::File > >(get_jobject(), a0); } jboolean android::test::RenamingDelegatingContext::deleteFile(local_ref< java::lang::String > const &a0) { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(13), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(13), jboolean >(get_jobject(), a0); } local_ref< array< local_ref< java::lang::String >, 1> > android::test::RenamingDelegatingContext::fileList() { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(14), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(14), local_ref< array< local_ref< java::lang::String >, 1> > >(get_jobject()); } local_ref< java::io::File > android::test::RenamingDelegatingContext::getCacheDir() { return call_method< android::test::RenamingDelegatingContext::J2CPP_CLASS_NAME, android::test::RenamingDelegatingContext::J2CPP_METHOD_NAME(15), android::test::RenamingDelegatingContext::J2CPP_METHOD_SIGNATURE(15), local_ref< java::io::File > >(get_jobject()); } J2CPP_DEFINE_CLASS(android::test::RenamingDelegatingContext,"android/test/RenamingDelegatingContext") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,0,"<init>","(Landroid/content/Context;Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,1,"<init>","(Landroid/content/Context;Landroid/content/Context;Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,2,"providerWithRenamedContext","(Ljava/lang/Class;Landroid/content/Context;Ljava/lang/String;)Landroid/content/ContentProvider;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,3,"providerWithRenamedContext","(Ljava/lang/Class;Landroid/content/Context;Ljava/lang/String;Z)Landroid/content/ContentProvider;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,4,"makeExistingFilesAndDbsAccessible","()V") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,5,"getDatabasePrefix","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,6,"openOrCreateDatabase","(Ljava/lang/String;ILandroid/database/sqlite/SQLiteDatabase$CursorFactory;)Landroid/database/sqlite/SQLiteDatabase;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,7,"deleteDatabase","(Ljava/lang/String;)Z") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,8,"getDatabasePath","(Ljava/lang/String;)Ljava/io/File;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,9,"databaseList","()[java.lang.String") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,10,"openFileInput","(Ljava/lang/String;)Ljava/io/FileInputStream;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,11,"openFileOutput","(Ljava/lang/String;I)Ljava/io/FileOutputStream;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,12,"getFileStreamPath","(Ljava/lang/String;)Ljava/io/File;") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,13,"deleteFile","(Ljava/lang/String;)Z") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,14,"fileList","()[java.lang.String") J2CPP_DEFINE_METHOD(android::test::RenamingDelegatingContext,15,"getCacheDir","()Ljava/io/File;") } //namespace j2cpp #endif //J2CPP_ANDROID_TEST_RENAMINGDELEGATINGCONTEXT_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
491e75509bbea7708cb542f47d059eecb149fa9a
90d253b075c47054ab1d6bf6206f37e810330068
/USACOcontests/gold/2019.12/cowmbat.cpp
5bb15db82156b472c3f3120b6ed17d2695302c6f
[ "MIT" ]
permissive
eyangch/competitive-programming
45684aa804cbcde1999010332627228ac1ac4ef8
de9bb192c604a3dfbdd4c2757e478e7265516c9c
refs/heads/master
2023-07-10T08:59:25.674500
2023-06-25T09:30:43
2023-06-25T09:30:43
178,763,969
22
8
null
null
null
null
UTF-8
C++
false
false
1,933
cpp
cowmbat.cpp
#include <bits/stdc++.h> #define f first #define s second using namespace std; typedef long long ll; typedef vector<ll> vi; typedef pair<ll, ll> pii; template <typename T1, typename T2> ostream &operator <<(ostream &os, pair<T1, T2> p){os << p.first << " " << p.second; return os;} template <typename T> ostream &operator <<(ostream &os, vector<T> &v){for(T i : v)os << i << ", "; return os;} template <typename T> ostream &operator <<(ostream &os, set<T> s){for(T i : s) os << i << ", "; return os;} template <typename T1, typename T2> ostream &operator <<(ostream &os, map<T1, T2> m){for(pair<T1, T2> i : m) os << i << endl; return os;} ll dp[100000][26]; ll mdp[100000]; ll sum[26]; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); freopen("cowmbat.in", "r", stdin); freopen("cowmbat.out", "w", stdout); ll N, M, K; cin >> N >> M >> K; string Sstr; cin >> Sstr; ll S[N]; for(ll i = 0; i < N; i++){ S[i] = Sstr[i] - 'a'; } ll dist[M][M]; for(ll i = 0; i < M; i++){ for(ll j = 0; j < M; j++){ cin >> dist[i][j]; } } for(ll k = 0; k < M; k++){ for(ll i = 0; i < M; i++){ for(ll j = 0; j < M; j++){ dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); } } } for(ll i = 0; i < M; i++){ for(ll j = 0; j < K; j++){ dp[j][i] = 1e9; sum[i] += dist[S[j]][i]; mdp[j] = 1e9; } } fill(mdp, mdp+N, 1e9); for(ll i = 0; i < M; i++){ dp[K-1][i] = sum[i]; mdp[K-1] = min(dp[K-1][i], mdp[K-1]); } for(ll i = K; i < N; i++){ for(ll j = 0; j < M; j++){ sum[j] += dist[S[i]][j]-dist[S[i-K]][j]; dp[i][j] = min(dp[i-1][j]+dist[S[i]][j], mdp[i-K]+sum[j]); mdp[i] = min(mdp[i], dp[i][j]); } } cout << mdp[N-1] << endl; return 0; }
1786cf6b1b2fa3da400628c6e955dea313ffa2d9
a12df435f92bd09b76f1df112942150363577372
/c/srt.cpp
7d318a78c048eba94378288dbbf9c8364e4bf787
[]
no_license
kars96/code
93edd9ac742bb0592832fba19b20c30c99009348
d9109685de7312395c6da4a2ea1a152d894746e8
refs/heads/master
2021-07-07T23:00:10.252738
2018-11-06T20:34:15
2018-11-06T20:34:15
152,961,109
0
0
null
2020-07-18T19:05:45
2018-10-14T10:06:53
Python
UTF-8
C++
false
false
323
cpp
srt.cpp
#include<stdio.h> #include<algorithm> using namespace std; struct x{ int a; int b; }; bool f(x &q, x &w){ if(q.a < w.a)return 1; return 0; } int main(){ x t[3]; t[0].a=3; t[1].a=9; t[2].a=2; t[0].b=7; t[1].b=3; t[2].b=9; sort(t, t+3, f); for(int i=0; i<3; i++)printf("%d->%d\n",t[i].a, t[i].b ); return 0; }
c6fb9cb851af609611ca8b0f93c5895c1bfb2205
385cb811d346a4d7a285fc087a50aaced1482851
/codeforces/1329/C.cpp
ab68d7278513d1e739da05009ded5e17b2a87804
[]
no_license
NoureldinYosri/competitive-programming
aa19f0479420d8d1b10605536e916f0f568acaec
7739344404bdf4709c69a97f61dc3c0b9deb603c
refs/heads/master
2022-11-22T23:38:12.853482
2022-11-10T20:32:28
2022-11-10T20:32:28
40,174,513
4
1
null
null
null
null
UTF-8
C++
false
false
2,380
cpp
C.cpp
#pragma GCC optimize ("O3") #include <bits/stdc++.h> #define loop(i,n) for(int i = 0;i < (n);i++) #define all(A) A.begin(),A.end() #define pb push_back #define mp make_pair #define sz(A) ((int)A.size()) typedef std::vector<int> vi; typedef std::pair<int,int> pi; typedef std::vector<pi> vp; typedef long long ll; #define popcnt(x) __builtin_popcount(x) #define LSOne(x) ((x) & (-(x))) #define print(A,t) cerr << #A << ": "; copy(all(A),ostream_iterator<t>(cerr," " )); cerr << endl #define prArr(A,n,t) cerr << #A << ": "; copy(A,A + n,ostream_iterator<t>(cerr," " )); cerr << endl #define PRESTDIO() cin.tie(0),cerr.tie(0),ios_base::sync_with_stdio(0) #define what_is(x) cerr << #x << " is " << x << endl #define bit_lg(x) (assert(x > 0),__builtin_ffsll(x) - 1) const double PI = acos(-1); template<class A,class B> std::ostream& operator << (std::ostream& st,const std::pair<A,B> p) { st << "(" << p.first << ", " << p.second << ")"; return st; } using namespace std; const int MAXN = 1 << 23; int A[MAXN]; int siz[MAXN], is_leaf[MAXN], depth[MAXN]; int H, G, n; vi ans; void dfs(int u, int d){ depth[u] = d; is_leaf[u] = d == H; if(!is_leaf[u]) { dfs(2*u, d+1); dfs(2*u+1, d+1); } } int get_val(int u){ if(u > n) return 0; return A[u]; } bool is_safe(int u){ if(u > n) return 1; if(depth[u] > G) return 1; int left = 2*u, right = 2*u + 1; if(get_val(left) == 0 && get_val(right) == 0) return 0; if(get_val(left) > get_val(right)) return is_safe(left); else return is_safe(right); } void f(int u){ if(u > n) return ; int left = 2*u, right = 2*u+1; int vl = get_val(left), vr = get_val(right); if(vl == 0 && vr == 0){ A[u] = 0; return; } if(vl > vr){ A[u] = vl; f(left); } else { A[u] = vr; f(right); } } void work(int u){ if(u > n || depth[u] > G) return; int left = 2*u, right = 2*u + 1; while(is_safe(u)) { ans.pb(u); f(u); } work(left); work(right); } ll get_res(int u){ if(depth[u] > G) return 0; return A[u] + get_res(2*u) + get_res(2*u+1); } ll solve(){ ans.clear(); dfs(1, 1); work(1); return get_res(1); } int main(){ #ifdef HOME freopen("in.in", "r", stdin); #endif int T; scanf("%d", &T); while(T--){ scanf("%d %d", &H, &G); n = (1 << H) - 1; for(int i = 1; i <= n; i++) scanf("%d", A + i); printf("%lld\n", solve()); for(int x : ans) printf("%d ", x); puts(""); } return 0; }
9b062fff4e60187735b1617084bbaff11c7a7769
c2eeeadefeb4aa403e8cc365a6d25f66d018997a
/Source/VehicleBase/WheelFrontBase.h
99b5c6964c1af098b7d62b6ce57f374b1fb62214
[]
no_license
NoCodeBugsFree/VehicleBase
9302cfdf8d93bb83c07f6a0b92dea1bdffb1b1dd
a9f2db8148dc0f542a2290c098a6471ff9612bee
refs/heads/master
2020-03-08T14:29:59.550825
2018-04-05T09:48:49
2018-04-05T09:48:49
128,187,201
1
0
null
null
null
null
UTF-8
C++
false
false
323
h
WheelFrontBase.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "VehicleWheel.h" #include "WheelFrontBase.generated.h" /** * */ UCLASS() class VEHICLEBASE_API UWheelFrontBase : public UVehicleWheel { GENERATED_BODY() public: UWheelFrontBase(); };
316e799c5c4ca6f359a2512fcd1293ef7e9d4e09
e9c01c673999c70e81b4bc316a9069473118e04e
/apps/libmc/graphics/oval.h
48f7883cde732e818a45d9e00a3508dd6d4bf78b
[ "MIT" ]
permissive
djpetti/molecube
c6c1763ddeb61d1fffb07dd8a87b38eb5a933867
b7267803f080ed62e158fc5c1cfcff6beb709de7
refs/heads/master
2020-03-28T06:59:38.403417
2019-02-19T00:15:50
2019-02-19T00:15:50
147,873,653
2
1
MIT
2018-12-23T00:38:39
2018-09-07T20:52:32
C++
UTF-8
C++
false
false
382
h
oval.h
#ifndef LIBMC_GRAPHICS_OVAL_H_ #define LIBMC_GRAPHICS_OVAL_H_ #include "types/graphics_types.h" #include "primitive.h" namespace libmc { namespace graphics { class Oval : Primitive { public: Oval(); virtual ~Oval() = default; protected: virtual void Draw(); virtual BBox GetBBox(); }; } // namespace graphics } // namespace libmc #endif // LIBMC_GRAPHICS_OVAL_H_
f1ba3d604d5e1a75fd5ea89b39b9a16148c93b8c
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/file21875.cpp
62d7ad82f7106958a9777e0dc8114934ab838c1e
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file21875.cpp
#ifndef file21875 #error "macro file21875 must be defined" #endif static const char* file21875String = "file21875";
d6038283c73218d19856742c25f380835f093a0e
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/xdktools/dvdutil/xblayout/CDVD_Insert.cpp
eae518c9261dd9731f6ddc278785ac3d54d4ef2a
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,169
cpp
CDVD_Insert.cpp
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // File: cdvd_insert.cpp // Contents: // Revisions: 6-Jul-2001: Created (jeffsim) // // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++ INCLUDE FILES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // "stdafx.h" -- Precompiled header file #include "stdafx.h" // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++ FUNCTIONS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::InsertObjectList // Purpose: // Arguments: // Return: 'true' if successful, 'false' otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::InsertObjectList(CObjList *pol, int nLayer, CObject *pobjDropAt) { return Insert(m_rgpolLayer[nLayer], pol, pobjDropAt); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::InsertForced // Purpose: // Arguments: // Return: 'true' if successful, 'false' otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::InsertForced(CObjList *ploLayer, CObject *poToInsert, DWORD dwLSN) { // This function is only called during initialization; the LSNs are gauranteed to be in the // proper order, so we can simply just Add the object as we go ploLayer->AddToTail(poToInsert); poToInsert->m_dwLSN = dwLSN; return true; } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::InsertAtEnd // Purpose: // Arguments: // Return: 'true' if successful, 'false' otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::InsertAtEnd(CObject *poToInsert) { // This function is only called during initialization; the LSNs are gauranteed to be in the // proper order, so we can simply just Add the object as we go // First try layer 0, if that fails, try layer 1 if (Insert(m_rgpolLayer[0], poToInsert, NULL)) return true; return Insert(m_rgpolLayer[1], poToInsert, NULL); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::Insert // Purpose: // Arguments: // Return: true if successfully inserted; false otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::Insert(CObject *poToInsert, CObject *poInsertAt) { // First try layer 0, if that fails, try layer 1 return Insert(m_rgpolLayer[0], poToInsert, poInsertAt) || Insert(m_rgpolLayer[1], poToInsert, poInsertAt); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::Insert // Purpose: // Arguments: // Return: true if successfully inserted; false otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::Insert(CObjList *ploLayer, CObject *poToInsert, CObject *poInsertAt) { CObjList ol; // Create a temp list for the main Insert function. ol.AddToTail(poToInsert); return Insert(ploLayer, &ol, poInsertAt); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::Insert // Purpose: // Arguments: // Return: true if successfully inserted; false otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::Insert(CObjList *ploLayer, CObjList *polToInsert, CObject *poInsertAt) { // We do not have to do this in an 'undo-able' fashion since the originator of this insertion // snapshot-ed the workspace before calling in here. If we determine that the insertion // can't be done, then we just return false, and the caller handles restoring the pre-insertion // state. StartProfile(PROFILE_INSERT); ploLayer->m_fModified = true; // Check if caller specified an outside insertion if (poInsertAt == (CObject*)INSERT_OUTSIDEEDGE) { poInsertAt = ploLayer->GetOutside(); } if (poInsertAt == (CObject*)INSERT_INSIDEEDGE) { poInsertAt = ploLayer->GetInside()->m_poOuter; } else if (poInsertAt == NULL) { // If the caller didn't specify an insertion point, then we simply insert it after the // farthest-inside object already in the list. // Start at the inside of the disc and move outward - the first time we hit a non-SEC // object, we've found our insertion point. poInsertAt = ploLayer->GetInside(); // Skip the initial bookend poInsertAt = ploLayer->GetNextOuter(); while (poInsertAt->GetType() == OBJ_SEC || poInsertAt->GetType() == OBJ_VOLDESC) poInsertAt = ploLayer->GetNextOuter(); } else if (poInsertAt->m_pog) { // Tried dropping onto a group. The only time this is allowed is when // it's the first item in the group (in which case, the user was actually // trying to insert before the group poInsertAt = poInsertAt->m_poInner; } CObj_Group *pogInsertion = poInsertAt->m_pog; int nDistMoveIn, nDistMoveOut; DWORD dwEmptySectors; int nLayer = (ploLayer == m_rgpolLayer[0]) ? 0 : 1; // We don't allow inserting into a group if (poInsertAt->m_pog != NULL) { EndProfile(PROFILE_INSERT); return false; } // Add all of the non-placeholder objects "inside of" the insertion point // to the list of objects to insert. Don't add members of groups -- the // group object will be handled as the sum of the contained objects. CObject *poCur = poInsertAt->m_poInner; while (poCur->GetType() != OBJ_BE) { CObject *poNext = poCur->m_poInner; if (poCur->GetType() != OBJ_SEC && poCur->GetType() != OBJ_VOLDESC) { ploLayer->Remove(poCur); if (poCur->m_pog == NULL) polToInsert->AddToHead(poCur); } poCur = poNext; } // NOTE: In all of this code, an object 'inside' of another object means closer to the inside // of the DVD. When refering to 'inside a group', it will be explicitly stated. // Iterate over each object in the array of objects to insert CObject *poToInsert = polToInsert->GetOutside(); while (poToInsert) { CObject *poInner = poInsertAt->m_poInner; // If the object is a member of a group, then ignore it and let the // group handle it atomically. When the group itself is added, its // contained objects will be added at that point. while (poToInsert->m_pog) { poToInsert = polToInsert->GetNextInner(); } // Move the insertion point inward until it's pointing at empty space while (true) { // Calculate how many empty sectors are between the current insertion point // and the object immediately inside of it (ie closer to the inside of the dvd). if (ploLayer->IsInsideOut()) dwEmptySectors = poInner->m_dwLSN - (poInsertAt->m_dwLSN + poInsertAt->m_dwBlockSize); else dwEmptySectors = poInsertAt->m_dwLSN - (poInner->m_dwLSN + poInner->m_dwBlockSize); if (dwEmptySectors > 0) break; poInsertAt = poInsertAt->m_poInner; poInner = poInsertAt->m_poInner; if (poInsertAt->GetType() == OBJ_BE) { // Hit the end of the list (inside of dvd) - no more room!. EndProfile(PROFILE_INSERT); return false; } } // At this point, m_poInsertAt points at a block of empty space. Is it *enough* empty // space to hold the to-insert object? if (poToInsert->m_dwBlockSize <= dwEmptySectors) { // There's enough space here. Place the object at the current insertion point. polToInsert->Remove(poToInsert); ploLayer->InsertInside(poToInsert, poInsertAt); if (nLayer == 0) poToInsert->m_dwLSN = poInsertAt->m_dwLSN - poToInsert->m_dwBlockSize; else poToInsert->m_dwLSN = poInsertAt->m_dwLSN + poInsertAt->m_dwBlockSize; // Continue with the next object in the 'to insert' list. poInsertAt = poToInsert; goto next; } // If the object inside of the current object is a bookend, then there's not enough // space for the object! if (poInner->GetType() == OBJ_BE) { // Hit the end of the list. No need to undo anything. The caller // will handle trying to insert on a different layer (or the scratch // window) or warn the user as appropriate EndProfile(PROFILE_INSERT); return false; } // Check if there's enough empty space combined between the empty space above poInsertAt // and the empty space (if any) between the placeholder above that and the next placeholder. // If not, then we can't fit it here, so move on to the next placeholder and try again. if (ploLayer->IsInsideOut()) dwEmptySectors += poInner->m_poInner->m_dwLSN - (poInner->m_dwLSN + poInner->m_dwBlockSize); else dwEmptySectors += poInner->m_dwLSN - (poInner->m_poInner->m_dwLSN + poInner->m_poInner->m_dwBlockSize); if (dwEmptySectors < poToInsert->m_dwBlockSize) { // Not enough empty space. poInsertAt = poInner; // *don't* get the next 'to insert' object; repeat the loop with the same one. continue; } // Can't move voldesc, and we're not allowing anything above it. Thus, // if at this point the 'inner' object is a volume descriptor, then we // can't insert the next object. if (poInner->GetType() == OBJ_VOLDESC) { EndProfile(PROFILE_INSERT); return false; } // Can the security placeholder above the empty space at the current insertion point move // down to the insertion point (ie is that a valid location?). The placeholder itself // is passed as well since we need to 'remove' it from the list of placeholders when checking // for validity. if (CheckValidPlaceholderLSN((CObj_Security*)poInner, poInsertAt->m_dwLSN - poInner->m_dwBlockSize)) nDistMoveOut = abs(poInsertAt->m_dwLSN - (poInner->m_dwLSN + poInner->m_dwBlockSize)); else nDistMoveOut = INT_MAX; // Can the security placeholder be moved up? Two checks: (1) there are no other placeholders // blocking this placeholder from moving up enough, (2) the position is a valid placeholder // position. if (!CheckValidPlaceholderLSN((CObj_Security*)poInner, poInsertAt->m_dwLSN - poToInsert->m_dwBlockSize - poInner->m_dwBlockSize)) nDistMoveIn = INT_MAX; else nDistMoveIn = abs(poInner->m_dwLSN - (poInsertAt->m_dwLSN - poToInsert->m_dwBlockSize - poInner->m_dwBlockSize)); // Move the placeholder the minimum valid distance possible if (nDistMoveOut == nDistMoveIn && nDistMoveOut == INT_MAX) { // Can't insert the object at the current position. Move the current insertion pointer // to before the placeholder and try again poInsertAt = poInner; continue; } else if (nDistMoveOut < nDistMoveIn) { // insert the object before the placeholder polToInsert->Remove(poToInsert); ploLayer->InsertInside(poToInsert, poInner); // Set the placeholder's and object's LSNs if (nLayer == 0) { poInner->m_dwLSN = poInsertAt->m_dwLSN - poInner->m_dwBlockSize; poToInsert->m_dwLSN = poInner->m_dwLSN - poToInsert->m_dwBlockSize; } else { poInner->m_dwLSN = poInsertAt->m_dwLSN + poInsertAt->m_dwBlockSize; poToInsert->m_dwLSN = poInner->m_dwLSN + poInner->m_dwBlockSize; } // Set current insertion point to before the inserted object poInsertAt = poToInsert; } else { // Move the placeholder inward // Insert the object at the current insertion point polToInsert->Remove(poToInsert); ploLayer->InsertInside(poToInsert, poInsertAt); // Set the placeholder's and object's LSNs if (nLayer == 0) { poInner->m_dwLSN = poInsertAt->m_dwLSN - poToInsert->m_dwBlockSize - poInner->m_dwBlockSize; poToInsert->m_dwLSN = poInsertAt->m_dwLSN - poToInsert->m_dwBlockSize; } else { poInner->m_dwLSN = poInsertAt->m_dwLSN + poInsertAt->m_dwBlockSize + poToInsert->m_dwBlockSize + poInner->m_dwBlockSize; poToInsert->m_dwLSN = poInsertAt->m_dwLSN - poInsertAt->m_dwBlockSize; } // Set current insertion point to before the security placeholder poInsertAt = poInner; } next: // If the newly placed object is a group object, then we need to add all of it's contained // objects immediately after the object itself (or before if on layer 1). if (poToInsert->GetType() == OBJ_GROUP) { // We just inserted a group -- we need to also insert all of it's // contained objects DWORD dwPrevLSN = poToInsert->m_dwLSN; CObject *poPrevContained = poToInsert; CObject *poContained; if (ploLayer->IsInsideOut()) poContained = ((CObj_Group*)poToInsert)->m_gol.Tail(); else poContained = ((CObj_Group*)poToInsert)->m_gol.Head(); while (poContained) { poContained->RemoveFromList(); poContained->m_dwLSN = dwPrevLSN; ploLayer->InsertOutside(poContained, poPrevContained); dwPrevLSN += poContained->m_dwBlockSize; if (ploLayer->IsInsideOut()) { poContained = ((CObj_Group*)poToInsert)->m_gol.Prev(); // poPrevContained->m_dwLSN = dwPrevLSN; } else { poPrevContained = poContained; poContained = ((CObj_Group*)poToInsert)->m_gol.Next(); } } } // Get the 'outside'-most object from the to-insert list. poToInsert = polToInsert->GetOutside(); } ValidatePlaceholders(); EndProfile(PROFILE_INSERT); return true; } #define VALIDLSN_LAYER0_FIRST 89856 #define VALIDLSN_LAYER0_LAST 1646000 #define VALIDLSN_LAYER1_FIRST 1781168 #define VALIDLSN_LAYER1_LAST 3337312 #define NUM_SECTORS 1715632 bool CheckPHError(bool fWarnUser, bool fValid) { if (fValid) return false; if (fWarnUser) MessageBox(NULL, "A placeholder was found in an invalid position. Please notify Microsoft Xbox tech support immediately.", "Invalid placeholder encountered", MB_ICONEXCLAMATION | MB_OK); return true; } bool CDVD::ValidatePlaceholders(bool fWarnUser) { CObjNode *ponTemp, *ponCur = m_onlPH.m_ponHead; assert(ponCur); while (ponCur) { // verify this guy has the correct updated size hack fix if(ponCur->m_pobj->m_dwBlockSize != 4098) return false; // verify previous same-layer item before is > 132kb away ponTemp = ponCur->m_ponPrev; while (ponTemp && ponTemp->m_pobj->m_dwLSN / NUM_SECTORS != ponCur->m_pobj->m_dwLSN / NUM_SECTORS) ponTemp = ponTemp->m_ponPrev; if (ponTemp) if (CheckPHError(fWarnUser, ponCur->m_pobj->m_dwLSN - ponTemp->m_pobj->m_dwLSN > 0x21002)) return false; // verify next same-layer item is > 132kb away ponTemp = ponCur->m_ponNext; while (ponTemp && ponTemp->m_pobj->m_dwLSN / NUM_SECTORS != ponCur->m_pobj->m_dwLSN / NUM_SECTORS) ponTemp = ponTemp->m_ponNext; if (ponTemp) if (CheckPHError(fWarnUser, ponTemp->m_pobj->m_dwLSN - ponCur->m_pobj->m_dwLSN > 0x21002)) return false; // verify previous diff-layer item is > 64kb away ponTemp = ponCur->m_ponPrev; while (ponTemp && ponTemp->m_pobj->m_dwLSN / NUM_SECTORS == ponCur->m_pobj->m_dwLSN / NUM_SECTORS) ponTemp = ponTemp->m_ponPrev; if (ponTemp) { DWORD dwLSNTemp = 2 * 1715632 - ponTemp->m_pobj->m_dwLSN - 0x1002; if (CheckPHError(fWarnUser, ponCur->m_pobj->m_dwLSN - dwLSNTemp > 0x11002)) return false; } // verify next diff-layer item is > 64kb away ponTemp = ponCur->m_ponNext; while (ponTemp && ponTemp->m_pobj->m_dwLSN / NUM_SECTORS == ponCur->m_pobj->m_dwLSN / NUM_SECTORS) ponTemp = ponTemp->m_ponNext; if (ponTemp) { DWORD dwLSNTemp = 2 * 1715632 - ponTemp->m_pobj->m_dwLSN - 0x1002; if (CheckPHError(fWarnUser, dwLSNTemp - ponCur->m_pobj->m_dwLSN > 0x11002)) return false; } ponCur = ponCur->m_ponNext; } return true; } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::CheckValidPlaceholderLSN // Purpose: Check if the specified placeholder can legally be placed at the // specified LSN // Arguments: // Return: 'true' if successful, 'false' otherwise // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ bool CDVD::CheckValidPlaceholderLSN(CObj_Security *posPH, DWORD dwLSN) { // There are a number of rules that must be obeyed in order for an LSN to // be valid for placeholder placement: // 1. The first possible layer 0 LSN start is 89856 // 2. The last possible layer 0 LSN start is 1646000 // 3. The first possible layer 1 LSN start is 1781168 // 4. The last possible layer 1 LSN start is 3337312 // 5. The end of a Placeholder cannot be any closer than 131072 sectors // from the start of the next placeholder on the same layer. // 6. Placeholders on different layers must be separated by a minimum of // 65536 sectors from the one's complement of each placeholder's // starting and ending addresses. StartProfile(PROFILE_CHECKVALIDPLACEHOLDERLSN); bool fValid = false; CObjNode *ponPH, *ponBase, *ponCur; CObject *poCur; DWORD dwLSNThis; poCur = m_onlPH.Head(); if (!poCur) { EndProfile(PROFILE_CHECKVALIDPLACEHOLDERLSN); return false; } do { DebugOutput("%d (%d)\r\n", poCur->m_dwLSN, poCur->m_dwLSN >= 1715632 ? 1715632*2-poCur->m_dwLSN : 0); } while (poCur = m_onlPH.Next()); // Verify that the LSN is within the valid ranges (rules 1-4 above) if (dwLSN < VALIDLSN_LAYER0_FIRST || dwLSN > VALIDLSN_LAYER1_LAST || (dwLSN > VALIDLSN_LAYER0_LAST && dwLSN < VALIDLSN_LAYER1_FIRST)) { EndProfile(PROFILE_CHECKVALIDPLACEHOLDERLSN); return false; } // Pointers to the placeholders are stored in sorted LSN order (relative // to start of layer!). Find the specified placeholder and remove it from // the list in preparation for checking rules 5 and 6. ponPH = m_onlPH.GetObjectNode(posPH); assert(ponPH); // Track which element the removed placeholder was following in case we // need to reinsert ponBase = ponPH->m_ponPrev; // Remove the placeholder from the placeholders list m_onlPH.Remove(posPH); // Now that the placeholder has been removed, find the new point at which // the placeholder will be inserted (ie where dwLSN fits in). DWORD dwLSN1 = (dwLSN > 1715632) ? 1715632*2 - dwLSN : dwLSN; ponCur = m_onlPH.m_ponHead; while (ponCur) { DWORD dwLSN2 = (ponCur->m_pobj->m_dwLSN > 1715632) ? 1715632 * 2 - ponCur->m_pobj->m_dwLSN : ponCur->m_pobj->m_dwLSN; if (dwLSN2 > dwLSN1) break; ponCur = ponCur->m_ponNext; } // At this point, ponCur points at the placeholder node with the next highest // LSN. posPH will fit in before it (if valid). If ponCur is NULL, it means // that posPH has the highest (layer-relative) LSN. // Find the previous and next placeholders on both the same and opposite layer. CObjNode *ponPrevSame = ponCur, *ponPrevDiff = ponCur, *ponNextSame = ponCur, *ponNextDiff = ponCur; if (!ponCur) { ponPrevSame = ponPrevDiff = m_onlPH.m_ponTail; ponNextSame = ponNextDiff = NULL; } else { bool fFoundPrevSame = false, fFoundPrevDiff = false, fFoundNextSame = false, fFoundNextDiff = false; do { if (!fFoundPrevSame) { ponPrevSame = ponPrevSame->m_ponPrev; if (!ponPrevSame || ponPrevSame->m_pobj->m_dwLSN/NUM_SECTORS == dwLSN/NUM_SECTORS) fFoundPrevSame = true; } if (!fFoundPrevDiff) { ponPrevDiff = ponPrevDiff->m_ponPrev; if (!ponPrevDiff || ponPrevDiff->m_pobj->m_dwLSN/NUM_SECTORS != dwLSN/NUM_SECTORS) fFoundPrevDiff = true; } if (!fFoundNextSame) { if (!ponNextSame || ponNextSame->m_pobj->m_dwLSN/NUM_SECTORS == dwLSN/NUM_SECTORS) fFoundNextSame = true; else ponNextSame = ponNextSame->m_ponNext; } if (!fFoundNextDiff) { if (!ponNextDiff || ponNextDiff->m_pobj->m_dwLSN/NUM_SECTORS != dwLSN/NUM_SECTORS) fFoundNextDiff = true; else ponNextDiff = ponNextDiff->m_ponNext; } } while(!(fFoundPrevSame && fFoundPrevDiff && fFoundNextSame && fFoundNextDiff)); } // Check rule 5: same-layer placeholders must be 131072 or more sectors apart if (ponNextSame) if ((int)(ponNextSame->m_pobj->m_dwLSN - (dwLSN + ponCur->m_pobj->m_dwBlockSize)) < 131072) goto done; if (ponPrevSame) if ((int)(dwLSN - (ponPrevSame->m_pobj->m_dwLSN + ponPrevSame->m_pobj->m_dwBlockSize)) < 131072) goto done; // Check rule 6. Placeholders on different layers must be separated by a // minimum of 65536 sectors from the one's complement of // each placeholder's starting and ending addresses. // Convert the to-be-inserted PH's LSN to the other PH's numeric space dwLSNThis = 2 * 1715632 - dwLSN - 0x1002; if (ponNextDiff && abs(dwLSNThis - ponNextDiff->m_pobj->m_dwLSN) < 0x11002) goto done; if (ponPrevDiff && abs(dwLSNThis - ponPrevDiff->m_pobj->m_dwLSN) < 0x11002) goto done; // If here, then we passed all rules! fValid = true; done: if (fValid) { // Insert at insertion point if (ponCur) m_onlPH.AddBefore(posPH, ponCur->m_pobj); else m_onlPH.Add(posPH); } else { // restore original point if (!ponBase) { ponBase = m_onlPH.m_ponHead; m_onlPH.AddBefore(posPH, ponBase->m_pobj); } else m_onlPH.AddAfter(posPH, ponBase->m_pobj); } ValidatePlaceholders(); EndProfile(PROFILE_CHECKVALIDPLACEHOLDERLSN); return fValid; } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Function: CDVD::RefreshPlaceholders // Purpose: // Arguments: None // Return: None // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void CDVD::RefreshPlaceholders(bool fValidate) { // refresh the placeholder list. This must be called after open, new, or // undo/redo operations (ie any time a placeholder could have been moved) DWORD dwLSNCur, dwLSNCur2; StartProfile(PROFILE_REFRESHPLACEHOLDERS); m_onlPH.RemoveAll(); // find all placeholders, add them to the list of placeholders in sorted // lsn order (relative to start of layer) for (int i = 0; i <= 1; i++) { CObjList *polLayer = m_rgpolLayer[i]; CObject *poCur = polLayer->GetInside(); while (poCur) { // If the object is a file-system object (folder or file), check // to see if it resides in the passed-in folder. if (poCur->GetType() == OBJ_SEC) { dwLSNCur = (poCur->m_dwLSN > 1715632) ? 1715632*2-poCur->m_dwLSN : poCur->m_dwLSN; // Find insertion point CObjNode *ponCur = m_onlPH.m_ponHead; while (ponCur) { dwLSNCur2 = (ponCur->m_pobj->m_dwLSN > 1715632) ? 1715632*2-ponCur->m_pobj->m_dwLSN : ponCur->m_pobj->m_dwLSN; if (dwLSNCur2 > dwLSNCur) break; ponCur = ponCur->m_ponNext; } if (ponCur) m_onlPH.AddBefore(poCur, ponCur->m_pobj); else m_onlPH.Add(poCur); } poCur = polLayer->GetNextOuter(); } } if (fValidate) ValidatePlaceholders(); #ifdef _DEBUG1 m_onlPH.Head(); m_onlPH.Next(); CheckValidPlaceholderLSN((CObj_Security*)m_onlPH.Next(), 48000+4100+131072); #endif EndProfile(PROFILE_REFRESHPLACEHOLDERS); }
15dd625ba535d6345a91e0bf47605f552f54ca63
68b89fc25effe9d4059968ca026151516fce50a9
/Wind/Component.cpp
0d59389674627a0c2cb272158aae4eac0e854c82
[]
no_license
lim-james/Wind
43ad73c24954196542d47bd82e5f9e202e02fdaf
7877959b5fdce2778c1d6c2e5e14082ece46be9e
refs/heads/master
2020-08-28T16:23:04.698101
2019-12-08T17:37:53
2019-12-08T17:37:53
217,752,231
0
0
null
null
null
null
UTF-8
C++
false
false
760
cpp
Component.cpp
#include "Component.h" #include <Events/EventsManager.h> Component::Component() : parent(nullptr) , active(false) { } Component::~Component() { } void Component::Initialize() { active = false; } void Component::SetActive(const bool& state) { active = state; } const bool& Component::IsActive() const { return active; } void Component::SetParent(Entity* const entity) { if (parent == entity) return; parent = entity; if (entity) { Events::EventsManager::GetInstance()->Trigger("COMPONENT_ATTACHED", new Events::AnyType<Component*>(this)); } else { SetActive(false); Events::EventsManager::GetInstance()->Trigger("COMPONENT_DETACHED", new Events::AnyType<Component*>(this)); } } Entity* const Component::GetParent() { return parent; }
a0f583a6badf9d4ee9118a4972a16cfcb353651e
94ed2113af11ba8b716fb959c5ac0a32c5549c18
/lib/pyre/version.h
954568d9e4a1e19cd8b3558da3062c8c10f5faba
[ "BSD-3-Clause" ]
permissive
avalentino/pyre
85ba21388514dc8c206d5136760e23b39aba1cae
7e1f0287eb7eba1c6d1ef385e5160079283ac363
refs/heads/main
2023-03-23T04:58:02.903369
2021-03-09T17:37:11
2021-03-09T17:37:11
347,723,195
0
0
NOASSERTION
2021-03-14T18:43:34
2021-03-14T18:43:33
null
UTF-8
C++
false
false
509
h
version.h
// -*- C++ -*- // -*- coding: utf-8 -*- // // michael a.g. aïvázis // orthologue // (c) 1998-2021 all rights reserved // code guard #if !defined(pyre_version_h) #define pyre_version_h // support #include <tuple> #include <string> // my declarations namespace pyre { // my version is an array of three integers and the git hash using version_t = std::tuple<int, int, int, std::string>; // access to the version number of the {pyre} library version_t version(); } #endif // end of file
8f28dd489dd7c9d2906fb3453f5fd757372a6e27
89b86517ee247855b7888fa637424fb1d8ac309e
/Arduino/DistanceReminder/DistanceReminder.ino
0bd985b135584b3740256f36578919862ae6c8e2
[]
no_license
billpugh/Pyramid-of-Possibilities
31464942a5434e79f136c6b8e0d9e6974ba69114
7ba3bd71e82f6bc8bde682483e44b0bcdb820382
refs/heads/master
2020-04-07T05:38:23.637848
2016-11-28T00:16:12
2016-11-28T00:16:12
16,173,729
1
1
null
2014-08-18T14:09:34
2014-01-23T13:52:34
C
UTF-8
C++
false
false
4,355
ino
DistanceReminder.ino
#include <Adafruit_NeoPixel.h> #include <Audio.h> #include <TimeLib.h> const int sensorPin = 16; // select the input pin for sensor const int sensorVpp = 15; const int sensorGnd = 14; const int touchPin = 17; const int touchPin2 = 18; const int ledPin = 13; // on board LED const int audioEnablePin = 8; const int neopixelPin = 12; const int numPixels = 1; AudioSynthWaveformSine sine1; //xy=132,263 AudioEffectEnvelope envelope1; //xy=264,199 AudioConnection patchCord1(sine1, envelope1); AudioOutputAnalog dac1; //xy=488,208 AudioConnection patchCord2(envelope1, dac1); Adafruit_NeoPixel pixels = Adafruit_NeoPixel(numPixels, neopixelPin, NEO_GRB + NEO_KHZ800); unsigned long lastBeep = 0; boolean beepOn = false; void setup() { setSyncProvider(getTeensy3Time); Serial.begin(9600); delay(100); Serial.println("Hello world"); if (timeStatus()!= timeSet) { Serial.println("Unable to sync with the RTC"); } else { Serial.println("RTC has set the system time"); } AudioMemory(10); sine1.amplitude(1); sine1.frequency(640); envelope1.sustain(0.8); pinMode(sensorGnd, OUTPUT); digitalWrite(sensorGnd, LOW); pinMode(sensorVpp, OUTPUT); digitalWrite(sensorVpp, HIGH); pinMode(audioEnablePin, OUTPUT); digitalWrite(audioEnablePin, HIGH); Serial.println("Audio initialized"); // declare the ledPin as an OUTPUT: pinMode(ledPin, OUTPUT); pixels.begin(); pixels.setPixelColor(0, 0, 255, 0); pixels.show(); Serial.println("GREEN"); delay(250); pixels.setPixelColor(0, 0, 0, 0); pixels.show(); Serial.println("LEDs initialized"); digitalClockDisplay(); } int smoothedSensorData = 30; int skipped = 0; void loop() { // read the value from the sensor: pixels.setPixelColor(0, 0, 0, 0); int sensorValue = analogRead(sensorPin); int touchValue = touchRead(touchPin); if (true) { if (sensorValue > 10 && sensorValue < 130) { digitalWrite(ledPin, HIGH); skipped = 0; if (sensorValue < smoothedSensorData) smoothedSensorData = (2 * smoothedSensorData + sensorValue + 2) / 3; else smoothedSensorData = (12 * smoothedSensorData + sensorValue + 4) / 13; // Serial.print(" "); // Serial.print(smoothedSensorData); } else { digitalWrite(ledPin, LOW); skipped++; if (skipped > 10) smoothedSensorData = 50; } // Serial.println(); const int good = 40; const int veryBad = 70; // < 55 -- good // 55 .. 60 -- marginal // 80+ bad int score = 0; // score 0 = green // score 100 = very bad if (skipped <= 5) { int r = 0; int g = 0; if (smoothedSensorData <= good) { score = 0; g = 255; } else if (smoothedSensorData >= veryBad) { r = 255; score = 100; } else { score = ((smoothedSensorData - good) * 100 / (veryBad - good)); r = 255 * score / 100; g = 255 - r; } digitalClockDisplay(); Serial.print(smoothedSensorData); Serial.print(" "); Serial.print(r); Serial.print(" "); Serial.println(g); for (int i = 0; i < numPixels; i++) pixels.setPixelColor(i, r, g, 0); } pixels.show(); unsigned long now = millis(); const unsigned long duration = 200; if (beepOn) { if (lastBeep + duration < now) { beepOn = false; envelope1.noteOff(); } } else if (score > 0 ) { int delay = 500 + 100000 / (score + 20); if (lastBeep + delay < now) { lastBeep = now; beepOn = true; envelope1.noteOn(); Serial.println("beep"); } } // Serial.println(); } delay(20); } time_t getTeensy3Time() { return Teensy3Clock.get(); } void printDigits(int digits){ // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits < 10) Serial.print('0'); Serial.print(digits); } void digitalClockDisplay() { // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); }
590a10325256854409f248a00af7bd46debc88da
60dbb8d07b04e581264e7686caa785710458479c
/PongOut_Server/PongOut_Server/Map.cpp
b8745d9efcbff2ad18ca5fa9223a5ff8dc881b8b
[]
no_license
Jereq/PongOut
15f4cf662a3d27ce8b381e0c75bcb7adaaa95505
46b8b9af38aa89aaa0be037fc2cd93809e692c09
refs/heads/master
2016-09-06T05:32:02.906945
2013-10-28T10:26:17
2013-10-28T10:26:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
Map.cpp
#include "stdafx.h" #include "Map.h" Map::Map(void) { } Map::~Map(void) { } void Map::setMapData( const CommonTypes::Block& _block ) { blockList.push_back(_block); }
664bccbbfedfb9e3c2fb09b6cd4279ffc228e813
0ecfb91c69bd1b6602c3106a5369fba6f5f324c8
/Nomoku/ANN.cpp
9180ca65207277221f907dde53458ec10b042490
[]
no_license
liu1084455812/Nomoku_Lhy
b32a59df61603025ad0f63a6cbe03319d9bcefbd
882664ddd45bdcd4b965db5889f742e42c86df07
refs/heads/master
2021-01-23T12:58:12.356514
2017-06-03T01:23:41
2017-06-03T01:23:41
93,215,184
0
0
null
null
null
null
GB18030
C++
false
false
5,310
cpp
ANN.cpp
// // ANN.cpp // Nomoku // // 输入层(width*height)个神经元 // 中间层1/2*(width*height)个神经元 // 输出层1个神经元 //一共3/2(width*height)+1个神经元 // 一共(1 / 2)*width*height*width*height+(1 / 2)*width*height个权值 // itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似: // // char str[255]; // sprintf(str, "%x", 100); //将100转为16进制表示的字符串 // // #include "ANN.h" #include "pisqpipe.h" #include "AI_Wrapper.h" #include <fstream> #include <cstring> #include <ctime> #include <cstdlib> int temp_board[MAX_BOARD][MAX_BOARD]; //全局变量棋盘状态 int mutex_ans = 0; //0:未使用,1:正在被占用 int semaphore_weight = 0; //表示是否有可用神经网络0:表示没有,1表示有 int ans = 0; //0:没有结果,1:胜,-1输。 char file_path[1000] = "E:/"; //文件路径,默认E盘 int input_number = width*height; //输入层神经元个数 int mid_number = (1.0 / 2)*width*height; //中间层神经元个数 int output_number = 1; //输出层神经元个数 int weight_number = input_number*mid_number + mid_number*output_number;//所有权值个数 输入*中间+中间*输出 int neure_number = input_number + mid_number + output_number;//所有神经元个数 输入+中间+输出 int winp_denominator = 10; //胜率的分母 int *neure = new int[neure_number]; //神经元序列 short *weight = new short[weight_number]; //权值序列 int get_result(){ int temp = 0; for (;;){ if (mutex_ans == 0){ mutex_ans = 1; if (ans == 0); else if (ans == 1)temp = ans; else if (ans == -1) temp = ans; mutex_ans = 0; } if (temp != 0) break; } return temp; }; void init_ANN_N(int(*board)[MAX_BOARD], int *neure){//初始化神经元 for (int i = 0; i < width; i++){ for (int j = 0; j < height; j++){ neure[i*height + j] = board[i][j]; } } memset(&(neure[width*height]), 0, sizeof(int)*(mid_number + output_number)); } void init_ANN_W(short *weight){//初始化神经网权值 srand((unsigned)time(NULL)); for (int i = 0; i < weight_number; i++){ weight[i] = rand() % 0xffff; } } //神将网络分配内存交给GA搜素算法部分 void init_ANN(int *neure, short *weight){//初始化ANN网络获得随机权值,输入神经元赋值,中间及输出神经元置0 //初始化前input_number个神经元值为棋盘状态 init_ANN_N(temp_board, neure); init_ANN_W(weight); } int Update_ANN(int *neure, short *weight){//根据权值更新中间,输出神经元值 //整合函数=加权求和g(x)=sum(wi*ai) //激活函数=线性函数f(x)=x for (int i = 0; i < mid_number; i++){//计算中间层神经元值 //neure[input_number+i]=sum(wi*ai) for (int j = 0; j < input_number; j++){ //每一个输入神经元J*乘上到中间神经元I的权重 neure[input_number + i] += neure[j] * weight[j*mid_number + i]; } } for (int i = 0; i <= mid_number; i++){//计算输出层神经元值 //nneure[input_number+mid_number] =sum(wi*ai) neure[input_number + mid_number] += neure[input_number + i] * weight[input_number*mid_number + i]; } return neure[input_number + mid_number]; } // double winrateCalc(std::vector<short> *nowWeight){//用来返回胜率 semaphore_weight = 1; for (int i = 0; i < weight_number; i++){ weight[i] = (*nowWeight)[i]; } //计算一局的函数 int counts; int win_times = 0; for (counts = 0; counts < winp_denominator; counts++){ if (get_result() == 1){ win_times++; } } semaphore_weight = 0; return (win_times*1.0) / counts; } int outputevaluation(){//给AB剪枝用来返回评价值 for (int i = 0; i < width; i++){ for (int j = 0; j < height; j++){ temp_board[i][j] = bc->board[i][j]; } } init_ANN_N(temp_board, neure); return Update_ANN(neure, weight); } void FOutANN(std::vector<short> *nowWeight){//神将网络权值输出到width_height.txt中 for (int i = 0; i < weight_number; i++){ weight[i] = (*nowWeight)[i]; } //计算一局的函数 char swidth[10], sheight[10]; char underline[2] = "_"; char filename[20]; sprintf(swidth, "%d", width); sprintf(sheight, "%d", height); strcpy(filename, file_path); strcat(filename, swidth); strcat(filename, "_"); strcat(filename, sheight); strcat(filename, ".txt"); std::ofstream file; file.open(filename); for (int i = 0; i < weight_number; i++){ file << weight[i] << '\n'; } file.close(); } void FINANN(std::vector<short> *nowWeight){//神将网络权值从width_height.txt输入 char swidth[10], sheight[10]; char underline[2] = "_"; char filename[20]; sprintf(swidth, "%d", width); sprintf(sheight, "%d", height); strcpy(filename, file_path); strcat(filename, swidth); strcat(filename, "_"); strcat(filename, sheight); strcat(filename, ".txt"); std::ifstream file; file.open(filename); if (file.is_open() == 0){ init_ANN_W(weight); for (int i = 0; i < weight_number; i++){ (*nowWeight)[i] = weight[i]; } } else { for (int i = 0; i < weight_number; i++){ file >> weight[i]; (*nowWeight)[i] = weight[i]; } } file.close(); //计算一局的函数 }
f3a980434b1209139ed3b4b7cb1da00e1da89440
6bc596e1e1635c025a012d2304211e62d413fc23
/Factory_Pattern/include/Pizza.h
e7e2d9ac8f64ca267ca095f9eb8e4fb3982fd32e
[]
no_license
umtkrl1993/CPP_Pattern_Implementation
3426da0b4a9b85054079fa6da8516c39167f50f5
b1d37a64270c14d2224def890faffbc43ebd56fa
refs/heads/master
2020-06-09T23:06:24.419475
2016-12-11T21:49:56
2016-12-11T21:49:56
76,131,901
0
0
null
null
null
null
UTF-8
C++
false
false
159
h
Pizza.h
#ifndef PIZZA_H #define PIZZA_H class Pizza{ public: virtual void prepare() = 0; virtual void bake() = 0; virtual void cut() = 0; }; #endif
2067381e2f44d0cf63861b1b80bd1a11cb95e384
2b93f887bdc61bbc5f7da771681659f72d2acc4f
/reader_common/.svn/pristine/20/2067381e2f44d0cf63861b1b80bd1a11cb95e384.svn-base
bc523bc6eff3df65a94e4dbed4ba0b8479885bb4
[]
no_license
PengWEI9/Vix
a0796ff0d5e8ce962efa60b4bd22eaba03ac6017
c6dd23d2ffc36d82221a8d920862c435683f1c24
refs/heads/master
2021-01-10T16:01:18.530308
2016-01-25T03:42:00
2016-01-25T03:42:00
49,394,563
3
0
null
null
null
null
UTF-8
C++
false
false
2,011
2067381e2f44d0cf63861b1b80bd1a11cb95e384.svn-base
/* Copyright (c) 2011. All rights reserved. ERG Transit Systems (HK) Ltd. ** ** cmd.cpp - general io commands ** ** Version Date Name Reason ** 1.0 12/12/11 Gerry Created ** */ #include <locale.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <cmd.h> static char *fifo_name() { static char buffer[40]; uid_t uid; uid = getuid(); sprintf(buffer, "/tmp/cmdfifo.%d", uid); return buffer; } char *make_fifo() { struct stat buf; int res; char *buffer = fifo_name(); res = stat(buffer, &buf); if (res < 0 && errno == ENOENT) { printf("creating fifo %s\n", buffer); mkfifo(buffer, S_IRUSR|S_IWUSR); } return buffer; } void write_cmd(int type, char *data, int len) { static int fh = -1; cmd_t cmd; if (fh == -1) { fh = open(make_fifo(), O_WRONLY); if (fh < 0) { printf("fifo creation/open failed\n"); return; } } memset(&cmd, 0, sizeof(cmd_t)); cmd.magic1 = MAGIC1; cmd.magic2 = MAGIC2; cmd.type = type; len = (len > CMD_LEN) ? CMD_LEN : len; cmd.length = len; memcpy(cmd.buffer, data, len); write(fh, &cmd, sizeof(cmd_t)); fdatasync(fh); } int read_cmd(cmd_t *cmd) { static int fh = -1; int res; // int magic1, magic2; if (fh == -1) { fh = open(make_fifo(), O_RDONLY); if (fh < 0) { printf("fifo %s doesn't exist yet\n", fifo_name()); return -1; } } res = read(fh, cmd, sizeof(cmd_t)); if (res == sizeof(cmd_t)) { /* read the right amount display it */ if (cmd->magic1 != MAGIC1 || cmd->magic2 != MAGIC2) { printf("ignored garbage\n"); } else { // got a structure return 1; } } return 0; } /* end of file */
259acd235a3638c28845f989e870193d812ac171
671f14d80b90156df474b7623f118bb0b4f5bba4
/src/lib/drishti/sensor/Sensor.h
7732373d88202e64b7317d80c1a1bdd14404a538
[ "BSD-3-Clause" ]
permissive
ZJCRT/drishti
fde64c05b424e054a98f2bcb4faaaa03cf952b0c
7c0da7e71cd4cff838b0b8ef195855cb68951839
refs/heads/master
2020-10-01T18:04:29.446614
2019-12-13T09:29:57
2019-12-13T09:29:57
227,594,066
0
0
BSD-3-Clause
2019-12-12T11:46:56
2019-12-12T11:46:55
null
UTF-8
C++
false
false
2,646
h
Sensor.h
/*! -*-c++-*- @file Sensor.h @author David Hirvonen @brief Implementation of a simple sensor/camera abstraction. \copyright Copyright 2014-2016 Elucideye, Inc. All rights reserved. \license{This project is released under the 3 Clause BSD License.} */ #ifndef __drishti_sensor_Sensor_h__ #define __drishti_sensor_Sensor_h__ #include "drishti/sensor/drishti_sensor.h" #include "drishti/core/Field.h" #include <opencv2/core/core.hpp> #include <array> #include <utility> DRISHTI_SENSOR_NAMESPACE_BEGIN inline float microToMeters(float microns) { return microns * 1e6f; } class SensorModel { public: // ### Intrisnic camera parameters: struct Intrinsic { Intrinsic(); Intrinsic(const cv::Point2f& c, float fx, const cv::Size& size); float getFocalLength() const { return m_fx; } const cv::Size& getSize() const { return *m_size; } void setSize(const cv::Size& size) { m_size = size; } cv::Matx33f getK() const; cv::Point3f getDepth(const std::array<cv::Point2f, 2>& pixels, float widthMeters) const; // Sample parameters for iPhone 5s front facing "Photo" mode shown below: core::Field<cv::Size> m_size; // = {640, 852}; core::Field<cv::Point2f> m_c; // = {320.f, 426.f}; core::Field<float> m_fx; // = 768.0; core::Field<float> m_pixelSize; // = 0.0; }; // ### Extrinsic camera parameters: struct Extrinsic { Extrinsic() = default; Extrinsic(const cv::Matx33f& R) : R(R) { } cv::Matx33f R; }; SensorModel() = default; // init with defaults SensorModel(const float fx) { m_intrinsic.m_fx = fx; } SensorModel(Intrinsic intrinsic) : m_intrinsic(std::move(intrinsic)) { } SensorModel(Intrinsic intrinsic, const Extrinsic& extrinsic) : m_intrinsic(std::move(intrinsic)) , m_extrinsic(extrinsic) { } const Intrinsic& intrinsic() const { return m_intrinsic; } Intrinsic& intrinsic() { return m_intrinsic; } const Extrinsic& extrinsic() const { return m_extrinsic; } Extrinsic& extrinsic() { return m_extrinsic; } protected: Intrinsic m_intrinsic; Extrinsic m_extrinsic; }; struct DeviceModel { SensorModel m_sensor; std::vector<cv::Point2f> m_points // screen coordinates (wcs/centimeters) { { -2.0, -3.0 }, { +2.0, -8.0 }, { +2.0, -3.0 }, { -2.0, -8.0 } }; }; DRISHTI_SENSOR_NAMESPACE_END #endif
8040b1384d4472ee5847571156d35dbc8888b672
e04e1a1b65b22415383f28a99366d5107b4cfb02
/Lesson5.cpp
3dd015e233e8908b0d3026078c8de5fe4cf9e135
[]
no_license
tsmriti02/Language1-
70b4a510c23797a34f494bebbca41c1bc9a1722a
a8ca7c5fb7cc951d14c525f2c888a4d559b9a26b
refs/heads/master
2023-06-07T09:37:48.846407
2021-07-01T17:39:17
2021-07-01T17:39:17
374,405,484
0
0
null
null
null
null
UTF-8
C++
false
false
2,078
cpp
Lesson5.cpp
#include <iostream> //there are two types of header files- //1. System header files: it comes with the compile. //2. User define header files: ti is written by the programmer. // this file should be in current directory to avoid errors. //ccp reference website for different header library files. //depricate - verge of extinction using namespace std; int main() { int a = 4, b = 5; cout << "This is a practice program"; Ccout << endl; cout << "Operators in C++:" << endl; cout << "Following are the Operators in C++" << endl; //Arithmetic operators cout << "The value of a+b is" << a + b << endl; cout << "The value of a-b is" << a - b << endl; cout << "The value of a*b is" << a * b << endl; cout << "The value of a/b is" << a / b << endl; cout << "The value of a%b is" << a % b << endl; cout << "The value of a++ is" << a++ << endl; cout << "The value of a-- is" << a-- << endl; cout << "The value of ++a is" << ++a << endl; cout << "The value of --a is" << --a << endl; cout << endl; // Assigment Operators - used to assign values to variables //int a=3, b=7; //char d = 'd'; // Comparison operator - comparision between values cout << "The value of a == b is" << (a == b) << endl; cout << "The value of a != b is" << (a != b) << endl; cout << "The value of a >= b is" << (a >= b) << endl; cout << "The value of a <= b is" << (a <= b) << endl; cout << "The value of a > b is" << (a > b) << endl; cout << "The value of a < b is" << (a < b) << endl; cout << endl; // the result is in 0/1 (T/F) form. // Any operation in interger will have interger as a result. //Logical Operation cout << "The value of logic and operator (a==b) && (a<b) is:" << ((a == b) && (a < b)) << endl; cout << endl; cout << "The value of logic or operator (a==b) || (a<b) is:" << ((a == b) || (a < b)) << endl; cout << endl; cout << "The value of logic not operator !(a==b) is:" << (!(a == b)) << endl; // <<endl is also used for new line. return 0; }
271c143142f47ca7ef9552ac433a12caad796433
d64d9c52f78d2b332791217a9e91bab7e8fa2599
/hpx/parallel/executors/service_executors.hpp
e6c5f75a87d2424fc704bbca77869582e44a4e4b
[ "LicenseRef-scancode-free-unknown", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Jakub-Golinowski/hpx
a81c7cdbd8e1daf530d93d2dbafb69d899229efa
7c762ea235d5d7cde0d2686c84902016c33f2bec
refs/heads/master
2021-04-26T23:19:08.776815
2018-05-04T12:36:48
2018-05-04T12:36:48
123,970,854
1
0
BSL-1.0
2018-03-05T19:53:11
2018-03-05T19:53:11
null
UTF-8
C++
false
false
4,311
hpp
service_executors.hpp
// Copyright (c) 2007-2016 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// \file parallel/executors/service_executors.hpp #if !defined(HPX_PARALLEL_EXECUTORS_SERVICE_EXECUTORS_MAY_15_2015_0548PM) #define HPX_PARALLEL_EXECUTORS_SERVICE_EXECUTORS_MAY_15_2015_0548PM #include <hpx/config.hpp> #include <hpx/lcos/future.hpp> #include <hpx/parallel/executors/static_chunk_size.hpp> #include <hpx/parallel/executors/thread_execution.hpp> #include <hpx/runtime/threads/executors/service_executors.hpp> #include <hpx/traits/executor_traits.hpp> namespace hpx { namespace parallel { namespace execution { /// A \a service_executor exposes one of the predefined HPX thread pools /// through an executor interface. /// /// \note All tasks executed by one of these executors will run on /// one of the OS-threads dedicated for the given thread pool. The /// tasks will not run as HPX-threads. /// using service_executor = threads::executors::service_executor; /// A \a io_pool_executor exposes the predefined HPX IO thread pool /// through an executor interface. /// /// \note All tasks executed by one of these executors will run on /// one of the OS-threads dedicated for the IO thread pool. The /// tasks will not run as HPX-threads. /// using io_pool_executor = threads::executors::io_pool_executor; /// A \a io_pool_executor exposes the predefined HPX parcel thread pool /// through an executor interface. /// /// \note All tasks executed by one of these executors will run on /// one of the OS-threads dedicated for the parcel thread pool. The /// tasks will not run as HPX-threads. /// using parcel_pool_executor = threads::executors::parcel_pool_executor; /// A \a io_pool_executor exposes the predefined HPX timer thread pool /// through an executor interface. /// /// \note All tasks executed by one of these executors will run on /// one of the OS-threads dedicated for the timer thread pool. The /// tasks will not run as HPX-threads. /// using timer_pool_executor = threads::executors::timer_pool_executor; /// A \a io_pool_executor exposes the predefined HPX main thread pool /// through an executor interface. /// /// \note All tasks executed by one of these executors will run on /// one of the OS-threads dedicated for the main thread pool. The /// tasks will not run as HPX-threads. /// using main_pool_executor = threads::executors::main_pool_executor; }}} #if defined(HPX_HAVE_EXECUTOR_COMPATIBILITY) #include <hpx/parallel/executors/v1/thread_executor_traits.hpp> /////////////////////////////////////////////////////////////////////////////// // Compatibility layer namespace hpx { namespace parallel { inline namespace v3 { /// \cond NOINTERNAL struct service_executor : threads::executors::service_executor { typedef static_chunk_size executor_parameters_type; service_executor( threads::executors::service_executor_type t, char const* name_suffix = "") : threads::executors::service_executor(t, name_suffix) {} }; struct io_pool_executor : service_executor { io_pool_executor() : service_executor( threads::executors::service_executor_type::io_thread_pool) {} }; struct parcel_pool_executor : service_executor { parcel_pool_executor(char const* name_suffix = "-tcp") : service_executor( threads::executors::service_executor_type::parcel_thread_pool, name_suffix) {} }; struct timer_pool_executor : service_executor { timer_pool_executor() : service_executor( threads::executors::service_executor_type::timer_thread_pool) {} }; struct main_pool_executor : service_executor { main_pool_executor() : service_executor( threads::executors::service_executor_type::main_thread) {} }; /// \endcond }}} #endif #endif
ec521d61cd33061203921e06a6495bc9d93ac13b
5e35d49887a0c50d75913ca82d187275e217c4f5
/Baekjoon/LEETCODE]longestincreasingsequence.cpp
892a516ffc12f12ba9a3f783dbe7a8f09ab12c33
[]
no_license
jiun0507/Interview-prep
4866f0c3d3dd6a407bc7078987aaa373d7111c2c
aeaae8a99dc21f2b11ae50f577a75ff49b56e1b3
refs/heads/master
2021-11-14T11:31:03.316564
2021-09-11T21:15:25
2021-09-11T21:15:25
214,645,862
0
0
null
2019-10-12T13:08:09
2019-10-12T12:44:57
null
UTF-8
C++
false
false
488
cpp
LEETCODE]longestincreasingsequence.cpp
class Solution { public: int lengthOfLIS(vector<int>& nums) { int len = nums.size(); int dp[len]; for(int i = 0;i<len;i++) dp[i] = 1; for(int i = 0;i<len;i++){ for(int j = 0;j<i;j++){ if(nums[j]<nums[i]){ dp[i] = max(dp[i], dp[j]+1); } } } int ret = 0; for(int i = 0;i<len;i++){ ret = max(ret, dp[i]); } return ret; } };
0bdf6314bdf62140cb4bb9b28961ca46fe810f7d
36c8cf395214abaad868ec06bd97bf418733b1b0
/test/unit-tests/journal_manager/log_buffer/log_write_context_test.cpp
2319b9ccd398012a3cacb8e7019ab52c74ca33a3
[ "BSD-3-Clause" ]
permissive
south-potato/poseidonos
69435ecb2dd80c1eb702f36501156705b1908111
35c5bbd392a261d257f1ead3e8be7c3f44c5831a
refs/heads/main
2023-08-12T13:31:32.495095
2021-09-30T09:59:22
2021-10-05T02:27:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,326
cpp
log_write_context_test.cpp
#include "src/journal_manager/log_buffer/log_write_context.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "src/journal_manager/log_buffer/log_buffer_io_context.h" #include "test/unit-tests/event_scheduler/event_mock.h" #include "test/unit-tests/journal_manager/log/log_handler_mock.h" #include "test/unit-tests/journal_manager/log_buffer/buffer_write_done_notifier_mock.h" using testing::NiceMock; using testing::Return; namespace pos { static const uint32_t INVALID_GROUP_ID = UINT32_MAX; TEST(LogWriteContext, LogWriteContext_testIfConstructedSuccessfully) { // Given, When NiceMock<MockLogHandlerInterface>* log = new NiceMock<MockLogHandlerInterface>; LogWriteContext logWriteContext(log, nullptr, nullptr); // Then: Log group id is invalid int result = logWriteContext.GetLogGroupId(); int retValue = INVALID_GROUP_ID; EXPECT_EQ(retValue, result); } TEST(LogWriteContext, GetLog_testIfExecutedSuccessfully) { // Given NiceMock<MockLogHandlerInterface>* log = new NiceMock<MockLogHandlerInterface>; LogWriteContext logWriteContext(log, nullptr, nullptr); // When LogHandlerInterface* result = logWriteContext.GetLog(); // Then EXPECT_EQ(log, result); } TEST(LogWriteContext, SetBufferAllocated_testIfExecutedSuccessfully) { // Given NiceMock<MockLogHandlerInterface>* log = new NiceMock<MockLogHandlerInterface>; LogWriteContext logWriteContext(log, nullptr, nullptr); // When uint64_t fileOffset = 0; int logGroupId = 1; uint32_t seqNum = 1; EXPECT_CALL(*log, SetSeqNum(seqNum)); logWriteContext.SetBufferAllocated(fileOffset, logGroupId, seqNum); // Then EXPECT_EQ(fileOffset, logWriteContext.fileOffset); EXPECT_EQ(logGroupId, logWriteContext.GetLogGroupId()); } TEST(LogWriteContext, IoDone_testIfExecutedSuccessfully) { // Given NiceMock<MockLogHandlerInterface>* log = new NiceMock<MockLogHandlerInterface>; NiceMock<MockEvent>* callback = new NiceMock<MockEvent>; NiceMock<MockLogBufferWriteDoneNotifier> notifier; LogWriteContext logWriteContext(log, EventSmartPtr(callback), &notifier); // When, Then EXPECT_CALL(notifier, NotifyLogFilled); EXPECT_CALL(*callback, Execute).WillOnce(Return(true)); logWriteContext.IoDone(); } } // namespace pos
73afc1b38146da6e86b77b04feadbe8c29dd07f2
2caf94cd1da6e0adaf7d40f136245f115b24bb1d
/App/App.cpp
432e89601dd53c284500f53931ced3dd88f08fc6
[]
no_license
ptahmose/DLLHellTest
ecc3fb28ef3e1056d62ab05a797dfc7e48457b45
aa640753889959034706d2b2f8686d573b0592bb
refs/heads/master
2021-01-10T04:46:00.021796
2015-12-06T22:28:09
2015-12-06T22:28:09
47,495,708
0
0
null
null
null
null
UTF-8
C++
false
false
5,316
cpp
App.cpp
// App.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <dllA.h> #include <dllB.h> typedef std::string(WINAPI *funcGetTextFromDll)(void); funcGetTextFromDll GetFunctionFromDll(LPCTSTR dllName, LPCSTR funcName, DWORD dwFlags) { HMODULE hMod = LoadLibraryEx(dllName, NULL, dwFlags); if (hMod == NULL) { return nullptr; } FARPROC f = GetProcAddress(hMod, funcName); if (f == NULL) { return nullptr; } return (funcGetTextFromDll)f; } void Test1() { // this will (usually) print // // Text from DLL A: couldn't load DllA // Text from DLL B : couldn't load DllB // // simply because the dllCommon.dll cannot be resolved funcGetTextFromDll getFromA = GetFunctionFromDll(_T("dllA"), "?GetTextA@@YG?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); funcGetTextFromDll getFromB = GetFunctionFromDll(_T("dllB"), "?GetTextB@@YG?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); auto strFromA = (getFromA != nullptr) ? (getFromA()) : std::string("couldn't load DllA"); auto strFromB = (getFromB != nullptr) ? (getFromB()) : std::string("couldn't load DllB"); std::cout << "Text from DLL A: " << strFromA << std::endl; std::cout << "Text from DLL B: " << strFromB << std::endl; } void Test2() { TCHAR szCurrentExecutableName[MAX_PATH]; GetModuleFileName(GetModuleHandle(NULL), szCurrentExecutableName, (sizeof(szCurrentExecutableName) / sizeof(szCurrentExecutableName[0]))); for (size_t i = _tcslen(szCurrentExecutableName) - 1; i >= 0;--i) { if (szCurrentExecutableName[i]==_T('\\')) { szCurrentExecutableName[i] = _T('\0'); break; } } std::basic_string<TCHAR> absFilename1(szCurrentExecutableName); absFilename1 += _T("\\dllA.dll"); std::basic_string<TCHAR> absFilename2(szCurrentExecutableName); absFilename2 += _T("\\dllB.dll"); std::basic_string<TCHAR> dllPath1(szCurrentExecutableName); dllPath1 += _T("\\v1\\"); std::basic_string<TCHAR> dllPath2(szCurrentExecutableName); dllPath2 += _T("\\v2\\"); DLL_DIRECTORY_COOKIE ckie1 = AddDllDirectory(dllPath1.c_str()); funcGetTextFromDll getFromA = GetFunctionFromDll(absFilename1.c_str(), "?GetTextA@@YG?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ", LOAD_LIBRARY_SEARCH_USER_DIRS); RemoveDllDirectory(ckie1); DLL_DIRECTORY_COOKIE ckie2 = AddDllDirectory(dllPath2.c_str()); funcGetTextFromDll getFromB = GetFunctionFromDll(absFilename2.c_str(), "?GetTextB@@YG?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ", LOAD_LIBRARY_SEARCH_USER_DIRS); RemoveDllDirectory(ckie2); auto strFromA = (getFromA != nullptr) ? (getFromA()) : std::string("couldn't load DllA"); auto strFromB = (getFromB != nullptr) ? (getFromB()) : std::string("couldn't load DllB"); std::cout << "Text from DLL A: " << strFromA << std::endl; std::cout << "Text from DLL B: " << strFromB << std::endl; } void Test3() { TCHAR szCurrentExecutableName[MAX_PATH]; GetModuleFileName(GetModuleHandle(NULL), szCurrentExecutableName, (sizeof(szCurrentExecutableName) / sizeof(szCurrentExecutableName[0]))); for (size_t i = _tcslen(szCurrentExecutableName) - 1; i >= 0; --i) { if (szCurrentExecutableName[i] == _T('\\')) { szCurrentExecutableName[i] = _T('\0'); break; } } std::basic_string<TCHAR> absFilename1(szCurrentExecutableName); absFilename1 += _T("\\dllA.dll"); std::basic_string<TCHAR> absFilename2(szCurrentExecutableName); absFilename2 += _T("\\dllB.dll"); std::basic_string<TCHAR> dllPath1(szCurrentExecutableName); dllPath1 += _T("\\v1\\"); std::basic_string<TCHAR> dllPath2(szCurrentExecutableName); dllPath2 += _T("\\v2\\"); DLL_DIRECTORY_COOKIE ckie1 = AddDllDirectory(dllPath1.c_str()); ACTCTX ctx1; ctx1.cbSize = sizeof(ctx1); ctx1.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID; ctx1.lpSource = absFilename1.c_str(); ctx1.lpResourceName = MAKEINTRESOURCE(2); HANDLE h1 = CreateActCtx(&ctx1); DWORD ckieActCtx1; BOOL B = ActivateActCtx(h1, &ckieActCtx1); funcGetTextFromDll getFromA = GetFunctionFromDll(absFilename1.c_str(), "?GetTextA@@YG?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ", LOAD_WITH_ALTERED_SEARCH_PATH/*LOAD_LIBRARY_SEARCH_USER_DIRS*/); RemoveDllDirectory(ckie1); DeactivateActCtx(0, ckieActCtx1); ACTCTX ctx2; ctx2.cbSize = sizeof(ctx2); ctx2.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID; ctx2.lpSource = absFilename2.c_str(); ctx2.lpResourceName = MAKEINTRESOURCE(2); DLL_DIRECTORY_COOKIE ckie2 = AddDllDirectory(dllPath2.c_str()); HANDLE h2 = CreateActCtx(&ctx2); DWORD ckieActCtx2; ActivateActCtx(h2, &ckieActCtx2); funcGetTextFromDll getFromB = GetFunctionFromDll(absFilename2.c_str(), "?GetTextB@@YG?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ", LOAD_LIBRARY_SEARCH_USER_DIRS); RemoveDllDirectory(ckie2); DeactivateActCtx(0, ckieActCtx2); auto strFromA = (getFromA != nullptr) ? (getFromA()) : std::string("couldn't load DllA"); auto strFromB = (getFromB != nullptr) ? (getFromB()) : std::string("couldn't load DllB"); std::cout << "Text from DLL A: " << strFromA << std::endl; std::cout << "Text from DLL B: " << strFromB << std::endl; } int main() { //Test1(); //Test2(); Test3(); return 0; }
5af525d8daebed1bf8267c8554dfce10a7beab57
7ebc12c326dd918bc96c08167f0457ed2f8f93de
/Trains/10112013/K/hax.cpp
cea81635379f245ea38981c77d7c66a240a29908
[]
no_license
qwaker00/Olymp
635b61da0e80d1599edfe1bc9244b95f015b3007
c3ab2c559fa09f080a3f02c84739609e1e85075d
refs/heads/master
2021-01-18T16:35:58.452451
2015-08-06T16:45:58
2015-08-06T16:46:25
5,674,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,181
cpp
hax.cpp
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; char s[1111111]; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); gets(s); int l = strlen(s), ans = 0; for (int i = 0; i < l;) { if (s[i] == '(') { ++i; while (i < l && (s[i] == ' ' || (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) ) ++i; if (s[i] == ')') { ++i; } else { ++ans; } } else { if (s[i] == '(' || s[i] == ')') ++ans; ++i; } } cout << ans << endl; return 0; }
e9287397f5f1511fbd58b0eaa19d20092e8946af
130fc6ecaf5f9e57ea64b08b5b6c287ce432dc1f
/C++/Graphics Programming/proyectodemo/Src/RenderThread/RenderThread.h
5bdd28a4fb53ba482cbc13a715af49c4ee96dceb
[]
no_license
Xuzon/PortFolio
d1dc98f352e6d0459d7739c0a866c6f1a701542d
c2f1674bc15930ce0d45143e4d935e3e631fe9c2
refs/heads/master
2021-01-17T15:05:08.179998
2020-05-13T17:26:19
2020-05-13T17:26:19
53,209,189
5
1
null
null
null
null
UTF-8
C++
false
false
485
h
RenderThread.h
#pragma once #include <thread> #include <atomic> #include "Queue.h" #include "CommandBuffer.h" class RenderThread { public: void Start(); void Stop(); int PendingFrames() { return pendingFrames; } void EnqueueAction(const CommandBuffer& command); private: void RenderLoop(); void DrawBox(int x, int y, int sizeX, int sizeY, int color); ConcurrentQueue<CommandBuffer> commandQueue; std::thread* thread = nullptr; std::atomic_bool quit = false; int pendingFrames = 0; };
193bc3b5be85272d7c8a5714a423832327f8eba9
ec0116dc9b9adbb49d5aa51e29de533f38f0394b
/448.find.all.nums.disappeared.in.array.cpp
a2be82a63bb971cd00ca5fadccd0e8a061f064db
[]
no_license
ro9n/lc
cce14c166b222523aa0d3a9fd4c5b95c33dc00fb
cb7208299906f6600f0ab20d70d3500c43203801
refs/heads/master
2023-03-09T01:12:27.143634
2021-02-18T07:45:21
2021-02-18T07:45:21
292,909,432
0
0
null
2020-09-04T17:35:37
2020-09-04T17:35:37
null
UTF-8
C++
false
false
578
cpp
448.find.all.nums.disappeared.in.array.cpp
/** * @file 448.find.all.nums.disappeared.in.array * @author Touhid Alam <taz.touhid@gmail.com> * * @date Friday October 09 2020 * * @brief */ #include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { int n = nums.size(); vector<int> ans; for (int i = 0; i < n; ++i) { if (nums[i] > n || nums[abs(nums[i]) - 1] < 0) continue; nums[abs(nums[i]) - 1] *= -1; } for (int i = 0; i < n; ++i) { if (nums[i] > 0) ans.emplace_back(i + 1); } return ans; } };
625400bf3fab05bbd5a610d4fad2387560095425
6150b22997c2bc11107765296bb142409b21de1c
/Main.cpp
f0359cbe8a72e61c399190725b634f64434908e4
[]
no_license
Manishthakur1297/Basic-JSON-Parser-C-
13379449ae4b6eb2a56034354a518c733a2c7f86
28d235b8e40eba0d8b9ee1e464beb71b2cc73c1c
refs/heads/master
2020-07-17T10:50:47.437634
2019-09-03T11:47:09
2019-09-03T11:47:09
206,005,443
0
0
null
null
null
null
UTF-8
C++
false
false
8,388
cpp
Main.cpp
#include <iostream> #include<bits/stdc++.h> #include<fstream> using namespace std; struct Node { string key; //vector<string> key; int level; vector<Node *>child; struct Node *prev; }; Node *newNode(string key) { Node *temp = new Node; temp->key = key; temp->level = 0; return temp; } void LevelOrderTraversal(Node * root) { if (root==NULL) return; queue<Node *> q; q.push(root); int counter = -1; while (!q.empty()) { int n = q.size(); counter++; while (n > 0) { Node * p = q.front(); q.pop(); //for(int i = 0;i<p->key.size();i++) //{ cout << p->key <<endl; //} for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); cout<<"\n---------------"<<endl; n--; } cout << "\nLevel========"<<counter<<endl; } } //Split String vector<string> split(string strToSplit, char delimeter) { stringstream ss(strToSplit); string item; vector<string> splittedStrings; while (getline(ss, item, delimeter)) { splittedStrings.push_back(item); } return splittedStrings; } int main() { string str = ""; string line; while(std::getline(cin, line)){ if (line.empty()){ break; } str+=line; } cout<<str<<endl; cout<<"-----------------------------------"<<endl; stack<char> stack; list<int> l; vector<string> vvv; vvv.push_back("data"); Node *root = newNode("data"); Node *temp = root; int pos = str.find("{"); if(pos==string::npos) { pos = 0; } int lpos = 0; stack.push('{'); bool flag = true; int lvl=0; int aC = 0; //cout<<"ddddddsws + "<<pos<<endl; for(int i=1;i<str.length();i++) { if(str[i]=='{') { //cout<<"dddddd + "<<endl; int len = i-lpos; string s = str.substr(lpos+1,len-1); vector<string> vv = split(s, ','); if(lvl==0 || stack.size()==1) { for(int k=0;k<vv.size();k++) { temp->child.push_back(newNode(vv[k])); temp->prev = temp; } lvl++; } else { //cout<<"111d111ddddd + "<<endl; int lll = temp->level; //cout<<"temp key"<<temp->child[0]->child[1]->key<<"kgh "<<lll<<endl; //int lll = vv.size()-1; for(int k=0;k<vv.size();k++) { (temp->child[lll]->child).push_back(newNode(vv[k])); temp->child[lll]->prev = temp; } temp = temp->child[lll]; if(vv.size()!=0) { temp->level = temp->level+vv.size()-1; } //cout<<"22111d111ddddd + "<<endl; } lpos = i; stack.push('{'); l.push_back(i); flag = true; } else if(str[i] == '[') { //cout<<"1111111111111 + "<<endl; int len = i-lpos; string s = str.substr(lpos+1,len-1); vector<string> vv = split(s, ','); //Node *c = newNode(vv); if(lvl==0) { for(int k=0;k<vv.size();k++) { temp->child.push_back(newNode(vv[k])); temp->prev = temp; } lvl++; } else { int lll = temp->level; for(int k=0;k<vv.size();k++) { (temp->child[lll]->child).push_back(newNode(vv[k])); temp->child[lll]->prev = temp; } temp = temp->child[lll]; aC = vv.size()-1; } lpos = i; stack.push('['); l.push_back(i); flag = true; } else if(str[i] == ']') { //cout<<"2222222222222 + "<<endl; int len = i-l.back(); string s = str.substr(l.back()+1,len-1); vector<string> vv = split(s, ','); //Node *c = newNode(vv); if(!l.empty()) { l.pop_back(); } stack.pop(); if(lvl==0) { for(int k=0;k<vv.size();k++) { temp->child.push_back(newNode(vv[k])); temp->prev = temp; } lvl++; } else { if(flag) { int lll = temp->level; //cout<<"oiuytr + "<<temp->key<<" "<<temp->child.size()<<endl; for(int k=0;k<vv.size();k++) { (temp->child[aC]->child).push_back(newNode(vv[k])); temp->child[aC]->prev = temp; } //cout<<"wewre + "<<endl; temp = temp->prev; } } lpos = i+1; if(i+1 !=str.length() && str[i+1]==',') { flag =true; } else { flag = false; } l.push_back(i+1); } else if(str[i] == '}') { //cout<<"eeeeeeeeeeeee + "<<endl; int len = i-l.back(); string s = str.substr(l.back()+1,len-1); vector<string> vv = split(s, ','); //Node *c = newNode(vv); if(!l.empty()) { l.pop_back(); } stack.pop(); if(i+1 !=str.length() && str[i+1]==',') { //cout<<"eeeededewfeeeeeeeeee + "<<endl; if(flag) { //cout<<"eeeeeeeeeeeee + "<<endl; int lll = temp->level; for(int k=0;k<vv.size();k++) { (temp->child[lll]->child).push_back(newNode(vv[k])); temp->child[lll]->prev = temp; } //cout<<"dweeeeeeeeeee + "<<endl; temp->level = temp->level+1; temp = temp->prev; //temp->level = temp->level+1; lpos = i+1; //cout<<"jhgewqeeeeeee + "<<endl; } else { temp->level = temp->level+1; temp = temp->prev; lpos = i+1; } flag = true; } else { if(lvl==0) { for(int k=0;k<vv.size();k++) { temp->child.push_back(newNode(vv[k])); temp->prev = temp; } lvl++; } else { if(flag) { int lll = temp->level; for(int k=0;k<vv.size();k++) { (temp->child[lll]->child).push_back(newNode(vv[k])); temp->child[lll]->prev = temp; } temp = temp->prev; } } flag = false; } } } cout << "\nLevel order traversal Before Mirroring\n"; LevelOrderTraversal(root); //cout<<root->child[1]->child[1]->key<<endl; //cout<<root->child[0]->child[1]->child[1]->child[1]->child[0]->key<<endl; return 0; }
69c1e21fdb466fb6aec61133e497eb78d00b54c2
95f692202f127f964df763c5725950a35b18c922
/build-Demo_VLC_Qt-Desktop_Qt_5_9_1_MinGW_32bit-Debug/ui_mainwindow.h
3e73751c532f060c8fd358529c1b57ea84ae4943
[]
no_license
renjiexiong/vlc
2ecabf2c4c5fc327956eaff40242fece50bfd217
ff0cf3a28b6a6e48b1e5a027a3c7b94ca00320a8
refs/heads/master
2023-07-02T09:01:03.086337
2021-08-02T02:41:06
2021-08-02T02:41:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,538
h
ui_mainwindow.h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QGridLayout *gridLayout; QLabel *lB_Path; QPushButton *pushButton; QPushButton *pB_Open; QLabel *label; QPushButton *pB_Stop; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(722, 508); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); gridLayout = new QGridLayout(centralWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); lB_Path = new QLabel(centralWidget); lB_Path->setObjectName(QStringLiteral("lB_Path")); lB_Path->setMaximumSize(QSize(16777215, 30)); gridLayout->addWidget(lB_Path, 0, 0, 1, 3); pushButton = new QPushButton(centralWidget); pushButton->setObjectName(QStringLiteral("pushButton")); gridLayout->addWidget(pushButton, 2, 0, 1, 1); pB_Open = new QPushButton(centralWidget); pB_Open->setObjectName(QStringLiteral("pB_Open")); gridLayout->addWidget(pB_Open, 0, 3, 1, 1); label = new QLabel(centralWidget); label->setObjectName(QStringLiteral("label")); QFont font; font.setFamily(QStringLiteral("Agency FB")); font.setPointSize(24); label->setFont(font); label->setStyleSheet(QStringLiteral("background-color: rgb(170, 255, 0);")); label->setAlignment(Qt::AlignCenter); gridLayout->addWidget(label, 1, 0, 1, 4); pB_Stop = new QPushButton(centralWidget); pB_Stop->setObjectName(QStringLiteral("pB_Stop")); gridLayout->addWidget(pB_Stop, 2, 3, 1, 1); MainWindow->setCentralWidget(centralWidget); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR)); lB_Path->setText(QApplication::translate("MainWindow", "Please enter \"Open\"", Q_NULLPTR)); pushButton->setText(QApplication::translate("MainWindow", "play", Q_NULLPTR)); pB_Open->setText(QApplication::translate("MainWindow", "Open", Q_NULLPTR)); label->setText(QApplication::translate("MainWindow", "Please enter \"play\"", Q_NULLPTR)); pB_Stop->setText(QApplication::translate("MainWindow", "stop", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
b6c075129de29203c95ff32c0dcdcef67edda9ff
2d506cd97e81bf5a1454f429c8ece08a78790919
/大作业/file.cpp
167dbdd1e26b1a29dc83d555cec6becdcd21ee83
[]
no_license
ACCRT/HelloCorn
44a1115a18e5ed8468ab2997bb76f7a74aad1617
ecfd8f72e7d4fded70a8abe918fc951a2515d090
refs/heads/master
2021-01-12T09:50:11.839270
2016-12-12T15:34:35
2016-12-12T15:34:35
76,270,243
0
0
null
null
null
null
UTF-8
C++
false
false
3,091
cpp
file.cpp
#include"file.h" #include"GUI.h" File* file =0; File::File() :save(),record(),load(),is_recording(false),is_reviewing(false) { if(!save) exit(0); file = this; } void File::write_file(string filename) { save.open(filename.c_str()); save<<gui->get_count()->get_game_time()<<"\n"; save<<gui->get_count()->get_score()<<"\n"; for(int i=0;i<6;i++) for(int j =0;j<6;j++) { save<<gui->get_map()->Get_color(i,j)<<" "; save<<gui->get_map()->Get_state(i,j)<<" "; save<<gui->get_map()->Get_kind(i,j)<<" "; save<<gui->get_map()->Get_effect(i,j)<<" "; save<<"\n"; } save.close(); } void File::read_file(string filename) { double temp; load.open(filename.c_str()); load>>temp; gui->get_count()->set_game_time(temp); load>>temp; gui->get_count()->set_score(temp); for(int i=0;i<6;i++) for(int j =0;j<6;j++) { load>>temp; gui->get_map()->Set_color(i,j,COLOR(int(temp))); load>>temp; gui->get_map()->Set_state(i,j,STATE(int(temp))); load>>temp; gui->get_map()->Set_kind(i,j,KIND(int(temp))); load>>temp; gui->get_map()->Set_effect(i,j,EFFECT(int(temp))); } load.close(); } void File::record_file() { record<<gui->get_count()->get_game_time()<<"\n"; record<<gui->get_count()->get_score()<<"\n"; for(int i=0;i<6;i++) for(int j =0;j<6;j++) { record<<gui->get_map()->Get_color(i,j)<<" "; record<<gui->get_map()->Get_state(i,j)<<" "; record<<gui->get_map()->Get_kind(i,j)<<" "; record<<gui->get_map()->Get_effect(i,j)<<" "; record<<gui->get_map()->Get_location(i,j).first<<" "; record<<gui->get_map()->Get_location(i,j).second<<" "; record<<"\n"; } } void File::review_file() { double temp; double temp2; review>>temp; if(review.eof()) { Logic::stop_review(); Logic::return_to_menu(); return; } gui->get_count()->set_game_time(temp); review>>temp; gui->get_count()->set_score(temp); for(int i=0;i<6;i++) for(int j =0;j<6;j++) { review>>temp; gui->get_map()->Set_color(i,j,COLOR(int(temp))); review>>temp; gui->get_map()->Set_state(i,j,STATE(int(temp))); review>>temp; gui->get_map()->Set_kind(i,j,KIND(int(temp))); review>>temp; gui->get_map()->Set_effect(i,j,EFFECT(int(temp))); review>>temp; review>>temp2; gui->get_map()->Set_location(i,j,pair<double,double>(temp,temp2)); } } void File::read_map(int i) { string s = "map0.txt"; s[3]=ftoa(i)[0]; read_file(s.c_str()); } void File::open_record(){record.open("video.txt");} void File::close_record(){record.close();} void File::open_review(){review.open("video.txt");} void File::close_review(){review.close();} bool File::get_is_recording() { return is_recording; } void File::set_is_recording(bool b) { is_recording = b; } bool File::get_is_reviewing() { return is_reviewing; } void File::set_is_reviewing(bool b) { is_reviewing = b; } void File::read_best_score() { load.open("best.txt"); int temp; load>>temp; gui->get_count()->set_best_score(temp); load.close(); } void File::write_best_score() { save.open("best.txt"); save<<gui->get_count()->get_best_score(); save.close(); }
08fd0f7ef05873ddbd262c1acadda4a6836bb66f
55419c24220f22649f40941e5de071d649611ea6
/Graph.h
22ccdeda3b037a3902aecc616fe854ad57dedab3
[]
no_license
SYury/skeleton
c80c2b52ec1ebc1bd4314e40ed57f9e4e1142bd0
b5cafaebc149c1dd1c93573eed0146ec13e9cf36
refs/heads/master
2022-09-02T18:56:25.536890
2020-05-22T16:19:45
2020-05-22T16:19:45
266,155,286
0
0
null
null
null
null
UTF-8
C++
false
false
254
h
Graph.h
#ifndef GRAPH_H_ #define GRAPH_H_ #include <vector> #include "Point.h" struct Vertex{ Point pos; size_t id; Point curr_pos; Float curr_time; }; struct Edge{ Vertex *v, *u; }; using Graph = std::vector<Edge*>; #endif // GRAPH_H_
c264f93ff829c6671b0f6dc51a6f1f5723571a34
3391892861a1e1e71af6e414bcdb9fc0df66c62e
/src/game/world/aspects/puppet_animation_aspect.cpp
a0f5cdb162560a09e032e066cd762508ef1fd3c8
[ "Apache-2.0" ]
permissive
jdmclark/gorc
a21208b1d03a85fc5a99fdd51fdad27446cc4767
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
refs/heads/develop
2021-01-21T05:01:26.609783
2020-12-21T00:26:22
2020-12-21T02:34:31
10,290,074
103
10
Apache-2.0
2020-12-21T02:34:33
2013-05-25T21:27:37
C++
UTF-8
C++
false
false
10,429
cpp
puppet_animation_aspect.cpp
#include "puppet_animation_aspect.hpp" #include "game/world/level_model.hpp" #include "game/world/keys/components/key_state.hpp" #include "game/world/keys/key_presenter.hpp" #include "game/world/events/armed_mode_changed.hpp" #include "game/world/events/jumped.hpp" #include "game/world/events/landed.hpp" #include "game/world/events/killed.hpp" #include "game/world/events/thing_created.hpp" using gorc::game::world::aspects::puppet_animation_aspect; puppet_animation_aspect::puppet_animation_aspect(entity_component_system<thing_id> &cs, level_presenter &presenter) : inner_join_aspect(cs) , presenter(presenter) { created_delegate = cs.bus.add_handler<events::thing_created>([&](events::thing_created const &e) { maybe_if(e.tpl.pup, [&](auto pup) { // New thing has a puppet. Create a puppet animations component. cs.emplace_component<components::puppet_animations>(e.thing, pup); }); }); armed_mode_delegate = cs.bus.add_handler<events::armed_mode_changed>([&](events::armed_mode_changed const &e) { for(auto &pup : cs.find_component<components::puppet_animations>(e.thing)) { bool is_underwater = false; for(auto &thing : cs.find_component<components::thing>(e.thing)) { auto const &cur_sector = at_id(presenter.model->sectors, thing.second->sector); is_underwater = cur_sector.flags & flags::sector_flag::Underwater; } flags::puppet_mode_type maj_mode = flags::puppet_mode_type::unarmed; switch(e.mode) { case flags::armed_mode::unarmed: maj_mode = is_underwater ? flags::puppet_mode_type::swimming_unarmed : flags::puppet_mode_type::unarmed; break; case flags::armed_mode::armed: maj_mode = is_underwater ? flags::puppet_mode_type::swimming_armed : flags::puppet_mode_type::armed; break; case flags::armed_mode::saber: maj_mode = is_underwater ? flags::puppet_mode_type::swimming_saber : flags::puppet_mode_type::saber; break; } pup.second->puppet_mode_type = maj_mode; } }); jumped_delegate = cs.bus.add_handler<events::jumped>([&](events::jumped const &e) { for(auto &pup : cs.find_component<components::puppet_animations>(e.thing)) { for(auto &thing : cs.find_component<components::thing>(e.thing)) { auto jump_submode = flags::puppet_submode_type::Rising; if(thing.second->physics_flags & flags::physics_flag::is_crouching) { jump_submode = flags::puppet_submode_type::Leap; } set_walk_animation(*thing.second, *pup.second, jump_submode, 1.0f); } } }); landed_delegate = cs.bus.add_handler<events::landed>([&](events::landed const &e) { auto rng = cs.find_component<components::puppet_animations>(e.thing); for(auto it = rng.begin(); it != rng.end(); ++it) { presenter.key_presenter->play_mode(thing_id(e.thing), flags::puppet_submode_type::Land); } }); killed_delegate = cs.bus.add_handler<events::killed>([&](events::killed const &e) { for(auto &pup : cs.find_component<components::puppet_animations>(e.thing)) { // HACK: Stop idle animation maybe_if(pup.second->actor_walk_animation, [&](thing_id anim) { presenter.key_presenter->stop_key(e.thing, anim, 0.0f); pup.second->actor_walk_animation = nothing; }); presenter.key_presenter->play_mode(e.thing, flags::puppet_submode_type::Death); } }); return; } void puppet_animation_aspect::set_walk_animation(components::thing &thing, components::puppet_animations &pup, flags::puppet_submode_type type, float speed) { if(thing.type == flags::thing_type::Corpse || !pup.actor_walk_animation.has_value()) { // Thing is dead and/or cannot play a walk animation. return; } keys::key_state *keyState = nullptr; maybe_if(pup.actor_walk_animation, [&](thing_id anim) { for(auto &key_state : ecs.find_component<keys::key_state>(anim)) { keyState = key_state.second; } }); if(!keyState) { return; } auto const &maybe_submode = pup.puppet->get_mode(pup.puppet_mode_type).get_submode(type); maybe_if(maybe_submode, [&](content::assets::puppet_submode const *submode) { if(keyState->animation != submode->anim) { keyState->animation_time = 0.0; } keyState->animation = submode->anim; keyState->high_priority = submode->hi_priority; keyState->low_priority = submode->lo_priority; keyState->flags = flag_set<flags::key_flag>(); keyState->speed = speed; }); } void puppet_animation_aspect::set_walk_animation_speed(components::puppet_animations &pup, float speed) { maybe_if(pup.actor_walk_animation, [&](thing_id anim) { for(auto &key_state : ecs.find_component<keys::key_state>(anim)) { key_state.second->speed = speed; } }); } bool puppet_animation_aspect::is_walk_animation_mode(components::puppet_animations &pup, flags::puppet_submode_type type) { maybe_if(pup.actor_walk_animation, [&](thing_id anim) { for(auto &key_state : ecs.find_component<keys::key_state>(anim)) { auto const &maybe_submode = pup.puppet->get_mode(pup.puppet_mode_type).get_submode(type); maybe_if(maybe_submode, [&](content::assets::puppet_submode const *submode) { return key_state.second->animation == submode->anim; }); } }); return false; } void puppet_animation_aspect::update_standing_animation(components::thing &thing, components::puppet_animations &pup) { auto oriented_vel = invert(thing.orient).transform(thing.vel); auto run_length = length(thing.vel); auto vel_fb = get<1>(oriented_vel); auto vel_lr = get<0>(oriented_vel); auto turn_rate = get<1>(thing.ang_vel); float run_anim_speed = run_length * 20.0f; float turn_anim_speed = static_cast<float>(fabs(turn_rate) / 360.0); if(thing.physics_flags & flags::physics_flag::is_crouching) { if(fabs(turn_rate) > 0.0001) { set_walk_animation(thing, pup, flags::puppet_submode_type::CrouchForward, turn_anim_speed * 20.0f); } else if(vel_fb >= 0.0f || fabs(vel_lr) > fabs(vel_fb)) { set_walk_animation(thing, pup, flags::puppet_submode_type::CrouchForward, run_anim_speed); } else { set_walk_animation(thing, pup, flags::puppet_submode_type::CrouchBack, run_anim_speed); } } else { if(run_length < 0.001f) { // Idle or turning. if(turn_rate > 60.0f) { // Turning right set_walk_animation(thing, pup, flags::puppet_submode_type::TurnRight, turn_anim_speed); } else if(turn_rate < -60.0f) { // Turning left set_walk_animation(thing, pup, flags::puppet_submode_type::TurnLeft, turn_anim_speed); } else if(fabs(turn_rate) < 0.001) { set_walk_animation(thing, pup, flags::puppet_submode_type::Stand, 1.0f); } else if(!is_walk_animation_mode(pup, flags::puppet_submode_type::Stand)) { set_walk_animation_speed(pup, turn_anim_speed); } } else if(fabs(vel_lr) > fabs(vel_fb)) { // Strafing left or right if(vel_lr >= 0.0f) { set_walk_animation(thing, pup, flags::puppet_submode_type::StrafeRight, run_anim_speed); } else { set_walk_animation(thing, pup, flags::puppet_submode_type::StrafeLeft, run_anim_speed); } } else if(vel_fb > 0.5f) { // Running forward set_walk_animation(thing, pup, flags::puppet_submode_type::Run, run_anim_speed); } else if(vel_fb > 0.0f) { set_walk_animation(thing, pup, flags::puppet_submode_type::Walk, run_anim_speed); } else { // Walking backwards set_walk_animation(thing, pup, flags::puppet_submode_type::WalkBack, run_anim_speed); } } } void puppet_animation_aspect::update(time_delta, thing_id tid, components::puppet_animations &pup, components::thing &thing) { // Updates the idle animation loop // There are many possible states. This aspect tries to determine how the // entity is moving based on its thing properties. // Create the walk animation, if one does not already exist if(!pup.actor_walk_animation.has_value()) { pup.actor_walk_animation = presenter.key_presenter->play_mode(tid, flags::puppet_submode_type::Stand); maybe_if(pup.actor_walk_animation, [&](auto walk_anim) { for(auto &key_state : ecs.find_component<keys::key_state>(walk_anim)) { key_state.second->flags = flag_set<flags::key_flag>(); } }); } if(static_cast<int>(thing.attach_flags)) { // Thing is standing on a hard surface update_standing_animation(thing, pup); } else { // Thing is in freefall. // If the player has just jumped, the jump animation is already playing. // Check to see if the player has reached apogee: if(dot(thing.vel, make_vector(0.0f, 0.0f, -1.0f)) > 0.0f) { // Thing's trajectory has reached apogee. set_walk_animation(thing, pup, flags::puppet_submode_type::Drop, 1.0f); } } return; }
bd72fe7a8cfdfe0ac538b590eaf6d1c8e7fbb6c0
ab758a6a265f63e9b419a7d26694289efee6f0a1
/Machine 2/machine2.20.09.11/1_loop.ino
404073cdcccbfd8dddc1ea3f7705e86f4c5f7b93
[]
no_license
ElectronsLibres/Metldown
d0a2991e323ab2b33a1e26142326b2ddee4aabf5
5b3ca8bd5a3d4f4f277471a3ce4da47d10b35066
refs/heads/master
2023-01-01T13:22:46.258694
2020-10-20T17:48:30
2020-10-20T17:48:30
294,712,282
0
0
null
null
null
null
UTF-8
C++
false
false
995
ino
1_loop.ino
void loop(){ debug(); udpIn(); if(event){ if(happyhour){ Serial.println("Event: happyhour"); allRandom(happyhour, 65000, 3); } else if(buzzers){ Serial.println("Event: buzzers"); allRandom(buzzers, 40, 7); } else if(konami){ Serial.println("Event: konami"); konamiEffect(); } else{ event = false; reset = true; } } else if(reset){ flash = true; LED.clear(); aleatoire(4, 70); aleatoire(5, 70); aleatoire(6, 100); aleatoire(7, 70); aleatoire(8, 70); aleatoire(9, 70); aleatoire(11, 70); aleatoire(10, 0); aleatoire(12, 0); reset = false; } else{ //-----Routine----- decompte(); flashEffect(); //-----Interactions----- clavierCode(); allumage(); danger(); vert(); rouge(); toggle(); teinte(); konamiCode(); } LED.show(); BOX.show(); delay(10); }
d5c7cc56ca3a3f84c791f2da4f0dcc2500868d01
90612a6ad224838bb6733261dcd262cb305d01fc
/demo/api/protobuf/addressbook.cpp
349a2241a4676f6598247d3657c869039cba14a0
[]
no_license
JelloHuang/note
3cd03ef9cf7cc1047cddc2313fb32538d0f3c607
8489063670f9e4eda4efd4065259ccd669cb6d08
refs/heads/master
2020-12-30T14:44:38.314612
2017-05-09T02:04:15
2017-05-09T02:04:15
91,080,986
0
1
null
2017-05-12T10:38:01
2017-05-12T10:38:01
null
UTF-8
C++
false
false
5,394
cpp
addressbook.cpp
#include <iostream> #include <fstream> #include <string> #include <assert.h> #include <fcntl.h> #include <unistd.h> #include "addressbook.pb.h" using namespace std; using namespace addressbook; int add_person(AddressBook &address_book, const char *name, const char *email, const char *phone_number){ int id = address_book.person_size(); Person *person = address_book.add_person(); person->set_id(id); // getline(cin, *person->mutable_name()); person->set_name(std::string(name)); person->set_email(email); Person::PhoneNumber* phone = person->add_phone(); phone->set_number(phone_number); switch(id % 3){ case 0: phone->set_type(Person::MOBILE); break; case 1: phone->set_type(Person::HOME); break; case 2: phone->set_type(Person::WORK); break; } return 0; } int print(AddressBook &address_book){ for(int i = 0; i < address_book.person_size(); i++){ const Person& person = address_book.person(i); cout << "Person ID: " << person.id() << endl; cout << " Name: " << person.name() << endl; if(person.has_email()){ cout << " E-mail address: " << person.email() << endl; } for(int j = 0; j < person.phone_size(); j++){ const Person::PhoneNumber& phone_number = person.phone(j); switch (phone_number.type()){ case Person::MOBILE: cout << " Mobile phone #: "; break; case Person::HOME: cout << " Home phone #: "; break; case Person::WORK: cout << " Work phone #: "; break; } cout << phone_number.number() << endl; } } return 0; } int mem2string(AddressBook &address_book, std::string &str){ if(address_book.SerializeToString(&str) == false){ fprintf(stderr, "SerializeToString error\n"); return -1; } return 0; } int string2mem(AddressBook &address_book, const std::string &str){ if(address_book.ParseFromString(str) == false){ fprintf(stderr, "ParseFromString error\n"); return -1; } fprintf(stdout, "\nGet from std::string\n"); print(address_book); return 0; } int mem2char(AddressBook &address_book, char *str, int max_size){ if(address_book.SerializeToArray(str, max_size) == false){ fprintf(stderr, "SerializeToArray error\n"); return -1; } return address_book.ByteSize(); } /** * func: read from C char array * para: size: the acutal size of message in Bytes, obtained from pb.ByteSize() **/ int char2mem(AddressBook &address_book, const char *str, int size){ if(address_book.ParseFromArray(str, size) == false){ fprintf(stderr, "ParseFromgArray error\n"); return -1; } fprintf(stdout, "\nGet from C char array\n"); print(address_book); return 0; } // write to file using C++ stream int mem2stream(AddressBook &address_book, const char *path){ fstream output(path, ios::out | ios::trunc | ios::binary); if (!address_book.SerializeToOstream(&output)){ cerr << "Failed to write address book." << endl; return -1; } return 0; } // read from file using C++ stream int stream2mem(AddressBook &address_book, const char* path){ fstream input(path, ios::in | ios::binary); if(!input){ cout << path << ": File not found. Creating a new file." << endl; } if(!address_book.ParseFromIstream(&input)){ cerr << "Failed to parse address book." << endl; return -1; } fprintf(stdout, "\nGet from file using C++ stream\n"); print(address_book); return 0; } int mem2file(AddressBook &address_book, const char *path){ int fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0644); if(fd <= 0){ fprintf(stderr, "open %s error\n", path); return -1; } if(address_book.SerializeToFileDescriptor(fd) == false){ fprintf(stderr, "SerializeToFileDescriptor error\n"); close(fd); return -1; } close(fd); return 0; } int file2mem(AddressBook &address_book, const char *path){ int fd = open(path, O_RDONLY); if(fd <= 0){ fprintf(stderr, "open %s error\n", path); return -1; } if(address_book.ParseFromFileDescriptor(fd) == false){ fprintf(stderr, "ParseFromFileDescriptor error\n"); close(fd); return -1; } close(fd); fprintf(stdout, "\nGet from file\n"); print(address_book); return 0; } int main(){ // Verify that the version of the library that we linked against is compatible with the version of the headers we compiled against. GOOGLE_PROTOBUF_VERIFY_VERSION; AddressBook address_book; int ret = 0; ret = add_person(address_book, "xxx", "xxx@xxx.com", "123456"); assert(ret == 0); fprintf(stdout, "Original data\n"); print(address_book); // std::string container std::string data; ret = mem2string(address_book, data); assert(ret == 0); ret = string2mem(address_book, data); assert(ret == 0); // char container int size = 1000; char *str = new (std::nothrow)char[size]; ret = mem2char(address_book, str, size); assert(ret > 0); ret = char2mem(address_book, str, ret); assert(ret == 0); if(str != NULL){ delete []str; } // stream file container char path[100] = {'\0'}; snprintf(path, 100, "%s", "./addressbook.data.stream"); ret = mem2stream(address_book, path); assert(ret == 0); ret = stream2mem(address_book, path); assert(ret == 0); // file container snprintf(path, 100, "%s", "./addressbook.data.file"); ret = mem2file(address_book, path); assert(ret == 0); ret = file2mem(address_book, path); assert(ret == 0); // Optional: Delete all global objects allocated by libprotobuf google::protobuf::ShutdownProtobufLibrary(); return 0; }
3e3f19726c704f9d2a8476cdae593d71374c17a1
9afd190f4f36b7876e0ab73ac8500719dc231476
/StudyModule/Node.cpp
d42a17353324faa9d637a8dc6350daafb2adb639
[]
no_license
DenBy1726/ModelingFramework
23b75d27cf9aa10c875b07b15cf6d16c177a26ca
00f888dc186e5f03338b631b486de14cb5f26602
refs/heads/master
2022-01-12T02:17:53.239910
2019-05-11T12:27:44
2019-05-11T12:27:44
112,616,758
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
5,012
cpp
Node.cpp
#pragma once #include "Node.h" #include "FIFOQueue.cpp"; namespace Model { Node::Node(Random::IDistribution<double>* dist, int capacity, Queue::IQueue<Transact*>* q) { this->generator = dist; this->Queue = q; this->channel = capacity; this->capacity = capacity; } Node::~Node() { Clear(); delete this->Queue; delete this->generator; } std::vector<Statistic::StateStatisticUnit> Node::GetStateStatistic() { return this->Statistic; } std::vector<Statistic::WorkStatisticUnit> Node::GetWorkStatistic() { return this->WorkStatistic; } //Занят ли канал полностью bool Node::IsBusy() { return capacity == 0; } //свободная емкость int Node::Capacity() { return capacity; } //количество каналов int Node::Channel() { return channel; } //захват канала и порождение события типа С2 Event* Node::Capture(Transact* haveEntered, const int& time) { OnStart(haveEntered->Cell, time); int timeToProcessed = time + this->generator->Next(); //событие возникнет к такту: текущее время + время обработки return new Event(EventId::Processed, haveEntered, timeToProcessed); } ///вызывается при обработке С1 //Попытаться занять канал если он свободен,иначе стать в очередь. В случае если транзакт //занял канал возвращает событие освобождения канала. Event* Node::TryCapture(Transact* haveEntered,const int& time) { Event* happened = nullptr; if (this->capacity == 0) { this->Queue->Add(0, haveEntered); } else { happened = Capture(haveEntered, time); } UpdateState(time); return happened; } //регистрирует зашедший в канал транзакт и начинает попытку занять его Event* Node::BeginCapture(Transact* haveEntered, const int& time) { OnEnter(haveEntered->GetId(), time); haveEntered->Cell = WorkStatistic.size() - 1; return TryCapture(haveEntered, time); } void Node::Register(Transact* haveEntered, const int& time) { OnEnter(haveEntered->GetId(), time); haveEntered->Cell = WorkStatistic.size() - 1; } ///Вызывается при обработке С2 //Освобождает канал и если в канал была загружена новая заявка, возвращает событие //освобождения канала Event* Node::Release(Transact* released,const int& time) { Event* willHappen = nullptr; OnRelease(released->Cell,time); released->Cell = -1; //если к каналу есть очередь, то берем следующую заявку, занимаем канал, и возвращаем //Событие освобождения канала if (Queue->IsEmpty() == false) { Transact* newTransact = Queue->Remove(); willHappen = Capture(newTransact, time); } UpdateState(time); return willHappen; } //Вызывется когда транзакт с номером numberOfTransact вошел в канал void Node::OnEnter(const int& id,const int& time) { WorkStatistic.push_back(Statistic::WorkStatisticUnit()); WorkStatistic[WorkStatistic.size()-1].Enter = time; } //Вызывется когда транзакт с номером numberOfTransact начинает обработку void Node::OnStart(const int& statId, const int& time) { WorkStatistic[statId].Start = time; this->capacity--; } //Вызывется когда транзакт с номером numberOfTransact освобождает канал void Node::OnRelease(const int& statId, const int& time) { WorkStatistic[statId].Release = time; this->capacity++; } //Вызывется когда транзакт начинает обработку void Node::OnStart(Transact* tr, const int& time) { WorkStatistic[tr->Cell].Start = time; this->capacity--; } //Вызывется когда транзакт завершает обработку void Node::OnRelease(Transact* tr, const int& time) { WorkStatistic[tr->Cell].Release = time; this->capacity++; } //очистка канала void Node::Clear() { this->Statistic.clear(); this->WorkStatistic.clear(); this->capacity = channel; } //вызывается всякий раз когда изменяется состояние канала или очереди void Node::UpdateState(const int& time) { Statistic::StateStatisticUnit temp; temp.Busy = channel - this->capacity; temp.Time = time; temp.QueueLength = this->Queue->Length(); this->Statistic.push_back(temp); } Descriptors::NodeDescriptor Node::GetDescriptor() { return Descriptors::NodeDescriptor(Descriptors::DistributionDescriptor(generator->Type(), generator->Argument()),capacity,this->Queue->Type()); } }
3d76b0c4aa33846ddbf82e987043747dc08b00a4
ec16d1aabe05241b68c57967638883668225528e
/tinydb/src/operator/Operator.hpp
9d84136086aa89036d4597913c9a9e3371de7ba3
[ "MIT" ]
permissive
erikmuttersbach/queryoptimization-ss14-tum
9386261c16513af067347069c52cfdbcc187cc74
2650e15d6e147e6d337b304b7b4022171b7ae746
refs/heads/master
2021-01-19T00:13:01.044613
2014-05-11T19:50:46
2014-05-11T19:50:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
801
hpp
Operator.hpp
#ifndef H_operator_Operator #define H_operator_Operator //--------------------------------------------------------------------------- #include <vector> //--------------------------------------------------------------------------- class Register; //--------------------------------------------------------------------------- /// Operator interface class Operator { public: /// Constructor Operator(); /// Destructor virtual ~Operator(); /// Open the operator virtual void open() = 0; /// Produce the next tuple virtual bool next() = 0; /// Close the operator virtual void close() = 0; /// Get all produced values virtual std::vector<const Register*> getOutput() const = 0; }; //--------------------------------------------------------------------------- #endif
9b756b874df73b3437a6f0c582586a5a5f500635
2b2949d69697d633512ce6f27ebc119dca493b30
/jni/application/ScriptReader/SCPlayBGM.cpp
9559fe5ab624d9104ae48304970b5c9bc4128705
[]
no_license
weimingtom/adv_cocos2dx
0adc7f789a1eebb4705cb7b8cd1e462b8c832b3c
c44d643c3a0d53b262871792a334666eca8ad671
refs/heads/master
2021-01-11T02:06:34.457907
2017-06-23T01:07:43
2017-06-23T01:07:43
70,804,972
0
1
null
null
null
null
UTF-8
C++
false
false
401
cpp
SCPlayBGM.cpp
#include "SCPlayBGM.h" #include "BackgroundMusicManager.h" ScriptReader::SCPlayBGM::SCPlayBGM(ScriptReader *reader, std::string key) :key(key) { this->reader = reader; this->type = PlayBGM; } ScriptReader::SCPlayBGM::~SCPlayBGM() { } void ScriptReader::SCPlayBGM::execute(cocos2d::CCNode* stage) { (reader->playBackgroundMusicObj->*reader->playBackgroundMusic)(key); reader->nextScript(); }
f206fc3acab0ff835a0b8909c30eff93230c5502
a64af2820e0418434efb7f12342c7fd911a3af8a
/10041.cpp
c35688f36278da6043baf46d64fa76f9c20ae7f6
[]
no_license
penolove/MystupidC
95fd68301edc56f132c7462f26028bfd1491ae63
f3f49212f89fc108eed5ac476914400a388d4d40
refs/heads/master
2020-12-11T22:16:56.784057
2016-05-06T09:32:06
2016-05-06T09:32:06
54,708,624
1
0
null
null
null
null
UTF-8
C++
false
false
730
cpp
10041.cpp
#include <iostream> #include <algorithm> using namespace std; int main(void) { int a; cin >> a; int q; int result[a]; int temp for(int i=0;i<a;i++){ //array size cin >> q; //array record s_i,s_j int w[q]; for (int j=0;j<q;j++){ cin >> w[j]; } //sort w sort(w,w+q); //calculate the sum of distance temp=0; if(q%2 == 0){ for (int j=0;j<q;j++){ temp=temp+abs(w[j]-w[(q/2)-1]); } result[i]=temp; }else{ for (int j=0;j<q;j++){ temp=temp+abs(w[j]-w[((q-1)/2)+1-1]); } result[i]=temp; } } for(int i=0;i<a;i++){ cout<<result[i]<<"\n"; } }
53f9b1f5ff356c9fc946f495c71d4012bd305c3e
8505106f68aa49e2cd1faadf0c5c5e5acbc88daa
/src/dictionary/user_dictionary_storage_test.cc
080f6bfff2fa227fa53df9e6bad9c31760b13abb
[ "BSD-3-Clause", "LicenseRef-scancode-unicode", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
rekikananlp/mozc
c5f597e731c6159b141cd676f396ee12e3d629f9
7f0169605e8ae71b694dcd618c7ebc90d79045cc
refs/heads/master
2022-01-08T17:59:31.712655
2019-06-22T12:15:30
2019-06-22T12:15:30
176,789,667
1
0
Apache-2.0
2019-06-22T12:15:31
2019-03-20T18:00:45
C++
UTF-8
C++
false
false
17,515
cc
user_dictionary_storage_test.cc
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. #include "dictionary/user_dictionary_storage.h" #include <string> #include <vector> #include "base/file_stream.h" #include "base/file_util.h" #include "base/logging.h" #include "base/mmap.h" #include "base/system_util.h" #include "base/util.h" #include "dictionary/user_dictionary_importer.h" #include "dictionary/user_dictionary_util.h" #include "testing/base/public/googletest.h" #include "testing/base/public/gunit.h" DECLARE_string(test_tmpdir); namespace mozc { namespace { using user_dictionary::UserDictionary; string GenRandomString(int size) { string result; const size_t len = Util::Random(size) + 1; for (int i = 0; i < len; ++i) { const char32 l = static_cast<char32>(Util::Random(static_cast<int>('~' - ' ')) + ' '); Util::UCS4ToUTF8Append(l, &result); } return result; } } // namespace class UserDictionaryStorageTest : public ::testing::Test { protected: virtual void SetUp() { backup_user_profile_directory_ = SystemUtil::GetUserProfileDirectory(); SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir); FileUtil::Unlink(GetUserDictionaryFile()); } virtual void TearDown() { FileUtil::Unlink(GetUserDictionaryFile()); SystemUtil::SetUserProfileDirectory(backup_user_profile_directory_); } static string GetUserDictionaryFile() { return FileUtil::JoinPath(FLAGS_test_tmpdir, "test.db"); } private: string backup_user_profile_directory_; }; TEST_F(UserDictionaryStorageTest, FileTest) { UserDictionaryStorage storage(GetUserDictionaryFile()); EXPECT_EQ(storage.filename(), GetUserDictionaryFile()); EXPECT_FALSE(storage.Exists()); } TEST_F(UserDictionaryStorageTest, LockTest) { UserDictionaryStorage storage1(GetUserDictionaryFile()); UserDictionaryStorage storage2(GetUserDictionaryFile()); EXPECT_FALSE(storage1.Save()); EXPECT_FALSE(storage2.Save()); EXPECT_TRUE(storage1.Lock()); EXPECT_FALSE(storage2.Lock()); EXPECT_TRUE(storage1.Save()); EXPECT_FALSE(storage2.Save()); EXPECT_TRUE(storage1.UnLock()); EXPECT_FALSE(storage1.Save()); EXPECT_FALSE(storage2.Save()); EXPECT_TRUE(storage2.Lock()); EXPECT_FALSE(storage1.Save()); EXPECT_TRUE(storage2.Save()); } TEST_F(UserDictionaryStorageTest, BasicOperationsTest) { UserDictionaryStorage storage(GetUserDictionaryFile()); EXPECT_FALSE(storage.Load()); const size_t kDictionariesSize = 3; uint64 id[kDictionariesSize]; const size_t dict_size = storage.dictionaries_size(); for (size_t i = 0; i < kDictionariesSize; ++i) { EXPECT_TRUE(storage.CreateDictionary( "test" + std::to_string(static_cast<uint32>(i)), &id[i])); EXPECT_EQ(i + 1 + dict_size, storage.dictionaries_size()); } for (size_t i = 0; i < kDictionariesSize; ++i) { EXPECT_EQ(i + dict_size, storage.GetUserDictionaryIndex(id[i])); EXPECT_EQ(-1, storage.GetUserDictionaryIndex(id[i] + 1)); } for (size_t i = 0; i < kDictionariesSize; ++i) { EXPECT_EQ(storage.mutable_dictionaries(i + dict_size), storage.GetUserDictionary(id[i])); EXPECT_EQ(NULL, storage.GetUserDictionary(id[i] + 1)); } // empty EXPECT_FALSE(storage.RenameDictionary(id[0], "")); // duplicated uint64 tmp_id = 0; EXPECT_FALSE(storage.CreateDictionary("test0", &tmp_id)); EXPECT_EQ(UserDictionaryStorage::DUPLICATED_DICTIONARY_NAME, storage.GetLastError()); // invalid id EXPECT_FALSE(storage.RenameDictionary(0, "")); // duplicated EXPECT_FALSE(storage.RenameDictionary(id[0], "test1")); EXPECT_EQ(UserDictionaryStorage::DUPLICATED_DICTIONARY_NAME, storage.GetLastError()); // no name EXPECT_TRUE(storage.RenameDictionary(id[0], "test0")); EXPECT_TRUE(storage.RenameDictionary(id[0], "renamed0")); EXPECT_EQ("renamed0", storage.GetUserDictionary(id[0])->name()); // invalid id EXPECT_FALSE(storage.DeleteDictionary(0)); EXPECT_TRUE(storage.DeleteDictionary(id[1])); EXPECT_EQ(kDictionariesSize + dict_size - 1, storage.dictionaries_size()); } TEST_F(UserDictionaryStorageTest, DeleteTest) { UserDictionaryStorage storage(GetUserDictionaryFile()); EXPECT_FALSE(storage.Load()); // repeat 10 times for (int i = 0; i < 10; ++i) { storage.Clear(); std::vector<uint64> ids(100); for (size_t i = 0; i < ids.size(); ++i) { EXPECT_TRUE(storage.CreateDictionary( "test" + std::to_string(static_cast<uint32>(i)), &ids[i])); } std::vector<uint64> alive; for (size_t i = 0; i < ids.size(); ++i) { if (Util::Random(3) == 0) { // 33% EXPECT_TRUE(storage.DeleteDictionary(ids[i])); continue; } alive.push_back(ids[i]); } EXPECT_EQ(alive.size(), storage.dictionaries_size()); for (size_t i = 0; i < alive.size(); ++i) { EXPECT_EQ(alive[i], storage.dictionaries(i).id()); } } } TEST_F(UserDictionaryStorageTest, ExportTest) { UserDictionaryStorage storage(GetUserDictionaryFile()); uint64 id = 0; EXPECT_TRUE(storage.CreateDictionary("test", &id)); UserDictionaryStorage::UserDictionary *dic = storage.GetUserDictionary(id); for (size_t i = 0; i < 1000; ++i) { UserDictionaryStorage::UserDictionaryEntry *entry = dic->add_entries(); const string prefix = std::to_string(static_cast<uint32>(i)); // set empty fields randomly entry->set_key(prefix + "key"); entry->set_value(prefix + "value"); // "名詞" entry->set_pos(UserDictionary::NOUN); entry->set_comment(prefix + "comment"); } const string export_file = FileUtil::JoinPath(FLAGS_test_tmpdir, "export.txt"); EXPECT_FALSE(storage.ExportDictionary(id + 1, export_file)); EXPECT_TRUE(storage.ExportDictionary(id, export_file)); string file_string; // Copy whole contents of the file into |file_string|. { InputFileStream ifs(export_file.c_str()); CHECK(ifs); ifs.seekg(0, std::ios::end); file_string.resize(ifs.tellg()); ifs.seekg(0, std::ios::beg); ifs.read(&file_string[0], file_string.size()); ifs.close(); } UserDictionaryImporter::StringTextLineIterator iter(file_string); UserDictionaryStorage::UserDictionary dic2; EXPECT_EQ(UserDictionaryImporter::IMPORT_NO_ERROR, UserDictionaryImporter::ImportFromTextLineIterator( UserDictionaryImporter::MOZC, &iter, &dic2)); dic2.set_id(id); dic2.set_name("test"); EXPECT_EQ(dic2.DebugString(), dic->DebugString()); } TEST_F(UserDictionaryStorageTest, SerializeTest) { // repeat 20 times for (int i = 0; i < 20; ++i) { FileUtil::Unlink(GetUserDictionaryFile()); UserDictionaryStorage storage1(GetUserDictionaryFile()); { EXPECT_FALSE(storage1.Load()); const size_t dic_size = Util::Random(50) + 1; for (size_t i = 0; i < dic_size; ++i) { uint64 id = 0; EXPECT_TRUE( storage1.CreateDictionary( "test" + std::to_string(static_cast<uint32>(i)), &id)); const size_t entry_size = Util::Random(100) + 1; for (size_t j = 0; j < entry_size; ++j) { UserDictionaryStorage::UserDictionary *dic = storage1.mutable_dictionaries(i); UserDictionaryStorage::UserDictionaryEntry *entry = dic->add_entries(); entry->set_key(GenRandomString(10)); entry->set_value(GenRandomString(10)); entry->set_pos(UserDictionary::NOUN); entry->set_comment(GenRandomString(10)); } } EXPECT_TRUE(storage1.Lock()); EXPECT_TRUE(storage1.Save()); EXPECT_TRUE(storage1.UnLock()); } UserDictionaryStorage storage2(GetUserDictionaryFile()); { EXPECT_TRUE(storage2.Load()); } EXPECT_EQ(storage1.DebugString(), storage2.DebugString()); } } TEST_F(UserDictionaryStorageTest, GetUserDictionaryIdTest) { UserDictionaryStorage storage(GetUserDictionaryFile()); EXPECT_FALSE(storage.Load()); const size_t kDictionariesSize = 3; uint64 id[kDictionariesSize]; EXPECT_TRUE(storage.CreateDictionary("testA", &id[0])); EXPECT_TRUE(storage.CreateDictionary("testB", &id[1])); uint64 ret_id[kDictionariesSize]; EXPECT_TRUE(storage.GetUserDictionaryId("testA", &ret_id[0])); EXPECT_TRUE(storage.GetUserDictionaryId("testB", &ret_id[1])); EXPECT_FALSE(storage.GetUserDictionaryId("testC", &ret_id[2])); EXPECT_EQ(ret_id[0], id[0]); EXPECT_EQ(ret_id[1], id[1]); } TEST_F(UserDictionaryStorageTest, ConvertSyncDictionariesToNormalDictionaries) { // "名詞" const UserDictionary::PosType kPos = UserDictionary::NOUN; const struct TestData { bool is_sync_dictionary; bool is_removed_dictionary; bool has_normal_entry; bool has_removed_entry; string dictionary_name; } test_data[] = { { false, false, false, false, "non-sync dictionary (empty)" }, { false, false, true, false, "non-sync dictionary (normal entry)" }, { true, false, false, false, "sync dictionary (empty)" }, { true, false, false, true, "sync dictionary (removed entry)" }, { true, false, true, false, "sync dictionary (normal entry)" }, { true, false, true, true, "sync dictionary (normal & removed entries)" }, { true, true, false, false, "removed sync dictionary (empty)" }, { true, true, false, true, "removed sync dictionary (removed entry)" }, { true, true, true, false, "removed sync dictionary (normal entry)" }, { true, true, true, true, "removed sync dictionary (normal & removed entries)" }, { true, false, true, false, UserDictionaryStorage::default_sync_dictionary_name() }, }; UserDictionaryStorage storage(GetUserDictionaryFile()); EXPECT_FALSE(storage.Load()) << "At first, we expect there is not user dictionary file."; EXPECT_FALSE(storage.ConvertSyncDictionariesToNormalDictionaries()) << "No sync dictionary available."; for (size_t i = 0; i < arraysize(test_data); ++i) { SCOPED_TRACE(Util::StringPrintf("add %d", static_cast<int>(i))); const TestData &data = test_data[i]; CHECK(data.is_sync_dictionary || !(data.is_removed_dictionary || data.has_removed_entry)) << "Non-sync dictionary should NOT have removed dictionary / entry."; uint64 dict_id = 0; ASSERT_TRUE(storage.CreateDictionary(data.dictionary_name, &dict_id)); UserDictionaryStorage::UserDictionary *dict = storage.mutable_dictionaries(storage.GetUserDictionaryIndex(dict_id)); dict->set_syncable(data.is_sync_dictionary); dict->set_removed(data.is_removed_dictionary); if (data.has_normal_entry) { UserDictionaryStorage::UserDictionaryEntry *entry = dict->add_entries(); entry->set_key("normal"); entry->set_value("normal entry"); entry->set_pos(kPos); } if (data.has_removed_entry) { UserDictionaryStorage::UserDictionaryEntry *entry = dict->add_entries(); entry->set_key("removed"); entry->set_value("removed entry"); entry->set_pos(kPos); entry->set_removed(true); } } EXPECT_EQ(9, UserDictionaryStorage::CountSyncableDictionaries(storage)); ASSERT_TRUE(storage.ConvertSyncDictionariesToNormalDictionaries()); const char kDictionaryNameConvertedFromSyncableDictionary[] = "同期用辞書"; const struct ExpectedData { bool has_normal_entry; string dictionary_name; } expected_data[] = { { false, "non-sync dictionary (empty)" }, { true, "non-sync dictionary (normal entry)" }, { true, "sync dictionary (normal entry)" }, { true, "sync dictionary (normal & removed entries)" }, { true, kDictionaryNameConvertedFromSyncableDictionary }, }; EXPECT_EQ(0, UserDictionaryStorage::CountSyncableDictionaries(storage)); ASSERT_EQ(arraysize(expected_data), storage.dictionaries_size()); for (size_t i = 0; i < arraysize(expected_data); ++i) { SCOPED_TRACE(Util::StringPrintf("verify %d", static_cast<int>(i))); const ExpectedData &expected = expected_data[i]; const UserDictionaryStorage::UserDictionary &dict = storage.dictionaries(i); EXPECT_EQ(expected.dictionary_name, dict.name()); EXPECT_FALSE(dict.syncable()); EXPECT_FALSE(dict.removed()); if (expected.has_normal_entry) { ASSERT_EQ(1, dict.entries_size()); EXPECT_EQ("normal", dict.entries(0).key()); } else { EXPECT_EQ(0, dict.entries_size()); } } // Test duplicated dictionary name. storage.Clear(); { uint64 dict_id = 0; storage.CreateDictionary( UserDictionaryStorage::default_sync_dictionary_name(), &dict_id); storage.CreateDictionary( kDictionaryNameConvertedFromSyncableDictionary, &dict_id); ASSERT_EQ(2, storage.dictionaries_size()); UserDictionaryStorage::UserDictionary *dict; dict = storage.mutable_dictionaries(0); dict->set_syncable(true); dict->add_entries()->set_key("0"); dict = storage.mutable_dictionaries(1); dict->set_syncable(false); dict->add_entries()->set_key("1"); } ASSERT_TRUE(storage.ConvertSyncDictionariesToNormalDictionaries()); EXPECT_EQ(0, UserDictionaryStorage::CountSyncableDictionaries(storage)); EXPECT_EQ(2, storage.dictionaries_size()); EXPECT_EQ(Util::StringPrintf("%s_1", kDictionaryNameConvertedFromSyncableDictionary), storage.dictionaries(0).name()); EXPECT_EQ(kDictionaryNameConvertedFromSyncableDictionary, storage.dictionaries(1).name()); } TEST_F(UserDictionaryStorageTest, AddToAutoRegisteredDictionary) { { UserDictionaryStorage storage(GetUserDictionaryFile()); EXPECT_EQ(0, storage.dictionaries_size()); EXPECT_TRUE(storage.AddToAutoRegisteredDictionary( "key1", "value1", UserDictionary::NOUN)); EXPECT_EQ(1, storage.dictionaries_size()); EXPECT_EQ(1, storage.dictionaries(0).entries_size()); const UserDictionaryStorage::UserDictionaryEntry &entry1 = storage.dictionaries(0).entries(0); EXPECT_EQ("key1", entry1.key()); EXPECT_EQ("value1", entry1.value()); EXPECT_EQ(UserDictionary::NOUN, entry1.pos()); EXPECT_TRUE(entry1.auto_registered()); EXPECT_TRUE(storage.AddToAutoRegisteredDictionary( "key2", "value2", UserDictionary::NOUN)); EXPECT_EQ(1, storage.dictionaries_size()); EXPECT_EQ(2, storage.dictionaries(0).entries_size()); const UserDictionaryStorage::UserDictionaryEntry &entry2 = storage.dictionaries(0).entries(1); EXPECT_EQ("key2", entry2.key()); EXPECT_EQ("value2", entry2.value()); EXPECT_EQ(UserDictionary::NOUN, entry2.pos()); EXPECT_TRUE(entry1.auto_registered()); } { FileUtil::Unlink(GetUserDictionaryFile()); UserDictionaryStorage storage(GetUserDictionaryFile()); storage.Lock(); // Already locked. EXPECT_FALSE(storage.AddToAutoRegisteredDictionary( "key", "value", UserDictionary::NOUN)); } } TEST_F(UserDictionaryStorageTest, Export) { const int kDummyDictionaryId = 10; const string kPath = FileUtil::JoinPath(FLAGS_test_tmpdir, "exported_file"); { UserDictionaryStorage storage(GetUserDictionaryFile()); { UserDictionary *dictionary = storage.add_dictionaries(); dictionary->set_id(kDummyDictionaryId); UserDictionary::Entry *entry = dictionary->add_entries(); entry->set_key("key"); entry->set_value("value"); entry->set_pos(UserDictionary::NOUN); entry->set_comment("comment"); } storage.ExportDictionary(kDummyDictionaryId, kPath); } Mmap mapped_data; ASSERT_TRUE(mapped_data.Open(kPath.c_str())); // Make sure the exported format, especially that the pos is exported in // Japanese. #ifdef OS_WIN EXPECT_EQ("key\tvalue\t名詞\tcomment\r\n", string(mapped_data.begin(), mapped_data.size())); #else EXPECT_EQ("key\tvalue\t名詞\tcomment\n", string(mapped_data.begin(), mapped_data.size())); #endif // OS_WIN } } // namespace mozc
2eef149966c9f67ea33ccf5b9298710f6a07d4b1
74f8ae27f782b75c2e91c9188e94aa2d9f849138
/main.cpp
56a0a0284ecd5e33558492650b8f900b134e5c41
[]
no_license
buptVivian/SFC
e2ca775ea894562b3e1065a5b3e372fc7cb1d7d8
a4102778f0d9ef86d1f1a5f1aa68a62bcf062272
refs/heads/master
2021-01-19T03:35:39.262286
2017-08-21T15:46:27
2017-08-21T15:46:27
87,326,229
0
0
null
null
null
null
UTF-8
C++
false
false
1,205
cpp
main.cpp
// // main.cpp // SFC // // Created by vivian_bytedance on 2017/7/6. // Copyright © 2017年 vivian_bytedance. All rights reserved. // //test //#include "test7_10.hpp" #include "simulation.hpp" int main() { //for test 2017.7.10 //写文件 ofstream ofile; ofile.open("/Users/vivian_bytedance/Documents/VNF/code/result/re5.txt", ios::out); if (!ofile) { cout << "open result file error!" << endl; exit(-2); } //初始vnf计算资源消耗,初始rf{1,10} srand((unsigned)time(0)); for (int i = 0;i<M;i++) { rf[i]=rand()%10+1; //test cout<<rf[i]<<" "; } //不断增大业务强度(提高到达率,离去率保持不变) for (double lamda = 10; lamda <20; lamda += 1)// lamda越大,时间间隔越短 { clock_t start = clock(); cout <<"到达率"<<lamda<<endl; initialize(1.0/lamda); run(ofile); clock_t end = clock(); double result = (double)(end - start) / CLOCKS_PER_SEC; cout << result << "s" << endl; } ofile.close(); system("pause"); cout << "finished" << endl; return 0; }
2d24684563694fb8753af1ec432c0b89557d660f
32f0ae8c436e475ed727d6363fe4bbf5dcf7d866
/src/common/src/values/NotificationValue.cpp
e79ccaf10a8ef023c4f40885e0f6e75854b653ef
[]
no_license
vvsosed/JsonStreamParser
61744348b9c7e7bfe5c5358dc21642edeb6618ec
a076e9f5ae66a4c23b2e798f392f4ef10c2465e2
refs/heads/master
2020-09-24T04:15:40.611992
2019-12-09T09:17:32
2019-12-09T09:17:32
225,660,270
0
0
null
null
null
null
UTF-8
C++
false
false
1,192
cpp
NotificationValue.cpp
#include <values/NotificationValue.h> #include <IValueCast.h> namespace common { NotificationValue::NotificationValue( uint8_t v1AlarmType, uint8_t v1AlarmLevel, const uint8_t* data, uint8_t dataSize ) : m_v1AlarmType( v1AlarmType ) , m_v1AlarmLevel( v1AlarmLevel ) , m_data( &data[0u], &data[dataSize] ) {} NotificationValue::NotificationValue( uint8_t v1AlarmType, uint8_t v1AlarmLevel, BlobType&& data ) : m_v1AlarmType( v1AlarmType ) , m_v1AlarmLevel( v1AlarmLevel ) , m_data( std::move( data ) ) {} void NotificationValue::accept( IValueVisitorConst& visitor ) const { visitor.visit( *this ); } void NotificationValue::accept( IValueVisitor& visitor ) { visitor.visit( *this ); } bool NotificationValue::operator==( const IValue& value ) const { auto notifVal = iValueCast<NotificationValue>( &value ); if( !notifVal ) { return false; } return m_v1AlarmType == notifVal->m_v1AlarmType && m_v1AlarmLevel == notifVal->m_v1AlarmLevel; } } // namespace common