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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
217db0aeb2febeda11d84f7a4e912efcebaaf26b | C++ | YegangWu/Alogirthms | /kd-tree/rectangle.h | UTF-8 | 404 | 2.59375 | 3 | [] | no_license | #ifndef INCLUDE_RECTANGLE_H
#define INCLUDE_RECTANGLE_H
#include "kd_tree.h"
struct Node;
class Rectangle
{
public:
Rectangle(double xLow, double yLow, double xHigh, double yHigh);
bool less(Node& node) const;
bool greater(Node& node) const;
bool inbetween(Node& node) const;
bool contain(Node& node) const;
private:
double xLow;
double yLow;
double xHigh;
double yHigh;
};
#endif
| true |
ca725a3549c49414bb7af357c277285e5e360b37 | C++ | kmcnelly/TicTacToe-Gomoku-GameBoard | /TicTacToe.h | UTF-8 | 966 | 2.859375 | 3 | [] | no_license | // TicTacToe.h : Declares TicTaceToeGame class w/ methods and instances. Also, overloaded <<
#pragma once
//link other files
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include "Base.h"
using namespace std;
class TicTacToeGame: public GameBase {
private:
enum board {
max_height = 5, max_width = 5,
board_height = 3, board_width = 3,
xCorner = 0, yCorner = 0,
xStart = xCorner + 1, yStart = yCorner + 1,
winLength = 5,
};
// const unsigned int height = max_height;
// const unsigned int width = max_width;
// bool turnFirst;
// string firstLog;
// string secondLog;
//
// vector<game_piece> pieceBoard;
public:
TicTacToeGame();
//overrides of Gamebase's
virtual void print();
virtual bool done();
virtual bool draw();
virtual int turn();
friend ostream & operator<< (ostream &, const TicTacToeGame &);
};
//overload to print TicTacToeGame
ostream & operator<< (ostream &, const TicTacToeGame &); | true |
2082107b8556e71af42e12b1ba91f9273e165ae8 | C++ | timepp/superword | /SuperWord/Word.h | GB18030 | 5,790 | 2.84375 | 3 | [] | no_license | // Word.h: interface for the CWord class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_WORD_H__F479280B_4102_4280_8D54_469EDEE875F6__INCLUDED_)
#define AFX_WORD_H__F479280B_4102_4280_8D54_469EDEE875F6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include "DetailMeaning.h"
#ifndef interface
#define interface struct
#endif
typedef unsigned int uint32_t;
namespace word
{
// -----------------------------------------------------------------------
// ʽӿ
interface Word
{
public:
virtual ~Word(){}
virtual const char * word() const = 0;
virtual const char * phonetic() const = 0;
virtual const char * meaning() const = 0;
virtual const char * detail_meaning() const = 0;
virtual WORD type() const = 0;
virtual time_t access_time() const = 0;
virtual bool set_word(const char * w) = 0;
virtual bool set_phonetic(const char * p) = 0;
virtual bool set_meaning(const char * m) = 0;
virtual bool set_type(WORD tp) = 0;
virtual bool set_access_time(time_t tm) = 0;
protected:
static CDetailMeaning m_dm;
};
typedef std::vector<Word *> WordVector;
std::ostream & operator << (std::ostream& os, const Word* pW);
bool word_less(const Word * pW1, const Word * pW2);
bool word_greater(const Word * pW1, const Word * pW2);
// -----------------------------------------------------------------------
// NullWord, ʵһΪյĵ
class NullWord : public Word
{
public:
virtual const char * word() const;
virtual const char * phonetic() const;
virtual const char * meaning() const;
virtual const char * detail_meaning() const;
virtual WORD type() const;
virtual time_t access_time() const;
virtual bool set_word(const char * w) { return false; };
virtual bool set_phonetic(const char * p) { return false; };
virtual bool set_meaning(const char * m) { return false; };
virtual bool set_type(WORD tp) { return false; };
virtual bool set_access_time(time_t tm) { return false; };
private:
static const char s_empty[];
};
// -----------------------------------------------------------------------
// FixedWord, ڲֻ洢һŵݵĻɴ˵ַת
class FixedWord : public Word
{
friend class FixedWordsCreator;
public:
FixedWord(const FixedWord& fw);
~FixedWord();
virtual const char * word() const;
virtual const char * phonetic() const;
virtual const char * meaning() const;
virtual const char * detail_meaning() const;
virtual WORD type() const;
virtual time_t access_time() const;
virtual bool set_word(const char * w) { return false; }
virtual bool set_phonetic(const char * p){ return false; }
virtual bool set_meaning(const char * m){ return false; }
virtual bool set_type(WORD tp);
virtual bool set_access_time(time_t tm);
private:
// ŵʵĻ
char * m_buf;
FixedWord();
// صռõĻС
inline size_t size() const;
};
// -----------------------------------------------------------------------
// UserWord
class UserWord : public Word
{
public:
UserWord();
UserWord(const UserWord& fw);
~UserWord();
virtual inline const char * word() const { return m_word.c_str(); }
virtual inline const char * phonetic() const { return m_phonetic.c_str(); }
virtual inline const char * meaning() const { return m_meaning.c_str(); }
virtual inline const char * detail_meaning() const { return meaning(); }
virtual inline WORD type() const { return m_type; }
virtual inline time_t access_time() const { return m_access_time; }
virtual inline bool set_type(WORD tp) { m_type = tp; return true; }
virtual inline bool set_access_time(time_t tm) { m_access_time = tm; return true; }
virtual bool set_word(const char * w) { m_word = w; return true; }
virtual bool set_phonetic(const char * p) { m_phonetic = p; return true; }
virtual bool set_meaning(const char * m) { m_meaning = m; return true; }
public:
bool operator < (const UserWord& uw);
private:
std::string m_word;
std::string m_meaning;
std::string m_phonetic;
WORD m_type;
time_t m_access_time;
};
std::istream& operator >> (std::istream& is, UserWord& uw);
// -----------------------------------------------------------------------
// FixedWordCreatorװ˼غͷõʵIJsingletonģʽʵ
// ͨڴӳļķѵʿֱӼص̵ĵַռ
// ʹ÷
#if 0
vector<Word *> vw;
FixedWordsCreator *pCreator = FixedWordsCreator::Instance();
pCreator->GetWords(vw);
// vwйе
#endif
class WordsCreator
{
};
class FixedWordsCreator : public WordsCreator
{
public:
~FixedWordsCreator();
static FixedWordsCreator* Instance();
virtual const WordVector * GetWords() const;
private:
FixedWordsCreator();
LPVOID m_pMappedAddr; // ļӳĻַ
FixedWord *m_arrWord; // Сʡ
WordVector m_vpWord; // ظġָ롱
};
class UserWordsCreator : public WordsCreator
{
public:
~UserWordsCreator();
static UserWordsCreator* Instance();
virtual WordVector * GetWords();
private:
UserWordsCreator();
DWORD m_dwOriginalCount; // userword.datеĵʸ
UserWord *m_arrWord; // Сʽṹvector
WordVector m_vpWord; // ظġָ롱
};
};
#endif // !defined(AFX_WORD_H__F479280B_4102_4280_8D54_469EDEE875F6__INCLUDED_)
| true |
eb8d9bf9526445d7c290fa41eccf18e40361f0ea | C++ | shnoh171/problem-solving | /backjoon-online-judge/1074-z/z.cpp | UTF-8 | 711 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
// https://www.acmicpc.net/problem/1074
int NthVisit(int n, int r, int c);
int main()
{
ios_base::sync_with_stdio(false);
int n, r, c;
cin >> n >> r >> c;
cout << NthVisit(n, r, c) << "\n";
return 0;
}
int NthVisit(int n, int r, int c) {
if (n == 0) return 0;
if (r < (1 << n-1) && c < (1 << n-1))
return NthVisit(n-1, r, c);
else if (r < (1 << n-1) && c >= (1 << n-1))
return (1 << n-1) * (1 << n-1) + NthVisit(n-1, r, c - (1 << n-1));
else if (r >= (1 << n-1) && c < (1 << n-1))
return 2 * (1 << n-1) * (1 << n-1) + NthVisit(n-1, r - (1 << n-1), c);
else
return 3 * (1 << n-1) * (1 << n-1) + NthVisit(n-1, r - (1 << n-1), c - (1 << n-1));
}
| true |
bcb3e57adf45c7bcc4c75b72355262f006e73e81 | C++ | ziomal9191/git2 | /test.cpp | UTF-8 | 384 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include "add.h"
#include "multiply.h"
#include "pow.h"
void areEquals(double expected, double got){
if(expected != got){
std::cout << "Expected = " << expected << "but got value" <<
got << "\n";
}
}
int main(){
areEquals(4, pow(2.0, 2));
areEquals(4, add(2,2));
areEquals(16, multiply(4, 4));
std::cout << "End of test!" << std::endl;
return 0;
}
| true |
df70a6d78cd3f87db0272423112aa3a60bbb1026 | C++ | aamshukov/frontend | /framework/core/text.cpp | UTF-8 | 10,764 | 2.546875 | 3 | [
"MIT"
] | permissive | //..............................
// UI Lab Inc. Arthur Amshukov .
//..............................
#include <core\pch.hpp>
#include <core\noncopyable.hpp>
#include <core\domain_helper.hpp>
#include <core\status.hpp>
#include <core\logger.hpp>
#include <core\unicode.hpp>
#include <core\text.hpp>
BEGIN_NAMESPACE(core)
bool text::string_to_codepoints0(const string_type& text, std::shared_ptr<typename text::datum_type[]>& codepoints, size_type& count, operation_status& status)
{
//log_info(L"Converting string (text) to codepoints ...");
count = 0;
bool result = false;
try
{
std::size_t text_count = text.size();
const uint16_t* source_start_aux(reinterpret_cast<const uint16_t*>(text.c_str()));
const uint16_t** source_start(&source_start_aux);
const uint16_t* source_end(source_start_aux + text_count);
std::shared_ptr<datum_type[]> buffer(new datum_type[text_count + 1]);
const datum_type* target_start_aux(buffer.get());
const datum_type** target_start(&target_start_aux);
const datum_type* target_end(target_start_aux + text_count);
convert_result cr = convert_utf16_to_utf32(source_start,
source_end,
(UTF32**)target_start,
(UTF32*)target_end,
conversion_flags::strict_conversion,
count,
false);
if(cr == conversion_ok)
{
buffer[count] = 0;
codepoints.swap(buffer);
result = true;
}
else
{
if(cr == source_exhausted)
{
OPERATION_FAILED(status::custom_code::error, L"Converting string (text) to codepoints: partial character in source, but hit end.")
}
else if(cr == target_exhausted)
{
OPERATION_FAILED(status::custom_code::error, L"Converting string (text) to codepoints: insufficient room in target for conversion.")
}
else if(cr == source_illegal)
{
OPERATION_FAILED(status::custom_code::error, L"Converting string (text) to codepoints: source sequence is illegal/malformed.")
}
}
}
catch(const std::exception& ex)
{
OPERATION_FAILED_EX(ex, status::custom_code::error, L"Converting string (text) to codepoints: error occurred.")
}
//log_info(L"Converted string (text) to codepoints.");
return result;
}
bool text::codepoints_to_string0(const typename text::datum_type* codepoints, size_type count, string_type& result_text, operation_status& status)
{
//??log_info(L"Converting codepoints to string ...");
bool result = false;
try
{
const uint32_t* source_start_aux(codepoints);
const uint32_t** source_start(&source_start_aux);
const uint32_t* source_end(source_start_aux + count);
size_type string_count = (count + 1) * 2;
std::shared_ptr<uint16_t[]> buffer(new uint16_t[string_count]);
const uint16_t* target_start_aux(buffer.get());
const uint16_t** target_start(&target_start_aux);
const uint16_t* target_end(target_start_aux + string_count);
convert_result cr = convert_utf32_to_utf16(source_start,
source_end,
(UTF16**)target_start,
(UTF16*)target_end,
conversion_flags::strict_conversion);
if(cr == conversion_ok)
{
buffer[count] = 0;
result_text.assign(reinterpret_cast<char_type*>(buffer.get()));
result = true;
}
else
{
if(cr == source_exhausted)
{
OPERATION_FAILED(status::custom_code::error, L"Converting codepoints to string: partial character in source, but hit end.")
}
else if(cr == target_exhausted)
{
OPERATION_FAILED(status::custom_code::error, L"Converting codepoints to string: insufficient room in target for conversion.")
}
else if(cr == source_illegal)
{
OPERATION_FAILED(status::custom_code::error, L"Converting codepoints to string: source sequence is illegal/malformed.")
}
}
}
catch(const std::exception& ex)
{
OPERATION_FAILED_EX(ex, status::custom_code::error, L"Converting codepoints to string: error occurred.")
}
//??log_info(L"Converted codepoints to string.");
return result;
}
bool text::string_to_codepoints(const string_type& text, std::shared_ptr<typename text::datum_type[]>& codepoints, size_type& count, operation_status& status)
{
//log_info(L"Converting string (text) to codepoints ...");
count = 0;
bool result = false;
try
{
UnicodeString ustr(text.c_str());
if(!ustr.isBogus())
{
int32_t size = ustr.length() + 1;
std::shared_ptr<datum_type[]> buffer(new datum_type[size]);
UErrorCode error = U_ZERO_ERROR;
int32_t length = ustr.toUTF32(reinterpret_cast<UChar32*>(buffer.get()), static_cast<int32_t>(size), error);
if(error == U_ZERO_ERROR)
{
buffer[length] = 0;
count = length;
codepoints.swap(buffer);
result = true;
}
else
{
OPERATION_FAILED(status::custom_code::error, format(L"Converting string (text) to codepoints: ICU error code is '%d'.", error).c_str())
}
}
else
{
OPERATION_FAILED(status::custom_code::error, L"Converting string (text) to codepoints: invalid input.")
}
}
catch(const std::exception& ex)
{
OPERATION_FAILED_EX(ex, status::custom_code::error, L"Converting string (text) to codepoints: error occurred.")
}
//log_info(L"Converted string (text) to codepoints.");
return result;
}
bool text::codepoints_to_string(const typename text::datum_type* codepoints, size_type count, string_type& result_text, operation_status& status)
{
//log_info(L"Converting codepoints to string ...");
bool result = false;
try
{
UnicodeString ustr(UnicodeString::fromUTF32(reinterpret_cast<const UChar32*>(codepoints), static_cast<int32_t>(count)));
if(!ustr.isBogus())
{
int32_t size = ustr.length();
std::unique_ptr<char16_t[]> buffer(new char16_t[size + 1]);
ustr.extractBetween(0, static_cast<int32_t>(size), buffer.get(), 0);
buffer.get()[size] = 0;
result_text.assign(reinterpret_cast<const char_type*>(buffer.get()));
result = true;
}
else
{
OPERATION_FAILED(status::custom_code::error, L"Converting codepoints to string: invalid input.")
}
}
catch(const std::exception& ex)
{
OPERATION_FAILED_EX(ex, status::custom_code::error, L"Converting codepoints to string: error occurred.")
}
//log_info(L"Converted codepoints to string.");
return result;
}
string_type text::codepoint_to_string(typename text::datum_type codepoint)
{
string_type result;
if(codepoint != text::invalid_codepoint)
{
std::unique_ptr<datum_type[]> codepoints(new datum_type[1 + 1]);
codepoints[0] = codepoint;
operation_status status; //??
text::codepoints_to_string(codepoints.get(), 1, result, status);
}
else
{
result = L"INVALID_CODEPOINT";
}
return result;
}
bool text::codepoint_to_string(typename text::datum_type codepoint, string_type& result_text, operation_status& status)
{
bool result = false;
if(codepoint != text::invalid_codepoint)
{
std::unique_ptr<datum_type[]> codepoints(new datum_type[1 + 1]);
codepoints[0] = codepoint;
text::codepoints_to_string(codepoints.get(), 1, result_text, status);
}
else
{
result_text = L"INVALID_CODEPOINT";
}
return result;
}
string_type text::trim(const string_type& text, const string_type& delimiters)
{
string_type result;
text::trim(text, delimiters, result);
return result;
}
void text::trim(const string_type& text, const string_type& delimiters, string_type& result_text)
{
result_text = text;
const char_type* data(text.c_str());
// find left offset
int left_offset = 0;
while(left_offset < text.size() && (delimiters.find(data[left_offset]) != string_type::npos))
{
left_offset++;
}
// find right offset
size_type right_offset = text.size() - 1;
while(right_offset >= 0 && (delimiters.find(data[right_offset]) != string_type::npos))
{
right_offset--;
}
// build result
if(left_offset > 0 || right_offset < text.size() - 1)
{
result_text.assign(data, left_offset, right_offset + 1);
}
}
void text::split(const string_type& text, const string_type& delimiters, std::vector<string_type>& parts)
{
const char_type* data(text.c_str());
size_type offset = 0;
while(data[offset] != 0)
{
while(data[offset] != 0 && (delimiters.find(data[offset]) != string_type::npos)) // skip delimiters
{
offset++;
}
size_type entry_start = offset;
size_type entry_length = 0;
while(data[offset] != 0 && (delimiters.find(data[offset]) == string_type::npos)) // populate entry
{
entry_length++;
offset++;
}
if(entry_length > 0)
{
string_type entry(data + entry_start, entry_length);
parts.emplace_back(entry);
}
}
}
bool text::starts_with(const string_type& text, const char_type* prefix)
{
return text.substr(0, wcslen(prefix)).compare(prefix) == 0;
}
bool text::starts_with(const string_type& text, const string_type& prefix)
{
return text.substr(0, prefix.size()).compare(prefix) == 0;
}
END_NAMESPACE
| true |
e04b616780c01cc712fbe5dc35ed68cdf3df0146 | C++ | silverspace/samsara-sdks | /openapi-generator/cpp-tizen/src/AddressGeofencePolygon.h | UTF-8 | 1,708 | 2.796875 | 3 | [] | no_license | /*
* AddressGeofence_polygon.h
*
* Information about a polygon geofence. This field is only populated if the geofence is a polygon.
*/
#ifndef _AddressGeofence_polygon_H_
#define _AddressGeofence_polygon_H_
#include <string>
#include "AddressGeofence_polygon_vertices.h"
#include <list>
#include "Object.h"
/** \defgroup Models Data Structures for API
* Classes containing all the Data Structures needed for calling/returned by API endpoints
*
*/
namespace Tizen {
namespace ArtikCloud {
/*! \brief Information about a polygon geofence. This field is only populated if the geofence is a polygon.
*
* \ingroup Models
*
*/
class AddressGeofence_polygon : public Object {
public:
/*! \brief Constructor.
*/
AddressGeofence_polygon();
AddressGeofence_polygon(char* str);
/*! \brief Destructor.
*/
virtual ~AddressGeofence_polygon();
/*! \brief Retrieve a string JSON representation of this class.
*/
char* toJson();
/*! \brief Fills in members of this class from JSON string representing it.
*/
void fromJson(char* jsonStr);
/*! \brief Get The vertices of the polygon geofence. These geofence vertices describe the perimeter of the polygon, and must consist of at least 3 vertices and less than 40.
*/
std::list<AddressGeofence_polygon_vertices> getVertices();
/*! \brief Set The vertices of the polygon geofence. These geofence vertices describe the perimeter of the polygon, and must consist of at least 3 vertices and less than 40.
*/
void setVertices(std::list <AddressGeofence_polygon_vertices> vertices);
private:
std::list <AddressGeofence_polygon_vertices>vertices;
void __init();
void __cleanup();
};
}
}
#endif /* _AddressGeofence_polygon_H_ */
| true |
e6c43a26a780d3b89a0a8a24e27a46dfaf478e7e | C++ | zhenl010/zhenl010 | /practice/ExistRouteBetween/ExistRouteBetween/skip_list_set.h | UTF-8 | 8,344 | 3.3125 | 3 | [] | no_license | #ifndef SKIP_LIST_SET_H_
#define SKIP_LIST_SET_H_
#include <cassert>
#include <iterator>
#include "rand_height_generator.h"
namespace augment_data_structure
{
//////////////////////////////////////////////////////////////////////////
// TEMPLATE STRUCT less
template<class ComparableType>
struct DefaultLess
{ // functor for operator<
bool operator()(const ComparableType& leftsidevalue, const ComparableType& rightsidevalue) const
{ // apply operator< to operands
return (leftsidevalue < rightsidevalue);
}
};
template < typename T, int MAX_HEIGHT, typename CompareFunc = DefaultLess<T> >
class SkipListSet
{
public:
// A very specific skip list type with predefined parameters
static const int SKIP_LIST_PINV = 4;
SkipListSet();
~SkipListSet();
// forward declare the iterator
class SkipListSetIterator;
// Iterator:
typedef SkipListSet<T, MAX_HEIGHT, CompareFunc> container;
typedef SkipListSetIterator iterator;
typedef size_t size_type;
typedef T value_type;
typedef ptrdiff_t difference_type;
typedef const T* pointer;
typedef const T& reference;
friend class SkipListSetIterator;
iterator begin() { return iterator(*this, head_node_->next_nodes[0]); }
iterator end() { return iterator(*this, nullptr); }
int Size() { return size_; }
void Insert(const T&);
bool Remove(const T&);
T* Find(const T& x) { Node* node=FindNodeByValue(x); return node==nullptr ? nullptr : &node->data; }
private:
struct Node
{
T data;
int height;
Node** next_nodes;
};
SkipListSet(const SkipListSet&);
SkipListSet& operator=(const SkipListSet&);
int size_;
int curr_height_;
Node* head_node_;
Node** node_fix_;
// Helper functions
void ClearContent();
Node* CreateNode(int height);
void ReleaseContent(Node* node);
Node* FindNodeByValue(T);
};
template < typename T, int MAX_HEIGHT, typename CompareFunc >
SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSet()
: size_(0), curr_height_(0)
{
head_node_ = CreateNode(MAX_HEIGHT);
node_fix_ = new Node* [MAX_HEIGHT];
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
SkipListSet<T, MAX_HEIGHT, CompareFunc>::~SkipListSet()
{
ClearContent();
}
template < typename T, int MAX_HEIGHT, typename CompareFunc>
void SkipListSet<T, MAX_HEIGHT, CompareFunc>::Insert(const T& value)
{
int height = RandHeight<MAX_HEIGHT, SKIP_LIST_PINV>::Instance().RandomHeight();
Node* new_node = CreateNode(height);
new_node->data = value;
Node* curr_node = head_node_;
CompareFunc less_func;
for (int idx = curr_height_-1; idx >= 0; --idx)
{
while (curr_node->next_nodes[idx]!=nullptr && less_func(curr_node->next_nodes[idx]->data, value) )
{
curr_node = curr_node->next_nodes[idx];
}
node_fix_[idx] = curr_node;
}
if (curr_node->next_nodes[0]!=nullptr && (curr_node->next_nodes[0]->data)==value)
{
// do nothing if already exist
return;
}
while (curr_height_ < new_node->height)
{
node_fix_[curr_height_++] = head_node_;
}
for (int idx=0; idx<(new_node->height); ++idx)
{
new_node->next_nodes[idx] = node_fix_[idx]->next_nodes[idx];
node_fix_[idx]->next_nodes[idx] = new_node;
}
++size_;
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
bool SkipListSet<T, MAX_HEIGHT, CompareFunc>::Remove(const T& value)
{
Node* prev_node = head_node_;
CompareFunc less_func;
for (int idx = curr_height_-1; idx >= 0; --idx)
{
while (prev_node->next_nodes[idx]!=nullptr && less_func(prev_node->next_nodes[idx]->data, value))
{
prev_node = prev_node->next_nodes[idx];
}
node_fix_[idx] = prev_node;
}
Node* curr_node = prev_node->next_nodes[0];
if (curr_node==nullptr || less_func(value, curr_node->data))
{
return false;
}
for (int idx=0; idx<curr_height_; ++idx)
{
if (node_fix_[idx]->next_nodes[idx]!=nullptr)
{
node_fix_[idx]->next_nodes[idx] = node_fix_[idx]->next_nodes[idx]->next_nodes[idx];
}
}
while (0<curr_height_ && head_node_->next_nodes[curr_height_-1]==nullptr)
{
--curr_height_;
}
ReleaseContent(curr_node);
--size_;
return true;
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
void SkipListSet<T, MAX_HEIGHT, CompareFunc>::ClearContent()
{
Node* curr_node = head_node_->next_nodes[0];
while (curr_node != nullptr)
{
Node* next_node = curr_node->next_nodes[0];
ReleaseContent(curr_node);
curr_node = next_node;
}
ReleaseContent(head_node_);
delete [] node_fix_;
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::Node* SkipListSet<T, MAX_HEIGHT, CompareFunc>::CreateNode(int height)
{
assert(0<height && height<=MAX_HEIGHT);
Node* new_node = new Node;
new_node->next_nodes = new Node* [height];
new_node->height = height;
for (int i=0; i<height; ++i)
{
new_node->next_nodes[i] = nullptr;
}
return new_node;
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
void SkipListSet<T, MAX_HEIGHT, CompareFunc>::ReleaseContent(Node* node)
{
delete [] node->next_nodes;
delete node;
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::Node* SkipListSet<T, MAX_HEIGHT, CompareFunc>::FindNodeByValue(T value)
{
CompareFunc less_func;
Node* curr_node = head_node_;
for (int idx = curr_height_-1; idx >= 0; --idx)
{
while (curr_node->next_nodes[idx]!=nullptr && less_func(curr_node->next_nodes[idx]->data,value))
{
curr_node = curr_node->next_nodes[idx];
}
}
curr_node = curr_node->next_nodes[0];
if (curr_node==nullptr || less_func(value, curr_node->data))
{
return nullptr;
}
else
{
return curr_node;
}
}
// Iterator class
template < typename T, int MAX_HEIGHT, typename CompareFunc >
class SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSetIterator
: public std::iterator<std::forward_iterator_tag,
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::value_type,
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::difference_type,
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::pointer,
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::reference>
{
public:
typedef typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::Node* NodePtr;
SkipListSetIterator(SkipListSet<T, MAX_HEIGHT, CompareFunc>&, NodePtr);
reference operator*() const { return node_->data; }
bool operator==(const SkipListSetIterator& rhs) const { return &(container_)==&(rhs.container_) && node_==rhs.node_; }
bool operator!=(const SkipListSetIterator& rhs) const { return !(*this==rhs); }
SkipListSetIterator& operator++(); // prefix
SkipListSetIterator operator++(int); // postfix
private:
SkipListSet<T, MAX_HEIGHT, CompareFunc>& container_;
NodePtr node_;
};
template < typename T, int MAX_HEIGHT, typename CompareFunc >
SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSetIterator::SkipListSetIterator(SkipListSet<T, MAX_HEIGHT, CompareFunc>& c, NodePtr node)
: container_(c), node_(node)
{
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSetIterator&
SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSetIterator
::operator++() // prefix
{
node_ = node_->next_nodes[0];
return *this;
}
template < typename T, int MAX_HEIGHT, typename CompareFunc >
typename SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSetIterator
SkipListSet<T, MAX_HEIGHT, CompareFunc>::SkipListSetIterator
::operator++(int) // prefix
{
SkipListSetIterator ans = *this;
++(*this);
return ans;
}
//////////////////////////////////////////////////////////////////////////
}
#endif | true |
e8d30857d4e3bd723d571938956ad5d59136e961 | C++ | wevsty/RDPBlocker | /RDPBlocker/random_utils.cpp | UTF-8 | 598 | 3.125 | 3 | [
"MIT"
] | permissive | #include "random_utils.h"
std::string random_string(const unsigned int count, const std::string& chars_table)
{
std::string buffer;
if (chars_table.empty())
{
return buffer;
}
std::size_t max_table_index = chars_table.size() - 1;
std::random_device rd;
std::default_random_engine rng(rd());
std::uniform_int_distribution<> index_dist(0, static_cast<int>(max_table_index));
if (count > 0)
{
buffer.resize(count);
}
for (unsigned int i = 0; i < count; ++i) {
buffer[i] = chars_table[index_dist(rng)];
}
return buffer;
} | true |
d823f458ec089efdac97acdd0e5ded9122f083b3 | C++ | myrrlyn/SeniorDesign | /SeniorDesign/Pilot.cpp | UTF-8 | 3,798 | 2.609375 | 3 | [] | no_license | #include "Pilot.hpp"
#include <Arduino.h>
#include <stdint.h>
#define PILOT_ACCEL_CLOCK 0x0028
Pilot::Pilot(pilot_motor_info_t* left, pilot_motor_info_t* right) {
this->left = left;
this->right = right;
running = false;
activity = all_stop;
}
void Pilot::init() {
// Set up Timer 3
// We are using this as a software timer to accelerate the motors
OCR3A = 0xAF;
TIMSK3 |= _BV(OCIE3A);
}
void Pilot::start() {
running = true;
}
void Pilot::halt() {
running = false;
left->speed = 0;
right->speed = 0;
}
void Pilot::restart() {
running = true;
left->speed = 0;
right->speed = 0;
analogWrite(10, 0);
analogWrite(11, 0);
}
void Pilot::set_speed(uint8_t speed) {
cruising_speed_l = speed;
cruising_speed_r = speed * 0.85;
left->goal = speed;
right->goal = speed;
}
void Pilot::set_routine(maneouvre_t routine) {
activity = routine;
switch (routine) {
case ahead_full:
left->speed = cruising_speed_l;
right->speed = cruising_speed_r;
case move_forward:
left->goal = cruising_speed_l;
right->goal = cruising_speed_r;
left->status = true;
right->status = true;
break;
// Do not accelerate when banking; just jump speeds immediately.
case bank_left:
left->goal = (cruising_speed_l * 3) / 4;
right->goal = cruising_speed_r;
left->speed = left->goal;
right->speed = right->goal;
left->status = true;
right->status = true;
break;
case bank_right:
left->goal = cruising_speed_l;
right->goal = (cruising_speed_r * 3) / 4;
left->speed = left->goal;
right->speed = right->goal;
left->status = true;
right->status = true;
break;
// When pivoting, clamp the relevant motor to 0.
// Take care to ensure that the clamped motor accelerates rather than
// jumps to restore speed.
case pivot_left:
left->status = false;
right->status = true;
break;
case pivot_right:
left->status = true;
right->status = false;
break;
case all_stop:
left->status = false;
right->status = false;
break;
}
}
void Pilot::adjust(pilot_motor_info_t* m) {
if (running && m->status) {
switch (activity) {
case move_forward:
if (m->speed < m->goal) {
++(m->speed);
}
else if (m->speed > m->goal) {
--(m->speed);
}
break;
case ahead_full:
case bank_left:
case bank_right:
case pivot_left:
case pivot_right:
m->speed = m->goal;
break;
case all_stop:
m->speed = 0;
break;
}
}
else {
m->speed = 0;
}
analogWrite(m->pin, m->speed);
}
#ifdef DEVEL
void Pilot::debug() {
Serial.println("MOTORS");
Serial.print("Status: ");
Serial.println(pilot.running ? "Ready" : "Blocked");
Serial.print("Activity: ");
switch (activity) {
case ahead_full:
case move_forward:
Serial.println("MOVING FORWARD");
break;
case bank_left:
Serial.println("BANKING LEFT");
break;
case bank_right:
Serial.println("BANKING RIGHT");
break;
case pivot_left:
Serial.println("PIVOTING LEFT");
break;
case pivot_right:
Serial.println("PIVOTING RIGHT");
break;
case all_stop:
Serial.println("HALTING");
break;
}
Serial.print("Speed: ");
Serial.print(left->speed);
Serial.print(", ");
Serial.println(right->speed);
Serial.println();
}
#endif
pilot_motor_info_t ctl_left = {
.goal = 0,
.speed = 0,
.pin = 10,
.direction = motor_offline,
.status = false,
};
pilot_motor_info_t ctl_right = {
.goal = 0,
.speed = 0,
.pin = 11,
.direction = motor_offline,
.status = false,
};
uint16_t clock_l = 0;
uint16_t clock_r = 0;
Pilot pilot(&ctl_left, &ctl_right);
SIGNAL(TIMER3_COMPA_vect) {
++clock_l;
if (clock_l == PILOT_ACCEL_CLOCK) {
pilot.adjust(&ctl_left);
clock_l = 0x0000;
}
++clock_r;
if (clock_r == PILOT_ACCEL_CLOCK) {
pilot.adjust(&ctl_right);
clock_r = 0x0000;
}
}
| true |
e1def6409e7a6c0f5e124a359d16d769e1047563 | C++ | ShahadatShipon/Solution-Euler-Project-Problem | /1Multi3&5.cpp | UTF-8 | 216 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long sum=0;
for(int i=0;i<1000;i++){
if(i%3==0 || i%5==0){
sum+=i;
}
}
cout << sum <<endl;
}
| true |
2be3091c0934d1626c504cbb964a9d577ba076c7 | C++ | md143rbh7f/competitions | /acm-icpc/mid-atlantic-usa/08/close_enough.cpp | UTF-8 | 381 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
inline double sub( int x ) { return x ? x - 0.5 : 0; }
int main()
{
while(1)
{
int a, b, c, d;
cin >> a >> b >> c >> d;
if( !a && !b && !c && !d ) break;
double lo = 9 * sub(b) + 4 * ( sub(c) + sub(d) );
double hi = 9 * ( b + 0.5 ) + 4 * ( c + d + 1 );
cout << ( lo <= a && a < hi ? "yes" : "no" ) << endl;
}
return 0;
}
| true |
0659601cac71acf09276bf11d6f98d453f851395 | C++ | clqsrc/os_public | /public_function.cpp | GB18030 | 39,920 | 2.65625 | 3 | [] | no_license |
#include "stdafx.h"
#include "os.h"
#include "thread_api.h"
#include "thread_lock.h"
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include "file_system.h"
#include "public_function.h"
//--------------------------------------------------
//Ҫ md5.h
#ifdef __USE_MD5__
#include "md5.h"
#endif
//--------------------------------------------------
//#include "md5.h"
#include <math.h>
//#include <gd.h>
//#include <gdfontg.h>
extern FILE * log_file;//־ļ
/* ú/ú */
//õļ·//[/]
std::string extract_file_path(const std::string fn)
{
std::string s = "";
char c = '\0';
int count = 0;
for (int i = 0; i < fn.size(); i++)
{
c = fn[fn.size()-i-1];
count++;
if (c == '\\' || c == '/')
break;
//s = c + s;
//count++;
}
s = fn.substr(0, fn.length()-count);
return s;
}
//õ mysql ʽĵǰʱ
std::string GetMysqlDateTime()
{
std::string s = "";
tm m = GetLocalTM();
s += int_to_str(m.tm_year+1900) + "-";
s += int_to_str(m.tm_mon+1) + "-";
s += int_to_str(m.tm_mday);
s += " ";
s += int_to_str(m.tm_hour) + ":";
s += int_to_str(m.tm_min) + ":";
s += int_to_str(m.tm_sec);
return s;
}
//һдļ// log ͵صļ
FILE * open_log_file(const std::string fn)
{
FILE * f = fopen(fn.c_str(), "a+b");
if(f == NULL)
{
printf("%s", "error! log file can't open!\r\n");
return NULL;
}
setbuf(f, NULL);//дļ
return f;
}
//õص tm ṹ
tm GetLocalTM()
{
time_t t = time(NULL);
tm * pm = NULL;
tm m;
memset(&m, 0, sizeof(m));
pm = localtime(&t);
if (pm != NULL)
{
m = (* pm);
}
return m;
}
//õ gm tm ṹ
tm GetTM()
{
time_t t = time(NULL);
tm * pm = NULL;
tm m;
memset(&m, 0, sizeof(m));
pm = gmtime(&t);
m = (* pm);
return m;
}
//ȡõǰʱ
int GetTimeZone()
{
time_t t = 0;//time(NULL);
tm * m = NULL;
tm gtm;//
tm ltm;//
memset(>m, 0, sizeof(tm));
memset(<m, 0, sizeof(tm));
m = gmtime(&t);
if (m == NULL) return 0;
gtm = *m;
m = localtime(&t);
if (m == NULL) return 0;
ltm = *m;
int r = ltm.tm_hour - gtm.tm_hour;
return r;
}
//mktime ǰ tm еʱ䵱ʱõʱ,Ҫ tm еʱֱӵʱ//㷨ϾҪʱ
time_t gm_mktime(struct tm * m)
{
time_t t = mktime(m);//ʱ t Ҫ 8 Сʱ,Ҫ8Сʱʱ//˵ôʱ.
//t = 8 * 60 * 60;
int iTimeZone = GetTimeZone();
t = t + iTimeZone * 60 * 60;
return t;
}
//ȽϸǷ//DzֱдȺűȽϵģҪһȷΧڲ
bool float_cmp(const float f1, const float f2)
{
bool r = false;
if (fabs(f1 - f2) < 0.000001)
{
r = true;
}
return r;
}
//ļװ//Ҫͷŷصַڴ澡úǸ
char * load_from_file(const char * fn, long & len)
{
if ((fn == NULL)||(strlen(fn) == 0))
{
return NULL;
}
len = file_system::get_file_length(fn);
if (0 >= len) return NULL;
//char * buf = new char[len];
char * buf = (char *)malloc(len);//ͳһ malloc/free
if (buf == NULL)
{
return NULL;
}
memset(buf, 0, len);
//BYTE buf[50000];
FILE * f = fopen(fn, "rb");
if (f == NULL)
{
free(buf);
return NULL;
}
long r = fread(buf, 1, len, f);//fread(buf, len, 1, f)buf㹻ʱǶԵģ
if (r != len)
{
//printf("error at ftp_client_socket::load_from_file!\r\n");
free(buf);
fclose(f);
return NULL;
}
fclose(f);
return (char *)buf;
}
std::string load_from_file(const char * fn)//ע,ķֵDz delete
{
long len;
char * buf = load_from_file(fn, len);
if (buf == NULL)
return "";
std::string s(buf, len);
//delete [] buf;
free(buf);//ͳһ malloc/free
return s;
}
void load_from_file(lines & l, const char * fn)
{
std::string buf = load_from_file(fn);
load_from_string(l, buf);
}
void load_from_string(lines & l, std::string & buf)
{
//std::string buf = load_from_file(fn);
std::string key = "";
std::string value = "";
std::string line = "";
for (long i=0; i<buf.size(); i++)
{
if (buf[i]=='\r') continue;
if (buf[i]=='\n')
{
l.push_back(line);
line = "";
continue;
}
line += buf[i];
}
//\n֮
if (line.size() > 0)
{
l.push_back(line);
line = "";
}
}
void load_from_file(lines & l, const char * fn, char sp)
{
std::string buf = load_from_file(fn);
load_from_string(l, buf, sp);
}
void load_from_string(lines & l, std::string & buf, char sp)
{
//std::string buf = load_from_file(fn);
//std::string key = "";
//std::string value = "";
std::string line = "";
for (long i=0; i<buf.size(); i++)
{
//if (buf[i]=='\r') continue;
if (buf[i] == sp)
{
l.push_back(line);
line = "";
continue;
}
line += buf[i];
}
//\n֮
if (line.size() > 0)
{
l.push_back(line);
line = "";
}
}
//һݵļ
bool save_to_file(const char * fn, const char * buf, long len)
{
//дļ
FILE * f = fopen(fn, "wb");
if (f == NULL)
{
//fclose(f);// ļû
return false;
}
long r = fwrite(buf, 1, len, f);
if (r != len)
{
fclose(f);
return true;
}
fclose(f);
return true;
}
//һݵļ
bool save_to_file(const std::string fn, const std::string buf)
{
//дļ
return save_to_file(fn.c_str(), buf.data(), buf.size());
}
//һݵļ
bool save_to_file(const std::string fn, lines & l)
{
std::string buf = "";
for (int i = 0; i < l.size(); i++)
{
buf += l[i] + "\r\n";
}
//дļ
return save_to_file(fn.c_str(), buf.data(), buf.size());
}
//תΪַ
std::string int_to_str(long value)
{
char s[256];
memset(s, 0, sizeof(s));
//ltoa(value,s,10);//ƺlinuxʹ
//sprintf(s, "%d", value);
sprintf(s, "%ld", value);////sprintf(s, "%08X", 4567); //"000011D7"
std::string r = s;
return r;
}
//תΪַ
std::string int_to_str(long value, int width)
{
char f[256];//ʽ
char s[256];
memset(f, 0, sizeof(s));
memset(s, 0, sizeof(s));
//ltoa(value,s,10);//ƺlinuxʹ
//sprintf(s, "%d", value);
sprintf(f, "%%0%dld", width);//"%08ld"
//sprintf(s, "%ld", value);////sprintf(s, "%08X", 4567); //"000011D7"
sprintf(s, f, value);////sprintf(s, "%08X", 4567); //"000011D7"
std::string r = s;
return r;
}
//תΪַ
std::string float_to_str(double value, int width)
{
char f[256];//ʽ
char s[256];
memset(f, 0, sizeof(s));
memset(s, 0, sizeof(s));
//ο http://www.cnblogs.com/wqlblogger/archive/2007/01/09/615525.aspx
//sprintf(f, "%%*.*f");
sprintf(f, "%%.*f");
sprintf(s, f, width, value);
std::string r = s;
return r;
}
//תΪַ
std::string float_to_str(double value)
{
char f[256];//ʽ
char s[256];
memset(f, 0, sizeof(s));
memset(s, 0, sizeof(s));
//ο http://www.cnblogs.com/wqlblogger/archive/2007/01/09/615525.aspx
sprintf(f, "%%f");//ĬϵСλΪ 6
//sprintf(f, "%%*.*f");//
sprintf(s, f, value);
std::string r = s;
return r;
}
int str_to_int(std::string v)
{
return atoi( v.c_str() );
}
//ģ庯
std::string get_template_string(std::string s, keys & k)
{
std::string r = "";
std::string key = "";
std::string value = "";
keys::iterator iter;
for (iter = k.begin(); iter != k.end();)
{
key = iter->first;
value = iter->second;
s = str_replace(s, key, value);
iter++;
}
//s = str_replace(s, key, value);
return s;
}
std::string get_template_string_from_file(std::string fn, keys & k)
{
std::string r = "";
std::string fs = load_from_file(fn.c_str());
r = get_template_string(fs, k);
return r;
}
//ģ庯
std::string make_string_3(const std::string src, std::string sp_begin1, std::string sp_end1, std::string & l, std::string & r)
{
std::string m = "";
std::string in1 = lcase(src);//in1ַλ,ȡʱȻʵsrc//ԺԴСдֲԭе
sp_begin1 = lcase(sp_begin1);
sp_end1 = lcase(sp_end1);
int pos_b1,pos_e1; //Ҫõַβλ
//pos_b1
if (sp_begin1.length()==0)//1ָΪվͱʾȡ2ָ֮ǰַ
{
pos_b1=0;
}
else//һָΪʱ
{
pos_b1=in1.find(sp_begin1);
if (pos_b1 == -1) return "";//һָΪգҲʱֵǿ
pos_b1 += sp_begin1.length();//ҪϷָij
}
//Ӻpos_b1ʼpos_e1
pos_e1=in1.find(sp_end1, pos_b1);
if (sp_end1.length()==0)//2ָΪվͱʾȡ1ַָ֮
{
pos_e1=in1.length();
}
//ַ,ؿմ
if (
((pos_b1==-1)&&(pos_e1==-1))
||((pos_b1==-1)&&(sp_begin1.size() > 0))
||((pos_e1==-1)&&(sp_end1.size() > 0))
)
{
return "";
}
//r = src.substr(pos_b1, pos_e1-pos_b1);
m = substring_JAVA(src, pos_b1, pos_e1);
l = substring_JAVA(src, 0, pos_b1);
r = substring_JAVA(src, pos_e1, src.length());
return m;
return m;
}
//滻ַ
std::string str_replace(const std::string s, const std::string old_s, const std::string new_s)
{
size_t pos = 0;
std::string r = s;
while(true)
{
pos = r.find(old_s, pos);
if (pos == std::string::npos) break;
//c++replaceͬ
//r.replace(pos, pos + old_s.length(), new_s);
//עڶ
r.replace(pos, old_s.length(), new_s);
pos += new_s.length();//λҪ
}
return r;
}
std::string trim(std::string s)
{
if (s.size()==0) return "";
//û뵽ͦд
//Ϊint ibpos = strbuf[i].find_first_not_of(" "); int iepos = strbuf[i].find_last_not_of(" ");ʵ
size_t ibpos = 0;
size_t iepos = s.size();
char c;
size_t i;
for (i = 0; i<s.size(); i++)
{
c = s[i];
if ((c == ' ')||(c == '\0')||(c == '\t')||(c == '\r')||(c == '\n'))
{
continue;
}
ibpos = i;
break;
}
for (i = s.size()-1; ; i--)//s.size()Ϊ0,ѭ
{
c = s[i];
if ((c == ' ')||(c == '\0')||(c == '\t')||(c == '\r')||(c == '\n'))
{
iepos = i;
if (i==0) break;
continue;
}
break;
}
return s.substr(ibpos, iepos - ibpos);
}
//ҪЧʵĵط trim//ȥұߵĿո
void trimr(char * buf, int buf_len)
{
char c;
int i = 0;
for (i = buf_len-1; ; i--)//s.size()Ϊ0,ѭ
{
c = buf[i];
if ((c == ' ')||(c == '\0')||(c == '\t')||(c == '\r')||(c == '\n'))
{
buf[i] = '\0';
if (i==0) break;
continue;
}
break;
}
}
//ҪЧʵĵط std::string ʵ
void lcase(char * buf, int buf_len)
{
for (int i=0; i < buf_len; i++)
{
buf[i] = tolower(buf[i]);
}
}
//Сд//עַȫ
std::string lcase(std::string s)
{
std::string r = "";
for (int i=0;i<s.size();i++)
{
r += tolower(s[i]);
}
return r;
}
//ҪЧʵĵط std::string ʵ
void ucase(char * buf, int buf_len)
{
for (int i=0; i < buf_len; i++)
{
buf[i] = toupper(buf[i]);
}
}
//д//עַȫ
std::string ucase(std::string s)
{
std::string r = "";
for (int i=0;i<s.size();i++)
{
r += toupper(s[i]);
}
return r;
}
////[Сд]
//std::string uncase_find(std::string s1, std::string s2)
bool ufind(std::string s, std::string sub_s)
{
//
if (lcase(s).find(lcase(sub_s)) != std::string::npos)
{
return true;
}
return false;
}
//javasubstringʵֵ,ҪΪjavaĴֲC++,VCstd::stringsubstrзʵIJԽĻ쳣[Ϊؿַ]
std::string substring_JAVA(std::string s, int beginIndex, int endIndex)
{
std::string r = "";
r = substring_STL(s, beginIndex, endIndex-beginIndex);//javaеsubstringĵ2ַָֹλ;stlҪƵij,̫ͻ쳣
return r;
}
//VCSTL쳣,μsubstring_JAVA˵
std::string substring_STL(std::string s, int pos, int n)
{
std::string r = "";
//ʼλ̫,ֱӷؿ
if (s.size()<=pos)
{
return "";
}
//ʼλ̫,ֱӷؿ
if (pos<0)
{
pos = 0;
}
//ֹʼλ̫,ֱȡַλ
if (s.size() <= pos+n )
{
n = s.size()-pos;
}
r = s.substr(pos, n);//vcstlpos_b1Сpos_e1//javaеsubstringĵ2ַָֹλ;stlҪƵij,̫ͻ쳣
return r;
}
//VCSTL쳣,μsubstring_JAVA˵
std::wstring substring_STL(std::wstring s, int pos, int n)
{
//std::wstring r = NULL;
std::wstring r;
r.resize(0);//ֱֲд r = "";
//ʼλ̫,ֱӷؿ
if (s.size()<=pos)
{
return r;
}
//ʼλ̫,ֱӷؿ
if (pos<0)
{
pos = 0;
}
//ֹʼλ̫,ֱȡַλ
if (s.size() <= pos+n )
{
n = s.size()-pos;
}
r = s.substr(pos, n);//vcstlpos_b1Сpos_e1//javaеsubstringĵ2ַָֹλ;stlҪƵij,̫ͻ쳣
return r;
}
//http://www.alhem.net/Sockets/html/Utility_8cpp-source.html//ȥIEUTF8ʹ
std::string rfc1738_decode_old(const std::string & src)
{
std::string dst;
for (size_t i = 0; i < src.size(); i++)
{
if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2]))
{
char c1 = src[i + 1];
char c2 = src[i + 2];
c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0);
c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0);
dst += (char)(c1 * 16 + c2);
}
else
if (src[i] == '+')
{
dst += ' ';
}
else
{
dst += src[i];
}
}
return dst;
} // rfc1738_decode
std::string rfc1738_decode(const std::string & src)
{
std::string dst;
//for (size_t i = 0; i < src.size(); i++)
size_t i = 0;
while(i < src.size())
{
//if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2]))
//if (false)
if (src[i] == '%')
{
if ((i+2) >= src.size()) break;//ȫЩ
char c1 = src[i + 1];
char c2 = src[i + 2];
c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0);
c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0);
//Ҳ,ֻǴд
//c1 = c1 - '0';
//c2 = c2 - '0';
dst += (char)(c1 * 16 + c2);
i += 3;
}
else
if (src[i] == '+')
{
dst += ' ';
i += 1;
}
else
{
dst += src[i];
i += 1;
}
}
return dst;
} // rfc1738_decode
std::string rfc1738_encode(const std::string& src)
{
static char hex[] = "0123456789ABCDEF";
std::string dst;
for (size_t i = 0; i < src.size(); i++)
{
if (isalnum(src[i]))
{
dst += src[i];
}
else
if (src[i] == ' ')
{
dst += '+';
}
else
{
dst += '%';
dst += hex[src[i] / 16];
dst += hex[src[i] % 16];
}
}
return dst;
} // rfc1738
//ִСд
std::string get_value1_old(std::string src, std::string sp_begin1, std::string sp_end1)
{
//return "";
///*
std::string in1 = lcase(src);//in1ַλ,ȡʱȻʵsrc
sp_begin1 = lcase(sp_begin1);
sp_end1 = lcase(sp_end1);
std::string fs1 = "";
int pos_b1,pos_e1; //Ҫõַβλ
//Ȱһַȡַ//fs1Ϊpos_b1ַ
pos_b1=in1.find(sp_begin1)+sp_begin1.length();
if (sp_begin1.length()==0)
{
pos_b1=0;
}
pos_e1=in1.length();
//fs1=in1.substr(pos_b1, pos_e1-pos_b1);//vcstlpos_b1Сpos_e1//javaеsubstringĵ2ַָֹλ;stlҪƵij,̫ͻ쳣
fs1 = substring_JAVA(in1, pos_b1, pos_e1);
//..end;
//Ȼٽȡַsp_end1ǰIJ
pos_e1=fs1.find(sp_end1);
pos_b1=0; //ʼλñ뻹ԭΪ
if (sp_end1.length()==0)
{
pos_e1=in1.length();
}
//ַ,ؿմ
if ((pos_b1==-1)&&(pos_e1==-1))
{
return "";
}
//fs1=fs1.substr(pos_b1, pos_e1-pos_b1);
fs1 = substring_JAVA(fs1, pos_b1, pos_e1);
return fs1;
//*/
}
std::string get_value1(std::string src, std::string sp_begin1, std::string sp_end1)
{
std::string in1 = lcase(src);//in1ַλ,ȡʱȻʵsrc//ԺԴСдֲԭе
sp_begin1 = lcase(sp_begin1);
sp_end1 = lcase(sp_end1);
std::string r = "";
int pos_b1,pos_e1; //Ҫõַβλ
//pos_b1
if (sp_begin1.length()==0)//1ָΪվͱʾȡ2ָ֮ǰַ
{
pos_b1=0;
}
else//һָΪʱ
{
pos_b1=in1.find(sp_begin1);
if (pos_b1 == -1) return "";//һָΪգҲʱֵǿ
pos_b1 += sp_begin1.length();//ҪϷָij
}
//Ӻpos_b1ʼpos_e1
pos_e1=in1.find(sp_end1, pos_b1);
if (sp_end1.length()==0)//2ָΪվͱʾȡ1ַָ֮
{
pos_e1=in1.length();
}
//ַ,ؿմ
if (
((pos_b1==-1)&&(pos_e1==-1))
||((pos_b1==-1)&&(sp_begin1.size() > 0))
||((pos_e1==-1)&&(sp_end1.size() > 0))
)
{
return "";
}
//r = src.substr(pos_b1, pos_e1-pos_b1);
r = substring_JAVA(src, pos_b1, pos_e1);
return r;
}
void load_keys_buf1(keys & k, std::string & buf)
{
std::string key = "";
std::string value = "";
std::string line = "";
lines ls;
load_from_string(ls, buf);
for (int i=0; i<ls.size(); i++)
{
line = ls[i];
if( (line.size() > 0) && (line[0]=='#') ) continue;//ע
key = lcase(get_value1(line, "", "="));
value = get_value1(line, "=", "");
k[key] = value;
continue;
}
}
//ļмؼֵ//apacheһ[#]ſʼΪע
void load_keys1(keys & k, const std::string fn)
{
std::string key = "";
std::string value = "";
std::string line = "";
lines ls;
load_from_file(ls, fn.c_str());
for (int i=0; i<ls.size(); i++)
{
line = ls[i];
if( (line.size() > 0) && (line[0]=='#') ) continue;//ע
key = get_value1(line, "", "=");;
value = get_value1(line, "=", "");
k[key] = value;
continue;
}
}
//ֵ
void save_keys1(keys & k, const std::string fn)
{
std::string key = "";
std::string value = "";
std::string line = "";
std::string buf = "";
keys::iterator iter;
for (iter = k.begin(); iter != k.end();)
{
key = iter->first;
value = iter->second;
buf += key + "=" + value + "\r\n";
iter++;
}
save_to_file(fn, buf);
}
//жijǷб
bool key_in_keys(std::string key, keys & list)
{
std::map<std::string, std::string>::iterator iter;
iter = list.find(key);
if(iter != list.end())
{
return true;
}
return false;
}
// NULL ֵ,ü
std::string safe_std_string(const char * str)
{
std::string r = "";
r = str;
return r;
}
std::string safe_std_string(const std::string str)
{
std::string r = "";
r = str.c_str();
return r;
}
std::string safe_std_string(keys & list, const std::string key)
{
std::string value = "";
std::map<std::string, std::string>::iterator iter;
iter = list.find(key);
if(iter != list.end())
{
value = iter->second;
//break;
}
return value;
}
//ֱ[]ȡֵDzȫ,Ҫһ
bool get_value(std::map<std::string, std::string> list, std::string key, std::string & value)
{
std::map<std::string, std::string>::iterator iter;
iter = list.find(key);
if(iter != list.end())
{
value = iter->second;
return true;
}
return false;
}
std::string get_value(std::map<std::string, std::string> list, std::string key)
{
std::string s;
if (get_value(list, key, s)==false)
return "";
return s;
}
std::string str_to_hex(std::string s)
{
char buf[250];
memset(buf, 0, sizeof(buf));
std::string r = "";
char c;
for(int i=0; i<s.size(); i++)
{
c = s[i];
//sprintf(buf, "%X", (byte)c);
sprintf(buf, "%02X", (unsigned char)c);//ҪУҪ 1 תΪ "1" Ҫ "01"
r += buf;
}
return r;
//return ucase(r);
}
//
std::string buf_to_hex(const char * s, int len)
{
char buf[250];
memset(buf, 0, sizeof(buf));
std::string r = "";
char c;
for(int i=0; i<len; i++)
{
c = s[i];
//sprintf(buf, "%X", (byte)c);
sprintf(buf, "%02X", (unsigned char)c);
r += buf;
}
return r;
//return ucase(r);
}
//['A']=>10
int hexchar_to_int(char c)
{
if(c<='9'&&c>='0')
return int(c)-48;
if(c<='Z'&&c>='A')
return int(c)-55;
if(c<='z'&&c>='a')
return int(c)-87;
return -1;
}
//["63"]=>["c"]
std::string hex_to_str(std::string s)
{
if ((s.size() % 2)!=0)//2ı
{
printfd2("error at hex_to_str():%s\r\n", s.c_str());
return "";
}
char buf[3];
memset(buf, 0, sizeof(buf));
std::string r = "";
char c1,c2;
int i1,i2;
for(int i=0; i<s.size(); )
{
c1 = s[i];
c2 = s[i+1];
i1 = hexchar_to_int(c1);
i2 = hexchar_to_int(c2);
if ((i1==-1)||(i2==-1))
{
printfd2("error at hex_to_str()2:%s\r\n", s.c_str());
return "";
}
r += ( (char)(i1*16 + i2) );
i += 2;
}
return r;
}
//Ƿǰȫַ//»,,ĸ
bool check_safe_str(std::string s)
{
char c1;
for(int i=0; i<s.size(); i++)
{
c1 = s[i];
if (c1=='.') return false;
if (c1=='_') return true;
if( (c1>='0' && c1<='9')||(c1>='a' && c1<='z')||(c1>='A' && c1<='Z') )
{
return true;
}
}
return true;
}
//ַǷͬ[Сд]
bool uncase_cmp(const char * buf,const char * cmd)
{
//ַDz
if (strlen(buf) < strlen(cmd)) return false;
//ÿַȽһ
for (int i=0;i<strlen(cmd);i++)
{
//һַһDzͬ
if (tolower(buf[i])!=tolower(cmd[i]))
{
return false;
}
}
return true;
}
bool str_eq(std::string s1, std::string s2)
{
if(s1.compare(s2) == 0)
{
return true;
}
else
{
return false;
}
}
//ԴСдıȽ
bool eqIgnoreCase(const std::string s1, const std::string s2)
{
if(lcase(s1).compare(lcase(s2)) == 0)
{
return true;
}
else
{
return false;
}
}
//õļ
std::string extract_file_ext(const std::string fn)
{
size_t pos = fn.rfind(".");
if (pos == std::string::npos) return "";
return fn.substr(pos);
}
//õļ
std::string extract_file_name(const std::string fn)
{
std::string s = "";
char c = '\0';
for (int i = 0; i < fn.size(); i++)
{
c = fn[fn.size()-i-1];
if (c == '\\' || c == '/')
break;
s = c + s;
}
return s;
}
//--------------------------------------------------
//Ҫ md5.h
#ifdef __USE_MD5__
//md5
std::string md5(const std::string strA1)
{
unsigned char szMD5[16];
char outbuf[3];
MD5_CTX md5;
MD5Init( &md5 );
MD5Update( &md5, (unsigned char *)strA1.c_str( ), (unsigned int)strA1.size( ) );
MD5Final( szMD5, &md5 );
//return std::string( (char *)szMD5, 16 );//ע//ԲǷнβ"\0"ַ
std::string s = "";
for (int i = 0; i < 16; i++)
{
sprintf(outbuf, "%02x", szMD5[i]);
s += outbuf;
}
return s;
}
#endif
//--------------------------------------------------
void printf_error(const char * s)
{
while(true)
{
printf("%s", s);
::Sleep(100);
}
}
//Ҫ gd /////////////////////////////////
#ifdef __USE_GD__
//ΪЧҪ gdFree ͷŷֵ
char * resize_imagett(const std::string fn, int new_W, int new_H, int & size)
{
FILE * old_fp = NULL;
FILE * new_fp = NULL;
gdImagePtr old_im, new_im; //ͼƬɡͼƬ
//char * old_fn = "C:\\Documents and Settings\\Administrator\\\\1.jpg";
//char * new_fn = "C:\\Documents and Settings\\Administrator\\\\2.jpg";
char * old_fn = "C:\\Documents and Settings\\wilson\\\\1.jpg";
char * new_fn = "C:\\Documents and Settings\\wilson\\\\2.jpg";
int A4_W = 40;//?
int A4_H = 40;//?
new_W = 100;//¿
new_H = 100;//¸߶
/*
if((old_fp=fopen(old_fn, "rb"))!=NULL)
{ //ԭͼƬļ
old_im=gdImageCreateFromJpeg(old_fp);//ȡԭͼƬ
new_im = gdImageCreate(A4_W,A4_H); //ͼƬȡþ
int white = gdImageColorAllocate(new_im, 255, 255, 255); //ɫ,ɫ
int black = gdImageColorAllocate(new_im, 0, 0, 0); //ɫ,ǰɫ
gdImageCopyResized(new_im,old_im,0,0,0,0,new_W,new_H,old_im->sx,old_im->sy);//ƲͼƬ,new_W,new_H,ͼƬĿ
if((new_fp=fopen(new_fn,"wb"))!=NULL)
{ //ļ
gdImageJpeg(new_im,new_fp,-1); //ͼƬļ
fclose(new_fp);
};
fclose(old_fp);
};
*/
if((old_fp=fopen(old_fn, "rb"))!=NULL)
{ //ԭͼƬļ
old_im=gdImageCreateFromJpeg(old_fp);//ȡԭͼƬ
}
return "";
}
//ΪЧҪ gdFree ͷŷֵ//type 0 - jpg, 1 - png
char * resize_image(const std::string fn, int new_W, int new_H, int & size, int type, int quality)
//char * resize_image(const std::string fn, int new_W, int new_H, long & size, int type, int quality)
{
FILE * old_fp = NULL;
FILE * new_fp = NULL;
gdImagePtr old_im = NULL;
gdImagePtr new_im = NULL; //ͼƬɡͼƬ
char * old_fn = (char *)fn.c_str();//"C:\\Documents and Settings\\Administrator\\\\1.jpg";
//char * old_fn = "C:\\Documents and Settings\\wilson\\\\1.jpg";
//char * new_fn = "C:\\Documents and Settings\\Administrator\\\\2.jpg";
//int A4_W = new_W;//40;//?
//int A4_H = new_H;//40;//?
//int new_W = 100;//¿
//int new_H = 100;//¸߶
char * data = NULL;
log_cur(log_file);
////ܷڴ
if((old_fp=fopen(old_fn, "rb"))!=NULL)
{ //ԭͼƬļ
log_cur(log_file);
old_im=gdImageCreateFromJpeg(old_fp);//ȡԭͼƬ
log_cur(log_file);
if (old_im == NULL)
return NULL;
log_cur(log_file);
//߶//ʱ
//old_im->sx;//
//old_im->sy;//߶
new_H = new_W * (((double)old_im->sy)/(double)(old_im->sx));
//߶//ʱ _end;
//һҪپͼƬڴй¶
fclose(old_fp);
//ں//gdImageDestroy(old_im);
//new_im = gdImageCreate(A4_W,A4_H); //ͼƬȡþ
// new_im = gdImageCreate(new_W, new_H); //ͼƬȡþ
new_im = gdImageCreateTrueColor(new_W, new_H); //ͼƬȡþ
//int white = gdImageColorAllocate(new_im, 255, 255, 255); //ɫ,ɫ
//int black = gdImageColorAllocate(new_im, 0, 0, 0); //ɫ,ǰɫ
//gdImageCopyResized ЧҶ˵
// gdImageCopyResized(new_im,old_im,0,0,0,0,new_W,new_H,old_im->sx,old_im->sy);//ƲͼƬ,new_W,new_H,ͼƬĿ
gdImageCopyResampled(new_im,old_im,0,0,0,0,new_W,new_H,old_im->sx,old_im->sy);//ƲͼƬ,new_W,new_H,ͼƬĿ
/*
if((new_fp=fopen(new_fn,"wb"))!=NULL)
{ //ļ
gdImageJpeg(new_im,new_fp,-1); //ͼƬļ
fclose(new_fp);
};
fclose(old_fp);
*/
if (type == 0)
{
data = (char *) gdImagePngPtr(new_im, &size);
}
else
{
if ((quality < -1)||(quality > 100))
{
quality = 85;//ѹ
}
//data = (char *) gdImageJpegPtr(new_im, &size, -1);//һʲô˼?// -1 Чdzã85 ȽϺ
data = (char *) gdImageJpegPtr(new_im, &size, quality);//һʲô˼?
}
if (!data)
{
//Error
return NULL;
}
};
log_cur(log_file);
//һҪپͼƬڴй¶
//fclose(old_fp);
//ں//
if (old_im != NULL)
{
gdImageDestroy(old_im);
}
if (new_im != NULL)
{
gdImageDestroy(new_im);//ᵼ data ʧЧ?
}
//--------------------------------------------------
//2010.4.5
if ((data != NULL)&&(size != 0))
{
char * out_data = (char *)malloc(size);
memcpy(out_data, data, size);
gdFree(data);
return out_data;
}
//return data;
return NULL;
//ע㺯һҪ//gdFree(data); //ãֱ free
}
#endif
//Ҫ gd /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//ֻ windows ²õĺ
#ifdef WIN32
//windowsʱתΪtime_t//https://ccvs.cvshome.org/source/browse/ccvs/windows-NT/JmgStat.c?rev=1.3&content-type=text/vnd.viewcvs-markup
bool FileTimeToUnixTime ( const FILETIME* ft, time_t* ut, bool local_time )
{
bool success = FALSE;
if ( local_time )
{
struct tm atm;
SYSTEMTIME st;
success = FileTimeToSystemTime ( ft, &st );
/* Important: mktime looks at the tm_isdst field to determine
* whether to apply the DST correction. If this field is zero,
* then no DST is applied. If the field is one, then DST is
* applied. If the field is minus one, then DST is applied
* if the United States rule calls for it (DST starts at
* 02:00 on the first Sunday in April and ends at 02:00 on
* the last Sunday in October.
*
* If you are concerned about time zones that follow different
* rules, then you must either use GetTimeZoneInformation() to
* get your system's TIME_ZONE_INFO and use the information
* therein to figure out whether the time in question was in
* DST or not, or else use SystemTimeToTzSpecifiedLocalTime()
* to do the same.
*
* I haven't tried playing with SystemTimeToTzSpecifiedLocalTime()
* so I am nor sure how well it handles funky stuff.
*/
atm.tm_sec = st.wSecond;
atm.tm_min = st.wMinute;
atm.tm_hour = st.wHour;
atm.tm_mday = st.wDay;
/* tm_mon is 0 based */
atm.tm_mon = st.wMonth - 1;
/* tm_year is 1900 based */
atm.tm_year = st.wYear>1900?st.wYear - 1900:st.wYear;
atm.tm_isdst = -1; /* see notes above */
*ut = mktime ( &atm );
}
else
{
/* FILETIME = number of 100-nanosecond ticks since midnight
* 1 Jan 1601 UTC. time_t = number of 1-second ticks since
* midnight 1 Jan 1970 UTC. To translate, we subtract a
* FILETIME representation of midnight, 1 Jan 1970 from the
* time in question and divide by the number of 100-ns ticks
* in one second.
*/
/* One second = 10,000,000 * 100 nsec */
const ULONGLONG second = 10000000L;
SYSTEMTIME base_st =
{
1970, /* wYear */
1, /* wMonth */
0, /* wDayOfWeek */
1, /* wDay */
0, /* wHour */
0, /* wMinute */
0, /* wSecond */
0 /* wMilliseconds */
};
ULARGE_INTEGER itime;
FILETIME base_ft;
success = SystemTimeToFileTime ( &base_st, &base_ft );
if (success)
{
itime.QuadPart = ((ULARGE_INTEGER *)ft)->QuadPart;
itime.QuadPart -= ((ULARGE_INTEGER *)&base_ft)->QuadPart;
itime.QuadPart /= second;
*ut = itime.LowPart;
}
}
if (!success)
{
*ut = -1; /* error value used by mktime() */
}
return success;
}
// GB2312 ת utf-8
std::string gbk_to_utf8(std::string src)
{
//int len = src.size() * 2 +1;//Сٴ
int len = (src.size()+1) * 4;//4
char * p_out = (char *)malloc(len);//LPWSTR
char * p_out_utf8 = (char *)malloc(len);
memset(p_out, 0, len);
memset(p_out_utf8, 0, len);
//gbk ת unicode
//int word_count = ::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src.c_str(), src.size(), (WCHAR *)p_out, src.size());
int word_count = ::MultiByteToWideChar(936, MB_PRECOMPOSED,
src.c_str(),
src.size(), // number of bytes in string//ֽ
(WCHAR *)p_out,
len//src.size()//size of buffer//עǻֽǿַĸ
);
//::MultiByteToWideChar(936, MB_PRECOMPOSED, gbBuffer, 2, pOut, 1);//936 ַ
//uncode ת CP_UTF8
//::WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK, (WCHAR *)p_out, word_count, p_out_utf8, len,
// WC_COMPOSITECHECK ת˵
word_count = ::WideCharToMultiByte(CP_UTF8, 0,
(WCHAR *)p_out,
word_count, // number of chars in string//ַĸ
p_out_utf8,
len,// size of buffer//ĴС
NULL, NULL);//CP_UTF8 UTF-8ôֵʱlpDefaultCharlpUsedDefaultCharΪNULL
std::string s = p_out_utf8;
free(p_out);
free(p_out_utf8);
return s;
/*
Code Value (Codepage) Alphabet
DIN_66003 20106 IA5 (German)
NS_4551-1 20108 IA5 (Norwegian)
SEN_850200_B 20107 IA5 (Swedish)
_autodetect 50932 Japanese (Auto Select)
_autodetect_kr 50949 Korean (Auto Select)
big5 950 Chinese Traditional (Big5)
csISO2022JP 50221 Japanese (JIS-Allow 1 byte Kana)
euc-kr 51949 Korean (EUC)
gb2312 936 Chinese Simplified (GB2312)
hz-gb-2312 52936 Chinese Simplified (HZ)
ibm852 852 Central European (DOS)
ibm866 866 Cyrillic Alphabet (DOS)
irv 20105 IA5 (IRV)
iso-2022-jp 50220 Japanese (JIS)
iso-2022-jp 50222 Japanese (JIS-Allow 1 byte Kana)
iso-2022-kr 50225 Korean (ISO)
iso-8859-1 1252 Western Alphabet
iso-8859-1 28591 Western Alphabet (ISO)
iso-8859-2 28592 Central European Alphabet (ISO)
iso-8859-3 28593 Latin 3 Alphabet (ISO)
iso-8859-4 28594 Baltic Alphabet (ISO)
iso-8859-5 28595 Cyrillic Alphabet (ISO)
iso-8859-6 28596 Arabic Alphabet (ISO)
iso-8859-7 28597 Greek Alphabet (ISO)
iso-8859-8 28598 Hebrew Alphabet (ISO)
koi8-r 20866 Cyrillic Alphabet (KOI8-R)
ks_c_5601 949 Korean
shift-jis 932 Japanese (Shift-JIS)
unicode 1200 Universal Alphabet
unicodeFEFF 1201 Universal Alphabet (Big-Endian)
utf-7 65000 Universal Alphabet (UTF-7)
utf-8 65001 Universal Alphabet (UTF-8)
windows-1250 1250 Central European Alphabet (Windows)
windows-1251 1251 Cyrillic Alphabet (Windows)
windows-1252 1252 Western Alphabet (Windows)
windows-1253 1253 Greek Alphabet (Windows)
windows-1254 1254 Turkish Alphabet
windows-1255 1255 Hebrew Alphabet (Windows)
windows-1256 1256 Arabic Alphabet (Windows)
windows-1257 1257 Baltic Alphabet (Windows)
windows-1258 1258 Vietnamese Alphabet (Windows)
windows-874 874 Thai (Windows)
x-euc 51932 Japanese (EUC)
x-user-defined 50000 User Defined
*/
}
// GB2312 ת unicode
std::wstring gbk_to_unicode(std::string src)
{
//int len = src.size() * 2 +1;//Сٴ
int len = (src.size()+1) * 4;//4
WCHAR * p_out = (WCHAR *)malloc(len);//LPWSTR
memset(p_out, 0, len);
//gbk ת unicode
//int word_count = ::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src.c_str(), src.size(), (WCHAR *)p_out, src.size());
int word_count = ::MultiByteToWideChar(936, MB_PRECOMPOSED,
src.c_str(),
src.size(), // number of bytes in string//ֽ
p_out,
len//src.size()//size of buffer//עǻֽǿַĸ
);
std::wstring s = p_out;
s.resize(word_count);//test//ʵһ⣬ʱ
free(p_out);
return s;
}
// unicode ת GB2312
std::string unicode_to_gbk(std::wstring src)
{
//int len = src.size() * 2 +1;//Сٴ
int len = (src.size()+1) * 4;//4
char * p_out_utf8 = (char *)malloc(len);
memset(p_out_utf8, 0, len);
WCHAR * p_out = (WCHAR *)src.c_str();
//uncode ת gbk
//int word_count = ::WideCharToMultiByte(936, 0, (WCHAR *)p_out, word_count, p_out_utf8, len,
int word_count = ::WideCharToMultiByte(936, 0, (WCHAR *)p_out, src.size(), p_out_utf8, len,
NULL, NULL);
std::string s = p_out_utf8;
//free(p_out);
free(p_out_utf8);
return s;
}
//ȡǰַ,עǺֵģֿܷһ
std::string left_string_cn(std::string src, int count)
{
std::wstring ws = gbk_to_unicode(src);
int src_count = ws.size();
if (count > src_count) count = src_count;//Խ
ws = substring_STL(ws, 0, count);
//ws = ws.substr(0, count);//test
std::string s = unicode_to_gbk(ws);
return s;
}
//ȡǰַ,עǺֵģֿܷһ
std::string sub_string_cn(std::string src, int begin, int count)
{
std::wstring ws = gbk_to_unicode(src);
int src_count = ws.size();
if (count > src_count) count = src_count;//Խ
//ws = substring_STL(ws, 0, count);
ws = substring_STL(ws, begin, count);
//ws = ws.substr(0, count);//test
std::string s = unicode_to_gbk(ws);
return s;
}
//windowsʱתΪtime_t
time_t get_time_t( const FILETIME ft )
{
time_t t;
FileTimeToUnixTime (&ft, &t, true);
return t;
}
std::string get_app_filename()
{
std::string r = "";
tmem t(MAX_PATH);//ͷʱڴ
char * buf = t.buf;
::GetModuleFileName(NULL, buf, MAX_PATH);
r = buf;
//printf("%s\r\n", r.c_str());
return r;
}
//ֻϷַ//Ҳᱻ
std::string clear_str(std::string s)
{
std::string r = "";
char c = 0;
for (int i = 0; i < s.size(); i++)
{
c = s[i];
if (
((c >= '0')&&( c <= '9'))
|| ((c >= 'a')&&( c <= 'z'))
|| ((c >= 'A')&&( c <= 'Z'))
|| (c == '_')
)
{
r += c;
}
/*
char * p = NULL;
p = strchr("_-",'5');
if (p != NULL)
{
r += c;
}
*/
}
return r;
}
#endif
////////////////////////////////////////////////////////////////
| true |
e7fbde90efa97b5aa426764ddde8af7fb4e07dca | C++ | jdmack/school-gfx | /src/light.cpp | UTF-8 | 3,031 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include "GL/glut.h"
#include "light.h"
#include "matrix4.h"
Light::Light()
{
number_ = 0;
enabled_ = false;
set_position(0.0, 0.0, 1.0, 1.0);
set_ambient(0.0, 0.0, 0.0, 1.0);
set_diffuse(1.0, 1.0, 1.0, 1.0);
set_specular(1.0, 1.0, 1.0, 1.0);
constant_atten_[0] = 1.0;
linear_atten_[0] = 0.0;
quadratic_atten_[0] = 0.0;
}
Light::Light(int number)
{
number_ = number;
enabled_ = false;
set_position(0.0, 0.0, 1.0, 1.0);
set_ambient(0.0, 0.0, 0.0, 1.0);
set_diffuse(1.0, 1.0, 1.0, 1.0);
set_specular(1.0, 1.0, 1.0, 1.0);
constant_atten_[0] = 1.0;
linear_atten_[0] = 0.0;
quadratic_atten_[0] = 0.0;
}
void Light::set_ambient(float a, float b, float c, float d)
{
ambient_[0] = a;
ambient_[1] = b;
ambient_[2] = c;
ambient_[3] = d;
}
void Light::set_specular(float a, float b, float c, float d)
{
specular_[0] = a;
specular_[1] = b;
specular_[2] = c;
specular_[3] = d;
}
void Light::set_diffuse(float a, float b, float c, float d)
{
diffuse_[0] = a;
diffuse_[1] = b;
diffuse_[2] = c;
diffuse_[3] = d;
}
void Light::set_position(float x, float y, float z, float w)
{
//std::cerr << "setting position: " << x << ", " << y << ", " << z << ", " << w << std::endl;
position_[0] = x;
position_[1] = y;
position_[2] = z;
position_[3] = w;
}
void Light::enable()
{
std::cerr << "Light " << number_ << " enabled" << std::endl;
//std::cerr << "Light " << number_ << " set" << std::endl;
Matrix4 matrix(true);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixd(matrix.pointer());
//std::cerr << "ambient: " << ambient_[0] << ", " << ambient_[1] << ", " << ambient_[2] << ", " << ambient_[3] << std::endl;
//std::cerr << "diffuse: " << diffuse_[0] << ", " << diffuse_[1] << ", " << diffuse_[2] << ", " << diffuse_[3] << std::endl;
//std::cerr << "specular_: " << specular_[0] << ", " << specular_[1] << ", " << specular_[2] << ", " << specular_[3] << std::endl;
glLightfv(GL_LIGHT0 + number_, GL_AMBIENT, ambient_);
glLightfv(GL_LIGHT0 + number_, GL_DIFFUSE, diffuse_);
glLightfv(GL_LIGHT0 + number_, GL_SPECULAR, specular_);
glLightfv(GL_LIGHT0 + number_, GL_POSITION, position_);
//glLightfv(GL_LIGHT0 + number_, GL_CONSTANT_ATTENUATION, constant_atten_);
//glLightfv(GL_LIGHT0 + number_, GL_LINEAR_ATTENUATION, linear_atten_);
//glLightfv(GL_LIGHT0 + number_, GL_QUADRATIC_ATTENUATION, quadratic_atten_);
glEnable(GL_LIGHT0 + number_);
enabled_ = true;
}
void Light::disable()
{
std::cerr << "Light " << number_ << " disabled" << std::endl;
enabled_ = false;
glDisable(GL_LIGHT0 + number_);
}
void Light::display()
{
if(!enabled_) return;
Matrix4 matrix(true);
matrix.translate(position_[0], position_[1], position_[2]);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixd(matrix.pointer());
glColor3f(0.0, 1.0, 0.0);
glutSolidSphere(0.2, 50, 50);
}
| true |
eece762cbe511d6580234df609fe4f69d56fb501 | C++ | lkramer37/CS302-Data-Structures | /PA09/PA09.3/Heap.cpp | UTF-8 | 8,023 | 3.640625 | 4 | [] | no_license | //Heap.cpp
#include <iostream>
#include <cmath>
#include "Heap.h"
using namespace std;
/**
@brief Default and Basic Constructor
@param maxNumber Maximum heap size
@post Creates an empty heap. Allocates enough memory for a heap containing maxNumber data items
*/
template < typename DataType, typename KeyType, typename Comparator >
Heap <DataType, KeyType, Comparator> :: Heap (int maxNumber)
{
dataItems = new DataType[maxNumber];
size = 0;
maxSize = maxNumber;
};
/**
@brief Copy constructor
@param other Address to the heap to be copied
@post Initializes the object to be an equivalent copy of other
@see {references}
*/
template < typename DataType, typename KeyType, typename Comparator >
Heap <DataType, KeyType, Comparator> :: Heap ( const Heap& other )
{
};
/**
@brief Overloaded Assignment Operator
@param other Address to the heap to be copied
@pre The address of this object cannot be the same as the address of other
@post Sets the heap to be equivalent to the other Heap
@return Reference to this object
@see {references}
*/
template < typename DataType, typename KeyType, typename Comparator >
Heap<DataType, KeyType, Comparator>& Heap <DataType, KeyType, Comparator> :: operator= ( const Heap& other )
{
};
/**
@brief Destructor
@post Deallocates the memory used to store the heap
@see {References}
*/
template < typename DataType, typename KeyType, typename Comparator >
Heap <DataType, KeyType, Comparator> :: ~Heap()
{
delete[] dataItems;
};
/**
@brief Insert
@param newDataItem Address of data item to be inserted
@pre Heap is not full
@post Inserts newDataItem into the heap.
@exception <exception-object> {exception description}
@note Inserts this data item as the bottom rightmost data item in the heap and moves it upward until the properties that define a heap are restored
@see {references}
*/
template < typename DataType, typename KeyType, typename Comparator >
void Heap <DataType, KeyType, Comparator> :: insert (const DataType &newDataItem ) throw ( logic_error )
{
if (isFull())
{
throw logic_error("Heap is Full");
}
if(!isFull())
{
++size;
dataItems[size-1] = newDataItem;
trickleUp(size-1);
}
};
template <typename DataType, typename KeyType, typename Comparator>
void Heap <DataType, KeyType, Comparator> :: trickleUp(int index)
{
if (index != 0)
{
DataType temp;
int parIndex;
if(index>2) { parIndex = parentIndex(index); }
else { parIndex = 0; }
if (comparator(dataItems[index].getPriority(), dataItems[parIndex].getPriority()))
{
temp = dataItems[parIndex];
dataItems[parIndex] = dataItems[index];
dataItems[index] = temp;
trickleUp(parIndex);
}
}
};
/**
@brief Remove
@pre Heap is not empty
@post Removes the data item with the highest priority (the root) from the heap and returns it.
@exception <exception-object> {exception description}
@note Replaces the root data item with the bottom rightmost data item and moves this data item downward until the properties that define a heap are restored
@return The root that is removed
@see {references}
*/
template < typename DataType, typename KeyType, typename Comparator >
DataType Heap <DataType, KeyType, Comparator> :: remove () throw (logic_error)
{
if (isEmpty())
{
throw logic_error("Heap is Empty");
}
//Copy the item from the last node and place it into the root
DataType removedItem = dataItems[0];
dataItems[0] = dataItems[size-1];
--size;
trickleDown(0);
return removedItem;
};
template < typename DataType, typename KeyType, typename Comparator >
void Heap <DataType, KeyType, Comparator> :: trickleDown( int index)
{
int right, left, larger;
right = rChildIndex(index);
left = lChildIndex(index);
//If there is either one or no children
if (right >= size) //If right child doesn't exist
{
if (left >= size) { return; } //If left child doesn't exist, done
else { larger = left; } //If only one child, this is the largest child
}
else //If 2 children exist, find larger child
{
if ( comparator(dataItems[left].getPriority(), dataItems[right].getPriority()))
{
larger = left;
}
else
{
larger = right;
}
}
//If parent is smaller than larger child, swap
if (comparator(dataItems[larger].getPriority(),dataItems[index].getPriority()))
{
DataType temp = dataItems[larger];
dataItems[larger] = dataItems[index];
dataItems[index] = temp;
trickleDown(larger);
}
};
/**
@brief Clear
@post Removes all the data items in the heap
@see {references}
*/
template < typename DataType, typename KeyType, typename Comparator >
void Heap <DataType, KeyType, Comparator> :: clear()
{
size = 0;
};
/**
@brief Empty Check
@return True if heap is empty. Otherwise, returns false.
*/
template < typename DataType, typename KeyType, typename Comparator >
bool Heap <DataType, KeyType, Comparator> :: isEmpty() const
{
if (size == 0) { return true; }
else { return false; }
};
/**
@brief Full Check
@return True if heap is full. Otherwise, returns false.
*/
template < typename DataType, typename KeyType, typename Comparator >
bool Heap <DataType, KeyType, Comparator> :: isFull() const
{
if (size == maxSize) {return true;}
return false;
};
/**
@brief Show Structure
@post Outputs the priorities of the data items in the heap in both array and tree form. The tree is output with its branches oriented from left (root) to right (leaves) - that is, the tree is output rotated counterclockwise ninety degrees from its conventional orientation. If the heap is empty, outputs "Empty Heap".
@note Intended for testing/debugging purposes only
*/
template < typename DataType, typename KeyType, typename Comparator >
void Heap<DataType,KeyType,Comparator>:: showStructure () const
{
int j; // Loop counter
cout << endl;
if ( size == 0 )
cout << "Empty heap" << endl;
else
{
cout << "size = " << size << endl; // Output array form
for ( j = 0 ; j < maxSize ; j++ )
cout << j << "\t";
cout << endl;
for ( j = 0 ; j < size ; j++ )
cout << dataItems[j].getPriority() << "\t";
cout << endl << endl;
showSubtree(0,0); // Output tree form
}
};
/**
@brief Output in level order
@pre {description of the precondition}
@post {description of the postcondition}
@note {text }
@see {Reference}
*/
template < typename DataType, typename KeyType, typename Comparator >
void Heap <DataType, KeyType, Comparator> :: writeLevels() const
{
int row = 1;
for(int i = 0; i < size; i++)
{
if(exp2(row) == (i + 1))
{
cout << endl;
row++;
}
cout << dataItems[i].getPriority() << " ";
}
cout << endl;
};
/**
@brief Show Structure Helper
@param level The level of this data Items within the tree
@post Helper function for the showStructure() function. Outputs the subtree (subheap) whose root is stored in dataItems[index].
*/
template < typename DataType, typename KeyType, typename Comparator >
void Heap <DataType, KeyType, Comparator> :: showSubtree (int index, int level) const
{
int j; // Loop counter
if ( index < size )
{
showSubtree(2*index+2,level+1); // Output right subtree
for ( j = 0 ; j < level ; j++ ) // Tab over to level
cout << "\t";
cout << " " << dataItems[index].getPriority(); // Output dataItems's priority
if ( 2*index+2 < size ) // Output "connector"
cout << "<";
else if ( 2*index+1 < size )
cout << "\\";
cout << endl;
showSubtree(2*index+1,level+1); // Output left subtree
}
};
| true |
20b14fc9731b5ab3d05ad02a55c4490e5c9dae7b | C++ | smmousavi76/chess | /Pieces/Pawn.cpp | UTF-8 | 2,333 | 2.859375 | 3 | [] | no_license | #include "Pawn.h"
Pawn::Pawn(int owner,int count):Piece(owner)
{
if(owner == 0)//white
{
typeId=5;
pos.yPos=1;
pos.xPos =count;
pos.yPos = 1;
}
else if(owner == 1)//black
{
typeId=11;
pos.xPos =count;
pos.yPos = 6;
}
isFirstMove = 1;
enemy=0;
}
std::vector <Posiotion> Pawn::PossibleMove(int owner)
{
// int count1;
std::vector<Posiotion> possibleMoves;
int First_x=pos.xPos;
int First_y=pos.yPos;
if (owner == 0){
if(isFirstMove){
Posiotion a;
a.xPos=First_x;
a.yPos=pos.yPos+1;
possibleMoves.push_back(a);
a.yPos=pos.yPos+2;
possibleMoves.push_back(a);
isFirstMove = false;
}
else{
Posiotion a;
a.xPos=First_x;
a.yPos=First_y;
a.yPos=pos.yPos+1;
possibleMoves.push_back(a);
if(enemy==1)
{
a.xPos=First_x;
a.yPos=First_y;
a.xPos=pos.xPos+1;
a.yPos=pos.yPos+1;
possibleMoves.push_back(a);
a.xPos=First_x;
a.yPos=First_y;
a.xPos=pos.xPos-1;
a.yPos=pos.yPos+1;
possibleMoves.push_back(a);
}
}
return possibleMoves;
}
else {
if(isFirstMove){
Posiotion a;
a.xPos=First_x;
a.yPos=pos.yPos-1;
possibleMoves.push_back(a);
a.yPos=pos.yPos-2;
possibleMoves.push_back(a);
isFirstMove=false;
}
//count1++;
else
{
Posiotion a;
a.xPos=First_x;
a.yPos=First_y;
a.yPos=pos.yPos-1;
possibleMoves.push_back(a);
if(enemy==1)
{
a.xPos=First_x;
a.yPos=First_y;
a.xPos=pos.xPos-1;
a.yPos=pos.yPos-1;
possibleMoves.push_back(a);
a.xPos=First_x;
a.yPos=First_y;
a.xPos=pos.xPos+1;
a.yPos=pos.yPos-1;
possibleMoves.push_back(a);
}
}
count1++;
return possibleMoves;
}
}
Pawn::~Pawn()
{
}
| true |
7907a38d799617641660e8d6f4009037518be56e | C++ | asheplyakov/mutex-internals-talk | /mutex_test.cc | UTF-8 | 1,554 | 3.0625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <functional>
#include <mutex>
#include <thread>
#include <chrono>
#include "peterson.h"
#ifdef USE_STD_MUTEX
typedef std::mutex lock_t;
static void lock(std::mutex& lk, int /* id */) {
lk.lock();
}
static void unlock(std::mutex& lk, int /* id */) {
lk.unlock();
}
#else
typedef peterson_spinlock lock_t;
static void lock(peterson_spinlock& lk, int id) {
peterson_lock(&lk, id);
}
static void unlock(peterson_spinlock& lk, int id) {
peterson_unlock(&lk, id);
}
#endif
static volatile int flag = -1;
static volatile int error_count = 0;
static lock_t flag_lock = {};
static void run(int id, int iterations, int busyloop_nsecs) {
using rolex = std::chrono::high_resolution_clock;
for (int i = 0; i < iterations; i++) {
lock(flag_lock, id);
flag = id;
auto end = rolex::now() + std::chrono::nanoseconds(busyloop_nsecs);
do {
if (flag != id) {
error_count++;
}
} while (rolex::now() < end);
unlock(flag_lock, id);
}
}
int main(int argc, char **argv) {
int iterations = std::atoi(argc > 1 ? argv[1] : "0");
if (!iterations) {
iterations = 1000*1000*100;
}
int busyloop_nsecs = std::atoi(argc > 2 ? argv[2] : "0");
if (busyloop_nsecs < 10) {
busyloop_nsecs = 10;
}
std::thread t0{run, 0, iterations, busyloop_nsecs};
std::thread t1{run, 1, iterations, busyloop_nsecs};
t0.join();
t1.join();
if (error_count != 0) {
std::printf("iterations: %d, errors: %d, busy loop duration %d nsec\n",
iterations, error_count, busyloop_nsecs);
}
return error_count != 0;
}
| true |
3aae306af8e587a055bed56241d2c5e3cad17587 | C++ | Pywwo/rtype | /commons/network/datagram/EnemyDeathDatagram.hpp | UTF-8 | 1,356 | 2.53125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** rtype
** File description:
** EnemyDeathDatagram.hpp
*/
/* Created the 24/11/2019 at 17:41 by jbulteau */
#ifndef RTYPE_ENEMYDEATHDATAGRAM_HPP
#define RTYPE_ENEMYDEATHDATAGRAM_HPP
#include "RtypeDatagram.hpp"
/*!
* @namespace rtype
* @brief Main namespace for all rtype project
*/
namespace rtype {
/*!
* @namespace rtype::network
* @brief Main namespace for all networking
*/
namespace network {
/*!
* @class EnemyDeathDatagram
* @brief Datagram for enemy death command
*/
class EnemyDeathDatagram : public RtypeDatagram {
public:
/*!
* @brief ctor
*/
EnemyDeathDatagram() = default;
/*!
* @brief dtor
*/
~EnemyDeathDatagram() = default;
/*!
* @brief Create datagram for enemy death command
* @param enemyId The id of the dead enemy
*/
void createEnemyDeathDatagram(uint64_t enemyId);
/*!
* @brief Extract enemy id from datagram
* @param enemyId The id of the dead enemy filled with datagram's content
*/
void extractEnemyDeathDatagram(uint64_t &enemyId);
};
}
}
#endif //RTYPE_ENEMYDEATHDATAGRAM_HPP
| true |
d57642dbe249522519e05a0662dc80812b6266fe | C++ | GregoryBen/cp-lib | /hash_function.cpp | UTF-8 | 550 | 2.515625 | 3 | [] | no_license | struct my_hash {
const uint64_t RANDOM = chrono::steady_clock::now().time_since_epoch().count();
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
return (size_t) splitmix64(x + RANDOM);
}
size_t operator()(pair<uint64_t, uint64_t> x) const {
return (size_t) splitmix64(x.first + RANDOM) ^
((size_t) splitmix64(x.second + RANDOM) >> 1);
}
};
| true |
b03a950b7682242be3294ceb7784e33b5b3e97b6 | C++ | alvas/ms_interview_100 | /leetcode/FizzBuzz.cpp | UTF-8 | 780 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include "NormalData.h"
using namespace std;
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
for (int i = 1; i <= n; ++i) {
int a = i % 3, b = i % 5;
if (!a && !b) {
res.push_back("FizzBuzz");
}
else if (!a) {
res.push_back("Fizz");
}
else if (!b) {
res.push_back("Buzz");
}
else {
res.push_back(to_string(i));
}
}
return res;
}
};
int main() {
Solution sln;
int n = 15;
vector<string> v = sln.fizzBuzz(n);
printVector<string>(v);
return 0;
}
| true |
3a67d36a191b6423e80e65ce9d1f71cf0376a082 | C++ | AlexRogalskiy/Duino | /arduino/microphone_can_you_hear_pin_drop/microphone_can_you_hear_pin_drop.ino | UTF-8 | 317 | 2.578125 | 3 | [
"MIT"
] | permissive | // microphone_can_you_hear_pin_drop.ino - print to serial when sound is heard
// (c) BotBook.com - Karvinen, Karvinen, Valtokari
const int audioPin = A0;
void setup() {
Serial.begin(115200);
}
void loop() {
int soundWave = analogRead(audioPin); // 1
if (soundWave>600) { // 2
Serial.println("Sound!");
}
delay(10);
}
| true |
3b4422b31e9a4562a348019549108c9d1eb5b950 | C++ | demetoir/ps-solved-code | /boj/4354 문자열 제곱.cpp | WINDOWS-1252 | 1,236 | 2.59375 | 3 | [] | no_license | //4354 ڿ
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
#include <math.h>
#include <functional>
#include <utility>
#define ll long long
#define pii pair<int, int>
#define si(a) scanf("%d", &(a))
#define sc(a) scanf("%c", &(a))
#define ss(a) scanf("%s",a)
#define sll(a) scanf("%lld", &(a))
#define pi(a) printf("%d\n", (a))
#define pc(a) printf("%c",a);
#define ENDL printf("\n");
#define pll(a) printf("%lld\n", (a))
#define INF 2e9
#define all(a) (a).begin(),(a).end()
#define MAX_N 1000001
using namespace std;
vector<int> make_pie(string &str) {
int n = str.size();
vector <int> pie(n);
int start = 1;
int match = 0;
while (start + match < n) {
if (str[start + match] == str[match]) {
match++;
pie[start + match - 1] = match;
}
else {
if (match == 0) start++;
else {
start += match - pie[match - 1];
match = pie[match - 1];
}
}
}
return pie;
}
char buff[MAX_N];
int main() {
while (1) {
ss(buff);
if (string(".") == string(buff))
break;
string str(buff);
vector<int>pie;
int n = str.size();
pie = make_pie(str);
int ans = n - pie[n - 1];
printf("%d\n", ans);
return 0;
}
}
| true |
1b88633c7192b3ac363e35c427512d79b30e591d | C++ | basbeu/Scorpions-et-gerbilles | /partie6/src/Environment/Wave.cpp | UTF-8 | 2,699 | 2.859375 | 3 | [] | no_license | /*
* Project : infoSV 2019
* Author : Bastien Beuchat
*/
#include <Environment/Wave.hpp>
#include <Obstacle/Obstacle.hpp>
#include <Utility/Vec2d.hpp>
#include <Utility/Constants.hpp>
#include <Utility/Utility.hpp>
#include <Application.hpp>
#include <math.h>
#include <list>
#include <utility>
#include <SFML/Graphics.hpp>
Wave::Wave(Vec2d const& origin, double energyLevel, double initialRadius, double mu, double propagationSpeed)
:CircularCollider (origin,initialRadius)
,initialEnergyLevel_(energyLevel)
,initialRadius_(initialRadius)
,mu_(mu)
,propagationSpeed_(propagationSpeed)
,timer_(sf::Time::Zero)
{
arcs_.push_back(Arc(0, 2 * PI));
}
Wave::~Wave()
{
}
void Wave::draw(sf::RenderTarget& target) const
{
for(auto& arc:arcs_) {
target.draw(buildArc(arc.first/DEG_TO_RAD, arc.second/DEG_TO_RAD, getRadius(), getPosition(), sf::Color::Black, 0, getAppConfig().wave_intensity_thickness_ratio * getIntensity()));
}
}
void Wave::update(sf::Time dt)
{
timer_ += dt;
setRadius(propagationSpeed_ * timer_.asSeconds() + initialRadius_);
std::list<Obstacle const*> obstacles = getAppEnv().getObstacleColliding(this);
for(auto& obstacle:obstacles) {
double obstacleAngle(computeRelativeAngle(obstacle->getPosition()));
Arc arcColliding = findArcColliding(obstacleAngle) ;
if(arcColliding != Arc(0,0)) {
double separationAngle(std::atan2(obstacle->getRadius(), getRadius() + obstacle->getRadius()));
arcs_.remove(arcColliding);
arcs_.push_back(Arc(arcColliding.first,obstacleAngle - separationAngle));
arcs_.push_back(Arc(obstacleAngle + separationAngle, arcColliding.second));
}
}
}
double Wave::getEnergy() const
{
return initialEnergyLevel_ * exp(-getRadius()/mu_);
}
double Wave::getIntensity() const
{
return getEnergy()/(2 * PI * getRadius());
}
double Wave::getIntensityAt(Vec2d const& position) const
{
double margin(getAppConfig().wave_on_wave_marging);
double distance((position-getPosition()).length());
if(distance > getRadius() - margin
&& distance < getRadius() + margin
&& findArcColliding(computeRelativeAngle(position)) != Arc(0,0)) {
return getIntensity();
}
return 0.0;
}
Wave::Arc Wave::findArcColliding(double obstacleAngle) const
{
for(auto& arc:arcs_) {
if(obstacleAngle >= arc.first && obstacleAngle <= arc.second) {
return arc;
}
}
return Arc(0,0);
}
double Wave::computeRelativeAngle(Vec2d const& position) const
{
double angle((position - getPosition()).angle());
if(angle < 0)
angle += 2*PI;
return angle;
}
| true |
8ef56d50a023767961991c85a85c20ede752e4ae | C++ | PanYuer/IntermediateCpp | /22B_H_6/Program_6C/LinkedList.hpp | UTF-8 | 710 | 3.234375 | 3 | [] | no_license | // Specification file for the LinkedList class
// Written By: Pan Yue
// IDE: VS Code
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "College.hpp"
class LinkedList
{
private:
// Declare a structure for the list
struct ListNode
{
College college; // The value in this node
ListNode *next; // To point to the next node
};
ListNode *head; // List head pointer
public:
LinkedList(); // Constructor
~LinkedList(); // Destructor
// Linked list operations
int count() const;
bool insertNode(College);
bool deleteNode(string);
void displayList() const;
const College *searchNode(string) const;
};
#endif
| true |
df4886aeb6558d0b83497fd9a3682741598d4690 | C++ | tuxaco/Ajedrez_C | /entrega/Movimiento.cc | UTF-8 | 943 | 3.03125 | 3 | [] | no_license | /*Alberto Castillo 53241547-C || Alberto Manuel Cervantes Bañón 74246650-M*/
#include "Movimiento.h"
Movimiento Movimiento::movimientoError;
Movimiento::Movimiento(){}
Movimiento::Movimiento(string s)
{
if (s.length()==4)
{
origen=Coordenada(s[1],s[0]);
destino=Coordenada(s[3],s[2]);
}
else
{
*this=movimientoError;
}
}
Movimiento::Movimiento(const Coordenada &origen, const Coordenada &destino)
{
this->origen=origen;
this->destino=destino;
}
Movimiento::Movimiento(const Movimiento &m)
{
origen=m.origen;
destino=m.destino;
}
void Movimiento::setOrigen(const Coordenada &origen)
{
this->origen=origen;
}
void Movimiento::setDestino(const Coordenada &destino)
{
this->destino=destino;
}
Coordenada Movimiento::getOrigen() const
{
return origen;
}
Coordenada Movimiento::getDestino() const
{
return destino;
}
bool Movimiento::isError() const
{
bool error=false;
if(origen.isError() || destino.isError())
{
error=true;
}
return error;
}
| true |
61b3c97e0c14153ba2959e2cd05998404fcf7ab0 | C++ | patiwwb/placementPreparation | /Trees/BinaryTrees/printNodesAtKDistance.cpp | UTF-8 | 663 | 3.453125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node *left,*right;
Node(int x){
data=x;
}
};
void printNodesAtKDistance(Node *root,int k){
if(root==NULL)return;
if(k==0){
cout<<root->data<<" ";
return;
}
else{
printNodesAtKDistance(root->left,k-1);
printNodesAtKDistance(root->right,k-1);
}
}
int main(){
Node *root=new Node(1);
root->left=new Node(2);
root->right=new Node(3);
root->left->left=new Node(4);
root->left->right=new Node(5);
root->right->left=new Node(6);
root->right->left->left=new Node(7);
root->right->left->right=new Node(8);
int k=3;
printNodesAtKDistance(root,k);
}
| true |
c94169fe8a6234e07c4de351b7402d81161bc789 | C++ | roblapp/uva_online_judge | /UVA939_Genes/main.cpp | WINDOWS-1250 | 2,602 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
/*
Accepted: 0.009s
Description: data structures - maps, recursion
*/
#define read cin
#define DOMINANT "dominant"
#define RECESSIVE "recessive"
#define NON_EXISTENT "non-existent"
using namespace std;
class Entry {
public:
vector<string> parents;
string status;
Entry() {
status = "";
}
};
bool hasGene(string status) {
if (status.empty())
return false;
if (status == RECESSIVE || status == DOMINANT)
return true;
return false;
}
string getStatus(map<string, Entry*> &m, Entry *e) {
if (e->status.empty()) {
vector<string> parents = e->parents;
if (parents.size() == 0) { /* Not sure if this can ever happen */
e->status = NON_EXISTENT;
return NON_EXISTENT;
}
string pa, pb;
Entry *ea = m.find(parents[0])->second;
pa = (ea->status.empty()) ? getStatus(m, ea) : ea->status;
Entry *eb = m.find(parents[1])->second;
pb = (eb->status.empty()) ? getStatus(m, eb) : eb->status;
bool hasA = hasGene(pa);
bool hasB = hasGene(pb);
/* the child has the gene if, and only if, both parents have it or it is dominant in one of the parents */
if ((hasA && hasB) || (pa == DOMINANT) || (pb == DOMINANT)) {
/* the childs gene is dominant if, and only if, the gene is dominant in both parents
or dominant in one and recessive in the other parent */
if ((pa == DOMINANT && pb == DOMINANT) ||
(pa == DOMINANT && pb == RECESSIVE) ||
(pa == RECESSIVE && pb == DOMINANT)) {
e->status = DOMINANT;
return DOMINANT;
}
e->status = RECESSIVE;
return RECESSIVE;
}
e->status = NON_EXISTENT;
return NON_EXISTENT;
} else { /* Status is empty */
return e->status;
}
}
int main() {
int n;
string a, b;
map<string, Entry*> m;
vector<string> parents;
read >> n; getline(read, a);
while (n--) {
read >> a >> b;
if (m.find(a) == m.end())
m[a] = new Entry;
if (b == "non-existent" || b == "recessive" || b == "dominant")
m[a]->status = b;
else {
if (m.find(b) == m.end())
m[b] = new Entry;
m[b]->parents.push_back(a);
}
}
for (map<string, Entry*>::iterator it = m.begin(); it != m.end(); it++)
cout << it->first << " " << getStatus(m, it->second) << endl;
return 0;
}
| true |
7baecf21e895fbf800586f1ba3b4a697e0f07d6b | C++ | normanlew/CS300-Assignment-4 | /LinkedList.h | UTF-8 | 4,255 | 3.921875 | 4 | [] | no_license | #ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
#include <fstream>
using namespace std;
template <class T>
struct node{
T data;
node<T>* next;
};
template <class T>
class LinkedList{
protected:
node<T> *head, *last;
int count;
public:
LinkedList();
bool is_empty();
int length();
void insert_first(T&);
void insert_last(T&);
void print();
bool contains(T&);
int numOfOccurrences(T&);
template <class U>
friend ostream& operator<< (ostream& os, LinkedList<U>& list);
template <class U>
friend void printLinkedList(LinkedList<U> &c);
node<T>* search(T&);
void delete_node(T&);
T back();
T front();
void destroy_list();
virtual ~LinkedList();
private:
void copy_list(LinkedList<T> otherlist);
};
//initializing the list: constructor
template <class T>
LinkedList<T>::LinkedList(){
//cout<<"Initializing list..."<<endl;
head = NULL;
last = NULL;
count = 0;
}
//check if list is empty
template <class T>
bool LinkedList<T>::is_empty(){
return head==NULL;
}
// check to see if the list contains an item
template<class T>
bool LinkedList<T>::contains(T& c)
{
node<T> *temp = head;
while (temp != NULL)
{
if (temp->data == c)
{
return true;
}
}
return false;
}
//get the number of nodes in the list
template <class T>
int LinkedList<T>::length(){
return count;
}
//insert a new element to the front
template <class T>
void LinkedList<T>::insert_first(T& item){
node<T>* current = new node<T>;
current->data = item;
current->next = NULL;
if(head != NULL){
current->next = head;
head = current;
}else{
head = last = current;
}
count++;
}
//insert a new item at the end of the list
template <class T>
void LinkedList<T>::insert_last(T& item){
node<T>* current = new node<T>;
current->data = item;
current->next=NULL;
if(head != NULL){
last->next = current;
last = current;
}else{
head=last=current;
}
count++;
}
template <class U>
ostream& operator<< (ostream& os, LinkedList<U>& list){
node<U>* temp = list.head;
while(temp != NULL){
os<<temp->data<<" ";
temp = temp->next;
}
return os;
}
template <class T>
node<T>* LinkedList<T>::search(T& item){
node<T>* temp = head;
while(head != NULL && temp->data!=item){
temp = temp->next;
}
return temp;
}
template <class T>
void LinkedList<T>::delete_node(T& item){
node<T> *p, *q;
if (head == NULL)
cout<<"List is empty..."<<endl;
else
if(head->data == item){
p = head;
head= head->next;
delete p;
count--;
if (head==NULL)
last = NULL;
}else{
p= head;
q = head->next;
while(q!=NULL && q->data!=item){
p = q;
q = q->next;
}
if (q==NULL)
cout<<"item is not found";
else{
p->next = q->next;
if (q->next==NULL)
last = p;
delete q;
count--;
}
}
}
template <class T>
T LinkedList<T>::back(){
assert(last!=NULL);
return last->data;
}
template <class T>
T LinkedList<T>::front(){
assert(head!=NULL);
return head->data;
}
template <class T>
void LinkedList<T>::destroy_list(){
node<T>* p;
while(head != NULL){
p = head;
head = head->next;
delete p;
}
last = NULL;
count = 0;
}
//destructor
template <class T>
LinkedList<T>::~LinkedList(){
cout<<"List is destroyed..."<<endl;
destroy_list();
}
// Prints the entire linked list
template <class U>
void printLinkedList(LinkedList<U> &c)
{
c.print();
cout << endl;
}
template <class T>
void LinkedList<T>::print()
{
node<T> * tempNode = head;
while (tempNode != NULL)
{
cout << tempNode->data << endl;
tempNode = tempNode->next;
}
}
// This function returns the number of occurrences of an item in the list
template<class T>
int LinkedList<T>::numOfOccurrences(T& c)
{
int num = 0;
node<T> * tempNode = head;
while (tempNode != NULL)
{
if (tempNode->data == c)
{
num++;
}
tempNode = tempNode->next;
}
return num;
}
#endif /* LINKEDLIST_H_ */
| true |
2424ae9792bfa6a62a13003324ff0e5974e8a3e7 | C++ | indexte/Labs-2sem | /Lab3a/Swap.cpp | UTF-8 | 106 | 2.578125 | 3 | [] | no_license | #include"Swap.h"
void swapM(Integers & x, Integers & y)
{
Integers temp = x;
x = y;
y = temp;
} | true |
b40b74384640bcbb2b3b270b1199d030823fc2ab | C++ | seacmonster/CS-172-Homework | /Ex03_04/Ex03_04/ex03_04.cpp | UTF-8 | 669 | 3.921875 | 4 | [] | no_license | //Colin Bondy
//EX03-04
//This is like the exercise we did the last day of class with everyone
#include <iostream>
#include <string>
using namespace std;
string sort(string &s)
{
for (int i = s.length() - 1; i >= 1; i--)// Finds the max
{
char Max = s[0];
int Maxvalue = 0;
for (int j = 1; j <= i; j++)
{
if (Max < s[j])
{
Max = s[j];
Maxvalue = j;
}
}
if (Maxvalue != i)//Swaps values
{
s[Maxvalue] = s[i];
s[i] = Max;
}
}
return s;
}
int main()
{
cout << "Enter a string s: "; //Asks for input string of characters
string s;
getline(cin, s);
cout << "The sorted string is " << sort(s) << endl << endl;
return 0;
}
| true |
ae02affe172d861cf1976925522a70a4314e03ca | C++ | Demorro/AMG_Teaching_Repo | /AMG Teaching/TweeningText.cpp | UTF-8 | 1,390 | 2.796875 | 3 | [] | no_license | #include "TweeningText.h"
TweeningText::TweeningText(sf::Font &font, int textSize, sf::Vector2f position, std::string initialString, bool shouldTweenIn, bool lockedToCamera, Camera *camera) : TweenableElement(shouldTweenIn, position)
{
text.setFont(font);
text.setCharacterSize(textSize);
text.setString(initialString);
text.setOrigin(text.getGlobalBounds().width/2, text.getGlobalBounds().height/2);
text.setPosition(position);
this->shouldTweenIn = shouldTweenIn;
this->isLockedToCamera = lockedToCamera;
this->gameCam = camera;
ResetTween();
}
TweeningText::~TweeningText(void)
{
}
void TweeningText::Update(sf::Event events, bool eventFired, double deltaTime)
{
DoTweenLogic(deltaTime,text);
}
void TweeningText::Render(sf::RenderWindow& window)
{
if(isLockedToCamera)
{
if(gameCam != nullptr)
{
text.move(gameCam->GetScreenSpaceOffsetVector());
window.draw(text);
text.move(-gameCam->GetScreenSpaceOffsetVector());
}
}
else
{
window.draw(text);
}
}
void TweeningText::SetText(std::string newText)
{
text.setString(newText);
}
void TweeningText::SetTextColor(sf::Color textColor)
{
text.setColor(textColor);
}
sf::Vector2f TweeningText::GetPosition()
{
return text.getPosition();
}
sf::Rect<float> TweeningText::GetLocalBounds()
{
return text.getLocalBounds();
}
void TweeningText::Move(sf::Vector2f movement)
{
text.move(movement);
} | true |
4a505c13fd976f6cfd11d8ab2813bac9c22210bf | C++ | SmirnovaES/mipt-archives | /algorithms 3 sem/C_Floyd/tests/InputTest.cpp | UTF-8 | 1,220 | 3.3125 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "Graph.h"
using testing::Eq;
namespace {
class ClassDeclaration2: public testing::Test {
public:
Graph obj2;
ClassDeclaration2 () {
obj2;
}
};
}
TEST_F(ClassDeclaration2, InputTest) {
std::istringstream ss("5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25");
Graph graph;
ss >> graph;
EXPECT_EQ(1, graph[0][0]);
EXPECT_EQ(2, graph[0][1]);
EXPECT_EQ(3, graph[0][2]);
EXPECT_EQ(4, graph[0][3]);
EXPECT_EQ(5, graph[0][4]);
EXPECT_EQ(6, graph[1][0]);
EXPECT_EQ(7, graph[1][1]);
EXPECT_EQ(8, graph[1][2]);
EXPECT_EQ(9, graph[1][3]);
EXPECT_EQ(10, graph[1][4]);
EXPECT_EQ(11, graph[2][0]);
EXPECT_EQ(12, graph[2][1]);
EXPECT_EQ(13, graph[2][2]);
EXPECT_EQ(14, graph[2][3]);
EXPECT_EQ(15, graph[2][4]);
EXPECT_EQ(16, graph[3][0]);
EXPECT_EQ(17, graph[3][1]);
EXPECT_EQ(18, graph[3][2]);
EXPECT_EQ(19, graph[3][3]);
EXPECT_EQ(20, graph[3][4]);
EXPECT_EQ(21, graph[4][0]);
EXPECT_EQ(22, graph[4][1]);
EXPECT_EQ(23, graph[4][2]);
EXPECT_EQ(24, graph[4][3]);
EXPECT_EQ(25, graph[4][4]);
}
| true |
ce35cbe629fceb15fe2b8e7f48f999cbc1a49c57 | C++ | human-osaka-game-2018/DeepSee-Stars | /DeepSee_Stars/DeepSee_Stars/Device/DirectXDevices/DeviceFactory/DeviceFactory.h | UTF-8 | 1,315 | 2.703125 | 3 | [] | no_license | #ifndef DEVICE_FACTORY_H_
#define DEVICE_FACTORY_H_
#include "../../DirectXDevice/DirectXDevice.h"
#include "../../DirectXGraphicDevice/DirectXGraphicDevice.h"
#include "../../DirectXInputDevice/DirectXInputDevice.h"
namespace device
{
/// <summary>
/// デバイス生成クラス
/// </summary>
class DeviceFactory
{
public:
/// <summary>
/// DirectXのデバイスを生成する
/// </summary>
/// <param name="ppD3D">DirectXのデバイスのポインタ</param>
static void Create(DirectXDevice** pDXDev)
{
*pDXDev = new DirectXDevice();
}
/// <summary>
/// DirectInputのデバイスを生成する
/// </summary>
/// <param name="ppDXInput">DInputのデバイスのポインタ</param>
static void Create(DirectXInputDevice** pDXInput)
{
*pDXInput = new DirectXInputDevice();
}
/// <summary>
/// DirectXの描画デバイスを生成する
/// </summary>
/// <param name="pDXGraphicDev">DirectXの描画のデバイスのポインタ</param>
/// <param name="pDXDev">DirectXのデバイスのポインタ</param>
static void Create(DirectXGraphicDevice** pDXGraphicDev, DirectXDevice* pDXDev)
{
*pDXGraphicDev = new DirectXGraphicDevice(pDXDev);
}
private:
DeviceFactory() {}
~DeviceFactory() {}
};
}
#endif // !DEVICE_FACTORY_H_
| true |
043df1547a48bc4750c58c13f18e641d7633c75e | C++ | lbr15/QT_Learn | /Qtimer/Qtimer/mainwindow.cpp | UTF-8 | 668 | 2.8125 | 3 | [] | no_license | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
#include "QKeyEvent"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
id1=startTimer(1000); //赋值时间 延时1000ms 每过1000ms溢出;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent *qevent)
{
if(qevent->key()==Qt::Key_0)
{
qDebug() << "Pressed Key_0";
}
}
void MainWindow::timerEvent(QTimerEvent *event)
{
if(event->timerId()==id1) //然后用event->timerid==id 引用这个溢出id就可以了.
{
qDebug () << "ddd";
}
}
| true |
9e22ab0ceed8f87947a99a4242ec43dbda06b79b | C++ | blueskyyun/codeCPP_vs | /OSExperimentSum/OSsimulation/OSsimulation/PCB.h | UTF-8 | 587 | 2.578125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
using std::string;
class PCB
{
private:
string processName;
//PCB* nextPCB;
int runTimeRequest;
int priority;
char state;
public:
PCB();
PCB(string pName);
PCB(string pName, int runTimeRequest, int priority);
string getProcessName();
//void setNextPCB(PCB* nPCB);
//PCB* getNextPCB();
void setRunTimeRequest(int runT);
int getRunTimeRequest();
void setPriority(int pri);
int getPriority();
void setState(char s);
char getState();
bool operator==(const PCB& pcb);
~PCB();
};
| true |
86a5a6de68d0540294fc4ae1682119b32b9a6194 | C++ | RogerGee/traffic-sim | /src/light.cpp | UTF-8 | 1,838 | 2.796875 | 3 | [] | no_license | // light.cpp - trafficsim
#include "light.h"
#include "opengl.h"
using namespace trafficsim;
light::light(bool on) : green_time(DEFAULT_LIGHTSPEED()), step_counter(0)
{
if (!on)
step_counter = green_time + YELLOW_TIME;
}
light_state light::get_state() const
{
if (step_counter < green_time)
return light_state_green;
if (step_counter < green_time + YELLOW_TIME)
return light_state_yellow;
return light_state_red;
}
void light::step()
{
step_counter = (step_counter + 1) % (green_time*2 + YELLOW_TIME*2);
}
void light::draw(point pos, size sz, direction d)
{
glPushMatrix();
glTranslated(pos.x, pos.y, 0);
glRotated(90 * int(d),0,0,1);
glColor3f(.4,.4,.4);
glBegin(GL_POLYGON);
glVertex2d(sz.width/2, sz.height/2+3);
glVertex2d(sz.width/2+1, sz.height/2+3);
glVertex2d(sz.width/2+1, sz.height/2);
glVertex2d(sz.width/2, sz.height/2);
glEnd();
double y = 0;
switch(get_state())
{
case light_state_green:
glColor3f(0,0.8,0);
y = 2;
break;
case light_state_yellow:
glColor3f(1,1,0);
y = 1;
break;
case light_state_red:
glColor3f(1,0,0);
y = 0;
break;
}
glBegin(GL_POLYGON);
{
glVertex2d(sz.width/2+.1, sz.height/2+2.9-y);
glVertex2d(sz.width/2+.9, sz.height/2+2.9-y);
glVertex2d(sz.width/2+.9, sz.height/2+2.1-y);
glVertex2d(sz.width/2+.1, sz.height/2+2.1-y);
}
glEnd();
glPopMatrix();
}
void light::update_rate(int greentime)
{
if (step_counter >= green_time + YELLOW_TIME)
{
int step = step_counter - (green_time+YELLOW_TIME);
step_counter = (greentime+YELLOW_TIME+step) % (greentime*2+YELLOW_TIME*2);
}
green_time = greentime;
}
int light::get_rate() const
{
return green_time;
}
| true |
68010f0c0039048663a0298f7df202cbb365a936 | C++ | melugoyal/icpc | /faculty_div_powers/gcpc11a.cpp | UTF-8 | 836 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
long dp_fact(long);
long rec_fact(long);
int main()
{
int tests = 0;
cin >> tests;
for (int a = 0; a < tests; a++)
{
long n = 0;
long k = 0;
cin >> n;
cin >> k;
long fact_n = rec_fact(n);
long max_i = 0;
for (long i = 1; i < 10; i++)
{
if (fmod(fact_n, pow((double)k, (double)i)) == 0 && (i > max_i))
max_i = i;
}
cout << max_i << endl;
}
}
long dp_fact(long a)
{
long result[a];
result[0]=1;
for (int i = 1; i <= a; i++)
{
result[i] = i*result[i-1];
}
return result[a];
}
long rec_fact(long a)
{
if (a==0)
return 1;
return a*rec_fact(a-1);
}
| true |
843eac3901bc377659ef74dab4bd56032d6efc4c | C++ | bebhav/CPP-PIPE-NOWAIT-NonBlocking | /ClientPipe/ClientPipe/PipeHandle.h | UTF-8 | 456 | 2.53125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <windows.h>
class PipeHandel
{
public:
enum class PipeState
{
ePipeUnknown,
ePipeInitComple,
ePipeRxTx,
};
PipeHandel(wchar_t* name,bool isServer);
~PipeHandel();
bool Connect();
bool SendData(char* data);
bool ReadData(char** data);
PipeState getState();
private:
PipeState state = PipeState::ePipeUnknown;
HANDLE pipe = NULL;
wchar_t *PipeName;
bool isServer;
};
| true |
3ccd89dfd8e086e329643eb54cf81c21c20ea150 | C++ | Aryan22g/Data-Structures-and-Algorithms | /Strings/maxChar.cpp | UTF-8 | 808 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<algorithm>
#include<climits>
using namespace std;
int main(){
string s="abcacbade";
//bruteforceapproach;
// int maxNum=INT_MIN;
// for(int i=0; i<s.length(); i++){
// int count=0;
// for(int j=i; j<s.length(); j++){
// if(s[i]==s[j]){
// count++;
// }
// maxNum=max(count, maxNum);
// }
// }
// cout<<maxNum;
//optimised approach
int freq[26];
for(int i=0; i<26; i++) freq[i]=0;
for(int i=0; i<s.length(); i++)
freq[s[i]-'a']++;
int maxNum=INT_MIN;
char ans='a';
for(int i=0; i<26; i++) {
if(freq[i]>maxNum) {
maxNum=freq[i];
ans=i+'a';
}
}
cout<<maxNum<<" "<<ans<<endl;
} | true |
84386214e14c569e1dc38636ecf2bef866366341 | C++ | MitchellOsborne/AbyssWatchers | /Abyss Watchers - Server/src/CollisionBox.cpp | UTF-8 | 1,618 | 2.8125 | 3 | [] | no_license | #include "CollisionBox.h"
CollisionBox::CollisionBox(glm::vec2 a_oPos, glm::vec2 a_oOffset, glm::vec2 a_oSize, BoxType a_eType)
{
m_oPos = a_oPos;
m_oOffset = a_oOffset;
m_oSize = a_oSize;
m_eType = a_eType;
TL = glm::vec2(m_oPos.x - m_oSize.x / 2, m_oPos.y + m_oSize.y / 2);
TR = glm::vec2(m_oPos.x + m_oSize.x / 2, m_oPos.y + m_oSize.y / 2);
BL = glm::vec2(m_oPos.x - m_oSize.x / 2, m_oPos.y - m_oSize.y / 2);
BR = glm::vec2(m_oPos.x + m_oSize.x / 2, m_oPos.y - m_oSize.y / 2);
}
void CollisionBox::SetOwner(Agent* a_oOwner)
{
Owner = a_oOwner;
}
void CollisionBox::Update()
{
m_oPos = Owner->m_oPos + glm::vec2(m_oOffset.x * Owner->m_iDir, m_oOffset.y);
TL = glm::vec2(m_oPos.x - m_oSize.x / 2, m_oPos.y + m_oSize.y / 2);
TR = glm::vec2(m_oPos.x + m_oSize.x / 2, m_oPos.y + m_oSize.y / 2);
BL = glm::vec2(m_oPos.x - m_oSize.x / 2, m_oPos.y - m_oSize.y / 2);
BR = glm::vec2(m_oPos.x + m_oSize.x / 2, m_oPos.y - m_oSize.y / 2);
}
void CollisionBox::Draw(SpriteBatch* sb)
{
sb->setSpriteColor(1, 0, 1, 1);
sb->drawLine(TL.x, TL.y, TR.x, TR.y, 1.f, 0);
sb->drawLine(TL.x, TL.y, BL.x, BL.y, 1.f, 0);
sb->drawLine(TR.x, TR.y, BR.x, BR.y, 1.f, 0);
sb->drawLine(BL.x, BL.y, BR.x, BR.y, 1.f, 0);
sb->setSpriteColor(1, 1, 1, 1);
}
bool CollisionBox::CheckCollision(CollisionBox* other)
{
if (IsWithin(other->TL) || IsWithin(other->TR) || IsWithin(other->BL) || IsWithin(other->BR))
{
return true;
}
return false;
}
bool CollisionBox::IsWithin(glm::vec2 point)
{
if (point.x >= TL.x && point.y <= TL.y)
{
if (point.x <= BR.x && point.y >= BR.y)
{
return true;
}
}
return false;
} | true |
d95d629ba6e66f5dc9a75a29fddafac8d847a3a5 | C++ | bassorama/FH_Aachen | /ADS/Praktikum 2/aufgb 3/queue.h | UTF-8 | 229 | 2.71875 | 3 | [] | no_license | // Datum: 10.04.2014
#pragma once
class queue
{
public:
int* data;
int L;
int S;
int size;
queue(const int elements);
~queue(void);
void Push(int item);
int Pop();
void Output();
bool isFull();
bool isEmpty();
};
| true |
553371ee402de18ca168236040ae89a446449f93 | C++ | ngangwar962/C_and_Cpp_Programs | /tut_on_strings_26_june/same_frequency.cpp | UTF-8 | 636 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int i,j,k,l;
vector<int> vec;
string str;
cin>>str;
int count[26]={0};
i=0;
while(str[i]!='\0')
{
count[str[i]-'a']++;
i++;
}
for(i=0;i<26;i++)
{
if(count[i])
{
vec.push_back(count[i]);
}
}
sort(vec.begin(),vec.end());
int len=vec.size();
if(vec[0]!=vec[len-1])
{
if(vec[len-1]==vec[len-2])
{
cout<<"No"<<"\n";
return 0;
}
else
{
cout<<"Yes"<<"\n";
return 0;
}
}
else
{
cout<<"Yes"<<"\n";
return 0;
}
for(i=0;i<vec.size();i++)
{
cout<<vec[i]<<" ";
}
cout<<"\n";
return 0;
}
| true |
bb682daa56a849b2da4d1068bc83e1d197ac6c80 | C++ | wokickic/cpp | /Ch02/Ch02/02_1_3.cpp | UTF-8 | 666 | 3.125 | 3 | [] | no_license | //
// 02_1_2.cpp
// Ch02
//
// Created by 이승원 on 2017. 2. 2..
// Copyright © 2017년 wokic. All rights reserved.
//
#include <iostream>
#include <cstdio>
using namespace std;
void SwapPointer_ref(int *(&ptr1), int *(&ptr2)){
int *ptr = ptr1;
ptr1 = ptr2;
ptr2 = ptr;
}
void SwapPointer(int *ptr1, int *ptr2){
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
int main(void){
int num1 = 5;
int *ptr1 = &num1;
int num2 = 10;
int *ptr2 = &num2;
cout << *ptr1 <<endl;
cout << *ptr2 <<endl;
SwapPointer(ptr1, ptr2);
printf("변경후 : %d %d\n",*ptr1,*ptr2);
}
| true |
a4e4713fe3c538d57a5854efe9d17f72020de287 | C++ | julia-lazariv/Labs | /Lab7/Lab7_1/Lab7_1/Lab7_1.cpp | WINDOWS-1251 | 3,117 | 3.296875 | 3 | [
"MIT"
] | permissive | // Lab_7_1.cpp
// < >
// 7.1.
// / .
// 15
#include <iostream>
#include <iomanip>
#include <time.h>
#include "windows.h"
#include <string>
using namespace std;
void Create(int** a, const int rowCount, const int colCount, const int Low, const int High);
void Print(int** a, const int rowCount, const int colCount);
void Sort(int** a, const int rowCount, const int colCount);
void Change(int** a, const int row1, const int row2, const int colCount);
void Calc(int** a, const int rowCount, const int colCount, int& S, int& k);
int main()
{
//
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
srand((unsigned)time(NULL));
int Low = -34;
int High = 26;
int rowCount = 8;
int colCount = 6;
int **a = new int*[rowCount];
for (int i = 0; i < rowCount; i++)
{
a[i] = new int[colCount];
}
Create(a, rowCount, colCount, Low, High);
cout << endl;
cout << "-------- -------- " << endl;
Print(a, rowCount, colCount);
cout << "-------- -------- " << endl;
Sort(a, rowCount, colCount);
Print(a, rowCount, colCount);
int S = 0;
int k = 0;
Calc(a, rowCount, colCount, S, k);
cout << "S = " << S << endl;
cout << "k = " << k << endl;
cout << "-------- -------- " << endl;
Print(a, rowCount, colCount);
for (int i = 0; i < rowCount; i++)
{
delete[] a[i];
}
delete[] a;
string str;
getline(cin, str);
return 0;
}
void Create(int** a, const int rowCount, const int colCount, const int Low, const int High)
{
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
a[i][j] = Low + rand() % (High - Low + 1);
}
}
}
void Print(int** a, const int rowCount, const int colCount)
{
cout << endl;
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
cout << setw(4) << a[i][j];
}
cout << endl;
}
cout << endl;
}
void Sort(int** a, const int rowCount, const int colCount)
{
for (int j0 = 0; j0 < colCount - 1; j0++)
{
for (int j1 = 0; j1 < colCount - j0 - 1; j1++)
{
if ((a[j1][0] < a[j1 + 1][0]) // 1
||
(a[j1][0] == a[j1 + 1][0] &&
a[j1][1] < a[j1 + 1][1]) // 2
||
(a[j1][0] == a[j1 + 1][0] &&
a[j1][1] == a[j1 + 1][1] &&
a[j1][2] < a[j1 + 1][2])) // 3
{
Change(a, j1, j1 + 1, rowCount);
}
}
}
}
void Change(int** a, const int row1, const int row2, const int colCount)
{
int tmp;
for (int j = 0; j < colCount; j++)
{
tmp = a[row1][j];
a[row1][j] = a[row2][j];
a[row2][j] = tmp;
}
}
void Calc(int** a, const int rowCount, const int colCount, int& S, int& k)
{
S = 0;
k = 0;
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
if (a[i][j] > 0 || !(a[i][j] % 2 != 0))
{
S += a[i][j];
k++;
a[i][j] = 0;
}
}
}
} | true |
1caceb8848c1cce5b132dff403cbd6777bdab90f | C++ | YigalB1/Train_Road_Blocker_Wemos | /Train_Road_Blocker_Wemos/src/classes.h | UTF-8 | 4,927 | 3.328125 | 3 | [] | no_license | #define in_range_const 10
class train_state {
public:
int state= 0; // the state of the train
bool l_flag = false; // from left sensor
bool r_flag = false; // from right sensor
bool gate_open = false; // activating servo
private:
int nxt_state = 0; // temp to hold next state
bool none,l_only,r_only,both;
public: void change_state() {
none = !l_flag && !r_flag;
l_only = l_flag && !r_flag;
r_only = !l_flag && r_flag;
both = l_flag && r_flag;
if (both) {
Serial.println("Error 0 - both sensors active???");
} // of if
// see excel file with all states for this state machine
switch (state) {
case 0: // Gate is closed, no train
if (none) { // wait for train
nxt_state = 0;
gate_open = false;
}
else if (l_only) { // arriving from left
nxt_state = 1;
gate_open = true;
}
else if (r_only) { // arriving from right
nxt_state = 4;
gate_open = true;
}
break;
case 1: // Train arriving from left
if (none) { // passed the left sensor
nxt_state = 2;
gate_open = true;
}
else if (l_only) { // still arriving from left
nxt_state = 1;
gate_open = true;
}
else if (r_only) { // ERROR 1
nxt_state = 10 ;
gate_open = true;
}
break;
case 2: // Train passed left, moving to right
if (none) { // passed left sensorm before right
nxt_state = 2;
gate_open = true;
}
else if (l_only) { // ERROR 2
nxt_state = 10;
gate_open = true;
}
else if (r_only) { // arrived right sensor
nxt_state = 3 ;
gate_open = true;
}
break;
case 3: // In right sensor
if (none) { // finished passing, close gate
nxt_state = 0;
gate_open = false;
}
else if (l_only) { // ERROR 3
nxt_state = 10;
gate_open = true;
}
else if (r_only) { // arrived right sensor
nxt_state = 3 ;
gate_open = true;
}
break; // finished left to right
case 4: // passing from right
if (none) { // passed rioght sensor, twards left
nxt_state = 5;
gate_open = false;
}
else if (l_only) { // ERROR 4
nxt_state = 10;
gate_open = true;
}
else if (r_only) { // still in right sensor
nxt_state = 4 ;
gate_open = true;
}
break;
case 5: // Between sensors, while right to left
if (none) { // still between sensors
nxt_state = 5;
gate_open = true;
}
else if (l_only) { // arrived left sensor from right
nxt_state = 6;
gate_open = true;
}
else if (r_only) { // ERROR 5
nxt_state = 10 ;
gate_open = true;
}
break;
case 6: // Between sensors, while right to left
if (none) { // finished left sensor form right, done, back to start
nxt_state = 0;
gate_open = false;
}
else if (l_only) { // still in left sensor from right
nxt_state = 6;
gate_open = true;
}
else if (r_only) { // ERROR 6
nxt_state = 10 ;
gate_open = true;
}
break;
} // of switch case
state = nxt_state;
} // of change_state()
}; // of train_state class
class Ultrasonic_Sensor {
public:
int trig_pin;
int echo_pin;
int dist;
bool in_range;
void measure_dist() {
long duration, distance; // Duration used to calculate distance
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
duration = pulseIn(echo_pin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
//Serial.println(distance);
//Delay 50ms before next reading.
delay(50);
dist = int(distance);
if ((dist < in_range_const) && (dist > 2)) {
in_range = true;
}
else {
in_range = false;
}
//return(int(distance));
} // of measure_dist()
}; // of Ultrasonic_Sensor class | true |
2ef0e18230746158902e61fd8e3ab7bb57afed71 | C++ | tounaishouta/ProjectEuler | /C++/0105.cpp | UTF-8 | 1,881 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <utility>
#include <list>
#include <set>
using namespace std;
inline bool is_special(list<int> as) {
int n = as.size();
int array[n]; {
int i = 0;
for (int a : as) {
array[i] = a;
i++;
}
for (int i = n; i > 0; i--)
for (int j = 0; j + 1 < i; j++)
if (array[j] > array[j + 1])
swap(array[j], array[j + 1]);
}
int i = 1;
int j = 0;
int sum_A = array[0];
int sum_B = 0;
while (true) {
i++;
j++;
if (i + j > n)
break;
sum_A += array[i - 1];
sum_B += array[n - j];
if (sum_A < sum_B)
return false;
}
set<int> sums; {
sums.insert(0);
}
list<int> queue;
for (int a : as) {
queue.clear();
for (int s : sums)
queue.push_back(s);
for (int s : queue) {
if (sums.count(s + a) > 0)
return false;
sums.insert(s + a);
}
}
return true;
}
inline int sum(list<int> as) {
int s = 0;
for (int a : as)
s += a;
return s;
}
const int SIZE = 100;
int main() {
list<int> data[SIZE]; {
ifstream file;
file.open("src/0105.txt");
for (int i = 0; i < SIZE; i++) {
while (true) {
int n;
file >> n;
data[i].push_back(n);
if (file.peek() == ',') {
file.ignore(1);
continue;
}
break;
}
}
file.close();
}
int total_sum = 0; {
for (int i = 0; i < SIZE; i++)
if (is_special(data[i]))
total_sum += sum(data[i]);
}
cout << total_sum << endl;
return 0;
}
| true |
d860e744e64ba9aa8d76babc01e307f8269b4760 | C++ | PaulC88/GamaGameEngine | /FileIOManager.cpp | UTF-8 | 1,491 | 3.09375 | 3 | [] | no_license | #include "FileIOManager.h"
#include "LogAndDebug.h"
#include <fstream>
#include <iostream>
#include <iterator>
namespace GamaGameEngine {
bool FileIOManager::readFileToBuffer(std::string filePath, std::vector<unsigned char>& buffer) {
std::ifstream file(filePath, std::ifstream::binary);
if (file.fail()) {
GamaGameEngine::fatalError("Failed to open " + filePath);
return false;
}
file.seekg(0, file.end);
unsigned int fileSize = (unsigned int)file.tellg();
file.seekg(0, file.beg);
fileSize -= (unsigned int)file.tellg();
buffer.resize(fileSize);
logData("Reading file: " + filePath);
if (file)
logData("File read successfully: " + filePath);
else
fatalError("Error reading file: " + filePath);
file.read((char *)&(buffer[0]), fileSize);
file.close();
return true;
}
bool FileIOManager::readFileToVector(std::string filePath, std::vector<std::string>& fileData) {
std::ifstream file;
file.open(filePath);
if (file.fail()) {
GamaGameEngine::fatalError("Failed to open " + filePath);
perror(filePath.c_str());
return false;
}
std::string tmp;
while (std::getline(file, tmp)) {
fileData.push_back(tmp);
}
file.close();
return true;
}
void FileIOManager::writeToFile(std::string filePath, std::vector<std::string>& fileData) {
std::ofstream newFile(filePath);
std::ostream_iterator<std::string> outputIterator(newFile, "\n");
std::copy(fileData.begin(), fileData.end(), outputIterator);
}
} | true |
e5f0964c021aa948a51315cd006f14a9f958f573 | C++ | khyun-kim/SW-expert-academy-study-storage | /JJongSue/D3/2806/solution.cpp | UTF-8 | 1,865 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int find_queen(int y, int x, vector<vector<bool>> &board, int queennum);
int main(void)
{
int testcase_num = 0;
scanf("%d", &testcase_num);
for (int testcase_i = 1; testcase_i <= testcase_num; testcase_i++)
{
int queennum = 0;
scanf("%d", &queennum);
vector<vector<bool>> board;
vector<bool> tmp(queennum, true);
for (int i = 0; i < queennum; i++)
board.push_back(tmp);
printf("#%d %d\n", testcase_i, find_queen(0,0,board,queennum));
}
return 0;
}
int find_queen(int y, int x, vector<vector<bool>> &board, int queennum)
{
if (y == queennum - 1 && x == queennum - 1)
{
if (board[y][x])
return 1;
else
return 0;
}
else if (y == queennum - 1)
{
int tmp = 0;
if (board[y][x])
tmp = 1;
return tmp + find_queen(y, x + 1, board, queennum);
}
else if (x == queennum - 1)
{
if (board[y][x])
{
vector<vector<bool>> board2 = board;
for (int i = y, j=0; i < queennum;i++, j++)
{
board2[i][x] = false;
board2[i][x-j] = false;
}
return find_queen(y+1, 0, board2, queennum);
}
else return 0;
}
else
{
if (board[y][x])
{
vector<vector<bool>> board2 = board;
for (int i = y, j=0; i < queennum;i++, j++)
{
board2[i][x] = false;
if(x-j >= 0) board2[i][x-j] = false;
if(x+j < queennum) board2[i][x+j] = false;
}
return find_queen(y, x+1, board, queennum)+find_queen(y+1, 0, board2, queennum);;
}
else return find_queen(y, x+1, board, queennum);
}
} | true |
843f0059de7a2e11498bed95f42cdb36ef252dc6 | C++ | dima9777/webdav-client-cpp | /examples/client/list.cpp | UTF-8 | 1,283 | 3.015625 | 3 | [
"curl"
] | permissive | #include <webdav/client.hpp>
std::ostream resources_to_string(std::vector<std::string> & resources)
{
std::ostream stream;
for (auto resource : resources)
{
stream << "\t" << "- " << resource << std::endl;
}
return stream;
}
int main() {
std::map<std::string, std::string> options =
{
{ "webdav_hostname", "https://webdav.yandex.ru" },
{ "webdav_login", "{webdav_login}" },
{ "webdav_password", "{webdav_password}" }
};
std::unique_ptr<WebDAV::Client> client(WebDAV::Client::Init(options));
auto remote_resources = {
"existing_file.dat",
"not_existing_file.dat",
"existing_directory",
"not_existing_directory"
};
for (auto remote_resource : remote_resources) {
auto resources = client->list(remote_resource);
std::cout << remote_resource << " resource contain:" << std::endl;
std::cout << resources_to_string(resources);
std::cout << std::endl;
}
}
/// existing_file.dat resource contain:
///
/// not_existing_file.dat resource contain:
///
/// existing_directory resource contain:
/// - dir/
/// - file.dat
///
/// not_existing_directory resource contain:
///
| true |
fccba4a5ccf29971a2a17d3fbfb014de13c497a6 | C++ | Flock19/LoadMonitor | /Bloc.cpp | ISO-8859-2 | 2,426 | 3.140625 | 3 | [] | no_license | #include "Bloc.h"
#include "Balance.h"
#include "Produits.h"
#include <iostream>
using namespace std;
Bloc::Bloc()
{
}
Bloc::Bloc(Balance& bal, Produits& prod)
{
this->bal = bal;
this->prod = prod;
if ((bal.chargeCourante() / prod.valMoyenne()) - int(bal.chargeCourante() / prod.valMoyenne()) >= 0.5) {
this->qte.push_back(int(bal.chargeCourante() / prod.valMoyenne()) + 1);
}
else {
this->qte.push_back(int(bal.chargeCourante() / prod.valMoyenne()));
}
}
Balance Bloc::getBalance()
{
return this->bal;
}
Produits Bloc::getProduits()
{
return this->prod;
}
void Bloc::setBalance(Balance bal)
{
this->bal = bal;
}
void Bloc::setProduits(Produits prod)
{
this->prod = prod;
}
int Bloc::showStock()
{
if (bal.chargeCourante() == 0) {
//this->qte = 0;
cout << "Trop tard, le stock a t dvalis !" << endl;
}
else {
double moy = prod.valMoyenne() * 1;
//cout << "Precision : " << bal.getPrecision() << endl;
//cout << "Nombre de " << prod.getNom() << " : " << bal.chargeCourante() << "/" << moy << " : " << bal.chargeCourante() / moy << endl;
if ((bal.chargeCourante() / moy) - int(bal.chargeCourante() / moy) >= 0.5) {
//this->qte = int(bal.chargeCourante() / moy) + 1;
cout << "Il reste : " << int(bal.chargeCourante() / moy) + 1 << " " << prod.getNom() << endl;
cout << "Vous avez pris : " << calculeQtePrise() << " " << prod.getNom() << endl;
this->qte.push_back(int(bal.chargeCourante() / moy)+1);
return int(bal.chargeCourante() / moy) + 1;
}
else {
//this->qte = int(bal.chargeCourante() / moy);
cout << "Il reste : " << int(bal.chargeCourante() / moy) << " " << prod.getNom() << endl;
cout << "Vous avez pris : " << calculeQtePrise() << " " << prod.getNom() << endl;
this->qte.push_back(int(bal.chargeCourante() / moy));
return int(bal.chargeCourante() / moy);
}
}
}
int Bloc::calculeQtePrise()
{
double moy = prod.valMoyenne();
/*cout << "La valeur prise : " <<((bal.chargetmp - bal.chargeCourante()) / moy) << endl;
cout << "La difference est : " << ((bal.chargetmp - bal.chargeCourante()) / moy) - floor((bal.chargetmp - bal.chargeCourante()) / moy) << endl;*/
if (((bal.chargetmp - bal.chargeCourante()) / moy) - floor((bal.chargetmp - bal.chargeCourante()) / moy) >= 0.5) {
cout << "oook";
return floor((bal.chargetmp - bal.chargeCourante()) / moy) + 1;
}
else {
return floor((bal.chargetmp - bal.chargeCourante()) / moy);
}
}
| true |
3e7a73303642dddfa64b0bfba7245e801877279d | C++ | zaBogdan/problemeInfo | /admiteri_facultati/cluj/2016/problema_2.cpp | UTF-8 | 218 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int virusi(int n,int k){
if(n<k) return 0;
if(n%2==0) return virusi(n/2,k)+1;
else return virusi(n+1,k)+1;
}
int main(){
cout << virusi(11,3);
return 0;
} | true |
a899c05ba9825256c4ef874b77a4b6d94cc9c857 | C++ | nucleus/tracker | /src/GridC.h | UTF-8 | 701 | 3.046875 | 3 | [] | no_license | #ifndef GRIDC_H
#define GRIDC_H
#define GRID_CELLSIZE 16
#include <Candidate.h>
#include <list>
using namespace std;
/*!
* Class: GridC.
*
* This class represents the grid data structure for candidates.
*/
class GridC {
public:
GridC(void);
GridC(int width, int height);
/*!
* Function: GetEntry.
*
* Returns the grid entry corresponding to the given (x,y) location.
*/
list<Candidate> * GetEntry(int x, int y);
/*!
* Function: SetEntry.
*
* Adds an entry to the grid cell with the given (x,y) location.
*/
void SetEntry(int x, int y, list<Candidate> * entry);
int xcells;
int ycells;
private:
list<Candidate> * * grid;
};
#endif
| true |
9bbb16667120149409719e9a5b866d70b5468eda | C++ | leannejdong/SparseTensor | /include/matrix.h | UTF-8 | 2,291 | 3.28125 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef SPARSETENSORLIB_LIBRARY_H
#define SPARSETENSORLIB_LIBRARY_H
#include <utility>
#include <iostream>
#include <cassert>
#include <map>
#include <vector>
using std::cerr;
namespace SparseTensor {
template<typename T1, typename T2>
class matrix {
private:
std::map<std::pair<T1,T1>,T2> element_map;
int n_rows;
int n_cols;
public:
matrix(std::size_t nrows, std::size_t ncols, T2 v = 0)
:n_rows(nrows), n_cols(ncols){};
matrix(std::initializer_list<std::initializer_list<T2>> values)
{
int i = 0;
for (const auto &row : values) {
int j = 0;
for (double element : row) {
element_map[std::pair(i,j)] = element;
++j;
}
++i;
}
cerr << "values.size(): " << values.size() << "\n";
cerr << "values.begin()->size(): " << values.begin()->size() << "\n";
n_rows = values.size();
n_cols = values.begin()->size();
}
T1 num_rows() const
{
return n_rows;
}
T1 num_cols() const
{
return n_cols;
}
T2 operator()(int row, int col) const
{
return element_map.find(std::pair(row,col))->second;
}
T2 &operator()(int row, int col)
{
return element_map[{row,col}];
}
};
template<typename T1, typename T2>
matrix<T1, T2>operator* (const matrix<T1, T2> &m1, const matrix<T1, T2> &m2)
{
matrix<T1, T2> result(m1.num_rows(), m2.num_cols(), 0);
std::cerr << "start multiply" << "\n";
//result.insert({{0, 0}, 2.0});
cerr << "result.num_rows()=" << result.num_rows() << "\n";
for (std::size_t row(0); row < result.num_rows(); ++ row) {
for (std::size_t col(0); col < result.num_cols(); ++col) {
for (std::size_t inner(0); inner < m2.num_rows(); ++inner) {
auto a = m1(row,inner);
auto b = m2(inner,col);
result(row, col) += a * b;
}
}
}
return result;
}
}
#endif ///SPARSETENSORLIB_LIBRARY_H
| true |
195e1d01ca394f1926df62745f0414004961dc62 | C++ | unbeman/Complex-Number | /ComplexNumber.cpp | UTF-8 | 2,081 | 3.3125 | 3 | [] | no_license | //
// Created by devernua on 28.09.16.
//
#include <iostream>
using namespace std;
#include <cmath>
#include "ComplexNumber.h"
ComplexNumber::ComplexNumber(const double Re, const double Im, const double eps){
this->Re = Re;
this->Im = Im;
this->eps = eps;
}
ComplexNumber::ComplexNumber(const ComplexNumber & number){
Re = number.Re;
Im = number.Im;
eps = number.eps;
}
double ComplexNumber::getRe() const { return Re;}
double ComplexNumber::getIm() const { return Im;}
double ComplexNumber::abs() const { return sqrt(Re * Re + Im * Im);}
double ComplexNumber::phase() const {
if (std::abs(Re) < eps){
return 0;
}
return atan(Im / Re); //только для 1 и 4 четвертей
}
ComplexNumber & ComplexNumber::operator+(const ComplexNumber & number){
Re += number.Re;
Im += number.Im;
return *this;
}
ComplexNumber & ComplexNumber::operator-(const ComplexNumber & number){
Re -= number.Re;
Im -= number.Im;
return *this;
}
ComplexNumber & ComplexNumber::operator*(const ComplexNumber & number){
Re = Re * number.Re - Im * number.Im;
Im = Re * number.Im + number.Re * Im;
return *this;
}
ostream &operator<<(ostream & stream, const ComplexNumber & number){
if (number.Im == 0){
stream << number.Re;
}
else if( number.Im == 1 || number.Im == -1){
stream << number.Re << ((number.Im >= 0)? "+" : "-") << "i";
}
else{
stream << number.Re << ((number.Im >= 0)? "+" : "") << number.Im << "i";
}
return stream;
}
istream &operator>>(istream & stream, ComplexNumber & number){
stream >> number.Re >> number.Im;
return stream;
}
void ComplexNumber::swap(ComplexNumber & number){
std::swap(Re, number.Re);
std::swap(Im, number.Im);
}
bool operator==(const ComplexNumber n1, const ComplexNumber n2){
double eps = min(n1.eps, n2.eps);
return (std::abs(n1.Re - n2.Re) < eps) && ( std::abs(n1.Im - n2.Im) < eps);
}
bool operator!=(const ComplexNumber n1, const ComplexNumber n2){
return !(n1 == n2);
}
| true |
3596de9798b5c8bcc0e44bc43ce7b9e8c45a8061 | C++ | bstatcomp/math | /stan/math/prim/fun/lb_free.hpp | UTF-8 | 1,139 | 2.984375 | 3 | [
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef STAN_MATH_PRIM_FUN_LB_FREE_HPP
#define STAN_MATH_PRIM_FUN_LB_FREE_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/identity_free.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the unconstrained value that produces the specified
* lower-bound constrained value.
*
* If the lower bound is negative infinity, it is ignored and
* the function reduces to <code>identity_free(y)</code>.
*
* @tparam T type of scalar
* @tparam L type of lower bound
* @param[in] y input scalar
* @param[in] lb lower bound
* @return unconstrained value that produces the input when
* constrained
* @throw std::domain_error if y is lower than the lower bound
*/
template <typename T, typename L>
inline return_type_t<T, L> lb_free(const T& y, const L& lb) {
using std::log;
if (lb == NEGATIVE_INFTY) {
return identity_free(y);
}
check_greater_or_equal("lb_free", "Lower bounded variable", y, lb);
return log(y - lb);
}
} // namespace math
} // namespace stan
#endif
| true |
be0a0b68a06b9ade2570dcb79e6ee39ed2decb5b | C++ | michalrzak/AoC2020_Scala | /20_day/task2.cpp | UTF-8 | 6,013 | 2.859375 | 3 | [] | no_license | #include <string>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
std::string getColumn(const std::vector<std::string>& tiles, size_t index){
std::string outp;
for (std::string row : tiles)
outp += row.at(index);
return outp;
}
std::vector<std::string> rotate(const std::vector<std::string>& tiles, int times){
std::vector<std::string> outp;
switch (times){
case 1:
for (size_t i {0}; i < tiles.size(); ++i){
outp.push_back("");
for (size_t j {0}; j < tiles.size(); ++j){
outp.back()+=tiles.at(j).at(i);
}
}
break;
case 2:
for(size_t i{tiles.size()}; i > 0; --i)
outp.push_back(tiles.at(i-1));
break;
}
return outp;
}
std::vector<std::string> flip(const std::vector<std::string>& tiles){
std::vector<std::string> outp;
for(std::string line : tiles){
outp.push_back("");
std::copy(line.crbegin(), line.crend(), std::back_inserter(outp.back()));
}
return outp;
}
std::vector<std::string> rot(const std::vector<std::string>& tS, int j){
std::vector<std::string> altTS;
switch(j){
case 0:
altTS = tS;
break;
case 1:
altTS = rotate(tS, 2);
break;
case 2:
altTS = flip(tS);
break;
case 3:
altTS = flip(rotate(tS, 2));
break;
case 4:
altTS = rotate(tS, 1);
break;
case 5:
altTS = flip(rotate(tS, 1));
break;
case 6:
altTS = rotate(rotate(tS, 1), 2);
break;
case 7:
altTS = flip(rotate(rotate(tS, 1), 2));
break;
}
return altTS;
}
int main(){
std::fstream input;
input.open("input.txt");
std::map<int, std::vector<std::string>> tiles;
int currentTile {-1};
std::string line;
while (getline(input, line)){
if (currentTile == -1){
line = line.substr(line.find(' ')+1, std::string::npos);
currentTile = std::stoi(line);
tiles.insert({currentTile, {}});
}
else if (line == "")
currentTile = -1;
else
tiles.at(currentTile).push_back(line);
}
input.close();
std::cout << tiles.size() << '\n';
std::vector<std::vector<int>> map(12);
std::vector<std::vector<int>> mapr(12);
for (auto& v : map)
for (size_t i {0}; i < 12; ++i)
v.push_back(0);
for (auto& v : mapr)
for (size_t i {0}; i < 12; ++i)
v.push_back(0);
map.at(0).at(0) = 1699;
mapr.at(0).at(0) = 3;
std::map<int, bool> placed;
placed[1699] = true;
//while(placed < 144){
for (size_t y {0}; y < 12; ++y){
std::cout << "helo?\n";
for (size_t x {0}; x < 12; ++x){
if (x == 0 && y == 0)
continue;
bool found {false};
for (auto tile : tiles){
std::cout << tile.first << '\n';
std::cout << placed[tile.first] << '\n';
if (placed[tile.first])
continue;
for (size_t i {0}; i < 8; ++i){
std::vector<std::string> ct {rot(tile.second, i)};
//for (auto ele : ct)
// std::cout << ele << '\n';
if (x!=0){
//std::cout << y << ' ' << x << '\n';
std::cout << map.at(y).at(x-1) << '\n';
std::cout << getColumn(ct, 0) << '\n';
std::cout << getColumn(rot(tiles.at(map.at(y).at(x-1)), mapr.at(y).at(x-1)), 9) << '\n';
if(getColumn(rot(tiles.at(map.at(y).at(x-1)), mapr.at(y).at(x-1)), 9) == getColumn(ct, 0)){
map.at(y).at(x) = tile.first;
mapr.at(y).at(x) = i;
placed[tile.first] = true;
found = true;
std::cout << tile.first << '\n';
std::cout << i << '\n';
std::cout << y << ' ' << x<< '\n';
//std::cin >> currentTile;
break;
}
}else
if (rot(tiles.at(map.at(y-1).at(x)), mapr.at(y-1).at(x)).at(9) == ct.at(0)){
map.at(y).at(x) = tile.first;
mapr.at(y).at(x) = i;
placed[tile.first] = true;
found = true;
std::cout << y << ' ' << x<< '\n';
break;
}
}
if (found)
break;
}
}
}
//std::cout << placed << '\n';
//}
for (size_t y {0}; y < 12; ++y){
for (size_t i {1}; i < 9; ++i){
for(size_t x {0}; x < 12; ++x){
//std::cout << rot(tiles.at(map.at(y).at(x)), mapr.at(y).at(x)).at(i);
std::cout << rot(tiles.at(map.at(y).at(x)), mapr.at(y).at(x)).at(i).substr(1, 8);
}
std::cout << '\n';
}
}
/*
for (size_t y {0}; y < 12; ++y){
for (size_t i {0}; i < 10; ++i){
for(size_t x {0}; x < 12; ++x){
std::cout << rot(tiles.at(map.at(y).at(x)), mapr.at(y).at(x)).at(i);
}
std::cout << '\n';
}
}
*/
return 0;
} | true |
31c3f70b9a62b374972c32c52623f8e814e591f8 | C++ | sujay170nanj/galaga-cinder | /tests/test_battleship.cc | UTF-8 | 1,133 | 2.8125 | 3 | [] | no_license | #include <core/entities/battleship.h>
#include <catch2/catch.hpp>
using namespace::galaga;
TEST_CASE("Generate Battleship hitbox") {
Battleship battleship(glm::vec2(100, 100));
REQUIRE(battleship.GenerateRectPosition().getUpperLeft() == glm::vec2(80, 80));
REQUIRE(battleship.GenerateRectPosition().getLowerRight() == glm::vec2(120, 120));
}
TEST_CASE("Battleship move") {
Battleship battleship(glm::vec2(100, 100));
SECTION("Right") {
battleship.MoveRight();
REQUIRE(battleship.GenerateRectPosition().getCenter() == glm::vec2(108, 100.5));
}
SECTION("Left") {
battleship.MoveLeft();
REQUIRE(battleship.GenerateRectPosition().getCenter() == glm::vec2(92, 100.5));
}
}
TEST_CASE("Battleship destroy") {
Battleship battleship(glm::vec2(100, 100));
battleship.Destroy();
REQUIRE(battleship.IsDead());
}
TEST_CASE("Decrement Battleship explosion timer") {
Battleship battleship(glm::vec2(100, 100));
battleship.Destroy();
size_t initial_timer = battleship.GetExplosionTimer();
battleship.DecrementExplosionTimer();
REQUIRE(battleship.GetExplosionTimer() == (initial_timer-1));
} | true |
00a86855ee73d680db16f435d76fd99ad1a29d9e | C++ | mikeym88/jeeh-fork | /examples/flash.cpp | UTF-8 | 815 | 2.90625 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | // Example of how to write to built-in flash memory.
#include <jee.h>
UartDev< PinA<9>, PinA<10> > console;
int printf(const char* fmt, ...) {
va_list ap; va_start(ap, fmt); veprintf(console.putc, fmt, ap); va_end(ap);
return 0;
}
Flash mem;
int main () {
// use a flash page well above the current code, i.e. @ 64K
uint32_t* testAddr = (uint32_t*) 0x00010000;
uint32_t x = testAddr[0], y = testAddr[1];
printf("before %08x %08x\n", x, y);
mem.erasePage(testAddr);
printf("erased %08x %08x\n", testAddr[0], testAddr[1]);
mem.write32(testAddr, x+1);
mem.write32(testAddr+1, y-1);
printf(" after %08x %08x\n", testAddr[0], testAddr[1]);
return 0;
}
// sample output:
//
// before 01234567 FEDCBA98
// erased FFFFFFFF FFFFFFFF
// after 01234568 FEDCBA97
| true |
fba994b6869d7e0e5b7033a67ba536dd309f1833 | C++ | techgarden/waterfall | /Schedule.cpp | UTF-8 | 1,981 | 3.265625 | 3 | [] | no_license |
#include "Schedule.h"
char* days[] = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" };
Schedule::Schedule(unsigned int address) {
this->address = address;
}
void Schedule::createAlarms() {
for (byte i = 0; i < NUMOFDAYS; i++) {
rules[i].createAlarms();
}
}
void Schedule::time(byte hour, byte min, byte sec, byte day, byte month, unsigned int year) {
setTime(hour, min, sec, day, month, year);
createAlarms();
}
void Schedule::time(byte hour, byte min, byte sec) {
time(hour, min, sec, this->day(), this->month(), this->year());
}
void Schedule::date(byte day, byte month, unsigned int year) {
time(this->hour(), this->minute(), this->second(), day, month, year);
}
uint8_t Schedule::hour() {
return ::hour();
}
uint8_t Schedule::minute() {
return ::minute();
}
uint8_t Schedule::second() {
return ::second();
}
uint8_t Schedule::day() {
return ::day();
}
uint8_t Schedule::month() {
return ::month();
}
uint16_t Schedule::year() {
return ::year();
}
unsigned int Schedule::store() {
for (byte i = 0; i < NUMOFDAYS; i++) {
address = rules[i].store(address);
}
return address;
}
void Schedule::fetch() {
for (byte i = 0; i < NUMOFDAYS; i++) {
rules[i].setDay(i);
rules[i].fetch(i * sizeof(WaterRule));
}
}
WaterRule& Schedule::get(Day day) {
return rules[day];
}
char Schedule::dayIndex(char* day) {
for (byte i = 0; i < 7; i++) {
if (strcmp(days[i], day) == 0) {
return i;
}
}
return -1;
}
unsigned int Schedule::storeDay(Day day) {
return rules[day].store(day * sizeof(WaterRule));
}
void Schedule::toString(char* buf) {
unsigned int pos = 0;
for (byte i = 0; i < NUMOFDAYS; i++) {
WaterRule& rule = rules[i];
pos += sprintf(&buf[pos], "%s : ", days[i]);
if (rule.isEnabled()) {
pos += rule.toString(&buf[pos]);
pos += sprintf(&buf[pos], "\n");
}
else {
pos += sprintf(&buf[pos], "not enabled\n");
}
}
}
| true |
acdfb923a50ab0f8e28a8c8ec7707ba2e6c7755e | C++ | vietthai2512/NetworkProgramming | /Example/Client.cpp | UTF-8 | 9,393 | 2.71875 | 3 | [] | no_license | // Task1_Client.cpp : Defines the entry point for the console application.
//
// Note: I define state block: -1 and state active 1
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#define BUFF_SIZE 2048
#define MAX_TRY_REQUEST 10
#define ACTIVE 1 // Account is active
#define BLOCKED -1 // Account is blocked
#define USERNAME_NOTFOUND -11
#define USERNAME_CORRECT 11
#define PASSWORD_INCORRECT -21
#define PASSWORD_CORRECT 21
#define LOGOUT_ERROR -31
#define LOUGOUT_SUCESS 31
#define ACCOUNT_LOGINED 41
// Link with Ws2_32.lib
#pragma comment(lib,"Ws2_32.lib")
// Prototype functions
void checkArguments(int argc, char **argv, char *serverIP, int *serverPort);
void checkIPv4Addr(char *ipAddr, char *serverIP);
int checkPortNumber(char *port);
void connectServer(SOCKET &client, sockaddr_in serverAddr);
int sendExt(SOCKET s, char *buff, int dataLen);
int recvExt(SOCKET s, char *buff);
void exitExt(int exitValue);
void checkUser(char *data);
void checkPassword(char *data);
void checkLogout(char *data);
void getData(char *recvBuff, char *data);
/**
Check arguments from keyboard
@param argc: Number of arguments
@param serverIP: Pointer to Server IP Address (string)
@param serverPort: Pointer to Server Port (int)
@return: No return value or exit (0) if Invalid arguments
*/
void checkArguments(int argc, char **argv, char *serverIP, int *serverPort) {
if (argc != 3) {
printf("\nUsage: %s ServerIP ServerPort.\n", argv[0]);
printf("Example: %s 127.0.0.1 5000\n", argv[0]);
system("pause");
exit(0);
}
checkIPv4Addr(argv[1], serverIP);
*serverPort = checkPortNumber(argv[2]);
if (serverIP[0] == '\0' || *serverPort == -1) {
system("pause");
exit(0);
}
printf(" ------------------------------------------------\n");
printf(" Welcome to application!\n");
}
/**
Checking the validity of the IP address
@param ipAddr: Pointer to argv[1].
@param serverIP: Pointer to Server IP Address (string)
@return: No return value.
*/
void checkIPv4Addr(char *ipAddr, char *serverIP) {
int i = 0;
int decValueAscii = 0;
static bool findChar = false;
int countDot = 0;
int len = strlen(ipAddr);
for (i = 0; ipAddr[i] != '\0'; i++) {
decValueAscii = ipAddr[i] - '0';
if (decValueAscii == -2) {
countDot++; // Find "."
continue;
}
else if (decValueAscii < 0 || decValueAscii > 9) {
findChar = true; // Find character
break;
}
}
unsigned long rs = inet_addr(ipAddr);
// Find character or octet of value greater than 255
if (findChar == true || countDot != 3 || rs == INADDR_NONE) {
printf("The IP address of server invalid.\n");
serverIP[0] = '\0'; // ServerIP = NULL if IP address invalid.
}
else strcpy_s(serverIP, 16, ipAddr);
}
/**
Checking the validity of the port
@param port: Pointer to port (string from keyboard
@return: port value (int) or error (-1)
*/
int checkPortNumber(char *port) {
int i = 0, decValueAscii = 0;
static bool findChar = false;
int len = strlen(port);
for (i = 0; port[i] != '\0'; i++) {
decValueAscii = port[i] - '0';
if (decValueAscii < 0 || decValueAscii > 9) {
findChar = true;
break;
}
}
// Find charachter or len(port) greater than len (65535)
if (findChar == true || len > 5) {
printf("The port value of server invalid.\n");
return -1;
}
// Caculate value port
i = 0;
int valuePort = 0;
while (i < len) {
valuePort = valuePort * 10 + (port[i] - '0');
i++;
}
return valuePort;
}
/**
Try connect to server
@param client: Socket using connect to server
@param serverAddr: socket address of server (connected)
@return: No return value or exit(0) if client disconnected with server
*/
void connectServer(SOCKET &client, sockaddr_in serverAddr) {
// Max request: 10
int countRequest = MAX_TRY_REQUEST;
int iResult = 0, dwError = 0;
while (1) {
iResult = connect(client, (sockaddr*)&serverAddr, sizeof(serverAddr));
if (iResult == SOCKET_ERROR) {
dwError = WSAGetLastError();
printf("Cannot connect to server. Error: %d.\n", dwError);
countRequest--;
if (!countRequest) {
exitExt(0);
}
}
else break;
}
printf("Client started at local host!\n");
printf("Connected with server!\n");
printf("Sending to TCP Server ...\n");
printf("Type USER:username to login.\n PASS:password to login.\n LGOU:username to logout.\n");
}
/** The send() wrapper function. */
int sendExt(SOCKET s, char *buff, int dataLen) {
int ret = send(s, buff, dataLen, 0);
if (ret == SOCKET_ERROR)
printf("Cannot send message. Error: %d\n.", WSAGetLastError());
return ret;
}
/** The recv() wrapper function. */
int recvExt(SOCKET s, char *buff) {
int ret = recv(s, buff, BUFF_SIZE, 0);
if (ret == SOCKET_ERROR) {
if (ret == WSAETIMEDOUT)
printf("Time-out!");
else
printf("Cannot receive message. Error: %d.\n", WSAGetLastError());
}
return ret;
}
/** The exit() wrapper function. */
void exitExt(int exitValue) {
WSACleanup();
system("pause");
exit(exitValue);
}
/**
Check User login
@param data: opcode of action check user
@return: No return value
*/
void checkUser(char *data) {
if (data[0] == USERNAME_NOTFOUND)
printf(" Username not found.\n");
else if (data[0] == BLOCKED)
printf(" Account is blocking.Enter other Username.\n");
else if (data[0] == ACCOUNT_LOGINED)
printf(" There exists a successful login account.\n You must logout before login the new account.\n");
else
printf(" OK! Username exist.Enter password to login.\n");
}
/**
Check password login
@param data: opcode of action check password
@return: No return value
*/
void checkPassword(char *data) {
if (data[0] == PASSWORD_INCORRECT)
printf(" Password incorrect.\n");
else if (data[0] == PASSWORD_CORRECT)
printf(" Password correct.\n Account login sucessfull.\n");
else if (data[0] == BLOCKED)
printf(" Account is blocking.Enter other Username.\n");
else if (data[0] == ACCOUNT_LOGINED)
printf(" There exists a successful login account.\n You must logout before type password.\n");
else
printf(" No User wating authenticated.\n");
}
/**
Send request logout to server
@param data: opcode of actioc check logout
@return: No return value
*/
void checkLogout(char *data) {
char userName[32];
int i = 1;
while (data[i] != '\0') {
userName[i - 1] = data[i];
i++;
}
userName[i - 1] = '\0';
if (data[0] == LOUGOUT_SUCESS)
printf(" Logout %s sucessfull.\n", userName);
else
printf(" Logout failed. Because no account logined.\n");
}
/**
Get data in message receive from client
@param recvBuff: Pointer to recvBuff string receive from client
@param data: Pointer to data in recvBuff
@return: No return value
*/
void getData(char *recvBuff, char *data) {
memset(data, 0, BUFF_SIZE);
int i = 5;
while (recvBuff[i] != '\0') {
data[i - 5] = recvBuff[i];
i++;
}
data[i - 5] = '\0';
}
int main(int argc, char **argv) {
char serverIP[16];
int serverPort = 0;
checkArguments(argc, argv, serverIP, &serverPort);
// Step 1: Initiate WinSock 2.2
WSADATA wsaData;
WORD wVersion = MAKEWORD(2, 2);
if (WSAStartup(wVersion, &wsaData)) {
printf("Version is not supported.\n");
system("pause");
return 0;
}
// Step 2: Construct socket
SOCKET client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client == INVALID_SOCKET) {
printf("Initiate socket fail. Error: %d.\n", WSAGetLastError());
exitExt(0);
}
// (optional) Set time-out for receiving
int tv = 1000; // Time-out interval: 1000 ms
int iResult = setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, (const char*)(&tv), sizeof(int));
if (iResult == SOCKET_ERROR) {
printf("Setup time-out for receiving fail. Error: %d.", WSAGetLastError());
closesocket(client);
exitExt(0);
}
// Step 3: Specify server address
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(serverPort);
serverAddr.sin_addr.s_addr = inet_addr(serverIP);
// Step 4: Request to connect server
connectServer(client, serverAddr);
// Step 5: Communicate with server
char buff[BUFF_SIZE];
int ret;
char msg_type[5];
char data[BUFF_SIZE];
while (1) {
// Send message
printf("Send to server: ");
gets_s(buff, BUFF_SIZE);
if (buff[0] == '\0') break;
ret = sendExt(client, buff, strlen(buff));
if (ret == SOCKET_ERROR) break;
// Receive echo message
ret = recvExt(client, buff);
if (ret == SOCKET_ERROR) break;
else {
buff[ret] = '\0';
printf("Receive from server[%s:%d]:\n", inet_ntoa(serverAddr.sin_addr), ntohs(serverAddr.sin_port));
strncpy_s(msg_type, 5, buff, 4);
getData(buff, data);
if (strcmp(msg_type, "USER") == 0)
checkUser(data);
else if (strcmp(msg_type, "PASS") == 0)
checkPassword(data);
else if (strcmp(msg_type, "LGOU") == 0)
checkLogout(data);
else
printf(" Invalid request.\n");
}
}
// Step 6: Close socket
closesocket(client);
// Step 7: Terminate Winsock
exitExt(0);
}
| true |
68b9aa7b39334111bf54c9bd0ec1f0813c5927d7 | C++ | Sahil12S/LeetCode | /Cplusplus/mergeKSortedLists.cpp | UTF-8 | 2,465 | 3.6875 | 4 | [] | no_license | // USING MIN HEAP
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
struct Compare {
bool operator() ( ListNode* l1, ListNode* l2 ) {
return l1->val > l2->val;
}
};
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* result = nullptr;
ListNode* last;
priority_queue< ListNode*, vector< ListNode* >, Compare > pq;
for ( auto list : lists )
{
if( list != nullptr )
{
pq.push( list );
}
}
while ( !pq.empty() )
{
ListNode* top = pq.top();
pq.pop();
if ( top->next != nullptr )
{
pq.push( top->next );
}
if ( result == nullptr )
{
result = top;
last = top;
}
else
{
last->next = top;
last = top;
}
}
return result;
}
};
// USING DIVIDE AND CONQUER
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode* merge( ListNode* l1, ListNode* l2 )
{
ListNode* result = nullptr;
if ( l1 == nullptr )
{
return l2;
}
else if ( l2 == nullptr )
{
return l1;
}
if ( l1->val <= l2->val )
{
result = l1;
result->next = merge( l1->next, l2 );
}
else
{
result = l2;
result->next = merge( l1, l2->next );
}
return result;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if ( lists.size() == 0 )
{
return nullptr;
}
int last = lists.size() - 1;
while ( last != 0 )
{
int i = 0;
int j = last;
while ( i < j )
{
lists[i] = merge( lists[i], lists[j] );
i++, j--;
if ( i >= j )
{
last = j;
}
}
}
return lists[0];
}
}; | true |
1760414009778a152bba042a9fa14a2a8384436a | C++ | MrPoldi/GRK-Projekt | /src/ParticleEmiterTex.cpp | UTF-8 | 5,515 | 2.78125 | 3 | [] | no_license | #include "ParticleEmiterTex.h"
#include <cstdlib>
#include "Texture.h"
//ParticleEmitterTex::ParticleEmitterTex(GLuint* program)
//{
// this->program = program;
//
// this->positionsArr = new float[PARTICLES_COUNT * 4];
//
// particles.resize(PARTICLES_COUNT);
// for (int i = 0; i < PARTICLES_COUNT; ++i)
// {
// particles[i].position = glm::vec3(0);
// particles[i].lifetime = randomFloat(1.0f, 2.0f);
// particles[i].radius = 0.01f;
// }
//
// generateBuffers();
//}
ParticleEmitterTex::ParticleEmitterTex(GLuint* program, int particleCount, float particleSize, GLuint texId)
{
this->program = program;
this->positionsArr = new float[particleCount * 4];
this->particleSize = particleSize;
this->texId = texId;
particles.resize(particleCount);
for (int i = 0; i < particleCount; ++i)
{
particles[i].position = glm::vec3(0);
particles[i].velocity = glm::normalize(glm::vec3(randomFloat(-2, 2), randomFloat(-2, 2), randomFloat(-2, 2)));
particles[i].lifetime = randomFloat(1.0f, 2.0f);
particles[i].radius = 0.02f;
}
generateBuffers();
}
void ParticleEmitterTex::generateBuffers()
{
glGenBuffers(1, &particleVertexBuffer);
std::vector< float > vertices;
vertices.push_back(0.0f); vertices.push_back(0.0f); vertices.push_back(0.0f);
vertices.push_back(1.0f); vertices.push_back(0.0f); vertices.push_back(0.0f);
vertices.push_back(0.0f); vertices.push_back(1.0f); vertices.push_back(0.0f);
vertices.push_back(1.0f); vertices.push_back(1.0f); vertices.push_back(0.0f);
glBindBuffer(GL_ARRAY_BUFFER, particleVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), vertices.data(), GL_STATIC_DRAW);
glGenBuffers(1, &particlePositionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, particlePositionBuffer);
glBufferData(GL_ARRAY_BUFFER, particles.size() * 4 * sizeof(float), positionsArr, GL_DYNAMIC_DRAW);
glGenBuffers(1, &particleTexBuffer);
std::vector<float> texCoord;
texCoord.push_back(0.0f); texCoord.push_back(0.0f);
texCoord.push_back(0.0f); texCoord.push_back(1.0f);
texCoord.push_back(1.0f); texCoord.push_back(0.0f);
texCoord.push_back(1.0f); texCoord.push_back(1.0f);
glBindBuffer(GL_ARRAY_BUFFER, particleTexBuffer);
glBufferData(GL_ARRAY_BUFFER, texCoord.size() * sizeof(float), texCoord.data(), GL_STATIC_DRAW);
}
void ParticleEmitterTex::setupUniforms(const glm::mat4 transformation, glm::mat4 cameraMatrix, glm::mat4 perspectiveMatrix)
{
glUniformMatrix4fv(glGetUniformLocation(*program, "transformation"), 1, GL_FALSE, (float*)&transformation);
glUniformMatrix4fv(glGetUniformLocation(*program, "M_v"), 1, GL_FALSE, (float*)&cameraMatrix);
glUniformMatrix4fv(glGetUniformLocation(*program, "M_p"), 1, GL_FALSE, (float*)&perspectiveMatrix);
glUniform1f(glGetUniformLocation(*program, "particleSize"), this->particleSize);
Core::SetActiveTexture(this->texId, "textureSampler", *this->program, 0);
}
float clamp(float min, float max, float a){
if (a > max) return max;
if (a < min) return min;
return a;
}
void ParticleEmitterTex::update(const float dt, const glm::mat4 transformation, glm::mat4 cameraMatrix, glm::mat4 perspectiveMatrix)
{
glUseProgram(*program);
setupUniforms(transformation, cameraMatrix, perspectiveMatrix);
for (int i = 0; i < particles.size(); ++i)
{
particles[i].lifetime -= dt*3;
//particles[i].radius += 0.0075;
//this->particleSize -= 0.000005f;
//ethis->particleSize = clamp(0.0, this->particleSize, this->particleSize - 0.000001f);
this->particleSize *= 0.999985f;
glUniform1f(glGetUniformLocation(*program, "particleSize"), this->particleSize);
/*if (particles[i].lifetime <= 0.0f)
{
particles[i].position = glm::vec3(0);
particles[i].lifetime = randomFloat(1.0f, 2.0f);
particles[i].radius = 0.02f;
}*/
float radius = particles[i].radius;
//particles[i].position -= glm::vec3(randomFloat(-radius, radius), randomFloat(-radius, radius), randomFloat(-radius, radius));
particles[i].position += particles[i].velocity * 0.035f;
positionsArr[i * 4 + 0] = particles[i].position[0];
positionsArr[i * 4 + 1] = particles[i].position[1];
positionsArr[i * 4 + 2] = particles[i].position[2];
positionsArr[i * 4 + 3] = particles[i].lifetime;
}
}
void ParticleEmitterTex::draw()
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_NOTEQUAL, 0.0);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glBindBuffer(GL_ARRAY_BUFFER, particlePositionBuffer);
glBufferSubData(GL_ARRAY_BUFFER, 0, particles.size() * 4 * sizeof(float), positionsArr);
glBindBuffer(GL_ARRAY_BUFFER, particleVertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, particlePositionBuffer);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribDivisor(4, 1);
glBindBuffer(GL_ARRAY_BUFFER, particleTexBuffer);
glVertexAttribPointer(5, 2, GL_FLOAT, false, 0, nullptr);
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, particles.size());
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(4);
glDisableVertexAttribArray(5);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
}
float ParticleEmitterTex::randomFloat(float min, float max) {
return (max - min) * ((((float)rand()) / (float)RAND_MAX)) + min;
}
ParticleEmitterTex::~ParticleEmitterTex()
{
glDeleteBuffers(1, &particleVertexBuffer);
glDeleteBuffers(1, &particlePositionBuffer);
glDeleteBuffers(1, &particleTexBuffer);
} | true |
3907943da0a3c936630acaf41a618d0481b4f8a4 | C++ | Gonefar/PAT-advanced-partly | /pat68.cpp | UTF-8 | 2,757 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
struct element
{
int val;
int index;
};
int mySum(vector <element> proj)
{
int sum = 0;
if( 0 == proj.size() )
{
return 0;
}
else
{
for( int j = 0; j < proj.size(); j++ )
{
sum += proj[j].val;
}
}
return sum;
}
int show(vector <element> proj)
{
int i = 0;
for( i = 0; i < proj.size(); i++ )
{
if( i > 0 )
{
cout << " ";
}
cout << proj[i].val;
}
cout << endl;
return 0;
}
int isEndLess(vector <element> proj)
{
int i = 0;
if( proj.size() == 1 )
{
return 0;
}
for( i = 0; i < proj.size() - 1; i++ )
{
if( proj[i].index != proj[i+1].index + 1 )
{
return 1;
}
}
return 0;
}
int process(int acoin[], int num, int payAmt)
{
vector <element> proj;
int sum = 0, i = 0, lastIndex = 0;
element tmp = {acoin[0], 0};
proj.push_back(tmp);
while(1)
{
sum = mySum(proj);
//show(proj);
if( sum < payAmt )
{
if( lastIndex == num - 1 )
{
if( 0 == isEndLess(proj) )
{
cout << "No solution\n";
return 1;
}
else
{
//lastIndex = proj[0].index;
//proj.clear();
proj.pop_back();
lastIndex = proj[proj.size() - 1].index;
proj.pop_back();
}
}
else
{
lastIndex++;
tmp.val = acoin[lastIndex];
tmp.index = lastIndex;
proj.push_back(tmp);
}
}
else if( sum > payAmt )
{
if( lastIndex == num - 1 && 0 == isEndLess(proj) )
{
cout << "No solution\n";
return 1;
}
if( proj.size() <= 1 )
{
cout << "No solution\n";
return 1;
}
proj.pop_back();
lastIndex = proj[proj.size() - 1].index;
proj.pop_back();
}
else
{
show(proj);
return 0;
}
}
return 0;
}
int main()
{
int coinNum, payAmt, i;
cin >> coinNum >> payAmt;
int *acoin = new int [coinNum];
for( i = 0; i < coinNum; i++ )
{
cin >> acoin[i];
}
sort(acoin, acoin+coinNum);
process(acoin, coinNum, payAmt);
return 0;
}
| true |
abcd1017eb220a08b5b03de9c6e5d47b28233860 | C++ | TackticalDude/algorithmsPlayground | /TOS_Equalizer/src/Equalizer.h | UTF-8 | 753 | 2.640625 | 3 | [] | no_license | /*
* Equalizer.h
*
* Created on: Jun 29, 2015
* Author: TackticalDude
*/
#ifndef EQUALIZER_H_
#define EQUALIZER_H_
#include "Coefficient.h"
#include "Queue.h"
#include <thread>
#include <stdlib.h>
#include <iostream>
#include <string>
/**
* @class Equalizer
* @brief Makes a thread to recalculate blocks
*/
class Equalizer {
private:
Queue *_from;
Queue *_to;
biquad_t _treble;
biquad_t _bass;
std::thread _objThread;
std::string _name;
bool finished;
public:
Equalizer(Queue *form, Queue *to, biquad_t treble, biquad_t bass);
Equalizer(Queue *form, Queue *to, biquad_t treble, biquad_t bass, std::string name);
void run();
void stop();
~Equalizer();
};
#endif /* EQUALIZER_H_ */
| true |
d5bdf50cac1c4b43196e7af5f49c421ca8ec9973 | C++ | herzfactory/AlgospotRepository | /CPP/WeeklyCalendar.cpp | UTF-8 | 1,636 | 3.375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
const int DAY_OF_WEEK = 7;
int lastDayOfMonth[] = {28, 30, 31};
char dayOfTheWeek[][10] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
void __fpurge() {
while (getchar() != '\n');
}
int* createWeeklyCalendar(int sunday, int last, int current) {
int* week = new int[DAY_OF_WEEK];
int lastday = current;
if (sunday < 1) {
sunday += last;
lastday = last;
}
for (int i = 0; i < DAY_OF_WEEK; i++) {
week[i] = (sunday + i) % lastday;
if (week[i] == 0) week[i] = lastday;
}
return week;
}
int main () {
int cases;
scanf("%d", &cases); __fpurge();
while (cases--) {
int month, day, sunday;
char dayOfWeek[1024];
scanf("%d %d", &month, &day);
getchar(); fgets(dayOfWeek, 1024, stdin);
for (int i = 0; i < DAY_OF_WEEK; i++) {
if (strncmp(dayOfTheWeek[i], dayOfWeek, strlen(dayOfWeek) - 1) == 0) sunday = day - i;
}
int* week;
switch (month) {
case 1 : case 8 :
week = createWeeklyCalendar(sunday, lastDayOfMonth[2], lastDayOfMonth[2]);
break;
case 2 :
week = createWeeklyCalendar(sunday, lastDayOfMonth[2], lastDayOfMonth[0]);
break;
case 3 :
week = createWeeklyCalendar(sunday, lastDayOfMonth[0], lastDayOfMonth[2]);
break;
case 4 : case 6 : case 9 : case 11 :
week = createWeeklyCalendar(sunday, lastDayOfMonth[2], lastDayOfMonth[1]);
break;
case 5 : case 7 : case 10 : case 12 :
week = createWeeklyCalendar(sunday, lastDayOfMonth[1], lastDayOfMonth[2]);
break;
}
for (int i = 0; i < DAY_OF_WEEK; i++) {
if (i != 0) printf(" ");
printf("%d", week[i]);
}
printf("\n");
}
}
| true |
d0943333b8408bb066a9e212b8af147b00772440 | C++ | ArtyomAdov/learning_sibsutis | /learning/thirdparty/OS/Лабораторная №13/p2.cpp | UTF-8 | 657 | 2.515625 | 3 | [] | no_license | #include <windows.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char buff[80];
fprintf(stdout, "<HTML>");
fprintf(stdout, "<BODY bgcolor=#FFDD00>");
fprintf(stdout, "<CENTER><TABLE>");
while (fgets(buff,80,stdin))
{
char *p = strchr(buff, '\n');
if (p)
*p='\0';
fprintf(stdout, "<TR>");
fprintf(stdout, "<TD>");
fprintf(stdout, "<H1>");
fprintf(stdout, "%s", buff);
fprintf(stdout, "</H1>");
fprintf(stdout, "</TD>");
fprintf(stdout, "</TR>");
}
fprintf(stdout, "</TABLE></CENTER");
fprintf(stdout, "</BODY>");
fprintf(stdout, "</HTML>");
return 0;
}
| true |
40c6d5142b2b5ea39dc82c5ee79c432533387649 | C++ | a5batra/LeetCode-Solutions-in-C-plus-plus | /shuffleAnArray.cpp | UTF-8 | 1,352 | 4.03125 | 4 | [] | no_license | //
// Created by Ankit Batra on 7/20/21.
//
/* Given an integer array nums, design an algorithm to randomly shuffle the array.
* All permutations of the array should be equally likely as a result of the shuffling.
* Implement the Solution class:
* Solution(int[] nums) Initializes the object with the integer array nums.
* int[] reset() Resets the array to its original configuration and returns it.
* int[] shuffle() Returns a random shuffling of the array. */
class Solution {
vector<int> arr;
public:
Solution(vector<int>& nums) {
arr = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return arr;
}
/** Returns a random shuffling of the array. */
void swapper(vector<int>& arr, int idx1, int idx2) {
int temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
vector<int> shuffle() {
vector<int> randomArray = arr;
for (int i = arr.size() - 1; i > 0; --i) {
int randomIdx = rand() % (i + 1);
swapper(randomArray, randomIdx, i);
}
return randomArray;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/
| true |
03d80fb2fa0be308b63809a84f5fa8e08c408a25 | C++ | victor-timoshin/Switch | /src/Switch.Core/include/Switch/System/Threading/Tasks/Parallel.hpp | UTF-8 | 2,923 | 3.09375 | 3 | [
"MIT"
] | permissive | /// @file
/// @brief Contains Switch::System::Threading::Tasks::Parallel class.
#pragma once
#include "Task.hpp"
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The System::Threading namespace provides classes and interfaces that enable multithreaded programming. In addition to classes for synchronizing thread activities and access to data ( Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.
namespace Threading {
/// @brief The System::Threading::Tasks namespace provides types that simplify the work of writing concurrent and asynchronous code. The main types are System::Threading::Tasks::Task which represents an asynchronous operation that can be waited on and cancelled, and System::Threading::Tasks::Task<TResult>, which is a task that can return a value. The System::Threading::Tasks::TaskFactory class provides static methods for creating and starting tasks, and the System::Threading::Tasks::TaskScheduler class provides the default thread scheduling infrastructure.
namespace Tasks {
/// @brief Provides support for parallel loops and regions.
class Parallel static_ {
public:
/// @brief Executes each of the provided actions, possibly in parallel.
/// @par Library
/// Switch.Core
/// @param An array of Action to execute.
/// @remarks This method can be used to execute a set of operations, potentially in parallel.
/// @remarks No guarantees are made about the order in which the operations execute or whether they execute in parallel. This method does not return until each of the provided operations has completed, regardless of whether completion occurs due to normal or exceptional termination.
/// @par Examples
/// This example demonstrates how to use the Invokemethod with other methods, anonymous delegates, and lambda expressions.
/// @include ParallelInvoke.cpp
static void Invoke(const Array<Action<>>& actions) {
System::Collections::Generic::List<Task<>> tasks;
for (const auto& action : actions)
tasks.Add(Task<>::Factory().StartNew(action));
Task<>::WaitAll(tasks.ToArray());
}
/// @cond
template<typename ...Args>
static void Invoke(Args... args) {Invoke({args...});}
/// @endcond
};
}
}
}
}
using namespace Switch;
| true |
ead394d5813accad3bccdf6dfc00b6c4e982a5e3 | C++ | vinaymenda/ignou-assignments | /mcs-21/ques-1.cpp | UTF-8 | 2,277 | 4.21875 | 4 | [] | no_license | /*
Write an algorithm that accepts a Tree as input and converts it into a Binary Tree and then prints
all the leaf nodes that are part of both Tree and Binary Tree
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *left;
struct node *right;
};
struct node* insert(struct node *curr, struct node *newnode)
{
if(curr == NULL)
{
curr = newnode;
}
else
{
if(newnode -> value <= curr -> value)
{
if(curr -> left == NULL)
{
curr -> left = newnode;
}
else
{
insert(curr -> left, newnode);
}
}
else
{
if(curr -> right == NULL)
{
curr -> right = newnode;
}
else
{
insert(curr -> right, newnode);
}
}
}
return curr;
}
void inorder(struct node *curr)
{
if(curr -> left != NULL)
{
inorder(curr -> left);
}
printf("%d ", curr -> value);
if(curr -> right != NULL)
{
inorder(curr -> right);
}
}
void preorder(struct node *curr)
{
printf("%d ", curr -> value);
if(curr -> left != NULL)
{
preorder(curr -> left);
}
if(curr -> right != NULL)
{
preorder(curr -> right);
}
}
void postorder(struct node *curr)
{
if(curr -> left != NULL)
{
postorder(curr -> left);
}
if(curr -> right != NULL)
{
postorder(curr -> right);
}
printf("%d ", curr -> value);
}
void printleaves(struct node *curr)
{
if(curr == NULL)
{
return;
}
if(curr -> left == NULL && curr -> right == NULL)
{
printf("%d ", curr-> value);
}
printleaves(curr -> left);
printleaves(curr -> right);
}
int main()
{
int numberOfnodes; int value;
printf("Enter number of nodes: ");
scanf("%d", &numberOfnodes);
struct node *root = NULL;
while(numberOfnodes!=0)
{
printf("Enter node value: ");
scanf("%d", &value);
struct node *newnode = (struct node*)malloc(sizeof(struct node));
if(newnode == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
newnode->value = value;
newnode -> left = NULL; newnode -> right = NULL;
root = insert(root, newnode);
numberOfnodes--;
}
printf("\n\n");
printf("Binary tree is as follows: ");
printf("\nPreorder: ");
preorder(root);
printf("\nPostorder: ");
postorder(root);
printf("\nInorder: ");
inorder(root);
printf("\n\n");
printf("Leaf nodes: ");
printleaves(root);
return 0;
}
| true |
4a12566776b76b2a70436188865ca8afb1d0f545 | C++ | shreysingla11/ssl-project | /Backend/Parser/submissions/Assignment 12/88.cpp | UTF-8 | 4,038 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <vector>
using namespace std;
// Graph class represents a directed graph using adjacency list representation
class Graph
{
public:
int V; // No. of vertices
vector<int> *adj; // Pointer to an array containing adjacency lists
vector<int> *inv_adj;
vector<int> go; // Pointer to an array containing adjacency lists
vector<int> nogo;
vector<int> threshold;
vector<int> num_Friends;
vector<bool> go_bool;
vector<bool> nogo_bool;
Graph(int V); // Constructor
void DFSUtil(int v, bool visited[]); // A function used by DFS
void addEdge(int v, int w); // function to add an edge to graph
void DFS(int v); // DFS traversal of the vertices reachable from v
void setThreshold(int v,int t);
void setNumFriends(int v,int n);
void addinvEdge(int v, int w);
};
Graph::Graph(int V)
{
this->V = V;
adj = new vector<int>[V];
inv_adj = new vector<int>[V];
go_bool.assign(V,false);
nogo_bool.assign(V,false);
go.assign(V,0);
nogo.assign(V,0);
threshold.assign(V,0);
num_Friends.assign(V,0);
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::addinvEdge(int v, int w)
{
inv_adj[v].push_back(w); // Add w to v’s invlist.
}
void Graph::setThreshold(int v,int t)
{
threshold[v] = t;
}
void Graph::setNumFriends(int v,int n)
{
num_Friends[v] = n;
}
int main()
{
int n;
int T_i,N_i;
int f_num;
int i,j,k,isize;
cin >> n;
Graph Network(n);
for(i = 0 ; i < n ; i++)
{
cin >> T_i >> N_i;
Network.setThreshold(i,T_i);
Network.setNumFriends(i,N_i);
for(j = 0 ; j < N_i ; j++)
{
cin >> f_num;
Network.addEdge(i,f_num);
Network.addinvEdge(f_num,i);
}
}
vector<int> go_list,nogo_list;
int gosize = 0,nogosize = 0;
for(i = 0 ; i < n ; i++)
{
if(Network.threshold[i] == 0)
{
go_list.push_back(i);
Network.go_bool[i] = true;
gosize++;
continue;
}
if(Network.threshold[i] > Network.num_Friends[i])
{
nogo_list.push_back(i);
Network.nogo_bool[i] = true;
nogosize++;
continue;
}
}
{
cout << go_list[i] << endl ;
}
cout << endl;
for(i = 0 ; i < nogosize ; i++)
{
cout << nogo_list[i] << endl ;
}
gosize = go_list.size();
nogosize = nogo_list.size();
int X;
for (k = 0 ; k < gosize ; k++)
{
i = go_list[k];
isize = Network.inv_adj[i].size();
for(j = 0 ; j < isize ; j++)
{
X = Network.inv_adj[i][j];
//cout << endl << X << endl;
if(Network.go_bool[X]){continue;}
else{Network.go[X] = Network.go[X] + 1;
if(Network.go[X] >= Network.threshold[X])
{
go_list.push_back(X);
gosize = go_list.size();
}}
}
}
for (k = 0 ; k < nogosize ; k++)
{
i = nogo_list[k];
cout << "3";
isize = Network.inv_adj[i].size();
for(j = 0 ; j < isize ; j++)
{
X = Network.inv_adj[i][j];
if(Network.nogo_bool[X]){continue;}
else{
Network.nogo[X] = Network.nogo[X] + 1;
cout << "1";
if(Network.num_Friends[X]-Network.nogo[X] < Network.threshold[X])
{
cout << "2";
nogo_list.push_back(X);
nogosize = nogo_list.size();
}}
}
}
/* for(i = 0 ; i < gosize ; i++)
{
cout << go_list[i] << endl ;
}
cout << endl;
for(i = 0 ; i < nogosize ; i++)
{
cout << nogo_list[i] << endl ;
}
//cout << endl << Network.threshold[2] << Network.go[2] << Network.nogo[2] ;*/
cout << gosize << " " << n - nogosize << endl;
}
| true |
bd7f502e930097adbacc495d241f5881f2475f1e | C++ | lailianqi/-My_leetcode | /leetcode/316.h | UTF-8 | 2,901 | 3.390625 | 3 | [] | no_license | #include <string>
#include <deque>
#include <algorithm>
#include <vector>
using namespace std;
// https://segmentfault.com/a/1190000004188227
// http://www.cnblogs.com/7z7chn/p/6341453.html
// https://discuss.leetcode.com/topic/31404/a-short-o-n-recursive-greedy-solution?page=1
/*
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
*/
/*
题目分析:消除掉重复字符串后剩下的字符串要按照字典排序。我们这样思考,对于每个字符,至少得剩下一个。首先,我们遍历字符串,
记录每个字符出现的次数,然后,我们继续从头遍历字符串,每次遍历到一个字符的时候,我们需要把该字符次数减一,
当减到只剩下1的时候,表示最多只能删除到当前,因为是按照字典排序,我们需要找到到当前位置的最小字符以及其位置,
那个该位置之前的字符可以被删除,最小字符也可以被删除,提取最小字符,递归查找新串。
*/
class Solution {
public:
string removeDuplicateLetters(string s) {
if (s.empty()) {
return s;
}
vector<int> cnt(26, 0);
for (int i = 0; i < s.size(); i++) {
cnt[s[i] - 'a']++;
}
int pos = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] < s[pos]) {
pos = i;
}
if (--cnt[s[i] - 'a'] == 0) {
break;
}
}
string str = s.substr(pos + 1);
str.erase(remove(str.begin(), str.end(), s[pos]), str.end());
return s[pos] + removeDuplicateLetters(str);
}
};
// https://discuss.leetcode.com/topic/32259/java-solution-using-stack-with-comments
class Solution_0 {
public:
string removeDuplicateLetters(string s) {
vector<int> cnt(26, 0);
vector<bool> visit(26, false);
deque<char> characterQueue;
for (int i = 0; i < s.size(); i++) {
cnt[s[i] - 'a']++;
}
int index = 0;
for (int i = 0; i < s.size(); i++) {
index = s[i] - 'a';
cnt[index]--;
if (!visit[index]) {
while (!characterQueue.empty() &&
characterQueue.back() > s[i] &&
cnt[characterQueue.back() - 'a'] > 0) {
visit[characterQueue.back() - 'a'] = false;
characterQueue.pop_back();
}
characterQueue.push_back(s[i]);
visit[index] = true;
}
}
string result;
while (!characterQueue.empty()) {
result += characterQueue.front();
characterQueue.pop_front();
}
return result;
}
};
//另外一种解法
// Easy to understand iterative Java solution
// https://discuss.leetcode.com/topic/31413/easy-to-understand-iterative-java-solution | true |
b50d50a73ac5d1fc03be5b03afca8e1fd605378b | C++ | alejoOxono/codeabbey-external-solutions | /184-matches-picking/184-matches-picking.cpp | UTF-8 | 2,013 | 3.125 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>
int main(int argc, char const *argv[])
{
unsigned long N;
int rc;
errno = 0;
rc = scanf(" %lu ", &N);
if(rc != 1) {
perror("failed to read input");
exit(-1);
}
errno = 0;
unsigned long* result;
result = (unsigned long*)malloc(N * sizeof(unsigned long));
if(result == NULL) {
perror("failed to allocate result buffer\n");
exit(-1);
}
/*optimal strategy calculator for matches taking game
* 'n' is normal play where player taking last matches wins
* 'i' is inverted play where last match taker losses*/
char game_mode;
unsigned long M, K;
unsigned long ii;
for(ii = 0; ii < N; ++ii) {
errno = 0;
rc = scanf(" %lu %lu %c ", &M, &K, &game_mode);
if(rc != 3) {
printf("Input read failure in input line\n" );
}
switch (game_mode) {
/*zero matches is invalid game state*/
assert(M > 0);
case 'n':
/*simple case where we can win first move*/
if(K < M) {
result[ii] = M % (K+1);
} else {
result[ii] = K;
}
break;
case 'i':
/*simple case where we can take all but last one on first move*/
if(K+1 < M) {
result[ii] = (M-1) % (K+1);
} else {
result[ii] = M-1;
}
break;
default:
/*this should never happen so indicate error and exit*/
fprintf(stdout, "Game mode '%c' unrecognized, should be [n/i]\n", game_mode);
fflush(stdout);
exit(-1);
}
}
/*print out the results*/
for(ii = 0; ii < N; ++ii) {
fprintf(stdout, "%lu ", result[ii]);
}
fprintf(stdout,"\n");
free(result);
return 0;
} | true |
6b4fa26d6a9f6425f91c20819416499e70c5f5f4 | C++ | wabisoft/waves | /src/level_io.cpp | UTF-8 | 1,973 | 2.546875 | 3 | [] | no_license |
#include "level_io.hpp"
#include "json.hpp"
#include "logging.hpp"
#include "serialize.hpp"
#include "stage.hpp"
#include "system.hpp"
bool LevelIO::open(Stage& stage, std::string& message) {
Stage s_ = {};
SerializeError e;
if(!loadStageFromFile(filename, s_, e)) {
message = "Failed to load file: " + filename + ".\nError: " + e.what;
logger.debug(message.c_str());
open_ = false;
} else {
message = "Opened file: " + filename + ".";
logger.debug("%s\n", message.c_str());
filename = filename;
stage = s_;
// s.state = editor->stage.state;
open_ = true;
}
return open_;
}
bool LevelIO::open(sf::WindowHandle windowHandle, Stage& stage, std::string& message) {
std::string filename = "";
if(selectAFileForOpen(windowHandle, filename, "Select a level to edit", "JSON Files\0*.json\0\0")) {
return open(stage, message);
} else {
message = "File selection cancelled";
logger.debug("%s\n", message.c_str());
return open_;
}
}
bool LevelIO::saveAndValidate(Stage& stage, std::string& message) {
SerializeError e;
if (! dumpStageToFile(filename, stage, e)) {
message = "Failed to save stage to file.\nError: " + e.what;
logger.debug("%s\n", message.c_str());
return false;
} else {
message = "Successfully saved to " + filename + "!";
logger.debug("%s\n", message.c_str());
return true;
}
}
bool LevelIO::save(sf::WindowHandle windowHandle, Stage& stage, std::string& message) {
if(filename.empty()) {
if(selectAFileForSave(windowHandle, filename, "Select a file to save level", "JSON Files\0*.json\0\0")) {
return saveAndValidate(stage, message);
}
} else {
return saveAndValidate(stage, message);
}
}
bool LevelIO::saveAs(sf::WindowHandle windowHandle, Stage& stage, std::string& message) {
SerializeError e;
std::string fname;
if(selectAFileForSave(windowHandle, fname, "Select file to save level as", "JSON Files\0*.json\0\0")) {
filename = fname;
return saveAndValidate(stage, message);
}
}
| true |
00e11155a8060e151f14db8086792d0c562ccc0f | C++ | I4I13I92/CppReview | /Tutorials/DS/Queue.cpp | UTF-8 | 4,300 | 3.953125 | 4 | [] | no_license | #include <iostream>
#include "Queue.h"
Queue::Queue()
{
this->front = 0; //set the front/back to the first element
this->back = 0;
this->nodes = new int[8]; //set the intitial capacity of the queue to 8
this->length = 0; //variable to keep track of elements used of queue
this->capacity = 8; //keep track of the capacity in case for resizing
}
//Class Destructor to delete dynamic array
Queue::~Queue()
{
delete[] this->nodes; //delete dynamically allocated array
this->nodes = nullptr; //set to NULL pointer
}
int Queue::pop()
{
int popped = 0; //where popped value will be stored
if (this->isEmpty()) //check to see if queue is not empty first
{
std::cout << "The queue is empty.\n";
return 0; //return 0 if it is empty, NEED TO FIND ALTERNATIVE WAY TO HANDLE THIS CASE!
}
else
{
popped == this->nodes[front]; //pop the front of the queue into variable POPPED
this->front++; //update the front of the queue
this->length--; //decrease the current length of the queue
}
return popped;
}
void Queue::insert(int value)
{
if (this->reachedCapacity()) //check to see if length has reached the capacity
{
this->resize(); //resize the queue
}
else if(!(this->isEmpty()) && this->front == this->back) //check to see if the front and back are at the same element and the queue is not empty
{ //in order to shift them both back to the 1st element
this->nodes[0] = this->nodes[back]; //if the is only one element left and not at [0], reshft its conetents there.
this->back = 0; //Reset the front and back back to the first element
this->front = 0;
}
else if (this->back == this->capacity - 1 && this->front != 0) //Check to see if we can wrap around the array for the back if there is space available
{
this->back = 0; //reset the back to point to the 1st element to wrap around
}
this->nodes[back] = value; //insert the node to the back of the queue, with 1st insertion also being the front
this->length++; //increment length
this->back++; //update the back to the following element
}
//Function to check if queue is empty
bool Queue::isEmpty()
{
if (this->length == 0) //returns true if it is empty
{
return true;
}
else
{
return false; //else returns false if not
}
}
void Queue::resize()
{
int* resize_queue = new int[2 * this->capacity]; //create a new dynamic array who's capacity is twice as large as the this->nodes
int shifted_start_index = this->front - this->capacity; //store the difference to offset the front of the two arrays
//when copying over during resizing
for (int i = 0, j = this->front; i < shifted_start_index; i++, j++) //use of i for the new resized array,
{ //j to start wherever the front maybe from previous array
resize_queue[i] = this->nodes[j];
}
shifted_start_index = this->front - this->capacity; //this time its used as starting point to copy over the rest of the elements
//due to this->array being wrapped around
for (int i = shifted_start_index, j = 0; j <= this->back; i++, j++) //have i iterate through the newly sized array and pick up from the above iteration,
{ //while j will iterate through this->nodes starting from the first element, til it
//reaches where the for loop above started
resize_queue[shifted_start_index] = this->nodes[j]; //copy over the remaining elements
}
delete[] this->nodes; //deallocate the old data the this->nodes holds
this->nodes = resize_queue; //update so this->nodes now points to the larger array with the copied pointers
resize_queue = nullptr; //set resize_queue to NULL pointer
this->capacity *= 2; //double the capacity to keep track of the new array
}
//Function to check if the length of queue has reached its capacity
bool Queue::reachedCapacity()
{
if (this->length > 0 && this->length == this->capacity) //Check to see if the length matches the capacity of the dynamic array
{ //and make sure length is greater than 0 or resizing will occur when length is 0.
return true;
}
else
{
return false;
}
}
| true |
05bd76e23a13ed8973cdf9a785537325844ed0c6 | C++ | dsbabkov/MeshTranslator | /source/GeometryReader.cpp | UTF-8 | 623 | 2.6875 | 3 | [] | no_license | #include "GeometryReader.h"
#include <fstream>
using namespace std;
GeometryReader::GeometryReader(const string &fileName)
: is_{make_unique<ifstream>(fileName)}
{
}
bool GeometryReader::isOpen() const
{
return is_->is_open();
}
void GeometryReader::skipCast()
{
int nodeCount = -1;
int elementCount = -1;
*is_ >> nodeCount >> elementCount;
string line;
getline(*is_, line);
for (int i = 0; i < nodeCount + elementCount * 2; ++i){
getline(*is_, line);
}
}
ifstream *GeometryReader::getStream() const
{
return is_.get();
}
GeometryReader::~GeometryReader() = default;
| true |
48271707a6eb6e4da28c49ea586b591fe535491b | C++ | khml/cyan | /cyan/include/cyan/impl/code_block.hpp | UTF-8 | 2,730 | 3.15625 | 3 | [
"MIT"
] | permissive | /**
* @file code_block.hpp
* @brief impl CodeBlock template functions
* @author KHML
*/
#ifndef CYAN_IMPL_CODE_BLOCK_HPP
#define CYAN_IMPL_CODE_BLOCK_HPP
namespace cyan
{
template<typename Control>
CodeBlock& CodeBlock::includeCtrl(const Control& control)
{
mergeVector(lines, control.codeGen(0));
return *this;
}
template<typename Control>
CodeBlock& CodeBlock::includeCtrl(Control&& control)
{
mergeVector(lines, control.codeGen(0));
return *this;
}
template<typename Value>
void CodeBlock::createArithmeticOp(std::string&& op, Value& right, Value& left, cyan::Variable& result)
{
lines.emplace_back(result() + " = " + right() + " " + op + " " + left() + ";");
registerVariable(result);
}
template<typename Value>
void CodeBlock::createAdd(Value& right, Value& left, Variable& result)
{
createArithmeticOp("+", right, left, result);
registerVariable(result);
}
template<typename Value>
void CodeBlock::createSub(Value& right, Value& left, Variable& result)
{
createArithmeticOp("-", right, left, result);
registerVariable(result);
}
template<typename Value>
void CodeBlock::createMul(Value& right, Value& left, Variable& result)
{
createArithmeticOp("*", right, left, result);
registerVariable(result);
}
template<typename Value>
void CodeBlock::createDiv(Value& right, Value& left, Variable& result)
{
createArithmeticOp("/", right, left, result);
registerVariable(result);
}
template<typename Value>
void CodeBlock::createMod(Value& right, Value& left, Variable& result)
{
createArithmeticOp("%", right, left, result);
registerVariable(result);
}
template<typename Value>
void CodeBlock::createRetValue(Value& value)
{
lines.emplace_back("return " + value() + ";");
}
template<typename Value>
void CodeBlock::createRetValue(Value&& value)
{
lines.emplace_back("return " + value() + ";");
}
template<typename Value>
void CodeBlock::createStdOut(const Value& value)
{
lines.emplace_back("std::cout << " + value() + " << std::endl;");
}
template<typename Value>
void CodeBlock::createStdOut(Value&& value)
{
createStdOut(value);
}
template<typename Value>
void CodeBlock::createStdErrOut(const Value& value)
{
lines.emplace_back("std::cerr << " + value() + " << std::endl;");
}
template<typename Value>
void CodeBlock::createStdErrOut(Value&& value)
{
createStdErrOut(value);
}
}
#endif //CYAN_CODE_BLOCK_HPP
| true |
bef91892fa6d0abfdb0cb44d136907642a4774b6 | C++ | miney727/Baekjoon | /동적 계획법 1/1932_정수 삼각형/b.1932.cc | UTF-8 | 836 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <algorithm> //max함수 사용
using namespace std;
int arr[500][500];
int hab[500][500]; //동적계획법
void tri(int n)
{
hab[0][0] = arr[0][0];
for (int i = 1; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
if (j == 0) //삼각형 왼쪽 끝
{
hab[i][j] = arr[i][j] + hab[i - 1][j];
}
else if (j == i)//삼각형 오른쪽 끝
{
hab[i][j] = arr[i][j] + hab[i - 1][j - 1];
}
else
{
hab[i][j] = arr[i][j] + max(hab[i - 1][j - 1], hab[i - 1][j]);
}
}
}
int maxnum = 0;
for (int i = 0; i < n; i++)
{
maxnum =max(maxnum, hab[n - 1][i]); //가장 큰 값
}
cout << maxnum << endl; //출력
}
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
for (int j = 0; j <= i; j++)
{
cin >> arr[i][j]; //입력
}
}
tri(N);
return 0;
}
| true |
598277121fb45f029228ceb933679f0c74b4689c | C++ | KaiPeng21/ECE368 | /Project/dialog_auto.cpp | UTF-8 | 15,494 | 2.703125 | 3 | [] | no_license | #include "dialog_auto.h"
#include "ui_dialog_auto.h"
#include <iostream>
#include <QKeyEvent>
#include <QPainter>
#include <QString>
#include <QTextDocument>
#include <QDebug>
#include <QTimer>
#include <QTime>
dialog_auto::dialog_auto(QWidget *parent) :
QDialog(parent)//,
//ui(new Ui::dialog_auto)
{
//ui->setupUi(this);
// set the screen size
resize((WIDTH+1)*SIZE, (HEIGHT+1)*SIZE + SIZE*3);
setWindowTitle("Snake Game Automation");
// initialize the game conditions
//initGame();
initGame_automative();
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
QTimer * timer = new QTimer(this);
// update game data
// connect(timer,SIGNAL(timeout()),this,SLOT(gameLoop()));
connect(timer,SIGNAL(timeout()),this,SLOT(gameLoop_automative()));
// update graphical display
connect(timer,SIGNAL(timeout()),this,SLOT(update()));
timer->start(10);
}
dialog_auto::~dialog_auto()
{
//delete ui;
}
void dialog_auto::initGame()
{
direction = UP;
play_status = PLAYING;
score = 0;
// initialize snake
sque.clear();
for (int i = 0; i < STARTING_L; i++){
enqueue_snake_head(WIDTH/2, HEIGHT/2+2 - i);
}
// initialize egg
generate_egg();
}
void dialog_auto::enqueue_snake_head(int x, int y)
{
Coordinate * pos = new Coordinate();
pos->x = x;
pos->y = y;
sque.enqueue(pos);
}
void dialog_auto::dequeue_snake_tail()
{
if (!sque.isEmpty()){
Coordinate * tmp = sque.dequeue();
delete tmp;
}
}
void dialog_auto::display_snake_coordinate()
{
for (int i = 0; i < sque.size(); ++i) {
qDebug() << "(" << sque.at(i)->x << " ," << sque.at(i)->y << ")" << " <- ";
}
qDebug() << "\n";
}
bool dialog_auto::is_egg(int x, int y)
{
if (x == egg.x && y == egg.y){
return true;
}
return false;
}
bool dialog_auto::egg_eaten()
{
int shead_x = sque.back()->x;
int shead_y = sque.back()->y;
if (is_egg(shead_x, shead_y)){
return true;
}
return false;
}
// randomly set the positon of egg.x and egg.y
// re-set if the position is snake or block
void dialog_auto::generate_egg()
{
int egg_x, egg_y;
do{
egg_x = qrand() % WIDTH + 1;
egg_y = qrand() % HEIGHT + 1;
}while(is_snake(egg_x, egg_y) || is_block(egg_x, egg_y));
egg.x = egg_x;
egg.y = egg_y;
}
// return true if game over, false if game is not over
// check if the snake head position is snake body or block
bool dialog_auto::game_over_check(int x, int y)
{
if (is_snake_body(x, y) || is_block(x, y)){
return true;
}
return false;
}
// check if the coordinate is a snake (excluding snake head)
bool dialog_auto::is_snake_body(int x, int y)
{
if (sque.size() != 0){
for (int i = 0; i < sque.size()-1; ++i) {
if (x == sque.at(i)->x && y == sque.at(i)->y){
return true;
}
}
}
return false;
}
// check if the coordinate is a snake (including snake head)
bool dialog_auto::is_snake(int x, int y)
{
if (is_snake_body(x, y)){
return true;
}
if (x == sque.back()->x && y == sque.back()->y){
return true;
}
return false;
}
bool dialog_auto::is_block(int x, int y)
{
if(x == 0 || x == WIDTH || y == 0 || y == HEIGHT){
return true;
}
return false;
}
void dialog_auto::initGame_automative()
{
direction = UP;
play_status = AUTO;
score = 0;
//
pathq.clear();
// initialize snake
sque.clear();
for (int i = 0; i < STARTING_L; i++){
enqueue_snake_head(WIDTH/2, HEIGHT/2+2 - i);
}
// initialize egg
generate_egg();
AutomatedSnake();
}
void dialog_auto::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Up && direction != DOWN && play_status == PLAYING){
direction = UP;
//qDebug() << direction;
}
else if (event->key() == Qt::Key_Down && direction != UP && play_status == PLAYING){
direction = DOWN;
//qDebug() << direction;
}
else if (event->key() == Qt::Key_Left && direction != RIGHT && play_status == PLAYING){
direction = LEFT;
//qDebug() << direction;
}
else if (event->key() == Qt::Key_Right && direction != LEFT && play_status == PLAYING){
direction = RIGHT;
//qDebug() << direction;
}
// quit game
else if (event->key() == Qt::Key_Escape){
if (play_status != OVER){
play_status = OVER;
}else{
// close screen
this->close();
}
}else if (event->key() == Qt::Key_Space){
// pause and resume
if(play_status == PLAYING){play_status = PAUSE;}
else if (play_status == PAUSE){play_status = PLAYING;}
else if (play_status == OVER){
sque.clear();
//initGame();
initGame_automative();
}
}
}
void dialog_auto::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
// if (play_status == PLAYING || play_status == PAUSE){
QBrush white(Qt::white,Qt::SolidPattern);
QRect background(0,0,SIZE*WIDTH, SIZE*HEIGHT);
painter.fillRect(background, white);
// draw egg
QBrush ebrush(Qt::red, Qt::SolidPattern);
QRect erect(SIZE*egg.x, SIZE*egg.y, SIZE, SIZE);
painter.fillRect(erect, ebrush);
// draw snake
QBrush sbrush(Qt::darkGreen, Qt::SolidPattern);
for (int i = 0; i < sque.size(); ++i) {
int tmp_x = sque.at(i)->x;
int tmp_y = sque.at(i)->y;
QRect srect(SIZE*tmp_x, SIZE*tmp_y, SIZE, SIZE);
painter.fillRect(srect, sbrush);
}
// draw block
QBrush bbrush(Qt::black, Qt::SolidPattern);
QRect brect1(0,0,SIZE,SIZE*(HEIGHT+1));
QRect brect2(0,0,SIZE*(WIDTH+1),SIZE);
QRect brect3(SIZE*WIDTH,0,SIZE, SIZE*(HEIGHT+1));
QRect brect4(0,SIZE*HEIGHT, SIZE*(WIDTH+1),SIZE);
painter.fillRect(brect1, bbrush);
painter.fillRect(brect2, bbrush);
painter.fillRect(brect3, bbrush);
painter.fillRect(brect4, bbrush);
// draw score
QString score_v = QString::number(score);
QString score_text = "Score: ";
score_text.append(score_v);
painter.drawText(SIZE, SIZE*(HEIGHT+1) + 2*SIZE, score_text);
// draw instructions
QString instruct = "Aumotation Mode Esc - Quit";
painter.drawText((WIDTH/2)*SIZE, SIZE*(HEIGHT+1) + 2*SIZE, instruct);
// }else if (play_status == OVER){ // gameover
if(play_status == OVER){
QRect endrect(SIZE*WIDTH/4,SIZE, SIZE*WIDTH/2, (HEIGHT-1)*SIZE);
QBrush endbrush(Qt::green, Qt::Dense6Pattern);
painter.fillRect(endrect,endbrush);
QString score_v = QString::number(score);
QString score_text = "Game Over! Your Score: ";
score_text.append(score_v);
painter.drawText(SIZE*WIDTH/2 - 6*SIZE, SIZE*HEIGHT/2, score_text);
QString instruct = "Space - Play Again, Esc - Exit";
painter.drawText(SIZE*WIDTH/2 - 7*SIZE, SIZE*HEIGHT/2 + 3*SIZE, instruct);
}
}
void dialog_auto::enqueue_path(int direction, int nothing)
{
Coordinate * pos = new Coordinate();
pos->x = direction;
pos->y = nothing;
pathq.enqueue(pos);
}
void dialog_auto::dequeue_path()
{
if (!pathq.isEmpty()){
pathq.dequeue();
}
}
void dialog_auto::gameLoop_automative()
{
if (play_status == AUTO){
direction = UP;
if(!pathq.isEmpty()){
direction = pathq.front()->x;
dequeue_path();
}
int tmp_x = sque.back()->x;
int tmp_y = sque.back()->y;
switch(direction){
case UP: enqueue_snake_head(tmp_x, tmp_y - 1); break;
case DOWN: enqueue_snake_head(tmp_x, tmp_y + 1); break;
case LEFT: enqueue_snake_head(tmp_x - 1, tmp_y); break;
case RIGHT: enqueue_snake_head(tmp_x + 1, tmp_y); break;
}
// check egg condition
if(egg_eaten()){
score++;
generate_egg();
AutomatedSnake();
}else{
dequeue_snake_tail();
}
// check game over
if (game_over_check(sque.back()->x, sque.back()->y)){
play_status = OVER;
}
}
}
void dialog_auto::AutomatedSnake(){
int i;
int j;
int count = 0;
int flag = 0;
int wall = INT_MAX - 1;
int snakebody = INT_MAX;
int top;
int bot;
int left;
int right;
for(i = 0; i <= WIDTH; i++){
array[i][0] = wall;
}
for(i = 0; i <= WIDTH; i++){
array[i][HEIGHT] = wall;
}
for(j = 1; j < HEIGHT; j++){
array[0][j] = wall;
}
for(j = 1; j < HEIGHT; j++){
array[WIDTH][j] = wall;
}
for(i = 1; i < WIDTH; i++){
for(j = 1; j < HEIGHT; j++){
array[i][j] = 0;
}
}
for(i = 1; i < sque.length(); i++){
array[sque.at(i)->x][sque.at(i)->y] = snakebody;
}
array[sque.back()->x][sque.back()->y] = 1;
do{
top = sque.back()->y - (count + 1);
if(top < 1){
top = 1;
}
bot = sque.back()->y + (count + 1);
if(bot > HEIGHT - 1){
bot = HEIGHT - 1;
}
right = sque.back()->x + (count + 1);
if(right > WIDTH - 1){
right = WIDTH - 1;
}
left = sque.back()->x - (count + 1);
if(left < 1){
left = 1;
}
for(i = left; i <= right; i++){
for(j = top; j <= bot; j++){
if(array[i][j] > 0 && array[i][j] < wall){
array[i][j]++;
}
}
}
for(i = left; i <= right; i++){
for(j = top; j <= bot; j++){
if(array[i][j] == 0){
if(array[i+1][j] > 1 && array[i+1][j] < wall){
array[i][j]++;
}
else if(array[i-1][j] > 1 && array[i-1][j] < wall){
array[i][j]++;
}
else if(array[i][j+1] > 1 && array[i][j+1] < wall){
array[i][j]++;
}
else if(array[i][j-1] > 1 && array[i][j-1] < wall){
array[i][j]++;
}
}
}
}
if(flag != 1 && sque.at(count) != sque.back()){
array[sque.at(count)->x][sque.at(count)->y] = 0;
}
else{
flag = 1;
}
count++;
}while(array[egg.x][egg.y] == 0);
/* for(j = 0; j <= HEIGHT; j++){
for(i = 0; i <= WIDTH; i++){
if(array[i][j] >= wall){
printf(" X ");
}
else if(i == egg.x && j == egg.y){
printf(" E ");
}
else{
printf( "%2d ", array[i][j]);
}
}
printf("\n");
}
*/
for(i = 0; i < pathq.length();i++){
dequeue_path();
}
CreatePath(egg.x, egg.y, count, 0);
return;
}
void dialog_auto::CreatePath(int i, int j, int count, int delay){
int temp = array[i][j];
int left;
int right;
int up;
int down;
int upleft;
int upright;
int downleft;
int downright;
int wall = INT_MAX - 1;
int snakebody = INT_MAX;
int flag;
// printf("%d ", array[i][j]);
if(count > 0 || count > delay){//(i != sque.back()->x) || (j != sque.back()->y)){
left = array[i-1][j];
right = array[i+1][j];
up = array[i][j-1];
down = array[i][j+1];
upleft = array[i-1][j-1];
upright = array[i+1][j-1];
downleft = array[i-1][j+1];
downright = array[i+1][j+1];
flag = 0;
if(delay > 0 || (left == array[sque.back()->x][sque.back()->y] && left != temp + 1) || (up == array[sque.back()->x][sque.back()->y] && up != temp + 1) || (down == array[sque.back()->x][sque.back()->y] && down != temp + 1) || (right == array[sque.back()->x][sque.back()->y] && right != temp + 1)){
if((left == array[i][j] - 1) && ((up < wall) && (upleft < wall) && (upright < wall) || (down < wall) && (downleft < wall) && (downright < wall))){
flag = 1;
array[i][j] = snakebody;
CreatePath(i-1, j, count - 1, delay - 2);
enqueue_path(RIGHT,0);
// printf("LEFT ");
return;
}
else if((right == array[i][j] - 1) && ((up < wall) && (upleft < wall) && (upright < wall) || (down < wall) && (downleft < wall) && (downright < wall))){
flag = 1;
array[i][j] = snakebody;
CreatePath(i+1, j, count - 1, delay - 2);
enqueue_path(LEFT,0);
// printf("RIGHT ");
return;
}
else if((up == array[i][j] - 1) && ((downright < wall) && (upright < wall) && (right < wall) || (left < wall) && (downleft < wall) && (upleft < wall))){
flag = 1;
array[i][j] = snakebody;
CreatePath(i, j-1, count - 1, delay - 2);
enqueue_path(DOWN,0);
// printf("UP ");
return;
}
else if((down == array[i][j] - 1) && ((downright < wall) && (upright < wall) && (right < wall) || (left < wall) && (downleft < wall) && (upleft < wall))){
flag = 1;
array[i][j] = snakebody;
CreatePath(i, j+1, count - 1, delay - 2);
enqueue_path(UP,0);
// printf("DOWN ");
return;
}
}
if(flag == 0){
if((((left > right) || (right >= wall)) && ((left > up) || (up >= wall)) && ((left > down) || (down >= wall))) && (left < wall)){
array[i][j] = snakebody;
CreatePath(i-1, j, count - 1, delay + left - temp - 1);
enqueue_path(RIGHT,0);
// printf("left ");
return;
}
else if((((right > up) || (up >= wall)) && ((right > down) || (down >= wall))) && (right < wall)){
array[i][j] = snakebody;
CreatePath(i+1, j, count - 1, delay + right - temp - 1);
enqueue_path(LEFT,0);
// printf("right ");
return;
}
else if(((up > down) || (down >= wall)) && (up < wall)){
array[i][j] = snakebody;
CreatePath(i, j-1, count - 1, delay + up - temp - 1);
enqueue_path(DOWN,0);
// printf("up ");
return;
}
else{
array[i][j] = snakebody;
CreatePath(i, j+1, count - 1, delay + down - temp - 1);
enqueue_path(UP,0);
// printf("down ");
return;
}
}
}
else{
return;
}
}
| true |
4656391b3c75cafd4dd683838890decb4cb9e904 | C++ | jason950374/VLSI-testing-hw2 | /Project1/GaloisField.cpp | UTF-8 | 294 | 2.578125 | 3 | [] | no_license | #include "GaloisField.h"
GaloisField::GaloisField(bool value){
this->value = value;
}
GaloisField GaloisField::operator*(const GaloisField & m2){
return GaloisField(value && m2.value);
}
GaloisField GaloisField::operator+(const GaloisField & m2){
return GaloisField(value != m2.value);
}
| true |
40ac36cdd01dc99be056b7e7310cf1b9bbc24af2 | C++ | WayfireWM/wf-utils | /wayfire/lexer/literal.hpp | UTF-8 | 406 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef LITERAL_HPP
#define LITERAL_HPP
#include "wayfire/variant.hpp"
#include <string>
namespace wf
{
/**
* @brief parse_literal Static helper method to parse a literal from a text fragment.
*
* @param[in] s The text fragment to convert to a literal value.
*
* @return The converted literal value.
*/
variant_t parse_literal(const std::string &s);
} // End namespace wf.
#endif // LITERAL_HPP
| true |
153615d91d70349e7901cd7d5e62d0e97adb85ab | C++ | TheUnicum/CTN_05_Hardware_3D_DirectX | /CTN_05_Hardware_3D_DirectX/src/ChiliMath.h | UTF-8 | 836 | 3.4375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <math.h>
constexpr float PI = 3.14159265f;
constexpr double PI_D = 3.1415926535897932;
template <typename T>
constexpr auto sq(const T& x) noexcept
{
return x * x;
}
template<typename T>
T wrap_angle(T theta) noexcept
{
constexpr T twoPi = (T)2 * (T)PI_D;
const T mod = (T)fmod(theta, twoPi);
if (mod > (T)PI_D)
{
return mod - twoPi;
}
else if (mod < -(T)PI_D)
{
return mod + twoPi;
}
return mod;
}
template<typename T>
constexpr T interpolate(const T& src, const T& dst, float alpha) noexcept
{
return src + (dst - src) * alpha;
}
template<typename T>
constexpr T to_rad(T deg) noexcept
{
return deg * PI / (T)180.0;
}
template<typename T>
constexpr T gauss(T x, T sigma) noexcept
{
const auto ss = sq(sigma);
return ((T)1.0 / sqrt((T)2.0 * (T)PI_D * ss)) * exp(-sq(x) / ((T)2.0 * ss));
}
| true |
ec3cf673e2643b3e6f8c364aff863685b5878f6d | C++ | ponasenko-rs/metaprogramming-seminars | /functor.h | UTF-8 | 2,066 | 2.921875 | 3 | [] | no_license | #pragma once
#include <memory>
#include "typelist.h"
#include "tuple.h"
namespace functor {
template <int args_left, typename Result, typename Tuple, typename Invoker,
typename... CollectedArgs>
traits::EnableIfT<args_left != 0, Result> InvokeTupleArgs(Invoker invoker, Tuple tuple,
CollectedArgs... args) {
return InvokeTupleArgs<args_left - 1, Result>(invoker, tuple,
tuple::TupleGet<args_left - 1>(tuple), args...);
}
template <int args_left, typename Result, typename Tuple, typename Invoker,
typename... CollectedArgs>
traits::EnableIfT<args_left == 0, Result> InvokeTupleArgs(Invoker invoker, Tuple tuple,
CollectedArgs... args) {
return invoker->invoke(args...);
}
template <typename Result, typename FunctionType>
struct FreeFunctionHolder {
template <typename... CallArgs>
Result operator()(CallArgs... args) {
return function(args...);
}
FreeFunctionHolder(FunctionType function) : function(function) {
}
template <typename... CallArgs>
Result invoke(CallArgs... args) {
return operator()(args...);
}
FunctionType function;
};
template <typename FunctionType, typename... Args>
class Functor {
using Tuple = tuple::Tuple<Args...>;
using Result = traits::GetFunctionResultTypeT<FunctionType>;
using Invoker = std::shared_ptr<FreeFunctionHolder<Result, FunctionType>>;
public:
Functor(FunctionType func, Args... args)
: invoker(new FreeFunctionHolder<Result, FunctionType>(func)) {
tuple::TupleAssign<0>(tuple, args...);
}
template <typename... CallArgs>
Result operator()(CallArgs... args) {
return InvokeTupleArgs<accepted_args_length, Result>(invoker, tuple, args...);
}
private:
Tuple tuple;
static constexpr int accepted_args_length = typelist::LengthV<typelist::TypeList<Args...>>;
Invoker invoker;
};
} // namespace functor | true |
1a0fa279b05b9fff9b18b5ea828a3b463c537dcf | C++ | mingdaz/leetcode | /_includes/leet040/leet040.cpp | UTF-8 | 967 | 2.984375 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& a, int target) {
sort(a.begin(),a.end());
vector<vector<int>> res;
vector<int> path;
helper(res,path,a,0,target);
return res;
}
void helper(vector<vector<int>>& res, vector<int>& path, vector<int>& a, int idx, int target){
if(target==0){
res.push_back(path);
return;
}
if(idx>=a.size()) return;
for(int i=idx;i<a.size();i++){
if(a[i]>target) break;
int j = i;
for(;i+1<a.size()&&a[i]==a[i+1];i++);
int k;
for(k=j;k<=i&&a[k]<=target;k++){
path.push_back(a[k]);
target -= a[k];
helper(res,path,a,i+1,target);
}
for(;k>j;k--){
path.pop_back();
target += a[j];
}
}
}
}; | true |
ab73a40d084cc0096aa5e8046ff5f288a5da3d13 | C++ | Thomas2511/Rush00 | /Game.hpp | UTF-8 | 650 | 2.6875 | 3 | [] | no_license | #ifndef GAME_HPP
# define GAME_HPP
# include "Player.hpp"
# include "CollisionChecker.hpp"
# include "EnemySpawner.hpp"
class Game
{
public:
Game( void );
Game( Window const & win );
Game(Game const & src);
~Game( void );
Game & operator=(Game const & rhs);
char getStatus() const;
void refresh();
static void addScore(int i);
static std::string getScore(void);
std::string getLife() const;
private:
char _status;
void _refreshGameEntity();
void _deathCheck();
void _isQuit();
void _isOver();
static int _score;
Player _player;
EnemySpawner _spawner;
};
#endif /* GAME_HPP */
| true |
3e7b0271710dd91239abd75c1736d690a5660821 | C++ | emil-e/rapidcheck | /include/rapidcheck/shrink/Shrink.h | UTF-8 | 1,622 | 3.0625 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include "rapidcheck/Seq.h"
namespace rc {
namespace shrink {
/// Tries to shrink the given container by removing successively smaller
/// consecutive chunks of it.
///
/// `Container` must support the following:
/// - `RandomAccessIterator begin(Container)`
/// - `RandomAccessIterator end(Container)`
/// - `Container::insert(It, It, It)`
/// - `Container::reserve(std::size_t)`
template <typename Container>
Seq<Container> removeChunks(Container elements);
/// Tries to shrink each element of the given container using the given
/// callable to create sequences of shrinks for that element.
///
/// `Container` must support `begin(Container)` and `end(Container)` which must
/// return random access iterators.
///
/// @param elements The collection whose elements to shrink.
/// @param shrink A callable which returns a `Seq<T>` given an element
/// to shrink.
template <typename Container, typename Shrink>
Seq<Container> eachElement(Container elements, Shrink shrink);
/// Shrinks an integral value towards another integral value.
///
/// @param value The value to shrink.
/// @param target The integer to shrink towards.
template <typename T>
Seq<T> towards(T value, T target);
/// Shrinks an arbitrary integral value.
template <typename T>
Seq<T> integral(T value);
/// Shrinks an arbitrary real value.
template <typename T>
Seq<T> real(T value);
/// Shrinks an arbitrary boolean value.
inline Seq<bool> boolean(bool value);
/// Shrinks a text character.
template <typename T>
Seq<T> character(T value);
} // namespace shrink
} // namespace rc
#include "Shrink.hpp"
| true |
6fc5461281a49bacd7b7eaee4a45b883903b5193 | C++ | DakkyDaWolf/OpenGL | /source/Library.Shared/ServiceContainer.cpp | UTF-8 | 560 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "pch.h"
#include "ServiceContainer.h"
using namespace std;
namespace Library
{
ServiceContainer GlobalServices;
void ServiceContainer::AddService(RTTI::IdType typeID, void* service)
{
mServices.insert(pair<RTTI::IdType, void*>(typeID, service));
}
void ServiceContainer::RemoveService(RTTI::IdType typeID)
{
mServices.erase(typeID);
}
void* ServiceContainer::GetService(RTTI::IdType typeID) const
{
map<RTTI::IdType, void*>::const_iterator it = mServices.find(typeID);
return (it != mServices.end() ? it->second : nullptr);
}
} | true |
fc38137acc4ecb37b42c801d492afd500ef91765 | C++ | goyeer/complete-cpp-developer-course | /course-source-files/section 4/VectorPractice/main.cpp | UTF-8 | 412 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> names;
names.push_back("Jackson");
names.push_back("Hoppy");
names.push_back("Orange");
names.push_back("Rozie");
names.push_back("Phillip");
names.insert(names.begin() + 2, "John Baugh");
names.pop_back();
for (string name : names)
{
cout << name << endl;
}
return 0;
} | true |
c155a03e6863ec8054271b691f5bddb321d8c561 | C++ | fafaovo/Binarytree | /二叉树非递归前序遍历.cpp | UTF-8 | 760 | 3.46875 | 3 | [] | no_license | class Solution {
public:
void pre(TreeNode* root,vector<int> &arr_int)
{
stack<TreeNode*> Treestack; //用栈容器来遍历
if(root == nullptr)
return;
Treestack.push(root);
while(!Treestack.empty())
{
TreeNode* node = Treestack.top();
Treestack.pop();
arr_int.push_back(node->val); //出栈并且把元素丢到数组中
if(node->right)Treestack.push(node->right); //想象一下栈,所以得右边先入栈
if(node->left)Treestack.push(node->left); //然后才是左边入栈
}
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> arr_int;
pre(root,arr_int);
return arr_int;
}
};
| true |
40674e6bf879f5fc3bdcc7422da1ea4f27c6df08 | C++ | vector8/2D-Animation-TIME | /SproutPlugin/include/PcPhysicalPoint3D.hpp | UTF-8 | 2,401 | 3.140625 | 3 | [] | no_license | #ifndef PC_PHYSICAL_POINT_3D_H
#define PC_PHYSICAL_POINT_3D_H
#include "HpPcApi.hpp"
#include "PcString.hpp"
#include "PcException.hpp"
namespace hp { namespace pc {
/// <summary>
/// The class PcPhysicalPoint3D represents a 3D physical point, that is, a 3D representation
/// of a physical point in the real world.
/// </summary>
/// <remarks>
/// A physical point in the real world has four coordinates, three for space and one
/// for time. Here, we are interested only in three coordinates, ignoring time and considering
/// the location of the point in the volume of space above the mat. The unit of
/// measurement for the coordinate system is millimeters.
/// </remarks>
class HPPC_API PcPhysicalPoint3D
{
public:
/// <summary>
/// Creates a 3D physical point at the location (0, 0, 0).
/// </summary>
PcPhysicalPoint3D();
/// <summary>
/// Destroys the instance of PcPhysicalPoint3D.
/// </summary>
virtual ~PcPhysicalPoint3D() {}
/// <summary>
/// Creates a 3D physical point using the provided physical coordinates along the X, Y, and Z axes.
/// </summary>
/// <param name="x">X coordinate in millimeters</param>
/// <param name="y">Y coordinate in millimeters</param>
/// <param name="z">Z coordinate in millimeters</param>
PcPhysicalPoint3D(double x, double y, double z);
/// <summary>
/// Gets the X coordinate of this 3D physical point in millimeters.
/// </summary>
/// <returns>The X coordinate of this 3D physical point.</returns>
double X() const throw ();
/// <summary>
/// Gets the Y coordinate of this 3D physical point in millimeters.
/// </summary>
/// <returns>The Y coordinate of this 3D physical point.</returns>
double Y() const throw ();
/// <summary>
/// Gets the Z coordinate of this 3D physical point in millimeters.
/// </summary>
/// <returns>The Z coordinate of this 3D physical point.</returns>
double Z() const throw ();
/// <summary>
/// Gets a string that represents the 3D physical point.
/// </summary>
/// <returns>
/// A string that represents the 3D physical point
/// </returns>
PcString ToString() const throw (PcException);
private:
double mX;
double mY;
double mZ;
};
} }
#endif // PC_PHYSICAL_POINT_3D_H
| true |
1b2badd5f12583464c26aa605b5448f82f25cf8b | C++ | victorcolombo/caderno | /code/hld.cpp | UTF-8 | 1,166 | 2.890625 | 3 | [] | no_license | /*
* nxt[i] = vértice mais alto da chain de i
* p[i] = parente de i
* query(in[a], in[b]) é a query entre os nós a e b na mesma chain (a mais alto que b)
* Cuidado entre queries em vértices vs arestas! (limites inclusivos e exclusivos)
*/
int sz[MAXV];
vector<int> g[MAXV];
void dfs_sz(int v = 0) {
sz[v] = 1;
for(auto &u: g[v])
{
dfs_sz(u);
sz[v] += sz[u];
if(sz[u] > sz[g[v][0]])
swap(u, g[v][0]);
}
}
int in[MAXV], rin[MAXV], nxt[MAXV], out[MAXV], lvl[MAXV], t;
void dfs_hld(int v = 0, int h = 0) {
lvl[v] = h;
in[v] = t++;
rin[in[v]] = v;
for(auto u: g[v])
{
nxt[u] = (u == g[v][0] ? nxt[v] : u);
dfs_hld(u, h + 1);
}
out[v] = t;
}
int p[MAXV];
int query_path(int a, int b) {
int ans = INT_MIN;
while (nxt[a] != nxt[b]) {
if (lvl[nxt[a]] > lvl[nxt[b]]) {
ans = max(ans, query(in[nxt[a]], in[a]));
a = p[nxt[a]];
} else {
ans = max(ans, query(in[nxt[b]], in[b]));
b = p[nxt[b]];
}
}
if (lvl[a] > lvl[b]) swap(a, b);
return max(ans, query(in[a] + 1, in[b]));
}
| true |
09a2cfa4e0d182d3339348dfd592507de46dd694 | C++ | nonanona/garbage_storage | /fonttest/src/gui.h | UTF-8 | 1,088 | 2.75 | 3 | [] | no_license | #pragma once
#include <goocanvas.h>
#include <string>
#include "glyf.h"
class Gui {
public:
Gui(int w, int h) : Gui(w, h, 0, 0) {}
Gui(int w, int h, int cx, int cy) : Gui(w, h, cx, cy, 1.0, 0) {}
Gui(int w, int h, int cx, int cy, float scale, int margin);
void drawPath(const std::string& command, const std::string& color, float width);
void drawPath(const std::vector<Contour>& contours, bool with_contours,
const std::string& color, bool close_path, float width);
void drawPath(const std::vector<GlyphPoint>& contours, bool with_contours,
const std::string& color, bool close_path, float width);
void drawPoint(int x, int y, float width, const std::string& color);
void drawLine(int from_x, int from_y, int to_x, int to_y, const std::string& color);
void fillRect(int x, int y, int w, int h, const std::string& color);
private:
int w_;
int h_;
int cx_;
int cy_;
int margin_;
float scale_;
int toX(int x) { return scale_ * x + cx_ + margin_; }
int toY(int y) { return h_ - scale_ * y - cy_ - margin_; }
GooCanvasItem* root_;
};
| true |
e853957cb42874cc7998c4e9fbce64166d5e040a | C++ | wenqf11/LeetCode | /C++/40. Combination Sum II/solution.h | UTF-8 | 891 | 3.046875 | 3 | [
"MIT"
] | permissive | #pragma once
#include<vector>
#include<string>
#include<climits>
#include<algorithm>
#include<stack>
#include<unordered_map>
#include<sstream>
using namespace std;
class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> nums;
solve(candidates, nums, target, 0);
return ans;
}
void solve(vector<int>& candidates, vector<int>& nums, int target, int start) {
if (target == 0) {
ans.push_back(nums);
}
for (int i = start; i < candidates.size(); i++) {
if (target - candidates[i] >= 0) {
if (i == start || (i > start && candidates[i - 1] != candidates[i])) {
nums.push_back(candidates[i]);
solve(candidates, nums, target - candidates[i], i + 1);
nums.erase(nums.end() - 1);
}
}
else {
break;
}
}
}
}; | true |
378bc97b60a85a2fc4ab4b5c09344de6ad19cf8c | C++ | Zeyu-Wang-MP/Kernel-course-project | /virtual memory management/vm_OS.h | UTF-8 | 6,845 | 2.921875 | 3 | [] | no_license | /*
* vm_OS.h
*
* Helper functions and variables
*/
#ifndef _VM_HELPER_H_
#define _VM_HELPER_H_
#include "vm_arena.h"
#include "vm_pager.h"
#include <vector>
#include <unordered_map>
#include <list>
#include <unordered_set>
#include <string>
struct OS_page_entry
{
OS_page_entry(page_table_entry_t* const entry_ptr, bool _isSwapBack,
int block_index, std::string _file_name):
isDirty(true), isReferenced(true), isResident(true), isSwapBack(_isSwapBack),
swap_or_file_block_index(block_index), file_name(_file_name), original_entry_ptr(entry_ptr){}
// don't need dtor
bool isDirty, isReferenced, isResident, isSwapBack;
// for swap-backed page, if this page is not in swap space, make it -1
// for file-backed page, make it file block index
int swap_or_file_block_index;
// for swap-backed page, make it empty
// for file-backed page, make it the file name
const std::string file_name;
// Infrastructure page table entry
page_table_entry_t* original_entry_ptr;
// just use the default copy/move ctor/assignment operator
};
struct Process
{
Process():invalid_arena_start(VM_ARENA_BASEADDR){
for(unsigned i = 0; i < VM_ARENA_SIZE/VM_PAGESIZE; ++i){
original_pagetable.ptes[i].ppage = 0;
original_pagetable.ptes[i].read_enable = 0;
original_pagetable.ptes[i].write_enable = 0;
}
// avoid the vector reallocate and make the owners pointer invalid
OS_process_pagetable.reserve(VM_ARENA_SIZE/VM_PAGESIZE);
}
~Process();
// OS page table with extra bits.
// only push_back when we make new page valid, so we don't need isValid bit
std::vector<OS_page_entry> OS_process_pagetable;
// real page table. Use for PTBR
page_table_t original_pagetable;
// Keep track of valid arena space (note: always increases)
void* invalid_arena_start;
Process(const Process&) = delete;
Process(Process&&) = delete;
Process& operator=(const Process&) = delete;
Process& operator=(Process&&) = delete;
};
// indicate the status of each page in physical memory/swap space
struct physical_page_t{
std::unordered_set<OS_page_entry*> owners;
physical_page_t(){}
// don't need to write dtor
// only allow move assignment
physical_page_t(const physical_page_t&) = delete;
physical_page_t& operator=(const physical_page_t&) = delete;
physical_page_t(physical_page_t&& rhs) noexcept:owners(std::move(rhs.owners)){}
physical_page_t& operator=(physical_page_t&& rhs) noexcept{
owners = std::move(rhs.owners);
return *this;
}
};
struct File_block_info{
std::string filename;
unsigned block_index;
struct Hasher{
size_t operator()(const File_block_info& block) const{
std::hash<std::string> str_hasher;
std::hash<unsigned> int_hasher;
std::hash<size_t> size_hasher;
return size_hasher(str_hasher(block.filename) + int_hasher(block.block_index));
}
};
struct Equal{
bool operator()(const File_block_info& lhs, const File_block_info& rhs)const{
return (lhs.filename == rhs.filename) && (lhs.block_index == rhs.block_index);
}
};
};
// Container for variables and functions for pager
class OS_Pager
{
public:
// clock queue - integer represents the pages index in physical memory
static std::list<unsigned int> clock;
// OS data structure of physical memory, use physical_page_t to indicate the use of each
// page in physical memory
// the size of it should be physical page number
static std::vector<physical_page_t> physical_memory;
// OS data structure indicating the use of all swap blocks
static std::vector<physical_page_t> swap_blocks;
// OS data structure indicating the use of each file opened
static std::unordered_map<std::string, std::vector<physical_page_t> > file_blocks;
// all current live processes
static std::unordered_map<pid_t, Process*> processes;
// use this set to manage free pages in physical memory and swap space
static std::unordered_set<unsigned> free_physmem_pages, free_swap_blocks;
// use this set to track if a file block is in the physical memory
static std::unordered_map<File_block_info, unsigned, \
File_block_info::Hasher, File_block_info::Equal> file_blocks_in_physmem;
static std::unordered_set<File_block_info, File_block_info::Hasher, File_block_info::Equal> file_blocks_seen;
static unsigned pinning_page_number;
static pid_t curr_process;
// for eager swap reservation, track how much pages in phsical memory,
// update when we create new swap-backed pages and kill a process
static unsigned total_swapbacked_pages;
// --------------- Helper functions --------------- //
// Given a page number, convert to physical address in vm_physmem
static char* physmem_page_to_address(unsigned int);
// Given *filename that resides in application virtual space, form a string version
static std::string read_c_string(const char *filename);
// Given ptr to virtual address, return virtual page number.
static unsigned virtual_address_to_page(const void*);
// Returns corrsponding virtual page AND offset as <page num, offset>
static std::pair<unsigned, unsigned> vAddress_to_page_offset(const void*);
// Given index into OS_Pager::physical_memory, return pointer to
// a OS virtual page owner of that physical page.
static OS_page_entry* get_virtual_owner(unsigned int phys_mem_index);
// run clock algorithm and evict one page
static void evict_pages();
// Checks physical_memory, swap_blocks, file_blocks
// returns true if owners have identical bits.
static void check_consistent();
};
#endif /* _VM_HELPER_H_ */
/*
482 P3 Notes
Good piazza posts
vm_destroy(): @1513
- should do liveness of physical page analysis (i.e. how many references it)
State Diagram/Thoughts
if reference == 0 || valid == 0 || resident 0
then BOTH r and w == 0
- must trap if not referenced to make referenced 1
- must trap if not valid to return error
- must trap if not resident to make resident (i.e. read from disk)
if ALL reference, valid, resident == 1
then we have to look at dirty bit.
if dirty bit == 0, then r: 1, w: 0
- if not modified, we allow app to read. If app writes, we must trap to make dirty bit: 1
if dirty bit == 1, then r: 1, w: 1
- if modified, then we can read or write to it without problems
Pinned pages
notes:
- page can only be evicted if resident: 1 (then turn into resident: 0)
-
Questions
- is there a way for virtual pages to be made invalid (i.e. arena always fills bottom to up)
*/ | true |
bbcef78fd8e853d0f70c1b3d99930138a64d400d | C++ | 1A-OneAngstrom/SAMSON-Developer-Tutorials | /PyBindTutorial/external/SAMSON-SDK-wrappers/include/SBDTypePhysicalMatrix66Wrapper.hpp | UTF-8 | 20,246 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include "SBDQuantityWrapper.hpp"
#include "SBDTypePhysicalVector3Wrapper.hpp"
#include "SBDTypePhysicalVector6Wrapper.hpp"
#include "SBDTypePhysicalMatrix33Wrapper.hpp"
#ifdef UNITSFORPYTHON
#include <string>
#include <iostream>
#include <vector>
#include "SBDTypePhysicalMatrix66.hpp"
#include "SBDQuantityType.hpp"
#include "SBDQuantityUnitType.hpp"
#include "SBDQuantityUnitSystem.hpp"
/*! \file SBDTypePhysicalMatrix66Wrapper.hpp */
/// \brief This class is used as a wrapper between SAMSON SDK SBDTypePhysicalMatrix66 and Python.
///
/// \tparam Units - SBDQuantityWrapper<SBUnitSystem>
template <typename Units = SBDQuantityWrapperSI>
class SBDTypePhysicalMatrix66Wrapper {
public:
/// \name Constructors
//@{
/// \brief The default constructor initializes all components to zero
SBDTypePhysicalMatrix66Wrapper() :
m00(SBDTypePhysicalMatrix33Wrapper<Units>()),
m01(SBDTypePhysicalMatrix33Wrapper<Units>()),
m10(SBDTypePhysicalMatrix33Wrapper<Units>()),
m11(SBDTypePhysicalMatrix33Wrapper<Units>())
{}
/// \brief Constructs a spatial matrix from four 3x3 matrices
///
/// \param mat00 The top left 3x3 block
/// \param mat01 The top right 3x3 block
/// \param mat10 The bottom left 3x3 block
/// \param mat11 The bottom right 3x3 block
///
/// This constructor initializes a spatial matrix from four 3x3 matrices
SBDTypePhysicalMatrix66Wrapper(const SBDTypePhysicalMatrix33Wrapper<Units>& mat00, const SBDTypePhysicalMatrix33Wrapper<Units>& mat01,
const SBDTypePhysicalMatrix33Wrapper<Units>& mat10, const SBDTypePhysicalMatrix33Wrapper<Units>& mat11) :
m00(mat00),
m01(mat01),
m10(mat10),
m11(mat11)
{}
/// \brief Constructs a spatial matrix from SBDTypePhysicalMatrix66 \p q
template<typename Quantity00, typename Quantity01,
typename Quantity10, typename Quantity11,
typename System = SBUnitSystemSI>
SBDTypePhysicalMatrix66Wrapper(const SBDTypePhysicalMatrix66<Quantity00, Quantity01, Quantity10, Quantity11>& u) {
m00 = SBDTypePhysicalMatrix33Wrapper<SBDQuantityWrapper<System>>(u.m00);
m01 = SBDTypePhysicalMatrix33Wrapper<SBDQuantityWrapper<System>>(u.m01);
m10 = SBDTypePhysicalMatrix33Wrapper<SBDQuantityWrapper<System>>(u.m10);
m11 = SBDTypePhysicalMatrix33Wrapper<SBDQuantityWrapper<System>>(u.m11);
}
//@}
/// \name Accessors
//@{
/// \brief Returns the first column of the spatial matrix
SBDTypePhysicalVector6Wrapper<Units> getE1() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00.m[0][0],
m00.m[1][0],
m00.m[2][0],
m10.m[0][0],
m10.m[1][0],
m10.m[2][0]
);
}
/// \brief Returns the second column of the spatial matrix
SBDTypePhysicalVector6Wrapper<Units> getE2() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00.m[0][1],
m00.m[1][1],
m00.m[2][1],
m10.m[0][1],
m10.m[1][1],
m10.m[2][1]
);
}
/// \brief Returns the third column of the spatial matrix
SBDTypePhysicalVector6Wrapper<Units> getE3() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00.m[0][2],
m00.m[1][2],
m00.m[2][2],
m10.m[0][2],
m10.m[1][2],
m10.m[2][2]
);
}
/// \brief Returns the fourth column of the spatial matrix
SBDTypePhysicalVector6Wrapper<Units> getE4() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m01.m[0][0],
m01.m[1][0],
m01.m[2][0],
m11.m[0][0],
m11.m[1][0],
m11.m[2][0]
);
}
/// \brief Returns the fifth column of the spatial matrix
SBDTypePhysicalVector6Wrapper<Units> getE5() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m01.m[0][1],
m01.m[1][1],
m01.m[2][1],
m11.m[0][1],
m11.m[1][1],
m11.m[2][1]
);
}
/// \brief Returns the sixth column of the spatial matrix
SBDTypePhysicalVector6Wrapper<Units> getE6() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m01.m[0][2],
m01.m[1][2],
m01.m[2][2],
m11.m[0][2],
m11.m[1][2],
m11.m[2][2]
);
}
/// \brief Returns the first row of this spatial physical matrix
SBDTypePhysicalVector6Wrapper<Units> getRow1() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00.m[0][0],
m00.m[0][1],
m00.m[0][2],
m01.m[0][0],
m01.m[0][1],
m01.m[0][2]
);
}
/// \brief Returns the second row of this spatial physical matrix
SBDTypePhysicalVector6Wrapper<Units> getRow2() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00.m[1][0],
m00.m[1][1],
m00.m[1][2],
m01.m[1][0],
m01.m[1][1],
m01.m[1][2]
);
}
/// \brief Returns the third row of this spatial physical matrix
SBDTypePhysicalVector6Wrapper<Units> getRow3() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00.m[2][0],
m00.m[2][1],
m00.m[2][2],
m01.m[2][0],
m01.m[2][1],
m01.m[2][2]
);
}
/// \brief Returns the fourth row of this spatial physical matrix
SBDTypePhysicalVector6Wrapper<Units> getRow4() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m10.m[0][0],
m10.m[0][1],
m10.m[0][2],
m11.m[0][0],
m11.m[0][1],
m11.m[0][2]
);
}
/// \brief Returns the fifth row of this spatial physical matrix
SBDTypePhysicalVector6Wrapper<Units> getRow5() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m10.m[1][0],
m10.m[1][1],
m10.m[1][2],
m11.m[1][0],
m11.m[1][1],
m11.m[1][2]
);
}
/// \brief Returns the sixth row of this spatial physical matrix
SBDTypePhysicalVector6Wrapper<Units> getRow6() const {
return SBDTypePhysicalVector6Wrapper<Units>(
m10.m[2][0],
m10.m[2][1],
m10.m[2][2],
m11.m[2][0],
m11.m[2][1],
m11.m[2][2]
);
}
/// \brief Returns the row \p r of this spatial physical matrix
SBPhysicalVector6Wrapper<Units> getRow(const unsigned int r) const {
if (r >= 6) throw std::runtime_error("Index out of range");
if (r == 0) return getRow1();
if (r == 1) return getRow2();
if (r == 2) return getRow3();
if (r == 3) return getRow4();
if (r == 4) return getRow5();
return getRow6();
}
/// \brief Returns the column \p c of this spatial physical matrix
SBPhysicalVector6Wrapper<Units> getColumn(const unsigned int c) const {
if (c >= 6) throw std::runtime_error("Index out of range");
if (c == 0) return getE1();
if (c == 1) return getE2();
if (c == 2) return getE3();
if (c == 3) return getE4();
if (c == 4) return getE5();
return getE6();
}
/// \brief Returns a dimensionless physical matrix whose components are equal to those of this physical matrix
std::vector<std::vector<double>> getValue() const {
std::vector<std::vector<double>> ret = {{m00.m[0][0].getValue(), m00.m[0][1].getValue(), m00.m[0][2].getValue(), m01.m[0][0].getValue(), m01.m[0][1].getValue(), m01.m[0][2].getValue()},
{m00.m[1][0].getValue(), m00.m[1][1].getValue(), m00.m[1][2].getValue(), m01.m[1][0].getValue(), m01.m[1][1].getValue(), m01.m[1][2].getValue()},
{m00.m[2][0].getValue(), m00.m[2][1].getValue(), m00.m[2][2].getValue(), m01.m[2][0].getValue(), m01.m[2][1].getValue(), m01.m[2][2].getValue()},
{m10.m[0][0].getValue(), m10.m[0][1].getValue(), m10.m[0][2].getValue(), m11.m[0][0].getValue(), m11.m[0][1].getValue(), m11.m[0][2].getValue()},
{m10.m[1][0].getValue(), m10.m[1][1].getValue(), m10.m[1][2].getValue(), m11.m[1][0].getValue(), m11.m[1][1].getValue(), m11.m[1][2].getValue()},
{m10.m[2][0].getValue(), m10.m[2][1].getValue(), m10.m[2][2].getValue(), m11.m[2][0].getValue(), m11.m[2][1].getValue(), m11.m[2][2].getValue()}};
return ret;
}
/// \brief Sets the components of this physical matrix equal to those of the dimensionless physical matrix \p u
void setValue(const std::vector<std::vector<double>>& u) {
if (u.size() != 6) throw std::runtime_error("The size of the input matrix should be 6x6");
for (auto v: u)
if (v.size() != 6) throw std::runtime_error("The size of the input matrix should be 6x6");
m00.m[0][0].setValue(u[0][0]); m00.m[0][1].setValue(u[0][1]); m00.m[0][2].setValue(u[0][2]); m01.m[0][0].setValue(u[0][3]); m01.m[0][1].setValue(u[0][4]); m01.m[0][2].setValue(u[0][5]);
m00.m[1][0].setValue(u[1][0]); m00.m[1][1].setValue(u[1][1]); m00.m[1][2].setValue(u[1][2]); m01.m[1][0].setValue(u[1][3]); m01.m[1][1].setValue(u[1][4]); m01.m[1][2].setValue(u[1][5]);
m00.m[2][0].setValue(u[2][0]); m00.m[2][1].setValue(u[2][1]); m00.m[2][2].setValue(u[2][2]); m01.m[2][0].setValue(u[2][3]); m01.m[2][1].setValue(u[2][4]); m01.m[2][2].setValue(u[2][5]);
m10.m[0][0].setValue(u[3][0]); m10.m[0][1].setValue(u[3][1]); m10.m[0][2].setValue(u[3][2]); m11.m[0][0].setValue(u[3][3]); m11.m[0][1].setValue(u[3][4]); m11.m[0][2].setValue(u[3][5]);
m10.m[1][0].setValue(u[4][0]); m10.m[1][1].setValue(u[4][1]); m10.m[1][2].setValue(u[4][2]); m11.m[1][0].setValue(u[4][3]); m11.m[1][1].setValue(u[4][4]); m11.m[1][2].setValue(u[4][5]);
m10.m[2][0].setValue(u[5][0]); m10.m[2][1].setValue(u[5][1]); m10.m[2][2].setValue(u[5][2]); m11.m[2][0].setValue(u[5][3]); m11.m[2][1].setValue(u[5][4]); m11.m[2][2].setValue(u[5][5]);
}
/// \brief Returns the arbitraty SBPhysicalMatrix66
template<typename Quantity00, typename Quantity01,
typename Quantity10, typename Quantity11,
typename System = SBUnitSystemSI>
SBPhysicalMatrix66<Quantity00, Quantity01, Quantity10, Quantity11> toSBPhysicalMatrix66 () const {
return SBPhysicalMatrix66<Quantity00, Quantity01, Quantity10, Quantity11>(
m00.template toSBPhysicalMatrix33<Quantity00>(), m01.template toSBPhysicalMatrix33<Quantity01>(),
m10.template toSBPhysicalMatrix33<Quantity10>(), m11.template toSBPhysicalMatrix33<Quantity11>());
}
/// \brief Returns true if the spatial matrix is dimensionless
bool isDimensionless() const {
return m00.isDimensionless() && m01.isDimensionless() && m10.isDimensionless() && m11.isDimensionless();
}
//@}
/// \name Operators
//@{
/// \brief Returns the sum of the spatial matrix with the \p mat spatial matrix
///
/// \param mat A spatial matrix
///
/// This function returns the sum of the spatial matrix with the \p mat spatial matrix. Both spatial matrices must
/// have identical units.
SBDTypePhysicalMatrix66Wrapper<Units> operator+(const SBDTypePhysicalMatrix66Wrapper<Units>& mat) const {
return SBDTypePhysicalMatrix66Wrapper<Units>(m00 + mat.m00, m01 + mat.m01, m10 + mat.m10, m11 + mat.m11);
}
/// \brief Adds the \p mat spatial matrix to this spatial matrix
///
/// \param mat A spatial matrix
///
/// This function adds the \p mat spatial matrix to this spatial matrix. Both spatial matrices must
/// have identical units.
SBDTypePhysicalMatrix66Wrapper<Units>& operator+=(const SBDTypePhysicalMatrix66Wrapper<Units>& mat) {
m00 += mat.m00;
m01 += mat.m01;
m10 += mat.m10;
m11 += mat.m11;
return *this;
}
/// \brief Returns the subtraction of the spatial matrix from the \p mat spatial matrix
///
/// \param mat A spatial matrix
///
/// This function returns the subtraction of the spatial matrix from the \p mat spatial matrix. Both spatial matrices must
/// have identical units.
SBDTypePhysicalMatrix66Wrapper<Units> operator-(const SBDTypePhysicalMatrix66Wrapper<Units>& mat) const {
return SBDTypePhysicalMatrix66Wrapper<Units>(m00 - mat.m00, m01 - mat.m01, m10 - mat.m10, m11 - mat.m11);
}
/// \brief Subtracts the \p mat spatial matrix from this spatial matrix
///
/// \param mat A spatial matrix
///
/// This function subtracts the \p mat spatial matrix from this spatial matrix. Both spatial matrices must
/// have identical units.
SBDTypePhysicalMatrix66Wrapper<Units>& operator-=(const SBDTypePhysicalMatrix66Wrapper<Units>& mat) {
m00 -= mat.m00;
m01 -= mat.m01;
m10 -= mat.m10;
m11 -= mat.m11;
return *this;
}
/// \brief Returns the opposite of the spatial matrix
SBDTypePhysicalMatrix66Wrapper<Units> operator-() const {
return SBDTypePhysicalMatrix66Wrapper<Units>(-m00, -m01, -m10, -m11);
}
/// \brief Returns the product of this spatial matrix with the double \p d
///
/// \param d A double
SBDTypePhysicalMatrix66Wrapper<Units> operator*(const double d) const {
return SBDTypePhysicalMatrix66Wrapper<Units>(m00 * d, m01 * d, m10 * d, m11 * d);
}
/// \brief Multiplies this spatial matrix with the double \p d
///
/// \param d A double
SBDTypePhysicalMatrix66Wrapper<Units>& operator*=(const double d) {
m00 *= d;
m01 *= d;
m10 *= d;
m11 *= d;
return *this;
}
/// \brief Returns the product of this spatial matrix with the spatial vector \p v
///
/// \param v A spatial vector
///
/// This function returns the product of this spatial matrix with the spatial vector \p v.
/// \ref pageUnits "SAMSON's unit system" checks that the units in the spatial matrix and the spatial vector are compatible.
SBDTypePhysicalVector6Wrapper<Units> operator*(const SBDTypePhysicalVector6Wrapper<Units>& v) const {
return SBDTypePhysicalVector6Wrapper<Units>(
m00 * v.angular + m01 * v.linear,
m10 * v.angular + m11 * v.linear
);
}
/// \brief Multiplies this spatial matrix with physical quantity \p d
SBDTypePhysicalMatrix66Wrapper<Units>& operator*=(const Units& d) {
if (!isDimensionless() || !d.isDimensionless()) throw std::runtime_error("Error, this function may only be used for dimensionless quantities");
m00 *= d;
m01 *= d;
m10 *= d;
m11 *= d;
return *this;
}
/// \brief Divides this spatial matrix by physical quantity \p d
SBDTypePhysicalMatrix66Wrapper<Units>& operator/=(const Units& d) {
if (!isDimensionless() || !d.isDimensionless()) throw std::runtime_error("Error, this function may only be used for dimensionless quantities");
m00 /= d;
m01 /= d;
m10 /= d;
m11 /= d;
return *this;
}
//@}
/// \name Useful functions
//@{
/// \brief Sets the matrix to zero
void setZero() {
m00.setZero();
m01.setZero();
m10.setZero();
m11.setZero();
}
/// \brief Makes the matrix symmetric
///
/// Makes the matrix symmetric by replacing it with the half-sum of itself and its transpose: \f$\mathbf{M}:=\frac{\mathbf{M}+\mathbf{M}^T}{2}\f$
void symmetrize() {
m00.m[0][1] = 0.5*(m00.m[0][1] + m00.m[1][0]); m00.m[0][2] = 0.5*(m00.m[0][2] + m00.m[2][0]); m01.m[0][0] = 0.5*(m01.m[0][0] + m10.m[0][0]); m01.m[0][1] = 0.5*(m01.m[0][1] + m10.m[1][0]); m01.m[0][2] = 0.5*(m01.m[0][2] + m10.m[2][0]);
m00.m[1][2] = 0.5*(m00.m[1][2] + m00.m[2][1]); m01.m[1][0] = 0.5*(m01.m[1][0] + m10.m[0][1]); m01.m[1][1] = 0.5*(m01.m[1][1] + m10.m[1][1]); m01.m[1][2] = 0.5*(m01.m[1][2] + m10.m[2][1]);
m01.m[2][0] = 0.5*(m01.m[2][0] + m10.m[0][2]); m01.m[2][1] = 0.5*(m01.m[2][1] + m10.m[1][2]); m01.m[2][2] = 0.5*(m01.m[2][2] + m10.m[2][2]);
m11.m[0][1] = 0.5*(m11.m[0][1] + m11.m[1][0]); m11.m[0][2] = 0.5*(m11.m[0][2] + m11.m[2][0]);
m11.m[1][2] = 0.5*(m11.m[1][2] + m11.m[2][1]);
m00.m[1][0] = m00.m[0][1];
m00.m[2][0] = m00.m[0][2]; m00.m[2][1] = m00.m[1][2];
m10.m[0][0] = m01.m[0][0]; m10.m[0][1] = m01.m[1][0]; m10.m[0][2] = m01.m[2][0];
m10.m[1][0] = m01.m[0][1]; m10.m[1][1] = m01.m[1][1]; m10.m[1][2] = m01.m[2][1]; m11.m[1][0] = m11.m[0][1];
m10.m[2][0] = m01.m[0][2]; m10.m[2][1] = m01.m[1][2]; m10.m[2][2] = m01.m[2][2]; m11.m[2][0] = m11.m[0][2]; m11.m[2][1] = m11.m[1][2];
}
/// \brief Sets the matrix to identity
void setIdentity() {
m00.setIdentity();
m11.setIdentity();
m01.setZero();
m10.setZero();
}
/// \brief Returns the transpose
SBDTypePhysicalMatrix66Wrapper<Units> transpose() const {
return SBDTypePhysicalMatrix66Wrapper<Units>(m00.transpose(), m10.transpose(), m01.transpose(), m11.transpose());
}
/// \brief Returns twice the symmetric part of the matrix
SBDTypePhysicalMatrix66Wrapper<Units> doubleSymmetricPart() const {
return SBDTypePhysicalMatrix66Wrapper<Units>(m00 + m00.transpose(), m01 + m10.transpose(), m10 + m01.transpose(), m11 + m11.transpose());
}
//@}
/// \name String representation
//@{
/// \brief Returns the string representation of the spatial matrix (with a full unit name when fullName is true)
std::string toStdString(bool fullName = false) const {
std::string ret = "";
ret += "m00\n" + m00.toStdString(fullName);
ret += "m01\n" + m01.toStdString(fullName);
ret += "m10\n" + m10.toStdString(fullName);
ret += "m11\n" + m11.toStdString(fullName);
return ret;
}
//@}
public:
SBDTypePhysicalMatrix33Wrapper<Units> m00; ///< The top left 3x3 matrix
SBDTypePhysicalMatrix33Wrapper<Units> m01; ///< The top right 3x3 matrix
SBDTypePhysicalMatrix33Wrapper<Units> m10; ///< The bottom left 3x3 matrix
SBDTypePhysicalMatrix33Wrapper<Units> m11; ///< The bottom right 3x3 matrix
};
/// \name Common types and shortnames
//@{
#define SBPhysicalMatrix66Wrapper SBDTypePhysicalMatrix66Wrapper
typedef SBDTypePhysicalMatrix66Wrapper<SBDQuantityWrapperSI> SBDTypePhysicalMatrix66WrapperSI;
typedef SBDTypePhysicalMatrix66Wrapper<SBDQuantityWrapperSI> SBPhysicalMatrix66WrapperSI;
//@}
/// \name External functions
//@{
/// \brief Returns the SBPhysicalMatrix66<Quantity00, Quantity01, Quantity10, Quantity11> from Unit \p u
template<typename Quantity00, typename Quantity01,
typename Quantity10, typename Quantity11,
typename T>
SBPhysicalMatrix66<Quantity00, Quantity01, Quantity10, Quantity11> getSBPhysicalMatrix66(const T& a) {
return a.template toSBPhysicalMatrix66<Quantity00, Quantity01, Quantity10, Quantity11>();
}
//@}
/// \name External operators
//@{
/// \brief Returns the product of double \p d and spatial matrix \p u
template<typename Units>
SBDTypePhysicalMatrix66Wrapper<Units> operator*(const double d, const SBDTypePhysicalMatrix66Wrapper<Units>& u) {
return SBDTypePhysicalMatrix66Wrapper<Units>(u.m00 * d, u.m01 * d, u.m10 * d, u.m11 * d);
}
//@}
#endif
| true |
b7601021539c1e075371c6ab65158f777ff8825b | C++ | darshan-kavathe/Broken-Heroes-of-the-Feral-Vale | /hero/role.h | UTF-8 | 763 | 3.203125 | 3 | [] | no_license | //
// Created by Darshan Kavathe on 3/1/2018.
//
#ifndef PROJECT_1_ROLE_H
#define PROJECT_1_ROLE_H
#include "iostream"
//using std::string
namespace hero{
class Role{
public:
//Their type.
enum Type { FIGHTER, HEALER, TANK };
//Create the role.
//@param Type type
Role (Type type);
//Get their type.
//Returns type
Role::Type get_type () const;
/*
* A string conversion operator that returns the string name of the role, e.g.
* "FIGHTER", "HEALER", "TANK".
* @returns string name
*/
operator std::string () const;
private:
//Their type.
Role::Type type_;
};
}
#endif //PROJECT_1_ROLE_H
| true |
55251fcddd0843eef8674ef4e8d0c14c156d24e1 | C++ | valeclere/TP4 | /Rectangle.cpp | UTF-8 | 565 | 3.328125 | 3 | [] | no_license | #include "Rectangle.hpp"
Rectangle::Rectangle(): Forme(Point(0,0),0,0)
{
std::cout << "Creation Rectangle" << std::endl;
}
Rectangle::Rectangle(int x, int y, int w, int h): Forme(Point(x,y), w,h)
{
std::cout << "Creation Rectangle" << std::endl;
}
std::string Rectangle::toString(void) const{
std::string chaine = "RECTANGLE "+std::to_string(p.getX())+" "+std::to_string(p.getY())+" "+std::to_string(w)+" "+std::to_string(h);
return chaine;
}
int Rectangle::getLargeur() const{
return w;
}
int Rectangle::getHauteur() const{
return h;
} | true |
8bb462540d5c937a9a40cd49454ed70bab8551a8 | C++ | alisson002/Estrutura-de-dados | /Lista 2/Q2/main.cpp | UTF-8 | 820 | 3.53125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int separarNumeros(int numero){
while(numero>=10){
numero-=10;
}
return numero;
}
int main()
{
int numero,vet[100],x=0,a,j,cond=true,i=0;
cout<<"Insira um numero: ";
cin>>numero;
while(numero>0){
vet[x] = separarNumeros(numero);
x++;
numero = numero/10;
}
cout<<endl;
j=x-1;
while(cond==true){
if(vet[i]==vet[j]){
cout<<vet[i]<<" = "<<vet[j]<<endl;
cond=true;
}
else{
cout<<vet[i]<<" != "<<vet[j]<<endl;
cond=false;
}
j--;
i++;
}
cout<<endl;
cout<<"Sim = 1 | Nao = 0: "<<cond<<endl;
return 0;
}
| true |
e3e19f5dda50a8d391bb57e743c1dc322cf27b5f | C++ | mgh3326/baekjoon_algorithm | /12_큐 사용하기/큐/큐/소스.cpp | UHC | 1,815 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include <vector>
#include <queue>
using namespace std;
int main(void) {
// 200Ʈ ڿ Ǵ 迭
// 迭 ˸ NULL 1 ʿϱ 200 + 1 = 201
int num;
scanf("%d", &num);
queue<int> que; // default deque ̳
//queue<int, vector<int>> que; vector ̳ʸ ̿Ͽ queue ̳
for (int i = 0; i < num; i++)
{
string str = "";
getline(cin, str);
if (str == "")//ó ̷ ־ϴ°ǰ ʹ.
{
getline(cin, str);
}
if (str.length() > 5 && str[4] == 32)//&& տ ȵǸ ڿ Ⱥ ű
{//̰ push ϰڴ.
string numberString = str.substr(5, str.length());
int myNr = std::stoi(numberString);
que.push(myNr); // ť
}
else if (str[0] == 'p')//pop
{
if (que.empty()) // ť Ȯ
printf("-1\n");
else {
printf("%d\n", que.front());
que.pop();
}
}
else if (str[0] == 's')//size
{
printf("%d\n", que.size());
}
else if (str[0] == 'e')//empty
{
if (que.empty()) // ť Ȯ
printf("1\n");
else {
printf("0\n");
}
}
else if (str[0] == 'f')//front
{
if (que.empty()) // ť Ȯ
printf("-1\n");
else {
printf("%d\n", que.front());
}
}
else if (str[0] == 'b')//back
{
if (que.empty()) // ť Ȯ
printf("-1\n");
else {
printf("%d\n", que.back());
}
}
}
return 0;
}
/*
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
*/
| true |
c5908fe957e8a3262e2a2f9db552c88a9ad60a51 | C++ | fickleview/Bridge | /Temperature.ino | UTF-8 | 7,477 | 2.625 | 3 | [] | no_license | // Last modified 2014-12-10
// Should not be modified
// DS18B20
OneWire ds18b20(DS18B20_PIN); // OneWire is a Dallas Semiconductor library
// DS18B20 Statemachine implementation
// SM_DS18B20.Set(M_start_DS18B20); // Do that when you want to collect temps
State SM_start_DS18B20()
{
//*DS18B20addr // Start using pointer
ds18b20.reset(); // reset the bus, no error detection
ds18b20.select(DS18B20addr); // Now all ROM commands address this device until next reset
ds18b20.write(0x44, 1); // Start conversion on selected device
SM_DS18B20.Set(SM_wait_DS18B20); //
}
byte aScratchPad[8];
byte *TempLSB = aScratchPad; // Only three elemements are named
byte *TempMSB = aScratchPad+1;
byte *CRC = aScratchPad+8; // We need all ScratchPad to create a CRC for comparison to what was sent
void printBinaryBits (byte bits)
{
for(int b = 7; b>=0; b--)
{
Serial << bitRead(bits,b);
}
}
State SM_wait_DS18B20()
{
if(SM_DS18B20.Timeout(1000))
{
int iDS18BTemp =0; // The last four bits of the MSB, Data[1]
int iDS18B20bits=0; // The last four bits of the LSB, Data[0] the decimal part, each bit .0625 degrees C
int iDS18B20bit =0; // The single decimal bit x10 that we will retain from all bits
float fDS18BTemp =0.0;
bool bCRCfailed = false;
ds18b20.reset();
ds18b20.select(DS18B20addr);
// Issue Read scratchpad command
ds18b20.write(0xBE);
// Read 9 bytes: aScratchPad[0], aScratchPad[1] ... aScratchPad[8]
for ( int i = 0; i < 9; i++)
{
aScratchPad[i] = ds18b20.read();
}
if (OneWire::crc8(aScratchPad, 8) != *CRC) // Compute the CRC using oneWire function and compare it to what was read
{
bCRCfailed = true;
Serial << endl << F("==== CRC FAILED ====") << endl << endl;
}
else
{
// Calculate temperature
fDS18BTemp = (((*TempMSB << 8) + *TempLSB) * 0.625) ;
iDS18BTemp = (int)fDS18BTemp;
}
switch(DS18B20addr[1])
{
default:
SM_DS18B20.Finish();
*insideTemp305 = -32000;
*outsideTemp306 = -32000;
break;
case (INSIDE_DS18B20_SENSOR):
if(bCRCfailed == false)
{
*insideTemp305 = iDS18BTemp;
}
DS18B20addr = DS18B20_BRIDGE_OUTSIDE_ADD;
SM_DS18B20.Set(SM_start_DS18B20); // Do outside
break;
case (OUTSIDE_DS18B20_SENSOR):
if(bCRCfailed == false)
{
//*outsideTemp306 = iDS18BTemp;
int calFactor = ((*insideTemp305 - iDS18BTemp)*10)/ *calFactorTemp307;
*outsideTemp306 = iDS18BTemp - calFactor ; // cal factor through the wall probe
Serial << endl << endl << "In: " << *insideTemp305 << " Out: " << iDS18BTemp << " Cal: " << calFactor << " Cor: " << *outsideTemp306 << endl << endl;
}
DS18B20addr = DS18B20_BRIDGE_INSIDE_ADD;
SM_DS18B20.Finish(); // In another function
break;
}
}
}
// end State machine DS18B20
/*
// DS18B20 test script
#define DS18S20_ID 0x10
#define DS18B20_ID 0x28
// OneWire ds18b20(DS18B20_PIN); // OneWire is a Dallas Semiconductor library
float fTempDS18B20;
int iTempDS18B20;
int iLastTempDS18B20 = 0;
boolean getTemperature()
{
byte i;
byte present = 0;
byte data[12];
byte addr[8];
//find a device
if (!ds18b20.search(addr))
{
ds18b20.reset_search();
return false;
}
// Print the address in HEX
Serial << "Found DS: ";
for( i = 0; i <= 8; i++)
{
Serial << _HEX(addr[i]);
}
Serial << endl;
if (OneWire::crc8( addr, 7) != addr[7])
{
return false;
}
if (addr[0] != DS18S20_ID && addr[0] != DS18B20_ID)
{
return false;
}
ds18b20.reset();
ds18b20.select(addr);
// Start conversion
ds18b20.write(0x44, 1);
// Wait some time...
delay(850);
present = ds18b20.reset();
ds18b20.select(addr);
// Issue Read scratchpad command
ds18b20.write(0xBE);
// Receive 9 bytes
for ( i = 0; i < 9; i++)
{
data[i] = ds18b20.read();
}
// Calculate temperature value
fTempDS18B20 = ( (data[1] << 8) + data[0] )*0.0625;
iTempDS18B20 = int(fTempDS18B20);
// Send a notification out the serial port
// Log it as well. Has to be to and from 'X'.. 116 is 't' text - low severity
// Humidity is '100' in the example
if(!(iLastTempDS18B20==iTempDS18B20))
{
iLastTempDS18B20=iTempDS18B20;
// Serial << F("DS18B20 status okay.") << endl;
Serial << F("Temp float: ") << fTempDS18B20 << endl;
Serial << F("Temp Int : ") << iTempDS18B20 << endl;
// Serial << F("RXXB*N4,116,") << iTempDS18B20 << F(",100,") << *absolute_time_t501 << "#" << endl;
}
return true;
}
*/
// TTTTTTTTTTTTTTTTTTTT Temperature 2.0 TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
// TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
#ifdef TEMPERATURE_LM335
#define BitsPerDegree 215 // Slope 2.15
// #define Bits0Degrees 5490 // Offset. 10 x the bits at zero degrees in WATER.
#define Bits0DegreesAir 5650 // Offset. 10 x the bits at zero degrees AIR temp.
// When self heating is an issue for air temp make this lower.
// Read the temperature LM335 sensor 2k2 and 5v
// makes the last digit round down, 5, or round up
int roundTemp(int t)
{
int m = 0; // Modulo
m = t % 10; // What is the last bit?
t -= m; // Strip the last bit
if (m >= 7)
{
m = 10; // Round up
}
else if (m <= 3)
{
m = 0; // Round down
}
else
{
m = 5; // Make it .5
}
return (t += m); // Now make the last digit round down, 5, or round up
}
// Read the temperature LM335 sensor 2k2 and 5v
int tempOnPin(int _pin,int _offset,int _slope)
{
int _temp;
_temp = ((analogRead(_pin) - _offset) * 100 / _slope); // 10 x the degrees c on pin returned
if ((_temp > MaxTempError) || (_temp < MinTempError)) // between Max and Min or error
{
return (TempError) ; // Used by calling routine to determine if sensor is shorted or open
}
else
{
return (roundTemp(_temp));
}
}
long getTemp() // fieldType = FieldBase, field = sensor or channel
{
switch (fieldType)
{
case (OTHER_BASE): // Currently ony 900 range
//
// pin = field // 0 to 5 else error
// offset= atoi(stData + (dataFieldsize + 1 ) ) // each temp channel has a custom offset
//
// 1 = 5574 air
// 0 = 5670 water
// slope = BitsPerDegree
// tempOnPin = 10x the degrees c, which peovides a single decimal point resolution.
// roundTemp = last digit rounded down to 0, 5 or rounded up to next.
if ((field >= 0) && (field <= 15)) // Valid analog pins for temperature
{
errorMRMP = '0';
return (tempOnPin(field,parm2,BitsPerDegree)) ;
}
else
{
errorMRMP = 't';
return TempError;
}
break;
default:
// RpacketReply('t',0);
errorMRMP = 't';
return TempError;
}
}
#endif // TEMPERATURe_LM335
| true |
6691bde56c7c0252bd625df307b8d502b2f30985 | C++ | sandwichboyyyy/Experiment_2_Summer | /Ex2_P4.cpp | UTF-8 | 291 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int counter;
cout << "Counting to 30... \n";
for(counter=1;counter<=9;counter++)
{
cout << counter << "," ;
}
for(counter=10;counter<=30;counter+=2)
{
cout << counter << ",";
}
getch();
return 0;
}
| true |