blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
7c24b2af7e35404c20e6df0dd32ee3e75c14153d
C++
AtwoodHuang/clean_LSTM
/ConsoleApplication4/lstm.cpp
UTF-8
8,861
2.734375
3
[]
no_license
#include"LSTM.h" #include<cmath> #include<assert.h> Matrix bottom_diff(const Matrix &pred, const Matrix &label) { assert(pred.size() == label.size() && pred[0].size() == 1 && label[0].size() == 1); Matrix result = pred; for (int i = 0; i < pred.size(); ++i) { result[i][0] = 2.0*(pred[i][0] - label[i][0]); } return result; } Matrix sigmoid(const Matrix& x) { assert(x[0].size() == 1); Matrix result = x; for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = 1.0 / (1.0 + exp(-1.0*x[i][j])); } } return result; } Matrix Tanh(const Matrix& x) { assert(x[0].size() == 1); Matrix result = x; for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = tanh(x[i][j]); } } return result; } Matrix sigmoid_d(const Matrix& value) { assert(value[0].size() == 1); Matrix result = value; for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = value[i][j] * (1 - value[i][j]); } } return result; } Matrix Tanh_d(const Matrix & value) { assert(value[0].size() == 1); Matrix result = value; for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = 1 - value[i][j] * value[i][j]; } } return result; } Matrix MatrixT(const Matrix& x) { Matrix result(x[0].size()); for (int i = 0; i < result.size(); ++i) { result[i].resize(x.size()); } for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = x[j][i]; } } return result; } Matrix MatrixOuter(const Matrix& one, const Matrix& two) { assert(one[0].size() == 1 && two[0].size() == 1); Matrix result(one.size()); for (int i = 0; i < one.size(); ++i) { result[i].resize(two.size()); } for (int i = 0; i < one.size(); ++i) { for (int j = 0; j < two.size(); ++j) { result[i][j] = one[i][0] * two[j][0]; } } return result; } void NumMutiMatrix(double lr, Matrix &matrix_i, const std::vector<std::vector<double>> &matrix_diff) { assert(matrix_i.size() == matrix_diff.size() && matrix_i[0].size() == matrix_diff[0].size()); for (int i = 0; i< matrix_i.size(); ++i) { for (int j = 0; j < matrix_i[0].size(); ++j) { matrix_i[i][j] -= lr*matrix_diff[i][j]; } } } Matrix MatrixMutiMatrix(const Matrix &one, const Matrix &two) { assert(one[0].size() == two.size()); Matrix result; result.resize(one.size()); for (int i = 0; i < result.size(); ++i) { result[i].resize(two[0].size()); } for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { double a = 0.0; for (int m = 0; m < two.size(); ++m) { a += one[i][m] * two[m][j]; } result[i][j] = a; } } return result; } Matrix MatrixPluMatrix(const Matrix &one, const Matrix &two) { assert(one.size() == two.size() && one[0].size() == two[0].size()); Matrix result = one; for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = one[i][j] + two[i][j]; } } return result; } Matrix MatrixDianMatrix(const Matrix &one, const Matrix &two) { assert(one.size() == two.size() && one[0].size() == two[0].size()); Matrix result = one; for (int i = 0; i < result.size(); ++i) { for (int j = 0; j < result[0].size(); ++j) { result[i][j] = one[i][j] * two[i][j]; } } return result; } void setMatixToZero(Matrix& matrix) { for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) matrix[i][j] = 0; } } void LstmParam::apply_diff(double lr) { NumMutiMatrix(lr, wop, wop_diff); NumMutiMatrix(lr, wg, wg_diff); NumMutiMatrix(lr, wi, wi_diff); NumMutiMatrix(lr, wf, wf_diff); NumMutiMatrix(lr, wo, wo_diff); NumMutiMatrix(lr, bop, bop_diff); NumMutiMatrix(lr, bg, bg_diff); NumMutiMatrix(lr, bi, bi_diff); NumMutiMatrix(lr, bf, bf_diff); NumMutiMatrix(lr, bo, bo_diff); setMatixToZero(wop_diff); setMatixToZero(wg_diff); setMatixToZero(wi_diff); setMatixToZero(wf_diff); setMatixToZero(wo_diff); setMatixToZero(bop_diff); setMatixToZero(bg_diff); setMatixToZero(bi_diff); setMatixToZero(bf_diff); setMatixToZero(bo_diff); } void LstmNode::bottom_data_is(const Matrix &x, const Matrix &s_prev_i, const Matrix &h_prev_i) { h_prev = h_prev_i; s_prev = s_prev_i; xc = x; xc.insert(xc.end(), h_prev.begin(), h_prev.end()); My_state.g = Tanh(MatrixPluMatrix(MatrixMutiMatrix(LstmNetwork::My_param.wg, xc), LstmNetwork::My_param.bg)); My_state.i = sigmoid(MatrixPluMatrix(MatrixMutiMatrix(LstmNetwork::My_param.wi, xc), LstmNetwork::My_param.bi)); My_state.f = sigmoid(MatrixPluMatrix(MatrixMutiMatrix(LstmNetwork::My_param.wf, xc), LstmNetwork::My_param.bf)); My_state.o = sigmoid(MatrixPluMatrix(MatrixMutiMatrix(LstmNetwork::My_param.wo, xc), LstmNetwork::My_param.bo)); My_state.s = MatrixPluMatrix(MatrixDianMatrix(My_state.g, My_state.i), MatrixDianMatrix(s_prev, My_state.f)); My_state.h = MatrixDianMatrix(My_state.s, My_state.o); My_state.y = MatrixPluMatrix(MatrixMutiMatrix(LstmNetwork::My_param.wop, My_state.h), LstmNetwork::My_param.bop); } void LstmNode::top_diff_is(const Matrix &top_diff_h, const Matrix &top_diff_s, const Matrix &top_diff_y) { Matrix ds = MatrixPluMatrix(MatrixDianMatrix(My_state.o, top_diff_h), top_diff_s); Matrix dO = MatrixDianMatrix(My_state.s, top_diff_h); Matrix di = MatrixDianMatrix(My_state.g, ds); Matrix dg = MatrixDianMatrix(My_state.i, ds); Matrix df = MatrixDianMatrix(s_prev, ds); Matrix di_input = MatrixDianMatrix(sigmoid_d(My_state.i), di); Matrix df_input = MatrixDianMatrix(sigmoid_d(My_state.f), df); Matrix do_input = MatrixDianMatrix(sigmoid_d(My_state.o), dO); Matrix dg_input = MatrixDianMatrix(Tanh_d(My_state.g), dg); LstmNetwork::My_param.wop_diff = MatrixPluMatrix(LstmNetwork::My_param.wop_diff, MatrixOuter(top_diff_y, My_state.h)); LstmNetwork::My_param.wi_diff = MatrixPluMatrix(LstmNetwork::My_param.wi_diff, MatrixOuter(di_input, xc)); LstmNetwork::My_param.wf_diff = MatrixPluMatrix(LstmNetwork::My_param.wf_diff, MatrixOuter(df_input, xc)); LstmNetwork::My_param.wo_diff = MatrixPluMatrix(LstmNetwork::My_param.wo_diff, MatrixOuter(do_input, xc)); LstmNetwork::My_param.wg_diff = MatrixPluMatrix(LstmNetwork::My_param.wg_diff, MatrixOuter(dg_input, xc)); LstmNetwork::My_param.bop_diff = MatrixPluMatrix(LstmNetwork::My_param.bop_diff, top_diff_y); LstmNetwork::My_param.bi_diff = MatrixPluMatrix(LstmNetwork::My_param.bi_diff, di_input); LstmNetwork::My_param.bf_diff = MatrixPluMatrix(LstmNetwork::My_param.bf_diff, df_input); LstmNetwork::My_param.bo_diff = MatrixPluMatrix(LstmNetwork::My_param.bo_diff, do_input); LstmNetwork::My_param.bg_diff = MatrixPluMatrix(LstmNetwork::My_param.bg_diff, dg_input); Matrix dxc = xc; for (auto &a : dxc) { for (auto &b : a) { b = 0; } } dxc = MatrixPluMatrix(dxc, MatrixMutiMatrix(MatrixT(LstmNetwork::My_param.wi), di_input)); dxc = MatrixPluMatrix(dxc, MatrixMutiMatrix(MatrixT(LstmNetwork::My_param.wf), df_input)); dxc = MatrixPluMatrix(dxc, MatrixMutiMatrix(MatrixT(LstmNetwork::My_param.wo), do_input)); dxc = MatrixPluMatrix(dxc, MatrixMutiMatrix(MatrixT(LstmNetwork::My_param.wg), dg_input)); My_state.bottom_diff_s = MatrixDianMatrix(ds, My_state.f); My_state.bottom_diff_h.assign(dxc.begin() + LstmNetwork::My_param.x_dim, dxc.end()); } void LstmNetwork::y_list_is(std::vector<Matrix> y, Matrix(*bottom_diff)(const Matrix&, const Matrix&)) { int idx = time - 1; Matrix diff_y = bottom_diff(NodeList[idx].My_state.y, y[idx]); Matrix diff_h = MatrixMutiMatrix(MatrixT(LstmNetwork::My_param.wop), diff_y); Matrix diff_s = NodeList[idx].My_state.bottom_diff_s; NodeList[idx].top_diff_is(diff_h, diff_s, diff_y); idx -= 1; while (idx >= 0) { diff_y = bottom_diff(NodeList[idx].My_state.y, y[idx]); diff_h = MatrixMutiMatrix(MatrixT(LstmNetwork::My_param.wop), diff_y); diff_h = MatrixPluMatrix(diff_h, NodeList[idx + 1].My_state.bottom_diff_h); diff_s = NodeList[idx + 1].My_state.bottom_diff_s; NodeList[idx].top_diff_is(diff_h, diff_s, diff_y); idx -= 1; } } void LstmNetwork::x_list_add(const Matrix &x) { LstmState temp(LstmNetwork::My_param.mem_cell_ct, LstmNetwork::My_param.x_dim, LstmNetwork::My_param.y_dim); NodeList.push_back(LstmNode(temp)); time += 1; int idx = time - 1; if (idx == 0) { Matrix s_prve(LstmNetwork::My_param.mem_cell_ct); Matrix h_prve(LstmNetwork::My_param.mem_cell_ct); for (int j = 0; j < LstmNetwork::My_param.mem_cell_ct; ++j) { s_prve[j].assign(1, 0); h_prve[j].assign(1, 0); } NodeList[idx].bottom_data_is(x, s_prve, h_prve); } else { Matrix s_prve = NodeList[idx - 1].My_state.s; Matrix h_prve = NodeList[idx - 1].My_state.h; NodeList[idx].bottom_data_is(x, s_prve, h_prve); } }
true
775cb84cda7c5585a9eb2c7143b766ccfa5d65a7
C++
schuay/gpu_architectures_and_computing
/src/consolidate.hpp
UTF-8
716
2.59375
3
[]
no_license
#ifndef __CONSOLIDATE_H #define __CONSOLIDATE_H #include <thrust/device_ptr.h> extern "C" { #include "sigpt.h" } /** * Given two incoming signals lhs and rhs, consolidate * builds a merged time sequence containing all points * of both signals plus all intersection points between both signals. * The output signals are constructed using interpolation and * contain all of these time points. */ void consolidate(const thrust::device_ptr<sigpt_t> &lhs, const int nlhs, const thrust::device_ptr<sigpt_t> &rhs, const int nrhs, thrust::device_ptr<sigpt_t> *olhs, thrust::device_ptr<sigpt_t> *orhs, int *nout); #endif /* __CONSOLIDATE_H */
true
c6ac792302adba04b63946aa8d680e64e471e606
C++
15831944/Pipe
/Pipe/TypeDef.h
SHIFT_JIS
3,901
2.875
3
[]
no_license
#pragma once namespace aht { // enum result{ rOk, rFail, rCancel, rNotExistBar, rNotExistPosition, rOutOfMemory, rInvalidOpenRate, rInvalidStopLoss, rInvalidLimit, rFailToOpenFile, rExistChart, rNotExistChart, rNotExistStrategy, rAlreadyRegistered, rFailToLoadStrategy, rFailToLoadIndicator, rFailToLoadCustomIndicator, rNotExistOrder, rOrderIsContracted, rNotExtistTestResult }; // o[ enum barKind{ bid = 0, ask = 4, middle = 8 }; // [g enum rateKind{ open, high, low, close }; // Ԙg enum timeFrame{ tick = 0, m1 = 1, m5 = 5, m10 = 10, m15 = 15, m30 = 30, h1 = 60, h4 = 240, d1 = 1440, w1 = 10080, mn1 = 43200 }; // Kpi enum typicalPrice{ O, H, L, C, HL, HLC, HLCC, HLCCC }; // |WVTCh enum positionSide{ flat, buy, sell }; // enum operation{ buyMarket, sellMarket, buyLimit, sellLimit, buyStop, sellStop }; // |WV enum positionKind{ simulation, real }; // |WV enum positionState{ psOrdering, // psOpen, // psClose, // ύς psCancel // LZ }; // enum trade{ longAndShort, longOnly, shortOnly, numOfTradeType }; // enum limitOrder{ oneEntryOneExit, // Eǂ炩1 onlyOneEntryEachBuyAndSell, // Eꂼ1 unlimitedEntry // }; // [gpX enum ratePath{ simple, detailBar, openOnly }; // eXg[h enum testMode{ bidOnly, bidAsk }; // ڍ׃o[ʒu enum detailBarLocation{ prev, // ڍ׃o[̓Co[̎ԑO inTime, // ڍ׃o[̓Co[̎Ԓ after // ڍ׃o[̓Co[̎Ԍ }; // őh[_E enum maxDDKind{ realizedLoss, // m葹 realizedProfitLossToUnRealizedLoss, // m葹v|܂ݑ numOfMaxDDKind // ސ }; // Y enum equityKind{ realizedProfitLoss, // m葹v unRealizedProfit, // ܂݉v unRealizedLoss, // ܂ݑ numOfEquityKind // ސ }; // for_each ̈ȗev[g֐ template <typename T_container, typename T_function> T_function for_each(T_container& rcontainer, T_function function) { return std::for_each(rcontainer.begin(), rcontainer.end(), function); } // t for_each JԂIꍇfunctiontrueԂ template <typename T_container, typename T_function> void for_each_if(T_container& rcontainer, T_function function) { std::find_if(rcontainer.begin(), rcontainer.end(), function); } // |C^[LXg template<class T> T pointer_cast(LPVOID p){ return static_cast<T>(p); } /////////////////////////////////////////////////////// // // STL^Cv` typedef std::basic_ofstream<TCHAR> tofstream; typedef std::basic_ifstream<TCHAR, std::char_traits<TCHAR> > tifstream; typedef std::basic_string< TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tstring; typedef std::vector<double> vecDouble; typedef std::vector<int> vecInt; // |WV|C^^Cv` //typedef std::unique_ptr<stPosition> positionPtr; // |WVRei^Cv`(key=`PbgNo, value=|WV) //typedef std::unordered_map<int, positionPtr> positionContainer; // |WVXg //typedef std::list<positionPtr> lstPosition; // |WVxN^[ //typedef std::vector<positionPtr> vecPosition; };
true
e084ea2e210935c4cba0e2cd2aec773a0caa0fed
C++
marin117/Collision_detection
/src/Wall.h
UTF-8
832
2.828125
3
[]
no_license
#ifndef Wall_h #define Wall_h #include "AABB_box.h" #include "vector3D.h" class Wall { public: AABB_box bBox; Vector3D vecDir; Wall() = default; Wall(const Point center, const float rX, const float rY, const float rZ, const float vecX, const float vecY, const float vecZ, const float m); Wall(const float x, const float y, const float z, const float rX, const float rY, const float rZ, const float vecX, const float vecY, const float vecZ, const float m); const float &x() const { return this->center.x; } const float &y() const { return this->center.y; } const float &z() const { return this->center.z; } const float &getMass() const { return this->mass; } Point &getCenter() { return this->center; } private: Point center; float r[3]; float mass; unsigned int i; }; #endif
true
4e8f14f5ebdb22814fbc098ff9b091c5fe80b31e
C++
mascai/exercise
/1_arrays/leetCode/16_container_with_most_water.cpp
UTF-8
982
3.203125
3
[]
no_license
/* Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Notice that you may not slant the container. https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/586/week-3-february-15th-february-21st/3643/ */ class Solution { public: int get_water(const vector<int>& v, int l, int r) { return min(v[r], v[l]) * (r - l); } int maxArea(vector<int>& height) { int l = 0; int r = height.size() - 1; int res = 0; while (l < r) { res = max(res, get_water(height, l, r)); if (height[l] < height[r]) { l++; } else { r--; } } return res; } };
true
645517be3cc7cbe85aafba785131e853e123bc6d
C++
mCRL2org/mCRL2
/libraries/data/include/mcrl2/data/detail/data_functional.h
UTF-8
2,941
2.625
3
[ "BSL-1.0" ]
permissive
// Author(s): Wieger Wesselink // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // 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 mcrl2/data/detail/data_functional.h /// \brief Add your file description here. #ifndef MCRL2_DATA_DETAIL_DATA_FUNCTIONAL_H #define MCRL2_DATA_DETAIL_DATA_FUNCTIONAL_H #include "mcrl2/data/basic_sort.h" #include "mcrl2/data/function_symbol.h" namespace mcrl2 { namespace data { namespace detail { template <typename Term> struct compare_term { const Term& term; compare_term(const Term& t) : term(t) {} /// \brief Function call operator /// \param t A term /// \return The function result template <typename Term2> bool operator()(Term2 t) const { return term == t; } }; /// Tests if a term is a sort, and if it is equal to s struct compare_sort { sort_expression s; compare_sort(sort_expression s_) : s(s_) {} bool operator()(const atermpp::aterm_appl& t) const { return is_sort_expression(t) && s == t; } }; /// \brief Function object that determines if a term is equal to a given data variable. struct compare_variable: public compare_term<variable> { compare_variable(const variable& v) : compare_term<variable>(v) {} }; /// \brief Function object that returns the name of a data variable struct variable_name { /// \brief Function call operator /// \param v A data variable /// \return The function result core::identifier_string operator()(const variable& v) const { return v.name(); } }; /// \brief Function object that returns the sort of a data expression template < typename Expression > struct sort_of_expression { /// \brief Function call operator /// \param v A data variable /// \return The function result sort_expression operator()(const Expression& e) const { return e.sort(); } }; /// \brief Function object that returns the sort of a data variable typedef sort_of_expression<variable> sort_of_variable; struct sort_has_name { std::string m_name; sort_has_name(std::string const& name) : m_name(name) {} /// \brief Function call operator /// \param s A sort expression /// \return The function result bool operator()(const sort_expression& s) const { return is_basic_sort(s) && std::string(basic_sort(s).name()) == m_name; } }; struct function_symbol_has_name { std::string m_name; function_symbol_has_name(std::string const& name) : m_name(name) {} /// \brief Function call operator /// \param c A data operation /// \return The function result bool operator()(const function_symbol& c) const { return std::string(c.name()) == m_name; } }; } // namespace detail } // namespace data } // namespace mcrl2 #endif // MCRL2_DATA_DETAIL_DATA_FUNCTIONAL_H
true
fcd27844823ab3d21d6d1fe9162d78acf83ae5f9
C++
LoghinVladDev/loghin-toolbox
/include/Vector2.h
UTF-8
9,489
3.015625
3
[]
no_license
// // Created by vladl on 13/07/2020. // #ifndef ENG1_VECTOR2_H #define ENG1_VECTOR2_H #include <string> #include <cmath> #include <exception> namespace engine { class Vector2F; class Vector2D; } engine::Vector2F operator+ (const engine::Vector2F&, float) noexcept; engine::Vector2F operator- (const engine::Vector2F&, float) noexcept; engine::Vector2F operator+ (const engine::Vector2F&, const engine::Vector2F&) noexcept; engine::Vector2F operator- (const engine::Vector2F&, const engine::Vector2F&) noexcept; engine::Vector2F operator* (const engine::Vector2F&, float) noexcept; engine::Vector2F operator* (const engine::Vector2F&, int) noexcept; engine::Vector2F operator/ (const engine::Vector2F&, float) noexcept (false); engine::Vector2F operator/ (const engine::Vector2F&, int) noexcept (false); engine::Vector2F operator^ (const engine::Vector2F&, float) noexcept; engine::Vector2F operator^ (const engine::Vector2F&, int) noexcept; float operator* (const engine::Vector2F&, const engine::Vector2F&) noexcept; engine::Vector2D operator+ (const engine::Vector2D&, double) noexcept; engine::Vector2D operator- (const engine::Vector2D&, double) noexcept; engine::Vector2D operator+ (const engine::Vector2D&, const engine::Vector2D&) noexcept; engine::Vector2D operator- (const engine::Vector2D&, const engine::Vector2D&) noexcept; engine::Vector2D operator* (const engine::Vector2D&, double) noexcept; engine::Vector2D operator* (const engine::Vector2D&, int) noexcept; engine::Vector2D operator/ (const engine::Vector2D&, double) noexcept (false); engine::Vector2D operator/ (const engine::Vector2D&, int) noexcept (false); engine::Vector2D operator^ (const engine::Vector2D&, double) noexcept; engine::Vector2D operator^ (const engine::Vector2D&, int) noexcept; double operator* (const engine::Vector2D&, const engine::Vector2D&) noexcept; bool operator==(const engine::Vector2F&, const engine::Vector2F&) noexcept; bool operator!=(const engine::Vector2F&, const engine::Vector2F&) noexcept; bool operator==(const engine::Vector2D&, const engine::Vector2D&) noexcept; bool operator!=(const engine::Vector2D&, const engine::Vector2D&) noexcept; namespace engine { class [[maybe_unused]] EngineVector2DivByZero : public std::exception { [[nodiscard]] const char *what() const noexcept override { return "Tried dividing by zero!"; } }; class Vector2F { private: float _x {0.0f}; float _y {0.0f}; public: [[maybe_unused]] static Vector2F nullVector; [[maybe_unused]] Vector2F() noexcept = default; [[maybe_unused]] Vector2F(float x, float y) noexcept : _x(x), _y(y) { } [[maybe_unused]] [[nodiscard]] bool isNull() const noexcept; [[maybe_unused]] Vector2F &setX(float x) noexcept { this->_x = x; return *this; } [[maybe_unused]] Vector2F &setY(float y) noexcept { this->_y = y; return *this; } [[maybe_unused]] [[nodiscard]] float getX() const noexcept { return this->_x; } [[maybe_unused]] [[nodiscard]] float getY() const noexcept { return this->_y; } [[maybe_unused]] [[nodiscard]] float length() const noexcept; [[maybe_unused]] [[nodiscard]] Vector2F normalize() const noexcept; [[maybe_unused]] [[nodiscard]] static float dotProduct(const Vector2F&, const Vector2F&, float) noexcept; [[maybe_unused]] [[nodiscard]] static bool perpendicular(const Vector2F&, const Vector2F&) noexcept; [[maybe_unused]] [[nodiscard]] static bool orthogonal(const Vector2F&, const Vector2F&) noexcept; [[maybe_unused]] [[nodiscard]] static bool parallel(const Vector2F&, const Vector2F&) noexcept; [[maybe_unused]] [[nodiscard]] static float getAngle(const Vector2F&, const Vector2F&) noexcept; [[maybe_unused]] [[nodiscard]] std::string toString() const noexcept; [[maybe_unused]] explicit operator std::string() const; [[maybe_unused]] explicit operator Vector2D() const; #pragma clang diagnostic push #pragma ide diagnostic ignored "NotImplementedFunctions" #pragma clang diagnostic push #pragma ide diagnostic ignored "UnusedGlobalDeclarationInspection" friend Vector2F (::operator+)(const Vector2F&, float) noexcept; friend Vector2F (::operator-)(const Vector2F&, float) noexcept; friend Vector2F (::operator+)(const Vector2F&, const Vector2F&) noexcept; friend Vector2F (::operator-)(const Vector2F&, const Vector2F&) noexcept; friend Vector2F (::operator*)(const Vector2F&, float) noexcept; friend Vector2F (::operator*)(const Vector2F&, int) noexcept; friend Vector2F (::operator/)(const Vector2F&, float) noexcept (false); friend Vector2F (::operator/)(const Vector2F&, int) noexcept (false); friend Vector2F (::operator^)(const Vector2F&, float) noexcept; friend Vector2F (::operator^)(const Vector2F&, int) noexcept; friend float (::operator*)(const Vector2F&, const Vector2F&) noexcept; #pragma clang diagnostic pop #pragma clang diagnostic pop Vector2F operator-() const noexcept; Vector2F& operator=(const Vector2F&) noexcept; Vector2F& operator=(const Vector2D&) noexcept; Vector2F& operator+=(const Vector2F&) noexcept; Vector2F& operator-=(const Vector2F&) noexcept; Vector2F& operator*=(float) noexcept; Vector2F& operator*=(int) noexcept; Vector2F& operator/=(float) noexcept (false); Vector2F& operator/=(int) noexcept (false); Vector2F& operator^=(float) noexcept; Vector2F& operator^=(int) noexcept; friend bool (::operator==)(const Vector2F&, const Vector2F&) noexcept; friend bool (::operator!=)(const Vector2F&, const Vector2F&) noexcept; }; class Vector2D { private: double _x {0.0f}; double _y {0.0f}; public: [[maybe_unused]] static Vector2D nullVector; [[maybe_unused]] Vector2D() noexcept = default; [[maybe_unused]] Vector2D(double x, double y) noexcept : _x(x), _y(y) { } [[maybe_unused]] [[nodiscard]] bool isNull() const noexcept; [[maybe_unused]] Vector2D &setX(double x) noexcept { this->_x = x; return *this; } [[maybe_unused]] Vector2D &setY(double y) noexcept { this->_y = y; return *this; } [[maybe_unused]] [[nodiscard]] double getX() const noexcept { return this->_x; } [[maybe_unused]] [[nodiscard]] double getY() const noexcept { return this->_y; } [[maybe_unused]] [[nodiscard]] double length() const noexcept; [[maybe_unused]] [[nodiscard]] Vector2D normalize() const noexcept; [[maybe_unused]] [[nodiscard]] static double dotProduct(const Vector2D&, const Vector2D&, double) noexcept; [[maybe_unused]] [[nodiscard]] static bool perpendicular(const Vector2D&, const Vector2D&) noexcept; [[maybe_unused]] [[nodiscard]] static bool orthogonal(const Vector2D&, const Vector2D&) noexcept; [[maybe_unused]] [[nodiscard]] static bool parallel(const Vector2D&, const Vector2D&) noexcept; [[maybe_unused]] [[nodiscard]] static double getAngle(const Vector2D&, const Vector2D&) noexcept; [[maybe_unused]] [[nodiscard]] std::string toString() const noexcept; [[maybe_unused]] explicit operator std::string() const; [[maybe_unused]] explicit operator Vector2F() const; #pragma clang diagnostic push #pragma ide diagnostic ignored "NotImplementedFunctions" #pragma clang diagnostic push #pragma ide diagnostic ignored "UnusedGlobalDeclarationInspection" friend Vector2D (::operator+)(const Vector2D&, double) noexcept; friend Vector2D (::operator-)(const Vector2D&, double) noexcept; friend Vector2D (::operator+)(const Vector2D&, const Vector2D&) noexcept; friend Vector2D (::operator-)(const Vector2D&, const Vector2D&) noexcept; friend Vector2D (::operator*)(const Vector2D&, double) noexcept; friend Vector2D (::operator*)(const Vector2D&, int) noexcept; friend Vector2D (::operator/)(const Vector2D&, double) noexcept (false); friend Vector2D (::operator/)(const Vector2D&, int) noexcept (false); friend Vector2D (::operator^)(const Vector2D&, double) noexcept; friend Vector2D (::operator^)(const Vector2D&, int) noexcept; friend double (::operator*)(const Vector2D&, const Vector2D&) noexcept; #pragma clang diagnostic pop #pragma clang diagnostic pop Vector2D operator-() const noexcept; Vector2D& operator=(const Vector2D&) noexcept; Vector2D& operator=(const Vector2F&) noexcept; Vector2D& operator+=(const Vector2D&) noexcept; Vector2D& operator-=(const Vector2D&) noexcept; Vector2D& operator*=(double) noexcept; Vector2D& operator*=(int) noexcept; Vector2D& operator/=(double) noexcept (false); Vector2D& operator/=(int) noexcept (false); Vector2D& operator^=(double) noexcept; Vector2D& operator^=(int) noexcept; friend bool (::operator==)(const Vector2D&, const Vector2D&) noexcept; friend bool (::operator!=)(const Vector2D&, const Vector2D&) noexcept; }; typedef engine::Vector2F Vector2; } #endif //ENG1_VECTOR2_H
true
57d0aafd3acfdff9cbaeeae2722b4e8c8042f0c0
C++
wilmercastrillon/Ejercicios-Uva-Judge-Online
/Competitive Programming 3/Graph/Special Graphs (Others)/10054 The Necklace.cpp
UTF-8
2,261
2.765625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <list> #include <vector> using namespace std; typedef pair<int, int> ii; typedef pair<int, bool> ib; typedef list<ii>::iterator liii; int degree[52]; vector<vector<ib>> lista;//nodo destino, bandera visitado list<ii> cyc; void EulerTour(liii i, int u){ //printf("sigue %d\n", u); for(int j = 0; j < lista[u].size(); j++){ ib v = lista[u][j]; if(v.second){ v.second = false; lista[u][j].second = false; //printf(" quitamos %d a %d\n", u, j); for(int k = 0; k < lista[v.first].size(); k++){ ib uu = lista[v.first][k]; //printf("#quitamos %d a %d\n", v.first, k); if(uu.first==u && uu.second){ uu.second = false; lista[v.first][k].second = false; break; } } //printf("inserta par %d a %d\n", u, v.first); EulerTour(cyc.insert(i, ii(v.first, u)), v.first); } } } int main(){ int n, m, x, y, t, caso = 0; scanf("%d", &t); while(t--){ scanf("%d", &n); lista.assign(52, vector<ib>(0)); memset(degree, 0, sizeof(degree)); for(int i = 0; i < n; i++){ scanf("%d %d", &x, &y); lista[x].push_back(ib(y, true)); lista[y].push_back(ib(x, true)); degree[x]++; degree[y]++; } bool par = true; int inicio = 1; for(int i = 0; i < 52 && par; i++){ if(degree[i]&1) par = false; else if(degree[i]){ inicio = i; } } printf("Case #%d\n", ++caso); if(!par){ printf("some beads may be lost\n"); }else{ cyc.clear(); EulerTour(cyc.begin(), inicio); for(liii it = cyc.begin(); it != cyc.end(); it++){ //vec.push_back(*it); printf("%d %d\n", (*it).first, (*it).second); } //for(int i = vec.size()-1; i >= 0; i--){ // printf("%d %d\n", vec[i].first, vec[i].second); //} } if(t > 0) printf("\n"); } return 0; }
true
e95fcbf6f3e3770064b4987756e4d5f093e8f120
C++
mfkiwl/AFEPackDemo
/movingmesh2D/simulation2D.cpp
UTF-8
11,788
3.0625
3
[]
no_license
/** * @file simulation2D.cpp * @author Heyu Wang <scshw@cslin107.csunix.comp.leeds.ac.uk> * @date Mon Mar 10 17:57:29 2014 * * @brief Build a template for the normal simulation in 2D. * * */ #include "simulation2D.h" #include <sstream> double g_t; double g_a; double boundary_value(const double *); double boundary_value(const double * p) { return 1. / (1. + exp((p[0] + p[1] - g_t) / (2. * g_a))); }; /** * Setup the values of the initial function. * * @param p input points in 2D space. * * @return the initial function value of point p. */ double ArgFunction::value(const double * p) const { return 1. / (1. + exp((p[0] + p[1] - t) / (2. * a))); }; /** * Setup the gradient vector of the initial function. * * @param p input points in 2D space. * * @return The gradient vector of the initial function in point p. All * zeros set here, right??? */ std::vector<double> ArgFunction::gradient(const double * p) const { std::vector<double> v(2); return v; }; /////////////////////////////////////////////////////////////////////////////// /** * The next part really assemble the stiff matrix. * */ void Simulation2D::Matrix::getElementMatrix( const Element<double,2>& element0, const Element<double,2>& element1, const ActiveElementPairIterator<2>::State state) { /// usually the degree of freedom sizes of the two spaces (the /// test function's and the numerical solution's) are same. int n_element_dof0 = elementDof0().size(); /// but what's will happened if two sizes are different? int n_element_dof1 = elementDof1().size(); /// get the volume of the element (area in 2D). double volume = element0.templateElement().volume(); /// get the quadraure info, with the specified algebric accuracy. const QuadratureInfo<2>& quad_info = element0.findQuadratureInfo(algebricAccuracy()); /// in each quadraure point, the determinant of the jacobian /// matrix of the coordinates transform is a scale. std::vector<double> jacobian = element0.local_to_global_jacobian(quad_info.quadraturePoint()); /// the number of the quadrature points in one element. int n_quadrature_point = quad_info.n_quadraturePoint(); /// the real coordinates of the quadrature points of one element, /// and has already transfer to the global coordinates. std::vector<AFEPack::Point<2> > q_point = element0.local_to_global(quad_info.quadraturePoint()); /// the values of all the basis function values on all the quadrature points on the real element. std::vector<std::vector<double> > basis_value = element0.basis_function_value(q_point); /// the gradient vectors of all the basis function on all the quadrature points on the real element. std::vector<std::vector<std::vector<double> > > basis_gradient = element0.basis_function_gradient(q_point); /// do the numerical integral by all quadrature points, get the /// stiff matrix coefficient of j row and k column, this loop /// complete the assemble of the stiff matrix. for (int l = 0; l < n_quadrature_point; l++) { double Jxw = quad_info.weight(l) * jacobian[l] * volume; for (int j = 0; j < n_element_dof0; j++) { for (int k = 0; k < n_element_dof1; k++) { elementMatrix(j, k) += Jxw * ((1 / dt) * basis_value[j][l] * basis_value[k][l] + a * innerProduct(basis_gradient[j][l], basis_gradient[k][l])); } } } }; /** * Contructor, input the basic parameters, mesh file, parameter a and * the start time. * * @param file mesh file name. */ Simulation2D::Simulation2D(const std::string& file) : mesh_file(file), a(0.005), t(0.05), dt(2.0e-3) { g_a = a; g_t = t; }; /** * Standard decontructor. * */ Simulation2D::~Simulation2D() {}; /** * All the prepare things here. * */ void Simulation2D::initialize() { /// get the mesh data. readDomain(mesh_file); /// template_geometry.readData("triangle.tmp_geo"); coord_transform.readData("triangle.crd_trs"); template_dof.reinit(template_geometry); template_dof.readData("triangle.1.tmp_dof"); basis_function.reinit(template_dof); basis_function.readData("triangle.1.bas_fun"); template_element.resize(1); template_element[0].reinit(template_geometry, template_dof, coord_transform, basis_function); fem_space.reinit(*this, template_element); int n_element = n_geometry(2); fem_space.element().resize(n_element); for (int i = 0; i < n_element; i++) fem_space.element(i).reinit(fem_space, i, 0); fem_space.buildElement(); fem_space.buildDof(); fem_space.buildDofBoundaryMark(); u_h.reinit(fem_space); std::cout << "Initialize mesh ... " << std::endl; double scale, scale_step = 0.2; scale = scale_step; do { initialValue(); outputSolution(); // getchar(); u_h.scale(scale); moveMesh(); std::cout << "\r\tscale = " << scale << std::endl; scale += scale_step; } while (scale <= 1.0); initialValue(); outputSolution(); }; void Simulation2D::run() { initialize(); do { moveMesh(); stepForward(); outputSolution(); std::cout << "t = " << t << std::endl; } while (t < 1.95); }; void Simulation2D::initialValue() { ArgFunction u(a, t); Operator::L2Project(u, u_h, Operator::LOCAL_LEAST_SQUARE, 3); }; void Simulation2D::boundaryValue() { }; void Simulation2D::getMonitor() { int i, l; FEMSpace<double,2>::ElementIterator the_element = fem_space.beginElement(); FEMSpace<double,2>::ElementIterator end_element = fem_space.endElement(); for (i = 0; the_element != end_element; ++the_element) { double volume = the_element->templateElement().volume(); const QuadratureInfo<2>& quad_info = the_element->findQuadratureInfo(1); std::vector<double> jacobian = the_element->local_to_global_jacobian(quad_info.quadraturePoint()); int n_quadrature_point = quad_info.n_quadraturePoint(); std::vector<AFEPack::Point<2> > q_point = the_element->local_to_global(quad_info.quadraturePoint()); std::vector<std::vector<double> > basis_value = the_element->basis_function_value(q_point); std::vector<std::vector<double> > u_h_gradient = u_h.gradient(q_point, *the_element); float d = 0, area = 0; for (l = 0; l < n_quadrature_point; l++) { double Jxw = quad_info.weight(l) * jacobian[l] * volume; area += Jxw; d += Jxw * innerProduct(u_h_gradient[l], u_h_gradient[l]); } monitor(i++) = d / area; } std::cerr << "max monitor=" << *std::max_element(monitor().begin(), monitor().end()) << "\tmin monitor=" << *std::min_element(monitor().begin(), monitor().end()) << std::endl; smoothMonitor(2); for (i = 0; i < n_geometry(2); i++) monitor(i) = 1. / sqrt(1. + monitor(i)); }; void Simulation2D::updateSolution() { fem_space.updateDofInterpPoint(); int i, j, l; FEMFunction<double,2> _u_h(u_h); const double& msl = moveStepLength(); MassMatrix<2,double> matrix(fem_space); matrix.algebricAccuracy() = 2; matrix.build(); for (i = 1; i > 0; i--) { Vector<double> rhs(fem_space.n_dof()); FEMSpace<double,2>::ElementIterator the_element = fem_space.beginElement(); FEMSpace<double,2>::ElementIterator end_element = fem_space.endElement(); for (; the_element != end_element; ++the_element) { double volume = the_element->templateElement().volume(); const QuadratureInfo<2>& quad_info = the_element->findQuadratureInfo(2); std::vector<double> jacobian = the_element->local_to_global_jacobian(quad_info.quadraturePoint()); int n_quadrature_point = quad_info.n_quadraturePoint(); std::vector<AFEPack::Point<2> > q_point = the_element->local_to_global(quad_info.quadraturePoint()); std::vector<std::vector<double> > basis_value = the_element->basis_function_value(q_point); std::vector<double> _u_h_value = _u_h.value(q_point, *the_element); std::vector<std::vector<double> > u_h_gradient = u_h.gradient(q_point, *the_element); std::vector<std::vector<double> > move_vector = moveDirection(q_point, the_element->index()); int n_element_dof = the_element->n_dof(); const std::vector<int>& element_dof = the_element->dof(); for (l = 0; l < n_quadrature_point; l++) { double Jxw = quad_info.weight(l) * jacobian[l] * volume; for (j = 0; j < n_element_dof; j++) { rhs(element_dof[j]) += Jxw * basis_value[j][l] * (_u_h_value[l] + (1. / i) * msl * innerProduct(move_vector[l], u_h_gradient[l])); } } } BoundaryFunction<double,2> boundary1(BoundaryConditionInfo::DIRICHLET, 1, &boundary_value); BoundaryFunction<double,2> boundary2(BoundaryConditionInfo::DIRICHLET, 2, &boundary_value); BoundaryFunction<double,2> boundary3(BoundaryConditionInfo::DIRICHLET, 3, &boundary_value); BoundaryFunction<double,2> boundary4(BoundaryConditionInfo::DIRICHLET, 4, &boundary_value); BoundaryConditionAdmin<double,2> boundary_admin(fem_space); boundary_admin.add(boundary1); boundary_admin.add(boundary2); boundary_admin.add(boundary3); boundary_admin.add(boundary4); boundary_admin.apply(matrix, u_h, rhs); AMGSolver solver(matrix); solver.solve(u_h, rhs); }; }; void Simulation2D::stepForward() { int i, j, k, l; FEMFunction<double,2> _u_h(u_h); Matrix matrix(fem_space, dt, a); matrix.algebricAccuracy() = 2; matrix.build(); Vector<double> rhs(fem_space.n_dof()); FEMSpace<double,2>::ElementIterator the_element = fem_space.beginElement(); FEMSpace<double,2>::ElementIterator end_element = fem_space.endElement(); for (; the_element != end_element; ++the_element) { double volume = the_element->templateElement().volume(); const QuadratureInfo<2>& quad_info = the_element->findQuadratureInfo(2); std::vector<double> jacobian = the_element->local_to_global_jacobian(quad_info.quadraturePoint()); int n_quadrature_point = quad_info.n_quadraturePoint(); std::vector<AFEPack::Point<2> > q_point = the_element->local_to_global(quad_info.quadraturePoint()); std::vector<std::vector<double> > basis_value = the_element->basis_function_value(q_point); std::vector<double> u_h_value = u_h.value(q_point, *the_element); std::vector<std::vector<double> > u_h_gradient = u_h.gradient(q_point, *the_element); int n_element_dof = the_element->n_dof(); const std::vector<int>& element_dof = the_element->dof(); for (l = 0; l < n_quadrature_point; l++) { double Jxw = quad_info.weight(l) * jacobian[l] * volume; for (j = 0; j < n_element_dof; j++) { rhs(element_dof[j]) += Jxw * (u_h_value[l] * basis_value[j][l] / dt - u_h_value[l] * (u_h_gradient[l][0] + u_h_gradient[l][1]) * basis_value[j][l]); } } } BoundaryFunction<double,2> boundary1(BoundaryConditionInfo::DIRICHLET, 1, &boundary_value); BoundaryFunction<double,2> boundary2(BoundaryConditionInfo::DIRICHLET, 2, &boundary_value); BoundaryFunction<double,2> boundary3(BoundaryConditionInfo::DIRICHLET, 3, &boundary_value); BoundaryFunction<double,2> boundary4(BoundaryConditionInfo::DIRICHLET, 4, &boundary_value); BoundaryConditionAdmin<double,2> boundary_admin(fem_space); boundary_admin.add(boundary1); boundary_admin.add(boundary2); boundary_admin.add(boundary3); boundary_admin.add(boundary4); boundary_admin.apply(matrix, u_h, rhs); AMGSolver solver(matrix); solver.solve(u_h, rhs); t += dt; g_t = t; }; void Simulation2D::outputSolution() { std::stringstream result; result.setf(std::ios::fixed); result.precision(4); result << "u_h_" << int(t / dt) << ".dx"; u_h.writeOpenDXData(result.str()); }; // // end of file ///////////////////////////////////////////////////////////////////////////////
true
d081130bc851dd4aa26497ffad552564be6629ca
C++
heiyanbin/cpp_projects
/code_exercise/code_exercise/findK.cpp
UTF-8
1,169
3.1875
3
[]
no_license
#include "lib.h" int partition(int a[], int n) { if(!a||n<1) return -1; if(n==1) return 0; int i= 0, j=n-1; int x = a[0]; while(i<j) { while (a[j]>=x && i< j) { j--; } if (i<j) { a[i]=a[j]; i++; } while (a[i]<x && i<j) { i++; } if(i<j){ a[j]=a[i]; j--; } } a[i]=x; return i; } int partition2(int a[], int n) { if(!a||n<1) return -1; if(n==1) return 0; int i=1, j=n-1; while(i<j) { while(i<j && a[i]<a[0]) i++; while(i<j && a[j]>=a[0]) j--; if(i<j) swap(a[i],a[j]); } if(a[i]<a[0]) swap(a[i],a[0]); else swap(a[i-1],a[0]); return i-1; } int findK(int a[], int n, int k) { if(!a||n<1||k>n) return -1; int j = partition2(a,n); if(k-1<j) return findK(a,j+1,k); else if(k-1>j) return findK(a+j+1,n-j-1, k-j-1); else return a[j]; } void testFindK() { int a[] ={3,4,2,1,7,6,5}; int k = findK(a,7,4); std::cout << k<< std::endl; }
true
31f73e48b08b4dcb0dc48d497cbfa2c7501e84cd
C++
daodaokami/FeaturesAbout
/src/spacenear_matcher.cpp
UTF-8
9,548
2.515625
3
[]
no_license
// // Created by lut on 18-12-22. // #include <spacenear_matcher.h> #include <opencv2/features2d.hpp> #include <opencv/cv.hpp> #include <iostream> #include <chrono> SpaceNear_Matcher::SpaceNear_Matcher(GridNet *gridNet_1, GridNet *gridNet_2) { this->gridNet_1 = gridNet_1; this->gridNet_2 = gridNet_2; } void SpaceNear_Matcher::SpaceNearMatcher(std::vector<cv::KeyPoint>& keyps_1, std::vector<cv::KeyPoint>& keyps_2, std::vector<cv::DMatch> &all_matches) { // SpaceNear_Matcher int grid_size = this->gridNet_1->gridKeypoints.size(); cv::BFMatcher matcher(cv::NORM_HAMMING); //得到对点内的匹配关系 //还有一个问题是,序列的关系!!! //首先最简单的是重新,重新计算keypoints 和 descriptors得到,都是新的数据,并绘制出来查看效果 std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); cv::Mat descriptors_1, descriptors_2; for(int index=0; index<grid_size; index++){ std::vector<cv::KeyPoint*> *ptr_vkps_1 = &this->gridNet_1->gridKeypoints[index];//获取了第index块的当前特征点 cv::Mat ptr_descs_1 = this->gridNet_1->gridDescs[index];//本身就是浅拷贝 //找img2 中的相邻特征点与相邻的描述子 std::vector<std::vector<cv::KeyPoint*>*> v_ptr_vkps_2; int neighbor_size = this->gridNet_2->neighbors[index].size(); std::vector<cv::Mat> v_descs_2; v_ptr_vkps_2.resize(neighbor_size); v_descs_2.resize(neighbor_size); for(int neighbor = 0; neighbor<neighbor_size; neighbor++){ v_ptr_vkps_2[neighbor] = this->gridNet_2->neighbors[index][neighbor]; v_descs_2[neighbor] = this->gridNet_2->descs_neighbors[index][neighbor]; } //把这些分散的数据整合成一串的数据 std::vector<cv::KeyPoint> kps_1, kps_2; cv::Mat desc_1, desc_2; merge_kps_descs(ptr_vkps_1, ptr_descs_1, kps_1, desc_1); merge_kps_descs(&v_ptr_vkps_2, v_descs_2, kps_2, desc_2); keyps_1.insert(keyps_1.end(), kps_1.begin(), kps_1.end()); keyps_2.insert(keyps_2.end(), kps_2.begin(), kps_2.end()); //一次插入一个块内的特征点 descriptors_1.push_back(desc_1); descriptors_2.push_back(desc_2); //这种时候是存在误匹配的 std::cout<<index<<" SpaceNearMatcher kps1 "<<kps_1.size()<<" desc_1 "<<desc_1.size<<std::endl; std::cout<<index<<" SpaceNearMatcher kps2 "<<kps_2.size()<<" desc_2 "<<desc_2.size<<std::endl; //这里没有出错,应该是set keypoints 出错了 std::vector<cv::DMatch> sub_matches; sub_matches.clear(); if(desc_1.empty() || desc_2.empty()){ continue; } matcher.match(desc_1, desc_2, sub_matches); //在vector的matchespush中,需要注意的是,可能存在 int start_posi_1 = keyps_1.size() - kps_1.size(); int start_posi_2 = keyps_2.size() - kps_2.size(); for(int i=0; i<sub_matches.size(); i++){ std::cout<<"cur_sub_matches "<<i<<" "<<sub_matches[i].queryIdx<<" - "<<sub_matches[i].trainIdx<<std::endl; sub_matches[i].queryIdx += start_posi_1; sub_matches[i].trainIdx += start_posi_2; //这里肯定是错的,要完成的任务如下 /** * sub_matches[] 是当前训练的A-的索引和对应B-的索引的块内的索引号 * * * */ } all_matches.insert(all_matches.end(), sub_matches.begin(), sub_matches.end()); } std::chrono::system_clock::time_point end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds_submatches = end - start; std::cout<<"all matches cost "<<elapsed_seconds_submatches.count()<<std::endl; std::cout<<"all matches size "<<all_matches.size()<<std::endl; } void SpaceNear_Matcher::SpaceNearMatcher(int index, std::vector<cv::DMatch> &sub_matches) { std::vector<cv::KeyPoint*> *ptr_vkps_1 = &this->gridNet_1->gridKeypoints[index];//获取了第index块的当前特征点 cv::Mat ptr_descs_1 = this->gridNet_1->gridDescs[index];//本身就是浅拷贝 //找img2 中的相邻特征点与相邻的描述子 std::vector<std::vector<cv::KeyPoint*>*> v_ptr_vkps_2; int neighbor_size = this->gridNet_2->neighbors[index].size(); std::vector<cv::Mat> v_descs_2; v_ptr_vkps_2.resize(neighbor_size); v_descs_2.resize(neighbor_size); for(int neighbor = 0; neighbor<neighbor_size; neighbor++){ v_ptr_vkps_2[neighbor] = this->gridNet_2->neighbors[index][neighbor]; v_descs_2[neighbor] = this->gridNet_2->descs_neighbors[index][neighbor]; } //把这些分散的数据整合成一串的数据 std::vector<cv::KeyPoint> kps_1, kps_2; cv::Mat desc_1, desc_2; merge_kps_descs(ptr_vkps_1, ptr_descs_1, kps_1, desc_1); merge_kps_descs(&v_ptr_vkps_2, v_descs_2, kps_2, desc_2); std::cout<<"SpaceNearMatcher kps1 "<<kps_1.size()<<" desc_1 "<<desc_1.size<<std::endl; std::cout<<"SpaceNearMatcher kps2 "<<kps_2.size()<<" desc_2 "<<desc_2.size<<std::endl; //这里没有出错,应该是set keypoints 出错了 cv::BFMatcher matcher(cv::NORM_HAMMING); std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); matcher.match(desc_1, desc_2, sub_matches); std::chrono::system_clock::time_point end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds_submatches = end - start; std::cout<<"sub matches cost "<<elapsed_seconds_submatches.count()<<std::endl; } void SpaceNear_Matcher::Set_KeyPoints_1(int index, std::vector<cv::KeyPoint> &kps_1) { std::vector<cv::KeyPoint*> *ptr_vkps_1 = &this->gridNet_1->gridKeypoints[index];//获取了第index块的当前特征点 int kps_size = ptr_vkps_1->size(); kps_1.resize(kps_size); for(int i=0; i<kps_size; i++) { cv::KeyPoint kp; kp.pt = (*ptr_vkps_1)[i]->pt; kp.octave = (*ptr_vkps_1)[i]->octave; kp.angle = (*ptr_vkps_1)[i]->angle; kp.response = (*ptr_vkps_1)[i]->response; kps_1[i] = kp; } std::cout<<"Set_Kps1 "<<kps_1.size()<<std::endl; } void SpaceNear_Matcher::Set_KeyPoints_2(int index, std::vector<cv::KeyPoint> &kps_2) { std::vector<std::vector<cv::KeyPoint*>*> v_ptr_vkps_2; int neighbor_size = this->gridNet_2->neighbors[index].size(); v_ptr_vkps_2.resize(neighbor_size); for(int neighbor = 0; neighbor<neighbor_size; neighbor++){ v_ptr_vkps_2[neighbor] = this->gridNet_2->neighbors[index][neighbor]; } int sum_kps = 0; for(int i=0; i<v_ptr_vkps_2.size(); i++){ sum_kps += v_ptr_vkps_2[i]->size(); } kps_2.resize(sum_kps); int count = 0; for(int i=0; i<v_ptr_vkps_2.size(); i++) { //即存在多少的邻居!!! for (int j = 0; j < v_ptr_vkps_2[i]->size(); j++) { cv::KeyPoint kp; kp.pt = (*(v_ptr_vkps_2[i]))[j]->pt; kp.octave = (*(v_ptr_vkps_2[i]))[j]->octave; kp.angle = (*(v_ptr_vkps_2[i]))[j]->angle; kp.response = (*(v_ptr_vkps_2[i]))[j]->response; kps_2[count] = kp; count++; } } std::cout<<"Set Kps2 "<<kps_2.size()<<std::endl; } void SpaceNear_Matcher::drawMatches(cv::Mat &img1, std::vector<cv::KeyPoint> &kps1, cv::Mat &img2, std::vector<cv::KeyPoint> &kps2, std::vector<cv::DMatch> &matches) { this->Set_KeyPoints_1(17, kps1); this->Set_KeyPoints_2(17, kps2); //采用多线程,四路同时计算 cv::Mat img_kps1; cv::drawKeypoints(img1, kps1, img_kps1); cv::Mat img_kps2; cv::drawKeypoints(img2, kps2, img_kps2); //从 第 85 号元素开始,就没有被赋予值了!! cv::imshow("drawmatches_img_kps1", img_kps1); cv::imshow("drawmatches_img_kps2", img_kps2); cv::Mat img_matches; cv::drawMatches(img1, kps1, img2, kps2, matches, img_matches); cv::imshow("draw_matches_img_matches", img_matches); cv::waitKey(0); } void SpaceNear_Matcher::merge_kps_descs(std::vector<cv::KeyPoint*> *ptr_vkps, cv::Mat& descs, std::vector<cv::KeyPoint>& kps, cv::Mat& cdescs){ cdescs = descs; kps.resize(ptr_vkps->size()); for(int i=0; i<ptr_vkps->size(); i++){ cv::KeyPoint kp; kp.pt = (*ptr_vkps)[i]->pt; kp.octave = (*ptr_vkps)[i]->octave; kp.angle = (*ptr_vkps)[i]->angle; kp.response = (*ptr_vkps)[i]->response; kps[i] = kp; } //完成融合与构造了 } void SpaceNear_Matcher::merge_kps_descs(std::vector<std::vector<cv::KeyPoint*>*> *ptr_v_ptr_vkps, std::vector<cv::Mat>& descs, std::vector<cv::KeyPoint>& kps, cv::Mat& cdescs){ int sum_kps = 0; for(int i=0; i<ptr_v_ptr_vkps->size(); i++){ sum_kps += (*ptr_v_ptr_vkps)[i]->size(); } kps.resize(sum_kps); int count = 0; for(int i=0; i<ptr_v_ptr_vkps->size(); i++){ //即存在多少的邻居!!! for(int j=0; j<(*ptr_v_ptr_vkps)[i]->size(); j++){ cv::KeyPoint kp; kp.pt = (*(*ptr_v_ptr_vkps)[i])[j]->pt; kp.octave = (*(*ptr_v_ptr_vkps)[i])[j]->octave; kp.angle = (*(*ptr_v_ptr_vkps)[i])[j]->angle; kp.response = (*(*ptr_v_ptr_vkps)[i])[j]->response; kps[count] = kp; count ++; } cdescs.push_back(descs[i]); } }
true
6a2f5007cedc4762439a56b2e00f61b7fead670f
C++
tejasborkar74/ProblemSolvingIB-
/String/Pretty_Json.cpp
UTF-8
1,237
2.890625
3
[]
no_license
vector<string> Solution::prettyJSON(string A) { vector<string> ans; string curr; int idn =0; for(int i=0;i<A.size();i++) { if(A[i] == '{' || A[i]=='[') { curr.push_back(A[i]); ans.push_back(curr); curr=""; idn++; int j=0; while(j<idn) { curr+= "\t"; j++; } } else if(A[i+1]=='{' ||A[i+1]=='[' || A[i] == ',') { curr.push_back(A[i]); ans.push_back(curr); curr=""; int j=0; while(j<idn) { curr+= "\t"; j++; } } else if(A[i]=='}' ||A[i]==']') { if(curr.length()>=1)ans.push_back(curr); curr=""; idn--; int j=0; while(j<idn) { curr+= "\t"; j++; } curr.push_back(A[i]); if(A[i+1] != ',') { ans.push_back(curr); curr=""; } } else{ curr.push_back(A[i]); } } return ans; }
true
f7667d26ef9636d3dac00cd8be4349ccb95e7d43
C++
sannier/XXX
/BD/TMState.h
UTF-8
4,016
3.046875
3
[]
no_license
#ifndef TMSTATE_H #define TMSTATE_H #include "syntactic_sugar.h" // Layout of a Turing Machine State Tape // // Let our SA Turing Machine State Tape be defined as a string of // bits containing a formatted header // // The header length is a function of the number of states. // The total header length is 8 + 20*n bytes, arranged as follows: // z, the number of (4-byte)words in the tape, 4 bytes // p, the bit offset from the start of the tape to active state, 4 bytes // ST, a complete description of the state table, 20n bytes // // Each state is represented as an opCode indicating this is a TuringMachineState, // followed by a 9-tuple of values specifying the next // symbol, direction and state that the machine prescribes, each a function // of the symbol read. // sym dir nxt // State 0: TMSOPCODE | 0 0 0 | 0 0 0 | 0 0 0 | // // State i: TMSOPCODE | sym0 sym1 sym2 | dir0 dir1 dir2 | nxt0 nxt1 nxt2 // // where: // TMSOPCODE [1 unsigned] // sym0, sym1, sym2 are in [00, 01, 10/11] [1 uchar with 2 waste bits] // dir0, dir1, dir2 are in [-1, 0, 1] [1 uchar with 2 waste bits] // PADDING(to help with C++ alignment) [2 uchar -- unused] // nxt0, nxt1, nxt2 are in [0, 1, ..., n-1] [3 unsigned] // // The pointers to the nxt states are stored as bit offsets into the state table // as counted from the start of the tape ... // to represent state i, the offset is 4+16i // if the offset is k , state i = (k-8)/16 // // The total length of the n state table is: // n*(4 uchars + 4 unsigned) = n*20 bytes // // We can get n from z (the number of words in the header) as: // 4*z = 4 + 4 + n*20 // (4z-8)/20 = n // (z-2)/5 = n //TODO: Make a parent class to indicate that BDM::TMState and BDM::Command are // both instances of Commands -- same size, same interface class TMState { private: friend class BitDeviceMachine; // Private data members // Total size: 5 words/ 20 bytes/ 160 bits unsigned opCode; // OPCODE for TuringMachineState uchar sym; // 3 2-bit symbols in [00, 01, 10](2 bits unused) uchar dir; // 3 2-bit symbols in [00, 01, 10](2 bits unused) uchar pad[2]; // 2 uchar pads for alignment unsigned nxt[3]; // 3 bit offsets to next states // Default constructor (never called because of "casting creation") TMState(); // Init state to given state, direction, symbol triples void Init(uchar s0, uchar s1, uchar sb, int d0, int d1, int db, unsigned n0, unsigned n1, unsigned nb); // Initialize a state to random values consistent with an n state machine void Random(int scnt); // Accessors unsigned OpCode(); // Return the opCode for TuringMachineState uchar Sym (uchar s); // Return sym[s] as uchar in [0,1,2] uchar Dirs(uchar s); // Return dir[s] as uchar in [0,1,2] int Dird(uchar s); // Return dir[s] as int in [-1,0,1] unsigned Nxto(uchar s); // Return nxt[s] as offset unsigned Nxts(uchar s); // Return nxt[s] as state // Addressors (useful for testing alignments) :-) uchar* SymA(); uchar* DirA(); uchar* NxtA(); // Address conversions static int SYM2Dir(unsigned ds); // ds in [0,1,2] to int in [-1, 0, 1] static uchar Dir2SYM(int d); // int in [-1, 0, 1] to uchar in [0, 1, 2] static unsigned STATE2OFF(unsigned s); // State index s in [1,..,n] to bit offsetn static unsigned OFF2STATE(unsigned o); // Bit offset o to state index in [1, ..,n] // Print status of current command to debug file void DBGPRINT(); // Equality and inequality operators bool operator==(const TMState &other) const; bool operator!=(const TMState &other) const; }; #endif
true
a3b3a7441bb24435bdf74bce0ed2e75923ec159d
C++
stevenfans/Rubiks-Cube
/RubiksCubed/OldCoordinates.h
UTF-8
3,247
2.8125
3
[]
no_license
#pragma once #include <vector> using namespace std; // Create 54 integer vector sets // top vector<int> s0x({ 27,30,24,27,27,30,24,24,30 }); vector<int> s1x({ 42,42,42,39,45,45,45,39,39 }); vector<int> s2x({ 53,53,53,50,50,50,56,56,56 }); vector<int> s3x({ 16,16,16,19,19,19,13,13,13 }); vector<int> s4x({ 30,30,30,33,33,33,17,17,17 }); vector<int> s5x({ 40,40,40,37,37,37,43,43,43 }); vector<int> s6x({ 7,7,7,10,10,10,4,4,4 }); vector<int> s7x({ 20,20,20,17,17,17,23,23,23}); vector<int> s8x({ 29,29,29,30,30,30,27,27,27 }); // right vector<int> s9x({ 36,36,36,33,33,33,39,39,39}); vector<int> s10x({ 48,48,48,51,51,51,45,45,45}); vector<int> s11x({ 57,57,57,59,59,59,55,55,55}); vector<int> s12x({ 37,37,37,35,35,35,39,39,39}); vector<int> s13x({ 47,47,47,45,45,45,49,49,49}); vector<int> s14x({ 55,55,55,56,56,56,54,54,54}); vector<int> s15x({ 38,38,38,40,40,40,36,36,36}); vector<int> s16x({ 47,47,47,48,48,48,46,46,46}); vector<int> s17x({ 54,54,54,55,55,55,53,53,53}); // left vector<int> s18x({ 3,3,3,4,4,4,2,2,2}); vector<int> s19x({ 10,10,10,9,9,9,11,11,11}); vector<int> s20x({ 23,23,23,21,21,21,25,25,25 }); vector<int> s21x({ 7,7,7,8,8,8,6,6,6}); vector<int> s22x({ 15,15,15,14,14,14,16,16,16}); vector<int> s23x({ 26,26,26,27,27,27,25,25,25}); vector<int> s24x({ 12,12,12,13,13,13,11,11,11}); vector<int> s25x({ 18,18,18,19,19,19,17,17,17}); vector<int> s26x({ 27,27,27,26,26,26,28,28,28}); // vector<int> s2() // ... // vector<int> s53() // top vector<int> s0y({ 28,28,28,31,25,31,25,31,25}); vector<int> s1y({ 19,16,22,19,19,16,22,22,16}); vector<int> s2y({ 12,15,9,12,15,9,12,15,9 }); vector<int> s3y({ 20,23,17,20,23,17,20,23,17 }); vector<int> s4y({ 13,16,10,13,16,10,13,16,10 }); vector<int> s5y({ 8, 10,6,8,10,6,8,10,6 }); vector<int> s6y({ 15,17,13,15,17,13,15,17,13 }); vector<int> s7y({ 9,12, 6, 9,12, 6, 9,12, 6 }); vector<int> s8y({ 6, 4, 8, 6, 4, 8, 6, 4, 8 }); // right vector<int> s9y({ 39,42,36,39,42,36,39,42,36 }); vector<int> s10y({ 29,32,26,29,32,26,29,32,26 }); vector<int> s11y({ 22,23,21,22,23,21,22,23,21}); vector<int> s12y({ 50,52,48,50,52,48,50,52,48}); vector<int> s13y({ 40,42,38,40,42,38,40,42,38}); vector<int> s14y({ 33,34,32,33,34,32,33,34,32}); vector<int> s15y({ 58,59,57,58,59,57,58,59,57}); vector<int> s16y({ 49,48,50,49,48,50,49,48,50}); vector<int> s17y({ 42,43,41,42,43,41,42,43,41}); // left vector<int> s18y({ 24,23,25,24,23,25,24,23,25 }); vector<int> s19y({ 30,31,29,30,21,29,30,31,29 }); vector<int> s20y({ 40,41,29,40,41,29,40,41,29}); vector<int> s21y({ 36,35,37,36,35,37,36,35,37}); vector<int> s22y({ 42,41,43,42,41,43,42,41,43}); vector<int> s23y({ 52,51,53,52,51,53,52,51,53}); vector<int> s24y({ 43,42,44,43,42,44,43,42,44}); vector<int> s25y({ 51,50,52,51,50,52,51,50,52}); vector<int> s26y({ 60,61,59,60,61,59,60,61,59}); /* . . . . */ vector<vector<int>> X({ s0x,s1x,s2x,s3x,s4x,s5x,s6x,s7x,s8x,s9x,s10x,s11x,s12x,s13x,s14x, s15x,s16x,s17x,s18x,s19x,s20x,s21x,s22x,s23x,s24x,s25x,s26x}); // add s2, ..., s53 vector<vector<int>> Y({ s0y,s1y,s2y,s3y,s4y,s5y,s6y,s7y,s8y,s9y,s10y,s11y,s12y,s13y, s14y,s15y,s16y,s17y,s18y,s19y,s20y,s21y,s22y,s23y,s24y,s25y,s26y});
true
940e19d44823e91d6693d2c4f80b989b820ee0f0
C++
stonesha/UNR-CS
/CS 302/Homework 7/hw7-revamped/TSP.h
UTF-8
4,468
3.34375
3
[]
no_license
/** * @brief CS-302 Homework 7 * @Author Stone Sha (stones@nevada.unr.edu) * @date May 2019 * * Self contained header file for the solving of the Traveling Salesman Problem * https://www.geeksforgeeks.org/traveling-salesman-problem-using-branch-and-bound-2/ used for reference */ #pragma once #include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <climits> #define V 5 //number of vertices //ease of typing for me typedef std::vector<int> VecInt; typedef std::vector<bool> VecBool; typedef std::vector<std::string> VecString; typedef std::vector<VecInt> Graph; class TSP { //public methods public: TSP(); void printSolution(std::ofstream& os); void printAllPaths(std::ofstream& os); //protected methods, only for helper methods protected: int firstMin(int i); int secondMin(int i); void TSPUtil(); void TSPRec(int curr_bound, int curr_weight, int level, VecInt curr_path); private: //adjacency matrix for cities Graph adj = { /*R SF SLC SE LV*/ /*R*/ { 0, 218, 518, 705, 439 }, /*SF*/ { 218, 0, 0, 806, 570 }, /*SLC*/ { 518, 0, 0, 840, 421 }, /*SE*/ { 705, 806, 832, 0, 1116 }, /*LV*/ { 438, 569, 421, 1125, 0}, }; //indes of cities in string form VecString index = { "Reno", "San Francisco", "Salt Lake City", "Seattle", "Las Vegas" }; //variables needed int final_weight = INT_MAX; VecInt final_path; VecBool visited; }; TSP::TSP() { } //finding minimum cost of edge at the end of vertex i int TSP::firstMin(int i) { int min = INT_MAX; for (int j = 0; j < V; j++) if (adj[i][j] < min && i != j) min = adj[i][j]; return min; } //finding second lowest edge cost at vertex i int TSP::secondMin(int i) { int first = INT_MAX, second = INT_MAX; for (int j = 0; j < V; j++) { if (i == j) continue; if (adj[i][j] <= first) { second = first; first = adj[i][j]; } else if (adj[i][j] <= second && adj[i][j] != first) { second = adj[i][j]; } } return second; } //recursive function to calculate shortest path and weight void TSP::TSPRec(int curr_bound, int curr_weight, int level, VecInt curr_path) { if (level == V) { if (adj[curr_path[level - 1]][curr_path[0]] != 0) { int curr_res = curr_weight + adj[curr_path[level - 1]][curr_path[0]]; if (curr_res < final_weight) { final_weight = curr_res; final_path = curr_path; } } } for (int i = 0; i < V; i++) { if (adj[curr_path[level - 1]][i] != 0 && visited[i] == false) { int temp = curr_bound; curr_weight += adj[curr_path[level - 1]][i]; if (level == 1) curr_bound -= ((firstMin(curr_path[level - 1]) + firstMin(i)) / 2); else curr_bound -= ((secondMin(curr_path[level - 1]) + firstMin(i)) / 2); if (curr_bound + curr_weight < final_weight) { curr_path[level] = i; visited[i] = true; TSPRec(curr_bound, curr_weight, level + 1, curr_path); } curr_weight -= adj[curr_path[level - 1]][i]; curr_bound = temp; visited.assign(visited.size(), false); for (int j = 0; j <= level - 1; j++) visited[curr_path[j]] = true; } } } //TSP function for calling recursive function void TSP::TSPUtil() { VecInt curr_path; int curr_bound = 0; curr_path.resize(V + 1); visited.resize(curr_path.size()); curr_path.assign(curr_path.size(), -1); visited.assign(curr_path.size(), false); for (int i = 0; i < V; i++) curr_bound += (firstMin(i) + secondMin(i)); curr_bound /= 2; visited[0] = true; curr_path[0] = 0; TSPRec(curr_bound, 0, 1, curr_path); } //printing of the optimal path void TSP::printSolution(std::ofstream &os) { TSPUtil(); os << "Minimun cost: " << final_weight << "\nPath by Vertex: "; for (unsigned int i = 0; i < V; i++) { os << final_path.at(i); if (i != final_path.size() - 1) os << " -> "; } os << final_path.at(0) << std::endl; os << "Path by City: "; for (unsigned int i = 0; i < V; i++) { os << index[final_path.at(i)]; os << " -> "; } os << index[0] << std::endl; } //printing all possible paths void TSP::printAllPaths(std::ofstream& os) { os << std::endl << "All Possible Paths" << std::endl << "Assuming direct connections between all vertexes" << std::endl; std::sort(index.begin() + 1, index.end()); while (std::next_permutation(index.begin() + 1, index.end())) { for (int i = 0; i < V; i++) { os << index[i]; if (i != index.size() - 1) { os << " -> "; } } os << std::endl; } }
true
7e996213b7bae38d1ee21fe6aff688fc42f6d62b
C++
Rakshit0404/OOPS-programs-and-explainations-by-me
/98_writing_classes_in_separate_files_using_define/Person.cpp
UTF-8
322
2.765625
3
[]
no_license
#include<iostream> using namespace std; #include "Person.h"//here the header file has been included. Person::Person()//the declared fucntions and variables inside the class in the header files have been defined here { cout<<"Constructor ran"<<endl; } void Person::display()//and here. { cout<<"Kya display"<<endl; }
true
fed21a5bd3aa5dfa580b5f3bbeca936338ff6f2d
C++
jarivandam/hu-ipass
/arm/calculations.hpp
UTF-8
827
2.609375
3
[ "BSL-1.0" ]
permissive
#include "stdint.h" #include "coordinate.hpp" /// \file /// \brief /// calculate the joint angles /// \details /// given the lenght and coordinates the arm should move to, this function calculates the angle of the joints /// calculations arm based on this document http:://www.hessmer.org/uploads/RobotArm/Inverse%2520Kinematics%2520for%2520Robot%2520Arm.pdf /// \param[in] int len1, the length of the first arm /// \param[in] int len2, the lenght of the second arm /// \param[in] coordinate position, the position the end of the arm should move to /// \param[out] uint16_t servo1, the angle joint1 should be set to /// \param[out] uint16_t servo2, the angle joint2 should be set to /// \result int error, 0 on success 1 on error. int calc_positions(int &len1,int &len2,coordinate &position,uint16_t &servo1, uint16_t &servo2);
true
2d27889064f0ee6d561c1057f4c93bfe6189c11c
C++
Plutoyo/C--Course-Project
/src/Date.cpp
UTF-8
836
3.078125
3
[]
no_license
#include <iostream> #include <time.h> #include "Date.h" using namespace std; Date::Date() { time_t timer; time(&timer); tm* t_tm = localtime(&timer); d=t_tm->tm_mday; m=t_tm->tm_mon+1; y=t_tm->tm_year+1900; isSet=0; } Date Date::operator++(int) { d++; adjust(); return *this; } int Date::returnisSet() { return isSet; } void Date::change(){ if(isSet==0) isSet=1; else isSet=0; } int Date::isLeapYear() { int a=0; if(y%4==0&&y%100!=0||y%400==0) a=1; return a; } ostream & operator<<(ostream& str,Date& a) { str<<a.y<<"/"<<a.m<<"/"<<a.d; return str; } void Date::adjust() { int k; k=isLeapYear(); int month[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}}; while(d>month[k][m-1]) { d-=month[k][m-1]; m++; if(m>12) { y++; m-=12; } k=isLeapYear(); } }
true
073da807f4da4c0b916ce6f3eb7b249e3ef41225
C++
algorithm-maintain-box/Programers
/JJune/Reference/Run3.cpp
UTF-8
874
3.375
3
[ "MIT" ]
permissive
#include <string> #include <vector> using namespace std; int solution(int number, vector<int> firecracker) { int result = 0; int affect = firecracker.size(); for (int i = firecracker.size() - 1; i >= 0; i--) { auto new_affect = i - firecracker[i]; if (affect > new_affect) { if (firecracker[i] == 0 || affect > i) { result++; } affect = new_affect; } if (affect < 0) { return result; } } return result; } #include <iostream> int main() { std::cout << "MINE : " << solution(4, {0, 1, 0, 5}) << " A : 1" << std::endl; std::cout << "MINE : " << solution(2, {0, 0}) << " A : 2" << std::endl; std::cout << "MINE : " << solution(10, {1, 1, 3, 0, 0, 0, 2, 1, 0, 3}) << " A : 3" << std::endl; return 0; }
true
54057b281fd5fba9e174fc6a3f243705b3d1ee40
C++
AbrMa/Competitive-Programming
/Codeforces/Div 2/A/Alarm Clock.cpp
UTF-8
429
2.578125
3
[]
no_license
#include <iostream> using namespace std; int main() { int a,b,c,d,t; long long int sum,aux,q; cin >> t; while (t--) { cin >> a >> b >> c >> d; if (a <= b) cout << b << endl; else if (c - d <= 0) cout << "-1" << endl; else { sum = 0, aux = 0; sum += b; aux = sum; q = (a - b) / (c - d); sum += q * (c - d); aux += q * c; if (sum < a) aux += c; cout << aux << endl; } } return 0; }
true
01c68269e1241cf31b108a4c9e5986981b9c80b9
C++
3pointer/ACM-ICPC
/3pointer's Submit/sdut/i.cpp
UTF-8
1,261
2.796875
3
[]
no_license
#include <stdio.h> #include <string.h> #define M 1000000007 #define N 4 struct Mat { int mat[N][N]; }; void init(Mat Mata) { for(int i=0;i<4;i++) for(int j=0;j<4;j++) Mata.mat[i][j]=0; Mata.mat[0][0]=1,Mata.mat[0][1]=3; Mata.mat[0][2]=2,Mata.mat[0][3]=7; Mata.mat[1][1]=3,Mata.mat[1][2]=2; Mata.mat[1][3]=7; Mata.mat[2][1]=Mata.mat[3][2]=1; } Mat mul(Mat p, Mat q) { Mat t; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { t.mat[i][j] = 0; for (int k = 0; k < N; k++) { t.mat[i][j] += p.mat[i][k] * q.mat[k][j]; if (t.mat[i][j] > M) { t.mat[i][j] %= M; } } } } return t; } Mat pw(Mat a, long long b) { Mat ans; //ans.mat[0][0] = 1; //ans.mat[1][0] = 1; //ans.mat[0][1] = 1; //ans.mat[1][1] = 0; while(b) { if (b & 1) ans = mul(ans, a); a = mul(a, a); b >>= 1; } return ans; } int main() { Mat a; a.mat[0][0] = 1; a.mat[0][1] = 1; a.mat[1][0] = 1; a.mat[1][1] = 0; long long n; scanf("%lld", &n); printf("%d\n", a.mat[1][1]); }
true
74e0ae59b2dcbf96704dffba010b66776e01bfa9
C++
sane03/Data-Intensive-Computing-in-Data-Science
/Lab2/pthread_diagonalTranspose.cpp
UTF-8
2,466
3.5
4
[]
no_license
#include <pthread.h> #include <iostream> #include <cstdlib> #include <vector> #include <time.h> #include <sys/time.h> #define NUM_THREADS 4 int** matrix; struct ThreadInfo { int thread_id; int matrix_size; int diagonal_index; }; /* Generates and Populates an n by n square matrix A with random numbers*/ int** randMatrix(int n) { int** A = new int*[n]; for(auto i = 0; i < n; i++) { A[i] = new int[n]; for(auto j = 0; j < n; j++) { A[i][j] = rand() % n; } } return A; } void* diagonalRowColumnExchange(void* threadArg) { struct ThreadInfo* data; data = (struct ThreadInfo*) threadArg; auto start = data -> thread_id + data -> diagonal_index + 1; auto increament = NUM_THREADS; auto index = data -> diagonal_index; for(auto i = start; i < data -> matrix_size; i+= increament) { std::swap(matrix[index][i], matrix[i][index]); } pthread_exit(NULL); } int** threadedDiagonalMatrixTranspose(int n) { pthread_t threads[NUM_THREADS]; struct ThreadInfo thread_data[NUM_THREADS]; for(auto i = 0; i < n; i++) { for(auto j = 0; j < NUM_THREADS; j++) { thread_data[j].thread_id = j; thread_data[j].diagonal_index = i; thread_data[j].matrix_size = n; /* Create NUM_THREADS threads and let each thread perform the row col exchange */ pthread_create(&threads[j], NULL, diagonalRowColumnExchange, (void*)&thread_data[j]); } for(auto k = 0; k < NUM_THREADS; k++) { pthread_join(threads[k], NULL); } } return matrix; } /* Determines the time taken to perform the tranpose operation on matrix A */ void benchMark(int n) { struct timeval start, end; gettimeofday(&start, NULL); threadedDiagonalMatrixTranspose(n); gettimeofday(&end, NULL); double elapsed = ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec))/ 1e6; std::cout << "Threaded diagonal transposition for N = " << n << ": " << elapsed << std::endl; } int main() { srand(time(NULL)); std::vector<int> sizes{128, 1024, 2048, 4096, 8192, 16384}; for(auto n : sizes) { matrix = randMatrix(n); benchMark(n); for(auto i = 0; i <n; i++) { delete[] matrix[i]; } delete[] matrix; } return 0; }
true
68d2426808aa128906abd0324d43ee9f415be2e4
C++
samueltrussell/CodeSamples
/Monster Engine Project/MonsterEngine/Timing.h
UTF-8
1,623
2.609375
3
[]
no_license
#ifndef TIMING_H #define TIMING_H #define MAX_FRAME_RATE 120.0f #include <WinBase.h> namespace Engine { namespace Timing { LARGE_INTEGER lastCount; LARGE_INTEGER initCount; LARGE_INTEGER frequency; #ifdef MAX_FRAME_RATE double minFrameTime = 1000.0f / MAX_FRAME_RATE; #endif bool Initialize() { QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&initCount); QueryPerformanceCounter(&lastCount); return true; } LARGE_INTEGER TotalRunTime() { LARGE_INTEGER currentCounts, totalTimeCounts; QueryPerformanceCounter(&currentCounts); totalTimeCounts.QuadPart = currentCounts.QuadPart - initCount.QuadPart; return totalTimeCounts; } double CalcLastFrameTime() { LARGE_INTEGER currentCount; QueryPerformanceCounter(&currentCount); LARGE_INTEGER elapsedCount; elapsedCount.QuadPart = currentCount.QuadPart - lastCount.QuadPart; elapsedCount.QuadPart *= 1000000; elapsedCount.QuadPart /= frequency.QuadPart; lastCount = currentCount; double dT = elapsedCount.QuadPart/1000.0f; #ifdef MAX_FRAME_RATE if (dT > 3.0 * minFrameTime) { return minFrameTime; } #endif return dT; } double CalcCurrentFrameTime() { LARGE_INTEGER currentCount; QueryPerformanceCounter(&currentCount); LARGE_INTEGER elapsedCount; elapsedCount.QuadPart = currentCount.QuadPart - lastCount.QuadPart; elapsedCount.QuadPart *= 1000000; elapsedCount.QuadPart /= frequency.QuadPart; double dT = elapsedCount.QuadPart / 1000.0f; return dT; } }//namespace Timing }//namespace Engine #endif //TIMING_H
true
91f05f6d9ed108f8f270689c42b8d410e37ed05b
C++
linksplatform/Data
/cpp/Platform.Data/ILinksExtensions.h
UTF-8
6,109
3.015625
3
[ "Unlicense" ]
permissive
namespace Platform::Data { using namespace Platform::Interfaces; template<typename TStorage> static typename TStorage::LinkAddressType Create(TStorage& storage, const typename TStorage::LinkType& substitution) { auto $continue { storage.Constants.Continue }; typename TStorage::LinkAddressType createdLinkAddress; storage.Create(substitution, [&createdLinkAddress, $continue] (const typename TStorage::LinkType& before, const typename TStorage::LinkType& after) { createdLinkAddress = after[0]; return $continue; }); return createdLinkAddress; } template<typename TStorage> static typename TStorage::LinkAddressType Create(TStorage& storage, std::convertible_to<typename TStorage::LinkAddressType> auto ...substitutionPack) { typename TStorage::LinkType substitution { static_cast<typename TStorage::LinkAddressType>(substitutionPack)... }; auto $continue { storage.Constants.Continue }; typename TStorage::LinkAddressType createdLinkAddress; storage.Create(substitution, [&createdLinkAddress, $continue] (const typename TStorage::LinkType& before, const typename TStorage::LinkType& after) { createdLinkAddress = after[0]; return $continue; }); return createdLinkAddress; } template<typename TStorage> static typename TStorage::LinkAddressType Update(TStorage& storage, const typename TStorage::LinkType& restriction, const typename TStorage::LinkType& substitution) { auto $continue{storage.Constants.Continue}; typename TStorage::LinkAddressType updatedLinkAddress; storage.Update(restriction, substitution, [&updatedLinkAddress, $continue] (const typename TStorage::LinkType& before, const typename TStorage::LinkType& after) { updatedLinkAddress = after[0]; return $continue; }); return updatedLinkAddress; } template<typename TStorage> static typename TStorage::LinkAddressType Delete(TStorage& storage, const typename TStorage::LinkType& restriction) { auto $continue{storage.Constants.Continue}; typename TStorage::LinkAddressType deletedLinkAddress; storage.Delete(restriction, [&deletedLinkAddress, $continue] (const typename TStorage::LinkType& before, const typename TStorage::LinkType& after) { deletedLinkAddress = before[0]; return $continue; }); return deletedLinkAddress; } template<typename TStorage> static typename TStorage::LinkAddressType Delete(TStorage& storage, typename TStorage::LinkAddressType linkAddress) { auto $continue{storage.Constants.Continue}; typename TStorage::LinkAddressType deletedLinkAddress; storage.Delete(typename TStorage::LinkType{linkAddress}, [&deletedLinkAddress, $continue] (const typename TStorage::LinkType& before, const typename TStorage::LinkType& after) { deletedLinkAddress = before[0]; return $continue; }); return deletedLinkAddress; } template<typename TStorage> static typename TStorage::LinkAddressType Count(const TStorage& storage, std::convertible_to<typename TStorage::LinkAddressType> auto ...restrictionPack) // TODO: later add noexcept(expr) { typename TStorage::LinkType restriction { static_cast<typename TStorage::LinkAddressType>(restrictionPack)... }; return storage.Count(restriction); } template<typename TStorage> static bool Exists(const TStorage& storage, typename TStorage::LinkAddressType linkAddress) noexcept { constexpr auto constants = storage.Constants; return IsExternalReference<typename TStorage::LinkAddressType, constants>(linkAddress) || (IsInternalReference<typename TStorage::LinkAddressType, constants>(linkAddress) && Count(storage, linkAddress) > 0); } template<typename TStorage> static typename TStorage::LinkAddressType Each(const TStorage& storage, const typename TStorage::ReadHandlerType& handler, std::convertible_to<typename TStorage::LinkAddressType> auto... restriction) // TODO: later create noexcept(expr) { typename TStorage::LinkType restrictionContainer { static_cast<typename TStorage::LinkAddressType>(restriction)... }; return storage.Each(restrictionContainer, handler); } template<typename TStorage> static typename TStorage::LinkType GetLink(const TStorage& storage, typename TStorage::LinkAddressType linkAddress) { constexpr auto constants = storage.Constants; auto $continue = constants.Continue; auto any = constants.Any; if (IsExternalReference<typename TStorage::LinkAddressType, constants>(linkAddress)) { typename TStorage::LinkType resultLink {linkAddress, linkAddress, linkAddress}; return resultLink; } typename TStorage::LinkType resultLink; storage.Each(typename TStorage::LinkType{linkAddress}, [&resultLink, $continue](const typename TStorage::LinkType& link) { resultLink = link; return $continue; }); Ensures(!resultLink.empty()); return resultLink; } template<typename TStorage> static bool IsFullPoint(TStorage& storage, typename TStorage::LinkAddressType link) { if (IsExternalReference(storage.Constants, link)) { return true; } Ensures(Exists(storage, link)); return Point<typename TStorage::LinkAddressType>::IsFullPoint(storage.GetLink(link)); } template<typename TStorage> static bool IsPartialPoint(TStorage& storage, typename TStorage::LinkAddressType link) { if (IsExternalReference(storage.Constants, link)) { return true; } Ensures(Exists(storage, link)); return Point<typename TStorage::LinkAddressType>::IsPartialPoint(storage.GetLink(link)); } }
true
4e02649a37db55f60b9f7b37f4c99faebbd7caa4
C++
thinkpiece/EasySaliency
/src/saliency.h
UTF-8
4,281
2.65625
3
[]
no_license
/** * @file saliency.h * @author Junyoung Park (thinkpiece@yahoo.com) * @brief Saliency-based Visual Attention Implementation * * Simple implementation for saliency-based visual attention model, which was * proposed by Itti. See below for details: * * H. Greenspan, et al., "Overcomplete steerable pyramid filters and rotation * invariance," Proc. IEEE CVPR, 1994. * */ #ifndef __EASY_SALIENCY_H__ #define __EASY_SALIENCY_H__ #include "scalespace.h" #include "normalizer.h" #include <vector> #include <opencv2/core/core.hpp> namespace cv { class SaliencyMap { public: /** there are two normalization method supported */ enum NormalizationMethod { kLocalMaxNormalize, kIterativeNormalize }; /** default constructor */ SaliencyMap(NormalizationMethod norm_method=kIterativeNormalize, bool ifdebug=false); ~SaliencyMap(); bool Compute(const Mat& image); /** returns the saliency map */ Mat get_saliency_map() const; /** returns the conspicuity map for intensity */ Mat get_conspicuity_map_intensity() const; /** returns the conspicuity map for color */ Mat get_conspicuity_map_color() const; /** returns the conspicuity map for orientation */ Mat get_conspicuity_map_orientation() const; /** @name Setting Parameters */ ///@{ /** set the center level */ void set_center_pyramid_level(unsigned int min, unsigned int max); /** set the surround level */ void set_surround_pyramid_level(unsigned int min, unsigned int max); /** set the saliency map level */ void set_saliency_map_level(unsigned int level); ///@} protected: /** generates feature channels * * @note * In this implementation, a total of 9 channels are used as features. * Intensity, Red color, Green color, Blue color, Yellow color, * Orientation with 0 degree, 45 degree, 90 degree, 135 degree. */ void GenerateFeatureChannels(const Mat& image, Mat& intensity_channel, Mat& red_channel, Mat& green_channel, Mat& blue_channel, Mat& yellow_channel, Mat& orient_0_channel, Mat& orient_45_channel, Mat& orient_90_channel, Mat& orient_135_channel); /** generates the feature maps based on center-surround difference model * * @note * Center-surround difference between a "center" fine scale and a "surround" * coarser scale yields the feature maps. */ void GenerateFeatureMaps(const ScaleSpace& pyramid, std::vector<Mat>& feature_maps); /** generates the feature maps based on excitation-inhibition model * * @note * For the color feature maps (Red-Green, and Blue-Yellow), a theory * a.k.a. "color double-opponent" system is adopted in this implementation. * According to the theory, in the center of the receptive field, neurons * are exicted by one color (e.g., red) and inhibited by another (e.g., green), * while the converse is true in the surround. Such spatial and chromatic * opponency exists for the red/green, blue/yellow pairs in human primary * visual cortex. */ void GenerateFeatureMapsEI(const ScaleSpace& pyramid_excitation, const ScaleSpace& pyramid_inhibition, std::vector<Mat>& feature_maps); void GenerateConspicuity(const std::vector<Mat>& maps, Mat& conspicuity); void AttenuateBorders(const int size, Mat& image); Size getGaborSize(const float sigma, const float gamma, const float theta); // void testMap(const Mat& testMap, const char *name); Mat ConvertMap(const Mat& image) const; private: Size saliency_map_shape_; unsigned int pyramid_level_; unsigned int saliency_level_; unsigned int center_level_min_; unsigned int center_level_max_; unsigned int surround_delta_min_; unsigned int surround_delta_max_; Normalizer *normalizer_; Mat conspicuity_map_intensity_; Mat conspicuity_map_color_; Mat conspicuity_map_orientation_; Mat saliency_map_; // for debug mode bool debug_; }; } #endif
true
3392ed9df07598f518c73ac98c2ccfffeb04a8a3
C++
PortfolioJohannOstero/GameEngineConstruction
/Dooperfighters/Dooperfighters/SheepDebugMessage.h
IBM852
2,236
2.953125
3
[]
no_license
#ifndef SHEEP_DEBUG_MESSAGE #define SHEEP_DEBUG_MESSAGE /* +=============================================+ +==============================================+ Debug Message.h Engine: Sheep Engine Author: Jhann ster. -- The Debug class is semi-purely there to make debugging and testing easier. it allows the client to output message to a "console" by taking strings and other extensions (that the get turned into strings). This Class can be accessed from anywhere! It allows for three different colours, White(normal), Yellow(warning), Red(error) By default it will always be white +==============================================+ +============================================+ */ #include <HAPI_lib.h> #include <vector> namespace Sheep { #define DEBUG_MESSAGE Sheep::DebugMessage::getInstance() enum MESSAGE_TYPE { NORMAL = 0, WARNING, ERROR }; struct Message { std::string message; MESSAGE_TYPE type; DWORD timestamp; Message() {} Message(const std::string& newMessage, const MESSAGE_TYPE messageType) : message(newMessage), type(messageType) {} }; class Vector2; class DebugMessage { public: /* +==== Singleton ====+ */ static void Create(); static void Destroy(); static DebugMessage& getInstance() { return *INSTANCE; } bool Initialise(const Vector2& windowPos, unsigned short maxRowOfMessage, unsigned int rowPadding); /* +==== Message Handling ====+ */ void PushMessage(const std::string& message, MESSAGE_TYPE type = MESSAGE_TYPE::NORMAL); // Extensions: void PushMessage(const Vector2& message, MESSAGE_TYPE type = MESSAGE_TYPE::NORMAL); /* +==== Render Text ====+ */ void RenderMessages(); /* +=== Toggles ===+ */ void Display(bool state); void DisplayTimeStamp(bool state); /* +=== Getter ===+ */ bool isDisplayOn() const; private: static DebugMessage* INSTANCE; HAPI_TColour mErrorColour{ 255, 12, 12 }; HAPI_TColour mWarningColour{ 255, 255, 12 }; HAPI_TColour mMessageColour; // <-- white std::vector<Message> mMessages; unsigned int mIndex = 0; Vector2* mWindowPosition = nullptr; unsigned int mRowPadding; bool mDisplayTimeStamp = true; bool mDisplayWindow = true; DebugMessage() {} ~DebugMessage(); }; } #endif
true
fc13f514b372cc46e469ad7395e83bd44a5a9592
C++
vdovych/meshell
/mymkdir.cpp
UTF-8
647
2.765625
3
[]
no_license
// // Created by stanislav on 08.06.18. // #include "mymkdir.h" int main(int argc, char **argv) { string dest; bool promi = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { cout << "Stuff" << endl; return 0; } if (strcmp(argv[i], "-p") == 0) promi = true; else dest = argv[i]; } if (!promi) { if (mkdir(dest.c_str(), S_IRWXG | S_IRWXO | S_IRWXU) < 0) { perror(dest.c_str()); return 1; } } else { recmkdir(dest); } return 0; }
true
3484787d8578b1da0aecf742c54ed46fa5503bb4
C++
Ravi2155/competitive_coding
/Rated competition Codes/The Last Problem.cpp
UTF-8
2,953
2.984375
3
[]
no_license
/* Solution by Rahul Surana *********************************************************** Deep wants to become a 7-star coder on CodeChef. To achieve this goal, everyday, he has to solve as many problems as he can. But for the first time since he was new to programming, he wasn't able to solve a single problem and lost his confidence. Can you help him solve the problem so that he gets a new boost to go ahead? In this problem, you are given a matrix that extends infinitely to the right and down, filled with values as shown below. 1 2 4 7 . . 3 5 8 . . . 6 9 . . . . 10 . . . . . . . . . . Let (x,y) denote the cell in the x-th row and y-th column. The upper-left cell (1,1) contains an integer 1. You begin at the cell (x1,y1) and must walk to the cell (x2,y2) by only moving right and down. Formally, from the cell (x,y), in one step you can move to the cell (x+1,y) or (x,y+1). The value of a path is the sum of the values in all visited cells, including (x1,y1) and (x2,y2). You need to calculate the maximum possible value on the path of a path from (x1,y1) to (x2,y2). Input The first line contains an integer T, the number of test cases. Then the test cases follow. Each test case contains of a single line of input, four integers x1, y1, x2, y2. Output For each test case, output in a single line the maximum possible value of a path from (x1,y1) to (x2,y2). *********************************************************** */ #include <bits/stdc++.h> #define ll long long #define vl vector<ll> #define vi vector<int> #define pi pair<int,int> #define pl pair<ll,ll> #define all(a) a.begin(),a.end() #define mem(a,x) memset(a,x,sizeof(a)) #define pb push_back #define mp make_pair #define F first #define S second #define FOR(i,a) for(int i = 0; i < a; i++) #define trace(x) cerr<<#x<<" : "<<x<<endl; #define trace2(x,y) cerr<<#x<<" : "<<x<<" | "<<#y<<" : "<<y<<endl; #define trace3(x,y,z) cerr<<#x<<" : "<<x<<" | "<<#y<<" : "<<y<<" | "<<#z<<" : "<<z<<endl; #define fast_io std::ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define MOD 1000000007 using namespace std; int ar[1001][1001]; int main() { fast_io; for(int i = 1; i <= 1000; i++) { ar[i][1] = (i*(i+1))/2; int k = i; int m = i; for(int j = 2; j <= 1000; j++){ ar[i][j] = ar[i][j-1] + m; k += m; m++; } } // for(int i = 1; i <= 10; i++) { // for(int j = 1; j <= 10; j++){ // cout << ar[i][j] << " "; // } // cout << "\n"; // } int t; cin >> t; while(t--) { int x1,y1,x2,y2; cin >>x1>>y1>>x2>>y2; ll sum = 0; while(x1 <= x2) { sum += ar[x1][y1]; x1++; } y1++; while(y1 <= y2) { sum += ar[x2][y1]; y1++; } cout << sum << "\n"; } }
true
d26f7da0fc809168f707f7fb8384773f39122b4e
C++
adriengivry/ElkEngine
/ElkEngine/ElkRendering/src/Data/CameraData.cpp
UTF-8
2,581
2.84375
3
[ "MIT" ]
permissive
#include "stdafxRendering.h" #include "ElkRendering/Data/CameraData.h" using namespace ElkRendering::Data; // Default camera values const float CameraData::PITCH = 0.0f; const float CameraData::YAW = -90.0f; const float CameraData::ROLL = 0.0f; const float CameraData::SPEED = 2.5f; const float CameraData::SENSITIVITY = 0.1f; const float CameraData::ZOOM = 45.0f; CameraData::CameraData( const glm::vec3 p_position, const glm::vec3 p_up, const float p_pitch, const float p_yaw, const float p_roll) : m_front(glm::vec3(0.0f, 0.0f, -1.0f)), m_movementSpeed(SPEED), m_mouseSensitivity(SENSITIVITY), m_zoom(ZOOM) { m_position = p_position; m_worldUp = p_up; m_pitch = p_pitch; m_yaw = p_yaw; m_roll = p_roll; UpdateCameraVectors(); } CameraData::CameraData( const float p_posX, const float p_posY, const float p_posZ, const float p_upX, const float p_upY, const float p_upZ, const float p_pitch, const float p_yaw, const float p_roll) : m_front(glm::vec3(0.0f, 0.0f, -1.0f)), m_movementSpeed(SPEED), m_mouseSensitivity(SENSITIVITY), m_zoom(ZOOM) { m_position = glm::vec3(p_posX, p_posY, p_posZ); m_worldUp = glm::vec3(p_upX, p_upY, p_upZ); m_pitch = p_pitch; m_yaw = p_yaw; m_roll = p_roll; UpdateCameraVectors(); } void CameraData::Setup() { } glm::mat4 CameraData::GetViewMatrix() { return glm::lookAt(m_position, m_position + m_front, m_up); } void CameraData::ProcessRotationMovement(const glm::vec3& p_rotation) { m_pitch = p_rotation.x; m_yaw = p_rotation.y; m_roll = p_rotation.z; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (m_pitch > 89.0f) m_pitch = 89.0f; if (m_pitch < -89.0f) m_pitch = -89.0f; // Update Front, Right and Up Vectors using the updated Euler angles UpdateCameraVectors(); } void CameraData::UpdateCameraVectors() { // Calculate the new Front vector glm::vec3 front; front.x = cos(glm::radians(m_pitch)) * cos(glm::radians(m_yaw)); front.y = sin(glm::radians(m_pitch)); front.z = cos(glm::radians(m_pitch)) * sin(glm::radians(m_yaw)); m_front = glm::normalize(front); // Also re-calculate the Right and Up vector m_right = glm::normalize(glm::cross(m_front, m_worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. m_up = glm::normalize(glm::cross(m_right, m_front)); // calculate the right vector m_right = glm::normalize( m_right * cos(m_roll) + m_up * sin(m_roll) ); // calculate the new up vector m_up = glm::cross(m_front, m_right); m_up *= -1; }
true
e82f6a4754d657d5c27cfeadb81bf1a5b92ab26f
C++
buptlxb/leetcode
/2nd/152_maximum_product_subarray.cpp
UTF-8
819
2.84375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int maxProduct(vector<int>& nums) { if (nums.empty()) return 0; vector<int> gmax(2, nums.front()), lmax(gmax), lmin(lmax); int idx = 0; for (auto i = nums.begin()+1, iend = nums.end(); i != iend; ++i) { lmax[idx] = trimax(lmax[1-idx] * *i, lmin[1-idx] * *i, *i); lmin[idx] = trimin(lmax[1-idx] * *i, lmin[1-idx] * *i, *i); gmax[idx] = max(gmax[1-idx], lmax[idx]); idx = 1 - idx; } return gmax[1-idx]; } int trimin(int a, int b, int c) { return min(a, min(b, c)); } int trimax(int a, int b, int c) { return max(a, max(b, c)); } }; int main(void) { return 0; }
true
7240cf703106afec8c738b56d9e36d0612988f50
C++
chrystallagh/HavadjiaChrystalla_CSC17a_42824
/Project/Project_2/Project2.V3/UsrInpt.cpp
UTF-8
1,090
2.953125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: UsrInpt.cpp * Author: chrystallahavadjia * * Created on May 18, 2016, 7:06 PM */ #include<iostream> using namespace std; #include "UsrInpt.h" //definition of static variable string UsrInpt::order[4]={"First","Second","Third","Fourth"}; //default constructor UsrInpt::UsrInpt() { mxPlys=0; hint=0; } //mutator functions void UsrInpt::setMxPlys(int m){//assigns value to variable mxPlys = m; } void UsrInpt::setHint(int h){//assigns value to variable hint = h; } //acessor functions int UsrInpt::getMxPlys() const{ return mxPlys; //returns value in member } int UsrInpt::getHint() const{ return hint; } //print funtion void UsrInpt::prntOrder(int j){ for(int i=0;i<4;i++){ if(i==j) cout << order[i]; } } //overload postfix and prefix operators UsrInpt UsrInpt::operator++(){ ++mxPlys; getMxPlys(); return *this; }
true
e2af86ceb1967d69b57ea8e76c274a791aad4c21
C++
kobake/KppLibs
/LogLib/src/Log.h
SHIFT_JIS
607
3.25
3
[]
no_license
#pragma once #include <string> //### LogoϐɎƒNXconst֐łprintĂׂ悤ɁA //### printconst֐ɂĂ邪A͐HH //! Oo̓NX class Log{ public: //RXgN^EfXgN^ Log() : enabled(true) { } virtual ~Log(){} //XCb` void setEnabled(bool b){ enabled=b; } bool isEnabled() const{ return enabled; } //o void print(const wchar_t* str, ...) const; void print(const std::string& str) const; void print(const std::wstring& str) const; private: bool enabled; };
true
647dbd9c1297ec4329c759bae6672c213723d62e
C++
TJArk-Robotics/coderelease_2017
/Src/Platform/Linux/DebugHandler.h
UTF-8
1,382
3
3
[ "BSD-2-Clause" ]
permissive
/** * @file Platform/linux/DebugHandler.h * * Class for debug communication over a TCP connection * * @author <A href="mailto:Thomas.Roefer@dfki.de">Thomas Röfer</A> */ #pragma once #include "Tools/Debugging/TcpConnection.h" #include "Tools/MessageQueue/MessageQueue.h" class DebugHandler : TcpConnection { public: /** * Constructor. * @param in The message queue that stores data received. * @param out The message queue containing data to be sent. * @param maxPackageSendSize The maximum size of an outgoing package. * If 0, this setting is ignored. * @param maxPackageReceiveSize The maximum size of an incouming package. * If 0, this setting is ignored. */ DebugHandler(MessageQueue& in, MessageQueue& out, int maxPackageSendSize = 0, int maxPackageReceiveSize = 0); /** * Destructor. * Delete buffered package if needed. */ ~DebugHandler() {if(sendData) delete [] sendData;} /** * The method performs the communication. * It has to be called at the end of each frame. * @param send Send outgoing queue? */ void communicate(bool send); private: MessageQueue& in, /**< Incoming debug data is stored here. */ & out; /**< Outgoing debug data is stored here. */ unsigned char* sendData; /**< The data to send next. */ int sendSize; /**< The size of the data to send next. */ };
true
92b0b7c6229ac319aa1698ec4a0ca96e0a27e4f6
C++
utec-ads-2019-2/babelfish-10282-ccaballerof00
/main.cpp
UTF-8
1,114
3.234375
3
[]
no_license
#include <iostream> #include <map> #include <vector> using namespace std; map<string,string> diccionario; void separar_strings(vector<string> a) { for(auto it : a) { string palabra1; string palabra2; bool p1 = true; bool p2 = false; for(int i = 0; i < it.length();i++ ) { if(p2) { palabra2+=it[i]; } if(it[i]==' ') { p1 = false; p2 = true; } if(p1) { palabra1+=it[i]; } } diccionario[palabra2] = palabra1; palabra1.clear(); palabra2.clear(); } } int main() { string inp="hola"; vector<string> inps; while(!inp.empty()) { getline(cin,inp); inps.push_back(inp); } separar_strings(inps); string inp2; while(cin>>inp2) { if(!diccionario[inp2].empty()) { cout<<diccionario[inp2]<<endl; } else { cout<<"eh"<<endl; } } }
true
7122393ad1e54c91ad78653d539031531f9a1c5b
C++
timkostka/cert3d
/firmware/GSL/inc/gsl_error.h
UTF-8
10,697
2.765625
3
[]
no_license
#pragma once #include <cstdint> #include <climits> #include "gsl_includes.h" // typedef to a void function with no arguments typedef void (*GSL_ERROR_HandlerFunction)(); // if not null, this will be called when we encounter a hard fault GSL_ERROR_HandlerFunction gsl_error_handler = nullptr; // this will output the current code position to the log #define LOG_POSITION \ LOG("\n"); \ if (!gsl_delog_add_timestamps) { \ LOG(GSL_GEN_GetTimestampSinceReset(), ": "); \ } \ LOG("In file ", GSL_BaseFilename(__FILE__)); \ LOG(" at line ", __LINE__); \ LOG(" in function ", __func__) // forward defines so blinking the error LED will work void GSL_PIN_Toggle(PinEnum pin); void GSL_PIN_SetLow(PinEnum pin); void GSL_PIN_Initialize( PinEnum pin, uint32_t gpio_mode, uint32_t resistor_mode, uint32_t gpio_speed); void GSL_PIN_Deinitialize(PinEnum pin); void GSL_DEL_MS(uint32_t delay_ms); // HALT(message) // stops the program and outputs debug information // ASSERT(statement) // if statement is false, stops the program and outputs debug information // This provides the HALT("message") macro which stops program execution as // well as the LOG function implementation // // In particular, the following function must be defined somewhere in your // compilation unit: // void LOG(const char * message); // return the filename without the path const char * GSL_BaseFilename (const char * filename) { const char * ptr = filename; while (*(++filename)) { if (*filename == '/' || *filename == '\\') { ptr = filename + 1; } } return ptr; } // forward declaration void GSL_DELOG_OutputRemainderBlocking(void); // blink the error LED [[noreturn]] void GSL_ERR_BlinkError(void) { __disable_irq(); GSL_DELOG_OutputRemainderBlocking(); GSL_PIN_Deinitialize(GSL_LED_ERROR_PIN); GSL_PIN_Initialize( GSL_LED_ERROR_PIN, GPIO_MODE_OUTPUT_PP, GPIO_NOPULL, GPIO_SPEED_LOW); GSL_PIN_SetLow(GSL_LED_ERROR_PIN); while (1) { for (uint8_t led_blink_cycle = 0; led_blink_cycle < 6; ++led_blink_cycle) { GSL_DEL_MS(100); GSL_PIN_Toggle(GSL_LED_ERROR_PIN); } GSL_DEL_MS(1000); if (gsl_error_handler) { GSL_DEL_MS(900); gsl_error_handler(); } } } // if handler is defined, call it, else loop forever // at the start, we set the USART interrupt priority to the highest possible // so that the debug log clears out #define BLINK_ERROR GSL_ERR_BlinkError() // run the following statements the first X times it is encountered #define LIMITED_RUN(times) \ static uint16_t run_count = 0; \ if (run_count <= (times)) { \ ++run_count; \ } \ if (run_count <= (times)) // output a message the first X times it is encountered #define LIMITED_LOG(times, ...) \ { \ static uint16_t output_count = 0; \ if (output_count < (times)) { \ LOG(__VA_ARGS__); \ ++output_count; \ } \ } \ ((void) 0) // output a message the first time it is encountered #define LOG_ONCE(...) LIMITED_LOG(1, ##__VA_ARGS__) // output the position once #define LOG_POSITION_ONCE \ LOG_ONCE("\n", GSL_GEN_GetTimestampSinceReset()); \ LOG_ONCE(": In file ", GSL_BaseFilename(__FILE__), " at line ", __LINE__, " in function ", __func__) // log the file, function and line number #define LOG_LOCATION \ LOG("\n"); \ LOG("\nWithin file: ", GSL_BaseFilename(__FILE__)); \ LOG("\n Function: ", __func__); \ LOG("\n Line: ", __LINE__) // stop execution with the following message #define HALT(...) \ LOG("\n\n"); \ LOG(__VA_ARGS__); \ LOG_LOCATION; \ LOG("\n\nExecution has been halted."); \ BLINK_ERROR // log the duration it took to do something #define LOG_DURATION(...) { \ uint32_t start_tick = GSL_DEL_Ticks(); \ {\ __VA_ARGS__; \ } \ LOG("\nIt took ", GSL_DEL_ElapsedUS(start_tick), " us."); \ } // generic assert comparison operator #define ASSERT_GEN(one, two, type, infix) { \ auto one_value = one; \ auto two_value = two; \ if (!(one_value infix two_value)) { \ LOG("\n\nASSERT_" type " FAILED:"); \ LOG("\n\nStatement: ", #one, " (", one_value, ") " #infix " "); \ LOG(#two, " (", two_value, ")"); \ LOG_LOCATION; \ LOG("\n\nExecution has been halted."); \ BLINK_ERROR; \ } \ } \ ((void) 0) // assert order between two values #define ASSERT_EQ(one, two) ASSERT_GEN(one, two, "EQ", ==) #define ASSERT_NE(one, two) ASSERT_GEN(one, two, "NE", !=) #define ASSERT_GT(one, two) ASSERT_GEN(one, two, "GT", >) #define ASSERT_GE(one, two) ASSERT_GEN(one, two, "GE", >=) #define ASSERT_LT(one, two) ASSERT_GEN(one, two, "LT", <) #define ASSERT_LE(one, two) ASSERT_GEN(one, two, "LE", <=) // assert a statement is true, else halt #define ASSERT(...) if (!(__VA_ARGS__)) { \ LOG("\n\nASSERT FAILED:"); \ LOG("\n\nStatement: ", #__VA_ARGS__); \ LOG_LOCATION; \ LOG("\n\nExecution has been halted."); \ BLINK_ERROR; \ } \ ((void) 0) // run a function that return a HAL_StatusTypeDef and error out if it doesn't // return HAL_OK #define HAL_RUN(...) \ { \ HAL_StatusTypeDef result = __VA_ARGS__; \ if (result != HAL_OK) { \ LOG("\n\nHAL routine failed:"); \ LOG("\n\nStatement: ", #__VA_ARGS__); \ LOG("\n\nReturn code was "); \ if (result == HAL_ERROR) {LOG("HAL_ERROR");} \ else if (result == HAL_BUSY) {LOG("HAL_BUSY");} \ else if (result == HAL_TIMEOUT) {LOG("HAL_TIMEOUT");} \ else {LOG(result);} \ LOG(" (", result, ")."); \ LOG("\nWe were expecting HAL_OK (0)."); \ LOG_LOCATION; \ LOG("\n\nExecution has been halted."); \ BLINK_ERROR; \ } \ } \ ((void) 0) // these must be defined elsewhere void LOG(const char * message); const char * GSL_OUT_Integer(uint32_t value); // log a uint64_t void LOGUINT64(uint64_t value) { uint64_t place = 1; // find largest place while (place < value && place < 1e19) { place *= 10; } if (place > value && place > 1) { place /= 10; } // output each character char out[2] = {0, 0}; while (place) { out[0] = '0' + (value / place) % 10; LOG(out); place /= 10; } } // log an unsigned integer void LOG(const uint64_t & in_value) { uint64_t value = in_value; // if the highest bit in value is set, we're going to assume the integer // is signed and output that instead if (value & 0x8000000000000000UL) { value ^= 0xFFFFFFFFFFFFFFFFUL; LOG("-"); } // if it's small enough, call the quicker function if (value <= UINT_MAX) { LOG(GSL_OUT_Integer(value)); } else { LOGUINT64(value); } } // log a uint8_t void LOG(const short int & value) { LOG(GSL_OUT_Integer(value)); } // log a uint8_t void LOG(const unsigned short int & value) { LOG(GSL_OUT_Integer(value)); } // log an int void LOG(const int & value) { LOG(GSL_OUT_Integer(value)); } // log an int void LOG(const unsigned int & value) { LOG(GSL_OUT_Integer(value)); } // log an int void LOG(const long int & value) { LOG(GSL_OUT_Integer(value)); } // log an int void LOG(const unsigned long int & value) { LOG(GSL_OUT_Integer(value)); } // log a pointer /*void LOG(void * ptr) { LOG((uint32_t) ptr); }*/ const char * GSL_OUT_FixedFloat(float value, uint8_t places, bool force_sign = false); // log a float void LOG(float value) { if (value < 0.0f) { LOG("-"); value *= -1.0f; } if (value == 0.0f) { LOG("0"); } else if (value < 0.0001f) { LOG(GSL_OUT_FixedFloat(value, 6)); } else if (value < 0.001f) { LOG(GSL_OUT_FixedFloat(value, 5)); } else if (value < 0.01f) { LOG(GSL_OUT_FixedFloat(value, 4)); } else if (value < 0.1f) { LOG(GSL_OUT_FixedFloat(value, 3)); } else if (value < 1.0f) { LOG(GSL_OUT_FixedFloat(value, 2)); } else if (value < 10.0f) { LOG(GSL_OUT_FixedFloat(value, 1)); } else { LOG(GSL_OUT_Integer(value + 0.5f)); } } // log two things template <class T, class T2> void LOG(T one, T2 two) { LOG(one); LOG(two); } // log three things template <class T, class T2, class T3> void LOG(T one, T2 two, T3 three) { LOG(one); LOG(two); LOG(three); } // log four things template <class T, class T2, class T3, class T4> void LOG(T one, T2 two, T3 three, T4 four) { LOG(one); LOG(two); LOG(three); LOG(four); } // log five things template <class T, class T2, class T3, class T4, class T5> void LOG(T one, T2 two, T3 three, T4 four, T5 five) { LOG(one); LOG(two); LOG(three); LOG(four); LOG(five); } // log six things template <class T, class T2, class T3, class T4, class T5, class T6> void LOG(T one, T2 two, T3 three, T4 four, T5 five, T6 six) { LOG(one); LOG(two); LOG(three); LOG(four); LOG(five); LOG(six); } // log seven things template <class T, class T2, class T3, class T4, class T5, class T6, class T7> void LOG(T one, T2 two, T3 three, T4 four, T5 five, T6 six, T7 seven) { LOG(one); LOG(two); LOG(three); LOG(four); LOG(five); LOG(six); LOG(seven); } // log seven things template <class T, class T2, class T3, class T4, class T5, class T6, class T7, class T8> void LOG(T one, T2 two, T3 three, T4 four, T5 five, T6 six, T7 seven, T8 eight) { LOG(one); LOG(two); LOG(three); LOG(four); LOG(five); LOG(six); LOG(seven); LOG(eight); } // log seven things template <class T, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> void LOG(T one, T2 two, T3 three, T4 four, T5 five, T6 six, T7 seven, T8 eight, T9 nine) { LOG(one); LOG(two); LOG(three); LOG(four); LOG(five); LOG(six); LOG(seven); LOG(eight); LOG(nine); } extern "C" { // this is used within the STM32 HAL files // Called from the assert_param() macro, usually defined in the stm32f*_conf.h void __attribute__((noreturn)) assert_failed (uint8_t* file, uint32_t line) { LOG("\n\nASSERT FAILED:"); LOG("\n\nFile: "); LOG((const char *) file); LOG(":"); LOG(line); LOG("\n\nExecution has been halted."); BLINK_ERROR; } } #define GSL_TIMEIT(...) { \ LOG("\n\nPerforming a timing test:"); \ LOG("\n- Statement: "#__VA_ARGS__); \ GSL_DELOG_WaitUntilEmpty(); \ uint32_t ticks_timeit = 0; \ ticks_timeit -= GSL_DEL_Ticks(); \ __VA_ARGS__; \ ticks_timeit += GSL_DEL_Ticks(); \ LOG("\n- It took ", ticks_timeit, " ticks"); \ float time_ns = (float) ticks_timeit / HAL_RCC_GetSysClockFreq() * 1e9; \ if (time_ns < 10000.0f) { \ LOG(" (", (uint32_t) (time_ns + 0.5f), " ns)"); \ } else if (time_ns < 10000000.0f) { \ LOG(" (", (uint32_t) (time_ns / 1e3 + 0.5f), " us)"); \ } else { \ LOG(" (", (uint32_t) (time_ns / 1e6 + 0.5f), " ms)"); \ } \ }
true
dfa0b02637fbf4028e4427d0672a90213022be7d
C++
PIDAMI/vsLaptop
/lab3_game_gems/lab3_game_gems/main.cpp
UTF-8
2,006
3.1875
3
[]
no_license
#include "Gems.hpp" #include <iostream> #include <exception> using namespace sf; //class Board : public RectangleShape { //public: // Board(size_t block_size,size_t board_size) { // for (int i = 0; i < board_size; i++) { // std::vector<RectangleShape> tmp; // for (int j = 0; j < board_size; j++) { // tmp.push_back(RectangleShape(Vector2f(block_size,block_size))); // } // _board.push_back(tmp); // } // } // void setColor(const std::vector<Color> colors) { // const size_t num_colors = colors.size(); // for (auto& line : _board) { // for (auto& block : line) { // block.setFillColor(colors[rand() % num_colors]); // } // } // } // // //private: // std::vector<std::vector<RectangleShape>> _board; //}; int main() { RenderWindow window(VideoMode(500, 500), "Gems"); const std::vector<Color> colors = { Color::Blue,Color::Green,Color::Red,Color::Yellow }; while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } window.clear(Color::White); //Board b(100, 5); //b.setFillColor({ Color::Black }); // define a 100x100 square, red, with a 10x10 texture mapped on it sf::Vertex vertices[] = { sf::Vertex(sf::Vector2f(0, 0), sf::Color::Red, sf::Vector2f(0, 0)), sf::Vertex(sf::Vector2f(0, 100), sf::Color::Red, sf::Vector2f(0, 10)), sf::Vertex(sf::Vector2f(100, 100), sf::Color::Red, sf::Vector2f(10, 10)), sf::Vertex(sf::Vector2f(100, 0), sf::Color::Red, sf::Vector2f(10, 0)) }; // draw it //window.draw(vertices, 4, sf::Quads); auto t = RectangleShape({ 50,100 }); t.setFillColor(Color::Blue); window.draw(t); window.display(); } return 0; }
true
20e34013079f58a9818f90bb56824a8e2e79e969
C++
hangim/ACM
/HDU/4864_Task/4864.cc
UTF-8
1,195
2.609375
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> #include <cstring> using namespace std; struct Node { int x, y; bool operator < (const Node &o) const { if (x != o.x) return x > o.x; return y > o.y; } }; Node mac[100001]; Node task[100001]; int c[101]; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m; while (cin >> n >> m) { for (int i = 0; i < n; i++) cin >> mac[i].x >> mac[i].y; for (int i = 0; i < m; i++) cin >> task[i].x >> task[i].y; sort(mac, mac + n); sort(task, task + m); memset(c, 0, sizeof(c)); int num = 0; long long money = 0; for (int i = 0, j = 0; i < m; i++) { while (j < n and mac[j].x >= task[i].x) { c[mac[j].y]++; j++; } for (int k = task[i].y; k <= 100; k++) { if (c[k]) { c[k]--; num++; money += 500 * task[i].x + 2 * task[i].y; break; } } } cout << num << " " << money << endl; } return 0; }
true
1e376bcd208d81019222367365518d169429866a
C++
qianfeng0/CodePractice
/LeetCode/345_ReverseVowelsofaString.cpp
UTF-8
1,381
4.125
4
[]
no_license
/* Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not include the letter "y". */ #include <string> #include <iostream> using namespace std; const string vowels = "aeiou"; class Solution { public: string reverseVowels(string s) { int i = 0, j = s.size() - 1; bool iVowel = false, jVowel = false; char temp; while(i < j){ if (iVowel && jVowel){ temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; iVowel = false; jVowel = false; } if (!iVowel){ if (vowels.find(tolower(s[i])) != string::npos){ iVowel = true; } else{ i++; } } if (!jVowel){ if (vowels.find(tolower(s[j])) != string::npos){ jVowel = true; } else{ j--; } } } return s; } }; int main() { Solution solution; string str = "leetcode"; cout << solution.reverseVowels(str) << endl; return 0; }
true
4a6af8fda6fd67c3bb55db2ad4f84da82be900b6
C++
Hatemmamdoh/recursion
/main.cpp
UTF-8
483
3.578125
4
[]
no_license
#include <iostream> using namespace std; int sumofdigit (int n) { int sum = 0 ; if (n == 0) return 0 ; sum = (n % 10 + sumofdigit(n / 10)) ; return sum ; } int DigitalRoot (int n) { int r = 0 ; if (n/10 == 0) return n ; r = DigitalRoot (sumofdigit (n)) ; return r ; } int main() { int number ; cout << "please enter the number :" ; cin >> number ; cout << "The Digital Root is: " << DigitalRoot(number) << endl ; return 0; }
true
2230832ad78a4c2aac10e8d9f3de6dbe3c75136a
C++
RomainH69/Puissance4
/Puissance4.cpp
UTF-8
1,568
2.828125
3
[]
no_license
#include "Puissance4.h" using namespace std; Puissance4::Puissance4(std::string _nom) :Jeu(_nom) { cout << "Puissance 4" << endl; int choix = -1; while (choix <0 || choix > 2) { cout << "Nouvelle Partie : contre l'ia (tapez 0) multijoueur (tapez 1) Ia vs Ia (tapez 2)" << endl; cout << "choix : "; cin >> choix; } if (choix == 0) { singlePlayer = true; joueur1 = new JoueurHumain("Jean", 'X'); joueur2 = new JoueurIA("Paul",'O'); } else if(choix == 1) { singlePlayer = false; joueur1 = new JoueurHumain("Jean", 'X'); joueur2 = new JoueurHumain("Pierre",'O'); } else if (choix == 2) { joueur1 = new JoueurIA("Pierre", 'X'); joueur2 = new JoueurIA("Paul", 'O'); } grille = new Grille(); } Puissance4::~Puissance4() { } void Puissance4::demarrer() { int a = 0; grille->Afficher(); while (grille->Gagne()=='N' && a<42) { if (a % 2 == 0) { joueur1->Jouer(grille); } else { joueur2->Jouer(grille); } a++; } grille->Afficher(); if(grille->Gagne() != 'N') std::cout << "Nous avons un gagnant !" << std::endl; else std::cout << "Plus de jetons" << std::endl; std::cout << "Entrez 1 pour recommencer" << std::endl; cin >> a; if (a) recommencer(); } void Puissance4::recommencer() { joueur1 = new JoueurHumain("Truc", 'X'); if (singlePlayer == true) joueur2 = new JoueurIA("Machin", 'O'); else joueur2 = new JoueurHumain("Chose", 'O'); grille->Initialiser(); Puissance4("jeu"); demarrer(); }
true
5e935ceedaf5a4308a2d18187358c383ec3c4d57
C++
mjww3/algorithms
/fibosum.cpp
UTF-8
670
2.890625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <math.h> #include <string> #include <algorithm> #include <vector> using namespace std; #define MAX 100000000 #define NIL -1 long long int lookup[MAX] = {NIL}; long long int fibonacci(int m) { if(lookup[m]==NIL) { if(m<=1) { lookup[m] = m; } else { lookup[m] = fibonacci(m-1)+fibonacci(m-2); } } return lookup[m]; } long long int result(int n,int m) { long long int sum = 0; for(int i=n;i<=m;i++) { sum = sum+lookup[i]; } } int main() { int t; cin>>t; int n, m; long long int gar = 0; while(t--) { cin>>n>>m; gar = fibonacci(m); cout<<result(n,m)<<endl; } return 0; }
true
9671f3da8ed7ca1883cb99e3a7211c1a2867920f
C++
PaddlePaddle/Paddle
/paddle/phi/core/utils/intrusive_ptr.h
UTF-8
4,254
2.84375
3
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2021 PaddlePaddle 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. */ #pragma once #include <utility> #include "glog/logging.h" #include "paddle/phi/core/enforce.h" namespace phi { template <typename T> class intrusive_ptr { public: using this_type = intrusive_ptr; constexpr intrusive_ptr() noexcept = default; ~intrusive_ptr() { if (px) { intrusive_ptr_release(px); } } intrusive_ptr(intrusive_ptr&& rhs) noexcept : px(rhs.px) { rhs.px = nullptr; } template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>> intrusive_ptr(intrusive_ptr<U>&& rhs) noexcept : px(rhs.get()) { rhs.reset(); } intrusive_ptr& operator=(intrusive_ptr&& rhs) { swap(rhs); return *this; } void reset() { this_type().swap(*this); } void reset(T* rhs) { this_type(rhs).swap(*this); } void reset(T* rhs, bool add_ref) { this_type(rhs, add_ref).swap(*this); } T* get() const noexcept { return px; } T* detach() noexcept { T* ret = px; px = nullptr; return ret; } T& operator*() const { PADDLE_ENFORCE_NOT_NULL( px, phi::errors::PreconditionNotMet( "The pointer must be non-null before the dereference operation.")); return *px; } T* operator->() const { PADDLE_ENFORCE_NOT_NULL( px, phi::errors::PreconditionNotMet( "The pointer must be non-null before the dereference operation.")); return px; } void swap(intrusive_ptr& rhs) noexcept { T* tmp = px; px = rhs.px; rhs.px = tmp; } private: template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>> explicit intrusive_ptr(U* p, bool add_ref = true) : px(p) { if (px && add_ref) { intrusive_ptr_add_ref(px); } } template <typename R, typename... Args> friend intrusive_ptr<R> make_intrusive(Args&&...); template <typename R> friend intrusive_ptr<R> copy_intrusive(const intrusive_ptr<R>&); T* px{nullptr}; }; template <typename T, typename U> inline bool operator==(const intrusive_ptr<T>& a, const intrusive_ptr<U>& b) noexcept { return a.get() == b.get(); } template <typename T, typename U> inline bool operator!=(const intrusive_ptr<T>& a, const intrusive_ptr<U>& b) noexcept { return a.get() != b.get(); } template <typename T, typename U> inline bool operator==(const intrusive_ptr<T>& a, U* b) noexcept { return a.get() == b; } template <typename T, typename U> inline bool operator!=(const intrusive_ptr<T>& a, U* b) noexcept { return a.get() != b; } template <typename T, typename U> inline bool operator==(T* a, const intrusive_ptr<U>& b) noexcept { return a == b.get(); } template <typename T, typename U> inline bool operator!=(T* a, const intrusive_ptr<U>& b) noexcept { return a != b.get(); } template <typename T> inline bool operator==(const intrusive_ptr<T>& p, std::nullptr_t) noexcept { return p.get() == nullptr; } template <typename T> inline bool operator==(std::nullptr_t, const intrusive_ptr<T>& p) noexcept { return p.get() == nullptr; } template <typename T> inline bool operator!=(const intrusive_ptr<T>& p, std::nullptr_t) noexcept { return p.get() != nullptr; } template <typename T> inline bool operator!=(std::nullptr_t, const intrusive_ptr<T>& p) noexcept { return p.get() != nullptr; } template <typename T, typename... Args> inline intrusive_ptr<T> make_intrusive(Args&&... args) { return intrusive_ptr<T>(new T(std::forward<Args>(args)...), false); } template <typename T> inline intrusive_ptr<T> copy_intrusive(const intrusive_ptr<T>& rhs) { return intrusive_ptr<T>(rhs.get(), true); } } // namespace phi
true
277c54d9f7e69b484b705603ff7701b14cd8229b
C++
davfeng/security
/ListGroups.cpp
UTF-8
4,217
2.65625
3
[]
no_license
// ListGroups.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <lm.h> void PrintLocalGroups() { ULONG_PTR lResume = 0; ULONG lTotal = 0; ULONG lReturned = 0; ULONG lIndex = 0; NET_API_STATUS netStatus; //LOCALGROUP_INFO_0* pinfoGroup; LOCALGROUP_INFO_1* pinfoGroup; do { netStatus = NetLocalGroupEnum(NULL, 1, (PBYTE*)&pinfoGroup, MAX_PREFERRED_LENGTH, &lReturned, &lTotal, &lResume); if ((netStatus == ERROR_MORE_DATA) || (netStatus == NERR_Success)) { for (lIndex = 0; lIndex < lReturned; lIndex++) { //wprintf(L"%s\n", pinfoGroup[lIndex].lgrpi1_name); wprintf(L"%s %s\n", pinfoGroup[lIndex].lgrpi1_name, pinfoGroup[lIndex].lgrpi1_comment); } NetApiBufferFree(pinfoGroup); } } while (netStatus == ERROR_MORE_DATA); } void PrintLocalGroups1() { PNET_DISPLAY_GROUP pBuff, p; DWORD res, dwRec, i = 0; // //pass a NULL or empty stringto retrieve the local information. // TCHAR szServer[255] = TEXT(""); do { // // Call the NetQueryDisplayInformation function, specify information level 3 (group account information). // res = NetQueryDisplayInformation(szServer, 3, i, 1000, MAX_PREFERRED_LENGTH, &dwRec, (PVOID*)&pBuff); // // If the call succeeds, // if ((res == ERROR_SUCCESS) || (res == ERROR_MORE_DATA)) { p = pBuff; for (; dwRec > 0; dwRec--) { // // Print the retrieved group information. // printf("Name: %S\n" "Comment: %S\n" "Group ID: %u\n" "Attributes: %u\n" "--------------------------------\n", p->grpi3_name, p->grpi3_comment, p->grpi3_group_id, p->grpi3_attributes); // // If there is more data, set the index. // i = p->grpi3_next_index; p++; } // // Free the allocated memory. // NetApiBufferFree(pBuff); } else printf("Error: %u\n", res); // // Continue while there is more data. // } while (res == ERROR_MORE_DATA); // end do } void PrintLocalUsers1() { PNET_DISPLAY_USER pBuff, p; DWORD res, dwRec, i = 0; // //pass a NULL or empty stringto retrieve the local information. // TCHAR szServer[255] = TEXT(""); do { // // Call the NetQueryDisplayInformation function, specify information level 3 (group account information). // res = NetQueryDisplayInformation(szServer, 1, i, 1000, MAX_PREFERRED_LENGTH, &dwRec, (PVOID*)&pBuff); // // If the call succeeds, // if ((res == ERROR_SUCCESS) || (res == ERROR_MORE_DATA)) { p = pBuff; for (; dwRec > 0; dwRec--) { // // Print the retrieved group information. // printf(L"Name: %ws\n" L"Comment: %ws\n" L"Full Name: %ws\n" L"Id: %u\n" L"--------------------------------\n", p->usri1_name, p->usri1_comment, p->usri1_full_name, p->usri1_user_id); // // If there is more data, set the index. // i = p->usri1_next_index; p++; } // // Free the allocated memory. // NetApiBufferFree(pBuff); } else printf("Error: %u\n", res); // // Continue while there is more data. // } while (res == ERROR_MORE_DATA); // end do } int _tmain(int argc, _TCHAR* argv[]) { PrintLocalUsers1(); return 0; }
true
4a4eca7738ae4bec3a3c3f8dda37ee791c713c21
C++
githublizhipan/Practice
/HZOJ/520.cpp
UTF-8
810
2.9375
3
[]
no_license
/************************************************************************* > File Name: 520.cpp > Author: > Mail: > Created Time: 2020年01月14日 星期二 10时28分11秒 ************************************************************************/ #include<iostream> using namespace std; int main() { int a, k, n, temp1, temp2; cin >> a; for(int i = a + 1; ; i++) { temp1 = a * (a - 1) / 2; temp2 = (a + 1 + i) * (i - a) / 2; if(temp1 == temp2) { cout << a << " " << i << endl; return 0; } else for(int j = a + 1; j < i; j++) { temp1 += (j - 1); temp2 -= j; if(temp1 == temp2) { cout << j << " " << i << endl; return 0; } } } return 0; }
true
3bc5b083676115c0230d8e0381ba52a781976e81
C++
alapan-sau/CP-Library
/euclidAlgorithm.cpp
UTF-8
388
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; // data types #define ll long long int #define ld long double ll gcd(ll a, ll b){ if(b==0) return a; else{ return gcd(b,a%b); } } ll lcm(ll a,ll b){ return (a*b)/gcd(a,b); } int main(){ ios_base::sync_with_stdio(false); ll a,b; cin >> a >> b; cout << gcd(a,b) << " " << lcm(a,b) << endl; return 0; }
true
e6f35d76117b8aead6d28ef46239c237c7e1ff98
C++
lucasdutraf/competitive-programming
/codeforces/maratonas-df/4-maratona-ifb/N.cpp
UTF-8
670
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; using pi = pair<int, ll>; using vi = vector<pi>; int main () { ios::sync_with_stdio(false); int n, m, aux; vi answ; ll tempo; cin >> n >> m; while(n--){ cin >> aux >> tempo; answ.push_back(make_pair(aux, tempo)); } sort(answ.begin(), answ.end()); if (answ[answ.size() - 1].first > m) { cout << "N" << endl; } else if ((answ[answ.size() - 1].first == m) && (answ[answ.size() - 1].second < (300 * m)) && (answ[answ.size() - 1].second > 0)) { cout << "N" << endl; } else { cout << "S" << endl; } return 0; }
true
a0193fb8cbaa42f0de59b67780624d93e4e7b3bd
C++
JohanJacobs/Head_First_Design_Patterns
/Chapter9_Composite_Pattern/src/Iterator_Menu_Classes/Iterators/DinerMenuIterator.h
UTF-8
740
2.921875
3
[ "MIT" ]
permissive
#pragma once #include <array> #include <memory> #include "IteratorInterface.h" #include "Iterator_Menu_Classes/MenuClasses/DinerMenuWithIterator.h" namespace Itertor_Menu { class DinerMenuIterator : public IteratorInterface { public: DinerMenuIterator(const std::array< std::shared_ptr<MenuItem>, 6>& items) :m_MenuItems{ items } { } bool HasNext() const override { if (m_Position >= m_MenuItems.size() || m_MenuItems[m_Position] == nullptr) { return false; } else { return true; } } const std::shared_ptr<MenuItem> Next() override { return m_MenuItems[m_Position++]; } private: const std::array<std::shared_ptr<MenuItem>, 6>& m_MenuItems; int m_Position{ 0 }; }; }
true
24b64a7b85021279722107cd64be87d356c44939
C++
ananddeb23/cppsolutions
/smallest-window-in-a-string-containing-all-the-characters-of-another-string.cpp
UTF-8
3,153
2.828125
3
[]
no_license
#include <iostream> #include<vector> #include<string.h> using namespace std; /* input format as follows n: number of test cases next n lines text 'space' pattern */ // OUTPUT CONTAINS TEXT WHICH MAY NOT BE IN ORDER. FOR ORDER CHECK WHEN COUNT==PATERNLENGTH WHETHER c==PT[PTL-1] int main() { //code int n; cin>>n; while(n--){ char txt[2000],pt[200]; cin>>txt;char dum; cin>>pt; // cout<<txt<<"\t"<<pt<<endl; int txtl=strlen(txt); int ptl=strlen(pt); // Print the indices for debugging /* for(int b=0;b<txtl;b++) cout<<b; cout<<"\t"; for(int b=0;b<ptl;b++) cout<<b; cout<<endl;*/ int ws=0,we=strlen(txt)-1,subs=-1,sube=-1; vector<int>v(ptl,0); int ptr=ws; int flag=-1; int count=0; while(ptr<we){ char c=txt[ptr]; ptr++; for(int i=0;i<ptl;i++){ if(pt[i]==c &&v[i]==0){ v[i]=1; count++; if(count==ptl ){ subs=ws; sube=ptr-1; ws++; we=ptr-1; //reset vector for(int a=0;a<ptl;a++){ v[a]=0; } flag=1; // cout<<" New start and end are "<<subs<<" "<<sube<<endl; break; } i=ptl; } } } if(flag==-1){ cout<<"not found\n"; return 0; } // cout<<" Im here"; while(!(we==txtl-1 && (we-ws)<ptl)&&(we<=txtl-1 && ws<txtl-1)){ ptr=ws; flag=0; count=0; //cout<<"Here\n"; //cout<<ws<<" "<<we<<endl; while(ptr<=we){ char c=txt[ptr]; ptr++; for(int i=0;i<ptl;i++){ if(pt[i]==c && v[i]==0){ v[i]=1; count++; if((count==ptl) ){ subs=ws; sube=ptr-1; we=sube; ws++; flag=1; // cout<<" New start and end are "<<subs<<" "<<sube<<endl; // Resetting the vector which checked whether all indices are covered or not for(int a=0;a<ptl;a++){ v[a]=0; } goto l1; } i=ptl; } } } if(flag==0){ we++; for(int a=0;a<ptl;a++){ v[a]=0; } } l1: cout<<""; } if(we==-1 || ws==-1){ cout<<" Not found\n"; } else{ for(int i=subs;i<=sube;i++){ cout<<txt[i]; } cout<<endl; } } return 0; }
true
8c485de6780a21112e29b7ccbda911879cee8e5d
C++
AlexGitHub99/cprojects
/binaryTree/main.cpp
UTF-8
5,381
3.875
4
[]
no_license
//Creator: Alex King //Last Modified: 3/25/19 //This program builds a binary search tree #include <iostream> #include "Node.h" #include <cstring> #include <cmath> using namespace std; void add(Node* current, Node* newNode); void del(Node* current, int number); void print(Node* current, int depth); Node* takeRight(Node* current); Node* delNode(Node* node); int main () { cout << "Welcome to binary search tree. Commands: " << endl; cout << "add <number> - add a number to the tree" << endl; cout << "del <numbers> - delete a number from the tree" << endl; cout << "print - prints the tree" << endl; cout << "quit - quit the program" << endl; Node* head = new Node(); char input[10]; bool cont = true; while(cont == true) { cin.getline (input, 10); cout << "User typed " << input << endl; if(strncmp(input, "add", 3) == 0) { int number = 0; number = atoi(&input[4]); //convert input characters to int Node* newNode = new Node(); newNode->setData(number); add(head, newNode); } else if(strncmp(input, "del", 3) == 0) { int number = 0; number = atoi(&input[4]); del(head, number); } else if(strncmp(input, "print", 5) == 0) { cout << "Printing graph" << endl; print(head, 0); } else if(strncmp(input, "quit", 4) == 0) { cont = false; } } } //adds a new node to the binary tree void add(Node* current, Node* newNode) { if(current != NULL) { if(newNode->getData() < current->getData()) { //smaller than current node if(current->getLeft() != NULL) { //already has a left node, recurse add(current->getLeft(), newNode); } else { //add it to the left current->setLeft(newNode); } } else { //larger than current node if(current->getRight() != NULL) { //already has a right node, recurse add(current->getRight(), newNode); } else { //add it to the right current->setRight(newNode); } } } } //deletes a node with a certain number from the tree if found void del(Node* current, int number) { if(current != NULL) { if(number < current->getData()) { //smaller than current node if(current->getLeft() != NULL) { //already has left node if(current->getLeft()->getData() == number) { //left node is the number, delete left current->setLeft(delNode(current->getLeft())); cout << "Deleted number" << endl; } else { //recurse del(current->getLeft(), number); } } else { cout << "Number not in the tree" << endl; } } else if(number > current->getData()) { if(current->getRight() != NULL) { if(current->getRight()->getData() == number) { current->setRight(delNode(current->getRight())); cout << "Deleted number" << endl; } else { //recurse del(current->getRight(), number); } } else { cout << "Number not in the tree" << endl; } } else { //current node is number, delete it delNode(current); cout << "Deleted number" << endl; } } } //returns the rightmost node from the passed in node and reconnects the node it was taken from Node* takeRight(Node* current) { if(current->getRight() != NULL) { if(current->getRight()->getRight() != NULL) { return takeRight(current->getRight()); } else { Node* temp = current->getRight(); current->setRight(temp->getLeft()); return temp; } } else { return current; } } //deletes a node and returns the in order successor Node* delNode(Node* node) { if(node->getLeft() == NULL && node->getRight() == NULL) { delete node; return NULL; } else if (node->getRight() == NULL) { Node* temp = node->getLeft(); delete node; return temp; } else if (node->getLeft() == NULL) { Node* temp = node->getRight(); delete node; return temp; } else { Node* temp = takeRight(node); temp->setLeft(node->getLeft()); temp->setRight(node->getRight()); delete node; return temp; } } //prints out tree recursively void print(Node* current, int depth) { cout << "(" << current->getData() << ")\n"; if(current->getLeft() != NULL) { for(int i = 0; i < depth; i++) { cout << " "; } cout << "(" << current->getData() << ")"; cout << " L> "; print(current->getLeft(), depth + 1); } if(current->getRight() != NULL) { for(int i = 0; i < depth; i++) { cout << " "; } cout << "(" << current->getData() << ")"; cout << " R> "; print(current->getRight(), depth + 1); } }
true
e4e8297838449dec618fc051200889b64fdb9fd7
C++
VietRise/GameJump
/Classes/UserData.cpp
UTF-8
1,909
2.640625
3
[ "MIT" ]
permissive
// // UserData.cpp // GameJump-mobile // // Created by MacBook on 1/5/19. // #include "UserData.h" #include "GameConfig.h" USING_NS_CC; using namespace std; UserData* UserData::_instance = nullptr; UserData::~UserData() { } UserData::UserData() { if (!UserDefault::getInstance()->getBoolForKey(USERDEFAULT_FILEEXIST)) { _bestScore = 0; this->setBestScore(_bestScore); UserDefault::getInstance()->setBoolForKey(USERDEFAULT_FILEEXIST, true); } else { _bestScore = this->getIntegerForKey(BEST_SCORE); } } UserData* UserData::getInstance() { if (_instance == nullptr) { _instance = new UserData(); } return _instance; } void UserData::destroyInstance() { CC_SAFE_DELETE(_instance); } void UserData::setBestScore(int bestScore) { _bestScore = bestScore; this->setIntegerForKey(BEST_SCORE, _bestScore); } int UserData::getBestScore() { return _bestScore; } void UserData::setIntegerForKey(const char* pKey, int value) { char szName[50] = { 0 }; sprintf(szName, "%i", value); string valueString = string(szName); encode(pKey, valueString); } int UserData::getIntegerForKey(const char* pKey) { string valueString = decode(pKey); int value = atoi(valueString.c_str()); return value; } void UserData::encode(const char* pKey, std::string value) { char* valueEncode; base64Encode(reinterpret_cast<const unsigned char*>(value.c_str()), strlen(value.c_str()) + 1, &valueEncode); UserDefault::getInstance()->setStringForKey(pKey, valueEncode); } std::string UserData::decode(const char* pKey) { string valueEncode = UserDefault::getInstance()->getStringForKey(pKey); unsigned char* value; base64Decode(reinterpret_cast<const unsigned char*>(valueEncode.c_str()), strlen(valueEncode.c_str()) + 1, &value); return string(reinterpret_cast<char*>(value)); }
true
b4956d9fe1522a25b3edf72a61024eaeac509676
C++
vonwenm/Hypodermic
/Hypodermic/TypedService.cpp
UTF-8
578
2.546875
3
[ "MIT" ]
permissive
#include "TypedService.h" #include <functional> namespace Hypodermic { TypedService::TypedService(const std::type_info& typeInfo) : typeInfo_(typeInfo) , typeIndex_(typeInfo_) { } const std::type_info& TypedService::typeInfo() const { return typeInfo_; } bool TypedService::operator==(const Service& rhs) const { return typeInfo_ == rhs.typeInfo(); } std::size_t TypedService::hashValue() const { return typeIndex_.hash_code(); } } // namespace Hypodermic
true
6ef8996ac027a805d80bd892d1482497a10070a5
C++
HerveSV/CrudeRender
/CrudeRender/src/Crude/Utils/OrthoCameraController.hpp
UTF-8
2,375
2.765625
3
[]
no_license
// // OrthoCameraController.hpp // CrudeRender // // Created by Hervé Schmit-Veiler on 5/20/20. // Copyright © 2020 Hervé Schmit-Veiler. All rights reserved. // #ifndef OrthoCameraController_hpp #define OrthoCameraController_hpp #include "CameraController.hpp" #include "OrthoCamera.hpp" namespace Crude::Utils { class OrthoCameraController : public CameraController { public: OrthoCameraController(float aspectRatio); virtual void onEvent(Event& event) override; virtual void onUpdate(Timestep deltaTime) override; void setTranslationSpeed(float speed) { m_CameraTranslationSpeed = speed; }; inline float getTranslationSpeed() const { return m_CameraTranslationSpeed; } //Zoom works as a multiplier where 1.0f will signify NO zoom, and for anything greater or smaller to scale the view up or down respectively void setZoom(float zoom); inline float getZoom() const { return m_ZoomLevel; } void setMaxZoom(float maxZoom) { m_CameraMaxZoom = maxZoom; } inline float getMaxZoom() const { return m_CameraMaxZoom; } void setMinZoom(float minZoom) { m_CameraMinZoom = minZoom; } inline float getMinZoom() const { return m_CameraMinZoom; } void setZoomSpeed(float zoomSpeed) { m_CameraZoomSpeed = zoomSpeed; } inline float getZoomSpeed() const { return m_CameraZoomSpeed; } //if true, translation speed will lower when zoomed in and vice versa void setScaleTranslationSpeedWithZoom(float flagTrueIfScale) { m_ScaleTranslationSpeedWithZoom = flagTrueIfScale; } inline OrthoCamera& getCamera() { return m_Camera; } protected: bool onWindowResizeEvent(WindowResizeEvent& event); bool onMouseScrolledEvent(MouseScrolledEvent& event); protected: OrthoCamera m_Camera; public://temporary glm::vec3 m_CameraPosition = {0.0f, 0.0f, 0.0f}; protected: float m_ZoomLevel = 1.0f; float m_AspectRatio; float m_CameraMaxZoom = 3.0f; float m_CameraMinZoom = 0.15f; float m_CameraZoomSpeed = 0.15f; float m_CameraTranslationSpeed = 3.0f; private: bool m_ScaleTranslationSpeedWithZoom = false; }; } #endif /* OrthoCameraController_hpp */
true
cc519c10a4578ceb448195e4e1254b1657e84c8c
C++
muru-raj10/2D-objects
/Shape.cpp
UTF-8
1,335
3.4375
3
[]
no_license
// Shape.cpp // // Defining functions for shape // Modifications // 14 July 16, file created #ifndef Shape_cpp //To avoid multiple inclusion #define Shape_cpp #include "Shape.hpp" #include <cmath> #include <sstream> // std::stringstream, std::stringbuffer #include "stdlib.h"; using namespace std; Shape::Shape() : id(rand()) {//default constructor cout<<"Default shape constructor used"<<endl; } Shape::Shape(const Shape& sh) : id(sh.id) {//copy constructor cout<<"Copy shape constructor used!"<<endl; } Shape::~Shape() {//destructor cout<<"Shape destructor used!"<<endl; } // Member operator overloading Shape& Shape::operator = (const Shape& source) // Assignment operator. { if(this != &source) { id=source.id; } return *this; //current object returned. No copy made. } //Retrive the id int Shape::ID() const { return id; } string Shape::ToString() const { stringstream ss; //defining a stringstream ss << " ID: "<<ID()<<endl; return ss.str(); } /*void Shape::Draw() const {//empty implementation as you cannot draw a shape. }*/ void Shape::Print() const { cout<<ToString()<<endl; //Call print function as a function of the polymorphic function ToString(). ToString() is overridden in the derived classes. } #endif
true
173f34fef3ba035cfe7299c7df887a976a1e36ff
C++
Caceresenzo/42
/CPP Modules/08/ex03/ICommand.hpp
UTF-8
2,055
2.703125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ICommand.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ecaceres <ecaceres@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/15 15:52:17 by ecaceres #+# #+# */ /* Updated: 2020/07/15 15:52:17 by ecaceres ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef ICOMMAND_HPP_ # define ICOMMAND_HPP_ # include <cstddef> # include <exception> # include <iostream> class Context; class ICommand { private: size_t _position; protected: ICommand(); ICommand(size_t position); ICommand(const ICommand &other); public: virtual ~ICommand(); ICommand& operator=(const ICommand &other); virtual void execute(Context &context); size_t position() const; class CommandException : public std::exception { private: const ICommand *_command; const std::string _message; public: CommandException(void); CommandException(ICommand *command); CommandException(ICommand *command, std::string message); CommandException(const CommandException &other); virtual ~CommandException(void) throw (); CommandException& operator=(const CommandException &other); virtual const char* what() const throw (); const std::string &message() const; const ICommand *command() const; static CommandException generic(ICommand *command, std::string reason); static CommandException notImplemented(ICommand *command); }; }; # include "Context.hpp" #endif /* ICOMMAND_HPP_ */
true
43b4acb93c8124dc7be8aed7882e189fbb34f616
C++
orocos-toolchain/utilmm
/utilmm/auto_flag.hh
UTF-8
1,910
3.421875
3
[ "BSD-3-Clause", "CECILL-B", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-cecill-b-en" ]
permissive
#ifndef UTILMM_AUTOFLAG_H #define UTILMM_AUTOFLAG_H #include <boost/noncopyable.hpp> namespace utilmm { /** Automatically sets and resets a boolean flag * on construction and destruction */ template<typename T> class auto_flag : private boost::noncopyable { int& m_field; int m_mask; bool m_restore; public: auto_flag(int& field, int mask, bool value = true, bool restore_old = true) : m_field(field), m_mask(mask) , m_restore(restore_old ? get() : !value) { set(value); } ~auto_flag() { set(m_restore); } bool get() { return (m_field & m_mask) == m_mask; } void set(bool value) { m_field = (m_field & ~m_mask) | (m_mask * static_cast<int>(value)); } }; template<> class auto_flag<bool> : private boost::noncopyable { bool& m_flag; bool m_restore; // Safe bool idiom struct safe_bool_struct { void method(); }; typedef void (safe_bool_struct::*safe_bool)(); public: /** Sets \c flag to \c init. On destruction, the flag * will be set to either ! \c init if restore_old is false, or * to the initial flag value if restore_old is true */ auto_flag(bool& flag, bool init = true, bool restore_old = true) : m_flag(flag), m_restore(restore_old ? flag : !init) { m_flag = init; } /** Sets the value of the flag according to the restore_old * argument of the constructor */ ~auto_flag() { m_flag = m_restore; } /** Get the current value of the flag * @return the current value of the flag */ bool get() const { return m_flag; } operator safe_bool() const { return m_flag ? &safe_bool_struct::method : 0; } }; } #endif
true
b4225e1e069951521209532a4093f1833ce5d7fa
C++
rombarte/WZORCE-PROJEKTOWE
/CHAIN/source.cpp
UTF-8
1,263
3.28125
3
[]
no_license
/* Autor: Bartłomiej Romanek */ /* Tytuł: Wzorzec "Łańcuch odpowiedzialności" */ /* Licencja: Licencja MIT */ /* Data modyfikacji: 21.02.2017 */ #include <iostream> #include <fstream> #include <string> using namespace std; class Ekran { public: int Wyswietl(string & napis) { cout << napis << endl; return 0; } }; class Plik { public: int Zapisz(string & napis) { ofstream plik("output.txt", ifstream::out); if (!plik.good()) { return 1; } plik << napis; plik.close(); return 0; } }; class Lancuch { public: void Zachowaj(string napis) { preferencja = 0; if (preferencja == 0) { Plik file1; preferencja = file1.Zapisz(napis); } if (preferencja == 1) { Ekran display1; preferencja = display1.Wyswietl(napis); } } private: int preferencja; }; int main(){ Lancuch strategy1; strategy1.Zachowaj("Bon na 10zl do Tesco: AH4S-C8H5-09NN"); system("pause"); } // Opis kodu: Klasa "Łancuch" posiada metodę "Zachowaj", która umożliwia zapis napisu do pliku. Jeżeli to się nie uda, // następuje próba wykonania operacji zastępczej: wypisanie napisu na ekran.
true
60ec9f16caa8bbccd6392dd8d1bdea42998b9f1c
C++
jairsaidds/DataStructures
/Stack.cpp
UTF-8
2,113
3.453125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; struct node{ node *next; int data; node(){ next = NULL; cout << "what"; } node(int X){ data = X; next = NULL; } }; struct Stack{ node *head; Stack(){ head = NULL; } void push(node *x){ node *tmp; if(head == NULL){ head = x; }else{ tmp = head; head = x; head -> next = tmp; } } void pop(){ head = head -> next; } int top(){ return head->data; } void printStack(){ node *tmp; tmp = head; while(tmp != NULL){ cout << tmp -> data << " "; tmp = tmp -> next; } cout << endl; } int getSize(){ int ans = 0; node *tmp; tmp = head; while(tmp != NULL){ ans ++; tmp = tmp -> next; } return ans; } int isEmpty(){ return head == NULL; } }; struct StackSet{ int maximum; int insertIn; vector<Stack>myset; StackSet(){ Stack st; myset.push_back(st); insertIn = 0; } StackSet(int f){ Stack st; myset.push_back(st); f = maximum; insertIn = 0; } int sizeOfStack(int idx){ return myset[idx].getSize(); } void push(int idx){ if(sizeOfStack(insertIn) == maximum){ insertIn++; Stack st; myset.push_back(st); } myset[insertIn].push(new node(idx)); } void pop(){ if(sizeOfStack(insertIn) == 0){ if(insertIn == 0){ cout << "VACIA" << endl; }else{ insertIn--; myset[insertIn].pop(); } } } }; Stack sortStack(Stack toSort){ Stack ans; while(toSort.getSize() > 0){ int u = toSort.top(), v; toSort.pop(); while(ans.getSize() > 0 and (v = ans.top()) > u){ toSort.push( new node(v)); ans.pop(); } ans.push(new node(u)); } return ans; } int main(){ Stack st; node *a = new node(90); node *b = new node(-8); node *c = new node(7); node *d = new node(-6); node *e = new node(5); node *f = new node(14); node *g = new node(-3); node *h = new node(2); node *i = new node(1); node *j = new node(-8); st.push(a); st.push(b); st.push(c); st.push(d); st.push(e); st.push(f); st.push(g); st.push(h); st.push(i); st.push(j); Stack ordered = sortStack(st); ordered.printStack(); return 0; }
true
d6d9a490d3146d2346acbf813b10168f29ff3453
C++
qjhart/qjhart.geostreams
/src/imgstr/src/test.cpp
UTF-8
2,735
3.09375
3
[]
no_license
/* GeoStreams Project A simple test to exercise the ImgStream module Carlos A. Rueda-Velasquez $Id: test.cpp,v 1.3 2005/07/09 07:17:27 crueda Exp $ This is a compilable and executable code following the schematic usage described in README file. To build and run this demo: make test ./test You will get a number of lines containing the generated stream. */ #include "ImgStream.h" /** * We need to provide a StreamWriter, so here it is: * This is an implementation of StreamWriter that writes to a regular * file or to stdout. */ class FileStreamWriter : public StreamWriter { string filename; FILE* file; public: /** @param filename The output filename. If equals to "-" then * it will write to stdout */ FileStreamWriter(string filename) : filename(filename) { if ( filename == "-" ) file = fdopen(fileno(stdout), "wb"); else file = fopen(filename.c_str(), "wb"); } ~FileStreamWriter() { if ( file && filename != "-" ) fclose(file); file = 0; }; /** calls fwrite(buf, nbytes, 1, file) and returns 0 * if that call was successful. */ int writeBuffer(const void* buf, int nbytes) { if ( 1 == fwrite(buf, nbytes, 1, file) ) return 0; // OK else return -1; // error ocurred } }; /** The stream will be written to stdout unless the name of a file * is given as the only argument to this program. The special * name "-" will also refer to the stdout. */ int main(int argc, char** argv) { string filename = "-"; if ( argc > 1 ) filename = argv[1]; FileStreamWriter writer(filename); Format format = ASCII_FORMAT; ReferenceSpace rs(5000, 5000, 25000, 17000); ImgStream* imgStream = ImgStream::createImgStream(&writer, format, rs); // some channel definitions: ChannelDef channel_def0("VISIBLE", 0, 1, 1, 16./18., 10); imgStream->writeChannelDef(channel_def0); ChannelDef channel_def1("INFRARED", 1, 2, 2, 16./18., 10); imgStream->writeChannelDef(channel_def1); // here, a loop bool keep_running = true; while ( keep_running ) { // when a frame starts: Rectangle rect(15000, 5000, 10, 5); // rectangle associated to frame FrameDef frame_def(0, rect); imgStream->startFrame(frame_def); // to send rows int current_frame_id = 0; // lets say 0 int channelNo = 1; // lets say 1 int w = 10; // number of columns in line uint16 line[10] = { 1,2,3,4,5,6,7,8,9,0}; // as an example int x = 15000; int y = 5000; for ( int i = 0; i < 5; i++ ) { Row row(current_frame_id, channelNo, x, y + i, w, line) ; imgStream->writeRow(row) ; } keep_running = false; // just to finish this test :-) } delete imgStream; return 0; }
true
f6f29bc2a62e84c599556c467eaf7aa8342b8acd
C++
stermaneran/searchEngine
/Crawler/HtmlPreprocesser.h
UTF-8
701
2.65625
3
[]
no_license
#ifndef HTMLPREPROCESSER_H #define HTMLPREPROCESSER_H #include <string> using namespace std; class HtmlPreprocesser { public: static void getTitle(const string &contentStr, string &title); static bool delBetweenHtmlTags(const string & str, const string tag, string &ret); static bool delComments(const string &str, string &ret); static bool delTags(const string &str, string &ret); static void replaceStr(const string &str, const string src, const string dest, string &ret); static void mergeSpaces(const string &str, string &ret); static void delOddchar(const string &str, const string dest, string &ret); private: static bool imatchHere(const string &str, int i, const string &pat); }; #endif
true
56a26ee824f496670a38731b69a4e52571caf368
C++
romange/gaia
/base/wheel_timer.h
UTF-8
18,002
2.9375
3
[ "BSD-2-Clause" ]
permissive
// -*- mode: c++; c-basic-offset: 4 indent-tabs-mode: nil -*- */ // // Copyright 2016 Juho Snellman, released under a MIT license (see // LICENSE). // // A timer queue which allows events to be scheduled for execution // at some later point. Reasons you might want to use this implementation // instead of some other are: // // - A single-file C++11 implementation with no external dependencies. // - Optimized for high occupancy rates, on the assumption that the // utilization of the timer queue is proportional to the utilization // of the system as a whole. When a tradeoff needs to be made // between efficiency of one operation at a low occupancy rate and // another operation at a high rate, we choose the latter. // - Tries to minimize the cost of event rescheduling or cancelation, // on the assumption that a large percentage of events will never // be triggered. The implementation avoids unnecessary work when an // event is rescheduled, and provides a way for the user specify a // range of acceptable execution times instead of just an exact one. // - Facility for limiting the number of events to execute on a // single invocation, to allow fine grained interleaving of timer // processing and application logic. // - An interface that at least the author finds convenient. // // The exact implementation strategy is a hierarchical timer // wheel. A timer wheel is effectively a ring buffer of linked lists // of events, and a pointer to the ring buffer. As the time advances, // the pointer moves forward, and any events in the ring buffer slots // that the pointer passed will get executed. // // A hierarchical timer wheel layers multiple timer wheels running at // different resolutions on top of each other. When an event is // scheduled so far in the future than it does not fit the innermost // (core) wheel, it instead gets scheduled on one of the outer // wheels. On each rotation of the inner wheel, one slot's worth of // events are promoted from the second wheel to the core. On each // rotation of the second wheel, one slot's worth of events is // promoted from the third wheel to the second, and so on. // // The basic usage is to create a single TimerWheel object and // multiple TimerEvent or MemberTimerEvent objects. The events are // scheduled for execution using TimerWheel::schedule() or // TimerWheel::schedule_in_range(), or unscheduled using the event's // cancel() method. // // Example usage: // // typedef std::function<void()> Callback; // TimerWheel timers; // int count = 0; // TimerEvent<Callback> timer([&count] () { ++count; }); // // timers.schedule(&timer, 5); // timers.advance(4); // assert(count == 0); // timers.advance(1); // assert(count == 1); // // timers.schedule(&timer, 5); // timer.cancel(); // timers.advance(4); // assert(count == 1); // // To tie events to specific member functions of an object instead of // a callback function, use MemberTimerEvent instead of TimerEvent. // For example: // // class Test { // public: // Test() : inc_timer_(this) { // } // void start(TimerWheel* timers) { // timers->schedule(&inc_timer_, 10); // } // void on_inc() { // count_++; // } // int count() { return count_; } // private: // MemberTimerEvent<Test, &Test::on_inc> inc_timer_; // int count_ = 0; // }; #ifndef RATAS_TIMER_WHEEL_H #define RATAS_TIMER_WHEEL_H #include <cassert> #include <cstdint> #include <cstdio> #include <memory> namespace base { typedef uint64_t Tick; class TimerWheelSlot; class TimerWheel; // An abstract class representing an event that can be scheduled to // happen at some later time. class TimerEventInterface { public: TimerEventInterface() { } // TimerEvents are automatically canceled on destruction. virtual ~TimerEventInterface() { cancel(); } // Unschedule this event. It's safe to cancel an event that is inactive. inline void cancel(); // Return true iff the event is currently scheduled for execution. bool active() const { return slot_ != NULL; } // Return the absolute tick this event is scheduled to be executed on. Tick scheduled_at() const { return scheduled_at_; } private: TimerEventInterface(const TimerEventInterface& other) = delete; TimerEventInterface& operator=(const TimerEventInterface& other) = delete; friend TimerWheelSlot; friend TimerWheel; // Implement in subclasses. Executes the event callback. virtual void execute() = 0; void set_scheduled_at(Tick ts) { scheduled_at_ = ts; } // Move the event to another slot. (It's safe for either the current // or new slot to be NULL). inline void relink(TimerWheelSlot* slot); Tick scheduled_at_ = 0; // The slot this event is currently in (NULL if not currently scheduled). TimerWheelSlot* slot_ = nullptr; // The events are linked together in the slot using an internal // doubly-linked list; this iterator does double duty as the // linked list node for this event. TimerEventInterface* next_ = nullptr; TimerEventInterface* prev_ = nullptr; }; // An event that takes the callback (of type CBType) to execute as // a constructor parameter. template <typename CBType> class TimerEvent : public TimerEventInterface { public: explicit TimerEvent(CBType&& callback) : callback_(std::forward<CBType>(callback)) { } void execute() override { callback_(); } private: TimerEvent<CBType>(const TimerEvent<CBType>& other) = delete; TimerEvent<CBType>& operator=(const TimerEvent<CBType>& other) = delete; CBType callback_; }; // An event that's specialized with a (static) member function of class T, // and a dynamic instance of T. Event execution causes an invocation of the // member function on the instance. template <typename T, void (T::*MFun)()> class MemberTimerEvent : public TimerEventInterface { public: MemberTimerEvent(T* obj) : obj_(obj) { } virtual void execute() { (obj_->*MFun)(); } private: T* obj_; }; // Purely an implementation detail. class TimerWheelSlot { public: TimerWheelSlot() { } private: // Return the first event queued in this slot. const TimerEventInterface* events() const { return events_; } // Deque the first event from the slot, and return it. TimerEventInterface* pop_event() { auto event = events_; events_ = event->next_; if (events_) { events_->prev_ = NULL; } event->next_ = NULL; event->slot_ = NULL; return event; } TimerWheelSlot(const TimerWheelSlot& other) = delete; TimerWheelSlot& operator=(const TimerWheelSlot& other) = delete; friend TimerEventInterface; friend TimerWheel; // Doubly linked (inferior) list of events. TimerEventInterface* events_ = NULL; }; // A TimerWheel is the entity that TimerEvents can be scheduled on // for execution (with schedule() or schedule_in_range()), and will // eventually be executed once the time advances far enough with the // advance() method. class TimerWheel { public: TimerWheel() { now_ = 0; } // Advance the TimerWheel by the specified number of ticks, and execute // any events scheduled for execution at or before that time. The // number of events executed can be restricted using the max_execute // parameter. If that limit is reached, the function will return false, // and the excess events will be processed on a subsequent call. // // - It is safe to cancel or schedule events from within event callbacks. // - During the execution of the callback the observable event tick will // be the tick it was scheduled to run on; not the tick the clock will // be advanced to. // - Events will happen in order; all events scheduled for tick X will // be executed before any event scheduled for tick X+1. // // Delta should be non-0. The only exception is if the previous // call to advance() returned false. // // advance() should not be called from an event callback. inline bool advance(Tick delta, size_t max_execute = size_t(-1)); // Schedule the event to be executed delta ticks from the current time. // The delta must be non-0. inline Tick schedule(TimerEventInterface* event, Tick delta); // Schedule the event to happen at some time between start and end // ticks from the current time. The actual time will be determined // by the TimerWheel to minimize rescheduling and promotion overhead. // Both start and end must be non-0, and the end must be greater than // the start. inline void schedule_in_range(TimerEventInterface* event, Tick start, Tick end); // Return the current tick value. Note that if the time increases // by multiple ticks during a single call to advance(), during the // execution of the event callback now() will return the tick that // the event was scheduled to run on. Tick now() const { return now_; } Tick ticks_to_next_event(Tick max = Tick(-1)) const { return ticks_to_next_event(now_, max, 0); } private: TimerWheel(const TimerWheel& other) = delete; TimerWheel& operator=(const TimerWheel& other) = delete; // This handles the actual work of executing event callbacks and // recursing to the outer wheels. inline bool process_current_slot(Tick now, size_t max_execute, unsigned level); inline bool cascade(Tick scaled_now, size_t max_execute, unsigned level); // Return the number of ticks remaining until the next event will get // executed. If the max parameter is passed, that will be the maximum // tick value that gets returned. The max parameter's value will also // be returned if no events have been scheduled. // // Will return 0 if the wheel still has unprocessed events from the // previous call to advance(). inline Tick ticks_to_next_event(Tick base, Tick max, unsigned level) const; // Total number of ticks reachable from the wheel: // (2^(WIDTH_BITS)) ^ NUM_LEVELS. For (7,5) its 2^35 ticks. If a tick is 1ms than it would take // 159 hours to reach the last one. static constexpr unsigned WIDTH_BITS = 7; static constexpr unsigned NUM_LEVELS = 5; static constexpr unsigned MAX_LEVEL = NUM_LEVELS - 1; static constexpr unsigned NUM_SLOTS = 1 << WIDTH_BITS; // The current timestamp for this wheel. This will be right-shifted // such that each slot is separated by exactly one tick even on // the outermost wheels. Tick now_; // We've done a partial tick advance. This is how many ticks remain unprocessed. Tick ticks_pending_ = 0; TimerWheelSlot slots_[NUM_LEVELS][NUM_SLOTS]; }; // Implementation void TimerEventInterface::relink(TimerWheelSlot* new_slot) { if (new_slot == slot_) { return; } // Unlink from old location. if (slot_) { if (next_) { next_->prev_ = prev_; } if (prev_) { prev_->next_ = next_; } else { // Must be at head of slot. Move the next item to the head. slot_->events_ = next_; } } // Insert in new slot. if (new_slot) { TimerEventInterface* old = new_slot->events_; next_ = old; if (old) { old->prev_ = this; } new_slot->events_ = this; } else { next_ = NULL; } prev_ = NULL; slot_ = new_slot; } void TimerEventInterface::cancel() { // It's ok to cancel a event that's not scheduled. if (slot_) { relink(NULL); } } bool TimerWheel::advance(Tick delta, size_t max_events) { if (ticks_pending_) { // Continue collecting a backlog of ticks to process if // we're called with non-zero deltas. ticks_pending_ += delta; // We only partially processed the last tick. Process the // current slot, rather incrementing like advance() normally // does. if (!process_current_slot(now_, max_events, 0)) { // Outer layers are still not done, propagate that information // back up. return false; } // The core wheel has been fully processed. We can now close // down the partial tick and pretend that we've just been // called with a delta containing both the new and original // amounts. delta = (ticks_pending_ - 1); ticks_pending_ = 0; } else { // Zero deltas are only ok when in the middle of a partially // processed tick. assert(delta > 0); } while (delta--) { ++now_; if (!process_current_slot(now_, max_events, 0)) { ticks_pending_ = (delta + 1); return false; } } return true; } bool TimerWheel::cascade(Tick base, size_t max_events, unsigned level) { assert(level > 0); if (ticks_pending_) { // We only partially processed the last tick. Process the // current slot, rather incrementing like advance() normally // does. return process_current_slot(base, max_events, level); } if (!process_current_slot(base, max_events, level)) { ticks_pending_ = 1; return false; } return true; } bool TimerWheel::process_current_slot(Tick now, size_t max_events, unsigned level) { size_t slot_index = now % NUM_SLOTS; auto slot = &slots_[level][slot_index]; if (slot_index == 0 && level < MAX_LEVEL) { if (!cascade(now >> WIDTH_BITS, max_events, level + 1)) { return false; } } while (slot->events()) { TimerEventInterface* event = slot->pop_event(); if (level > 0) { assert((now_ % NUM_SLOTS) == 0); if (now_ >= event->scheduled_at()) { event->execute(); if (!--max_events) { return false; } } else { // There's a case to be made that promotion should // also count as work done. And that would simplify // this code since the max_events manipulation could // move to the top of the loop. But it's an order of // magnitude more expensive to execute a typical // callback, and promotions will naturally clump while // events triggering won't. assert(0 == now_ % (1 << (WIDTH_BITS * level))); Tick delta = event->scheduled_at() - now_; unsigned lvl = 0; while (delta >= NUM_SLOTS) { ++lvl; delta >>= WIDTH_BITS; } TimerWheelSlot& slot = slots_[lvl][delta]; event->relink(&slot); } } else { event->execute(); if (!--max_events) { return false; } } } return true; } Tick TimerWheel::schedule(TimerEventInterface* event, Tick delta) { assert(delta > 0); Tick at = now_ + delta; event->set_scheduled_at(at); unsigned level = 0; Tick base = now_; while (delta >= NUM_SLOTS) { delta = (delta + (base % NUM_SLOTS)) >> WIDTH_BITS; base >>= WIDTH_BITS; ++level; } size_t slot_index = (base + delta) % NUM_SLOTS; auto slot = &slots_[level][slot_index]; event->relink(slot); return at; } void TimerWheel::schedule_in_range(TimerEventInterface* event, Tick start, Tick end) { assert(end > start); if (event->active()) { auto current = event->scheduled_at() - now_; // Event is already scheduled to happen in this range. Instead // of always using the old slot, we could check compute the // new slot and switch iff it's aligned better than the old one. // But it seems hard to believe that could be worthwhile. if (current >= start && current <= end) { return; } } // Zero as many bits (in WIDTH_BITS chunks) as possible // from "end" while still keeping the output in the // right range. Tick mask = ~0; while ((start & mask) != (end & mask)) { mask = (mask << WIDTH_BITS); } Tick delta = end & (mask >> WIDTH_BITS); schedule(event, delta); } Tick TimerWheel::ticks_to_next_event(Tick base, Tick max, unsigned level) const { if (ticks_pending_) { return 0; } // Smallest tick (relative to now) we've found. Tick min = max; for (unsigned i = 0; i < NUM_SLOTS; ++i) { // Note: Unlike the uses of "now", slot index calculations really // need to use now_. auto slot_index = (base + 1 + i) % NUM_SLOTS; // We've reached slot 0. In normal scheduling this would // mean advancing the next wheel and promoting or executing // those events. So we need to look in that slot too // before proceeding with the rest of this wheel. But we // can't just accept those results outright, we need to // check the best result there against the next slot on // this wheel. if (slot_index == 0 && level < MAX_LEVEL) { // Exception: If we're in the core wheel, and slot 0 is // not empty, there's no point in looking in the outer wheel. // It's guaranteed that the events actually in slot 0 will be // executed no later than anything in the outer wheel. if (level > 0 || !slots_[level][slot_index].events()) { Tick now = base >> WIDTH_BITS; auto up_slot_index = (now + 1) % NUM_SLOTS; const auto& slot = slots_[level + 1][up_slot_index]; for (auto event = slot.events(); event != NULL; event = event->next_) { min = std::min(min, event->scheduled_at() - now_); } } } bool found = false; const auto& slot = slots_[level][slot_index]; for (auto event = slot.events(); event != NULL; event = event->next_) { min = std::min(min, event->scheduled_at() - now_); // In the core wheel all the events in a slot are guaranteed to // run at the same time, so it's enough to just look at the first // one. if (level == 0) { return min; } else { found = true; } } if (found) { return min; } } // Nothing found on this wheel, try the next one (unless the wheel can't // possibly contain an event scheduled earlier than "max"). if (level < MAX_LEVEL && (max >> (WIDTH_BITS * level + 1)) > 0) { return ticks_to_next_event(base >> WIDTH_BITS, max, level + 1); } return max; } } // namespace base #endif // RATAS_TIMER_WHEEL_H
true
3151c6a05d24a0c44391cfeaaada35f85073e3bc
C++
MaxFanCheak/ITMO
/1_Course/1_Term/Algorithms and Data Structures/Stacks.Queue/C.cpp
UTF-8
1,229
2.90625
3
[]
no_license
#include<stdio.h> #include<algorithm> #include<deque> using namespace std; deque <int> ::iterator queue[100000]{}; class backQueue { deque<int> val; public: void push(int x) { val.push_back(x); queue[x] = val.end(); } void popBack() { val.pop_back(); } void popFront() { val.pop_front(); } int getQueue(int id) { return distance(val.begin(), queue[id])-1; } int getHead() { return *val.begin(); } void print_stek() { for (auto i = val.begin(); i < val.end(); i++) printf("%d\n", *i); printf("\n\n"); } }; int scan() { int mod = 0, znak = 1; char x = getchar(); while (x > '9' || x < '0') { if (x == '-') znak = -1; x = getchar(); } while (x >= '0' && x <= '9') { mod = mod * 10 + x - '0'; x = getchar(); } return mod * znak; } void main() { backQueue val; int n, c; int x; n=scan(); for (; n; n--) { c = scan(); switch (c) { case 1: x = scan(); val.push(x); break; case 2: val.popFront(); break; case 3: val.popBack(); break; case 4: x = scan(); printf("%d\n", val.getQueue(x)); break; case 5: printf("%d\n", val.getHead()); break; default: break; } } }
true
7921c77cb4c7e6f315b9f36578337a884cf318d2
C++
oWASDo/OpenglEngine
/OpenGL_Engine/header/FileReader.h
UTF-8
457
2.90625
3
[ "MIT" ]
permissive
#pragma once #include<iostream> #include<fstream> static std::string ReadFile(std::string filePaht) { std::ifstream myReadFile; myReadFile.open(filePaht.c_str()); char output; std::string outString; if (myReadFile.is_open()) { while (!myReadFile.eof()) { //myReadFile >> output; output = myReadFile.get(); outString.push_back(output); // std::cout << output; } } myReadFile.close(); outString.pop_back(); return outString; }
true
cd659671fec54aae8c0f12a95ad93a292e93fc12
C++
Wokulsky/projekt
/projekt/Enemy.cpp
WINDOWS-1250
2,231
3.078125
3
[]
no_license
#include "Enemy.h" /* Enemy::Enemy(sf::Texture &tex) { this->setTexture(tex); /*speed = 0.25; name = "Dragon"; hp = 150; damage = 20; level = 1; row = 3; //tex.loadFromFile("enemy.png"); this->setTextureRect(sf::IntRect(0, 0, 100, 100)); animation = std::make_shared<Animation>(tex, sf::Vector2u(4, 4), 100.0); //Buffer by nie byo nagych zmian kierunkw animationBuffer = 0; //Aby nie dominoway dwa kierunki flagAnimation = true; } Enemy::~Enemy() { } void Enemy::Update(float ElapsedTime, sf::Vector2f playerPos) { /*if (hp > 0) { float x = this->getPosition().x; float y = this->getPosition().y; //Poruszanie si wroga if (x <= playerPos.x) {//PRAWO x += speed * ElapsedTime; if (animationBuffer <= 0 && flagAnimation) { row = 2; animationBuffer = BufferSize; flagAnimation = false; } } else if (x >= playerPos.x) {//LEWO x -= speed * ElapsedTime; if (animationBuffer <= 0){ row = 1; animationBuffer = BufferSize; flagAnimation = false; } } if (y <= playerPos.y) {//GRA y += speed * ElapsedTime; if (animationBuffer <= 0 && !flagAnimation){ animationBuffer = BufferSize; row = 0; flagAnimation = true; } } else if (y >= playerPos.y) {//Dӣ y -= speed * ElapsedTime; if (animationBuffer <= 0) { row = 3; animationBuffer = BufferSize; flagAnimation = true; } } animationBuffer--; float targetX; this->setPosition(x, y); animation->Update(row, ElapsedTime); this->setTextureRect(animation->uvRect); this->setScale(1.3, 1.3); } } void Enemy::Render(sf::RenderWindow &App) { /*if(hp > 0) App.draw(*this); }*/ std::string Enemy::getName() { return name; } bool Enemy::isAlive() { return hp > 0; } float Enemy::getSpeed() { return speed; } int Enemy::getHp() { return hp; } int Enemy::getDamage() { return damage; } int Enemy::getLevel() { return level; } void Enemy::setSpeed(float set) { speed = set; } void Enemy::setHp(int set) { hp = set; } void Enemy::setDamage(int set) { damage = set; } void Enemy::setLevel(int set) { level = set; } void Enemy::setName(std::string name) { this->name = name; } void Enemy::DecreaseHP(int set) { hp -= set; }
true
8da972cf9b0c7f6e3ecff06dd54f25e413552dc4
C++
drlongle/leetcode
/algorithms/problem_1899/solution.cpp
UTF-8
4,062
3.421875
3
[]
no_license
/* 1899. Merge Triplets to Form Target Triplet Medium A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise. Example 1: Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] The target triplet [2,7,5] is now an element of triplets. Example 2: Input: triplets = [[1,3,4],[2,5,8]], target = [2,5,8] Output: true Explanation: The target triplet [2,5,8] is already an element of triplets. Example 3: Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true Explanation: Perform the following operations: - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. The target triplet [5,5,5] is now an element of triplets. Example 4: Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. Constraints: 1 <= triplets.length <= 10^5 triplets[i].length == target.length == 3 1 <= ai, bi, ci, x, y, z <= 1000 */ #include <algorithm> #include <atomic> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <condition_variable> #include <functional> #include <future> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <memory> #include <numeric> #include <queue> #include <random> #include <regex> #include <set> #include <sstream> #include <stack> #include <string_view> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include "common/ListNode.h" #include "common/TreeNode.h" using namespace std; class Solution { public: bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) { vector<int> checked(3, false); for (int i = 0, sz = triplets.size(); i < sz; ++i) { for (int k = 0; k < 3; ++k) { if (triplets[i][k] == target[k] && triplets[i][(k+1) % 3] <= target[(k+1) % 3] && triplets[i][(k+2) % 3] <= target[(k+2) % 3]) checked[k] = true; } } return count(begin(checked), end(checked), true) == 3; } }; int main() { Solution sol; vector<vector<int>> triplets; vector<int> target; // Output: true triplets = {{2,5,3},{1,8,4},{1,7,5}}, target = {2,7,5}; cout << boolalpha << sol.mergeTriplets(triplets, target) << endl; // Output: true triplets = {{1,3,4},{2,5,8}}, target = {2,5,8}; cout << boolalpha << sol.mergeTriplets(triplets, target) << endl; // Output: true triplets = {{2,5,3},{2,3,4},{1,2,5},{5,2,3}}, target = {5,5,5}; cout << boolalpha << sol.mergeTriplets(triplets, target) << endl; // Output: false triplets = {{3,4,5},{4,5,6}}, target = {3,2,5}; cout << boolalpha << sol.mergeTriplets(triplets, target) << endl; return 0; }
true
07b24f0ff9fdf8ecb71080c37ae29f584154060a
C++
washing1127/LeetCode
/Solutions/0066/0066.cpp
UTF-8
469
2.875
3
[]
no_license
class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.end() - digits.begin(); int p = 1; for (int i=n-1; i>=0; i--){ if (digits[i] == 9){ digits[i] = 0; p = 1; }else { digits[i]++; p = 0; } if (p == 0) break; } if (p) digits.insert(digits.begin(), 1); return digits; } };
true
322c3542c2b1109647dae340569d6c107f57afc8
C++
ktp-forked-repos/header_libraries
/include/daw/iterator/daw_checked_iterator_proxy.h
UTF-8
6,266
2.609375
3
[ "MIT" ]
permissive
// The MIT License (MIT) // // Copyright (c) 2016-2019 Darrell Wright // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files( the "Software" ), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and / or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <stdexcept> #include <type_traits> #include "../daw_exception.h" #include "../daw_move.h" namespace daw { template<typename IteratorFirst, typename IteratorLast> class checked_iterator_proxy_t { enum flag_t : uint8_t { check_increment = 1, check_decrement = 2, check_dereference = 4 }; IteratorFirst current; IteratorFirst first; IteratorLast last; uint8_t flags; constexpr bool is_flag_set( flag_t flag ) const noexcept { return 0 != ( flags & flag ); } constexpr auto get_flag_value( bool CheckIncrement, bool CheckDecrement, bool CheckDereference ) const noexcept { uint8_t result = CheckIncrement ? check_increment : 0; result |= CheckDecrement ? check_decrement : 0; result |= CheckDereference ? check_dereference : 0; return result; } public: checked_iterator_proxy_t( IteratorFirst it_first, IteratorLast it_last, bool CheckIncrement = true, bool CheckDecrement = true, bool CheckDereference = true ) : current{it_first} , first{daw::move( it_first )} , last{daw::move( it_last )} , flags{ get_flag_value( CheckIncrement, CheckDecrement, CheckDereference )} {} checked_iterator_proxy_t( checked_iterator_proxy_t const & ) = default; checked_iterator_proxy_t( checked_iterator_proxy_t && ) = default; checked_iterator_proxy_t & operator=( checked_iterator_proxy_t const & ) = default; checked_iterator_proxy_t & operator=( checked_iterator_proxy_t && ) = default; checked_iterator_proxy_t( ) = default; ~checked_iterator_proxy_t( ) = default; checked_iterator_proxy_t &operator++( ) { if( is_flag_set( check_increment ) and current == last ) { daw::exception::daw_throw<std::out_of_range>( "Attempt to increment iterator past end of range" ); } ++current; return *this; } checked_iterator_proxy_t operator++( int ) const { checked_iterator_proxy_t result{*this}; ++result; return result; } checked_iterator_proxy_t &operator--( ) { if( is_flag_set( check_decrement ) and current == first ) { throw std::out_of_range( "Attempt to decrement iterator past beginning of range" ); } --current; return *this; } checked_iterator_proxy_t operator--( int ) const { checked_iterator_proxy_t result{*this}; --result; return result; } auto &operator*( ) { if( is_flag_set( check_dereference ) and current == last ) { throw std::out_of_range( "Attempt to dereference an iterator at end of range" ); } return *current; } auto const &operator*( ) const { if( is_flag_set( check_dereference ) and current == last ) { throw std::out_of_range( "Attempt to dereference an iterator at end of range" ); } return *current; } auto &operator-> ( ) { if( is_flag_set( check_dereference ) and current == last ) { throw std::out_of_range( "Attempt to access members an iterator at end of range" ); } return current.operator->( ); } auto const &operator-> ( ) const { if( is_flag_set( check_dereference ) and current == last ) { throw std::out_of_range( "Attempt to access members an iterator at end of range" ); } return current.operator->( ); } template<typename IteratorFirst_lhs, typename IteratorFirst_rhs, typename IteratorLast_lhs, typename IteratorLast_rhs> friend bool operator==( checked_iterator_proxy_t<IteratorFirst_lhs, IteratorLast_lhs> const &lhs, checked_iterator_proxy_t<IteratorFirst_rhs, IteratorLast_rhs> const &rhs ) { return lhs.current == rhs.current; } template<typename IteratorFirst_lhs, typename IteratorLast_lhs, typename Iterator_rhs> friend bool operator==( checked_iterator_proxy_t<IteratorFirst_lhs, IteratorLast_lhs> const &lhs, Iterator_rhs const &rhs ) { return lhs.current == rhs; } template<typename IteratorFirst_lhs, typename IteratorFirst_rhs, typename IteratorLast_lhs, typename IteratorLast_rhs> friend bool operator!=( checked_iterator_proxy_t<IteratorFirst_lhs, IteratorLast_lhs> const &lhs, checked_iterator_proxy_t<IteratorFirst_rhs, IteratorLast_rhs> const &rhs ) { return lhs.current != rhs.current; } template<typename IteratorFirst_lhs, typename IteratorLast_lhs, typename Iterator_rhs> friend bool operator!=( checked_iterator_proxy_t<IteratorFirst_lhs, IteratorLast_lhs> const &lhs, Iterator_rhs const &rhs ) { return lhs.current != rhs; } }; // checked_iterator_proxy_t template<typename IteratorFirst, typename IteratorLast> auto make_checked_iterator_proxy( IteratorFirst first, IteratorLast last, bool CheckIncrement = true, bool CheckDecrement = true, bool CheckDereference = true ) { return checked_iterator_proxy_t<IteratorFirst, IteratorLast>{ first, last, CheckIncrement, CheckDecrement, CheckDereference}; } } // namespace daw
true
9a57168ae1ed442e68e36279199595eefe68c565
C++
drowsell/LeetCode-Practice
/Power-of-two.cpp
UTF-8
360
2.875
3
[]
no_license
class Solution { public: bool isPowerOfTwo(int n) { double answer = 0; if(n == 0 || n < 0) return false; else answer = log2(n); if(answer == static_cast<int>(answer)) return true; cout << answer << endl; return false; } };
true
2c393f071a4e2aaf97125382c793909833791856
C++
3jackdaws/Minesweeper
/Minesweeper/Cell.cpp
UTF-8
6,204
3.125
3
[]
no_license
/************************************************************* * Author: Ian Murphy * Filename: Cell.cpp * Date Created: 1/18/16 * Modifications: 1/18/16 - added documentation **************************************************************/ #include "Cell.hpp" /********************************************************************** * Purpose: Default ctor for cell. * * Precondition: * none * * Postcondition: * sets _grid to nullptr, _prox to 'W', and _mark to false * ************************************************************************/ Cell::Cell() : _grid(nullptr), _prox('W'), _mark(false) { } /********************************************************************** * Purpose: 3 arg ctor for cell. * * Precondition: * none * * Postcondition: * sets _grid to grid, _prox to 'W', and _mark to false, and _row to row, and _col to col * ************************************************************************/ Cell::Cell(Array2D<Cell> * grid, int row, int col): _exposed(false), _prox('0'), _grid(grid), _row(row), _col(col), _mark(false) { } /********************************************************************** * Purpose: copy ctor for cell. * * Precondition: * cp must be an object * * Postcondition: * sets everything equal to cp * ************************************************************************/ Cell::Cell(const Cell & cp) : _exposed(cp._exposed), _prox(cp._prox), _grid(cp._grid), _mark(cp._mark) { } /********************************************************************** * Purpose: d'tor for cell. * * Precondition: * cell is instantiated * * Postcondition: * cell is gone * ************************************************************************/ Cell::~Cell() { } /********************************************************************** * Purpose: op = overload for cell. * * Precondition: * both objects are instantiated * * Postcondition: * sets cell to values in rhs * ************************************************************************/ Cell & Cell::operator=(Cell &rhs) { if(&rhs != this) { _prox = rhs._prox; _exposed = rhs._exposed; _row = rhs._row; _col = rhs._col; _grid = rhs._grid; } return *this; } /********************************************************************** * Purpose: increments the _prox value in cell * * Precondition: * _prox must have some value * * Postcondition: * sets _prox to 1 more than its previous value * ************************************************************************/ char Cell::operator++(int) { char old = _prox; if(_prox != 'W' && _prox != 'B') _prox++; return old; } /********************************************************************** * Purpose: Tells the cell object that it is now a bomb * * Precondition: * none, really * * Postcondition: * _prox is set to 'B' all cells around the cell have their _prox incremented * ************************************************************************/ void Cell::SetBomb() { _prox = 'B'; (*_grid)[_row][_col-1]++; //west (*_grid)[_row-1][_col-1]++; //North West (*_grid)[_row-1][_col]++; //north (*_grid)[_row-1][_col+1]++; //north east (*_grid)[_row][_col+1]++; //east (*_grid)[_row+1][_col+1]++; //south east (*_grid)[_row+1][_col]++; //south (*_grid)[_row+1][_col-1]++; //south west } /********************************************************************** * Purpose: Sets _prox to p. * * Precondition: * none * * Postcondition: * _prox is now p * ************************************************************************/ void Cell::SetProx(char p) { _prox = p; } /********************************************************************** * Purpose: returns the value in _prox. * * Precondition: * _prox needs a value * * Postcondition: * returns _prox * ************************************************************************/ char Cell::getProx() { return _prox; } /********************************************************************** * Purpose: Uncovers the current cell. * * Precondition: * cell must be real * * Postcondition: * Cell is set to uncovered, will call uncover on all cells around it if the _prox of the current cell is 0 will return true if a bomb is uncovered * ************************************************************************/ bool Cell::Uncover() { bool rval = false; if(_exposed == false && _mark == false) { _exposed = true; if(_prox == '0') { (*_grid)[_row][_col-1].Uncover(); //west (*_grid)[_row-1][_col-1].Uncover(); //North West (*_grid)[_row-1][_col].Uncover(); //north (*_grid)[_row-1][_col+1].Uncover(); //north east (*_grid)[_row][_col+1].Uncover(); //east (*_grid)[_row+1][_col+1].Uncover(); //south east (*_grid)[_row+1][_col].Uncover(); //south (*_grid)[_row+1][_col-1].Uncover(); //south west } else if(_prox == 'B') { rval = true; } else //not one of those { } } return rval; } /********************************************************************** * Purpose: returns the cells exposure status * * Precondition: * none * * Postcondition: * returns _exposed * ************************************************************************/ bool Cell::getExposure() { return _exposed; } /********************************************************************** * Purpose: Marks a cell. * * Precondition: * none * * Postcondition: * toggles _mark for a cell * ************************************************************************/ void Cell::Mark() { if(!_exposed) _mark == true ? _mark = false : _mark = true; } /********************************************************************** * Purpose: returns the cell's mark status * Precondition: * none * * Postcondition: * returns _mark * ************************************************************************/ bool Cell::MarkStatus() { return _mark; }
true
dafb95de981a97846eee398b2ef8f1af410d5eb7
C++
mortele/HartreeFock
/old/Integrator/Orbitals/orbital.h
UTF-8
1,079
2.546875
3
[]
no_license
#pragma once class Orbital { public: Orbital(int dimensions, int quantumNumbers); virtual double computeWavefunction(double* coordinates, int* numberOfQuantumNumbers) = 0; virtual double* getCoordinateScales() = 0; int getNumberOfDimensions() { return m_dimensions; } int getNumberOfQuantumNumbers() { return m_numberOfQuantumNumbers; } virtual double integrandOne(double* allCoordinates, int* allQuantumNumbers); virtual double integrandTwo(double* allCoordinates, int* allQuantumNumbers); virtual void updateCoordinateScales(int* allQuantumNumbers, int numberOfQuantumNumbers); static int* mapToOrbitals(int p, int type); static int* generateQuantumNumbers(int* indices, int oneBodyOrTwoBody, int type); protected: int m_dimensions = 0; int m_numberOfQuantumNumbers = 0; static int factorial(int n); public: static double associatedLaguerrePolynomial(double x, int n, int m); };
true
5d3c0c0895972fd92834dec9e52f63cfb91c7445
C++
It4innovations/espreso
/src/input/parsers/meshgenerator/elements/3D/hexahedron20.cpp
UTF-8
1,254
2.65625
3
[]
no_license
#include "hexahedron20.h" using namespace espreso; Hexahedron20Generator::Hexahedron20Generator() { subelements = 1; enodes = 20; code = Element::CODE::HEXA20; } void Hexahedron20Generator::pushElements(std::vector<esint> &elements, const std::vector<esint> &indices) const { elements.push_back(indices[ 2]); elements.push_back(indices[ 8]); elements.push_back(indices[ 6]); elements.push_back(indices[ 0]); elements.push_back(indices[20]); elements.push_back(indices[26]); elements.push_back(indices[24]); elements.push_back(indices[18]); elements.push_back(indices[ 5]); elements.push_back(indices[ 7]); elements.push_back(indices[ 3]); elements.push_back(indices[ 1]); elements.push_back(indices[23]); elements.push_back(indices[25]); elements.push_back(indices[21]); elements.push_back(indices[19]); elements.push_back(indices[11]); elements.push_back(indices[17]); elements.push_back(indices[15]); elements.push_back(indices[ 9]); } void Hexahedron20Generator::pushFace(std::vector<esint> &elements, std::vector<esint> &esize, std::vector<int> &etype, const std::vector<esint> &indices, CubeFace face) const { pushNodes(elements, indices, face); esize.push_back(8); etype.push_back((int)Element::CODE::SQUARE8); }
true
1388cdd4eed7015c5929d40377992a977c1bc7c5
C++
Mpaop/my_experiment_code
/uotree/test.cpp
UTF-8
565
2.859375
3
[]
no_license
#include "uotree.h" #include <iostream> auto main() -> int { mpaop::smartptr::uotree::MUnorderedTree<int> tree(5, 10); { tree.insert(100, 20); } { tree.insert(-1, 100); } for(int32_t i = 0, j = 11; i <= 10; ++i, ++j) { std::cout << "Do Insert\n"; if(i != 5) tree.insert(i, j); std::cout << "Next\n"; } std::cout << (** tree.find(3)) << std::endl; std::cout << (** tree.find(6)) << std::endl; tree.remove(2); tree.insert(12, 5); tree.remove(5); return 0; }
true
e0c9505ab274c18ed367abddc1d7f2f314efdb31
C++
wzshare/Leetcode
/easy/26_Remove_Duplicates_from_Sorted_Array.cpp
UTF-8
860
3.671875
4
[ "MIT" ]
permissive
#include "../libstruct.h" using namespace std; /* * NO.26 * Given a sorted array, remove the duplicates in-place such that each * element appear only once and return the new length. * Do not allocate extra space for another array, you must do this by * modifying the input array in-place with O(1) extra memory. */ class Solution { public: int removeDuplicates(vector<int>& nums) { int a = 0, b = a; while (b < nums.size()) { while (b < nums.size() && nums[a] == nums[b]) b++; if (++a < nums.size() && b < nums.size()) nums[a] = nums[b]; } return a; } }; int main(int argc, char const *argv[]) { Solution solution; vector<int> vec = {1, 1, 2}; int n = solution.removeDuplicates(vec); for (int i = 0; i < n; i++) cout << vec[i] << " "; cout << endl; return 0; }
true
e7e1cd60e88d8d48e755b15112bf6623e9f0287d
C++
patrick24r/sparkboxHD
/device/shared/host/filesystem/host_filesystem_driver.h
UTF-8
1,567
2.90625
3
[]
no_license
#pragma once #include <cstdint> #include <filesystem> #include <fstream> #include <map> #include <memory> #include <string> #include "sparkbox/status.h" #include "sparkbox/filesystem/filesystem_driver.h" namespace { using ::sparkbox::Status; } // namespace namespace device::shared::host { class HostFilesystemDriver final : public sparkbox::filesystem::FilesystemDriver { public: static constexpr int kMaxFiles = 5; static constexpr int kMaxDirs = 3; // Nothing special to be done for initialization on host Status Init() final { return Status::kOk; } Status Exists(const std::string& path, bool& exists) final; Status CreateDirectory(const std::string& directory) final; Status Remove(const std::string& path) final; Status Open(int& file_id, const std::string& path, IoMode mode) final; Status Close(int file_id) final; Status Read(int file_id, void * data, size_t bytes_to_read, size_t& bytes_read) final; Status Write(int file_id, const void * data, size_t bytes_to_write, size_t& bytes_written) final; private: std::map<int, std::unique_ptr<std::fstream>> open_files_; // Gets a unique id for a new file by just picking the next int. // If not available, check the next one int GetUniqueFileId() { static int next_file_id = 0; while (open_files_.count(next_file_id)) { ++next_file_id; } return next_file_id; } }; } // namespace device::shared::host
true
34ed3aa32d953bc4be04750e4e4cd7aecdf4cdc1
C++
xTimShultz/euler
/euler-004.cpp
UTF-8
1,995
4.09375
4
[]
no_license
// https://projecteuler.net/problem=4 // A palindromic number reads the same both ways. The largest palindrome made from // the product of two 2-digit numbers is 9009 = 91 × 99. // Find the largest palindrome made from the product of two 3-digit numbers. // // Assume that the largest palindrome will be a 6-digit number. // The largest 6-digit palindrome is 999999. The smallest is 100001 // // So, we will start with forming palindromes by mirroring their // 3-digit countersparts like 999 -> 999999, starting with the largest. // This will give us a palindrome to solve for and a single factor. // // We'll use another loop to find a second factor that produces the palindrome as // a product. If we get a match, then we're done, since we start with the largest // palindromes and work backwards to find their 3-digit factors. // // e.g. 999 (factor) #include <iostream> using std::cout; using std::endl; unsigned int form_palindrome(unsigned int num) { unsigned int ones = num % 10; unsigned int hundreds = num / 100; unsigned int tens = (num - ones - (hundreds * 100)) / 10; // Mirror and return result unsigned int result = (num * 1000) + (ones * 100) + (tens * 10) + hundreds; return result; } int main() { for (unsigned int i = 999; i >= 100; i--) { unsigned int palindrome = form_palindrome(i); for (unsigned int factor1 = 100; factor1 * factor1 <= palindrome; factor1++) { // If factor1 is an evenly divisible factor, find factor2 if (palindrome % factor1 == 0) { unsigned int factor2 = palindrome / factor1; if ((palindrome % factor2 == 0) && (factor2 >= 100) && (factor2 <= 999)) { // Largest palindrome found cout << palindrome << endl; return 0; } } } } return 0; }
true
ff215076141afa285c0cbd73a439735821573d88
C++
grahameger/EECS398Engine
/include/PersistentHashMap.h
UTF-8
15,032
2.953125
3
[]
no_license
// Created by Graham Eger on 4/1/2019 #pragma once #ifndef PERSISTENTHASHMAP_H_398 #define PERSISTENTHASHMAP_H_398 #include <cstdlib> #include <cstdio> #include <iterator> #include <iostream> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <assert.h> #include "hash.h" #include "mmap.h" #include "Pair.h" #include "String.h" #include "PersistentBitVector.h" #ifndef O_NOATIME #define O_NOATIME 0 #endif // Linear Probing thread-safe file backed hash map template <typename Key, typename Mapped> class PersistentHashMap { public: // Custom typedefs using KeyType = Key; using MappedType = Mapped; using ValueType = Pair<Key, Mapped>; using SizeType = std::size_t; // Constructor PersistentHashMap(String filename, double loadFactorIn = 0.7); ~PersistentHashMap(); // Square Brackets Operator MappedType& operator[](const KeyType& key); MappedType& at(const KeyType& key); // Inserts value into hash table, thread safe. void insert(const ValueType& keyVal); // Flush function bool flush(); // Erase the item in the table matching the key. // Returns whether an item was deleted. bool erase(const Key& key); // Iterator forward declares class Iterator; friend class Iterator; Iterator find(const KeyType& key); // Usual iterator operations Iterator begin(); Iterator end(); // Basic info member functions SizeType size(); bool empty(); SizeType capacity(); void printState(); private: static const SizeType INITIAL_CAPACITY = 64; // probing functions SizeType probeForExistingKey(const KeyType& key ); SizeType probeEmptySpotForKey(const KeyType& key ); // insert funcitons void insertKeyValue(const ValueType& value); void noProbeNoRehashInsertKeyValueAtIndex(const ValueType &value, SizeType index); void rehashAndGrow(); bool rehashNeeded(); void writeLock(); void readLock(); void unlock(); private: // private data struct HeaderType { size_t numElements; size_t capacity; double loadFactor; threading::ReadWriteLock rwLock; }; int fd; HeaderType * header; ValueType * buckets; PersistentBitVector isGhost; PersistentBitVector isFilled; }; // Iterator class for the hash table, just simple forward iteration. template <typename Key, typename Mapped> class PersistentHashMap<Key, Mapped>::Iterator { public: using iterator_category = std::forward_iterator_tag; using value_type = Pair<Key, Mapped>; using different_type = ssize_t; using pointer = std::add_pointer_t<value_type>; using reference = std::add_lvalue_reference_t<value_type>; Iterator() : index(0) {} Iterator(size_t index_in, PersistentHashMap* persistentHashMapIn) : persistentHashMap{persistentHashMapIn}, index{index_in} {} // No need for locks here as we already have the index // it's on the programmer to know if their iterator has been invalidated Pair<Key, Mapped>& operator*() { assert(!this->persistentHashMap->isGhost.at(this->index)); assert(this->persistentHashMap->isFilled.at(this->index)); return this->persistentHashMap->buckets[this->index]; } // We'll read lock here just because we're iterating through the Hash Map Iterator& operator++() { this->persistentHashMap->readLock(); ++this->index; for (; (this->index != this->persistentHashMap->size() && (this->persistentHashMap->isGhost.at(this->index) || !this->persistentHashMap->isFilled.at(this->index))); ++this->index); this->persistentHashMap->unlock(); return *this; } // No lock necessary, iterators aren't volatile. bool operator!= (const Iterator& other) { return this->index != other.index; } private: PersistentHashMap<Key, Mapped> * persistentHashMap; size_t index; }; template <typename Key, typename Mapped> PersistentHashMap<Key, Mapped>::PersistentHashMap(String filename, double loadFactorIn) : isGhost( filename + "_ghost" ), isFilled( filename + "_filled" ) { // check if the file exists struct stat buffer; bool fileExists = (stat(filename.CString(), &buffer) == 0); // open file with correct flags int openFlags = O_RDWR | O_NOATIME; if (!fileExists) { openFlags |= O_CREAT; } fd = open(filename.CString(), openFlags, 0755); if (fd < 0) { fprintf(stderr, "open() returned -1 - error: %s\n", strerror(errno)); exit(1); } // mmap and setup the header portion header = (HeaderType*)mmapWrapper(fd, sizeof(HeaderType), 0); // memory mapped files should be initialized to 0 // jokes on me they're not in practice if (header->capacity == 0) { header->rwLock = threading::ReadWriteLock(); } // TODO: this feels deadlocky, putting this comment here just in case header->rwLock.writeLock(); if (!fileExists) { header->capacity = INITIAL_CAPACITY; } header->loadFactor = loadFactorIn; // mmap the data portion this->buckets = (ValueType*)mmapWrapper(fd, header->capacity * sizeof(ValueType), sizeof(HeaderType)); // we shouldn't memset we should default construct the objects? this->header->rwLock.unlock(); } template <typename Key, typename Mapped> PersistentHashMap<Key, Mapped>::~PersistentHashMap() { // unmap buckets munmapWrapper(buckets, this->header->capacity * sizeof(ValueType)); // unmap header munmapWrapper(header, sizeof(HeaderType)); } template <typename Key, typename Mapped> bool PersistentHashMap<Key, Mapped>::flush() { // sync buckets int rv = msyncWrapper(buckets, this->header->capacity * sizeof(ValueType)); if (rv != 0) { return false; } // sync header rv = msyncWrapper(header, sizeof(HeaderType)); if (rv != 0) { return false; } return true; } // Inserts the value into the hash table at a given indice. template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>:: noProbeNoRehashInsertKeyValueAtIndex(const ValueType &value, SizeType index) { // insert into the buckets and then update the other members this->buckets[index] = value; this->isFilled.set(index, true); assert(isFilled.at(index)); this->isGhost.set(index, false); assert(!isGhost.at(index)); } template<typename Key, typename Mapped> bool PersistentHashMap<Key, Mapped>::rehashNeeded() { double currentLoadFactor = static_cast<double>(this->header->numElements) / static_cast<double>(this->header->capacity); return currentLoadFactor > this->header->loadFactor; } // private insert function template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::insertKeyValue(const ValueType& value) { // check if the value exists auto indexOld = this->probeForExistingKey(value.first); if (indexOld != this->header->capacity) return; // Check the load factor for a rehash if (this->rehashNeeded()) this->rehashAndGrow(); // insert the value ++this->header->numElements; auto indexToInsert = this->probeEmptySpotForKey(value.first); this->noProbeNoRehashInsertKeyValueAtIndex(value, indexToInsert); } template<typename Key, typename Mapped> size_t PersistentHashMap<Key, Mapped>::probeEmptySpotForKey(const Key& key) { //size_t i = std::hash<KeyType>{}(key) % this->header->capacity; size_t i = hash::Hash<KeyType>{}.get(key) % this->header->capacity; size_t start = i; // when we find one return index, if it already exists, return that index for (; i < this->header->capacity; ++i) { if (!isFilled.at(i) || isGhost.at(i)) { return i; } } for (i = 0; i < start; ++i) { if (!isFilled.at(i) || isGhost.at(i)) { return i; } } return this->header->capacity; } // const functions need a read lock // non-const functions need a write lock template<typename Key, typename Mapped> size_t PersistentHashMap<Key, Mapped>::probeForExistingKey(const Key& key) { // if it's there then we return the index // otherwise return one past the end // size_t i = std::hash<KeyType>{}(key) % this->header->capacity; size_t i = hash::Hash<KeyType>{}.get(key) % this->header->capacity; size_t start = i; for (; (isGhost.at(i) || isFilled.at(i)) && i < this->header->capacity; ++i ) { if (buckets[i].first == key) { return i; } } if (!isGhost.at(i) && isFilled.at(i)) { return this->header->capacity; } else { for (i = 0; (isGhost.at(i) || isFilled.at(i)) && i < start; ++i) { if (buckets[i].first == key) { return i; } } } // if we get here we should be setting return this->header->capacity; } // O(1) average // O(n) worse case template<typename Key, typename Mapped> Mapped& PersistentHashMap<Key, Mapped>::operator[] (const KeyType& key) { // probe for key, if it doesn't exist then insert this->writeLock(); auto indexForKey = this->probeForExistingKey(key); if (indexForKey == this->header->capacity) { this->insertKeyValue(ValueType{key, MappedType{}}); } // get key and return val at that location indexForKey = this->probeForExistingKey(key); auto& rv = this->buckets[indexForKey].second; this->unlock(); return rv; } template<typename Key, typename Mapped> Mapped& PersistentHashMap<Key, Mapped>::at(const KeyType& key) { // probe for key this->readLock(); auto indexForKey = this->probeForExistingKey(key); if (indexForKey == this->header->capacity) { this->unlock(); throw std::out_of_range("Key does not exist in hash map"); } auto& rv = this->buckets[indexForKey].second; this->unlock(); return rv; } template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::rehashAndGrow() { // double the size of the mapped buckets portion size_t newCapacity = this->header->capacity * 2; size_t newBucketSize = newCapacity * sizeof(ValueType); // unmap old region munmapWrapper(buckets, newBucketSize / 2); // map the new region buckets = (ValueType*)mmapWrapper(fd, newBucketSize, sizeof(HeaderType)); // zero only the new region of memory size_t half = sizeof(ValueType) * this->header->capacity; memset((void*)((uint8_t*)buckets + half), 0x0, half); // double the size of the isFilled and isGhost bit vectors isGhost.resize(newCapacity); isFilled.resize(newCapacity); // adjust the capacity to reflect the changes above this->header->capacity = newCapacity; // rehash for (size_t i = 0; i < newCapacity / 2; ++i) { if (!isGhost.at(i) && isFilled.at(i)) { size_t emptySpot = probeEmptySpotForKey(buckets[i].first); isFilled.set(i, false); isGhost.set(i, true); noProbeNoRehashInsertKeyValueAtIndex(buckets[i], emptySpot); } } } template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::insert(const ValueType& keyValue) { this->writeLock(); this->insertKeyValue(keyValue); this->unlock(); } // these templates are getting a little ridiculous template<typename Key, typename Mapped> typename PersistentHashMap<Key, Mapped>::Iterator PersistentHashMap<Key, Mapped>::find(const Key& key) { this->readLock(); size_t index = probeForExistingKey(key); this->unlock(); return Iterator(index, this); } // returns an iterator to the first filled bucket template<typename Key, typename Mapped> typename PersistentHashMap<Key, Mapped>::Iterator PersistentHashMap<Key, Mapped>::begin() { // this should always be good // TODO: remove in release mode this->readLock(); // no need to unlock on these, they'll kill the program assert(this->header->capacity == isFilled.size()); assert(this->header->capacity == isGhost.size()); size_t firstIndex; for (firstIndex = 0; firstIndex != this->header->capacity; ++firstIndex) { if (this->isFilled.at(firstIndex) && !this->isGhost.at(firstIndex)) { this->unlock(); return Iterator(firstIndex, this); } } // if there's nothing then just return one past the end this->unlock(); return this->end(); } // returns an iterator to one past the end template<typename Key, typename Mapped> typename PersistentHashMap<Key, Mapped>::Iterator PersistentHashMap<Key, Mapped>::end() { this->readLock(); size_t rvCapacity = this->header->capacity; this->unlock(); return Iterator(rvCapacity, this); } template<typename Key, typename Mapped> bool PersistentHashMap<Key, Mapped>::erase(const Key& key) { // find specified element this->writeLock(); auto indexForElement = this->probeForExistingKey(key); if (indexForElement == this->header->capacity) { this->unlock(); return false; } // delete the element from bucket and decrement numElements this->isGhost.set(indexForElement, false); this->isFilled.set(indexForElement, false); --this->header->numElements; this->unlock(); return true; } template<typename Key, typename Mapped> size_t PersistentHashMap<Key, Mapped>::capacity() { this->readLock(); size_t rv = this->header->capacity; this->unlock(); return rv; } template<typename Key, typename Mapped> size_t PersistentHashMap<Key, Mapped>::size() { this->readLock(); size_t rv = this->header->numElements; this->unlock(); return rv; } template<typename Key, typename Mapped> bool PersistentHashMap<Key, Mapped>::empty() { this->readLock(); auto rv = this->header->elements == 0; this->unlock(); return rv; } // Do we really need these? template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::readLock() { header->rwLock.readLock(); } template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::writeLock() { header->rwLock.writeLock(); } template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::unlock() { header->rwLock.unlock(); } template<typename Key, typename Mapped> void PersistentHashMap<Key, Mapped>::printState() { std::cout << "-----" << std::endl; for (size_t i = 0; i < this->header->capacity; ++i) { if (this->isGhost.at(i)) { fprintf(stdout, "%s", "[--]\n"); continue; } else if (!this->isFilled.at(i)) { fprintf(stdout, "%s", "[]\n"); continue; } // if an element is present then print the element std::cout << "[" << this->buckets[i].first << "] " << this->buckets[i].second << std::endl; } std::cout << "-----" << std::endl; } #endif
true
e3181057f85f80523fed7934b54e36bf7ed258fc
C++
luchenqun/leet-code
/problems/387-first-unique-character-in-a-string.cpp
UTF-8
811
3.140625
3
[]
no_license
/* * [387] First Unique Character in a String * * https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/ * https://leetcode.com/problems/first-unique-character-in-a-string/discuss/ * * algorithms * Easy (30.73%) * Total Accepted: 3.2K * Total Submissions: 10.5K * Testcase Example: '"leetcode"' * * 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 * 案例: * s = "leetcode" * 返回 0. * s = "loveleetcode", * 返回 2. * 注意事项:您可以假定该字符串只包含小写字母。 */ #include <iostream> #include <string> using namespace std; class Solution { public: int firstUniqChar(string s) { } }; int main() { Solution s; return 0; }
true
f4a37dfc98b29de0006f25435ee56d49724c51f5
C++
moyamu/ONYA-json
/json.h
UTF-8
5,758
2.96875
3
[ "LicenseRef-scancode-public-domain" ]
permissive
//////////////////////////////////////////////////////////////////////////////////////////////////// // I, the creator of this work, hereby release it into the public domain. This applies worldwide. // In case this is not legally possible: I grant anyone the right to use this work for any purpose, // without any conditions, unless such conditions are required by law. //////////////////////////////////////////////////////////////////////////////////////////////////// // ONYA:json - JSON parser // Public interfaces #ifndef JSON_H #define JSON_H #include <stdexcept> #include <stdlib.h> #include <string> namespace Json { ///////////////////////////////////////////////////////////////////////////////////////////////// /// The type of a JSON value. enum Type { JNULL, JBOOL, JSTRING, JNUMBER, JOBJECT, JARRAY }; ///////////////////////////////////////////////////////////////////////////////////////////////// /// A JSON value. struct Value { /// The value's name if it is part of an object, "" otherwise. Never null. const char *name_; /// The value's textual representation for simple values. If this is an object /// or array, pointer to the first element. const char *value_; /// The next element for object and array members, or null Value *next_; /// Returns the type of this value. Type type() const { return (Type) name_[-1]; } /// Interprets the value as an integer. /// Throws if this is not a number or boolean. int asInt() const; /// Interprets the value as a floating point value. double asDouble() const { return atof(value_); } /// Returns the value's string representation. /// Throws if this is an array or object. const char *asString() const; /// Returns the boolean interpretation of the value. /// false, null and zero numbers (integer or float) are falsy. /// All other values are thruthy. bool asBool() const; /// Returns the number of array of object members. /// Returns 0 for simple types. size_t length() const; /// Returns the first child or NULL if the array/object is empty. /// Throws if this is not an array or object. const Value* children() const; /// Array element access. const Value& get(int i) const; const Value& operator[](int i) const { return get(i); } /// Object member access. const Value& get(const char *name) const; const Value& get(const std::string &key) const { return get(key.c_str()); }; const Value& operator[](const char *key) const { return get(key); } const Value& operator[](const std::string &key) const { return get(key.c_str()); } }; ///////////////////////////////////////////////////////////////////////////////////////////////// enum ParseMode { NON_DESTRUCTIVE, // copy the source before parsig DESTRUCTIVE // don't copy, ovewrite source buffer }; class Tree { private: struct Chunk { char *eofs_; // end of free space Chunk *next_; // next chunk }; Chunk *head_; Value* root_; Value *parseInternal(char *source, const char **error_pos, const char **error_desc); void parseInternal(char *source); Tree(const Tree&); // not implemented void operator=(const Tree&); // not implemented public: Tree(); Tree(char *source, ParseMode mode = NON_DESTRUCTIVE); Tree(const char *source); Tree(const std::string &source); ~Tree(); char *malloc(size_t size); void parse(char *source, ParseMode mode = NON_DESTRUCTIVE); void parse(const char *source); void parse(const std::string &source); const Value& root() const; /// Convenience methods for transparent root access. size_t length() const { return root_->length(); } Type type() const { return root_->type(); } const Value& get(int i) const { return root_->get(i); } const Value& get(const char *name) const { return root_->get(name); } int asInt() const { return root_->asInt(); } double asDouble() const { return root_->asDouble(); } const char *asString() const { return root_->asString(); } bool asBool() const { return root_->asBool(); } const Value& operator[](int i) const { return root_->get(i); } const Value& operator[](const char *key) const { return root_->get(key); } const Value& operator[](const std::string &key) const { return root_->get(key); } }; ///////////////////////////////////////////////////////////////////////////////////////////////// class SyntaxError: public std::runtime_error { public: // The source offset where the error was detected. const size_t offset_; public: ~SyntaxError() throw(); SyntaxError(size_t offset, const char *message); }; ///////////////////////////////////////////////////////////////////////////////////////////////// /// Simple, non-validating JSON formatter. /// Formats the JSON document in «source» and outputs formatted document via «emit()». «usr» is /// passed in the first argument to «emit()». Formatting is done with an indentation of 2 spaces. /// The output is terminated by a newline. void prettyPrint(char const *source, void (*emit)(void *usr, char const *, size_t), void *usr); /// Formats and writes to the given file. void prettyPrint(char const *source, FILE *f); /// Formats and appends to the given string. void prettyPrint(char const *source, std::string &buffer); } #endif
true
efc6774cfc19e927e8c25a0007568c02acde3bd3
C++
Aryan1310/Cpp
/Assignment 2/Ganesha'sPattern.cpp
UTF-8
885
2.953125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void swastika(int row) { for (int i = 0; i < row; i++) { for (int j = 0; j < row; j++) { if (i < row / 2) { if (j < row / 2) { if (j == 0) cout <<"*"; else cout <<" "; } else if (j == row / 2) cout <<"*"; else { if (i == 0) cout <<"*"; } } else if (i == row / 2) cout <<"*"; else { if (j == row / 2 || j == row - 1) cout <<"*"; else if (i == row - 1) { if (j <= row / 2 || j == row - 1) cout <<"*"; else cout <<" "; } else cout <<" "; } } cout <<endl; } } int main() { int row; cin>>row; swastika(row); return 0; }
true
a0eb67493331235cd787aad924502d15ae9b4a8d
C++
Ido25/AlgoProj
/DataStructers/Queue.h
UTF-8
1,128
3.734375
4
[]
no_license
/* * This is the Queue . * It's implemented with a 2-way linked list of vertexes. * */ #pragma once #include "Vertex.h" class Queue{ public: //////////////////CONSTRUCTORS////////////////// Queue() : _size(0), _head(nullptr), _tail(nullptr){};//Basic constructor for uninitialized vertexes Queue(Queue &Q) = delete; //////////////////DESTRUCTOR////////////////// ~Queue(); //////////////////METHODS////////////////// void enqueue(int v);//this func gets a number, allocates a vertex with the number and inserts it to the queue int dequeue();//this func returns the data of the queue's head, deletes the queue head and replaces it with the one before him int fornt(){ return this->_head->data(); };//this func returns the queue's head data int back(){ return this->_tail->data(); };//this func returns the queue's tail data int size(){ return this->_size; };//this func returns the queue's size bool isEmpty(){ return this->size() == 0; };//this func returns whether the queue is empty or not void makeEmpty(){ delete this; };//this func deletes the queue private: int _size; Vertex *_head, *_tail; };
true
194b33df4120c5acb44440239eec5305e2826bf3
C++
00mjk/UVa-Online-Judge
/369.cpp
UTF-8
755
3.046875
3
[ "MIT" ]
permissive
#include <cstdio> using namespace std; long gcd(long A, long B) { if (A % B == 0) return B; return gcd(B, A % B); } void Divbygcd(long& A, long& B) { long g = gcd(A, B); A /= g; B /= g; } long C(long N, long K) { long num = 1, den = 1, toMul, toDiv; if (K > N/2) K = N - K; for (int i = K; i; i--) { toMul = N - K + i; toDiv = i; Divbygcd(toMul, toDiv); Divbygcd(toMul, den); Divbygcd(toDiv, num); num *= toMul; den *= toDiv; } return num / den; } int main() { while (true) { long N, M; scanf("%ld%ld", &N, &M); if (!N && !M) break; printf("%ld things taken %ld at a time is %ld exactly.\n", N, M, C(N, M)); } }
true
1a8add1ce99b9902c1d8c04c5efaa0a231fef673
C++
tytell/ForceFeedback
/teensy_timer/teensy_timer.ino
UTF-8
968
3.0625
3
[]
no_license
// Create an IntervalTimer object IntervalTimer myTimer; const int ledPin = LED_BUILTIN; // the pin with a LED void setup() { pinMode(A21, OUTPUT); analogWriteResolution(10); Serial.begin(9600); myTimer.begin(pulse, 100); // 1000 us } // The interrupt will blink the LED, and keep // track of how many times it has blinked. int onState = 0; int onVal = 0; int onDir = 1; volatile unsigned long blinkCount = 0; // use volatile for shared variables // functions called by IntervalTimer should be short, run as quickly as // possible, and should avoid calling other functions if possible. void pulse() { if (onVal == 1023) { onDir = -1; } else if (onVal == 0) { onDir = 1; } if (onState == 0) { analogWrite(A21, onVal); onVal = onVal + onDir; onState = 1; } else { analogWrite(A21, 0); onState = 0; } } // The main program will print the blink count // to the Arduino Serial Monitor void loop() { delay(100); }
true
ea25a0f99337caa012925e2d86690f73dd945727
C++
jtb/RIVALS
/Utils/interval.h
UTF-8
2,000
2.5625
3
[]
no_license
/* * Copyright 2010 Justin T. Brown * All Rights Reserved * EMAIL: run.intervals@gmail.com * * This file is part of Rivals. * * Rivals 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. * * Rivals 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 Rivals. If not, see <http://www.gnu.org/licenses/>. */ #ifndef INTERVAL_H_ #define INTERVAL_H_ #include "typedef.h" namespace rivals { class Interval { public: Interval(Domain start, Domain stop, int str); Interval(); int getStrand() const; Domain getStart() const; Domain getStop() const; Domain getSubMax() const; void setInterval(Domain start, Domain stop, int str); void setStrand(int s); void setStart(Domain start); void setStop(Domain stop); void setSubMax(Domain max); Length getLength() const; bool inRange(Domain start, Domain stop); bool overlaps(const Interval & b, bool strand_specific = false); bool operator<(const Interval & b) const; void printInterval() const; private: Domain submax; // 4 bytes Domain left; // 4 bytes Domain right; // 4 bytes // total bytes = 12 bytes }; class cInterval { public: cInterval(Domain start, Domain stop, int str) : intv(start, stop, str) {} cInterval() : intv() {} bool operator<(const cInterval & b) const { if(intv.getSubMax() == b.intv.getSubMax()){ return intv < b.intv; } return intv.getSubMax() < b.intv.getSubMax(); } private: Interval intv; }; }//namespace rivals #endif
true
d7ead9c503b131bdb31679bf29e257865332a2d1
C++
kevinlq/MyQt
/LMThreadOP/workdaatathread.cpp
UTF-8
1,227
2.6875
3
[]
no_license
#include "workdaatathread.h" #include "messagequeue.h" #include <QDebug> WorkDaataThread::WorkDaataThread(QObject *parent): QThread(parent) { m_bIsRunning = false; m_pMsgQueue = NULL; } WorkDaataThread::~WorkDaataThread() { qDebug()<<"delete WorkDaataThread"; } void WorkDaataThread::startThread() { if ( !isRunning ()) { setRuningFlag (true); start (); } } void WorkDaataThread::waitForFinished() { if ( isRunning ()) { setRuningFlag (false); wait (10); } } void WorkDaataThread::setMessgQueue(MessageQueue *pMsg) { if ( pMsg != NULL ) { m_pMsgQueue = pMsg; } } void WorkDaataThread::run() { qDebug()<<"====WorkDaataThread start"; QString buffer = ""; while (getRunningFlag ()) { buffer = m_pMsgQueue->dequeue (); if ( buffer.isEmpty ()) { msleep (4); continue; } //deal with data..... emit signalMsg (buffer); } } bool WorkDaataThread::getRunningFlag() { QMutexLocker locker(&m_mutex); return m_bIsRunning; } void WorkDaataThread::setRuningFlag(bool bRun) { QMutexLocker locker(&m_mutex); m_bIsRunning = bRun; }
true
234034c6f196494581f4773c923e6fe3b089bedc
C++
Viktor-Sok/Coursera-Cpp
/Red_belt_approx/my_Yangle/sync.h
UTF-8
1,143
2.78125
3
[]
no_license
#pragma once #include <future> #include <mutex> #include <unordered_map> #include <vector> #include <utility> #include <cstdint> #include <algorithm> using namespace std; auto Lock(mutex& m); using Hitcounts = pair<vector<uint16_t>, unordered_map<uint16_t, uint16_t>>; struct Access { lock_guard<mutex> guard; Hitcounts& ref_to_value; Access(const string& key, pair<mutex, unordered_map<string, Hitcounts>>& bucket_content); }; class SyncIndex { public: explicit SyncIndex(); Access operator[](const string& key); unordered_map<string, Hitcounts> BuildOrdinaryMap(); bool Find(const string& word) const; void FillHitcount(); private: vector<pair<mutex, unordered_map<string, Hitcounts>>> data; }; template <typename T> class Synchronized { public: explicit Synchronized(T initial = T()) : value(move(initial)) { } struct Access { T& ref_to_value; lock_guard<mutex> guard; }; Access GetAccess() { return {lock_guard(m), value}; } private: T value; mutex m; };
true
e05979ec932afc69db7687313fa99cb04b30f85b
C++
hello-sources/Coding-Training
/NowCoder/NC69链表中倒数最后k个节点.cpp
UTF-8
725
3.359375
3
[]
no_license
/** * struct ListNode { * int val; * struct ListNode *next; * }; * * C语言声明定义全局变量请加上static,防止重复定义 */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead ListNode类 * @param k int整型 * @return ListNode类 */ struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) { // write code here struct ListNode *p = pHead, *q = pHead; int cnt = 0; while (p) { cnt++; p = p->next; } if (cnt < k) return NULL; p = pHead; for (int i = 0; i < k; i++) q = q->next; while (q) { q = q->next; p = p->next; } return p; }
true
5ca12e55458d2f8ab855d0e9c69de35f898ec438
C++
NQNStudios/ASCIILib
/ASCIILib/PixelFont.h
UTF-8
1,145
2.8125
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <map> using namespace std; #include "unicode/utypes.h" #include "Color.h" using namespace ascii; #include "SDL.h" namespace ascii { // Represents a font defined inside a uniformly grid-based texture sheet. class PixelFont { public: // Create and load a pixel font PixelFont(int charWidth, int charHeight, string fontLayoutFile, string textureSheet); void Initialize(SDL_Renderer* pRenderer); void Dispose(); ~PixelFont(); // Draw the given character at the point given in pixels using the // given renderer void RenderCharacter(UChar character, int x, int y, Color color); int charHeight() { return mCharHeight; } private: SDL_Renderer* mpRenderer; SDL_Texture* mpTextureSheet; map<UChar, SDL_Rect> mCharacterRectangles; int mCharWidth; int mCharHeight; string mFontLayoutPath; string mFontPath; bool mInitialized; }; }
true
fce872d30d4af1a420675887284c2488d1cc3c2c
C++
Ian-peace/Pet_shop
/User_system.h
GB18030
4,390
2.984375
3
[]
no_license
#ifndef USER_SYSTEM_H_INCLUDED #define USER_SYSTEM_H_INCLUDED using namespace std; class User //û { private: int id, pet_id; string name, tel; char sex; public: User(string n, char s, int petid, int id_flag, string t); //캯 int get_id(); int get_pet_id(); string get_tel(); string get_name(); char get_sex(); }; User::User(string n, char s, int petid, int id_flag, string t) //幹캯 { name = n; sex = s; pet_id = petid; id = id_flag + 1; tel = t; } int User::get_id() { return id; } int User::get_pet_id() { return pet_id; } char User::get_sex() { return sex; } string User::get_name() { return name; } string User::get_tel() { return tel; } class member:public User { private: int leaguer_grade; public: member(string n, char s, int petid, int id_flag, string t, int l) : User(n,s,petid,id_flag,t) { leaguer_grade = l; } int display(); }; int member::display() { return leaguer_grade; } string na, tele; char se; int petid, l; void User_add() //ûϢ { cout << "û"; cin >> na; cout << "ûԱ(f/m)"; cin >> se; while(se != 'f' && se != 'm'){ cout << "ûԱ"; cin >> se; } cout << "ûϵ绰"; cin >> tele; cout << "ûID"; cin >> petid; cout << "ûԱ"; cin >> l; } void User_list() //ûϢ { system("cls"); int len = CountLines("User.txt"); for(int i = 1; i <= len; i++){ cout << ReadLine("User.txt", i) << endl; } } void User_delete() //ɾûϢ { User_list(); int Userid, le; le = CountLines("User.txt"); cout << "\nҪɾû(0<n<=" << le << ")(-1һ˵)"; cin >> Userid; if(Userid == -1) return; while(Userid <= 0 || Userid > le){ cout << "Χ룺"; cin >> Userid; if(Userid == -1) return; } DeleteLine("User.txt", Userid); } void user_sys() //ûϵͳ { int t; Menu_user(); int f = 0, ff = 1; cout << "ѡ"; while(cin >> t){ switch(t){ case(1): { string line; char str[1000]; int id_flag, j = 0; //ûid line = ReadLine("User.txt", CountLines("User.txt")); if(CountLines("User.txt") == 0) id_flag = 0; else{ for(int i = 0; i < line.length(); i++){ if(line[i] == '\t') break; else if(line[i] >= '0' && line[i] <= '9') str[j++] = line[i]; } id_flag = atoi(str); //ȡûid } User_add(); member User(na, se, petid, id_flag, tele, l); //û ofstream fout("User.txt", ios::app|ios::in); //ļ if(!fout){ cout << "Cannot open output file\n"; } else{ fout << "ûţ" << User.get_id() << "\tû֣" << User.get_name() << "\tûԱ" << User.get_sex()<< "\tûţ" << User.get_pet_id() << "\tûԱ" << User.display() << endl; fout.close(); } break; } case(2): User_delete(); break; case(3): User_list(); system("pause"); break; case(0): f = 1; break; default: cout << "Ƿ룺"; ff = 0; } if(f) break; if(ff){ system("cls"); Menu_user(); cout << "ѡ"; } } } #endif // USER_SYSTEM_H_INCLUDED
true
041b52a3b68bddcd85393227f2b844cc35169301
C++
MisterCapi/Software-Engineering---design-patterns
/FactoryMethod/code/main.cpp
UTF-8
1,986
3.515625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; class GPU { public: virtual void computeSomeMatrices() = 0; }; class RTX3070 : public GPU { public: RTX3070(string name){ this->name = name; } void computeSomeMatrices(){ cout << name << " is computing matrices\n"; } private: string name; }; class RTX3080 : public GPU { public: RTX3080(string name){ this->name = name; } void computeSomeMatrices(){ cout << name << " is computing matrices very fast\n"; } private: string name; }; class GPUProductionLine { public: virtual GPU* makeGPU() = 0; }; class RTX3080ProductionLine : public GPUProductionLine { public: GPU* makeGPU(){ cout << "RTX3080\n"; return new RTX3080("RTX3080"); } }; class RTX3070ProductionLine : public GPUProductionLine { public: GPU* makeGPU(){ cout << "RTX3070\n"; return new RTX3070("RTX3070"); } }; class GPUFactory { public: static GPU* makeGPU(GPUProductionLine* productionLine){ cout << "Factory is starting a production line for: "; return productionLine->makeGPU(); } }; class PC { public: PC(string name, vector<GPU*> gpus){ this->name = move(name); this->gpus = move(gpus); } void useGpusToCompute(){ cout << "PC (" << name << ") is using GPUs to compute\n"; for(unsigned int i=0; i<gpus.size(); i++){ gpus[i]->computeSomeMatrices(); } } private: string name; vector<GPU*> gpus; }; int main() { GPUProductionLine* rtx3080ProdLine = new RTX3080ProductionLine(); GPUProductionLine* rtx3070ProdLine = new RTX3070ProductionLine(); GPU* gpu1 = GPUFactory::makeGPU(rtx3080ProdLine); GPU* gpu2 = GPUFactory::makeGPU(rtx3070ProdLine); vector<GPU*> connected_gpus = {gpu1, gpu2}; PC strongPC = PC("strong_PC", connected_gpus); strongPC.useGpusToCompute(); return 0; }
true
90121b43c64522ae8447b7a511278014e805b976
C++
pragati21p/InterviewbitProgramming
/Strings/Amazing Subarrays.cpp
UTF-8
410
3.03125
3
[]
no_license
bool isVowel( char c ){ if(c=='A' || c=='E' || c=='I' || c=='O' || c=='U' || c=='a' || c=='e' || c=='i' || c=='o' || c=='u' ) return 1; return 0; } int Solution::solve(string A) { long long int count=0; for(long long int i=0;i<A.size();i++){ if( isVowel(A[i]) ){ count = (count + (A.size() - i)%10003)%10003; } } return count%10003; }
true
fc80c16e17d7dfe57adf510b89c658a3ea5478a7
C++
brokenlanceorg/owlsong
/code/cc/Miscellaneous/StockSeries.hpp
UTF-8
3,629
2.71875
3
[]
no_license
//*********************************************************************************************** // File : StockSeries.hpp // Purpose : This class derives from the DataserieS class to provide additional // : functionality such as a moving average line. // : // Author : Brandon Benham // Date : 6/18/00 //*********************************************************************************************** #ifndef __STOCKSERIES_HPP #define __STOCKSERIES_HPP #include "DataSeries.hpp" #include "SmoothedMovingAverage.hpp" #include "Mathmatc.hpp" //*********************************************************************************************** // Class : StockserieS //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Purpose : This class derives from the DataserieS class to provide additional // : functionality such as a moving average line. //*********************************************************************************************** class StockserieS : public DataserieS { public: StockserieS( long double = 0.1 ); // Default Constructor declaration StockserieS( int, long double = 0.1 ); // Constructor for persistent dataseries StockserieS( int, char*, long double = 0.1 ); // Constructor for persistent dataseries StockserieS( char*, long double, long double = 0.1 ); // Constructor for persistent dataseries ~StockserieS(); // Destructor declaration virtual void AddElement( long double ); virtual void SetSmoothingFactor( long double ldx ) { ldSmoothing_Factor = ldx; Recalculate(); } virtual void SetFirstAverage( long double ldF ) { ldFirst_Average = ldF; Recalculate(); } VectoR* GetAverages() { return vThe_Averages; } long double GetDataMaximum() { return ldData_Maximum; } long double GetDataMinimum() { return ldData_Minimum; } long double GetSMAMaximum() { return ldSMA_Maximum; } long double GetSMAMinimum() { return ldSMA_Minimum; } long double Compare( VectoR* ); virtual long double GetLastAverage() { return vThe_Averages->pVariables[vThe_Averages->cnRows-1]; } virtual long double GetFirstAverage() { return vThe_Averages->pVariables[ 0 ]; } virtual StockserieS* Peel( int ); virtual inline char* GetName() { return DataserieS::GetName(); } virtual inline void SetName( char* pc ) { DataserieS::SetName( pc ); } virtual inline int GetID() { return iObjectID; } virtual inline void SetID( int id ) { iObjectID = id; } virtual inline char* GetSuffix() { return pcSuffix; } virtual inline void SetSuffix( char* ); virtual inline void GenerateFileName(); virtual inline int GetNumberOfElements(); void SetTransient( bool bT = true ) { DataserieS::SetTransient( bT ); } protected: void Setup(); void Recalculate(); void CalculateMax(); void CalculateMin(); char* MakeFileName( int ); char* MakeFileName( int, char* ); private: SmoothedMovingAveragE* theMoving_Average_Calculator; VectoR* vThe_Averages; FunctioN* Fthe_Function; long double ldFirst_Average; long double ldSmoothing_Factor; long double ldData_Minimum; long double ldData_Maximum; long double ldSMA_Minimum; long double ldSMA_Maximum; int iObjectID; char* pcSuffix; }; // end StockserieS declaration #endif
true
e14db3828c3f8057489549229962896f946bced1
C++
SayaUrobuchi/uvachan
/TNFSH_OJ/629.cpp
UTF-8
675
2.6875
3
[]
no_license
#include <iostream> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, i, cmd, t, u; int a[4], b[4]; string s; while (cin >> n) { a[1] = a[2] = 1; b[1] = b[2] = 0; for (i=0; i<n; i++) { cin >> cmd; if (cmd == 1) { cin >> t; cout << max(a[1]*t+b[1], a[2]*t+b[2]) << "\n"; } else if (cmd == 2) { cin >> t >> s >> u; if (s[0] == '+') { b[t] += u; } else { a[t] *= u; b[t] *= u; } } else { t = a[1]-a[2]; u = b[2]-b[1]; if (t == 0 || u % t) { cout << "no\n"; } else { cout << u/t << "\n"; } } } } return 0; }
true
f53fcd8d6ee97085b3f2f7c0ec95e71a180e89df
C++
AzamAzam/OOPLabsAssignments
/lab10/lab10/Q5.cpp
UTF-8
1,790
3.15625
3
[]
no_license
//#include <iostream> //#include<string> //#include <fstream> //using namespace std; // //struct Division //{ // string name; // double sales[4]; //}; // // // //int main(){ // Division d[4]; // fstream file; // int i = 0; // double totalQuarterSales[4] = { 0 }; // double totalDivisionSales[4] = { 0 }; // double totalSale=0; // double avgSaleForDivision[4] = { 0 }; // int highQuarter, lowQuarter; // // file.open("Sales.txt", ios::in); // while (i<4) // { // // file >> d[i].name; // // cout << d[i].name << endl; // for (int j = 0; j < 4; j++){ // file >> d[i].sales[j]; // totalDivisionSales[i] += d[i].sales[j]; // // cout << d[i].sales[j]<<" "; // // // // // // } // avgSaleForDivision[i] = totalDivisionSales[i] / 4; // i++; // cout << endl; // // } //// calculet total quarteer sales high and low // // highQuarter = 0; // lowQuarter = 0; // for (int i = 0; i < 4; i++){ // for (int j = 0; j < 4; j++){ // totalQuarterSales[i] += d[j].sales[i]; // } // // // totalSale += totalQuarterSales[i]; // if (totalQuarterSales[i] < totalQuarterSales[lowQuarter]) // lowQuarter = i; // if (totalQuarterSales[i]>totalQuarterSales[highQuarter]) // highQuarter = i; // } // // //cout << highQuarter+1 << " " << lowQuarter+1; // // for (int i = 0; i < 4; i++){ // cout << "Total Corporate sale for Quarter " << i + 1 << " : " << totalQuarterSales[i] << endl; // }for (int i = 0; i < 4; i++){ // cout << "total sale for Division " << d[i].name << " : " << totalDivisionSales[i] << endl; // }for (int i = 0; i < 4; i++){ // cout << "Average sale for Division " << d[i].name << " : " << totalDivisionSales[i] / 4 << endl; // // // // } // cout << "Highest Quarter " << highQuarter+1 << endl; // cout << "Lowest Quarter " << lowQuarter + 1 << endl; // // //} //
true
3a48b5aa2d5fb9e4f0e75f867644bd734447f751
C++
vignura/Code-Files
/BasicC++/LCM.cpp
UTF-8
617
3.171875
3
[]
no_license
#include<iostream> using namespace std; int main() { int a,b; int getLCM(int, int); cout<<"LCM Finder"<<endl; cout<<"Enter two numbers: "; cin>>a>>b; cout<<"LCM ("<<a<<", "<<b<<") = "<<getLCM(a,b)<<endl; return 0; return 0; } int getLCM(int a, int b) { int LCM,HCF; int getHCF(int,int); HCF = getHCF(a,b); cout<<"HCF ("<<a<<", "<<b<<") = "<<getHCF(a,b)<<endl; LCM = (a / HCF) * b; return LCM; } //HCF Finding Function int getHCF(int a, int b) { int num,div,rem; if(a < b){ div = a; num = b; } else{ div = b; num = a; } do{ rem = num % div; if(rem != 0){ num = div; div = rem; } }while(rem != 0); return div; }
true
6fe9ede8be8896648a21a179b361234b947fb779
C++
Shivam-Vishwakarma/CPP
/structure/STUDENT.BAK
UTF-8
1,073
3.328125
3
[]
no_license
#include<iostream.h> #include<conio.h> #include<stdio.h> #include<stdlib.h> struct student { char name[30]; int rno; int per; public: void getinfo(); void showinfo(); }; void student::getinfo() { clrscr(); cout<<"=============================================================="; cout<<"\n Enter your name : "; gets(name); cout<<"\n Enter your rno :"; cin>>rno; cout<<"\n Enter percentage : "; cin>>per; } void student::showinfo() { cout<<"\t"<<name<<"\t"<<rno<<"\t"<<per<<endl; } void main() { int ch; student o[10]; int n=-1; while (1) { clrscr(); cout<<endl<<"1. Add new student "; cout<<endl<<"2. Display all students "; cout<<endl<<"3. exit"; cout<<"\n enter choice : "; cin>>ch; switch (ch) { case 3: exit(0); case 2: { clrscr(); cout<<"==============================================="<<endl; cout<<"\tname\trno\tpercentage"<<endl; for(int i=0;i<=n;i++) o[i].showinfo(); getch(); } break; case 1: { n++; o[n].getinfo(); getch(); } break; default : cout<<"\n Wrong Choice !!!";getch();break; } } }
true
fe6762d50bbb8ff0dbe98a1c62fac331db6a4c27
C++
tst-ccamp/earthenterprise
/earth_enterprise/src/fusion/portableglobe/cutspec.cpp
UTF-8
10,056
2.796875
3
[ "Apache-2.0" ]
permissive
// Copyright 2017 Google Inc. // Copyright 2020 The Open GEE Contributors // // 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. // Classes for specifying the part of the quadtree for which data should // be kept during a cut. Other than the coarse level thresholds, this is // done by building a simple quadtree whose leaves indicate that the node // each leaf represents should be kept, as should all of the nodes that // are descendents of this node in the full quadtree (assuming they // don't violate those coarse thresholds mentioned above). #include "fusion/portableglobe/cutspec.h" #include <fstream> // NOLINT(readability/streams) #include <iostream> // NOLINT(readability/streams) #include "common/notify.h" namespace fusion_portableglobe { /** * Constructor. If this is the last node in the path, mark it as * a leaf. Otherwise, recursively call the constructor to make * the next node in the path. */ HiresNode::HiresNode(std::string path) { if (path.empty()) { is_leaf = true; } else { is_leaf = false; AddChild(path[0], new HiresNode(path.substr(1))); } } /** * Destructor. Recursively deletes all children. */ HiresNode::~HiresNode() { if (!IsLeaf()) { if (children.size() == 0) { return; } for (int i = 0; i < 4; ++i) { if (children[i] != NULL) { delete children[i]; } } } } /** * Returns pointer to child node for the given char * or returns NULL if there is no such child. The * node_num char shoud be '0', '1', '2' or '3'. */ HiresNode* const HiresNode::GetChild(char node_num) const { size_t idx = GetChildIndex(node_num); if (idx < children.size()) return children[idx]; return NULL; } /** * Adds given node as a child in the position specified by * node_num. The node_num char shoud be '0', '1', '2' or '3'. */ void HiresNode::AddChild(char node_num, HiresNode* child) { if (children.size() < 4) { children.resize(4); } children[GetChildIndex(node_num)] = child; } /** * Debugging routine that recursively shows which nodes are * in a tree. */ void HiresNode::Show(const std::string& address) const { if (IsLeaf()) { std::cout << "f"; } if (children.size() == 0) { std::cout << "L"; return; } for (int i = 0; i < 4; ++i) { std::string new_address = address; if (children[i] != NULL) { std::cout << std::endl << address << i; switch (i) { case 0: new_address += "0"; break; case 1: new_address += "1"; break; case 2: new_address += "2"; break; case 3: new_address += "3"; break; } children[i]->Show(new_address); } } } /** * Recursively checks if path is in the tree starting with * this node as the root. * TODO: Consider eliminating this method and just * TODO: calculating this iteratively in the tree method. * * @return whether this path is in the tree. */ bool HiresNode::IsTreePath(const std::string& path) const { // If path is empty, we have a match. if (path.empty()) { return true; } // If we are at a leaf, everything below is a match. if (is_leaf) { return true; } // See if we can match child for next node in path. const HiresNode* child = GetChild(path[0]); if (child != NULL) { return child->IsTreePath(path.substr(1)); } // If not, the path is not in the tree. return false; } size_t HiresNode::GetChildIndex(char node_num) const { return (size_t) node_num - ZERO_CHAR; } /** * Adds node(s) for the given path that are not already in the tree. * Used for "strict" trees where every node must be explicitly * included. */ void HiresTree::AddNode(const std::string& path) { HiresNode* node = tree_; // Go until we find nodes that haven't been created yet. for (size_t i = 0; i < path.size(); ++i) { HiresNode* child_node = node->GetChild(path[i]); if (child_node == NULL) { // Add remaining needed nodes to the tree. node->SetLeaf(false); node->AddChild(path[i], new HiresNode(path.substr(i + 1))); return; } // Keep descending through the existing tree nodes. node = child_node; } notify(NFY_DEBUG, "%s node already in place.", path.c_str()); } /** * Adds node(s) for the specified path. If an ancestor path is already in the * tree, the node is ignored since all descendents are already assumed. * For the polygon to qt node algorithm, this would be unexpected because * it tries not to pass any redundant information. * Used for "encompassing" trees where any node that is a descendent of * a leaf in the tree is considered to be included by the tree. */ void HiresTree::AddHiResQtNode(HiresNode* node, const std::string& path) { // Go until we find nodes that haven't been created yet. for (size_t i = 0; i < path.size(); ++i) { if (node->IsLeaf()) { notify(NFY_WARN, "Lower-level parent node already in place."); return; } HiresNode* child_node = node->GetChild(path[i]); if (child_node == NULL) { // Add remaining needed nodes to the tree. node->AddChild(path[i], new HiresNode(path.substr(i + 1))); return; } // Keep descending through the existing tree nodes. node = child_node; } node->SetLeaf(true); notify(NFY_WARN, "%s node already in place, may be losing specificity.", path.c_str()); } void HiresTree::LoadHiResQtNodeFile(const std::string& file_name) { std::ifstream fin(file_name.c_str()); LoadHiResQtNodes(&fin); } /** * Load quadtree node paths into tree structure so we can quick check if a * quadtree node is a leaf in the tree or is a child of a leaf in the tree. * We don't care about the ordering of the leaves in this stream, the * same tree should be built independent of the order if all are leaves. * TODO: Use QuadTreePath instead of std::string. */ void HiresTree::LoadHiResQtNodes(std::istream* fin) { std::string next_node_path; while (!fin->eof()) { next_node_path = ""; *fin >> next_node_path; if (!next_node_path.empty()) { AddHiResQtNode(tree_, next_node_path); } } } bool HiresTree::IsTreePath(const std::string& path) const { return TestTreePath(path, true); } bool HiresTree::IsInTree(const std::string& path) const { return TestTreePath(path, false); } bool HiresTree::TestTreePath( const std::string& path, bool includeLeafDescendents) const { HiresNode* node = tree_; std::string remaining_path = path; while (true) { // If path is empty, we have a match. if (remaining_path.empty()) { return true; } // If we are at a leaf, everything below is a match. if (node->IsLeaf()) { if (includeLeafDescendents) { return true; } else { return true; } } // See if we can match child for next node in path. node = node->GetChild(remaining_path[0]); if (node == NULL) { return false; } // So far so good: keep going. remaining_path = remaining_path.substr(1); } } void HiresTree::Show() const { tree_->Show(""); std::cout << std::endl; } /** * Constructor. Builds acceptance tree from quadtree node file and * stores cut limits. */ CutSpec::CutSpec(const std::string& qt_node_file_name, std::uint16_t min_level, std::uint16_t default_level, std::uint16_t max_level) : min_level_(min_level), default_level_(default_level), max_level_(max_level), is_exclusion_enabled_(false) { hires_tree_.LoadHiResQtNodeFile(qt_node_file_name); } /** * Constructor. Builds acceptance tree from quadtree one node file and * an exclusion tree from another. Exclusion trumps acceptance. * Also stores cut limits. */ CutSpec::CutSpec(const std::string& qt_node_file_name, const std::string& exclusion_qt_node_file_name, std::uint16_t min_level, std::uint16_t default_level, std::uint16_t max_level) : min_level_(min_level), default_level_(default_level), max_level_(max_level), is_exclusion_enabled_(true) { hires_tree_.LoadHiResQtNodeFile(qt_node_file_name); exclusion_tree_.LoadHiResQtNodeFile(exclusion_qt_node_file_name); } /** * Returns whether the given quadtree node should be kept (i.e. not pruned). * If the node is at or below (lower resolution) the default level or if * it is in the specified high-resolution nodes, then it should not be * pruned. */ bool CutSpec::KeepNode(const std::string& qtpath) const { std::uint16_t level = qtpath.size(); // If we are below the min level, keep nothing. if (level < min_level_) { return true; } // If we are at or below the default level, keep everything. if (level <= default_level_) { return true; } // If we are above the max level, keep nothing. if (level > max_level_) { return false; } // Check the quadtree path to see if it is one we are keeping. return hires_tree_.IsTreePath(qtpath); } /** * Returns whether data in the given quadtree node should be excluded. */ bool CutSpec::ExcludeNode(const std::string& qtpath) const { if (!is_exclusion_enabled_) { return false; } // If we are at or below the default level, do not exclude. if (qtpath.size() <= default_level_) { return false; } // Check the quadtree path to see if it is one we are excluding. return exclusion_tree_.IsTreePath(qtpath); } } // namespace fusion_portableglobe
true
b3e5471afe876941262d66bff37c686e1751e982
C++
Edwin254-byte/cpp_practise
/constructor-functions.cpp
UTF-8
1,239
4.28125
4
[]
no_license
//special function that is called whenever we create a new object. It is defined in the class block #include <iostream> using namespace std; class Student { public: string name, course, adm_no; int age; Student(string aName, string aCourse, string aAdm_No, int aAge) { name = aName; course = aCourse; adm_no = aAdm_No; age = aAge; } Student() { name = "no name"; course = "not given"; adm_no = "unknown"; age = 0; } //this constructor with no parameters acts as an error handler whenever the user fails to enter the object details }; int main() { Student std1("Peter", "Computer Science", "COM/1234/10", 18); Student std2("Bill", "Education Arts", "EA/2342/21", 20); //creating an object and its attribute using function constructor Student std3; // the constructor with no attribute will be called cout << std1.name <<"\t" << std1.course << "\t" << std1.adm_no << "\t" << std1.age <<endl; cout << std2.name << "\t" << std2.course << "\t" << std2.adm_no << "\t" << std2.age <<endl; cout << std3.name; // uses the error handler function constructor return 0; }
true
b1598a5d41b17ff508eb0671b999104c226e171d
C++
Becavalier/playground-cpp
/primer-answer/chapter10/10.36.cc
UTF-8
238
2.578125
3
[ "MIT" ]
permissive
#include <iostream> #include <list> #include <algorithm> using namespace std; int main (int argc, char **argv) { list<int> l{0, 1, 2, 3, 4, 0, 1}; auto e = find(l.rbegin(), l.rend(), 0); cout << *e << endl; return 0; }
true
959fdba60a9713c8a5ab42183453d23f1e81dd91
C++
Krandelbord/gettext_translator
/Utils.cc
UTF-8
1,437
2.875
3
[]
no_license
#include "Utils.h" #include <aspell.h> #include <vector> std::vector<Glib::ustring> getDictionaryList() { std::vector<Glib::ustring> list; struct AspellConfig *a_config = new_aspell_config(); AspellDictInfoList *dlist = get_aspell_dict_info_list(a_config); AspellDictInfoEnumeration *dels = aspell_dict_info_list_elements(dlist); const AspellDictInfo *entry; while ( (entry = aspell_dict_info_enumeration_next(dels)) != 0) { list.push_back(entry->name); } return list; } void replaceAll(Glib::ustring &string, const Glib::ustring &search, const Glib::ustring &sub) { Glib::ustring::size_type found_pos = string.find(search); while (found_pos!=Glib::ustring::npos) { Glib::ustring::size_type search_start = found_pos+sub.length(); string.replace(found_pos, search.length(), sub); found_pos = string.find(search, search_start); } } Glib::ustring replaceAllReturn(const Glib::ustring &string, const Glib::ustring &search, const Glib::ustring &sub) { Glib::ustring retval(string); replaceAll(retval, search, sub); return retval; } bool compare(const Glib::ustring &str1, const Glib::ustring &str2) { if (str1.find(str2)!=Glib::ustring::npos) return true; return false; } bool IcaseCompare(const Glib::ustring &str1, const Glib::ustring &str2) { Glib::ustring u_str1 = str1.lowercase(); Glib::ustring u_str2 = str2.lowercase(); if (u_str1.find(u_str2)!=Glib::ustring::npos) return true; return false; }
true
675c591ff75e98fa2181378cb6370f3ddf07e921
C++
jacquerie/leetcode
/leetcode/0926_flip_string_to_monotone_increasing.cpp
UTF-8
808
2.984375
3
[ "MIT" ]
permissive
// Copyright (c) 2018 Jacopo Notarstefano #include <algorithm> #include <cassert> #include <string> using namespace std; class Solution { public: int minFlipsMonoIncr(string S) { int ones_count = 0, result = 0; for (const auto& c : S) { if (c == '0' && ones_count == 0) { continue; } else if (c == '0') { result++; } else { ones_count++; } result = min(result, ones_count); } return result; } }; int main() { auto solution = Solution(); assert(1 == solution.minFlipsMonoIncr("00110")); assert(2 == solution.minFlipsMonoIncr("010110")); assert(2 == solution.minFlipsMonoIncr("00011000")); assert(3 == solution.minFlipsMonoIncr("0101100011")); }
true
82d94322e1dcba46fb2532e5f03c47d29f6eab60
C++
alexandraback/datacollection
/solutions_5631989306621952_1/C++/btzy/A.cpp
UTF-8
502
2.796875
3
[]
no_license
#include<iostream> #include<string> using namespace std; int t; string curr,inp; int main(){ cin>>t; for(int c=1;c<=t;++c){ cin>>inp; curr=""; for(int i=0;i<inp.size();++i){ string first=curr+inp[i]; string second=inp[i]+curr; if(first<second){ curr=second; } else{ curr=first; } } cout<<"Case #"<<c<<": "<<curr<<endl; } }
true