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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
544f6b5a6c0d741b6f593b28c58e56e36b2763c1 | C++ | AgmLee/Networking-Library | /Test Project/ntwk server/ntwk/ServerController.h | UTF-8 | 1,925 | 3.125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <vector>
namespace ntwk
{
///Though this class was made to help with controlling the ServerManger functions and settings,
///This was designed in a way that makes it more of a Command-line controller.
///Create a derived class and in 'compareToCommands' don't reference the ServerManager or a
///dirived class of it and it will still be usable for taking in an input and checking it to different commands.
class ServerController
{
public:
///Make sure to overide the 'Instance' function when creating a dirived class.
///Otherwise it will return a new ServerController and not a ServerController pointer to the child class.
//Returns the current instance of ServerController, if none exists it creates one
static ServerController * Instance(void);
//Destroys the current instance of ServerController
static void Destroy(void);
//Ends processing, use outside of the class
static void EndProcessing(void);
//Splits input then sends it through compareToCommands and reacts accordingly
std::string checkInput(const std::string&);
//Continues the processing loop until it returns false
bool isProcessing(void);
//Used for ending the processing from outside of the class
void setProcessing(bool);
protected:
ServerController(); //Default constructor
virtual ~ServerController(); //Destructor
//Removed constructors/operators
ServerController(const ServerController&) = delete; //Copy constructor
void operator=(const ServerController&) = delete; //Assignment opperator
//Compares the split input to different commands, can use the full input as well
virtual std::string compareToCommands(const std::vector<std::string>&, const std::string&);
static ServerController * s_instance;
///Set processing to false in compareToCommands as to end the process loop from inside of the class.
bool m_processing = true;
};
} //ntwk
| true |
275bcd3fa500269e4272a5530c9842f10899a060 | C++ | giranath/SpookySushi | /engine/async/public/job.hpp | UTF-8 | 3,805 | 2.78125 | 3 | [] | no_license | #ifndef SPOOKYSUSHI_JOB_HPP
#define SPOOKYSUSHI_JOB_HPP
#include "../../platform/public/host_infos.hpp"
#include <atomic>
#include <cstring>
#include <new>
#include <memory>
namespace sushi { namespace async {
class job {
public:
using job_fn = void(*)(job&);
private:
job_fn fn;
job* parent;
std::atomic_size_t unfinished_count;
// Add some padding to disable False-Sharing
static const std::size_t PAYLOAD_SIZE = sizeof(decltype(fn)) + sizeof(decltype(parent)) + sizeof(decltype(unfinished_count));
static const std::size_t PADDING_SIZE = sushi::CACHE_LINE_SIZE - PAYLOAD_SIZE;
uint8_t padding[PADDING_SIZE];
void terminate() noexcept;
public:
constexpr job() noexcept
: fn(nullptr)
, parent(nullptr)
, unfinished_count(0)
, padding{0} {
}
constexpr job(job_fn fn) noexcept
: fn(fn)
, parent(nullptr)
, unfinished_count(1)
, padding{0} {
}
constexpr job(job_fn fn, job* parent) noexcept
: fn(fn)
, parent(parent)
, unfinished_count(1)
, padding{0} {
if(parent) {
parent->unfinished_count++;
}
}
void execute();
bool is_finished() const noexcept;
// Can only store small pod data
template<typename Data, typename Allocator = std::allocator<Data>>
typename std::enable_if<std::is_pod<Data>::value && (sizeof(Data) <= PADDING_SIZE)>::type
store(const Data& data) noexcept {
std::memcpy(padding, &data, sizeof(data));
}
// Construct an object in place
template<typename Type, typename... Args>
typename std::enable_if<sizeof(Type) <= PADDING_SIZE>::type
emplace(Args... args) {
new(padding) Type(std::forward<Args>(args)...);
}
// Retrieve stored data
template<typename Data>
Data& data() noexcept {
return *reinterpret_cast<Data*>(padding);
}
template<typename Data>
const Data& data() const noexcept {
return *reinterpret_cast<Data*>(padding);
}
template<typename Closure, typename Allocator = std::allocator<Closure>>
static typename std::enable_if<(sizeof(Closure) <= PADDING_SIZE), job*>::type
make_closure(job* j, job* parent, Closure closure) {
auto fn = [](job& ze_job) {
Closure& closure = ze_job.data<Closure>();
// Execute the function
closure(ze_job);
// Calls the destructor of the attached closure
closure.~Closure();
};
new(j) job(fn, parent);
j->emplace<Closure>(closure);
return j;
}
template<typename Closure, typename Allocator = std::allocator<Closure>>
static typename std::enable_if<(sizeof(Closure) > PADDING_SIZE), job*>::type
make_closure(job* j, job* parent, Closure closure) {
struct closure_data {
Closure* closure;
Allocator allocator;
closure_data(Closure* closure, const Allocator& allocator)
: closure(closure)
, allocator(allocator) {
}
};
auto fn = [](job& ze_job) {
auto data = ze_job.data<closure_data>();
(*data.closure)(ze_job);
// Calls destructor
data.closure->~Closure();
data.allocator.deallocate(data.closure, 1);
};
new(j) job(fn, parent);
Allocator allocator;
Closure* ptr_location = allocator.allocate(1);
new(ptr_location) Closure{closure};
j->emplace<closure_data>(ptr_location, allocator);
return j;
}
template<typename Closure, typename Allocator = std::allocator<Closure>>
static job* make_closure(job* j, Closure closure) {
return make_closure(j, nullptr, std::move(closure));
}
};
}}
#endif //SPOOKYSUSHI_JOB_HPP
| true |
d6bc35867679b31f4b7ed49e31a12cefb57ec1ec | C++ | Nikitosis/Graph-Helper | /Forms/visualalgorithm.cpp | UTF-8 | 8,842 | 2.5625 | 3 | [] | no_license | #include "visualalgorithm.h"
#include "ui_visualalgorithm.h"
VisualAlgorithm::VisualAlgorithm(Graph *graph,QWidget *parent) :
QDialog(parent),
ui(new Ui::VisualAlgorithm)
{
ui->setupUi(this);
_graph=new Graph(graph,this);
init();
initDfs();
isExit=false;
}
void VisualAlgorithm::init()
{
QSizePolicy policy=ui->Graph->sizePolicy();
policy.setHorizontalStretch(3.93);
ui->Graph->setSizePolicy(policy);
policy=ui->Code->sizePolicy();
policy.setHorizontalStretch(7);
ui->Code->setSizePolicy(policy);
ui->splitter_2->setStretchFactor(0,2);
ui->splitter_2->setStretchFactor(1,1);
ui->Watch->setColumnCount(2);
QStringList list;
list<<"Name"<<"Value";
ui->Watch->setHeaderLabels(list);
QVector<MyEdge*> Edges=_graph->getEdges();
QVector<Bridge*> Bridges=_graph->getBridges();
for(int i=0;i<Edges.size();i++)
{
ui->Graph->addElement(Edges[i]);
Edges[i]->setParent(ui->Graph);
}
for(int i=0;i<Bridges.size();i++)
{
ui->Graph->addElement(Bridges[i]);
Bridges[i]->setParent(ui->Graph);
}
}
VisualAlgorithm::~VisualAlgorithm()
{
delete ui;
}
void VisualAlgorithm::addOneDArray(QVector<QString> &values, QVector<QString> &names, QString mainName)
{
QTreeWidgetItem *mainItem=new QTreeWidgetItem(ui->Watch);
mainItem->setText(0,mainName);
for(int i=0;i<names.size();i++)
{
QTreeWidgetItem *item=new QTreeWidgetItem(mainItem);
item->setText(0,names[i]);
item->setText(1,values[i]);
}
}
void VisualAlgorithm::addTwoDArray(QVector<QVector<QString>> &values, QVector<QString> &arrayNames,QVector<QString> valueNames, QString mainName)
{
QTreeWidgetItem *mainItem=new QTreeWidgetItem(ui->Watch);
mainItem->setText(0,mainName);
for(int i=0;i<arrayNames.size();i++)
{
QTreeWidgetItem *arrayItem=new QTreeWidgetItem(mainItem);
arrayItem->setText(0,arrayNames[i]);
for(int j=0;j<valueNames.size();j++)
{
QTreeWidgetItem *item=new QTreeWidgetItem(arrayItem);
item->setText(0,valueNames[j]);
item->setText(1,values[i][j]);
}
}
}
void VisualAlgorithm::changeBridgeColor(int startEdgeId, int endEdgeId,QColor color)
{
QVector<Bridge *> &Bridges=_graph->getBridges();
for(int i=0;i<Bridges.size();i++)
if((Bridges[i]->getStartEdge()->getId()==startEdgeId && Bridges[i]->getEndEdge()->getId()==endEdgeId)
|| (Bridges[i]->getStartEdge()->getId()==endEdgeId && Bridges[i]->getEndEdge()->getId()==startEdgeId))
{
Bridges[i]->setColor(color);
return;
}
qDebug()<<"Cannot find Bridge by its Edges"<<endl;
}
void VisualAlgorithm::changeEdgeColor(int id, QColor color)
{
QVector<MyEdge *>&Edges=_graph->getEdges();
for(int i=0;i<Edges.size();i++)
if(Edges[i]->getId()==id)
{
Edges[i]->setColor(color);
return;
}
qDebug()<<"Cannot find Edge by its Id"<<endl;
}
void VisualAlgorithm::changeAllBridgesColor(QColor color)
{
QVector<Bridge *> &Bridges=_graph->getBridges();
for(int i=0;i<Bridges.size();i++)
Bridges[i]->setColor(color);
}
void VisualAlgorithm::changeAllEdgesColor(QColor color)
{
QVector<MyEdge *>&Edges=_graph->getEdges();
for(int i=0;i<Edges.size();i++)
Edges[i]->setColor(color);
}
void VisualAlgorithm::Dfs(int startEdge)
{
mtx.lock();
QVector<QVector<int>> &Matrix=_graph->getCorrectMatrix();
QVector<MyEdge *> Edges=_graph->getEdges();
QVector<bool> Visited(Matrix.size());
QVector<int> Stack;
QVector<QPair<int,int>> BridgesVec;
if(Matrix.size()==0)
{
isExit=true;
mtx.unlock();
return;
}
updateDfs(Matrix,Visited,Stack);
lockLine(4);
Visited[startEdge]=true;
updateDfs(Matrix,Visited,Stack);
lockLine(5);
Stack.push_back(startEdge);
updateDfs(Matrix,Visited,Stack);
lockLine(6);
while(!Stack.empty())
{
changeEdgeColor(Edges[Stack.last()]->getId(),ACTIVE_BRIDGE_COLOR);
updateDfs(Matrix,Visited,Stack);
lockLine(8);
for(int i=0;i<Matrix.size();i++)
{
lockLine(9);
lockLine(10);
if(Matrix[Stack.last()][i]!=0 && !Visited[i])
{
changeBridgeColor(Edges[Stack.last()]->getId(),Edges[i]->getId(),ACTIVE_BRIDGE_COLOR);
changeEdgeColor(Edges[i]->getId(),ACTIVE_BRIDGE_COLOR);
changeEdgeColor(Edges[Stack.last()]->getId(),PASSIVE_BRIDGE_COLOR);
if(BridgesVec.size()>0)
{
int first=BridgesVec[BridgesVec.size()-1].first;
int second=BridgesVec[BridgesVec.size()-1].second;
changeBridgeColor(Edges[first]->getId(),Edges[second]->getId(),PASSIVE_BRIDGE_COLOR);
}
BridgesVec.push_back({Stack.last(),i});
lockLine(11);
lockLine(12);
Visited[i]=true;
updateDfs(Matrix,Visited,Stack);
lockLine(13);
Stack.push_back(i);
updateDfs(Matrix,Visited,Stack);
lockLine(14);
i=-1;
updateDfs(Matrix,Visited,Stack);
lockLine(15);
}
lockLine(16);
}
changeEdgeColor(Edges[Stack.last()]->getId(),PASSIVE_BRIDGE_COLOR);
if(BridgesVec.size()>0)
{
int first=BridgesVec[BridgesVec.size()-1].first;
int second=BridgesVec[BridgesVec.size()-1].second;
changeBridgeColor(Edges[first]->getId(),Edges[second]->getId(),PASSIVE_BRIDGE_COLOR);
BridgesVec.pop_back();
}
updateDfs(Matrix,Visited,Stack);
lockLine(17);
Stack.pop_back();
updateDfs(Matrix,Visited,Stack);
lockLine(18);
}
updateDfs(Matrix,Visited,Stack);
lockLine(19);
qDebug()<<"Go!";
mtx.unlock();
}
void VisualAlgorithm::initDfs()
{
QFile file(":/Algorithms/Algorithms/DFS.txt");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream(&file);
stream.setCodec("UTF-8");
ui->Code->document()->setPlainText(stream.readAll());
changeAllBridgesColor(DEFAULT_BRIDGE_COLOR);
changeAllEdgesColor(DEFAULT_BRIDGE_COLOR);
isExit=false;
int startEdge=-1;
do
{
bool isOk=false;
QString str= QInputDialog::getText(0,
"First Edge",
"First Edge:",
QLineEdit::Normal,
"",
&isOk
);
if(!isOk)
return;
QVector<MyEdge *>Edges=_graph->getEdges();
for(int i=0;i<Edges.size();i++)
if(Edges[i]->getInfo()==str)
{
startEdge=i;
break;
}
}while(startEdge==-1);
future = QtConcurrent::run(this,&VisualAlgorithm::Dfs,startEdge); //Create thread with Algo function
}
void VisualAlgorithm::updateDfs(QVector<QVector<int> > &Matrix, QVector<bool> &Visited, QVector<int> &Stack)
{
if(isExit)
return;
ui->Watch->clear();
QVector<MyEdge *>Edges=_graph->getEdges();
QVector<QString> Names(Edges.size());
QVector<QVector<QString>> StringMatrix(Matrix.size());
for(int i=0;i<Edges.size();i++)
Names[i]=Edges[i]->getInfo();
for(int i=0;i<Matrix.size();i++)
for(int j=0;j<Matrix[i].size();j++)
StringMatrix[i].push_back(QString::number(Matrix[i][j]));
addTwoDArray(StringMatrix,Names,Names,"Matrix");
QVector<QString> Values;
for(int i=0;i<Visited.size();i++)
Values.push_back(QString::number(Visited[i]));
addOneDArray(Values,Names,"Visited");
Values.clear();
for(int i=0;i<Stack.size();i++)
Values.push_back(Edges[Stack[i]]->getInfo());
QVector<QString> Numbers;
for(int i=0;i<Stack.size();i++)
Numbers.push_back(QString::number(i+1));
addOneDArray(Values,Numbers,"Stack");
}
void VisualAlgorithm::breakAlgo()
{
isExit=true;
condit.wakeAll();
future.waitForFinished(); //to not leave working thread
}
void VisualAlgorithm::lockLine(int codeLineIndex)
{
if(isExit)
return;
ui->Code->enableDebugMode(codeLineIndex);
ui->Code->update();
condit.wait(&mtx);
}
void VisualAlgorithm::reject()
{
breakAlgo();
delete this;
}
void VisualAlgorithm::on_debugStep_clicked()
{
if(!future.isRunning())
initDfs();
condit.wakeAll();
}
void VisualAlgorithm::on_debugBreak_clicked()
{
breakAlgo();
initDfs();
}
| true |
865c6bcc9a7fe8f18594c8a27e09cb8b05e39988 | C++ | SBNSoftware/icaruscode | /icaruscode/Utilities/EventRegistry.h | UTF-8 | 7,018 | 2.703125 | 3 | [] | no_license | /**
* @file icaruscode/Utilities/EventRegistry.h
* @brief Class keeping track of _art_ event IDs.
* @author Gianluca Petrillo (petrillo@slac.stanford.edu)
* @date January 22, 2021
* @see icaruscode/Utilities/EventRegistry.cxx
*
*
*
*
*/
#ifndef ICARUSCODE_UTILITIES_EVENTREGISTRY_H
#define ICARUSCODE_UTILITIES_EVENTREGISTRY_H
// framework libraries
#include "canvas/Persistency/Provenance/EventID.h"
#include "cetlib_except/exception.h"
// C/C++ standard libraries
#include <unordered_map>
#include <vector>
#include <mutex>
#include <utility> // std::pair<>
#include <string>
#include <functional> // std::hash<>
#include <optional>
#include <limits> // std::numeric_limits<>
#include <cstddef> // std::size_t
// -----------------------------------------------------------------------------
namespace std {
template <>
struct hash<art::EventID> {
std::size_t operator() (art::EventID const& ID) const noexcept
{
return std::hash<std::uint64_t>{}(
(std::uint64_t{ ID.run() } << 40U) // run: 24 bits (16M)
+ (std::uint64_t{ ID.subRun() } << 22U) // subrun: 18 bits (256k)
+ (std::uint64_t{ ID.event() }) // event: 22 bits (4M)
);
}
}; // hash<art::EventID>
} // namespace std
// -----------------------------------------------------------------------------
namespace sbn { class EventRegistry; }
/**
* @brief Keeps a record of all registered events and their source.
*
* This registry object will keep track of every time an event is "registered".
* An event is represented by its ID (`art::EventID`), and it is associated to
* the input file(s) it is stored in.
*
* Input files can be registered separately by file name, or at the same time
* with the event.
*
*
* Thread safety
* --------------
*
* Registration of events can happen concurrently (thread-safe).
* Registration of source files, instead, is not protected.
*
* It is guaranteed that the source file records are never modified once
* registered (i.e. neither removed from the registry, nor the path of a source
* record changed).
*
*/
class sbn::EventRegistry {
public:
using EventID_t = art::EventID; ///< Type used to identify an event.
using FileID_t = std::size_t; ///< Type used to identify a source file.
/// Element of the registry for an event.
struct EventRecord_t {
std::vector<FileID_t> sourceFiles; ///< List of ID of source files.
}; // EventRecord_t
/// Type with event ID (`first`) and event record information (`second`).
using EventIDandRecord_t = std::pair<EventID_t, EventRecord_t>;
/// Mnemonic for no file ID.
static constexpr FileID_t NoFileID = std::numeric_limits<FileID_t>::max();
// -- BEGIN -- Source interface ----------------------------------------------
/// @name Source interface
/// @{
/**
* @brief Registers a source file and returns its ID in the registry.
* @param fileName the name of the source file to be registered
* @return the internal ID this registry will refer to `fileName` with
*
* If `fileName` has already been registered, the existing ID is returned and
* no other action is performed.
*/
FileID_t recordSource(std::string const& fileName);
/// Returns whether the specified file ID is registered as a source.
bool hasSource(FileID_t const& fileID) const;
/// Returns whether the specified file name is registered as a source.
bool hasSource(std::string const& fileName) const;
/// Returns the ID of the source with the specified file name (slow!).
/// @return the ID of the source, or unset if `fileID` is not registered
std::optional<FileID_t> sourceID(std::string const& fileName) const;
/// Returns the name of the source associated to the specified file ID.
/// @return the name of the source, or unset if `fileID` is not registered
std::optional<std::string> sourceName(FileID_t const& fileID) const;
/// Returns the name of the source associated to the specified file ID.
/// @return the name of the source, or `defName` if `fileID` is not registered
std::string sourceNameOr
(FileID_t const& fileID, std::string const& defName) const;
/// @}
// -- END -- Source interface ------------------------------------------------
// -- BEGIN -- Event interface -----------------------------------------------
/// @name Event interface
/// @{
/// Returns a copy of all event records.
std::vector<EventIDandRecord_t> records() const;
/// Returns a copy of the specified event record.
/// @return the record for `event`, or unset if `event` is not registered
std::optional<EventRecord_t> eventRecord(art::EventID const& event) const;
/**
* @brief Registers an event and returns a copy of its record.
* @param event ID of the event to be registered
* @param sourceFileID ID of the source file to be associated with the `event`
* @return the current copy, just updated, of the record of the `event`
* @throw cet::exception (category: `"sbn::EventRegistry"`) if `sourceFileID`
* dose not match a registered source file
* @see `recordEvent(EventID_t const&, std::string const&)`
*
* The record of the specified `event` is updated adding `sourceFileID` among
* its sources. A single `sourceFileID` can appear multiple times for the same
* event, indicating a duplicate event in the same source file.
*
* A source with `sourceFileID` must have been registered already
* (`recordSource()`).
*
*/
EventRecord_t recordEvent(EventID_t const& event, FileID_t sourceFileID);
/// @}
// -- END -- Event interface -------------------------------------------------
private:
/// Type for source file registry.
using FileRegistry_t = std::vector<std::string>;
/// Registered source file, by file ID key.
std::vector<std::string> fSourceFiles;
/// Registry of all events.
std::unordered_map<EventID_t, EventRecord_t> fEventRegistry;
mutable std::mutex fEventRegistryLock; ///< Lock for `fEventRegistry`.
//@{
/// Returns an iterator pointing to the specified file registry entry.
FileRegistry_t::iterator findSource(std::string const& fileName);
FileRegistry_t::const_iterator findSource(std::string const& fileName) const;
//@}
/// Copies all event records into `recordCopy`.
void copyEventRecordsInto(std::vector<EventIDandRecord_t>& recordCopy) const;
/// Returns a lock guard around `fEventRegistry`.
std::lock_guard<std::mutex> lockEventRegistry() const;
/// Converts an internal index in file source registry into a `FileID_t`.
static FileID_t indexToFileID(std::size_t index);
/// Converts a `FileID_t` into an internal index in file source registry.
static std::size_t fileIDtoIndex(FileID_t fileID);
}; // sbn::EventRegistry
// -----------------------------------------------------------------------------
#endif // ICARUSCODE_UTILITIES_EVENTREGISTRY_H
| true |
fca3713ab389484f5ff8468d0ddf0ada6a4fe8ad | C++ | polybar/polybar | /include/utils/command.hpp | UTF-8 | 2,618 | 2.84375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #pragma once
#include "common.hpp"
#include "components/logger.hpp"
#include "components/types.hpp"
#include "errors.hpp"
#include "utils/file.hpp"
POLYBAR_NS
DEFINE_ERROR(command_error);
enum class output_policy {
REDIRECTED,
IGNORED,
};
/**
* Wrapper used to execute command in a subprocess.
* In-/output streams are opened to enable ipc.
* If the command is created using command<output_policy::REDIRECTED>, the child streams are
* redirected and you can read the program output or write into the program input.
*
* If the command is created using command<output_policy::IGNORED>, the output is not redirected and
* you can't communicate with the child program.
*
* Example usage:
*
* @code cpp
* command<output_policy::REDIRECTED>auto(m_log, "cat /etc/rc.local");
* cmd->exec();
* cmd->tail([](string s) { std::cout << s << std::endl; });
* @endcode
*
* @code cpp
* command<output_policy::REDIRECTED>auto(m_log, "for i in 1 2 3; do echo $i; done");
* cmd->exec();
* cout << cmd->readline(); // 1
* cout << cmd->readline() << cmd->readline(); // 23
* @endcode
*
* @code cpp
* command<output_policy::IGNORED>auto(m_log, "ping kernel.org");
* int status = cmd->exec();
* @endcode
*/
template <output_policy>
class command;
template <>
class command<output_policy::IGNORED> {
public:
explicit command(const logger& logger, string cmd);
command(const command&) = delete;
~command();
command& operator=(const command&) = delete;
int exec(bool wait_for_completion = true);
void terminate();
bool is_running();
int wait();
pid_t get_pid();
int get_exit_status();
protected:
const logger& m_log;
string m_cmd;
pid_t m_forkpid{-1};
int m_forkstatus{-1};
};
template <>
class command<output_policy::REDIRECTED> : private command<output_policy::IGNORED> {
public:
explicit command(const logger& logger, string cmd);
command(const command&) = delete;
~command();
command& operator=(const command&) = delete;
int exec(bool wait_for_completion = true, const vector<pair<string, string>>& env = {});
using command<output_policy::IGNORED>::terminate;
using command<output_policy::IGNORED>::is_running;
using command<output_policy::IGNORED>::wait;
using command<output_policy::IGNORED>::get_pid;
using command<output_policy::IGNORED>::get_exit_status;
void tail(std::function<void(string)> cb);
string readline();
int get_stdout(int c);
int get_stdin(int c);
protected:
int m_stdout[2]{0, 0};
int m_stdin[2]{0, 0};
unique_ptr<fd_stream<std::istream>> m_stdout_reader{nullptr};
};
POLYBAR_NS_END
| true |
fc73a457569d16077d40c136f437f12135e0a525 | C++ | AndrewBowerman/example_projects | /C++/selectionSort.cpp | UTF-8 | 2,695 | 4.1875 | 4 | [] | no_license | /*
selectionSort.cpp
Andrew Bowerman
4 Sept 2018
user picks a number (n)
array of n numbers are generated
array of n numbers are sorted with selection sort
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// clearScreen() shoves all the old stuff off screen to tidy everything up
void clearScreen(){
int numLines, i;
numLines = 50;
for (i=0; i < numLines; i++){
cout << endl;
}
} // end clearScreen()
// printArray(int array, int) iterates through and prints an array
void printArray(int printMe[], int n){
int i; //sentry
for (i=0; i < n; i++) {
//print each element
cout << printMe[i];
// put commas between elements
if (i < (n-1))
cout << ", ";
}
}//end printArray
// selectionSort performs an in-place sort of an array using swap() to swap values
void selectionSort(int sortMe[], int n)
{
int i, j, minimum, temp; //sentry, sentry, min val, holder variable
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
minimum = i;
for (j = i+1; j < n; j++)
if (sortMe[j] < sortMe[minimum])
minimum = j;
// Swap the found minimum element with the first element
temp = sortMe[minimum];
sortMe[minimum] = sortMe[i];
sortMe[i] =temp;
}
}
int main(){
//initialize variables
int i, n, x; // sentry, array size, max array size
x=10; //set max array size
//initialize array for sorting
//collect array size
clearScreen();
cout << "It's time to sort an array." << endl <<
"You decide how big it will be," << endl <<
"then I'll make that many random numbers & sort them." << endl <<
"How many numbers would you like to sort?" << endl <<
"ENTER AN INTEGER (1-10): ";
cin >> n;
while ((n<1) || (n>10)){
cout << endl<< "ENTER AN INTEGER (1-10): ";
cin >> n;
}
//generate random seed
srand(time(NULL));
//create array of n integers
int sortMe[n];
//populate with random values
for (i=0; i < n; i++) {
sortMe[i] = rand() % 501; //put a random value from 0-500 inside the array
}
//display unsorted array
clearScreen();
cout << "Here's your array:" << endl ;
printArray(sortMe, n);
cout << endl <<
"Let's sort it using a SELECTION SORT" << endl <<
"Press ENTER to continue: " << endl;
cin.ignore(); cin.ignore(); // wait for user
//sort array
selectionSort(sortMe, n);
//display sorted array
cout << "All sorted:" << endl;
printArray(sortMe, n);
cout << endl;
} // end main()
| true |
00e2c6e34f8f7b0bd810ed09c957fcf33a54ad73 | C++ | RKrnn/ray_tracing | /texture.h | UTF-8 | 2,886 | 3.1875 | 3 | [] | no_license | #ifndef TEXTURE_H
#define TEXTURE_H
#include "rtweekend.h"
#include <iostream>
class my_texture {
public:
__device__ virtual color value(float u, float v, const vec3& p) const = 0;
};
class solid_color : public my_texture {
public:
__host__ __device__ solid_color() {}
__host__ __device__ solid_color(color c) : color_value(c) {}
__host__ __device__ solid_color(float red, float green, float blue)
: solid_color(color(red,green,blue)) {}
__device__ virtual color value(float u, float v, const vec3& p) const override {
return color_value;
}
private:
color color_value;
};
class checker_texture : public my_texture {
public:
__host__ __device__ checker_texture() {}
__host__ __device__ checker_texture(my_texture* _even, my_texture* _odd)
: even(_even), odd(_odd) {}
__host__ __device__ checker_texture(color c1, color c2)
: even(new solid_color(c1)) , odd(new solid_color(c2)) {}
__device__ virtual color value(float u, float v, const vec3& p) const override {
float sines = sin(10.0f *p.x())*sin(10.0f *p.y())*sin(10.0f *p.z());
if (sines < 0.0f)
return odd->value(u, v, p);
else
return even->value(u, v, p);
}
public:
my_texture* odd;
my_texture* even;
};
class image_texture : public my_texture {
public:
const static int bytes_per_pixel = 3;
__device__ image_texture()
: data(nullptr), width(0), height(0), bytes_per_scanline(0) {}
__device__ image_texture(unsigned char *p, int w, int h) {
data = p;
width = w;
height = h;
bytes_per_scanline = bytes_per_pixel * width;
}
__device__ virtual color value(float u, float v, const vec3& p) const override {
// If we have no texture data, then return solid cyan as a debugging aid.
if (data == nullptr)
return color(0,1,1);
// Clamp input texture coordinates to [0,1] x [1,0]
u = clamp(u, 0.0f, 1.0f);
v = 1.0 - clamp(v, 0.0f, 1.0f); // Flip V to image coordinates
int i = static_cast<int>(u * width);
int j = static_cast<int>(v * height);
// Clamp integer mapping, since actual coordinates should be less than 1.0
if (i >= width) i = width-1;
if (j >= height) j = height-1;
const float color_scale = 1.0f / 255.0f;
unsigned char* pixel = data + j*bytes_per_scanline + i*bytes_per_pixel;
return color(color_scale*pixel[0], color_scale*pixel[1], color_scale*pixel[2]);
}
private:
unsigned char *data;
int width, height;
int bytes_per_scanline;
};
#endif | true |
08f74d5fdaf6bebd6cb8b9378b21259250109203 | C++ | avinashw50w/practice_problems | /ACM ICPC/Practice problems/searching/Hackerrank - Search/count luck.cpp | UTF-8 | 4,040 | 3.5625 | 4 | [] | no_license | /* Hermione Granger is lost in the Forbidden Forest while collecting some herbs for a magical potion. The forest is magical and has only
one exit point, which magically transports her back to the Hogwarts School of Witchcraft and Wizardry.
The forest can be considered as a grid of N×M size. Each cell in the forest is either empty (represented by '.') or has a tree
(represented by 'X'). Hermione can move through empty cells, but not through cells with a tree in it. She can only travel LEFT, RIGHT, UP,
and DOWN. Her position in the forest is indicated by the marker 'M' and the location of the exit point is indicated by '*'. Top-left corner
is indexed (0, 0).
.X.X......X
.X*.X.XXX.X
.XX.X.XM...
......XXXX.
In the above forest, Hermione is located at index (2, 7) and the exit is at (1, 2). Each cell is indexed according to Matrix Convention
She starts her commute back to the exit, and every time she encounters more than one option to move, she waves her wand and the correct path
is illuminated and she proceeds in that way. It is guaranteed that there is only one path to each reachable cell from the starting cell.
Can you tell us if she waved her wand exactly K times or not? Ron will be impressed if she is able to do so.
Input Format
The first line contains an integer T; T test cases follow.
Each test case starts with two space-separated integers, N and M.
The next N lines contain a string, each having a length of M, which represents the forest.
The last line of each single test case contains integer K.
Output Format
For each test case, if she could impress Ron then print Impressed, otherwise print Oops!.
Constraints
1≤T≤10
1≤N,M≤100
0≤K≤10000
There is exactly one 'M' and one '*' in the graph.
Exactly one path exists between 'M' and '*.'
Explanation:
This is a good exercise for the graph theory, as the problem statement states we are dealing with a tree. This can be realized out of the
sentence “It is guaranteed that there is only one path to each reachable cell from the starting cell.” So simply you have to count branches
on the path from “M” to “*” and check if it is equal to K. This can be done by DFS or BFS in linear time.
Counting the branches is the tricky part. One way is to:
As we traverse through the maze, on path from "M" to "*", lets count number of “.” which leaves current node with more depth and then
if that number is more than or equal to 2 then we are at a branch and increase answer by one.
//The key here is to find the ONLY path from M to *, then trace it back, and count the point where Hermione has multiple choices. */
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#define ll long long int
using namespace std;
char grid[101][101];
int n,m,wands;
bool inside(int x,int y){
return (x>=0 && y>=0 && x<n && y<m && grid[x][y]!='X');
}
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
bool dfs(int x,int y,int px=-1,int py=-1){
if(grid[x][y]=='*') return 1;
int f=0 , c=0;
for(int i=0;i<4;i++){
int k=x+dx[i];
int l=y+dy[i];
if(!inside(k,l)) continue;
if(k==px && l==py) continue;
if(dfs(k,l,x,y)) f=1;
c++;
}
if(f && c>1) wands++; // if there is a path from M to * ,and if she encounters more than one option to move to ,then increment
return f; // the no of wand moves by one .
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;cin>>t;
while(t--){
cin>>n>>m;
int mx,my;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
cin>>grid[i][j];
if(grid[i][j]=='M'){
mx=i; my=j;
}
}
int k;
cin>>k;
wands=0;
dfs(mx,my);
if(wands==k) cout<<"Impressed\n";
else cout<<"Oops!\n";
}
return 0;
}
| true |
2926d629015e601d73df22812708f40e8d6e32d5 | C++ | charlottemarriner/Semester-1-GEC | /Week 3/Program9_Share of Savings/Share of Savings/Source.cpp | UTF-8 | 377 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
//Set values for mySavings and yourPercentage
int mySavings = 2000;
float yourPercentage = 50;
//Set value for yourShare by using other variables
int yourShare = (mySavings * (yourPercentage / 100));
//Output yourShare
cout << "Your share: " << yourShare << endl;
//Get user input
cin.get();
return 0;
} | true |
4d6e18f86952685f2577c5f2ad36720a95fd8360 | C++ | denis-gubar/Leetcode | /all/1404. Number of Steps to Reduce a Number in Binary Representation to One.cpp | UTF-8 | 410 | 2.765625 | 3 | [] | no_license | class Solution {
public:
int numSteps(string s) {
int result = 0;
while (s != "1")
{
++result;
if (s.back() == '0')
s.pop_back();
else
{
int i = s.size() - 1;
for (; i >= 0; --i)
if (s[i] == '1')
s[i] = '0';
else
{
s[i] = '1';
break;
}
if (i < 0)
return result + s.size();
}
}
return result;
}
}; | true |
a754ecd1d29443b9d5091c04e8e83602c35924c5 | C++ | paksas/Tamy | /Code/Include/core/RoundBuffer.h | UTF-8 | 2,142 | 2.875 | 3 | [] | no_license | /// @file core/RoundBuffer.h
/// @brief round buffer data structure
#ifndef _ROUND_BUFFER_H
#define _ROUND_BUFFER_H
#include "core\MemoryRouter.h"
#include "core\MemoryAllocator.h"
///////////////////////////////////////////////////////////////////////////////
/**
* This is a structure similar to a queue, but it operates
* on a constant area of memory, and thus is much much faster.
*
* NOTE: This allocator is not thread safe - keep that in mind when you use it.
*/
class RoundBuffer : public MemoryAllocator
{
DECLARE_ALLOCATOR( RoundBuffer, AM_DEFAULT );
private:
static size_t BUFFER_INFO_CHUNK_SIZE;
size_t m_bufSize;
char* m_memory;
volatile size_t m_tail;
volatile size_t m_head;
volatile uint m_allocationsCount;
public:
/**
* Constructor.
*
* @param size buffer size
*/
RoundBuffer( size_t size );
~RoundBuffer();
/**
* Returns the number of allocations made.
*/
inline uint getAllocationsCount() const;
/**
* Returns the number of elements in it ( equal to the number of allocations that have been made ).
*/
inline uint size() const;
/**
* Checks if the buffer has any elements in it.
*/
inline bool empty() const;
/**
* Returns the front element.
*/
template< typename T >
T* front();
/**
* Calculates amount of memory required to allocate an object of the specified type.
*
* @param T
*/
template< typename T >
static uint sizeOf();
// -------------------------------------------------------------------------
// MemoryAllocator implementation
// -------------------------------------------------------------------------
void* alloc( size_t size );
void dealloc( void* ptr );
ulong getMemoryUsed() const;
private:
void getTail( size_t& outOffset, size_t& outSize );
};
///////////////////////////////////////////////////////////////////////////////
#include "core\RoundBuffer.inl"
///////////////////////////////////////////////////////////////////////////////
#endif // _ROUND_BUFFER_H
| true |
a99417b81ad1789df843c6f642266f0754f7e713 | C++ | curet/Learningcpp | /general-practice/temp/max_of_dataset.cpp | UTF-8 | 717 | 3.984375 | 4 | [] | no_license | // Write a C++ program to find the max of an integral data set. The program will ask the user to
// input the number of data values in the set and each value. The program prints on screen a
// pointer that points to the max value.
#include <iostream>
using namespace std;
int main(){
int size = 1;
int A[size];
int *ptrA;
int max = 0;
cout << "Enter the amount of values: ";
cin >> size;
for(int i=0; i<size; i++){
cout << "Enter the values: ";
cin >> A[i];
}
for(int i=0; i<size; i++){
if(max<A[i]){
max = A[i];
}
}
ptrA = &max;
cout << "Max value is " << *ptrA << " in the address " << ptrA;
return 0;
} | true |
6acd743215dc30e27c88d5a42afb44638d612b55 | C++ | ChrisRzech/Snake | /src/TileMap/Map.cpp | UTF-8 | 2,173 | 3.15625 | 3 | [] | no_license | #include "Map.hpp"
#include <cmath>
namespace TM
{
Map::Map(const sf::Vector2u& pixelSize, const sf::Vector2u& tileCount)
: m_pixelSize(pixelSize), m_tileCount(tileCount)
{
updateTilePixelSize();
}
sf::Vector2u Map::getPixelSize() const
{
return m_pixelSize;
}
sf::Vector2u Map::getTileCount() const
{
return m_tileCount;
}
sf::Vector2f Map::getTilePixelSize() const
{
return static_cast<sf::Vector2f>(m_tilePixelSize);
}
void Map::setPixelSize(const sf::Vector2u& a)
{
m_pixelSize = a;
updateTilePixelSize();
}
void Map::setTileCount(const sf::Vector2u& a)
{
m_tileCount = a;
updateTilePixelSize();
}
sf::Vector2f Map::tileToPixel(const Tile& a) const
{
float x = static_cast<float>(a.getPos().x * m_tilePixelSize.x);
float y = static_cast<float>(a.getPos().y * m_tilePixelSize.y);
return sf::Vector2f(x,y);
}
Tile Map::pixelToTile(const sf::Vector2f& a) const
{
int x = static_cast<int>(std::floor(a.x / m_tilePixelSize.x));
int y = static_cast<int>(std::floor(a.y / m_tilePixelSize.y));
return Tile(x, y);
}
/* Bounds check */
bool Map::isInBounds(const Tile& a) const
{
return a.getPos().x >= 0 &&
a.getPos().x < static_cast<int>(m_tileCount.x) &&
a.getPos().y >= 0 &&
a.getPos().y < static_cast<int>(m_tileCount.y);
}
void Map::draw(sf::RenderWindow& window, const sf::Color& fill, const sf::Color& border) const
{
//TODO instead of drawing each tile, draw elongated rectangles as borders
sf::RectangleShape block;
for(unsigned int x = 0; x < m_tileCount.x; x++)
{
for(unsigned int y = 0; y < m_tileCount.y; y++)
{
block.setPosition(tileToPixel(Tile(x, y)));
block.setSize(static_cast<sf::Vector2f>(m_tilePixelSize));
block.setFillColor(fill);
block.setOutlineColor(border);
block.setOutlineThickness(0.5);
window.draw(block);
}
}
}
void Map::updateTilePixelSize()
{
m_tilePixelSize.x = m_pixelSize.x / m_tileCount.x;
m_tilePixelSize.y = m_pixelSize.y / m_tileCount.y;
}
}
| true |
ad9be34eb2f6f35991345d14cf9d8643e6e423c7 | C++ | Reactor11/Data-Structures-Practice | /Array/array_index_place.cpp | UTF-8 | 715 | 3.421875 | 3 | [
"MIT"
] | permissive | // Place the elements of array according to their index. if not present place -1.
#include<bits/stdc++.h>
using namespace std;
bool lfind(int a[],int val,int n){
for(int i=0;i<n;i++){
if(a[i]==val) return true;
}
return false;
}
int main(){
int n,k;
cout<<"N : ";
cin>>n;
int arr[n],a[n];
for(int i=0;i<n;i++){
cin>>arr[i];
a[i] = arr[i];
}
// Approach 1:
int t[n] = {0},temp[n];
for(int i=0;i<n;i++){
t[arr[i]] = 1;
}
for(int i=0;i<n;i++){
if(t[i] == 1) arr[i] = i;
else arr[i] = -1;
}
// Approach 2:
for(int i=0;i<n;i++){
if(lfind(a,i,n)) temp[i] = i;
else temp[i] = -1;
}
for(int i=0;i<n;i++){
cout<<"arr : "<<arr[i]<<" ";
// cout<<"temp : "<<temp[i]<<" ";
}
}
| true |
1a5f6ab892d5f2984ffd6c99ceaecf39aa1b9374 | C++ | xiaohunziaaaa/CUDAExercise | /MultiThreading/MutexLock.h | UTF-8 | 465 | 2.921875 | 3 | [] | no_license | #ifndef __MUTEXLOCK_H__
#define __MUTEXLOCK_H__
#include <pthread.h>
class MutexLock{
private:
pthread_mutex_t mutex;
public:
MutexLock(){
pthread_mutex_init(&mutex, NULL);
}
~MutexLock(){
pthread_mutex_destroy(&mutex);
}
void lock(){
pthread_mutex_lock(&mutex);
}
void unlock(){
pthread_mutex_unlock(&mutex);
}
pthread_mutex_t* getmutex(){
return &mutex;
}
};
#endif | true |
337dd0917ca722c09311139f6d191b955b6c1540 | C++ | korca0220/Algorithm_study | /ACMICPC/SWtest/Problem/Review/new_hanoi.cpp | UTF-8 | 1,338 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <array>
#include <queue>
#include <map>
#include <tuple>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int main(){
array<string, 3> in;
for(int i=0; i<3; i++){
int cnt;
cin >> cnt;
if(cnt > 0){
cin >> in[i];
}else in[i] = "";
}
int cnt[] = {0,0,0};
for(int i=0; i<3; i++){
for(int j=0; j<in[i].length(); j++){
cnt[in[i][j] - 'A'] += 1;
}
}
map<array<string,3>, int> dist;
queue<array<string,3>> q;
q.push(in);
dist[in] = 0;
while(!q.empty()){
auto now = q.front();
q.pop();
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
if(i==j) continue;
if(now[i].length() == 0) continue;
array<string,3> next(now);
next[j].push_back(next[i].back());
next[i].pop_back();
if(dist.count(next) == 0){
q.push(next);
dist[next] = dist[now]+1;
}
}
}
}
array<string,3> ans; // correct
for(int i=0; i<3; i++){
for(int j=0; j<cnt[i]; j++){
ans[i] += (char)('A'+i);
}
}
cout << dist[ans];
return 0;
} | true |
51fa1b33a23b3da3d9bdfdeddb98b3565aebeee1 | C++ | SerRataGo/CompetitiveCode | /CodeChef_problems/ATTND/solution.cpp | UTF-8 | 1,585 | 3.328125 | 3 | [
"MIT"
] | permissive | // The logic is to check the first name of all students and maintain records of those students who have common first name.
// By maintaining the record, we'll be able to distinguish the students whose first & last names need to be called out.
#include<bits/stdc++.h> // includes every standard library
#define lli long long int
using namespace std;
int main() {
ios_base::sync_with_stdio(false); // Speeds up the execution time
cin.tie(NULL);
lli t; // number of test cases
cin >> t;
while(t--) {
lli n;
cin >> n;
// save first name and last name in different arrays
vector<string> first(n);
vector<string> last(n);
for(lli i = 0; i < n; i++) {
cin >> first[i] >> last[i];
}
vector<bool> callOnlyFirstName(n, true);
// check if first name of one student matches with any other student's first name.
for(lli i = 0; i < n - 1; i++) {
if(callOnlyFirstName[i] != false) {
for(lli j = i + 1; j < n; j++) {
if(first[i] == first[j]) {
callOnlyFirstName[i] = false;
callOnlyFirstName[j] = false;
}
}
}
}
// Output first & lastname for students having same first name and print only first name for all others.
for(lli i = 0; i < n; i++){
if(callOnlyFirstName[i]) {
cout << first[i] << endl;
} else {
cout << first[i] << " " << last[i] << endl;
}
}
}
return 0;
} | true |
0e3b1aa8fa2921e83f41738240a19d9eda6b79fc | C++ | haneulshin1030/USACO | /List of Topics/(2) Data Structures/Storage/(6) Wavelet Tree.cpp | UTF-8 | 1,894 | 3.03125 | 3 | [] | no_license | /**
* Source: https://ideone.com/Tkters
* Unused
*/
int MAX = 1000000;
int a[300000];
struct wavelet {
int lo, hi;
wavelet *c[2];
vi b;
wavelet(int *from, int *to, int x, int y) {
lo = x, hi = y;
if (lo == hi || from >= to) return;
int mid = (lo+hi)/2;
auto f = [mid](int x) { return x <= mid; };
b.pb(0); for (auto it = from; it != to; it++) b.pb(b.back()+f(*it));
auto pivot = stable_partition(from,to,f);
c[0] = new wavelet(from,pivot,lo,mid);
c[1] = new wavelet(pivot,to,mid+1,hi);
}
int kth(int l, int r, int k) { // kth number in [l,r]
if (l > r) return 0;
if (lo == hi) return lo;
int inLeft = b[r]-b[l-1];
int lb = b[l-1], rb = b[r];
if (k <= inLeft) return c[0]->kth(lb+1,rb,k);
return c[1]->kth(l-lb,r-rb,k-inLeft);
}
int LTE(int l, int r, int k) { // less than or equal to k
if(l > r || k < lo) return 0;
if(hi <= k) return r-l+1;
int lb = b[l-1], rb = b[r];
return c[0]->LTE(lb+1, rb, k)+c[1]->LTE(l-lb, r-rb, k);
}
int count(int l, int r, int k) { // equal to k
if(l > r || k < lo || k > hi) return 0;
if(lo == hi) return r - l + 1;
int lb = b[l-1], rb = b[r], mid = (lo+hi)/2;
if(k <= mid) return c[0]->count(lb+1, rb, k);
return c[1]->count(l-lb, r-rb, k);
}
};
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
int i,n,k,j,q,l,r;
cin >> n;
F0R(i,n) cin >> a[i+1];
wavelet T(a+1, a+n+1, 1, MAX);
cin >> q;
while (q--){
int x;
cin >> x >> l >> r >> k;
if(x == 0){
//kth smallest
cout << "Kth smallest: ";
cout << T.kth(l, r, k) << endl;
}
if(x == 1){
//less than or equal to K
cout << "LTE: ";
cout << T.LTE(l, r, k) << endl;
}
if(x == 2){
//count occurence of K in [l, r]
cout << "Occurence of K: ";
cout << T.count(l, r, k) << endl;
}
}
} | true |
69d0998238b9f573812365797e17aa932cbbdd74 | C++ | autious/kravall | /include/gfx/GFXInterface.hpp | UTF-8 | 16,167 | 2.5625 | 3 | [] | no_license | #ifndef GFXINTERFACE_INCLUDE_HPP
#define GFXINTERFACE_INCLUDE_HPP
#ifdef _WIN32
#ifdef GFX_DLL_EXPORT
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
#else
#define DLL_API
#endif
#include <glm/glm.hpp>
#include <GL/glew.h>
#include <GFXDefines.hpp>
typedef glm::vec2 GFXVec2;
typedef glm::vec3 GFXVec3;
typedef glm::vec4 GFXVec4;
typedef glm::mat4x4 GFXMat4x4;
typedef GFXVec4 GFXColor;
#include <vector>
#include <iostream>
#include <gfx/Vertex.hpp>
#include <gfx/BitmaskDefinitions.hpp>
#include <gfx/FontData.hpp>
namespace GFX
{
class Particle;
}
namespace GFX
{
DLL_API void test(std::vector<float>* t);
/*!
Initializes the graphics engine on the currently bound context.
\return Returns #GFX_SUCCESS if successful, else returns #GFX_FAIL
*/
DLL_API int Init(int windowWidth, int windowHeight);
/*!
Executes all draw calls made to the graphics engine and
renders it to the screen.
*/
DLL_API void Render(const double& delta);
/*!
Resizes the graphics to render on with specified dimensions.
\param width Width to use for rendering
\param height Height to use for rendering
*/
DLL_API void Resize(int width, int height);
/*!
Sets the view matrix used by the main camera.
\param matrix Pointer to a 4x4 matrix
*/
DLL_API void SetViewMatrix(GFXMat4x4 matrix);
/*!
Sets the projection matrix used by the main camera.
\param matrix Pointer to a 4x4 matrix
*/
DLL_API void SetProjectionMatrix(GFXMat4x4 matrix, float nearZ, float farZ);
/*!
Sets the view matrix used by the overlay cam
\param matrix Pointer to a 4x4 matrix
*/
DLL_API void SetOverlayViewMatrix(GFXMat4x4 matrix);
/*!
Sets the projection matrix used by the overlay cam
\param matrix Pointer to a 4x4 matrix
*/
DLL_API void SetOverlayProjectionMatrix(GFXMat4x4 matrix);
/*!
Issues a draw command to the graphics engine.
\param bitmask The bitmask containing the type of draw call to be queued.
\param data A pointer to the data used for rendering
*/
DLL_API void Draw(GFXBitmask bitmask, void* data);
/*!
Sets the values needed to draw the selection box.
\param posDim This is a vec4 containing position and dimension (x, y, w, h)
\param color The color of the selectionbox
*/
DLL_API void DrawSelectionbox(const glm::vec4& posDim, const GFXColor& color );
/*!
Draws a rectangle on the screen.
\param position The screen space position for the top left corner
\param dimensions Rectangle dimensions
\param solid If true, the rectangle will be filled, else only outlines will be shown
\param color Color of the rectangle
*/
DLL_API void DrawFilledRect(GFXVec2 position, GFXVec2 dimensions, GFXColor color);
/*!
Issues a draw text command to the graphics engine.
\param position Position of the starting letter
\param size Vertical size of each letter
\param color The color of the text
\param text The text to be rendered
*/
DLL_API void RenderText(GFX::FontData* fontData, GFXVec2 position, float size, GFXVec4 color, const char* text);
/*!
Issues a draw text command to the graphics engine.
\param rectangle Rectangle (x, y, w, h) in which to draw the text
\param offset Scroll offset in pixels, if offset is zero, the text is scrolled all the way to the top
\param size Vertical size of each letter
\param color The color of the text
\param text The text to be rendered
*/
DLL_API void RenderTextbox(GFX::FontData* fontData, GFXVec4 rectangle, float offset, float size, GFXVec4 color, const char* text);
/*!
Returns the actual width and height of a textbox of specified size
\param width The width of the textbox after which text is wrapped
\param size Vertical size of each letter
\param text The text to use
*/
DLL_API void GetActualTextboxSize(GFX::FontData* fontData, float width, float size, const char* text, float& out_actualWidth, float& out_actualHeight);
/*!
Shows the console window
*/
DLL_API void ShowConsole();
/*!
Hides the console window
*/
DLL_API void HideConsole();
/*!
Toggles the console window
*/
DLL_API void ToggleConsole();
/*!
Is this magic?
\param renderSplash If true, the splash screen will render at start
*/
DLL_API void RenderSplash(bool renderSplash);
/*!
Deletes all of the dynamically allocated memory in GFX
*/
DLL_API void DeleteGFX();
/*!
\return Returns the screen width
*/
DLL_API int GetScreenWidth();
/*!
\return Returns the screen height
*/
DLL_API int GetScreenHeight();
namespace Content
{
/*!
Loads a 2D RGBA texture onto the GPU
\param out_id Reference to the id created for the texture
\param data Texture data
\param width Width of the texture
\param height Height of the texture
*/
DLL_API void LoadTexture2DFromMemory(unsigned int& out_id, unsigned char* data, int width, int height, bool decal);
/*!
Deletes a texture from the GPU
\param textureHandle The handle of the texture to be deleted
*/
DLL_API void DeleteTexture(unsigned int id);
/*!
Loads a mesh to the GPU
\param meshID Reference to the id created for the mesh
\param sizeVerts Number of vertices in the mesh
\param sizeIndices Number of indices in the mesh
\param verts Array of vertices to use for the mesh
\param indices Array of indices to use for the mesh
*/
DLL_API void LoadMesh(unsigned int& meshID, int& sizeVerts, int& sizeIndices, GFX::Vertex* verts, int* indices);
/*!
Creates a skeleton on the GPU
\param out_skeletonID Reference returning the id created for the skeleton
\return Returns #GFX_FAIL if unable to create skeleton, else returns #GFX_SUCCESS
*/
DLL_API int CreateSkeleton(int& out_skeletonID);
/*!
Deletes a skeleton, removing its animations
\param skeletonID The id of the skeleton to delete
\return Returns #GFX_FAIL if unable to remove skeleton, else returns #GFX_SUCCESS
*/
DLL_API int DeleteSkeleton(const int& skeletonID);
/*!
Binds a skeleton to a mesh
\param meshID The mesh to bind the skeleton to
\param skeletonID The id of the skeleton which to bind to the mesh
\return Returns #GFX_FAIL if unable bind skeleton to mesh, else returns #GFX_SUCCESS
*/
DLL_API int BindSkeletonToMesh(const unsigned int& meshID, const int& skeletonID);
/*!
Gets the skeleton ID linked to the mesh
*/
DLL_API int GetSkeletonID(const unsigned int& meshID);
/*!
Adds an animation to a skeleton. The data must contain the same number of bones for all frames
\param skeletonID Reference id of the skeleton to bind the animation to
\param frames Array of bone matrices sorted by frame
\param numFrames Number of bone matrices in the array
\param numBonesPerFrame Number of bone matrices per frame
\return Returns the animation ID if successful, else returns #GFX_INVALID_ANIMATION or #GFX_INVALID_SKELETON
*/
DLL_API int AddAnimationToSkeleton(const int& skeletonID, GFXMat4x4* frames, const unsigned int& numFrames, const unsigned int& numBonesPerFrame);
/*!
Gets the info for a particular animation.
\param skeletonID The id of the skeleton
\param animationID The id of the animation
\param out_frameCount The number of frames in this animation
\return Returns #GFX_SUCCESS if successful, else returns #GFX_INVALID_ANIMATION or #GFX_INVALID_SKELETON
*/
DLL_API int GetAnimationInfo(const int& skeletonID, const int& animationID, unsigned int& out_frameCount, unsigned int& out_bonesPerFrame, unsigned int& out_animationOffset);
/*!
Deletes a mesh
\param meshID The id of the mesh to delete
*/
DLL_API void DeleteMesh(unsigned int& meshID);
/*!
Creates an empty material
\param out_id Reference to set material id
*/
DLL_API void CreateMaterial(unsigned long long int& out_id);
/*!
Deletes a material
\param id The id of the material to remove
*/
DLL_API void DeleteMaterial(const unsigned long long int& id);
/*!
Adds a texture to a material
\param materialID Id to material to attach texture to
\param textureID Id of texture to attach
\return Returns #GFX_SUCCESS, #GFX_INVALID_MATERIAL
*/
DLL_API int AddTextureToMaterial(const unsigned long long int& materialID, const unsigned long long int& textureID);
/*!
Adds a texture to a material
\param materialID Id to material where the texture is attached
\param textureID Id of texture to detach
*/
DLL_API void RemoveTextureFromMaterial(const unsigned long long int& materialID, const unsigned long long int& textureID);
/*!
Gets the shader id of the shader specified by the null terminated string.
\param shaderId Reference to set shader id.
\param shaderName The identifying string of the shader.
\return Returns #GFX_SUCCESS or #GFX_INVALID_SHADER
*/
DLL_API int GetShaderId(unsigned int& shaderId, const char* shaderName);
/*!
Sets a shader for a material
\param materialID Id to material to attach shader to
\param textureID Id of shader to attach
\return Returns #GFX_SUCCESS, #GFX_INVALID_MATERIAL
*/
DLL_API int AttachShaderToMaterial(const unsigned long long int& materialID, const unsigned int& shaderID);
/*!
Creates a buffer that stores particles.
\param bufferId Out parameter that will be assigned the id of the particle buffer.
\param particleCount The number of particles that the buffer will hold.
*/
DLL_API void CreateParticleBuffer(unsigned int& bufferId, unsigned int particleCount);
/*!
Deletes the specified particle buffer.
\param bufferId The Id of the particle buffer to be deleted.
*/
DLL_API void DeleteParticleBuffer(unsigned int bufferId);
/*!
Transfers data over to the given particle buffer.
\param bufferId The buffer id to assign the data to.
\param particleData The data to be set.
\param particleCount The number of particles the data contains.
*/
DLL_API void BufferParticleData(unsigned int bufferId, GFX::Particle* const data);
DLL_API void ReloadLUT();
}
namespace Debug
{
/*!
Sets whether to draw debug or not.
\param enable If true, enables debug drawing.
*/
DLL_API void SetEnableDebug(bool enable);
/*!
Draws a point on the screen.
\param point The screen space position where to draw the point.
\param color The color of the point
*/
DLL_API void DrawPoint(GFXVec2 point, GFXColor color);
/*!
Draws a point on the screen.
\param point The screen space position where to draw the point.
\param color The color of the point
\param size Size of the point
*/
DLL_API void DrawPoint(GFXVec2 point, GFXColor color, float size);
/*!
Draws a line on the screen.
\param p1 World space position of the starting point of the line
\param p2 World space position of the end point of the line
\param color Color of the line
\param useDepth If true, the depth buffer is used to occlude if behind an object, else draws on top of existing geometry regardless of depth
*/
DLL_API void DrawLine(GFXVec3 p1, GFXVec3 p2, GFXColor color, bool useDepth);
/*!
Draws a line on the screen.
\param p1 The world space position of the starting point of the line
\param p2 The world space position of the end point of the line
\param color Color of the line
\param thickness Thickness of the line
\param useDepth If true, the depth buffer is used to occlude if behind an object, else draws on top of existing geometry regardless of depth
*/
DLL_API void DrawLine(GFXVec3 p1, GFXVec3 p2, GFXColor color, float thickness, bool useDepth);
/*!
Draws a line on the screen.
\param p1 Screen space position of the starting point of the line
\param p2 Screen space position of the end point of the line
\param color Color of the line
*/
DLL_API void DrawLine(GFXVec2 p1, GFXVec2 p2, GFXColor color);
/*!
Draws a line on the screen.
\param p1 The screen space position of the starting point of the line
\param p2 The screen space position of the end point of the line
\param color Color of the line
\param thickness Thickness of the line
*/
DLL_API void DrawLine(GFXVec2 p1, GFXVec2 p2, GFXColor color, float thickness);
/*!
Draws a rectangle on the screen.
\param position The screen space position for the top left corner
\param dimensions Rectangle dimensions
\param solid If true, the rectangle will be filled, else only outlines will be shown
\param color Color of the rectangle
*/
DLL_API void DrawRectangle(GFXVec2 position, GFXVec2 dimensions, bool solid, GFXColor color);
/*!
Draws an axis-aligned box on the screen.
\param position The world space position for the center of the box
\param dimensions Box dimensions
\param solid If true, the box will be filled, else only outlines will be shown
\param color Color of the rectangle
\param useDepth If true, the depth buffer is used to occlude if behind an object, else draws on top of existing geometry regardless of depth
*/
DLL_API void DrawBox(GFXVec3 position, GFXVec3 dimensions, bool solid, GFXColor color, bool useDepth);
/*!
Draws a representation of a sphere on the screen.
\param position World space position for the center of the sphere
\param radius Sphere radius
\param color Color of the sphere
\param useDepth If true, the depth buffer is used to occlude if behind an object, else draws on top of existing geometry regardless of depth
*/
DLL_API void DrawSphere(GFXVec3 position, float radius, GFXColor color, bool useDepth);
/*!
Draws a screen space circle on the screen.
\param position Screen space position for the center of the circle
\param radius Circle radius
\param lineWidth Width of the outline line, the circle will be filled if this value is 0
\param color Color of the circle
*/
DLL_API void DrawCircle(GFXVec2 position, float radius, unsigned int lineWidth, GFXColor color);
/*!
Draws a frustum
\param cameraMatrix The matrix representing the frustum to draw
\param color The color to draw the frustum
\param useDepth If true, the depth buffer is used to occlude if behind an object, else draws on top of existing geometry regardless of depth
*/
DLL_API void DrawFrustum(GFXMat4x4 cameraMatrix, GFXColor color, bool useDepth);
/*!
Sets the font used for rendering the time statistics.
\param font Poitner to GFX::FontData struct used for rendering.
*/
DLL_API void SetStatisticsFont(GFX::FontData* font);
/*!
Enables or disables display of gfx system info
\param enabled If true, toggles graphics system info to show on the screen, false disables it
*/
DLL_API void DisplaySystemInfo(bool enabled);
/*!
Enables or disables display of frame buffers as miniatures
\param which Which rendertarget to show -1: disabled, 0: miniatures, 1-4: displays target 1-4 as full screen
*/
DLL_API void DisplayFBO(int which);
} // namespace Debug
namespace Settings
{
/*!
Sets gamma
\param gamma
*/
DLL_API void SetGamma(float gamma);
/*!
Gets gamma
*/
DLL_API float GetGamma();
/*!
Sets a setting to the specified value
\return Returns either GFX_SUCCESS or GFX_FAIL
*/
DLL_API int SetConfiguration(const int setting, const int value);
/*!
Gets the value of a setting
\return Returns either GFX_SUCCESS or GFX_FAIL
*/
DLL_API int GetConfiguration(const int setting, int& out_value);
/*!
Gets the animation play framerate.
\return Returns animation play framerate
*/
DLL_API unsigned int GetAnimationFramerate();
/*!
Sets the animation play framerate.
\param framerate The target framerate for animations (clamped between 12 and 48 fps)
*/
DLL_API void SetAnimationFramerate(unsigned int framerate);
} // namespace Settings
namespace ColorSettings
{
/*!
Sets the white point which means a pixel should be full-brighted
\param whitePoint
*/
DLL_API void SetWhitePoint(GFXVec3 whitePoint);
/*!
Sets exposure
\param exposure
*/
DLL_API void SetExposure(float exposure);
DLL_API void SetLUT(const char* LUT);
}
} // namespace GFX
#endif //GFXINTERFACE_INCLUDE_HPP
| true |
34d13394113c8efa47c3cb3b5af4ced159c83f48 | C++ | blacksea3/Cpp-STL-test | /other/CppAlgs/Graph/Prim.cpp | GB18030 | 1,856 | 3.1875 | 3 | [] | no_license | #include "Prim.hpp"
/*
* PrimС
* ߣÿһбʾһڵߣڲÿһpairfirstʾһڵ㣬secondʾģǸ
* С
* ⲿӦȷedgesijӼܹγͨͼ, ȷڵedges.size()ڵIDϷ
*/
int PrimInterface(vector<vector<pair<int, unsigned int>>> edges)
{
//ʵ϶ͷǰ{·Ӧڵ}pairʹĬgreater pairʽ
priority_queue<pair<unsigned int, pair<int, int>>, vector<pair<unsigned int, pair<int, int>>>,
greater<pair<unsigned int, pair<int, int>>>> q; //ŵǰ룬ڵŶ{start, end}pair
//ѡһʼ, Ϊ0, ʼȶ
for (auto& it:edges[0])
{
q.push({ it.second, {0, it.first} });
}
unordered_set<int> us;
us.insert(0);
int res = 0;
while (!q.empty())
{
pair<unsigned int, pair<int, int>> tmp = q.top(); //ȡǰдʹõ·Ľڵ
q.pop();
if (us.find(tmp.second.first) == us.end()) //ڿԼtmp.second.firstڵ
{
int newadd = tmp.second.first;
us.insert(newadd);
res += tmp.first;
for (auto& it : edges[newadd])
{
q.push({ it.second, {newadd, it.first} });
}
}
else if (us.find(tmp.second.second) == us.end())
{
int newadd = tmp.second.second;
us.insert(newadd);
res += tmp.first;
for (auto& it : edges[newadd])
{
q.push({ it.second, {newadd, it.first} });
}
}
}
return res;
}
void primTest()
{
const unsigned int INF = 0x1f1f1f1f;
vector<vector<pair<int, unsigned int>>> edges = {
{ {1,4},{4,1},{5,2}},
{ {0,4},{2,8},{3,6},{4,5} },
{ {1,8},{3,1} },
{{1,6},{2,1},{4,9}},
{{0,1},{1,5},{3,9},{5,3} },
{{0,2},{4,3}}
};
int res = PrimInterface(edges);
int i = 1;
}
| true |
149f9c400835c681bdde6771b1cf9e01eb18e476 | C++ | randym32/vector-cloud | /internal/log/util/logging/logging/printfLoggerProvider.h | UTF-8 | 1,149 | 2.625 | 3 | [
"MIT"
] | permissive | /**
* File: printfLoggerProvider
*
* Author: damjan stulic
* Created: 4/25/15
*
* Description:
*
* Copyright: Anki, inc. 2015
*
*/
#ifndef __Util_Logging_PrintfLoggerProvider_H_
#define __Util_Logging_PrintfLoggerProvider_H_
#include "util/logging/iFormattedLoggerProvider.h"
namespace Anki {
namespace Util {
class PrintfLoggerProvider : public IFormattedLoggerProvider {
public:
PrintfLoggerProvider();
PrintfLoggerProvider(ILoggerProvider::LogLevel minToStderrLogLevel,
bool colorizeStderrOutput = false);
void Log(ILoggerProvider::LogLevel logLevel, const std::string& message) override;
// Set the minimum level required to print to stderr.
// Everything above prints to stdout.
void SetMinToStderrLevel(int level) { _minToStderrLevel = level; };
void SetColorizeStderrOutput(bool b = true) { _colorizeStderrOutput = b; };
void Flush() override;
private:
int _minToStderrLevel;
// Use ANSI escape color codes to colorize printf output to stderr
bool _colorizeStderrOutput = false;
};
} // end namespace Util
} // end namespace Anki
#endif //__Util_Logging_PrintfLoggerProvider_H_
| true |
5b34650d6326944c639ee2adcff36099a4ed8e43 | C++ | PetyrEftimov/GitHubPetyrEftimov | /Nasledqvane_Car/Car.cpp | UTF-8 | 640 | 2.859375 | 3 | [] | no_license | //
// Car.cpp
// Nasledqvane_Car
//
// Created by Pepi on 4/26/17.
// Copyright © 2017 Pepi. All rights reserved.
//
#include "Car.hpp"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
Car::Car(){}
Car::Car(string brand , string model){
this -> brand = brand;
this -> model = model;
}
void Car::setBrand(string){
this -> brand = brand;
}
void Car::setModel(string){
this -> model = model;
}
string Car::getBrand(){
return this -> brand;
}
string Car::getModel(){
return this -> model;
}
void Car::printInfo(){
cout << getBrand()<<endl;
cout << getModel()<<endl;
}
| true |
990e572a58f9e3b02e21f4d9dc68a61aa0abe661 | C++ | qq464418017/bintalk | /compiler/Context.cpp | GB18030 | 1,172 | 2.515625 | 3 | [] | no_license | #include "Context.h"
#include "Options.h"
#include <stdio.h>
Context gContext;
Context::Context():
lineno_(1)
{}
Context::~Context()
{
// ɾеdefinitionʵ.
for(size_t i = 0; i < definitions_.size(); i++)
delete definitions_[i];
}
Definition* Context::findDefinition(const std::string& name)
{
for(size_t i = 0; i < definitions_.size(); i++)
{
if(definitions_[i]->name_ == name)
return definitions_[i];
}
return NULL;
}
int yyparse();
extern FILE *yyin;
bool Context::build()
{
// Դļ.
yyin = fopen(gOptions.input_.c_str(), "r");
if(yyin == NULL)
{
fprintf(stderr, "failed to open file \"%s\".", gOptions.input_.c_str());
return false;
}
// õǰļ
curFilename_ = gOptions.inputFN_;
// ʼļ.
if(yyparse())
{
fclose(yyin);
return false;
}
fclose(yyin);
return true;
}
#include <cstdio>
#include <cstdarg>
#define GET_VARARGS(str, len, fmt) char str[len];va_list argptr; va_start(argptr, fmt);vsprintf(str, fmt, argptr);va_end(argptr);
void Context::error(const char* e, ...)
{
GET_VARARGS(str, 1024, e);
fprintf(stderr, "%s(%d):%s\n", curFilename_.c_str(), lineno_, str);
} | true |
9fe7838c433e25ae1923eb63d8c610cc0facfe85 | C++ | sergiyvan/robotic_vl | /src/tools/kinematicEngine/kinematicNode.h | UTF-8 | 6,301 | 2.59375 | 3 | [] | no_license | /*
* kinematicNode.h
*
* Created on: 12.02.2014
* Author: lutz
*/
#ifndef KINEMATICNODE_H_
#define KINEMATICNODE_H_
#include "kinematicVisual.h"
#include "kinematicMass.h"
#include "platform/hardware/robot/motorIDs.h"
#include "utils/units.h"
#include "utils/math/Math.h"
#include <string>
#include "physics/physicsEnvironment.h"
#include <ode/ode.h>
#include <armadillo>
/**
* this represents something movable
*/
class KinematicNode {
public:
KinematicNode();
KinematicNode(MotorID id,
KinematicNode *parent,
std::string name,
double minValue,
double maxValue,
double preferredValue,
Millimeter translationX,
Millimeter translationY,
Millimeter translationZ,
Degree alphaX,
Degree alphaY,
Degree alphaZ);
virtual ~KinematicNode();
/// create a copy of this node without parent or children
virtual KinematicNode* cloneDetached() const = 0;
/// define whether this node is a servo
virtual bool isServo() const {
return false;
}
virtual void setValue(double newValue) = 0;
virtual double getValue() const = 0;
virtual void setValueDerivative(double newValueDerivative)
{
m_valueDerivative = newValueDerivative;
}
virtual double getValueDerivative() const
{
return m_valueDerivative;
}
/**
* returns the partial derivative of the endeffector of this joint.
* @param an effector in this joint's coordinate system
* @return partial derivative (locally linearized) of the endeffectors movement
*/
virtual arma::colvec3 getPartialDerivativeOfLocationToEffector(arma::colvec3 effector) const = 0;
virtual arma::colvec3 getPartialDerivativeOfOrientationToEffector(arma::colvec3 effector) const = 0;
/**
* what is the linear velocity of the point position in this nodes coordinates given the nodes speed (value derivative)
* @param position
* @return
*/
virtual arma::colvec4 getLinearSpeedOfPoint(arma::colvec3 position) const = 0;
virtual double clipValue(double newValue) const
{
return Math::limited(newValue, m_minValue, m_maxValue);
}
/**
* adds a child to this node (does NOT take ownership of pointer)
* @param child
*/
inline void addChild(KinematicNode *child)
{
m_children.push_back(child);
}
/**
* adds a visual to this node and takes ownership of pointer
* @param visual the visual to add
*/
inline void addVisual(KinematicVisual *visual)
{
m_visuals.push_back(visual);
}
/**
* returns the affine transformation to a neighbor node (parent or child)
* @param relative parent or child of this node
* @return affine transformation
*/
arma::mat44 getMatrixToRelative(MotorID relative) const;
arma::mat44 getInvMatrixToRelative(MotorID relative) const;
inline arma::mat44 getForwardMatrix() const
{
return forwardMatrix;
}
inline arma::mat44 getBackwardMatrix() const
{
return backwardMatrix;
}
inline MotorID getID() const
{
return id;
}
/**
* should only be called at construction time an never touched again since this node does not remove itself from its parent
* @param parent
*/
inline void setParent(KinematicNode *parent)
{
m_parent = parent;
if (parent != nullptr)
parent->addChild(this);
}
inline const KinematicNode *getParent() const
{
return m_parent;
}
inline std::vector<KinematicNode*> &getChildren()
{
return m_children;
}
// FIXME: this is not really const, if the vector contains non-const pointers
inline const std::vector<KinematicNode*> &getChildren() const
{
return m_children;
}
// FIXME: this is not really const, if the vector contains non-const pointers
inline const std::vector<KinematicVisual*> &getVisuals() const
{
return m_visuals;
}
inline const std::string &getName() const
{
return m_name;
}
inline bool hasMass() const
{
return m_hasMass;
}
inline const std::vector<KinematicMass> &getMasses() const
{
return m_masses;
}
inline std::vector<KinematicMass> &getMasses()
{
return m_masses;
}
/**
* can this node move?
* @return true iff this node can move
*/
virtual bool isFixedNode() const
{
return true;
}
virtual void addMass(double massGrams, arma::colvec3 position, std::string name)
{
if (0 != massGrams)
{
m_masses.push_back(KinematicMass(position, massGrams, name));
m_hasMass = true;
/* calculate new equivalent mass */
m_equivalentMass = KinematicMass();
for (KinematicMass const & mass : m_masses)
{
m_equivalentMass = m_equivalentMass.mean(mass);
}
}
}
virtual KinematicMass getEquivalentMass() const
{
return m_equivalentMass;
}
virtual void setAdditionalExtrinsicRotation(arma::mat33 _rotMat);
virtual dBodyID attachToODE(PhysicsEnvironment *environment, dSpaceID visualSpaceID, dSpaceID collisionSpaceID, arma::mat44 coordinateFrame) = 0;
virtual dBodyID getODEBody() const {
return m_odeBody;
}
virtual dMass getODEMass(arma::mat44 coordinateFrame);
/**
* a dummy node must not possess a body and thus a mass.
* This function shall be overridden by any dummy node to pass its attached masses to its parent
* @param coordinateFrame parents coordinate frame
* @return
*/
virtual dMass getODEMassToAttachToParent(arma::mat44 coordinateFrame) {
dMass dummyMass;
dMassSetZero(&dummyMass);
return dummyMass;
}
virtual void attatchODEVisuals(arma::mat44 coordinateFrame, dBodyID body, dSpaceID space);
/**
* let the node apply a torque in the ode world
* @param torque
*/
virtual void setTorqueForODE(double torque) = 0;
protected:
MotorID id;
KinematicNode *m_parent;
std::string m_name;
double m_value;
double m_valueDerivative;
double m_minValue;
double m_maxValue;
double m_preferredValue;
Millimeter m_translationX;
Millimeter m_translationY;
Millimeter m_translationZ;
Degree m_alphaX;
Degree m_alphaY;
Degree m_alphaZ;
bool m_hasMass = false;
std::vector<KinematicNode*> m_children;
std::vector<KinematicVisual*> m_visuals;
arma::mat44 forwardMatrix, backwardMatrix, preRotationMatrix;
std::vector<KinematicMass> m_masses;
KinematicMass m_equivalentMass;
arma::mat44 m_additionalExtrinsicRotation;
dBodyID m_odeBody;
arma::mat44 m_odeNodeBodyOffset; // the offset you have to add to the nodes coordinate frame to get the center of the body
};
#endif /* KINEMATICNODE_H_ */
| true |
5549fa7b20f9b2e32c22c892f32d3cb80b97decb | C++ | santidv6/kairos-device-climatizer | /src/main/util.cpp | UTF-8 | 774 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "util.hpp"
enum sources { EEPROM, DEFAULt };
const int source = DEFAULt;
/**
* Carga la configuración general.
* @return configuración cargada
*/
Config LoadConfig() {
struct Config config;
switch (source) {
case EEPROM:
config = LoadEEPROMConfig();
break;
case DEFAULt:
config = LoadDEFAULtConfig();
break;
}
return config;
}
/**
* Carga la configuración general de la EEPROM
* @return configuración cargada.
*/
Config LoadEEPROMConfig() {
struct Config config;
// TODO
return config;
}
/**
* Carga la configuración general por defecto
* @return configuración cargada.
*/
Config LoadDEFAULtConfig() {
struct Config config;
config.hour = 12;
config.minute = 0;
config.interval = 8*60;
return config;
}
| true |
526858f2bf4db8498435da8b738c13717023a018 | C++ | kazunetakahashi/atcoder | /201510_201609/1114_codefes2015_final/E.cpp | UTF-8 | 1,033 | 2.609375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <cmath>
#include <tuple>
#include <string>
#include <cassert>
using namespace std;
typedef long long ll;
int calc(string S, int x) {
reverse(S.begin(), S.end());
for (auto c : S) {
if (c == '-') {
x = -x;
} else {
if (x == 0) {
x = -1;
} else {
x = 0;
}
}
}
return x;
}
string S;
string K[100] = {
"!", "-!", "!-", "!!", "-!-", "-!!", "!-!", "!!-",
"-!-!", "-!!-", "!-!-", "-!-!-"
};
string ans() {
int X = calc(S, 2);
if (X == 2) {
return "";
} else if (X == -2) {
return "-";
} else {
for (auto i=0; ; i++) {
string T = K[i];
for (int i=-2; i<=2; i++) {
if (calc(T, i) != calc(S, i)) {
goto EXIT;
}
}
return T;
EXIT:
continue;
}
}
assert(false);
cout << "0" << endl;
}
int main() {
cin >> S;
cout << ans() << endl;
}
| true |
7bc00196cd0caa1cdc14e3d2af4bc15f3afad8c3 | C++ | FederikoCorp/Editor | /export/Core/Property/propertyfloat.h | UTF-8 | 764 | 2.84375 | 3 | [] | no_license | #ifndef PROPERTYFLOAT_H
#define PROPERTYFLOAT_H
#include <limits>
#include "property.h"
class PropertyFloat : public Property
{
public:
PropertyFloat(const std::string &name);
~PropertyFloat() override = default;
void createPropertyControl(UserInterfaceGateway *userInterfaceGateWay) override;
StoragePropertyPtr createStorageProperty(UnloadGateway *unloadGateway) override;
PropertyPtr clone() override;
float getValue() const;
void setValue(float value);
float getMin() const;
void setMin(float value);
float getMax() const;
void setMax(float value);
private:
float value = 0;
float min = std::numeric_limits<float>::min();
float max = std::numeric_limits<float>::max();
};
#endif // PROPERTYFLOAT_H
| true |
4131e940e25051dca4b4e4a947bce27dbf0046dc | C++ | knagar06/Competitive-Coding | /Leetcode/Medium/15 Kth Largest Element in an Array.cpp | UTF-8 | 527 | 3.015625 | 3 | [] | no_license | class Solution {
public:
int findKthLargest(vector<int>& nums, int k) { // declare a min heap // where in question it is given largest/greatest means create min heap and for smaller create max heap
int val;
priority_queue<int,vector<int>,greater<int>> minh;
int n= nums.size();
for (int i=0;i<n;i++)
{
minh.push(nums[i]);
{
if (minh.size()>k)
minh.pop();
}
}
return minh.top();
}
};
| true |
b5a94f2e5afc3c87389c006315af197471f66d12 | C++ | Swarnava1997/Image-Processing | /Day 2/assignment2.cpp | UTF-8 | 657 | 2.6875 | 3 | [] | no_license | //scale down a image(half)
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
using namespace cv;
int main ()
{
Mat img=imread("a.png",0);
int m=img.rows;
int n=img.cols;
Mat tmp(m/2+1, n/2+1, CV_8UC1, Scalar(0) );
namedWindow ("win", WINDOW_NORMAL);
int i,j;
int a,b,c,d;
for(i=0;i<m/2+1;i++)
{
for(j=0;j<n/2+1;j++)
{
a=img.at<uchar>(i*2,j*2);
b=img.at<uchar>(i*2,j*2+1);
c=img.at<uchar>(i*2+1,j*2);
d=img.at<uchar>(i*2+1,j*2+1);
tmp.at<uchar>(i,j)=(a+b+c+d)/4;
}
}
imshow("win", tmp);
waitKey(0);
}
| true |
4c8b86002a380211b6350229d0454aedcc3839c9 | C++ | ezEngine/ezEngine | /Code/Engine/Core/ResourceManager/ResourceManager.h | UTF-8 | 24,960 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <Core/ResourceManager/Implementation/WorkerTasks.h>
#include <Core/ResourceManager/Resource.h>
#include <Core/ResourceManager/ResourceHandle.h>
#include <Core/ResourceManager/ResourceTypeLoader.h>
#include <Foundation/Configuration/Plugin.h>
#include <Foundation/Containers/HashTable.h>
#include <Foundation/Threading/LockedObject.h>
#include <Foundation/Types/UniquePtr.h>
class ezResourceManagerState;
/// \brief The central class for managing all types derived from ezResource
class EZ_CORE_DLL ezResourceManager
{
friend class ezResourceManagerState;
static ezUniquePtr<ezResourceManagerState> s_pState;
/// \name Events
///@{
public:
/// Events on individual resources. Subscribe to this to get a notification for events happening on any resource.
/// If you are only interested in events for a specific resource, subscribe on directly on that instance.
static const ezEvent<const ezResourceEvent&, ezMutex>& GetResourceEvents();
/// Events for the resource manager that affect broader things.
static const ezEvent<const ezResourceManagerEvent&, ezMutex>& GetManagerEvents();
/// \brief Goes through all existing resources and broadcasts the 'Exists' event.
///
/// Used to announce all currently existing resources to interested event listeners (ie tools).
static void BroadcastExistsEvent();
///@}
/// \name Loading and creating resources
///@{
public:
/// \brief Returns a handle to the requested resource. szResourceID must uniquely identify the resource, different spellings / casing
/// will result in different resources.
///
/// After the call to this function the resource definitely exists in memory. Upon access through BeginAcquireResource / ezResourceLock
/// the resource will be loaded. If it is not possible to load the resource it will change to a 'missing' state. If the code accessing the
/// resource cannot handle that case, the application will 'terminate' (that means crash).
template <typename ResourceType>
static ezTypedResourceHandle<ResourceType> LoadResource(ezStringView sResourceID);
/// \brief Same as LoadResource(), but additionally allows to set a priority on the resource and a custom fallback resource for this
/// instance.
///
/// Pass in ezResourcePriority::Unchanged, if you only want to specify a custom fallback resource.
/// If a resource priority is specified, the target resource will get that priority.
/// If a valid fallback resource is specified, the resource will store that as its instance specific fallback resource. This will be used
/// when trying to acquire the resource later.
template <typename ResourceType>
static ezTypedResourceHandle<ResourceType> LoadResource(ezStringView sResourceID, ezTypedResourceHandle<ResourceType> hLoadingFallback);
/// \brief Same as LoadResource(), but instead of a template argument, the resource type to use is given as ezRTTI info. Returns a
/// typeless handle due to the missing template argument.
static ezTypelessResourceHandle LoadResourceByType(const ezRTTI* pResourceType, ezStringView sResourceID);
/// \brief Checks whether any resource loading is in progress
static bool IsAnyLoadingInProgress();
/// \brief Generates a unique resource ID with the given prefix.
///
/// Provide a prefix that is preferably not used anywhere else (i.e., closely related to your code).
/// If the prefix is not also used to manually generate resource IDs, this function is guaranteed to return a unique resource ID.
static ezString GenerateUniqueResourceID(ezStringView sResourceIDPrefix);
/// \brief Creates a resource from a descriptor.
///
/// \param szResourceID The unique ID by which the resource is identified. E.g. in GetExistingResource()
/// \param descriptor A type specific descriptor that holds all the information to create the resource.
/// \param szResourceDescription An optional description that might help during debugging. Often a human readable name or path is stored
/// here, to make it easier to identify this resource.
template <typename ResourceType, typename DescriptorType>
static ezTypedResourceHandle<ResourceType> CreateResource(ezStringView sResourceID, DescriptorType&& descriptor, ezStringView sResourceDescription = nullptr);
/// \brief Returns a handle to the resource with the given ID if it exists or creates it from a descriptor.
///
/// \param szResourceID The unique ID by which the resource is identified. E.g. in GetExistingResource()
/// \param descriptor A type specific descriptor that holds all the information to create the resource.
/// \param szResourceDescription An optional description that might help during debugging. Often a human readable name or path is stored here, to make it easier to identify this resource.
template <typename ResourceType, typename DescriptorType>
static ezTypedResourceHandle<ResourceType> GetOrCreateResource(ezStringView sResourceID, DescriptorType&& descriptor, ezStringView sResourceDescription = nullptr);
/// \brief Returns a handle to the resource with the given ID. If the resource does not exist, the handle is invalid.
///
/// Use this if a resource needs to be created procedurally (with CreateResource()), but might already have been created.
/// If the returned handle is invalid, then just go through the resource creation step.
template <typename ResourceType>
static ezTypedResourceHandle<ResourceType> GetExistingResource(ezStringView sResourceID);
/// \brief Same as GetExistingResourceByType() but allows to specify the resource type as an ezRTTI.
static ezTypelessResourceHandle GetExistingResourceByType(const ezRTTI* pResourceType, ezStringView sResourceID);
template <typename ResourceType>
static ezTypedResourceHandle<ResourceType> GetExistingResourceOrCreateAsync(ezStringView sResourceID, ezUniquePtr<ezResourceTypeLoader>&& pLoader, ezTypedResourceHandle<ResourceType> hLoadingFallback = {})
{
ezTypelessResourceHandle hTypeless = GetExistingResourceOrCreateAsync(ezGetStaticRTTI<ResourceType>(), sResourceID, std::move(pLoader));
auto hTyped = ezTypedResourceHandle<ResourceType>((ResourceType*)hTypeless.m_pResource);
if (hLoadingFallback.IsValid())
{
((ResourceType*)hTypeless.m_pResource)->SetLoadingFallbackResource(hLoadingFallback);
}
return hTyped;
}
static ezTypelessResourceHandle GetExistingResourceOrCreateAsync(const ezRTTI* pResourceType, ezStringView sResourceID, ezUniquePtr<ezResourceTypeLoader>&& pLoader);
/// \brief Triggers loading of the given resource. tShouldBeAvailableIn specifies how long the resource is not yet needed, thus allowing
/// other resources to be loaded first. This is only a hint and there are no guarantees when the resource is available.
static void PreloadResource(const ezTypelessResourceHandle& hResource);
/// \brief Similar to locking a resource with 'BlockTillLoaded' acquire mode, but can be done with a typeless handle and does not return a result.
static void ForceLoadResourceNow(const ezTypelessResourceHandle& hResource);
/// \brief Returns the current loading state of the given resource.
static ezResourceState GetLoadingState(const ezTypelessResourceHandle& hResource);
///@}
/// \name Reloading resources
///@{
public:
/// \brief Goes through all resources and makes sure they are reloaded, if they have changed. If bForce is true, all resources
/// are updated, even if there is no indication that they have changed.
static ezUInt32 ReloadAllResources(bool bForce);
/// \brief Goes through all resources of the given type and makes sure they are reloaded, if they have changed. If bForce is true,
/// resources are updated, even if there is no indication that they have changed.
template <typename ResourceType>
static ezUInt32 ReloadResourcesOfType(bool bForce);
/// \brief Goes through all resources of the given type and makes sure they are reloaded, if they have changed. If bForce is true,
/// resources are updated, even if there is no indication that they have changed.
static ezUInt32 ReloadResourcesOfType(const ezRTTI* pType, bool bForce);
/// \brief Reloads only the one specific resource. If bForce is true, it is updated, even if there is no indication that it has changed.
template <typename ResourceType>
static bool ReloadResource(const ezTypedResourceHandle<ResourceType>& hResource, bool bForce);
/// \brief Reloads only the one specific resource. If bForce is true, it is updated, even if there is no indication that it has changed.
static bool ReloadResource(const ezRTTI* pType, const ezTypelessResourceHandle& hResource, bool bForce);
/// \brief Calls ReloadResource() on the given resource, but makes sure that the reload happens with the given custom loader.
///
/// Use this e.g. with a ezResourceLoaderFromMemory to replace an existing resource with new data that was created on-the-fly.
/// Using this function will set the 'PreventFileReload' flag on the resource and thus prevent further reload actions.
///
/// \sa RestoreResource()
static void UpdateResourceWithCustomLoader(const ezTypelessResourceHandle& hResource, ezUniquePtr<ezResourceTypeLoader>&& pLoader);
/// \brief Removes the 'PreventFileReload' flag and forces a reload on the resource.
///
/// \sa UpdateResourceWithCustomLoader()
static void RestoreResource(const ezTypelessResourceHandle& hResource);
///@}
/// \name Acquiring resources
///@{
public:
/// \brief Acquires a resource pointer from a handle. Prefer to use ezResourceLock, which wraps BeginAcquireResource / EndAcquireResource
///
/// \param hResource The resource to acquire
/// \param mode The desired way to acquire the resource. See ezResourceAcquireMode for details.
/// \param hLoadingFallback A custom fallback resource that should be returned if hResource is not yet available. Allows to use domain
/// specific knowledge to get a better fallback.
/// \param Priority Allows to adjust the priority of the resource. This will affect how fast
/// the resource is loaded, in case it is not yet available.
/// \param out_AcquireResult Returns how successful the acquisition was. See ezResourceAcquireResult for details.
template <typename ResourceType>
static ResourceType* BeginAcquireResource(const ezTypedResourceHandle<ResourceType>& hResource, ezResourceAcquireMode mode,
const ezTypedResourceHandle<ResourceType>& hLoadingFallback = ezTypedResourceHandle<ResourceType>(),
ezResourceAcquireResult* out_pAcquireResult = nullptr);
/// \brief Same as BeginAcquireResource but only for the base resource pointer.
static ezResource* BeginAcquireResourcePointer(const ezRTTI* pType, const ezTypelessResourceHandle& hResource);
/// \brief Needs to be called in concert with BeginAcquireResource() after accessing a resource has been finished. Prefer to use
/// ezResourceLock instead.
template <typename ResourceType>
static void EndAcquireResource(ResourceType* pResource);
/// \brief Same as EndAcquireResource but without the template parameter. See also BeginAcquireResourcePointer.
static void EndAcquireResourcePointer(ezResource* pResource);
/// \brief Forces the resource manager to treat ezResourceAcquireMode::AllowLoadingFallback as ezResourceAcquireMode::BlockTillLoaded on
/// BeginAcquireResource.
static void ForceNoFallbackAcquisition(ezUInt32 uiNumFrames = 0xFFFFFFFF);
/// \brief If the returned number is greater 0 the resource manager treats ezResourceAcquireMode::AllowLoadingFallback as
/// ezResourceAcquireMode::BlockTillLoaded on BeginAcquireResource.
static ezUInt32 GetForceNoFallbackAcquisition();
/// \brief Retrieves an array of pointers to resources of the indicated type which
/// are loaded at the moment. Destroy the returned object as soon as possible as it
/// holds the entire resource manager locked.
template <typename ResourceType>
static ezLockedObject<ezMutex, ezDynamicArray<ezResource*>> GetAllResourcesOfType();
///@}
/// \name Unloading resources
///@{
public:
/// \brief Deallocates all resources whose refcount has reached 0. Returns the number of deleted resources.
static ezUInt32 FreeAllUnusedResources();
/// \brief Deallocates resources whose refcount has reached 0. Returns the number of deleted resources.
static ezUInt32 FreeUnusedResources(ezTime timeout, ezTime lastAcquireThreshold);
/// \brief If timeout is not zero, FreeUnusedResources() is called once every frame with the given parameters.
static void SetAutoFreeUnused(ezTime timeout, ezTime lastAcquireThreshold);
/// \brief If set to 'false' resources of the given type will not be incrementally unloaded in the background, when they are not referenced anymore.
template <typename ResourceType>
static void SetIncrementalUnloadForResourceType(bool bActive);
template <typename TypeBeingUpdated, typename TypeItWantsToAcquire>
static void AllowResourceTypeAcquireDuringUpdateContent()
{
AllowResourceTypeAcquireDuringUpdateContent(ezGetStaticRTTI<TypeBeingUpdated>(), ezGetStaticRTTI<TypeItWantsToAcquire>());
}
static void AllowResourceTypeAcquireDuringUpdateContent(const ezRTTI* pTypeBeingUpdated, const ezRTTI* pTypeItWantsToAcquire);
static bool IsResourceTypeAcquireDuringUpdateContentAllowed(const ezRTTI* pTypeBeingUpdated, const ezRTTI* pTypeItWantsToAcquire);
private:
static ezResult DeallocateResource(ezResource* pResource);
///@}
/// \name Miscellaneous
///@{
public:
/// \brief Returns the resource manager mutex. Allows to lock the manager on a thread when multiple operations need to be done in
/// sequence.
static ezMutex& GetMutex() { return s_ResourceMutex; }
/// \brief Must be called once per frame for some bookkeeping.
static void PerFrameUpdate();
/// \brief Makes sure that no further resource loading will take place.
static void EngineAboutToShutdown();
/// \brief Calls ezResource::ResetResource() on all resources.
///
/// This is mostly for usage in tools to reset resource whose state can be modified at runtime, to reset them to their original state.
static void ResetAllResources();
/// \brief Calls ezResource::UpdateContent() to fill the resource with 'low resolution' data
///
/// This will early out, if the resource has gotten low-res data before.
/// The resource itself may ignore the data, if it has already gotten low/high res data before.
///
/// The typical use case is, that some other piece of code stores a low-res version of a resource to be able to get
/// a resource into a usable state. For instance, a material may store low resolution texture data for every texture that it references.
/// Then when 'loading' the textures, it can pass this low-res data to the textures, such that rendering can give decent results right
/// away. If the textures have already been loaded before, or some other material already had low-res data, the call exits quickly.
static void SetResourceLowResData(const ezTypelessResourceHandle& hResource, ezStreamReader* pStream);
///@}
/// \name Type specific loaders
///@{
public:
/// \brief Sets the resource loader to use when no type specific resource loader is available.
static void SetDefaultResourceLoader(ezResourceTypeLoader* pDefaultLoader);
/// \brief Returns the resource loader to use when no type specific resource loader is available.
static ezResourceTypeLoader* GetDefaultResourceLoader();
/// \brief Sets the resource loader to use for the given resource type.
///
/// \note This is bound to one specific type. Derived types do not inherit the type loader.
template <typename ResourceType>
static void SetResourceTypeLoader(ezResourceTypeLoader* pCreator);
///@}
/// \name Named resources
///@{
public:
/// \brief Registers a 'named' resource. When a resource is looked up using \a szLookupName, the lookup will be redirected to \a
/// szRedirectionResource.
///
/// This can be used to register a resource under an easier to use name. For example one can register "MenuBackground" as the name for "{
/// E50DCC85-D375-4999-9CFE-42F1377FAC85 }". If the lookup name already exists, it will be overwritten.
static void RegisterNamedResource(ezStringView sLookupName, ezStringView sRedirectionResource);
/// \brief Removes a previously registered name from the redirection table.
static void UnregisterNamedResource(ezStringView sLookupName);
///@}
/// \name Asset system interaction
///@{
public:
/// \brief Registers which resource type to use to load an asset with the given type name
static void RegisterResourceForAssetType(ezStringView sAssetTypeName, const ezRTTI* pResourceType);
/// \brief Returns the resource type that was registered to handle the given asset type for loading. nullptr if no resource type was
/// registered for this asset type.
static const ezRTTI* FindResourceForAssetType(ezStringView sAssetTypeName);
///@}
/// \name Export mode
///@{
public:
/// \brief Enables export mode. In this mode the resource manager will assert when it actually tries to load a resource.
/// This can be useful when exporting resource handles but the actual resource content is not needed.
static void EnableExportMode(bool bEnable);
/// \brief Returns whether export mode is active.
static bool IsExportModeEnabled();
/// \brief Creates a resource handle for the given resource ID. This method can only be used if export mode is enabled.
/// Internally it will create a resource but does not load the content. This way it can be ensured that the resource handle is always only
/// the size of a pointer.
template <typename ResourceType>
static ezTypedResourceHandle<ResourceType> GetResourceHandleForExport(ezStringView sResourceID);
///@}
/// \name Resource Type Overrides
///@{
public:
/// \brief Registers a resource type to be used instead of any of it's base classes, when loading specific data
///
/// When resource B is derived from A it can be registered to be instantiated when loading data, even if the code specifies to use a
/// resource of type A.
/// Whenever LoadResource<A>() is executed, the registered callback \a OverrideDecider is run to figure out whether B should be
/// instantiated instead. If OverrideDecider returns true, B is used.
///
/// OverrideDecider is given the resource ID after it has been resolved by the ezFileSystem. So it has to be able to make its decision
/// from the file path, name or extension.
/// The override is registered for all base classes of \a pDerivedTypeToUse, in case the derivation hierarchy is longer.
///
/// Without calling this at startup, a derived resource type has to be manually requested in code.
static void RegisterResourceOverrideType(const ezRTTI* pDerivedTypeToUse, ezDelegate<bool(const ezStringBuilder&)> overrideDecider);
/// \brief Unregisters \a pDerivedTypeToUse as an override resource
///
/// \sa RegisterResourceOverrideType()
static void UnregisterResourceOverrideType(const ezRTTI* pDerivedTypeToUse);
///@}
/// \name Resource Fallbacks
///@{
public:
/// \brief Specifies which resource to use as a loading fallback for the given type, while a resource is not yet loaded.
template <typename RESOURCE_TYPE>
static void SetResourceTypeLoadingFallback(const ezTypedResourceHandle<RESOURCE_TYPE>& hResource)
{
RESOURCE_TYPE::SetResourceTypeLoadingFallback(hResource);
}
/// \sa SetResourceTypeLoadingFallback()
template <typename RESOURCE_TYPE>
static inline const ezTypedResourceHandle<RESOURCE_TYPE>& GetResourceTypeLoadingFallback()
{
return RESOURCE_TYPE::GetResourceTypeLoadingFallback();
}
/// \brief Specifies which resource to use as a missing fallback for the given type, when a resource cannot be loaded.
///
/// \note If no missing fallback is specified, trying to load a resource that does not exist will assert at runtime.
template <typename RESOURCE_TYPE>
static void SetResourceTypeMissingFallback(const ezTypedResourceHandle<RESOURCE_TYPE>& hResource)
{
RESOURCE_TYPE::SetResourceTypeMissingFallback(hResource);
}
/// \sa SetResourceTypeMissingFallback()
template <typename RESOURCE_TYPE>
static inline const ezTypedResourceHandle<RESOURCE_TYPE>& GetResourceTypeMissingFallback()
{
return RESOURCE_TYPE::GetResourceTypeMissingFallback();
}
using ResourceCleanupCB = ezDelegate<void()>;
/// \brief [internal] Used by ezResource to register a cleanup function to be called at resource manager shutdown.
static void AddResourceCleanupCallback(ResourceCleanupCB cb);
/// \sa AddResourceCleanupCallback()
static void ClearResourceCleanupCallback(ResourceCleanupCB cb);
/// \brief This will clear ALL resources that were registered as 'missing' or 'loading' fallback resources. This is called early during
/// system shutdown to clean up resources.
static void ExecuteAllResourceCleanupCallbacks();
///@}
/// \name Resource Priorities
///@{
public:
/// \brief Specifies which resource to use as a loading fallback for the given type, while a resource is not yet loaded.
template <typename RESOURCE_TYPE>
static void SetResourceTypeDefaultPriority(ezResourcePriority priority)
{
GetResourceTypePriorities()[ezGetStaticRTTI<RESOURCE_TYPE>()] = priority;
}
private:
static ezMap<const ezRTTI*, ezResourcePriority>& GetResourceTypePriorities();
///@}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
private:
friend class ezResource;
friend class ezResourceManagerWorkerDataLoad;
friend class ezResourceManagerWorkerUpdateContent;
friend class ezResourceHandleReadContext;
// Events
private:
static void BroadcastResourceEvent(const ezResourceEvent& e);
// Miscellaneous
private:
static ezMutex s_ResourceMutex;
// Startup / shutdown
private:
EZ_MAKE_SUBSYSTEM_STARTUP_FRIEND(Core, ResourceManager);
static void OnEngineShutdown();
static void OnCoreShutdown();
static void OnCoreStartup();
static void PluginEventHandler(const ezPluginEvent& e);
// Loading / reloading / creating resources
private:
struct LoadedResources
{
ezHashTable<ezTempHashedString, ezResource*> m_Resources;
};
struct LoadingInfo
{
float m_fPriority = 0;
ezResource* m_pResource = nullptr;
EZ_ALWAYS_INLINE bool operator==(const LoadingInfo& rhs) const { return m_pResource == rhs.m_pResource; }
EZ_ALWAYS_INLINE bool operator<(const LoadingInfo& rhs) const { return m_fPriority < rhs.m_fPriority; }
};
static void EnsureResourceLoadingState(ezResource* pResource, const ezResourceState RequestedState);
static void PreloadResource(ezResource* pResource);
static void InternalPreloadResource(ezResource* pResource, bool bHighestPriority);
template <typename ResourceType>
static ResourceType* GetResource(ezStringView sResourceID, bool bIsReloadable);
static ezResource* GetResource(const ezRTTI* pRtti, ezStringView sResourceID, bool bIsReloadable);
static void RunWorkerTask(ezResource* pResource);
static void UpdateLoadingDeadlines();
static void ReverseBubbleSortStep(ezDeque<LoadingInfo>& data);
static bool ReloadResource(ezResource* pResource, bool bForce);
static void SetupWorkerTasks();
static ezTime GetLastFrameUpdate();
static ezHashTable<const ezRTTI*, LoadedResources>& GetLoadedResources();
static ezDynamicArray<ezResource*>& GetLoadedResourceOfTypeTempContainer();
EZ_ALWAYS_INLINE static bool IsQueuedForLoading(ezResource* pResource) { return pResource->m_Flags.IsSet(ezResourceFlags::IsQueuedForLoading); }
[[nodiscard]] static ezResult RemoveFromLoadingQueue(ezResource* pResource);
static void AddToLoadingQueue(ezResource* pResource, bool bHighPriority);
struct ResourceTypeInfo
{
bool m_bIncrementalUnload = true;
bool m_bAllowNestedAcquireCached = false;
ezHybridArray<const ezRTTI*, 8> m_NestedTypes;
};
static ResourceTypeInfo& GetResourceTypeInfo(const ezRTTI* pRtti);
// Type loaders
private:
static ezResourceTypeLoader* GetResourceTypeLoader(const ezRTTI* pRTTI);
static ezMap<const ezRTTI*, ezResourceTypeLoader*>& GetResourceTypeLoaders();
// Override / derived resources
private:
struct DerivedTypeInfo
{
const ezRTTI* m_pDerivedType = nullptr;
ezDelegate<bool(const ezStringBuilder&)> m_Decider;
};
/// \brief Checks whether there is a type override for pRtti given szResourceID and returns that
static const ezRTTI* FindResourceTypeOverride(const ezRTTI* pRtti, ezStringView sResourceID);
};
#include <Core/ResourceManager/Implementation/ResourceLock.h>
#include <Core/ResourceManager/Implementation/ResourceManager_inl.h>
| true |
1ef76f95748799a4d5925782fea7a83604e9f350 | C++ | prajogotio/expriment-kalmanfilter | /kalman.h | UTF-8 | 1,586 | 2.890625 | 3 | [] | no_license | #ifndef KALMAN_KALMAN_H
#define KALMAN_KALMAN_H
#include "matrix.h"
namespace kalman {
class KalmanFilter {
public:
// 'initial_mean' refers to the initial state of the system, while
// 'initial_covariance' refers to the initial error matrix of the state.
KalmanFilter(const Matrix& initial_mean, const Matrix& initial_covariance)
: mean_(initial_mean), covariance_(initial_covariance) {}
// Performs the prediction stage of Kalman Filter. Suppose x and P are the
// state and covariance matrix respectively, let 'transition' be F and
// 'process_error' be Q, then we have:
// x := Fx
// P := FPF' + Q
void Predict(const Matrix& transition, const Matrix& process_error);
// Performs the update stage of Kalman Filter, using the newest 'reading'
// value with 'reading_covariance' error. Suppose x and P are the state and
// covariance matrix respectively, while 'reading' and 'reading_covariance'
// are r and R. Also, let 'scaling' be H. Then we have:
// K := PH' inv(HPH' + R) [kalman gain]
// P := P - KHP
// x := x + K (r - Hx)
void UpdateWithCurrentReading(const Matrix& reading,
const Matrix& reading_covariance,
const Matrix& scaling);
// Returns the current mean value of the state of the system.
const Matrix& GetCurrentMean() const;
// Returns the current covariance of the state of the system.
const Matrix& GetCurrentCovariance() const;
private:
Matrix mean_;
Matrix covariance_;
};
} // namespace kalman
#endif // KALMAN_KALMAN_H | true |
8d3ee197798bc8c177dcb466095f70252bdd4dd3 | C++ | RomanPas/Lab_2 | /tests/test_database.cpp | UTF-8 | 2,924 | 3.140625 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "tools.h"
#include "ipv4.h"
#include "database.h"
#include <vector>
using namespace std;
namespace {
class TestDatabase : public Database {
public:
const vector<Ipv4>& getData() const;
pair<itIp, itIp> checkFindRange(Ipv4 min, Ipv4 max);
bool checkCorrectIp(const std::vector<std::string>& vecStrIp);
};
const vector<Ipv4>& TestDatabase::getData() const {
return data_;
}
pair<itIp, itIp> TestDatabase::checkFindRange(Ipv4 min, Ipv4 max) {
return findRange(min, max);
}
bool TestDatabase::checkCorrectIp(const std::vector<std::string>& vecStrIp) {
return correctIp(vecStrIp);
}
}
TEST(database, add) {
TestDatabase database;
vector<Ipv4> answer = { 0, 77777, 255, 1234, 8 };
for (auto ip : answer)
database.addIp(ip);
auto data = database.getData();
EXPECT_EQ(data.size(), answer.size());
for (size_t i = 0; i < answer.size(); ++i)
EXPECT_EQ(data[i], answer[i]);
}
TEST(database, findRange) {
TestDatabase database;
vector<Ipv4> vecIp = { 0, 1, 2, 10, 22, 255, 256, 257, 999 };
for (auto ip : vecIp)
database.addIp(ip);
auto data = database.getData();
EXPECT_EQ(data.size(), vecIp.size());
Ipv4 minIp = 0;
Ipv4 maxIp = 1;
auto range = database.checkFindRange(minIp, maxIp);
vector<Ipv4> answer = { 1, 0 };
vector<Ipv4> result = { range.first, range.second };
EXPECT_EQ(result.size(), answer.size());
EXPECT_EQ(result, answer);
minIp = 0;
maxIp = 999;
range = database.checkFindRange(minIp, maxIp);
answer = { 999, 257, 256, 255, 22, 10, 2, 1, 0 };
result = { range.first, range.second };
EXPECT_EQ(result.size(), answer.size());
EXPECT_EQ(result, answer);
minIp = 22;
maxIp = 22;
range = database.checkFindRange(minIp, maxIp);
answer = { 22 };
result = { range.first, range.second };
EXPECT_EQ(result.size(), answer.size());
EXPECT_EQ(result, answer);
minIp = 999;
maxIp = 1000;
range = database.checkFindRange(minIp, maxIp);
answer = { 999 };
result = { range.first, range.second };
EXPECT_EQ(result.size(), answer.size());
EXPECT_EQ(result, answer);
minIp = 1000;
maxIp = 999;
range = database.checkFindRange(minIp, maxIp);
answer = {};
result = { range.first, range.second };
EXPECT_EQ(result.size(), answer.size());
EXPECT_EQ(result, answer);
}
TEST(database, correctIp) {
TestDatabase database;
vector<string> vecStrIp;
EXPECT_FALSE(database.checkCorrectIp(vecStrIp));
vecStrIp = { "0" };
EXPECT_FALSE(database.checkCorrectIp(vecStrIp));
vecStrIp = { "0", "0", "0", "0", "0" };
EXPECT_FALSE(database.checkCorrectIp(vecStrIp));
vecStrIp = { "1", "2", "3", "999" };
EXPECT_FALSE(database.checkCorrectIp(vecStrIp));
vecStrIp = { "1", "2", "3", "4" };
EXPECT_TRUE(database.checkCorrectIp(vecStrIp));
vecStrIp = { "255", "255", "255", "255" };
EXPECT_TRUE(database.checkCorrectIp(vecStrIp));
vecStrIp = { "0", "0", "0", "0" };
EXPECT_TRUE(database.checkCorrectIp(vecStrIp));
} | true |
06bd67e062b9c9ae6b56e759628b9e821302f1ee | C++ | MatiCuartero/Matias | /Correcciones de Franquito 2.0/TP Final cosnultas/Project34/cRamal.cpp | UTF-8 | 675 | 2.515625 | 3 | [] | no_license | #include "cRamal.h"
#include "cParada.h"
#include "cListaT.h"
cRamal::cRamal()
{
//////////agregar algo/////////////
nombre = "";
}
cRamal::cRamal(string nombre, cParada *parada1, cParada *parada2, cParada *parada3, cParada *parada4, cParada *parada5)
{
/*this->parada1 = parada1;
this->parada2 = parada2;
this->parada3 = parada3;
this->parada4 = parada4;
this->parada5 = parada5;*/
//Por cada Ramal que me cree voy a tener una lista diferente con las paradas del ramal respectivamente.
*ListaParadas+parada1;
*ListaParadas+parada2;
*ListaParadas+parada3;
*ListaParadas+parada4;
*ListaParadas+parada5;
}
cRamal::~cRamal()
{
}
| true |
d2a5bfca07fcb209bd3ac16eed58b37d617352ac | C++ | QAlexBall/C- | /exercise_cpp11/list_back_test.cpp | UTF-8 | 367 | 3.171875 | 3 | [] | no_license | //
// Created by deren zhu on 2019/10/15.
//
#include<iostream>
#include<list>
int main(){
// Initialization of list
std::list<int> demo_list;
// Adding elements to the list
demo_list.push_back(10);
demo_list.push_back(20);
demo_list.push_back(30);
// prints the last element of demo_list
std::cout << demo_list.back();
return 0;
} | true |
4cb6b7e0241862b2d96e85f85df2d75462024c1a | C++ | nonanona/myeditor | /src/text_util.cc | UTF-8 | 476 | 2.796875 | 3 | [] | no_license | #include "text_util.h"
namespace text_util {
std::vector<std::vector<uint32_t>> split(std::vector<uint32_t> str,
uint32_t delimiter) {
std::vector<std::vector<uint32_t>> result;
std::vector<uint32_t> element;
for (uint32_t i = 0; i < str.size(); ++i) {
element.push_back(str[i]);
if (str[i] == delimiter) {
result.push_back(element);
element.clear();
}
}
return result;
}
} // namespace text_util
| true |
63c94217b1f6f25f2fa28ad6be4f57d67427d06d | C++ | benard-g/wire-frame | /src/space/shape/Cube.cpp | UTF-8 | 1,796 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "wf/space/shape/Cube.hpp"
wf::space::shape::Cube::Cube(double size, sf::Color color):
m_size(size),
m_color(color)
{}
void wf::space::shape::Cube::generateLines(LineInserter const &insertLine) {
double offset = m_size / 2;
// Points
wf::core::Position front1{ .x=-offset, .y=-offset, .z=-offset };
wf::core::Position front2{ .x= offset, .y=-offset, .z=-offset };
wf::core::Position front3{ .x= offset, .y= offset, .z=-offset };
wf::core::Position front4{ .x=-offset, .y= offset, .z=-offset };
wf::core::Position back1{ .x=-offset, .y=-offset, .z= offset };
wf::core::Position back2{ .x= offset, .y=-offset, .z= offset };
wf::core::Position back3{ .x= offset, .y= offset, .z= offset };
wf::core::Position back4{ .x=-offset, .y= offset, .z= offset };
// Front square
insertLine(wf::core::Line{ .p1=front1, .p2=front2, .color=m_color });
insertLine(wf::core::Line{ .p1=front2, .p2=front3, .color=m_color });
insertLine(wf::core::Line{ .p1=front3, .p2=front4, .color=m_color });
insertLine(wf::core::Line{ .p1=front4, .p2=front1, .color=m_color });
// Back square
insertLine(wf::core::Line{ .p1=back1, .p2=back2, .color=m_color });
insertLine(wf::core::Line{ .p1=back2, .p2=back3, .color=m_color });
insertLine(wf::core::Line{ .p1=back3, .p2=back4, .color=m_color });
insertLine(wf::core::Line{ .p1=back4, .p2=back1, .color=m_color });
// Link front and back
insertLine(wf::core::Line{ .p1=front1, .p2=back1, .color=m_color });
insertLine(wf::core::Line{ .p1=front2, .p2=back2, .color=m_color });
insertLine(wf::core::Line{ .p1=front3, .p2=back3, .color=m_color });
insertLine(wf::core::Line{ .p1=front4, .p2=back4, .color=m_color });
}
| true |
52251dc4921a484b9fc09f29525834bb4f00bcd2 | C++ | Szymon200227/vector-json | /cgi-vector-sortowanie.cpp | UTF-8 | 2,065 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <fstream>
#include <conio.h>
#include <queue>
#include <string>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
struct osoba
{
string imie, nazwisko;
int wiek;
};
class klasa
{
vector <struct osoba> spis;
public:
void zapiszDoPliku(const char *);
void wczytajZPliku(const char *);
};
void klasa::zapiszDoPliku(const char *nazwa)
{
ofstream plik;
plik.open(nazwa);
plik <<"["<<endl;
int liczba;
if(plik.good())
for (vector<struct osoba>::iterator it = spis.begin(); it != spis.end(); ++it)
{
plik <<" {"<<endl;
plik << '"'<<"title"<<'"'<<":"<<'"'<< it->imie << " "
<< it->nazwisko <<'"'<<","<<"\n"<<'"'<< "subtitle" <<'"'<<":"
<<'"'<< it->wiek <<'"'<<"\n";
plik <<"},"<<"\n" ;
liczba++;
if(liczba<spis.size());
}
plik <<"]";
plik.close();
}
void klasa::wczytajZPliku(const char *nazwa)
{
int p=0;
queue<string>kolejka;
char t[1000];
ifstream plik;
plik.open(nazwa);
struct osoba s;
if(plik.good())
while(!plik.eof())
{
plik >> s.wiek >> s.imie >> s.nazwisko ;
cout <<"Imie: " << s.imie <<", Nazwisko: "
<< s.nazwisko <<", Wiek: "
<< s.wiek <<"\n";
spis.push_back(s);
}
plik.close();
}
int main(int argc, char** argv) {
klasa TI;
TI.wczytajZPliku("C:\\Users\\szymo\\OneDrive\\Pulpit\\populacja.txt");
TI.zapiszDoPliku("C:\\Users\\szymo\\OneDrive\\Pulpit\\dopopulacja.txt");
return 0;
}
| true |
7d233ce83910772d62e7619d670c9f527df508b7 | C++ | geekhch/homework | /CPP/程序/第6章程序/s6_13/smain6_13.cpp | GB18030 | 797 | 3.390625 | 3 | [] | no_license | // ļ·:s6_13\smain6_13.cpp
#include <iostream> // Ԥ
#include <deque> // Ԥ
#include <stack> // Ԥ
using namespace std; // ʹռstd
int main() // main()
{
stack<int> s; // ջ
for(int i = 1; i <= 5; ++i)
{ // ջ
s.push(i); // iջ
}
cout << "ջs:"; // ʾ
while (!s.empty())
{ // ջsǿ
cout << s.top() << " "; // ջ
s.pop(); // ջ
}
cout << endl; //
system("PAUSE"); // ÿ⺯system( )ϵͳʾϢ
return 0; // ֵ0, زϵͳ
}
| true |
b1b4e368ef7fe4feafc8f1adf21fcb0f55192032 | C++ | ColorlessBoy/leetcode | /84.柱状图中最大的矩形.cpp | UTF-8 | 1,022 | 3.234375 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=84 lang=cpp
*
* [84] 柱状图中最大的矩形
*/
#include <bits/stdc++.h>
using namespace std;
// @lc code=start
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if(heights.empty()) return false;
stack<int> s;
heights.push_back(0);
int n = heights.size(), max_area = 0;
for(int current_i = 0; current_i < n; ++current_i) {
int current_h = heights[current_i];
while(!s.empty() && heights[s.top()] > current_h) {
int top_i = s.top(); s.pop();
int distance = (s.empty())? current_i: current_i-s.top()-1;
int area = heights[top_i] * distance;
max_area = max(max_area, area);
}
s.push(current_i);
}
return max_area;
}
};
// @lc code=end
int main(int argc, char **argv) {
Solution s;
vector<int> heights = {2, 1, 2};
int rst = s.largestRectangleArea(heights);
return 0;
}
| true |
a20ef9bdab182490ab3c2380c96dcb324f89f0c7 | C++ | Sandeep-Pasumarthi/4thSemster | /ProgrammingParadigmsLabaratory/Lab-4/Part 1/PP_A4_Part1_P2.cpp | UTF-8 | 4,221 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Person
{
protected:
string name;
int age;
char gender;
public:
Person(){};
Person(string, int, char);
~Person();
virtual void readData(string, int, char);
virtual void displayData();
};
class Student : virtual public Person
{
protected:
string department;
int year;
public:
Student(){};
Student(string, int, string, int, char);
~Student();
void readData(string, int, string, int, char);
void displayData();
};
class Clerk : virtual public Person
{
protected:
int workload;
int salary;
public:
Clerk(){};
Clerk(int, int, string, int, char);
~Clerk();
void readData(int, int, string, int, char);
void displayData();
};
class Professor : public Student, public Clerk
{
protected:
int courseload;
public:
Professor(){};
Professor(string, int, int, string, int, char);
~Professor();
void readData(string, int, int, string, int, char);
void displayData();
};
int main()
{
Person p1("Arjuna", 17, 'M');
p1.displayData();
cout << "\n\n";
Person p2;
p2.readData("Sandeep", 19, 'M');
p2.displayData();
cout << "\n\n";
Student s1("CST", 2021, "Sandeep", 18, 'M');
s1.displayData();
cout << "\n\n";
Student s2;
s2.readData("AERO", 2023, "Arjuna", 17, 'M');
s2.displayData();
cout << "\n\n";
Clerk c1(16, 20000, "Sandeep", 16, 'M');
c1.displayData();
cout << "\n\n";
Clerk c2;
c2.readData(17, 25000, "Satwik", 18, 'M');
c2.displayData();
cout << "\n\n";
Professor pr1("CST", 5, 100000, "Dhrona", 1000, 'M');
pr1.displayData();
cout << "\n\n";
Professor pr2;
pr2.readData("AERO", 10, 1000000, "Shukra", 15000, 'M');
pr2.displayData();
cout << "\n\n";
return 0;
}
Person ::Person(string n, int a, char g)
{
name = n;
age = a;
gender = g;
cout << "Parameterized Person Constructor" << endl;
}
Person ::~Person()
{
cout << "Person Destructor" << endl;
}
void Person ::readData(string n, int a, char g)
{
name = n;
age = a;
gender = g;
}
void Person ::displayData()
{
cout << "Name: - " << name << endl;
cout << "Age: - " << age << endl;
cout << "Gender: - " << gender << endl;
}
Student ::Student(string d, int y, string n, int a, char g) : Person(n, a, g)
{
department = d;
year = y;
cout << "Parameterized Student Constructor" << endl;
}
Student ::~Student()
{
cout << "Student Destructor" << endl;
}
void Student::readData(string d, int y, string n, int a, char g)
{
Person::readData(n, a, g);
department = d;
year = y;
}
void Student::displayData()
{
Person::displayData();
cout << "Department: - " << department << endl;
cout << "Year: - " << year << endl;
}
Clerk ::Clerk(int w, int s, string n, int a, char g) : Person(n, a, g)
{
workload = w;
salary = s;
cout << "Parameterized Clerk Costructor" << endl;
}
Clerk ::~Clerk()
{
cout << "Clerk Destructor" << endl;
}
void Clerk ::readData(int w, int s, string n, int a, char g)
{
Person::readData(n, a, g);
workload = w;
salary = s;
}
void Clerk ::displayData()
{
Person::displayData();
cout << "Work Load: - " << workload << endl;
cout << "Salary: - " << salary << endl;
}
Professor ::Professor(string d, int c, int s, string n, int a, char g) : Student(d, 0, n, a, g), Clerk(0, s, n, a, g), Person(n, a, g)
{
courseload = c;
cout << "Parameterized Professor Constructor" << endl;
}
Professor ::~Professor()
{
cout << "Professor Destructor" << endl;
}
void Professor::readData(string d, int c, int s, string n, int a, char g)
{
Person::readData(n, a, g);
department = d;
courseload = c;
salary = s;
}
void Professor::displayData()
{
Person::displayData();
cout << "Department: - " << department << endl;
cout << "Course Load: - " << courseload << endl;
cout << "Salary: - " << salary << endl;
} | true |
ff247e74cb0edc57b55d2e0174203f660a4d5024 | C++ | KhaledAbdelgalil/sheet-mostafa-saad-problem-solving- | /Some Explaintion/Topics to be taken/DP/content in vidoes/videos 1-12/video12/dp19/main.cpp | UTF-8 | 1,258 | 3.125 | 3 | [] | no_license | //probability with dp
//TC: PrimeSoccer(another solution(prob without dp)in video 12 is left for now)
#include <bits/stdc++.h>
using namespace std;
double a,b;
double table[19][19][19];//state is which interval what a scores till now what b scores till now
bool prime(int n)
{
switch(n)
{
case 0:
case 1:
case 4:
case 6:
case 8:
case 9:
case 10:
case 12:
case 14:
case 15:
case 16:
case 18:
return false;
default: return true;
}
}
double solution(int r,int g1,int g2)
{
if(r>=18) return (prime(g1)||prime(g2))?1:0;
if(fabs(table[r][g1][g2]+1)>1e-9) return table[r][g1][g2];
double res=a*b*(solution(r+1,g1+1,g2+1));
res+=a*(1-b)*(solution(r+1,g1+1,g2));
res+=(1-a)*(1-b)*(solution(r+1,g1,g2));
res+=(1-a)*(b)*(solution(r+1,g1,g2+1));
return table[r][g1][g2]=res;
}
class PrimeSoccer
{
public:
double getProbability (int skillOfTeamA,int skillOfTeamB)
{
a=(double)(skillOfTeamA)/100.0;
b=(double)skillOfTeamB/100.0;
memset(table,-1,sizeof table);
return solution(0,0,0);
}
};
int main()
{
PrimeSoccer* s;
s=new PrimeSoccer();
int c,d;
cin>>c>>d;
cout<<s->getProbability(c,d);
return 0;
}
| true |
45a40f75d2f66d4f5704e1af452c787fc81afb33 | C++ | rohanraja/dbms_abhijeet | /delta.cpp | UTF-8 | 890 | 2.90625 | 3 | [] | no_license | #include <cmath>
#include <vector>
#include <iostream>
#include<string>
#include<sstream>
#include<map>
#include<cstdlib>
#include<utility>
using namespace std;
struct WINDOW{
int x0, x;
vector<int> T;
vector<int> Y;
int sumx, sumy, sumx2, sumy2, sumxy ;
};
struct CONSTANTS{
float a, b ;
};
CONSTANTS Linear_fit(WINDOW w)
{
CONSTANTS c;
w.sumx += w.T[w.x];
w.sumy += w.Y[w.x];
w.sumx2 += w.T[w.x]*w.T[w.x];
w.sumy2 += w.Y[w.x]*w.Y[w.x];
w.sumxy += w.Y[w.x]*w.T[w.x];
return c;
};
float LSS(WINDOW w, CONSTANTS c)
{
return 0.0;
}
int delta(WINDOW data, int k){
int x0 = 0;
for(int x = 2; x < data.Y.size(); x++){
WINDOW window;
window = data;
window.x0 = x0;
window.x = x;
CONSTANTS c = Linear_fit(window) ;
cost1 = LSS(window, c);
Reset_Sums(window);
}
return 0.0;
}
int main(){
return 0;
}
| true |
9ab31915eb5141d50ee63501ed0ac4f62866d6b6 | C++ | Forrest-Z/cplus_plus_code | /014_UNIX_LINUX/getopt/getopt2.cpp | UTF-8 | 1,057 | 3.296875 | 3 | [] | no_license | #include<iostream>
#include<unistd.h>
class Program {
public:
Program(unsigned int c) : count(c) {}
void run();
private:
unsigned int count;
};
void Program::run() {
for(unsigned int i = 0; i < count; ++i) {
std::cout << "Hello World with getopt!.\n";
}
}
int main(int argc, char **argv) {
if(argc > 1) {
int opt;
unsigned int counter = 0;
while((opt = getopt(argc, argv, "c:")) != -1) {
switch(opt) {
case 'c':
counter = atoi(optarg);
if(counter == 0) {
std::cerr << "Error requires loop count...\n";
exit(EXIT_FAILURE);
}
break;
default:
std::cout << " use -c counter\n";
exit(0);
break;
}
}
Program program(counter);
program.run();
} else {
std::cerr << "use: " << argv[0] << " -c counter\n";
}
return 0;
}
| true |
4e1fe12382921bdf95993643183283777ead1342 | C++ | vinsonleelws/LeetCode | /223-Rectangle Area.cpp | UTF-8 | 1,542 | 3.46875 | 3 | [] | no_license | Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Rectangle Area
Example:
Input: -3, 0, 3, 4, 0, -1, 9, 2
Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
// 把两个矩形的八个顶点分别投影到x轴和y轴上,两个矩形相交的条件就是既在x轴上的投影有交集,又在y轴上的投影有交集。
// Reference solution:
// 首先找出所有的不相交的情况,只有四种,一个矩形在另一个的上下左右四个位置不重叠,这四种情况下返回两个矩形面积之和。
// 其他所有情况下两个矩形是有交集的,这时候我们只要算出相交部分的长和宽,即可求出交集区域的大小,然后从两个矩形面积之
// 和中减去交集面积就是最终答案。关键在求交集区域的长和宽,由于交集都是在中间,所以左端点是两个矩形左顶点横坐标的较大
// 值,右端点是两个矩形右顶点的较小值,同理,下端点是两个矩形下顶点纵坐标的较大值,上端点是两个矩形上顶点纵坐标的较小值。
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int sum = (C - A) * (D - B) + (H - F) * (G - E);
if (E >= C || F >= D || B >= H || A >= G)
return sum;
return sum - ((min(G, C) - max(A, E)) * (min(D, H) - max(B, F)));
}
};
| true |
9a583feff7f06c792563c8e7ea84a25fa61a8ac6 | C++ | jiahaochen666/CS103 | /lab3/Automobile.cpp | UTF-8 | 162 | 2.53125 | 3 | [] | no_license | #include "Automobile.hpp"
Automobile::Automobile(std::string n, double sp, double w, int sz): Vehicle(std::move(n), sp, w, sz){}
Automobile::~Automobile(){} | true |
d94a8bfdbad5fad6a7706a769169f7d09e15f9e7 | C++ | padesai/Caching | /MyTag.cc | UTF-8 | 1,075 | 2.625 | 3 | [] | no_license | #include "ns3/tag.h"
#include "ns3/packet.h"
#include "ns3/uinteger.h"
#include <iostream>
#include "MyTag.h"
namespace ns3
{
TypeId
MyTag::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::MyTag")
.SetParent<Tag> ()
.AddConstructor<MyTag> ()
.AddAttribute ("TagData",
"File Id",
EmptyAttributeValue (),
MakeUintegerAccessor (&MyTag::GetTag),
MakeUintegerChecker<uint64_t> ())
;
return tid;
}
TypeId
MyTag::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
uint32_t
MyTag::GetSerializedSize (void) const
{
return sizeof(tagValue);
}
void
MyTag::Serialize (TagBuffer i) const
{
i.WriteU64(tagValue);
}
void
MyTag::Deserialize (TagBuffer i)
{
tagValue = i.ReadU64();
}
void
MyTag::Print (std::ostream &os) const
{
os << " tagValue = " << tagValue << std::endl;
}
void
MyTag::SetTag(uint64_t value)
{
tagValue = value;
}
uint64_t
MyTag::GetTag(void) const
{
return tagValue;
}
} | true |
36015e0993dd3d4e70813144ea17f01a1b513aaa | C++ | opendarkeden/server | /src/server/gameserver/item/Dermis.h | UHC | 3,868 | 2.78125 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : Dermis.h
// Written By : Elca
// Description :
//////////////////////////////////////////////////////////////////////////////
#ifndef __DERMIS_H__
#define __DERMIS_H__
#include "Item.h"
#include "ConcreteItem.h"
#include "ItemPolicies.h"
#include "ItemInfo.h"
#include "InfoClassManager.h"
#include "ItemFactory.h"
#include "ItemLoader.h"
#include "Mutex.h"
//////////////////////////////////////////////////////////////////////////////
// class Dermis;
//////////////////////////////////////////////////////////////////////////////
class Dermis : public ConcreteItem<Item::ITEM_CLASS_DERMIS, NoStack, NoDurability, HasOption, AccessoryGrade, NoAttacking>
{
public:
Dermis() ;
Dermis(ItemType_t itemType, const list<OptionType_t>& optionType) ;
public:
virtual void create(const string & ownerID, Storage storage, StorageID_t storageID, BYTE x, BYTE y, ItemID_t itemID=0) ;
virtual void save(const string & ownerID, Storage storage, StorageID_t storageID, BYTE x, BYTE y) ;
void tinysave(const string & field) const { tinysave(field.c_str()); }
void tinysave(const char* field) const ;
virtual string toString() const ;
static void initItemIDRegistry(void) ;
private:
static Mutex m_Mutex; // ID
static ItemID_t m_ItemIDRegistry; // Ŭ ̵ ߱ޱ
};
//////////////////////////////////////////////////////////////////////////////
// class DermisInfo
//////////////////////////////////////////////////////////////////////////////
class DermisInfo : public ItemInfo
{
public:
virtual Item::ItemClass getItemClass() const { return Item::ITEM_CLASS_DERMIS; }
Defense_t getDefenseBonus() const { return m_DefenseBonus; }
void setDefenseBonus(Defense_t acBonus) { m_DefenseBonus = acBonus; }
Protection_t getProtectionBonus() const { return m_ProtectionBonus; }
void setProtectionBonus(Protection_t acBonus) { m_ProtectionBonus = acBonus; }
virtual uint getItemLevel(void) const { return m_ItemLevel; }
virtual void setItemLevel(uint level) { m_ItemLevel = level; }
virtual string toString() const ;
private:
Defense_t m_DefenseBonus; // ߷ ʽ
Protection_t m_ProtectionBonus;
uint m_ItemLevel;
};
//////////////////////////////////////////////////////////////////////////////
// class DermisInfoManager;
//////////////////////////////////////////////////////////////////////////////
class DermisInfoManager : public InfoClassManager
{
public:
virtual Item::ItemClass getItemClass() const { return Item::ITEM_CLASS_DERMIS; }
virtual void load() ;
};
// global variable declaration
extern DermisInfoManager* g_pDermisInfoManager;
//////////////////////////////////////////////////////////////////////////////
// class DermisFactory
//////////////////////////////////////////////////////////////////////////////
class DermisFactory : public ItemFactory
{
public:
virtual Item::ItemClass getItemClass() const { return Item::ITEM_CLASS_DERMIS; }
virtual string getItemClassName() const { return "Dermis"; }
public:
virtual Item* createItem(ItemType_t ItemType, const list<OptionType_t>& OptionType) { return new Dermis(ItemType,OptionType); }
};
//////////////////////////////////////////////////////////////////////////////
// class DermisLoader;
//////////////////////////////////////////////////////////////////////////////
class DermisLoader : public ItemLoader
{
public:
virtual Item::ItemClass getItemClass() const { return Item::ITEM_CLASS_DERMIS; }
virtual string getItemClassName() const { return "Dermis"; }
public:
virtual void load(Creature* pCreature) ;
virtual void load(Zone* pZone) ;
virtual void load(StorageID_t storageID, Inventory* pInventory) ;
};
extern DermisLoader* g_pDermisLoader;
#endif
| true |
cb361cc4e25463dc45e42181e15ec60eec68361a | C++ | luabeltranga/Herramientas | /MatrixCodes/gsl/chp03/arraysUniv2.cpp | UTF-8 | 2,023 | 3.890625 | 4 | [] | no_license | // ejemplos de arrays unidimensionales
// ejemplo:
// tipo name[int size];
#include <iostream>
using namespace std;
typedef double REAL;
// typedef float REAL;
#define SIZE 7
int main(void)
{
// int size = 5;
// declarar arreglo de int
int arrayInt[SIZE];
// declarar arreglo de REAL
REAL arrayReal[SIZE + 2];
// Cual es el tamanho de los arrays?
cout << sizeof(arrayInt) << endl;
cout << sizeof(int) << endl;
cout << sizeof(arrayReal) << endl;
cout << sizeof(REAL) << endl;
// el valor inicial de los arreglos es aleatorio porque
// no se declararon con valor inicial, imprimirlos para ver
int i;
for (i = 0; i < SIZE; i++) {
cout << arrayInt[i] << "\t";
}
cout << endl;
cout << endl;
for (i = 0; i < SIZE; i++) {
cout << arrayReal[i] << "\t";
}
cout << endl;
cout << endl;
// Como asignar los valores inciales?
// declarar otros arreglos REAL
REAL arrayReal2[SIZE + 2] = {0}; // todos a cero
REAL arrayReal3[SIZE + 2] = {1,2,3,4,55,66,77,88,99}; // uno a uno
REAL arrayReal4[SIZE + 2] = {1,2,3,4}; // algunos, el resto a cero
REAL arrayReal5[] = {1,2,3,4}; // cuatro elementos
cout << "Todos a cero" << endl;
for (i = 0; i < SIZE; i++) {
cout << arrayReal2[i] << "\t";
}
cout << endl;
cout << endl;
cout << "Uno a uno" << endl;
for (i = 0; i < SIZE; i++) {
cout << arrayReal3[i] << "\t";
}
cout << endl;
cout << endl;
cout << "Algunos, resto a cero" << endl;
for (i = 0; i < SIZE; i++) {
cout << arrayReal4[i] << "\t";
}
cout << endl;
cout << endl;
cout << "Cuatro elementos automatico, error en "
"impresion (tamanho incorrecto)" << endl;
for (i = 0; i < SIZE; i++) {
cout << arrayReal5[i] << "\t";
}
cout << endl;
cout << endl;
cout << "Cuatro elementos automatico, NO error en "
"impresion (tamanho correcto)" << endl;
for (i = 0; i < sizeof(arrayReal5)/sizeof(REAL); i++) {
cout << arrayReal5[i] << "\t";
}
cout << endl;
cout << endl;
return 0;
}
| true |
8c71487e374e3ba01c3b610e06edd53d6a2cdc3e | C++ | CPardi/Test-Cpp | /Mandlebrot/Grid.hxx | UTF-8 | 901 | 3.640625 | 4 | [] | no_license | #include "Grid.h"
template<class resultType>
Grid<resultType>::Grid(int xPoints, int yPoints, resultType x0, resultType xMax, resultType y0, resultType yMax)
{
// Set the classes public fields.
XPoints = xPoints;
YPoints = yPoints;
// Intialize vectors.
_xValues.resize(xPoints);
_yValues.resize(yPoints);
// Calculate the grid widths.
double xWidth = xMax - x0;
double yWidth = yMax - y0;
// Calculate the grid spacings.
double dx = xWidth / (xPoints - 1);
double dy = yWidth / (yPoints - 1);
// Fill values for the x-axis.
for (int i = 0; i < xPoints; i++)
{
_xValues[i] = x0 + i*dx;
}
// Fill values for the y-axis.
for (int j = 0; j < yPoints; j++)
{
_yValues[j] = y0 + j*dy;
}
};
template<class resultType>
resultType Grid<resultType>::X(int i)
{
return _xValues[i];
};
template<class resultType>
resultType Grid<resultType>::Y(int j)
{
return _yValues[j];
}; | true |
7345ec0b57c56c46e309fc243981af9b965d4748 | C++ | karlgluck/evidyon-2.10 | /Evidyon/apps/common/gui/guirect.cpp | UTF-8 | 4,044 | 3.09375 | 3 | [
"MIT"
] | permissive | //------------------------------------------------------------------------------------------------
// File: guirect.cpp
//
// Desc:
//
// Copyright (c) 2007-2008 Unseen Studios. All rights reserved.
//------------------------------------------------------------------------------------------------
#include "guipoint.h"
#include "guisize.h"
#include "guirect.h"
//------------------------------------------------------------------------------------------------
// Name: set
// Desc: Sets up this rectangle to have the top-left coordinate at 'point' and the
// bottom-right coordinate at point + size
//------------------------------------------------------------------------------------------------
void GUIRect::set(GUIPoint point, GUISize size)
{
left = point.x;
top = point.y;
right = left + size.width;
bottom = top + size.height;
}
//------------------------------------------------------------------------------------------------
// Name: contains
// Desc: Determines whether or not this rectangle contains the given point
//------------------------------------------------------------------------------------------------
bool GUIRect::contains(GUIPoint point) const
{
return point.x >= left && point.x < right && point.y >= top && point.y < bottom;
}
//------------------------------------------------------------------------------------------------
// Name: isValid
// Desc: Returns 'true' if the dimensions are non-negative
//------------------------------------------------------------------------------------------------
bool GUIRect::isValid() const
{
GUISize size = calculateSize();
return size.width >= 0 && size.height >= 0;
}
//------------------------------------------------------------------------------------------------
// Name: constrain
// Desc: Changes the coordinates of the given point so that the point lies within this rectangle
//------------------------------------------------------------------------------------------------
GUIPoint GUIRect::constrain(GUIPoint point) const
{
point.x = point.x > left ? point.x : left;
point.y = point.y > top ? point.y : top;
point.x = point.x < right ? point.x : right;
point.y = point.y < bottom ? point.y : bottom;
return point;
}
//------------------------------------------------------------------------------------------------
// Name: calculateSize
// Desc: Calculates the size of this rectangle
//------------------------------------------------------------------------------------------------
GUISize GUIRect::calculateSize() const
{
GUISize size = { right - left, bottom - top };
return size;
}
//------------------------------------------------------------------------------------------------
// Name: intersect
// Desc: Calculates the common rectangle between this rectangle and the other
//------------------------------------------------------------------------------------------------
void GUIRect::intersect(const GUIRect* other, GUIRect* intersection) const
{
#define min(a,b) ((a)<(b))?(a):(b);
#define max(a,b) ((a)>(b))?(a):(b);
intersection->left = max(left, other->left);
intersection->right = min(right, other->right);
intersection->top = max(top, other->top);
intersection->bottom = min(bottom, other->bottom);
}
//------------------------------------------------------------------------------------------------
// Name: overlaps
// Desc: Determines whether or not this rectangle overlaps another
//------------------------------------------------------------------------------------------------
bool GUIRect::overlaps(const GUIRect* other) const
{
GUIRect intersection;
intersect(other, &intersection);
return intersection.isValid();
}
//------------------------------------------------------------------------------------------------
// Name: zero
// Desc: Resets the members of this structure
//------------------------------------------------------------------------------------------------
void GUIRect::zero()
{
left = 0;
right = 0;
top = 0;
bottom = 0;
} | true |
8f2c5a57733f7e77755944ef881d7b18019422fb | C++ | Vuean/ThinkingInCPlusPlus | /2. Making & Using Objects/Exercise/ex2.cpp | UTF-8 | 435 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int radius;
cout << "Enter the circle radius: ";
cin >> radius;
if(radius < 0)
{
cout << "Radius must be greater than zero." << endl;
cout << "Please try again!" << endl;
}
float area = 3.14 * radius * radius;
cout << "Area of the circle with radius equal to " << radius << " is "
<< area << "." << endl;
return 0;
} | true |
2c7a52e6944e35a7568b70cd49d1295dc25b1ea2 | C++ | shubhammatta/hackerrank | /prac.cpp | UTF-8 | 1,456 | 2.5625 | 3 | [] | no_license | //Author : Nitin Singh Budhwar a.k.a SinOfWrath
#define ssync ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0) // in case of using only c++ input stream and not stdio(much faster)
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define fst first
#define scd second
#define pb push_back
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip> //io manipluation
#include <climits>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;
typedef long long ll;
typedef pair<int,ll> pil;
typedef vector<int> vi;
typedef unsigned long long int ull;
int main(){
ssync;
int n,m;
cin>>n>>m;
int cost[n+1];
cost[0]=0;
FOR(i,1,n+1) cin>>cost[i];
vector<ll> ed(35,0);
int a,b;
FOR(i,0,m){
cin>>a>>b;
ed[a] |= ((ll)1<<(b-1));
ed[b] |= ((ll)1<<(a-1));
}
vector<pil> best[35];
best[0].pb(pil(0,(ll)0));
best[1].pb(pil(cost[1],ed[1]));
int sum,maxc=cost[1],count_max=1;
FOR(i,2,n+1){
best[i].pb(pil(cost[i],ed[i]));
if(maxc<cost[i]){
maxc=cost[i];
count_max=1;
}
else if(maxc==cost[i]) count_max++;
for(int j=i-1;j>0;j--){
FOR(k,0,best[j].size()){
if(((ll)1<<(i-1) & best[j][k].scd)==0){
best[i].pb(pil(best[j][k].fst+cost[i],best[j][k].scd | ed[i]));
sum=best[j][k].fst+cost[i];
if(maxc<sum){
maxc=sum;
count_max=1;
}
else if(maxc==sum) count_max++;
}
}
}
}
cout << maxc << " "<<count_max<<endl;
return 0;
} | true |
9f70a32225a2ddbfa03bb80f72abe63ab15e7544 | C++ | Minek124/Studia-Informatyka | /Cpp/zad2-1.cpp | UTF-8 | 393 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
while(true){
int x;
cin >> x;
if(x != 0)
v.push_back(x);
else
break;
}
int max = -2147483647;
int min = 2147483647;
for(auto i : v){
if(i > max)
max = i;
if(i < min)
min = i;
}
cout << "min:" << min << " max:" << max << endl;
return 0;
}
| true |
7b91d7cebcb960fff887c321ba06638c0d8e75df | C++ | haikentcode/code | /collegeTime/cpp/rotedarray.cpp | UTF-8 | 913 | 2.9375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int bs(int A[],int left,int right,int k){
int mid=left+(right-left)/2;
if(left<=right){
if(A[mid]==k) return mid;
else if(A[mid]>k) return bs(A,left,mid-1,k);
else return bs(A,mid+1,right,k);}
return -1;
}
int brs(int A[],int left,int right,int k){
int mid=left+(right-left)/2;
if(left<=right){
if(A[mid]==k) return mid;
else if(A[mid]>k){
if(A[left]<=k) return brs(A,left,mid-1,k);
else return brs(A,mid+1,right,k);
}
else{
if(A[right]>=k) return brs(A,mid+1,right,k);
else return brs(A,left,mid-1,k);
}
}
return -1;
}
int search(int A[],int n,int k){
return brs(A,0,n,k);
}
int main(){
int n;
cin>>n;
int A[n];
for(int i=0;i<n;i++) cin>>A[i];
for(int i=0;i<n;i++) cout<<A[i]<<" ";
while(1){
int k;
cin>>k;
cout<<search(A,n,k);
}
}
| true |
1d6a2da291c67654427568914e40b3397746c80a | C++ | munawar-shakil/Tricks | /Dynamic Connectivity Offline D&C.cpp | UTF-8 | 4,570 | 2.515625 | 3 | [] | no_license | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<map>
#include<list>
#include<queue>
#include<iostream>
#include<algorithm>
#include<set>
#include<deque>
#include<stack>
#define vi vector<int>
#define vll vector<LL>
#define pii pair<int,int>
#define pli pair<LL,int>
#define pll pair<LL,LL>
#define fr first
#define sc second
#define MAX 50010
#define LL long long int
#define ll long long int
//#define LLL long long int
#define inf (1ll<<62)
#define INF 10000000
#define mod 1000000007
//#define N 65
#define mMax 30010
#define nMax 2010
#define SZ(a) a.size()
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define rep1(i,b) for(int i=1;i<=b;i++)
#define rep2(i,b) for(int i=0;i<b;i++)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define all(A) A.begin(),A.end()
#define isf(a) scanf("%d",&a);
#define Lsf(a) scanf("%I64d",&a);
#define lsf(a) scanf("%lld",&a);
#define csf(a) scanf("%c",&a);
#define vedge vector<Edge>
using namespace std;
LL bigmod(LL a,LL b,LL Mod)
{
if(b==0) return 1ll;
if(b%2) return (a*bigmod(a,b-1,Mod))%Mod;
LL c=bigmod(a,b/2,Mod);
return (c*c)%Mod;
}
///Divide and Conquer Trick
struct Edge{
int u,v,l,r,f;
Edge(){}
Edge(int a,int b,int c,int d,int zz=0)
{
u=a;
v=b;
l=c;
r=d;
f=zz;
}
void rein(int x,int y){
u=x;v=y;
}
};
vector<vi> E;
int comp[100010];
vi vis;
/// for finding the number of component in the graph
void dfs(int u,int col)
{
comp[u]=col;
rep2(i,SZ(E[u]))
if(comp[E[u][i]]==-1)
dfs(E[u][i],col);
return;
}
/// adding edge between biconnected components
void add(int u,int v)
{
E[u].pb(v);E[v].pb(u);
}
vi ans;
int query[100010];
/// this technique would be easier to understand if you learn a (n+m)sqrt(n+m)
/// algorithm to solve this problem.
/// start of divide and conquer
/// 0. We will save our queries as edges and each edge will have a lifetime
/// ie starting time = when it was added in the graph and
/// ending time = when it will be deleted or removed
/// eg. if at time t1 we get a query to add edge e and at time t2 we get a request
/// to remove it then lifetime will be [t1,t2] .
/// 1.Each time we will compress the graph where the graph build with
/// the edges that cover the block [L,R] since for this range we are
/// only sure about the existence of these edges.
/// 2. Key optimization: We will delete all components that are not mentioned
/// in the block[L,R] . Eg. if a edge added at time 5 then we dont care about
/// it at range [2,4]. Thus every range wil have no more than R-L+1 edges.
/// So at any level we process no more then m edges where m is # of query
/// and maximum level lgm . So compexity O(mlgm).
void D_C(int L,int R,vedge edges,int n)
{
if(L>R) return;
if(query[R+1]-query[L] <=0)
{
return;
}
rep2(i,n) E[i].clear();
vedge nedges;
///building graph
rep2(i,SZ(edges))
{
if(edges[i].l<=L && edges[i].r>=R && edges[i].f==0) add(edges[i].u,edges[i].v);
else if(edges[i].l<R && edges[i].r>L) nedges.pb(edges[i]);
else if(edges[i].l>=L && edges[i].r<=R && edges[i].f==1) nedges.pb(edges[i]);
}
int m=0;
rep2(i,n) comp[i]=-1;
///finding components
rep2(i,n)
if(comp[i]==-1)
dfs(i,m++);
vi deg(n,0);
rep2(i,SZ(nedges)){
nedges[i].u=comp[nedges[i].u];
nedges[i].v=comp[nedges[i].v];
if(nedges[i].u != nedges[i].v)
deg[nedges[i].u]++,deg[nedges[i].v]++;
}
n=0;
edges.clear();
///removing the components that are not mentioned in this block
rep2(i,m) if(deg[i]) comp[i]=n++;
rep2(i,SZ(nedges)){
nedges[i].u=comp[nedges[i].u];
nedges[i].v=comp[nedges[i].v];
}
//a/answering connection query
if(L==R)
{
if(query[R+1]-query[R] == 1) ans.pb(nedges[0].u==nedges[0].v);
return;
}
/// divide
int mid=(L+R)>>1;
D_C(L,mid,nedges,n);
D_C(mid+1,R,nedges,n);
return;
}
map<pii,int> Map;
int main()
{
int T=10000000;
while(T--);/// wasting time :D
int n,m;
char str[10];
cin>>n>>m;
E.assign(n+1,vi());
vedge edges;
rep2(i,m)
{
int a,b;
scanf("%s %d %d",str,&a,&b);
if(a>b) swap(a,b);
if(str[0]=='a') Map[mp(a,b)]=i;
else if(str[0]=='r')
{
int &temp=Map[mp(a,b)];
/// setting lifetime for edges
edges.pb(Edge(a,b,temp,i));
temp=-1;
}
else {edges.pb(Edge(a,b,i,i,1));query[i+1]=1;}
query[i+1]=query[i]+query[i+1];
}
for(map<pii,int>::iterator it=Map.begin();it!=Map.end();it++)
if(it->sc!=-1) /// taking only those edges that are not removed
edges.pb(Edge(it->fr.fr,it->fr.sc,it->sc,m));
D_C(0,m-1,edges,n);
rep2(i,SZ(ans))
if(ans[i]==0) printf("NO\n");
else printf("YES\n");
return 0;
}
| true |
e9700cb33d95506e6c6d9a4912348f0a90f40d44 | C++ | thuy288/HackerRank-Problem-solve | /Tree Heihgt of a Binary Tree.cpp | UTF-8 | 458 | 3.65625 | 4 | [] | no_license | /*The tree node has data, left child and right child
class Node {
int data;
Node* left;
Node* right;
};
*/
int height(Node* root) {
if(root == NULL)
return -1; ///single node has height 0 here
///if single node has defined height 1 then it will returning 0
int l_ht = height(root->left);
int r_ht = height(root->right);
return 1 + max(l_ht, r_ht);
}
| true |
3f56d618d5aa6ab7b1e69b58a1ee44c821d3eb18 | C++ | SNHU-projects/Clocks | /MenuOptions.cpp | UTF-8 | 2,215 | 3.625 | 4 | [
"Apache-2.0"
] | permissive | //
// Created by Jef DeWitt on 3/16/20.
//
#include <iostream>
#include "MenuOptions.h"
#include "DisplayClocks.h"
#include "chrono"
// Default Constructor
MenuOptions::MenuOptions() {
}
// Build menu interface
void MenuOptions::DisplayMenu() {
std::cout << " *************************" << std::endl;
std::cout << " * 1 - Add One Hour *" << std::endl;
std::cout << " * 2 - Add One Minute *" << std::endl;
std::cout << " * 3 - Add One Second *" << std::endl;
std::cout << " * 4 - Exit Program *" << std::endl;
std::cout << " *************************" << std::endl;
}
// Method to handle user input
void MenuOptions::CollectUserInput(tm * currentTime) {
DisplayClocks displayClocks;
int userInput;
do {
// Collect user input
std::cout << "Press ENTER to display menu." << std::endl;
// Check for enter key presses
if (std::cin.get() == '\n') {
DisplayMenu();
std::cin >> userInput;
std::cin.clear(); // clears input error flag
std::cin.ignore(100,'\n'); // clears out leftover characters, including newlines
}
else {
// If user enters a selection before entering menu, re-prompt to show menu.
userInput = 5;
std::cin.clear(); // clears input error flag
std::cin.ignore(100,'\n'); // clears out leftover characters, including newlines
}
// Switch handles expected user input and
// calls appropriate methods
switch(userInput) {
case 1:
displayClocks.AddOneHour(currentTime);
break;
case 2:
displayClocks.AddOneMinute(currentTime);
break;
case 3:
displayClocks.AddOneSecond(currentTime);
break;
case 4:
std::cout << "System exiting. Goodbye." << std::endl;
exit(0);
default:
std::cout << "Please try again." << std::endl;
}
// When userInput is 4, exit
} while (userInput != 4);
}
| true |
55988b972820eb588d509e5b0f996233b5cb1d1a | C++ | PredatorFeesh/NeuralNetwork | /cpp/Matrix.cpp | UTF-8 | 4,554 | 3.15625 | 3 | [] | no_license | #include "../headers/Matrix.h"
#include <iostream>
#include <algorithm>
using std::vector;
using std::cout;
using std::endl;
using std::transform;
void Matrix::initZero()
{
// Done by default so pass
}
void Matrix::initLowRandoms(float low, float top)
{
std::default_random_engine gen;
std::uniform_real_distribution<float> dist(low, top);
for( unsigned i=0; i < rows; i++ )
{
generate(m_matrix[i].begin(), m_matrix[i].end(), [&](){return dist(gen) ;}); // random values
}
}
void Matrix::initXavier(float n_i1, float n_i2) // n_i1 is layer i, n_i2 is layer i+1
{
float sqrt6 = sqrt(6);
initLowRandoms( - (sqrt6 / ( n_i1 + n_i2 ) ) , (sqrt6 / ( n_i1 + n_i2 ) ) );
}
void Matrix::print(int rows, int cols)
{
for( unsigned i = 0; i < rows; i++ )
{
for ( unsigned j = 0; j < cols; j++)
cout << m_matrix[i][j] << " ";
cout << ";" << endl;
}
}
Matrix Matrix::transpose()
{
Matrix output(cols, rows);
for( unsigned i = 0; i < rows; i++ )
for( unsigned j = 0; j < cols; j++ )
output.m_matrix[j][i] = m_matrix[i][j];
return output;
}
Matrix Matrix::apply( std::function<float (float)> activation )
{
Matrix output(rows, cols);
for( unsigned i = 0; i < rows; i++ )
for( unsigned j = 0; j < cols; j++ )
output[i][j] = activation( m_matrix[i][j] );
return output;
}
Matrix Matrix::operator/(float a)
{
Matrix out(rows, cols);
for(unsigned i=0; i<rows; i++)
for(unsigned j=0; j<cols; j++)
out.m_matrix[i][j] = m_matrix[i][j]/a;
return out;
}
Matrix Matrix::operator+(Matrix m)
{
// cout << "Adding" << endl;
// cout << rows << " " << cols << endl;
// cout << m.rows << " " << m.cols << endl;
if ( m.rows != rows || m.cols != cols ){ cout << "Parameters don't match! Can't add!"; exit(1); }
Matrix out(rows, cols);
int i = 0;
for( i = 0; i < rows; i++ )
{
// for( j = 0; j < cols; j++)
// {
// output.m_matrix[i][j] = m_matrix[i][j] + m.m_matrix[i][j];
// cout << output[i][j];
// }
std::transform( m_matrix[i].begin(), m_matrix[i].end(), m.m_matrix[i].begin(), out.m_matrix[i].begin(), std::plus<float>() );
}
cout << "Done adding!" << endl;
return out; // We get an error on return? Why?
}
Matrix Matrix::operator*(Matrix m)
{
// cout << "Multiplying" << endl;
// cout << rows << " " << cols << endl;
// cout << m.rows << " " << m.cols << endl;
if ( cols != m.rows ){ cout << "Rows != Col! Can't multiply!"; exit(1); }
Matrix output(rows, m.cols);
int i, j, k;
// Initializing elements of matrix mult to 0.
for(i = 0; i < rows; ++i)
{
for(j = 0; j < m.cols; ++j)
{
output[i][j] = 0;
}
}
// Multiplying matrix firstMatrix and secondMatrix and storing in array mult.
for(i = 0; i < rows; ++i)
{
for(j = 0; j < m.cols; ++j)
{
for(k=0; k<cols; ++k)
{
output[i][j] += m_matrix[i][k] * m.m_matrix[k][j];
}
}
}
return output;
}
void Matrix::operator+=(Matrix m)
{
*this = *this + m;
}
void Matrix::operator-=(Matrix m)
{
*this = *this - m;
}
Matrix Matrix::operator-(Matrix m)
{
if ( rows != m.rows || cols != m.cols){ cout << "Cant sub! Rows and Cols noteq :: " << rows<<"x"<<cols<<" - "<<m.rows<<"x"<<m.cols<< endl; exit(1); }
Matrix temp(rows, cols);
return *this + (m * -1);
}
Matrix Matrix::operator*(float x)
{
Matrix temp(rows, cols);
for(unsigned i = 0; i < rows; i++)
for(unsigned j = 0; j < cols; j++)
temp[i][j] = m_matrix[i][j] * x;
return temp;
}
Matrix Matrix::hadmard(Matrix m)
{
if ( rows != m.rows || cols != m.cols ) { cout << "Hadmard error! : " << rows<<"x"<<cols<<" = "<<m.rows<<"x"<<m.cols << endl; exit(1); }
Matrix temp(rows, cols);
for(unsigned i = 0; i < rows; i++)
for(unsigned j = 0; j < cols; j++)
temp[i][j] = m_matrix[i][j] * m.m_matrix[i][j];
return temp;
}
void Matrix::operator=(Matrix m)
{
// if (rows != m.rows || cols != m.cols) {cout << "Cant equate! Rows and Cols noteq :: " << rows<<"x"<<cols<<" = "<<m.rows<<"x"<<m.cols<< endl; exit(1);};
rows = m.rows;
cols = m.cols;
m_matrix = m.m_matrix;
// m_matrix.reserve(rows);
// for(unsigned i = 0; i < rows; i++)
// {
// // m_matrix[i].reserve(cols);
// for(unsigned j = 0; j < cols; j++)
// {
// m_matrix[i][j] = m.m_matrix[i][j];
// }
// }
} | true |
36dfff38d52a242459cad36c9865bcbf1933cc14 | C++ | c-square/homework | /Licență/Anul I/POO/Poligon/punct.h | UTF-8 | 1,105 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
#ifndef PUNCT
#define PUNCT
class Punct
{
int X, Y; // coordonatele punctului
public:
static const Punct Origine;
static const Punct UnuZero;
static const Punct ZeroUnu;
Punct(int X = 0, int Y = 0); // constructor
~Punct(){} // destructor
int GetX() const; // returneaza coordonata pe orizontala
int GetY() const; // returneaza coordonata pe verticala
void MutaX (int x = 1); // deplaseaza punctul pe orizontala
void MutaY (int y = 1); // deplaseaza punctul pe verticala
void MutaXY(int x = 1, int y = 1); // deplaseaza punctul pe orizontala si verticala
bool isInOrigine();
bool isEgal(const Punct&);
bool isColiniar(const Punct&, const Punct&);
void interschimba(Punct&);
double distanta(const Punct&);
void operator=(int);
};
istream& operator>>(istream& i, Punct& p);
ostream& operator<<(ostream& o, Punct& p);
bool puncteEgale (const Punct&, const Punct&);
void detDreptunghi (const Punct&, const Punct&, Punct*);
bool operator==(const Punct&, const Punct&);
bool operator!=(const Punct&, const Punct&);
#endif
| true |
f1253dfb95d6ea6cfac698e6926b297e699cb92c | C++ | shufisyahida/cp | /latihan/12554.cpp | UTF-8 | 939 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <utility>
using namespace std;
#define REP(a,b) for (int a = 0; a < b; a++)
#define PB(v,a) v.push_back(a)
bool check(vector< pair<string, bool> > v) {
bool checked = true;
REP(i, v.size()) {
checked = checked && v[i].second;
}
}
int main() {
int n;
cin >> n;
vector<string> s;
vector< pair<string, bool> > v;
PB(s, "Happy");
PB(s, "birthday");
PB(s, "to");
PB(s, "you");
PB(s, "Happy");
PB(s, "birthday");
PB(s, "to");
PB(s, "you");
PB(s, "Happy");
PB(s, "birthday");
PB(s, "to");
PB(s, "Rujia");
PB(s, "Happy");
PB(s, "birthday");
PB(s, "to");
PB(s, "you");
REP(i, n) {
string fam;
cin >> fam;
pair<string, bool> p;
p.first = fam;
p.second = false;
PB(v, p);
}
bool isDone = false;
while(!isDone) {
}
return 0;
} | true |
028841308c16047e8ea75c94ae54891fadf3d7d9 | C++ | inbei/klib | /src/thread/KAtomic.h | UTF-8 | 5,223 | 3 | 3 | [] | no_license | #ifndef _ATOMIC_HPP_
#define _ATOMIC_HPP_
#if defined(WIN32)
#include <windows.h>
#endif
#include <map>
#include "thread/KMutex.h"
#include "thread/KLockGuard.h"
/**
原子操作类
**/
namespace klib {
template<typename VariantType>
class AtomicVariant
{
public:
AtomicVariant(const VariantType& d)
:m_dat(d) {}
inline void Assign(const VariantType& d)
{
KLockGuard<KMutex> lock(m_vtMtx);
m_dat = d;
}
inline VariantType Get() const
{
KLockGuard<KMutex> lock(m_vtMtx);
return m_dat;
}
inline operator VariantType() const
{
KLockGuard<KMutex> lock(m_vtMtx);
return m_dat;
}
inline AtomicVariant& operator=(const VariantType& dt)
{
KLockGuard<KMutex> lock(m_vtMtx);
m_dat = dt;
return *this;
}
private:
VariantType m_dat;
KMutex m_vtMtx;
};
template<typename KeyType, typename ValueType>
class AtomicMap
{
public:
inline void Assign(const KeyType& ky, const ValueType& vt)
{
KLockGuard<KMutex> lock(m_mpMtx);
m_dat[ky] = vt;
}
inline void Assign(const std::map<KeyType, ValueType>& d)
{
KLockGuard<KMutex> lock(m_mpMtx);
m_dat = d;
}
inline bool Get(const KeyType& ky, ValueType& val)
{
KLockGuard<KMutex> lock(m_mpMtx);
if (m_dat.find(ky) != m_dat.end())
{
val = m_dat[ky];
return true;
}
return false;
}
inline void Get(std::map<KeyType, ValueType>& d) const
{
KLockGuard<KMutex> lock(m_mpMtx);
d = m_dat;
}
inline void Erase(const KeyType& ky)
{
KLockGuard<KMutex> lock(m_mpMtx);
m_dat.erase(ky);
}
inline void Clear()
{
KLockGuard<KMutex> lock(m_mpMtx);
m_dat.clear();
}
inline bool Empty() const
{
KLockGuard<KMutex> lock(m_mpMtx);
return m_dat.empty();
}
inline size_t Size() const
{
KLockGuard<KMutex> lock(m_mpMtx);
return m_dat.size();
}
private:
std::map<KeyType, ValueType> m_dat;
KMutex m_mpMtx;
};
template<typename IntegerType>
class AtomicInteger
{
public:
AtomicInteger(IntegerType v = 0) :m_ival(v) {}
inline operator IntegerType() const { return Load(); }
inline AtomicInteger& operator=(IntegerType v){ Exchange(v); return *this; }
inline IntegerType operator++() { return FetchAdd(1) + 1; }//prefix
inline IntegerType operator--() { return FetchSub(1) - 1; }//prefix
inline IntegerType operator++(int) { return FetchAdd(1); }//suffix
inline IntegerType operator--(int) { return FetchSub(1); }//suffix
inline bool operator==(IntegerType v){ return Load() == v; }
inline bool operator==(const AtomicInteger& rh){ return Load() == rh.Load(); }
private:
inline IntegerType FetchAdd(IntegerType val)
{
#if defined(WIN32)
KLockGuard<KMutex> lock(m_intMtx);
IntegerType tmp = m_ival;
m_ival += val;
return tmp;
#else
return __sync_fetch_and_add(&m_ival, val);
#endif
}
inline IntegerType FetchSub(IntegerType val)
{
#if defined(WIN32)
KLockGuard<KMutex> lock(m_intMtx);
IntegerType tmp = m_ival;
m_ival -= val;
return tmp;
#else
return __sync_fetch_and_sub(&m_ival, val);
#endif
}
inline IntegerType Load() const
{
#if defined(WIN32)
KLockGuard<KMutex> lock(m_intMtx);
return m_ival;
#else
return __sync_fetch_and_add(const_cast<IntegerType*>(&m_ival), 0);
#endif
}
inline IntegerType Exchange(IntegerType val)
{
#if defined(WIN32)
KLockGuard<KMutex> lock(m_intMtx);
IntegerType tmp = m_ival;
m_ival = val;
return tmp;
#else
__sync_synchronize();
return __sync_lock_test_and_set(&m_ival, val);
#endif
}
private:
IntegerType m_ival;
#if defined(WIN32)
KMutex m_intMtx;
#endif
};
class AtomicBool
{
public:
AtomicBool(bool v = false):m_dat(v ? 1 : 0){}
inline operator bool() const{ return (int(m_dat) != 0 ? true : false); }
inline AtomicBool& operator=(bool v){ m_dat = (v ? 1 : 0); return *this; }
inline bool operator==(bool v) const{ return (operator bool() == v); }
inline bool operator==(const AtomicBool& rh) const{ return (m_dat == rh.m_dat); }
private:
AtomicInteger<int> m_dat;
};
};
#endif // !_ATOMIC_HPP_
| true |
5829bbadeefd7726875adb87e05fe5c64910b4e2 | C++ | PeterZhouSZ/DataDrivenBipedController | /PyCommon/external_libraries/VirtualPhysics/vpLib/include/VP/vpNDOFJoint.h | UTF-8 | 6,540 | 2.640625 | 3 | [
"LicenseRef-scancode-other-permissive",
"MIT",
"Apache-2.0"
] | permissive | /*
VirtualPhysics v0.9
2008.Feb.21
Imaging Media Research Center, KIST
jwkim@imrc.kist.re.kr
*/
#ifndef VP_NDOFJOINT
#define VP_NDOFJOINT
#include <VP/vpDataType.h>
#include <VP/vpJoint.h>
/*!
\class TransformNDOF
\brief Abstract class model an arbitrary N DOF joint
*/
class TransformNDOF
{
public:
TransformNDOF(int dof);
/*!
Transform function
*/
virtual SE3 GetTransform(const scalarArray &) = 0;
/*!
Jacobian function
The Jacobain is defined as \f$ J_i(q) = T(q)^{-1} \frac{\partial T(q)}{\partial q_i} \in se(3)\f$
If the Jacobian function is not overrided, VP will evaluate the Jacobian using numerical differentiation.
The numerical differentiation requires DOF + 1 times of evaluating the transform function in general.
Also another potential problem of the numerical differentiation is that it may be very sensitive to the epsilon value.
The default epsilon used for numerical differentiation is set as m_rEPS = 1E-4.
*/
virtual void GetJacobian(const scalarArray &, se3Array &);
/*!
Hessian function
The Hessian is defined as \f$ H_{ij}(q) = \frac{\partial J_i(q)}{\partial q_j} \in se(3)\f$
Only the upper triangular part of H will be used.
That is, \f$ H_{ij} \f$ for i > j will not be referenced.
if the Hessian function is not overrided , VP will evalute the Hessian based on a numerical differentiation.
*/
virtual void GetHessian(const scalarArray &, se3DbAry &);
int m_iDOF;
scalar m_rEPS;
};
/*!
\class vpNDOFJoint
\brief arbitrary N DOF joint
vpNDOFJoint is a class for user defined N DOF joint.
*/
class vpNDOFJoint : public vpJoint
{
public:
vpNDOFJoint(int dof);
/*!
set a transform function
*/
void SetTransformFunc(TransformNDOF *);
/*!
set a joint value
*/
void SetPosition(int i, const scalar &);
void SetVelocity(int i, const scalar &);
void SetAcceleration(int i, const scalar &);
/*!
set a torque of the joint.
The torque will be reset after every simulation step
*/
void SetTorque(int i, const scalar &);
/*!
add a torque to the joint.
The torque will be reset after every simulation step
*/
void AddTorque(int i, const scalar &);
/*!
set an initial angle of the joint variable.
*/
void SetInitialPosition(int i, const scalar &);
/*!
set an elasticity of the joint variable.
*/
void SetElasticity(int i, const scalar &);
/*!
set a damping parameter of the joint variable.
*/
void SetDamping(int i, const scalar &);
/*!
set an upper joint limit.
*/
void SetUpperLimit(int i, const scalar &);
/*!
set an upper joint limit.
*/
void SetLowerLimit(int i, const scalar &);
/*!
set a restitution.
*/
void SetRestitution(int i, const scalar &);
/*!
get an angle of the joint variable.
*/
scalar GetPosition(int i) const;
/*!
get an anglular velocity of the joint variable.
*/
scalar GetVelocity(int i) const;
/*!
get an anglular acceleration of the joint variable.
*/
scalar GetAcceleration(int i) const;
/*!
get a torque of the joint.
*/
scalar GetTorque(int i) const;
/*!
get an initial angle of the joint variable.
*/
scalar GetInitialPosition(int i) const;
/*!
get an elasticity of the joint variable.
*/
const scalar &GetElasticity(int i) const;
/*!
get a damping paramter of the joint variable.
*/
const scalar &GetDamping(int i) const;
/*!
get an lower joint limit.
*/
const scalar &GetLowerLimit(int i) const;
/*!
disable upper joint limit.
*/
void DisableUpperLimit(int i);
/*!
disable lower joint limit.
*/
void DisableLowerLimit(int i);
/*!
return whether this joint is set to have upper limit
*/
bool IsEnabledUpperLimit(int) const;
/*!
return whether this joint is set to have lower limit
*/
bool IsEnabledLowerLimit(int) const;
virtual int GetDOF(void) const;
virtual scalar GetNormalForce(void) const;
virtual scalar GetNormalTorque(void) const;
virtual void streamOut(ostream &) const;
protected:
virtual void SwapBody(void);
virtual void BuildKinematics(void);
virtual SE3 Transform(void) const;
virtual void UpdateSpringDamperTorque(void);
virtual scalar GetPotentialEnergy(void) const;
virtual const scalar &GetDisplacement_(int) const;
virtual void SetDisplacement_(int, const scalar &);
virtual const scalar &GetVelocity_(int) const;
virtual void SetVelocity_(int, const scalar &);
virtual const scalar &GetAcceleration_(int) const;
virtual void SetAcceleration_(int, const scalar &);
virtual const scalar &GetImpulsiveTorque_(int) const;
virtual void SetImpulsiveTorque_(int, const scalar &);
virtual scalar GetTorque_(int) const;
virtual void SetTorque_(int, const scalar &);
virtual void SetSpringDamperTorque_(int, const scalar &);
virtual const scalar &GetRestitution_(int) const;
virtual bool ViolateUpperLimit_(int) const;
virtual bool ViolateLowerLimit_(int) const;
virtual void UpdateTorqueID(void);
virtual void UpdateTorqueHD(void);
virtual void UpdateVelocity(const se3 &);
virtual void UpdateAccelerationID(const se3 &);
virtual void UpdateAccelerationFD(const se3 &);
virtual void UpdateAInertia(AInertia &);
virtual void UpdateLOTP(void);
virtual void UpdateTP(void);
virtual void UpdateLP(void);
virtual dse3 GetLP(void);
virtual void ClearTP(void);
virtual void IntegrateDisplacement(const scalar &);
virtual void IntegrateVelocity(const scalar &);
dse3Array m_sL;
scalarArray m_rQ;
scalarArray m_rDq;
scalarArray m_rDdq;
scalarArray m_rActuationTau;
scalarArray m_rSpringDamperTau;
scalarArray m_rImpulsiveTau;
scalarArray m_rQi;
scalarArray m_rQul;
scalarArray m_rQll;
scalarArray m_rRestitution;
scalarArray m_rK;
scalarArray m_rC;
boolArray m_bHasUpperLimit;
boolArray m_bHasLowerLimit;
se3Array m_sS;
se3DbAry m_sH;
se3 m_sVl; // local velocity
se3 m_sDSdq;
RMatrix m_sO;
RMatrix m_sT;
RMatrix m_sP;
int m_iDOF;
TransformNDOF *m_pTransform;
};
#ifndef VP_PROTECT_SRC
#include "vpNDOFJoint.inl"
#endif
#endif
| true |
20ab08192c6407c8ad722307c918f073b8f3a65e | C++ | Divyalok123/LeetCode_Practice | /Practice/Maximum Product of Word Lengths.cpp | UTF-8 | 760 | 3.15625 | 3 | [] | no_license | /*
https://leetcode.com/problems/maximum-product-of-word-lengths/
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
vector<long long> store(n);
for(int i = 0; i < n; i++) {
long long val = 0;
for(auto& j: words[i])
val |= (1 << (j-'a'));
store[i] = val;
}
size_t ans = 0;
for(int i = 0; i < n-1; i++)
for(int j = i+1; j < n; j++)
if((store[i]&store[j]) == 0)
ans = max(ans, words[i].size() * words[j].size());
return ans;
}
}; | true |
b0469306dcb696f5e5350d7597cf859f34f72bd5 | C++ | michael-smirnov/vision_internal | /Core/MathItemGenerator.cpp | UTF-8 | 1,564 | 2.9375 | 3 | [] | no_license | #include "MathItemGenerator.h"
namespace vision
{
Mat MathItemGenerator::matrix_by_row( const std::vector<float>& row )
{
Mat res( row.size(), row.size(), CV_32F );
for( uint i = 0; i < row.size(); i++ )
for( uint j = 0; j < row.size(); j++ )
res.at<float>( j, i ) = row[i];
return res;
}
Mat MathItemGenerator::color_map_matrix( const Mat& m,
int16_t min_value,
int16_t max_value )
{
Mat colored = Mat::zeros( m.rows, m.cols, CV_8UC3 );
int16_t half_value = (max_value - min_value) / 2;
for(int row = 0; row < m.rows; row++)
{
for(int col = 0; col < m.cols; col++)
{
int16_t value = m.at<int16_t>(row, col);
if( value < min_value )
continue;
if( value >= min_value && value < half_value )
{
uint8_t r = (value) / (float)half_value * 255;
uint8_t g = (half_value - value) / (float)half_value * 255;
colored.at<Vec3b>(row, col) = { 0, g, r };
}
else
{
uint8_t r = (max_value- value) / (float)half_value * 255;
uint8_t b = (value - half_value) / (float)half_value * 255;
colored.at<Vec3b>(row, col) = { b, 0, r };
}
}
}
return colored;
}
} | true |
c2e41c8d11ad5f9f501365b3fe2c6670a5dc3660 | C++ | VikramGaru/Projects | /CSE250-DataStructures/TreasureHunter/GameBoard.h | UTF-8 | 1,152 | 2.96875 | 3 | [
"Unlicense"
] | permissive | #ifndef UNTITLED_GAMEBOARD_H
#define UNTITLED_GAMEBOARD_H
#include <set>
#include <unordered_map>
#include <utility>
#include <sstream>
#include "GameLogic.h"
using namespace std;
// Wrapper class for an (x,y) point
class Location{
private:
int x;
int y;
public:
Location();
Location(int, int);
Location(const Location&);
void setX(int);
void setY(int);
int getX() const;
int getY() const;
bool operator==(const Location& otherLocation) const;
};
bool operator<(const Location& location1, const Location& location2);
class GameBoard {
private:
Location goalLocation;
set<Location> treasureLocations;
set<Location> enemyLocations;
public:
GameBoard(Location goalLocation);
GameBoard();
~GameBoard();
GameBoard(const GameBoard&);
void addEnemy(Location);
void addTreasure(Location);
// You only need to call these GameBoard functions for the assignment
bool isTreasure(Location) const;
bool isEnemy(Location) const;
Location getGoalLocation() const;
void killEnemy(Location);
void removeTreasure(Location);
};
#endif //UNTITLED_GAMEBOARD_H
| true |
5ab99ccf431ff1b36475327b1351ca5f25e3bb26 | C++ | wurikiji/algorithm-PS | /acmicpc/1003.cpp | UTF-8 | 390 | 2.734375 | 3 | [] | no_license | #include <cstdio>
int main(void) {
long long arr[64][4];
int t;
scanf("%d", &t);
arr[0][0] = 1; arr[0][1] = 0;
arr[1][0] = 0; arr[1][1] = 1;
for (int i = 2; i <= 40;i++) {
arr[i][0] = arr[i-1][0] + arr[i-2][0];
arr[i][1] = arr[i-1][1] + arr[i-2][1];
}
while(t--) {
int n;
scanf("%d", &n);
printf("%lld %lld\n", arr[n][0], arr[n][1]);
}
return 0;
}
| true |
1815d70f9bc38d51d830178b57643667a8f90196 | C++ | brucelevis/cBoy | /include/flags.h | UTF-8 | 828 | 2.765625 | 3 | [] | no_license | /*
Project: cBoy: A Gameboy emulator written in C++
Author: Danny Glover - https://github.com/DannyGlover
File: flags.h
*/
#ifndef FLAGS_H
#define FLAGS_H
// includes
#include "typedefs.h"
// flag class
class Flags
{
public:
// for getting members which should be indirectly-publicly accessible
class Get
{
public:
static BYTE Z();
static BYTE N();
static BYTE H();
static BYTE C();
};
// for setting members which should be indirectly-publicly accessible
class Set
{
public:
static void Z();
static void N();
static void H();
static void C();
static void All();
};
// for resetting members which should be indirectly-publicly accessible
class Reset
{
public:
static void Z();
static void N();
static void H();
static void C();
static void All();
};
};
#endif
| true |
6ab3e7ade1352d87fab2a94aa1f4fe536927c7a2 | C++ | AyinDJ/HeXiaojun_46090 | /Hmwk/Assignment5/Gaddis_8thEd_Chap6_Prog2/main.cpp | UTF-8 | 1,081 | 3.59375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Xiaojun He
* Purpose: Gaddis_8thEd_Chap6_Prog2
*
* Created on July 12, 2015, 10:19 PM
*/
#include <iostream>
using namespace std;
//User Libraries
//Global Constants
//Function Prototypes
void Input (float&,float&);
float Area (float&,float&,float&);
void Display (float&,float&,float&);
//Execution Begins Here!
int main(int argc, char** argv){
//Declare Variables
float length=0.0,
width=0.0,
area=0.0;
Input(length,width);
area=Area(length,width,area);
Display(length,width,area);
return 0;
}
void Input (float &length,float &width){
cout<<"Enter the length and the width of the rectangle :"<<endl;
cin>>length>>width;
}
float Area (float &length,float &width,float &area){
area=length*width;
return area;
}
void Display (float &length,float &width,float &area){
cout<<"The length of the rectangle = "<<length<<endl;
cout<<"The width of the rectangle = "<<width<<endl;
cout<<"The area of the rectangle = "<<Area(length,width,area)<<endl;
} | true |
c7fb47541a97f4fe617f0946af57b754e1bae8c9 | C++ | shenyunhan/sudoku | /sudoku/writer.cpp | UTF-8 | 1,884 | 2.796875 | 3 | [] | no_license | #include "stdafx.h"
#include "writer.h"
inline void decode(int x, int& r, int& c, int& v)
{
x--;
v = x % 9, x /= 9;
c = x % 9, x /= 9;
r = x;
}
inline void transform(const std::vector<int>& pos, char (&board)[10][10])
{
for (auto i : pos)
{
int r, c, v;
decode(i, r, c, v);
board[r][c] = '1' + v;
}
}
unsigned WINAPI output_main(void* args)
{
Writer* pWriter = (Writer*)args;
for (;;)
{
WaitForSingleObject(pWriter->semaphore, INFINITE);
EnterCriticalSection(&pWriter->lock);
if (pWriter->idx.empty() && pWriter->kill)
{
LeaveCriticalSection(&pWriter->lock);
break;
}
int n = pWriter->idx.front();
pWriter->idx.pop();
char board[10][10];
transform(pWriter->boards.front(), board);
pWriter->boards.pop();
LeaveCriticalSection(&pWriter->lock);
if (n != 1) fputc('\n', pWriter->index);
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (j) fputc(' ', pWriter->index);
fputc(board[i][j], pWriter->index);
}
fputc('\n', pWriter->index);
}
fflush(pWriter->index);
}
return 0;
}
Writer::Writer(FILE* index) :
index(index), kill(false), next_id(1), idx(), boards()
{
InitializeCriticalSection(&lock);
semaphore = CreateSemaphoreW(NULL, 0, LONG_MAX, NULL);
hThread = (HANDLE)_beginthreadex(NULL, 0, output_main, this, 0, NULL);
}
Writer::~Writer()
{
fclose(index);
CloseHandle(hThread);
CloseHandle(semaphore);
}
void Writer::pass(uint32_t curr_id, std::vector<int>& pos)
{
// Spin wait.
while (next_id != curr_id) NOP;
EnterCriticalSection(&lock);
idx.push(curr_id);
boards.push(pos);
ReleaseSemaphore(semaphore, 1, NULL);
++next_id;
LeaveCriticalSection(&lock);
}
void Writer::join()
{
WaitForSingleObject(hThread, INFINITE);
}
void Writer::set_kill()
{
EnterCriticalSection(&lock);
kill = true;
ReleaseSemaphore(semaphore, 1, NULL);
LeaveCriticalSection(&lock);
} | true |
9f645d9407241a57229f318ce639a861a00d5427 | C++ | sgmtec1/23-shock | /shock.ino | UTF-8 | 1,344 | 2.59375 | 3 | [] | no_license | //Open Source
#include <LiquidCrystal_I2C.h> //INCLUSÃO DE BIBLIOTECA
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3, POSITIVE); //ENDEREÇO DO I2C E DEMAIS INFORMAÇÕES
int Led = 8;
int shock = 2;
int buzzer = 3;
int val;
void setup () {
lcd.begin (16,2); //SETA A QUANTIDADE DE COLUNAS(16) E O NÚMERO DE LINHAS(2) DO DISPLAY
lcd.setBacklight(HIGH); //LIGA O BACKLIGHT (LUZ DE FUNDO)
lcd.begin (16,2); //SETA A QUANTIDADE DE COLUNAS(16) E O NÚMERO DE LINHAS(2) DO DISPLAY
lcd.setBacklight(HIGH); //LIGA O BACKLIGHT (LUZ DE FUNDO)
pinMode (Led, OUTPUT);
pinMode (shock, INPUT);
pinMode (buzzer, OUTPUT);
}
void loop () {
Serial.println("OBJETO: ");
lcd.setCursor(0,0); //SETA A POSIÇÃO DO CURSOR
lcd.print("OBJETO: "); //IMPRIME O TEXTO NO DISPLAY LCD
val = digitalRead (shock);
if (val == HIGH ) {
digitalWrite(Led, HIGH);
tone(buzzer, 1000, 1000);
Serial.println("FORA DA POSICAO");
lcd.setCursor(0,1); //SETA A POSIÇÃO DO CURSOR
lcd.print("FORA DA POSICAO "); //IMPRIME O TEXTO NO DISPLAY LCD
} else {
digitalWrite (Led, LOW);
noTone(buzzer);
Serial.println("NA POSICAO CORRETA");
lcd.setCursor(0,1); //SETA A POSIÇÃO DO CURSOR
lcd.print("NA POSICAO CORRETA"); //IMPRIME O TEXTO NO DISPLAY LCD
delay (500);
}
}
| true |
5caf47bce04215dad7b7ed1d8bca908c2f1bffe3 | C++ | Coastchb/cpp_primer_plus | /function/0_varible_args.cpp | UTF-8 | 283 | 2.875 | 3 | [] | no_license | //
// Created by coastcao(操海兵) on 2019-09-03.
//
#include<iostream>
int sum(int a, ...){
int *temp = &a, sum=0;
//++temp;
for (int i = 0; i < a; ++i)
sum+=*temp++;
return sum;
}
int main(){
std::cout<<sum(4, 1, 2, 3, 4)<<std::endl;
return 0;
}
| true |
f2ec5ec6830b6bb75e9dd11780065c8b71df536e | C++ | rarora7777/GAUSS | /src/Base/include/DOF.h | UTF-8 | 3,768 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef DOF_H
#define DOF_H
#include "State.h"
namespace Gauss {
/**
Even baser class
*/
template<typename DataType, unsigned int Property=0>
class DOFBase
{
public:
explicit DOFBase(unsigned int localId) {
m_localId = localId;
m_globalId = localId;
}
~DOFBase() { }
inline void setIds(unsigned int localId, unsigned int globalId) {
m_localId = localId;
m_globalId = globalId;
}
inline unsigned int getNumScalarDOF() {
return m_numScalarDOF;
}
inline unsigned int getNumScalarDOF() const {
return m_numScalarDOF;
}
inline unsigned int getLocalId() const {
return m_localId;
}
inline unsigned int getGlobalId() const {
return m_globalId;
}
inline std::tuple<DataType *, unsigned int> getPtr(const State<DataType> &state, unsigned int offset) {
return state. template getStatePtr<Property>(offset);
}
inline std::tuple<DataType *, unsigned int> getPtr(const State<DataType> &state) {
return state. template getStatePtr<Property>(m_globalId);
}
inline std::tuple<DataType *, unsigned int> getPtr(const State<DataType> &state) const {
return state. template getStatePtr<Property>(m_globalId);
}
virtual inline void offsetGlobalId(unsigned int offset) {
m_globalId += offset;
}
protected:
unsigned int m_localId;
unsigned int m_globalId;
unsigned int m_numScalarDOF;
private:
};
/**
"Base Class" for Degree-Of-Freedom for a physical system
DOFs serve as a reference to memory in the state and can contain methods that manipulate that data. They do not store there own information
*/
template<typename DataType, template<typename A, unsigned int B> class Impl, unsigned int PropertyIndex = 0>
class DOF : public DOFBase<DataType, PropertyIndex>
{
public:
//Do something about this, dofID should be pulled from the state or assigned automatically
//somehow
explicit DOF(unsigned int localId = 0) : DOFBase<DataType, PropertyIndex>(localId), m_dofImpl() {
DOFBase<DataType, PropertyIndex>::m_numScalarDOF = m_dofImpl.getNumScalarDOF();
}
DOF(const DOF &toCopy) : DOFBase<DataType, PropertyIndex>(toCopy), m_dofImpl() {
m_dofImpl = toCopy.m_dofImpl;
}
~DOF() {
}
constexpr unsigned int getIndex() { return PropertyIndex; }
//The t parameter is optional and is used for spacetime degrees of freedom
/*inline unsigned int getNumScalarDOF() const {
return m_dofImpl.getNumScalarDOF();
}
inline unsigned int getLocalId() const {
return m_localId;
}
inline unsigned int getGlobalId() const {
return m_globalId;
}
inline void offsetGlobalId(unsigned int offset) {
m_globalId += offset;
}*/
//inline std::pair<DataType *, unsigned int> getPtr(const State<DataType> &state) const {
// return m_dofImpl.getPtr(state, DOFBase<DataType, PropertyIndex>::m_globalId);
//}
protected:
Impl<DataType, PropertyIndex> m_dofImpl;
//unsigned int m_globalId;
//unsigned int m_localId;
//unsigned int m_numScalarDOF;
private:
};
}
#endif
| true |
5aa7bc5b152648c8eddb8bd6178597016414d343 | C++ | SinoReimu/homework | /hw3/includes/tree.h | UTF-8 | 449 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
#ifndef TREE_H
#define TREE_H
struct TreeNode {
string content;
TreeNode* left;
TreeNode* right;
};
class Tree {
public :
Tree () {
TreeNode *tn = new TreeNode;
tn->left = NULL;
tn->right = NULL;
tn->content = "ROOT";
root = tn;
}
void addLeft (TreeNode*, string);
void addRight (TreeNode*, string);
void showTree (TreeNode*);
TreeNode* root;
};
#endif
| true |
2f4a4235d145d1b6580eae88ecb4d5244a1c4235 | C++ | HarekrushnaPradhan/CS141 | /lab5q23.cpp | UTF-8 | 290 | 3 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
//declare
int i,n;
//ask user for number
cout << "enter the starting number from where you want to countdown to 0" <<endl;
cin >> n;
//countdown till 0
while (n>=0){
cout << n<<endl;
--n;}
cout << "done !!!";
return 0;
}
| true |
06c9f538c2ea3eb4bec7bbedb878c9cf9e14eac8 | C++ | tarundhamor/leetcode-june | /Day 23 - Count Complete Tree Nodes.cpp | UTF-8 | 580 | 2.90625 | 3 | [] | no_license | class Solution {
public:
int countNodes(TreeNode* root) {
if (root == NULL)
return 0;
int height = 0;
int count = 0;
TreeNode *left = root->left;
TreeNode *right = root->left;
while(right != NULL)
{
height++;
left = left->left;
right = right->right;
}
count = (1 << height) - 1;
if (left == NULL)
return 1 + count + countNodes(root->right);
return 1 + count + countNodes(root->left);
}
}; | true |
bce98eb0ad20dc296a7d971525c9f3c9dd1f8ebc | C++ | RontuGeorgiana/POO---tema-1 | /vect.h | UTF-8 | 481 | 2.890625 | 3 | [] | no_license | class vect//clasa pentru citirea si afisarea a n numere complexe
{
int n;//numarul de numere complexe
Complex *obj;//vectorul de numere complexe
public:
vect ();//constructor de declarare
vect (int);//constructor de initializare
vect (const vect &);//constructor de copierre
~vect ();//destructor
void cit_n(int n, Complex *obj);//metoda de citire si scriere a n numere complexe
Complex* get_obj();//furnizarea unui numar complex
};
| true |
cc4df02b7774b90a68dc70de36d53baebe60ebd4 | C++ | lfxgroove/cpplibutil | /json_unstructured.cpp | UTF-8 | 17,837 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "json_unstructured.h"
#include "json.h"
namespace json {
std::string Parser::findKey(JsonStructured::Str const& s) const {
return findKey(s.begin(), s.end());
}
std::string Parser::findKey(JsonStructured::Str::const_iterator start, JsonStructured::Str::const_iterator end) const {
JsonStructured::Str::const_iterator resStart = end, resEnd = end;
for (auto it = start; it != end; ++it) {
// Means we've reached the end of a key: value pair,
// the key didn't start with a " and therefore we
// can't continue
if (*it == ':' && resStart == end) {
throw ParseError{util::format("Could not find a key before the value started, looked in `", std::string{start, it}, "' before encountering the beginning of a value. Keys must be quoted.")};
}
// Means we've reached the end of the object and we can't really do much more.
if (*it == '}' && resStart == end) {
return "";
}
if (*it == '"' && resStart != end && *(it - 1) != '\\') {
resEnd = it;
break;
}
if (*it == '"' && resStart == end) {
resStart = it + 1;
}
}
assert(resEnd > resStart); // This must always hold true for our cast to be valid down here
return std::string{resStart, static_cast<std::string::size_type>(resEnd - resStart)};
}
Object Parser::parseArr(std::string s) {
std::stringstream ss{s};
JsonStructured json{ss};
std::vector<std::string> values = json.lookupArray({}, true);
std::vector<Object> result;
for (auto const& val : values) {
result.push_back(parseHelper(val));
}
return Object{result};
}
Object Parser::parseObj(std::string s) {
Obj obj;
std::stringstream ss{s};
JsonStructured json{ss};
//find the first key in this object
std::string key = findKey(json.data());
if (key == "") {
throw ParseError{util::format("Can't find a key for object in input: `", s, "'. Keys must have quotation marks around them.")};
}
// ptr will be a pointer into data() owned by JsonStructured
char const* ptr;
size_t len;
std::tie(ptr, len) = lookupValue(json, key);
obj[key] = parseHelper(std::string{ptr, len});
// find the rest of the keys in this object
while (true) {
// jump past what we just handled
ptr += len;
JsonStructured::Str const& data = json.data();
key = findKey(data.begin() + (ptr - data.c_str()), data.end());
if (key == "") {
break;
}
std::tie(ptr, len) = lookupValue(json, key);
obj[key] = parseHelper(std::string{ptr, len});
}
return Object{obj};
}
Object Parser::parseString(std::string const& s) {
return Object{util::stripQuotes(s)};
}
Object Parser::parseInt(std::string const& s) {
// this can throw
// perhaps 64bit instead?
int i = util::extract<int>(s);
return Object{i};
}
Object Parser::parseDouble(std::string const& s) {
// this can throw
double d = util::extract<double>(s);
return Object{d};
}
Object Parser::parseBool(std::string const& s) {
if (s == "true") {
return Object{true};
} else {
return Object{false};
}
}
Object Parser::parseHelper(std::string s) {
if (arr(s)) {
return parseArr(s);
}
if (obj(s)) {
return parseObj(s);
}
if (dbl(s)) {
return parseDouble(s);
}
if (i(s)) {
return parseInt(s);
}
if (b(s)) {
return parseBool(s);
}
if (null(s)) {
return Object{NullType()};
}
if (str(s)) {
return parseString(s);
}
throw ParseError{util::format("Encountered unknown token when processing `", s, "'")};
}
size_t Parser::iPos(std::string const& s) const {
if (s.size() < 1) {
return static_cast<size_t>(-1);
}
if (s[0] != '-' && !std::isdigit(s[0])) {
return static_cast<size_t>(-1);
}
for (auto it = s.begin() + 1; it != s.end(); ++it) {
if (!std::isdigit(*it)) {
return it - s.begin() - 1;
}
}
return s.size() - 1;
}
std::tuple<char const*, size_t> Parser::lookupValue(JsonStructured& json, std::string const& key) const {
char const* ptr;
size_t len;
std::tie(ptr, len) = json.lookupPath({key});
// Make sure that we keep the string delimiters so that we can
// properly identify strings if that is needed.
if (*(ptr - 1) == '"') {
JsonStructured::Str const& data = json.data();
if (data.c_str() + data.size() > ptr) {
ptr -= 1;
len += 2;
} else {
// This might imply other things than the
// message says, but this'll have to do for
// now
// TODO: More descriptive error message?
ptrdiff_t byteIndex{data.c_str() + data.size() - ptr};
throw ParseError{util::format("Found beginning of string with no end, at byte `", byteIndex, "'")};
}
}
return std::make_tuple(ptr, len);
}
bool Parser::i(std::string const& s) const {
size_t pos = iPos(s);
if (pos == static_cast<size_t>(-1)) {
return false;
}
return pos == s.size() - 1;
}
bool Parser::dbl(std::string const& s) const {
size_t pos = iPos(s);
if (pos == static_cast<size_t>(-1) || pos == s.size() - 1) {
return false;
}
//123.123e12
if (s[pos + 1] == '.' && s.size() - 1 > pos + 1) {
std::string mid = s.substr(pos + 2);
// this covers 123.123
size_t midPos = iPos(mid);
if (midPos == mid.size() - 1) {
return true;
}
if (midPos == static_cast<size_t>(-1)) {
return false;
}
if (mid[midPos + 1] == 'e' || mid[midPos + 1] == 'E') {
std::string end = mid.substr(midPos + 2);
return iPos(end) == end.size() - 1;
}
}
//123e12
if ((s[pos + 1] == 'e' || s[pos + 1] == 'E') && s.size() - 1 > pos + 1) {
std::string end = s.substr(pos + 2);
return iPos(end) == end.size() -1;
}
return false;
}
bool Parser::str(std::string const& s) const {
if (s.length() < 1) {
return false;
}
if (s[0] != '"') {
return false;
}
for (auto it = s.begin() + 1; it != s.end() - 1; ++it) {
if (*it == '"' && *(it - 1) != '\\') {
return false;
}
}
return s.back() == '"';
}
bool Parser::null(std::string const& s) const {
return s == "null";
}
bool Parser::b(std::string const& s) const {
return s == "true" || s == "false";
}
bool Parser::obj(std::string const& s) const {
return find(s, '{');
}
bool Parser::arr(std::string const& s) const {
return find(s, '[');
}
Object Parser::parse(std::string const& json) {
return Parser{}.parseHelper(json);
}
namespace {
// from https://stackoverflow.com/questions/31320857/how-to-determine-if-a-boostvariant-is-empty
struct IsBlank : boost::static_visitor<bool> {
bool operator()(boost::blank) const { return true; }
template<typename T>
bool operator()(T const&) const { return false; }
};
}
bool Object::blank() const {
return boost::apply_visitor(IsBlank(), value);
}
bool Object::operator==(Object const& rhs) const {
return isEqual<boost::blank, Str, Int, Double, Bool, Arr, Obj>(*this, rhs);
}
bool Object::operator!=(Object const& rhs) const {
return !(*this == rhs);
}
bool Object::addProperty(Path path, Property prop) {
Obj& obj = getOrInsert<Obj>(path);
bool hadProp = obj.find(prop.name) != obj.end();
obj[prop.name] = prop.value;
return hadProp;
}
bool Object::addProperty(Property prop) {
Obj& obj = into<Obj&>();
bool hadProp = obj.find(prop.name) != obj.end();
obj[prop.name] = prop.value;
return hadProp;
}
void Object::push(Path path, Object value) {
Arr& arr = get<Arr>(path);
arr.push_back(value);
}
void Object::push(Object value) {
into<Arr&>().push_back(value);
}
namespace {
template<typename T, typename U>
struct ExtractFromObj : boost::static_visitor<U> {
std::string name{};
ExtractFromObj(std::string const& name) :
name{name} {}
U operator()(T val) const {
return val.at(name);
}
template<typename V>
U operator()(V) const {
throw ObjectError{util::format("Trying to get property from object when object is of type `", util::type_name<T>(), "' and not of type `", util::type_name<U>(), "'")};
}
};
template<typename T, typename U>
struct ExtractFromObjAndAdd : boost::static_visitor<U> {
std::string name{};
bool create{false};
ExtractFromObjAndAdd(std::string const& name) :
name{name} {}
U operator()(T val) const {
if (val.find(name) == val.end()) {
val[name] = Obj();
}
return val.at(name);
}
template<typename V>
U operator()(V) const {
throw ObjectError{util::format("Trying to get property from object when object is of type `", util::type_name<T>(), "' and not of type `", util::type_name<U>(), "'")};
}
};
}
Object& Object::getOrInsert(std::string const& name) {
if (blank()) {
auto val = json::Obj();
val[name] = json::Obj();
value = val;
}
return boost::apply_visitor(ExtractFromObjAndAdd<Obj&, Object&>(name), value);
}
Object const& Object::get(std::string const& name) const {
return boost::apply_visitor(ExtractFromObj<Obj const&, Object const&>(name), value);
}
Object& Object::get(std::string const& name) {
return boost::apply_visitor(ExtractFromObj<Obj&, Object&>(name), value);
}
namespace {
template<typename T, typename U>
struct ExtractFromArr : boost::static_visitor<U> {
int index;
ExtractFromArr(int index) : index{index} {}
U const& operator()(T val) const {
return val.at(index);
}
template<typename V>
U const& operator()(V) const {
throw ObjectError{util::format("Trying to get position `", index, "' from object of type `", util::type_name<V>(), "' when it should be `", util::type_name<U>(), "'")};
}
};
} /* namespace anon */
Object const& Object::get(int index) const {
return boost::apply_visitor(ExtractFromArr<Arr const&, Object const&>(index), value);
}
Object& Object::get(int index) {
return boost::apply_visitor(ExtractFromArr<Arr&, Object&>(index), value);
}
namespace {
struct ExtractKeysFromObj : boost::static_visitor<std::vector<std::string>> {
std::vector<std::string> operator()(Obj const& val) const {
std::vector<std::string> res{};
for (auto const& it : val) {
res.push_back(it.first);
}
return res;
}
template<typename T>
std::vector<std::string> operator()(T val) const {
throw ObjectError{util::format("Trying to get keys for object which isn't of type `json::Obj', but instead is `", util::type_name<T>(), "'")};
}
};
} /* namespace anon */
std::vector<std::string> Object::keys() const {
return boost::apply_visitor(ExtractKeysFromObj(), value);
}
int Object::length() const {
return into<Arr>().size();
}
std::string Object::prettyPrint(int depth /* = 4*/) const {
struct PrettyPrint : boost::static_visitor<std::string> {
int depth;
PrettyPrint(int depth) : depth{depth} {}
std::string operator()(boost::blank) const { return ""; }
std::string operator()(Str const& val) const { return "\"" + val + "\""; }
std::string operator()(NullType const&) const { return "null"; }
std::string operator()(Double const& val) const {
return util::format(val);
}
std::string operator()(Int const& val) const {
return util::format(val);
}
std::string operator()(Bool const& val) const {
if (val) {
return "true";
} else {
return "false";
}
}
std::string operator()(Arr const& val) const {
std::stringstream ss;
ss << "[";
for (unsigned i{0}; i < val.size(); ++i) {
ss << val[i].prettyPrint();
if (i < val.size() - 1) {
ss << ", ";
}
}
ss << "]";
return ss.str();
}
std::string operator()(Obj const& val) const {
std::stringstream ss;
ss << "{\n";
for (auto const& it : val) {
for (int i = 0; i < depth; ++i) {
ss << ' ';
}
ss << "\"" << it.first <<"\": " << it.second.prettyPrint(depth + 2) << ",\n";
}
for (int i = 0; i < depth - 2; ++i) {
ss << ' ';
}
ss << "}";
return ss.str();
}
};
return boost::apply_visitor(PrettyPrint(depth), value);
}
std::string Object::serialize() const {
struct Serialize : boost::static_visitor<std::string> {
std::string operator()(boost::blank) const { return ""; }
std::string operator()(Str const& val) const { return "\"" + val + "\""; }
std::string operator()(NullType const&) const { return "null"; }
std::string operator()(Double const& val) const {
std::string ret;
std::stringstream ss;
ss << val;
ss >> ret;
return ret;
}
std::string operator()(Int const& val) const {
std::string ret;
std::stringstream ss;
ss << val;
ss >> ret;
return ret;
}
std::string operator()(Bool const& val) const {
if (val) {
return "true";
} else {
return "false";
}
}
std::string operator()(Arr const& val) const {
std::stringstream ss;
ss << "[";
for (unsigned i{0}; i < val.size(); ++i) {
ss << val[i].serialize();
if (i < val.size() - 1) {
ss << ",";
}
}
ss << "]";
return ss.str();
}
std::string operator()(Obj const& val) const {
std::stringstream ss;
ss << "{";
for (auto it = val.begin(); it != val.end(); ++it) {
ss << "\"" << it->first << "\":" << it->second.serialize();
auto fwd = it;
fwd++;
if (fwd != val.end()) {
ss << ",";
}
}
ss << "}";
return ss.str();
}
};
return boost::apply_visitor(Serialize(), value);
}
} /* namespace json */
| true |
cb785612de72b522e12a077334d7f8f9302cabc4 | C++ | rakhi2207/C-Learning | /Practice questions/Fibonacci.cpp | UTF-8 | 320 | 3.125 | 3 | [] | no_license | #include<iostream>
using namespace std;
void Fibonacci(int a)
{
int t1=0;
int t2=1;
int b=0;
for(int i=0;i<a;i++)
{
cout<<t1<<"\n";
b=t1+t2;
t1=t2;
t2=b;
}
return;
}
int main(){
int a;
cout<<"Enter a no";
cin>>a;
Fibonacci(a);
return 0;
}
| true |
c3220e4e980f64675d711a9a86177f8f4c687d0e | C++ | Nabil-mubarak/manual-c- | /src/main.cpp | UTF-8 | 887 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
float a,b,hasil;
char aritmatika;
cout << "Selamat datang di program calculator \n \n" ;
//memasukkan input dari user
cout << "Masukkan nilai pertama: ";
cin >> a;
cout << "silakan pilih operator: ";
cin >> aritmatika;
cout << "masukkan nilai kedua: ";
cin >> b;
cout << "\nHasil perhitungan ";
cout << a << " " << aritmatika << " "<< b;
if (aritmatika == '+') {
hasil = a + b;
} else if (aritmatika == '-') {
hasil = a - b;
} else if (aritmatika == '/') {
hasil = a / b;
} else if (aritmatika == '*') {
hasil = a * b;
}
cout << " = " << hasil << endl;
cout << "selesai" << endl;
cout << "jika anda ingin mengulangi lagi silakan tekan ctrl + shift + b";
cin.get();
return 0;
}
| true |
71ad9db3156ae99a762ffcb40ce52edadb577cd4 | C++ | timal75/Ecole42Dev | /piscinec++/j01/ex07/main.cpp | UTF-8 | 1,709 | 2.703125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jblancha <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/11 21:31:58 by jblancha #+# #+# */
/* Updated: 2017/01/11 22:31:10 by jblancha ### ########.fr */
/* */
/* ************************************************************************** */
#include <string>
#include <iostream>
#include <fstream>
int main (int argc, char **argv)
{
std::ifstream input(argv[1]);
std::string output1;
std::ofstream output;
std::string line;
std::string str(argv[2]);
std::string str1(argv[3]);
std::string::size_type n = 0;
if (argc != 4)
{
std::cout << "Wrong Number of Inputs !!" << std::endl;
std::cout <<"usage ./replacestring <filename> <str to be replaced> <str to replace by>\n";
return (1);
}
output1 = argv[1];
output1 += ".replace";
output.open(output1);
if (input.is_open())
{
while (getline(input, line))
{
n = 0;
while ( ( n = line.find( str, n ) ) != std::string::npos )
{
line.replace( n, str.size(), str1 );
n += str1.size ();
}
output << line << std::endl;
}
}
input.close();
output.close();
return (0);
}
| true |
463efb078c42f85bbfe84a9845e78effe57205bf | C++ | thyton/fasterBinPacking | /main.cpp | UTF-8 | 1,403 | 2.78125 | 3 | [] | no_license | #include "header.h"
#include "random.h"
#include "main_helper.h"
int result::N = 0;
int main(int argc , char *argv[])
{
const int RUNS = 50;
vector<vector<double>> sequences;
vector<double> seq_sums;
vector<result> results;
ofstream o;
// prepare random weight sequences
result::N = atoi(argv[1]);
// Uncomment this to run with
get_random_sequences(result::N, RUNS, sequences, seq_sums);
// Uncomment this to run with 10th decimal place, using to compare outputs of optimized and normal versio
// get_random_sequences(result::N, RUNS, 10, sequences, seq_sums);
print_title(result::N);
// First Fit (FF)
make_output_file_funcname("FF", o, result::N);
experiment(sequences, seq_sums, results, first_fit);
print(o, results, "FF");
o.close();
// First Fit Decreasing (FFD)
make_output_file_funcname("FFD", o, result::N);
experiment(sequences, seq_sums, results, first_fit_decreasing);
print(o, results, "FFD");
o.close();
// Best Fit (BF)
make_output_file_funcname("BF", o, result::N);
experiment(sequences, seq_sums, results, best_fit);
print(o, results, "BF");
o.close();
// Best Fit Decreasing (BFD)
make_output_file_funcname("BFD", o, result::N);
experiment(sequences, seq_sums, results, best_fit_decreasing);
print(o, results, "BFD");
o.close();
return 0;
}
| true |
4177ea1679c79a3123e1b9ccbe3eae061e451a84 | C++ | tongnamuu/Algorithm-PS | /B1874/B1874.cpp | UTF-8 | 645 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <string>
using namespace std;
int n;
stack<int>s;
string ans;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
int num;
int max = 0;
for (int i = 0; i < n; ++i) {
cin >> num;
if (num >= max) {
for (int i = max + 1; i <= num; ++i) {
s.push(i);
ans += "+\n";
}
max = num;
s.pop();
ans += "-\n";
}
if (num < max) {
while (!s.empty() && s.top() != num) {
s.pop();
ans += "-\n";
}
if (s.empty()||s.top() != num) {
cout << "NO" << '\n';
return 0;
}
s.pop();
ans += "-\n";
}
}
cout << ans << '\n';
} | true |
bc23a2ea0a538746702bff80c3ad013122e3f3c4 | C++ | datmemerboi/CPP-pbl | /Typecasting/Q4.cpp | UTF-8 | 379 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void GetVowelCount(char word[]){
int count = 0;
for (int i = 0; i < strlen(word); ++i)
{
if( word[i]=='a' || word[i]=='e' || word[i]=='i' || word[i]=='o' || word[i]=='u')
++count;
}
if( count>2 ){
cout<<word<<"\t--"<<count<<endl;
}
}
int main()
{
char input[100];
while(1){
cin>>input;
GetVowelCount(input);
}
} | true |
cf7539b84cd325e2115f44bd4157382d1d72a1b7 | C++ | oajerd/CIS375-Project | /CIS375Project/login.h | UTF-8 | 1,655 | 3.578125 | 4 | [] | no_license | #pragma once
#include<string>
#include <iostream>
bool checkPassword(std::string p1, std::string p2) {
if (p1 == p2) { return true; }
else { return false; }
}
void login() {
char choice;
std::cout << "\nA.Director\nB.Manager\nC.Operator\nD.Crew " << std::endl;
std::cin >> choice;
switch (choice)
{
case('A'): case('a'):
{
std::string pass = "Director123";
std::string password;
while (true) {
std::cout << "Please Enter Password: ";
std::cin >> password;
bool check = checkPassword(pass, password);
if (check) {
std::cout << "Success!";
break;
}
else
std::cout << "Try again.";
}
break;
}
case('B'): case('b'):
{
std::string pass = "Manager123";
std::string password;
while (true) {
std::cout << "Please Enter Password: ";
std::cin >> password;
bool check = checkPassword(pass, password);
if (check) {
std::cout << "Success!";
break;
}
else
std::cout << "Try again.";
}
break;
}
case('C'): case('c'):
{
std::string pass = "Operator123";
std::string password;
while (true) {
std::cout << "Please Enter Password: ";
std::cin >> password;
bool check = checkPassword(pass, password);
if (check) {
std::cout << "Success!";
break;
}
else
std::cout << "Try again.";
}
break;
}
case('D'): case('d'):
{
std::string pass = "Crew123";
std::string password;
while (true) {
std::cout << "Please Enter Password: ";
std::cin >> password;
bool check = checkPassword(pass, password);
if (check) {
std::cout << "Success!";
break;
}
else
std::cout << "Try again.";
}
break;
}
}
}
| true |
e7ac22c126ad09e33bef3c1e39998f9d4331b48d | C++ | danilotuzita/programacao-cientifica | /DataStructures/DataStructures/Item.hpp | UTF-8 | 714 | 3.515625 | 4 | [] | no_license | #pragma once
#include <string>
template <class T>
class Item
{
private:
T value;
Item* previous;
public:
Item();
~Item();
T getValue() const;
Item *getPrevious() const;
void setValue(T value);
void setPrevious(Item *previous);
};
template < class T >
Item<T>::Item()
{
value = T();
previous = nullptr;
}
template<class T>
Item<T>::~Item() {}
template < class T >
T Item<T>::getValue() const
{
return value;
}
template Item<int>::Item();
template < class T >
void Item<T>::setValue(T value)
{
Item::value = value;
}
template < class T >
Item<T>* Item<T>::getPrevious() const
{
return previous;
}
template < class T >
void Item<T>::setPrevious(Item *previous)
{
Item::previous = previous;
}
| true |
8004f87d3c4d2e064ddbb19050209004c03fd4d1 | C++ | Marbax/second_exam_cpp | /Entity.h | UTF-8 | 1,804 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef ENTITY_H
#define ENTITY_H
#include "SFML-2.5.1/include/SFML/Graphics.hpp"
#include "SFML-2.5.1/include/SFML/Window.hpp"
#include "SFML-2.5.1/include/SFML/System.hpp"
#include <iostream>
//------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------БАЗОВЫЙ_КЛАСС_ОБЬЕКТА-------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------
class Entity
{
private:
protected:
float posX = 0.0f, posY = 0.0f; // текущая позиция обьекта
int spriteW = 0, spriteH = 0, sprite_posX = 0, sprite_posY = 0; // высота,ширина, координаты спрайта по x, по y
bool life = 1, isMove = 0, onGround = 0, sitting = 0; // доп состояния
sf::Texture texture;
sf::Sprite sprite;
sf::String name = "NONE";
public:
// явное отключение конструктора по умолчанию
Entity() = delete;
Entity(const float &posX, const float &posY, sf::Image &image, sf::String name);
virtual ~Entity();
virtual sf::FloatRect getSpriteRect();
virtual void setPosX(const float &posX);
virtual void setPosY(const float &posY);
virtual const float &getPosX() const;
virtual const float &getPosY() const;
virtual void setMove(const bool &isMove);
//virtual void move(const float &boostX, const float &boostY, const float &dt) = 0;
virtual void update(const float &dt) = 0;
virtual void setPosition() = 0;
virtual void render(sf::RenderTarget *target) = 0;
};
#endif | true |
c3f05859c3ce9307ad169823d499e6c89c982e39 | C++ | ZaynF/lab5 | /class.cpp | UTF-8 | 1,025 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<cstdlib>
#include"class.h"
using namespace std;
HugeInt::HugeInt(int a){
int p[1000]={0};
string s;
for(int i=0;a!=0;i++){
ans[i]=a%10;
a=a/10;
}
}
HugeInt::HugeInt(string b){
for(int i=0;i<1000;i++){
ans[i]=(b[i]-48)%10;
}
}
HugeInt HugeInt::operator+(HugeInt add){
HugeInt m;
for(int i=1000-1;i>=0;i--){
m.ans[i]=ans[i]+add.ans[i];
}
for(int j=0;j<1000;j++){
m.ans[j+1]+=m.ans[j]/10;
m.ans[i]%=10;
}
return m;
}
HugeInt HugeInt::operator-(HugeInt sub){
HugeInt n;
for(int i=0;i<1000;i++){
n.ans[i]=ans[i]-sub.ans[i];
}
for(int j=0;j<1000-1;j++){
if(n.ans[i]<0){
n.ans[i+1]--;
n.ans[i]+=10;
}
}
return n;
}
ostream &operator<<(ostream& out,const HugeInt &w){
for(int i=1000-1;i>=0;i--){
if(w.ans[i]!=0){
for(;i>=0;i--){
out<<w.ans[i];
}
}
}
return out;
}
istream &operator>>(istream& in,HugeInt &w){
int q[1000];
string l;
in>>l;
for(int i=0;i<l.size();i++){
w.ans[i]=(l[i]-48)%10;
}
return in;
}
| true |
aa98c8affe530eb7de4b2269c1b8a09ee8b40539 | C++ | voxel-tracer/riow | /vren/rawdata.h | UTF-8 | 2,530 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <vector>
#include <fstream>
#include <stdexcept>
#include <cstring>
#include "vec3.h"
#include <yocto/yocto_cli.h>
class RawData {
protected:
std::vector<vec3> data;
unsigned width;
unsigned height;
public:
RawData(unsigned width, unsigned height) : width(width), height(height) {
data.resize(width * height);
}
RawData(std::string filename) {
std::fstream in(filename, std::ios::in | std::ios::binary);
const char* HEADER = "REF_00.01";
int headerLen = strlen(HEADER) + 1;
char* header = new char[headerLen];
in.read(header, headerLen);
if (strcmp(HEADER, header) != 0) {
yocto::print_fatal("invalid header: " + std::string(header));
}
in.read((char*)&width, sizeof(unsigned));
in.read((char*)&height, sizeof(unsigned));
data.resize(width * height);
in.read((char*)&data[0], sizeof(vec3) * width * height);
in.close();
}
void set(unsigned x, unsigned y, const vec3& v) {
data[y * width + x] = v;
}
void saveToFile(std::string filename) const {
std::fstream out(filename, std::ios::out | std::ios::binary);
const char* HEADER = "REF_00.01";
out.write(HEADER, strlen(HEADER) + 1);
out.write((char*)&width, sizeof(unsigned));
out.write((char*)&height, sizeof(unsigned));
out.write((char*)&data[0], sizeof(vec3) * width * height);
out.close();
}
double rmse(const RawData& ref) const {
if (ref.width != width || ref.height != height)
throw std::invalid_argument("ref image has a different size");
double error = 0.0;
for (auto i = 0; i < width*height; i++) {
const vec3 f = data[i];
const vec3 g = ref.data[i];
for (auto c = 0; c < 3; c++) {
error += (f[c] - g[c]) * (f[c] - g[c]) / 3.0;
}
}
return sqrt(error / (width * height));
}
bool findFirstDiff(const RawData& ref, yocto::vec2i &coord) const {
if (ref.width != width || ref.height != height)
throw std::invalid_argument("ref image has a different size");
for (auto i = 0; i < width * height; i++) {
const vec3 f = data[i];
const vec3 g = ref.data[i];
if (f != g) {
coord.x = i % width;
coord.y = i / width;
return true;
}
}
return false;
}
}; | true |
e6fdc94b725971c37fb06fab3c743cc6d8d6d8b8 | C++ | Peter-Zheng-Sp/STL | /06_algorithms/07_copy/01_copy-overlap.cpp | UTF-8 | 2,610 | 3.59375 | 4 | [
"MIT"
] | permissive |
/*
* Date:2021-08-18 14:32
* filename:01_copy-overlap.cpp
*
*/
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
using namespace std;
template <class T>
struct display {
void operator() (const T& x) {
cout << x << ' ';
}
};
int main() {
{
int ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
cout << "原串:";
for_each(ia, ia + 9, display<int>());
cout << endl;
//以下 输出区间的终点与输入区间重叠,没有问题
copy(ia + 2, ia + 7, ia);
cout << "copy(ia + 2, ia + 7, ia):";
for_each(ia, ia + 9, display<int>());
cout << endl;
}
cout << endl;
{
int ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
cout << "原串:";
for_each(ia, ia + 9, display<int>());
cout << endl;
//以下,输出区间的起点与输入区间重叠,可能会有问题
copy(ia + 2, ia + 7, ia + 4);
cout << "copy(ia + 2, ia + 7, ia + 4):";
for_each(ia, ia + 9, display<int>());
cout << endl;
//本例结果正确,因为调用的copy算法使用memmove()执行实际复制操作
}
cout << endl;
{
cout << "deque test:" << endl;
int ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
deque<int> id(ia, ia + 9);
deque<int>::iterator first = id.begin();
deque<int>::iterator last = id.end();
++++first; //advance(first, 2);
cout << "advance(first, 2):";
cout << *first << endl; //2
----last; //advance(last, -2);
cout << "advance(last, -2):";
cout << *last << endl; //7 不是6
deque<int>::iterator result = id.begin();
cout << *result << endl;// 第一个元素
cout << endl << "before copy:";
for_each(id.begin(), id.end(), display<int>());
cout << endl;
//以下,输出区间的终点与输入区间重叠,没有问题
copy(first, last, result);
cout << "copy(first, last, result):";
for_each(id.begin(), id.end(), display<int>());
cout << endl;
}
cout << endl;
{
cout << "vector test:" << endl;
int ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
std::vector<int> id(ia, ia + 9);
vector<int>::iterator first = id.begin();
vector<int>::iterator last = id.end();
++++first; //advance(first, 2);
cout << "advance(first, 2):";
cout << *first << endl; //2
----last; //advance(last, -2);
cout << "advance(last, -2):";
cout << *last << endl; //7 不是6
vector<int>::iterator result = id.begin();
advance(result ,4);
cout << *result << endl;
//以下,输出区间的终点与输入区间重叠,可能有问题
copy(first, last, result);
cout << "copy(first, last, result):";
for_each(id.begin(), id.end(), display<int>());
cout << endl;
}
}
| true |
d3f8f5e05814cfd331bf25b82e09b0d346b4806b | C++ | EYH0602/dcash | /Database.cpp | UTF-8 | 7,183 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "Database.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
#include <mysql/mysql.h>
#include "ClientError.h"
#include "StringUtils.h"
using namespace std;
Database::Database(string un, string pwsd, string host, int port, string name, string key) {
this->stripe_secret_key = key;
// init db
this->db = mysql_init(NULL);
this->db = mysql_real_connect(
this->db, host.c_str(), un.c_str(), pwsd.c_str(), name.c_str(), port, NULL, 0
);
if (!this->db) {
throw "DB Connection Faild.";
}
// create tables as needed
this->applyQuery(this->getCreateTableSQL("users"));
this->applyQuery(this->getCreateTableSQL("transfers"));
this->applyQuery(this->getCreateTableSQL("deposits"));
}
string Database::getCreateTableSQL(string table_name) {
string sql;
if (table_name == "users") {
sql = "CREATE TABLE IF NOT EXISTS `users` ("
" `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,"
" `username` varchar(255) NOT NULL,"
" `password` varchar(255) NOT NULL,"
" `user_id` varchar(255) NOT NULL COMMENT 'randomized string',"
" `email` varchar(255) NOT NULL DEFAULT '',"
" `balance` bigint(20) NOT NULL DEFAULT 0,"
" `create_time` timestamp NOT NULL COMMENT 'timestamp when the user was first created',"
" `update_time` timestamp NOT NULL COMMENT 'timestamp when the user info is most recently updated',"
" PRIMARY KEY (`id`), INDEX(`username`), INDEX(`create_time`)"
") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='Account info of users'";
} else if (table_name == "transfers") {
sql = "CREATE TABLE IF NOT EXISTS `transfers` ("
" `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,"
" `from` varchar(255) NOT NULL,"
" `to` varchar(255) NOT NULL,"
" `amount` bigint(20) NOT NULL,"
" `create_time` timestamp NOT NULL COMMENT 'timestamp when the transfer was made',"
" PRIMARY KEY (`id`), INDEX(`from`), INDEX(`create_time`)"
" ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='Transfer records'";
} else if (table_name == "deposits") {
sql = "CREATE TABLE IF NOT EXISTS `deposits` ("
" `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,"
" `to` varchar(255) NOT NULL,"
" `amount` bigint(20) NOT NULL,"
" `stripe_charge_id` varchar(255) NOT NULL,"
" `create_time` timestamp NOT NULL COMMENT 'timestamp when the deposit was made',"
" PRIMARY KEY (`id`), INDEX(`to`), index(`create_time`)"
" ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='Deposit records'";
} else {
throw ClientError::forbidden();
}
return sql;
}
vector<vector<string>> Database::applyQuery(string query) {
vector<vector<string>> res;
int rnt = mysql_query(this->db, query.c_str());
if (rnt != 0) {
throw "MySQL Query ERROR: " + to_string(rnt);
}
// store the results of this query
MYSQL_RES *rst = mysql_use_result(this->db);
// if there is not return result for this query,
// just exist
if (!rst) {
return res;
}
// fetch the query results
MYSQL_ROW sql_row;
while (sql_row = mysql_fetch_row(rst), sql_row) {
vector<string> row;
for (size_t j = 0; j < mysql_num_fields(rst); j++) {
row.push_back(string(sql_row[j]));
}
res.push_back(row);
}
mysql_free_result(rst);
return res;
}
int Database::loginUser(User *user, string username, string password) {
string sql =
"SELECT user_id, email, balance, password FROM users WHERE"
" username = '" + username + "'";
StringUtils string_util;
int rnt;
vector<vector<string>> rst = this->applyQuery(sql);
if (rst.size() > 1) {
throw "DB Error: User not unique.";
}
// down searching
user->username = username;
user->password = password;
if (rst.size() == 0) {
rnt = 0;
user->user_id = string_util.createUserId();
user->email = "";
user->balance = 0;
this->addUser(user);
} else {
rnt = 1;
user->user_id = rst[0][0];
user->email = rst[0][1];
user->balance = atoi(rst[0][2].c_str());
}
if (rnt != 0 && rst[0][3] != password) {
rnt = 2;
}
return rnt;
}
bool Database::hasUser(string username) {
string sql = "SELECT COUNT(username) FROM users WHERE username = '" + username + "'";
vector<vector<string>> rst = this->applyQuery(sql);
return rst[0][0] == "1";
}
int Database::updateBalance(std::string username, int amount) {
string time = this->getCurrentTimestamp();
string sql =
"UPDATE users SET"
" update_time = '" + time + "',"
" balance = balance + " + to_string(amount) +
" WHERE username = '" + username + "'";
this->applyQuery(sql);
sql = "SELECT balance FROM users WHERE username = '" + username + "'";
vector<vector<string>> rst = this->applyQuery(sql);
return atoi(rst[0][0].c_str());
}
void Database::updateEmail(User *user) {
string sql =
"UPDATE users SET"
" email = '" + user->email + "', "
" update_time = '" + this->getCurrentTimestamp() + "'"
" WHERE username = '" + user->username + "'";
this->applyQuery(sql);
}
void Database::addUser(User *user) {
string time = this->getCurrentTimestamp();
string sql =
"INSERT INTO users"
" (username, password, user_id, create_time, update_time) "
"VALUES"
" ('" + user->username + "', '" + user->password + "', '" + user->user_id + "', '"
+ time + "', '" + time+ "')";
this->applyQuery(sql);
}
void Database::addTransfer(Transfer *tr) {
string time = this->getCurrentTimestamp();
string sql =
"INSERT INTO transfers"
" (`from`, `to`, amount, create_time) "
"VALUES"
" ('" + tr->from + "', '" + tr->to+ "', '" + to_string(tr->amount) + "', '" + time + "')";
this->applyQuery(sql);
}
void Database::addDeposit(Deposit *dp) {
string time = this->getCurrentTimestamp();
string sql =
"INSERT INTO deposits"
" (`to`, amount, stripe_charge_id, create_time) "
"VALUES"
" ('" + dp->to + "', '" + to_string(dp->amount) + "', '" + dp->stripe_charge_id + "', '" + time + "')";
this->applyQuery(sql);
}
vector<string> Database::getUserInfo(string username) {
string sql = "SELECT * FROM users WHERE `username` = '" + username + "'";
return this->applyQuery(sql)[0];
}
vector<vector<string>> Database::getTransferHistory(string from) {
string sql = "SELECT `from`, `to`, amount FROM transfers WHERE `from` = '" + from + "'";
return this->applyQuery(sql);
}
vector<vector<string>> Database::getDepositHistory(string to) {
string sql = "SELECT `to`, amount, stripe_charge_id FROM deposits WHERE `to` = '" + to + "'";
return this->applyQuery(sql);
}
string Database::getCurrentTimestamp() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
return string(buf);
}
Database::~Database() {
mysql_close(this->db);
for (auto kv: this->auth_tokens) {
delete kv.second;
}
}
| true |
d62fe0cd4275197a7b52eb87f067d566922e97b8 | C++ | Godongwon/Dungreed | /팀포폴/DungreedProject/Object/Item/AllItemList.cpp | UHC | 2,446 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "AllItemList.h"
void AllItemList::init_weaponKeysAll()
{
_itemKeys.push_back("۶콺");
_itemKeys.push_back("");
_itemKeys.push_back("");
_itemKeys.push_back("ܰ");
_itemKeys.push_back("б");
_itemKeys.push_back("ġ");
}
void AllItemList::delete_weaponKeysAll()
{
auto iter = _itemKeys.begin();
for (;iter != _itemKeys.end();)
{
iter = _itemKeys.erase(iter);
}
swap(_itemKeys, vItemKey());
}
Item * AllItemList::make_item(string strKey)
{
Item * item = nullptr;
//
if (strKey.compare("۶콺") == 0) { item = new Gladius; }
else if (strKey.compare("") == 0) { item = new Jukdo; }
else if (strKey.compare("") == 0) { item = new LongSword; }
else if (strKey.compare("ܰ") == 0) { item = new ShortSword; }
else if (strKey.compare("б") == 0) { item = new Mace; }
else if (strKey.compare("ġ") == 0) { item = new WarHammer; }
// °
else if (strKey.compare("") == 0) { item = new Coin; }
else if (strKey.compare("") == 0) { item = new GoldBar; }
else if (strKey.compare("") == 0) { item = new Fairy; }
if (item != nullptr) { item->init(); }
return item;
}
Item * AllItemList::make_item_toField(string strKey, POINT center)
{
Item * item = nullptr;
item = make_item(strKey);
image image = item->get_item_img_field();
RECT rect = RectMakeCenter(center.x, center.y,
image.getWidth(), image.getHeight());
item->set_item_rect(rect);
return item;
}
void AllItemList::push_itemList(Item * item)
{
_itemList.push_back(item);
}
void AllItemList::delete_itemListAll()
{
auto iter = _itemList.begin();
for (;iter != _itemList.end(); )
{
iter = _itemList.erase(iter);
}
swap(_itemList, vItem());
}
void AllItemList::update_itemList()
{
auto iter = _itemList.begin();
for (;iter != _itemList.end();iter++)
{
(*iter)->update();
}
}
void AllItemList::draw_itemList()
{
auto iter = _itemList.begin();
for (;iter != _itemList.end();iter++)
{
if ((*iter)->get_kinditem() == GAIN)
{
(*iter)->frameRender(getMemDC());
}
else
{
(*iter)->render();
}
}
}
AllItemList::AllItemList()
{
}
AllItemList::~AllItemList()
{
}
HRESULT AllItemList::init()
{
init_weaponKeysAll();
return S_OK;
}
void AllItemList::release()
{
delete_weaponKeysAll();
}
void AllItemList::update()
{
}
void AllItemList::render()
{
}
| true |
efa5f68a21294a6b4b242ba0e408b7332c7266d3 | C++ | z-Endeavor/OpenJudge-NOI | /1.4 编程基础之逻辑表达式与条件分支/20 求一元二次方程的根/20-1.cpp | UTF-8 | 599 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main(){
double a, b, c;
cin>>a>>b>>c;
if (b*b == 4*a*c) {
if(b == 0) printf("x1=x2=%.5f", b / (2*a));
else printf("x1=x2=%.5f", -b / (2*a));
} else if (b*b > 4*a*c) {
printf("x1=%.5f;x2=%.5f", (-b + sqrt(b*b-4*a*c))/(2*a), (-b - sqrt(b*b-4*a*c))/(2*a));
} else {
if(b == 0) printf("x1=%.5f+%.5fi;x2=%.5f-%.5fi", b / (2*a), sqrt(4*a*c-b*b) / (2*a), b / (2*a), sqrt(4*a*c-b*b) / (2*a));
else printf("x1=%.5f+%.5fi;x2=%.5f-%.5fi", -b / (2*a), sqrt(4*a*c-b*b) / (2*a), -b / (2*a), sqrt(4*a*c-b*b) / (2*a));
}
return 0;
}
| true |
7c4b745f26ed7176817fa77d427af6facb742f8a | C++ | Sun-Yi-Heng/MyAlgorithmPractice | /Q206.cpp | GB18030 | 920 | 3.453125 | 3 | [] | no_license | //
// Created by һ on 2020/3/21.
// Q206ת
//
#include "util.h"
class Solution {
public:
/**
* ת
* ʱ临ӶO(n),ռ临ӶO(1)
*/
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *n1 = head, *n2 = head->next;
n1->next = NULL;
while (n2 != NULL) {
ListNode *n3 = n2->next;
n2->next = n1;
n1 = n2;
n2 = n3;
}
return n1;
}
/**
* ݹ鷴ת
* ʱ临ӶȺͿռ临ӶȶΪO(1)
*/
ListNode* reverseList1(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* p = reverseList1(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
| true |
502c4ebe9806268f98ab37146bff2cc5575b0f8d | C++ | Rijul1204/Algorithm_ACM | /Source_Code/MST/Krushkal's/1147 Heavy Cycle edge.cpp | UTF-8 | 915 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
using namespace std;
struct edge{
int u;
int v;
int w;
};
edge edges[31000],select1[31000];
int pre[11000],n,m;
int find(int x){
if(pre[x]==x) return x;
return pre[x]=find(pre[x]);
}
bool comp(edge a,edge b){
return a.w<b.w;
}
void set(int n){
for(int i=0;i<=n;i++){
pre[i]=i;
}
}
int main(){
int i,j,k,l;
//freopen("in.txt","r",stdin);
while(scanf("%d %d",&n,&m)==2){
if(!n&&!m) break;
set(n);
for(i=0;i<m;i++){
scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].w);
}
sort(edges,edges+m,comp);
j=0;
for(i=0;i<m;i++){
k=find(edges[i].u); l=find(edges[i].v);
if(k!=l){
pre[k]=l;
}
else select1[j++]=edges[i];
}
sort(select1,select1+j,comp);
if(j==0){
printf("forest\n");
continue;
}
for(i=0;i<j;i++){
if(i>0) printf(" ");
printf("%d",select1[i].w);
}
printf("\n");
}
return 0;
} | true |
1bf36c01e9b07931c9df1b60f57dad4a3fdcae56 | C++ | Indidev/cornEngine | /control/util/Log.h | UTF-8 | 1,099 | 2.78125 | 3 | [] | no_license | #ifndef LOG_H
#define LOG_H
#include <QString>
#include <iostream>
#include <stdlib.h>
using std::cout;
using std::cerr;
using std::endl;
/**
* @brief Used for printing log messages
* TODO: add function to log in file(Log::f)
*/
class Log
{
public:
/**
* @brief d Print message on screen only when in debug mode
* @param tag preferable the classpath
* @param message message
* @param funcName function the message is thrown from (opt)
*/
static void d(QString tag, QString message, QString funcName = "");
/**
* @brief e Print an error message
* @param tag preferable the classpath
* @param message message
* @param funcName function the message is thrown from (opt)
*/
static void e(QString tag, QString message, QString funcName = "");
/**
* @brief v Print a verbose message
* @param tag preferable the classpath
* @param message message
* @param funcName function the message is thrown from (opt)
*/
static void v(QString tag, QString message, QString funcName = "");
};
#endif // LOG_H
| true |
7e460febd4bb90a2228eb89538678da5c70888bf | C++ | Aschen/cutebox-public | /sql/Database.cpp | UTF-8 | 1,244 | 2.625 | 3 | [] | no_license | #include "Database.hh"
#include <QStringList>
#include <QSqlQuery>
#include <QSqlError>
#include "Debug.hh"
Database::Database()
{
}
Database::~Database()
{
if (m_db.isOpen())
m_db.close();
}
bool Database::initDatabase(const QString & databaseName)
{
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(databaseName);
if ( ! m_db.open())
{
DEBUG("Unable to open database", true);
return false;
}
return true;
}
bool Database::createTables()
{
using Table = QPair<QString, QString>;
bool ret = true;
QList<Table> tables;
QStringList existingTables = m_db.tables();
tables.push_back(Table("users", "(id integer primary key, email varchar, password varchar)"));
tables.push_back(Table("files", "(id integer primary key, user_id integer, filename varchar, filepath varchar)"));
QSqlQuery q;
for (const Table & table : tables)
{
if (existingTables.contains(table.first))
continue;
if ( ! q.exec ("create table " + table.first + table.second))
{
DEBUG("Query error :" << q.lastError().text(), true);
ret = false;
}
}
return ret;
}
| true |
023a57645fc62b17ee0e6ffb74e55821b6782bc3 | C++ | dungna29/PT15306-UD-SOF307 | /PT15306_UD_SOF307/PT15306_UD_SOF307/BAI_2.5_CacThuatToanTimKiem/Main.cpp | UTF-8 | 1,320 | 3.515625 | 4 | [] | no_license | #include <stdio.h>
int getMax(int a[], int n)
{
int max = a[0];//Coi giá trị ở index 0 là số lớn nhất
for (int i = 1; i < n; i++)
{
if (max < a[i])//Nếu max nhỏ hơn giá trị trong mảng thì gán lại cho max
{
max = a[i];
}
}
return max;
}
int getMin(int a[], int n)
{
int min = a[0];
for (int i = 1; i < n; i++)
{
if (min > a[i])
{
min = a[i];
}
}
return min;
}
//Tìm kiếm tuần tự vét cạn(Exhaustive Linear)
// n là điều kiện dừng vòng lặp
int LinearExhaustive(int a[], int n, int x) {
for (int i = 0; i < n; i++) {
if (a[i] == x) {
return i;
}
}
return -1;
}
//Tìm kiếm tuần tự lính canh (Sentinel Linear)
int LinearSentinel(int a[], int n, int x) {
a[n] = x;
for (int i = 0; i < n; i++) {
if (a[i] == x) {
return i;
}
}
return -1;
}
int main() {
int n;
printf("Nhap so luong phan tu: ");
scanf_s("%d", &n);
int* a = new int[n];
for (int i = 0; i < n; i++)
{
printf("Nhap a[%d]: ", i);
scanf_s("%d", &a[i]);
}
int x;
printf("Nhap gia tri phan tu can tim kiem: ");
scanf_s("%d", &x);
int i = LinearSentinel(a, n, x);
if (i == -1) {
printf("Khong tim thay x trong mang A\n");
}
else {
printf("Vi tri x trong mang A la: %d\n", i + 1);
//Tại sao lại xuất i+1 ở đây
}
return 0;
} | true |
4bf40415dadd34802b68d6fc27bf312fa91448a0 | C++ | CLAYouX/codeForLeet | /121_maxProfit.cpp | UTF-8 | 799 | 3 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<cmath>
#include<vector>
#include<iterator>
#include<limits>
#include<algorithm>
#include<map>
#include<utility>
#include<set>
#include<unordered_map>
#include<stack>
#include<queue>
#include<unordered_set>
#include<numeric>
using namespace std;
int maxProfit(vector<int>& prices);
int main() {
vector<int> prices = {7,1,5,3,6,4};
cout << maxProfit(prices) << endl;
return 0;
}
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<int> leftMin(n);
leftMin[0] = prices[0];
for (int i = 1; i < n; ++i) {
leftMin[i] = min(leftMin[i-1], prices[i]);
}
int maxProfit = 0;
for (int i = 0; i < n; ++i) {
maxProfit = max(maxProfit, prices[i]-leftMin[i]);
}
return maxProfit;
} | true |
df18d1aa202aed7b3f95c9a17b7b9d5d83236cf3 | C++ | mertfozzy/Gym-Management-Software | /Gym Software v2.cpp | UTF-8 | 21,426 | 2.84375 | 3 | [] | no_license | /*
Beykoz University - Computer Enginerring
Name: Mert Altuntas
ID : 1804010005
For Login System;
username = "Mert"
password = "1234"
*/
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
using namespace std;
int main();
class Credential {
public:
void payment_methods() {
system("cls");
printf("\n=============================================================\n");
printf("\n\n\t\tPAYMENT METHODS AND DISCOUNTS\n\n");
printf("\n\tA- Fitness / Normal Membership : 1 Mounth (5 days a week)- 20$");
printf("\n\tB- Fitness / Normal Membership : 1 Mounth (3 days a week)- 15$");
printf("\n\tC- Fitness / Student Discount : 1 Mounth (3 days a week)- 10$\n");
printf("\n\tD- Swimming / Normal Membership : 1 Mounth (5 days a week)- 25$");
printf("\n\tE- Swimming / Normal Membership : 1 Mounth (3 days a week)- 20$");
printf("\n\tF- Swimming / Student Discount : 1 Mounth (3 days a week)- 15$\n");
printf("\n\tG- Fitness and Swimming / Normal Membership : 1 Mounth (5 days a week)- 40$");
printf("\n\tH- Fitness and Swimming / Normal Membership : 1 Mounth (3 days a week)- 30$");
printf("\n\tI- Fitness and Swimming / Student Discount : 1 Mounth (3 days a week)- 20$");
printf("\n\n=============================================================\n\n");
printf("Press any key to return to main menu..\n");
getch();
system("cls");
main();
}
void signupFunction() {
string username;
string password;
system("cls");
printf("\nChoose an username : \n");
scanf("%s", & username);
printf("Choose a numeric password : \n"),
scanf("%s", & password);
printf("\n ***Your account ready to use. Please go back.*** \n");
loginFunction();
}
//--------------------------------------------------------------------------------------------------------------------------
void loginFunction() {
system("cls");
char username[200] = "Mert";
char password[200] = "1234";
char userName[200];
char passWord[200];
tekrar:
printf("\nPlease enter username: \t");
scanf("%s", & userName);
printf("\nPlease enter numeric password : ");
scanf("%s", & passWord);
if (strcmp(username, userName) == 0 && strcmp(password, passWord) == 0) {
printf("\n\nLogin successful. Press any key to continue.\n");
//Access granted ;
getch();
x:
system("cls");
int secim2;
printf("\n=============================================================\n");
printf("\n\n\t\tMEMBER MANAGEMENT");
printf("\n\n\tPlease choose what do you want : ");
printf("\n\t1.Delete a member.");
printf("\n\t2.View list of all members.");
printf("\n\n=============================================================\n\n");
printf("\n\n\tENTER YOUR CHOICE:\t");
scanf("%d", & secim2);
if (secim2 == 2) //displaying members.txt on screen*****************************************************************
{
system("cls");
FILE * dosya;
char character;
dosya = fopen("MemberList.txt", "r");
if (dosya != NULL) {
character = fgetc(dosya);
while (character != EOF) {
printf("%c", character);
character = fgetc(dosya);
}
}
/* actually i wanted to use this method but its not seen good :(
system ("cls");
FILE * dosya;
char isimler [500][30], soyisimler [500][30], branchs[500][30], options[500][10];
int i=0;
dosya = fopen("MemberList.txt" , "r");
if(dosya!=NULL)
{
while(!feof(dosya))
{
fscanf(dosya,"%s %s %s %s",&isimler[i], &soyisimler[i], &branchs[i] );
printf("%s %s : %s - Option %s\n",isimler[i], soyisimler[i], branchs[i]);
}
}
*/
else {
printf("\nFile does not exist. Try Again.");
goto x;
}
fclose(dosya);
printf("\nPress any key to return to the main menu.");
getch();
system("cls");
main();
} else if (secim2 == 1) //deleting member according to name***********************************************************************
{
FILE * dosya;
char isimler[30], soyisimler[30], branchs[30], options[10];
char mem[20], adrs[25], id[30];
int ag, cono, count = 0;
FILE * fp;
dosya = fopen("Memberlist.txt", "r");
fp = fopen("NewMemberlist.txt", "w");
printf("\nEnter the name of member: \n");
getchar();
gets(mem);
while (!feof(dosya)) {
fscanf(dosya, "%s%s%s", & isimler, & soyisimler, & branchs);
if (strcmp(isimler, mem) != 0) {
fprintf(fp, "%s %s %s\n", isimler, soyisimler, branchs);
} else if (strcmp(isimler, mem) == 0) {
printf("\nDetails of the deleted member is:\n");
printf("Name : %s\nSurname : %s\nBranch : %s\n", isimler, soyisimler, branchs);
} else {
printf("\nPlease enter the correct details\n");
}
}
fclose(dosya);
fclose(fp);
dosya = fopen("Memberlist.txt", "w");
fp = fopen("NewMemberlist.txt", "r");
while (!feof(fp)) {
fscanf(fp, "%s %s %s", & isimler, & soyisimler, & branchs);
fprintf(dosya, "%s %s %s\n", isimler, soyisimler, branchs);
}
fclose(fp);
fclose(dosya);
}
getch();
system("cls");
main();
} else {
printf("\n\nWrong username or password.\nPlease try again or sign up.\n");
goto tekrar;
}
}
};
class Member {
public:
//--------------------------------------------------------------------------------------------------------------------------
void new_member() {
system("cls");
char isim[30], soyisim[30], branch[30], paymentMethod[10];
printf("\nEnter Name : \t");
scanf("%s", isim);
printf("\nEnter Surname : ");
scanf("%s", soyisim);
printf("\nEnter Main Branch : ");
scanf("%s", branch);
printf("\n\nChoose a payment method : ");
printf("\n=============================================================\n");
printf("\n\n\t\tPAYMENT METHODS AND DISCOUNTS\n\n");
printf("\n\tA- Fitness / Normal Membership : 1 Mounth (5 days a week)- 20$");
printf("\n\tB- Fitness / Normal Membership : 1 Mounth (3 days a week)- 15$");
printf("\n\tC- Fitness / Student Discount : 1 Mounth (3 days a week)- 10$\n");
printf("\n\tD- Swimming / Normal Membership : 1 Mounth (5 days a week)- 25$");
printf("\n\tE- Swimming / Normal Membership : 1 Mounth (3 days a week)- 20$");
printf("\n\tF- Swimming / Student Discount : 1 Mounth (3 days a week)- 15$\n");
printf("\n\tG- Fitness and Swimming / Normal Membership : 1 Mounth (5 days a week)- 40$");
printf("\n\tH- Fitness and Swimming / Normal Membership : 1 Mounth (3 days a week)- 30$");
printf("\n\tI- Fitness and Swimming / Student Discount : 1 Mounth (3 days a week)- 20$");
printf("\n\n=============================================================\n\n");
printf("Enter the choice with Letter : \t");
scanf("%s", paymentMethod);
FILE * f;
f = fopen("MemberList.txt", "a");
fprintf(f, "%s %s %s\n", isim, soyisim, branch);
fclose(f);
printf("\nPress any key to return to the main menu.");
getch();
system("cls");
main();
}
//--------------------------------------------------------------------------------------------------------------------------
void member_management() {
Credential credential;
system("cls");
int secim;
printf("\n=============================================================\n");
printf("\n\n\t\tADMINISTRATIVE LOGIN PAGE");
printf("\n\n\t1.Login to system with username and password.");
printf("\n\t2.Sign-up to system.");
printf("\n\n=============================================================\n\n");
printf("\n\n\tENTER YOUR CHOICE:\t");
scanf("%d", & secim);
switch (secim) {
case 1:
credential.loginFunction();
break;
case 2:
credential.signupFunction();
break;
default:
printf("\nWrong choice. Please try again.\n");
break;
}
}
};
class Intro {
public:
//--------------------------------------------------------INTRO------------------------------------------------------------------
void intro_ekrani() {
printf("\n----------------------------------\n");
printf("| Software Engineering Project |");
printf("\n----------------------------------\n");
printf("| Made By: Mert Altuntas |");
printf("\n----------------------------------\n");
printf("|\t ID: 1804010005 |");
printf("\n----------------------------------\n\n\n");
printf("Loading ");
int j, a;
for (a = 0; a <= 5; a++) {
printf(".");
for (j = 0; j <= 120000000; j++);
}
system("cls");
}
};
class Gym {
public:
//--------------------------------------------------------------------------------------------------------------------------
void workout() {
int c, u;
system("cls");
printf("\n\n\n\n");
printf("\t ****** BE THE BEAST AND WORK HARD *******\n\n\n");
printf("\t ****** ALWAYS HEALTH COMES FIRST *******\n\n\n");
printf("\t ****** PRESS ANY KEY TO SELECT THE WORK OUT *******\n\n\n");
getch();
system("cls");
z:
printf("\n\n\n\n\n\n");
printf("\tPRE-WORKOUT EXERCISE ARE COMPLUSORY\n\n\n");
printf("\t1 : CHEST WORKOUT\n\n");
printf("\t2 : BACK WORKOUT\n\n");
printf("\t3 : BICEPS WORKOUT\n\n");
printf("\t4 : TRICEPS WORKOUT\n\n");
printf("\t5 : ABS WORKOUT\n\n");
printf("\t6 : SHOULDER WORKOUT\n\n");
printf("\t7 : LEGS\n\n");
printf("\t8 : BACK TO MAIN MENU\n\n");
printf("\t");
scanf("%d", & c);
system("cls");
switch (c) {
case 1:
printf("\n");
printf("\t PUSH UP: 3 SETS; 15,12,10 REPS\n\n");
printf("\t INCLINED BENCH-PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t FLAT BENCH-PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t DECLINED BENCH-PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t INCLIDE DUMBBELL-PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t FLAT DUMBELL-PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t DECLINED DUMBELL-PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t CABLE CROSS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t SEATED MACHINE FLY: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n\n\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 2:
printf("\n");
printf("\t WIDE GRIP PULL-UP: 3 SETS; 15,12,10 REPS\n\n");
printf("\t LAT PULL DOWN BACK: 3 SETS; 15,12,10 REPS\n\n");
printf("\t T-BAR: 3 SETS; 15,12,10 REPS\n\n");
printf("\t SEATED RAW: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PULL DOWN ROW: 3 SETS; 15,12,10 REPS\n\n");
printf("\t ONR ARM DUMBBELL ROWS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t BARBELL BENT OVER: 3 SETS; 15,12,10 REPS\n\n");
printf("\t DEAD LIFT: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 3:
printf("\n");
printf("\t SMALL GRIP PULL-UP: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PREACHER CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t BARBELL CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t ONE BY ONE DUMBELL CURL: 3 SETS; 15,12,10 REPS\n\n");
printf("\t CONCENTRATION CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t CABLE BICEPS CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t INCLINED DUMBELL CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t REVERSE CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t HAMMER CURLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 4:
printf("\n");
printf("\t DIAMOND PUSH-UP: 3 SETS; 15,12,10 REPS\n\n");
printf("\t FLAT BAR TRICEPS EXTENSION: 3 SETS; 15,12,10 REPS\n\n");
printf("\t BAR TRICEPS EXTENSION: 3 SETS; 15,12,10 REPS\n\n");
printf("\t ONE ARM DUMBELL PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t BOTH ARM DUMBELL PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t KICKBACK: 3 SETS; 15,12,10 REPS\n\n");
printf("\t CABLE PUSH DOWN: 3 SETS; 15,12,10 REPS\n\n");
printf("\t CABLE PUSH OVERHEAD: 3 SETS; 15,12,10 REPS\n\n");
printf("\t TRICEPS DIPS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 5:
printf("\n");
printf("\t HANGING LEG RAISE: 3 SETS; 15,12,10 REPS\n\n");
printf("\t MACHINE CRUNCH: 3 SETS; 15,12,10 REPS\n\n");
printf("\t CABLE PALLOF PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t KNEELING CABLE CRUNCH: 3 SETS; 15,12,10 REPS\n\n");
printf("\t DECLINE-BENCH CRUNCH WITH MEDICINE BALL: 3 SETS; 15,12,10 REPS\n\n");
printf("\t EXERCISE BALL PIKE: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLANK: 7,5,3 MINUTES\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 6:
printf("\n");
printf("\t BAREBELL FRONT PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t DUMBELL PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t LATERAL RAISES: 3 SETS; 15,12,10 REPS\n\n");
printf("\t FRONT PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t DUMBELL BENT OVER: 3 SETS; 15,12,10 REPS\n\n");
printf("\t UPRIGHT ROW: 3 SETS; 15,12,10 REPS\n\n");
printf("\t SHRUG: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 7:
printf("\n");
printf("\t SET-UPS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t SUMO DUMBELL SQUATS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t LUNGES DUMBELLS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t SEATED LEGS CRULS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t SEATED MACHINE EXTENSIONS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t STANDING DUMBELL CALF: 3 SETS; 15,12,10 REPS\n\n");
printf("\t REVERSE LEGS CRULS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t HEAVY LEG PRESS: 3 SETS; 15,12,10 REPS\n\n");
printf("\t PLEASE DONT LIFT OVER-WEIGHT\n\n");
printf("\t TO RETURN TO WORKOUT LIST PLEASE PRESS '2' ");
scanf("%d", & u);
if (u == 2) {
system("cls");
goto z;
} else
break;
case 8:
main();
break;
}
}
void rules() {
system("cls");
printf("\t\t=============================================================\n");
printf("\n\t\t RULES AND REGULATIONS \n");
printf("\t\t=============================================================\n");
printf("\n\t1.Do not bring your gym bag or other personal belongings onto the fitness floor.\n");
printf("\t2.Refrain from yelling, using profanity, banging weights and making loud sounds\n");
printf("\t3.Do not sit on machines between sets\n");
printf("\t4.Re-rack weights and return all other equipment and accessories to their proper locations\n");
printf("\t5.Ask staff to show you how to operate equipment properly so that others are not waiting as you figure it out.\n");
printf("\t6.Wipe down all equipment after use.\n");
printf("\t7.Stick to posted time limits on all cardiovascular machines.\n");
printf("\t8.Do not bring children onto the gym floor. Children must remain in the childcare area.\n");
printf("\t9.Do not disturb others. Focus on your own workout and allow others to do the same.\n");
printf("\t10.Before beginning your workout, wash your hands and wipe off any cologne or perfume.\n\n");
printf("\n\tPRESS ANY KEY TO BACK MAIN MENU\n");
getch();
system("cls");
main();
}
void bmi_calculation() {
system("cls");
float height, weight, bmi = 0;
int age;
printf("\nPlease enter weight (kg): \n");
scanf("%f", & weight);
printf("Please enter height (dot m): \n");
scanf("%f", & height);
bmi = weight / (height * height);
if (bmi < 18.50) {
printf("\n\nYou are below your ideal weight.\n\n");
printf("The result is : %.2f\n\n", bmi);
} else if (bmi >= 18.50 && bmi < 24.99) {
printf("\n\nYour weight is ideal.\n\n");
printf("The result is : %.2f\n\n", bmi);
} else if (bmi > 25) {
printf("\n\nYou are above your ideal weight.\n\n");
printf("The result is : %.2f\n\n", bmi);
}
printf("Press any key to return to the main menu.\n");
getch();
system("cls");
main();
}
};
class MainMenu {
Intro intro;
Member member;
Credential credential;
Gym gym;
public:
void mainMenu(void) {
system("COLOR 1F");
intro.intro_ekrani();
int rakam;
printf("\n=============================================================\n");
printf("\n\n\t\tWELCOME TO GYM MANAGEMENT SOFTWARE");
printf("\n\n\t1. CREATE A NEW MEMBER");
printf("\n\t2. MEMBER MANAGEMENT (requires admin login)");
printf("\n\t3. WORKOUT PROGRAM SUGGESTION");
printf("\n\t4. RULES AND REGULATIONS");
printf("\n\t5. REVIEW PAYMENT METHODS & DISCOUNTS");
printf("\n\t6. MAKE A BMI CALCULATION");
printf("\n\t7. EXIT");
printf("\n\n=============================================================\n\n");
printf("\n\n\tENTER YOUR CHOICE:\t");
scanf("%d", & rakam);
switch (rakam) {
case 1:
member.new_member();
break;
case 2:
member.member_management();
break;
case 3:
gym.workout();
break;
case 4:
gym.rules();
break;
case 5:
credential.payment_methods();
break;
case 6:
gym.bmi_calculation();
break;
case 7:
printf("\n\n\tTHANK YOU\n");
exit(0);
break;
default:
printf("\nWrong choise. Please enter the correct numbers to use program.\n");
break;
}
}
};
//--------------------------------------------------------MAIN-------------------------------------------------------------------
int main() {
MainMenu mainMenu;
mainMenu.mainMenu();
}
| true |
a4a835d7d78b6f224214aa8cfc0f79271ab13892 | C++ | juanalbertogutierrez/Competition | /Acm 2016/Actividad 2/eight/basicgeometry.cpp | UTF-8 | 1,503 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <iomanip>
# define N_PI 3.14159265358979323846
using namespace std;
long double calculaoAngulo(int radio, int altura){
return 2 * (acos(1 - ((double)altura / (double)radio))* 180.0 / N_PI);//sacamos angulo y convertimos a grados
}
long double calculoArea(int radio,int altura){
return (pow(radio,2) / 2) * ( ((N_PI * (2 * (acos(1 - ((long double)altura / (long double)radio))* 180.0 / N_PI))) / 180) - sin((2 * (acos(1 - ((double)altura / (double)radio))* 180.0 / N_PI))*N_PI/180) );//sacamos el area
}
int main(){
int A,B,C;
long double AreaA, AreaB, AreaC;
long double angulo, areaSegmento, area;
while(cin>>A>>B){
if(A==0 && B==0)
{
cout<<"0\n";
}
else{
C = A + B;//calculamos el radio del circulo grande
AreaA = N_PI * pow(A,2);
AreaB = N_PI * pow(B,2);
AreaC = N_PI * pow(C,2);
if(A >= B){
//angulo = calculaoAngulo(C,B*2);//enviamos radio y la altura de B
//calculo de area
area = calculoArea(C,B*2) - (N_PI * pow(B,2));
//hacemos la resta del area del segmento y del area del circulo
//area = areaSegmento - AreaB;
}
if(B > A){
//angulo = calculaoAngulo(C,A*2);//enviamos radio y la altura de A
//calculo de area
area = calculoArea(C,A*2) - (N_PI * pow(A,2));
//hacemos la resta del area del segmento y del area del circulo
//area = areaSegmento - AreaA;
}
cout<<roundf(area*1000)/1000<<endl;
}
}
return 0;
}
| true |