hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ecb9d9a556ffb3fd54b3cce5077b37052fd85bec | 747 | cpp | C++ | Data Structures/Binary Tree/C++/Deletion of a node in a BST.cpp | sanchit2812/Data-Structures-Algorithms-Hacktoberfest-2K19 | 88bc29e924d6d15993db742ccaede4752c0083e8 | [
"MIT"
] | null | null | null | Data Structures/Binary Tree/C++/Deletion of a node in a BST.cpp | sanchit2812/Data-Structures-Algorithms-Hacktoberfest-2K19 | 88bc29e924d6d15993db742ccaede4752c0083e8 | [
"MIT"
] | null | null | null | Data Structures/Binary Tree/C++/Deletion of a node in a BST.cpp | sanchit2812/Data-Structures-Algorithms-Hacktoberfest-2K19 | 88bc29e924d6d15993db742ccaede4752c0083e8 | [
"MIT"
] | null | null | null | node* del(node* root, int data){
if(root == NULL) return NULL;
if(data > root->data) root->right = del(root->right, data);
else if(data<root->data) root->left = del(root->left,data);
else{
if (root->left == NULL){
node* temp =root->right;
free(root);
return temp;
}
else if(root->right==NULL){
node* temp = root->left;
free(root);
return temp;
}
node* temp = find_max(root->left);
root->data = temp->data;
root->left = del(root->left, root->data);
}
return root;
}
node* find_max(struct node* root){
while(root->right!=NULL) root = root->right;
return root;
} | 27.666667 | 64 | 0.497992 | sanchit2812 |
ecbf1c4da32433f343307200c5540b44d77d3bb2 | 3,984 | cpp | C++ | questions/button-timer-38645219/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | 54 | 2015-09-13T07:29:52.000Z | 2022-03-16T07:43:50.000Z | questions/button-timer-38645219/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | null | null | null | questions/button-timer-38645219/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | 31 | 2016-08-26T13:35:01.000Z | 2022-03-13T16:43:12.000Z | // https://github.com/KubaO/stackoverflown/tree/master/questions/button-timer-38645219
#if 1
#include <QtWidgets>
class Timer : public QObject {
Q_OBJECT
QElapsedTimer timer;
public:
Q_SLOT void start() { timer.start(); }
Q_SLOT void stop() { emit elapsed(timer.elapsed()); }
Q_SIGNAL void elapsed(qint64);
};
class Widget : public QWidget {
Q_OBJECT
QFormLayout layout{this};
QPushButton button{"Press Me"};
QLabel label;
public:
Widget() {
layout.addRow(&button);
layout.addRow(&label);
connect(&button, &QPushButton::pressed, this, &Widget::pressed);
connect(&button, &QPushButton::released, this, &Widget::released);
}
Q_SIGNAL void pressed();
Q_SIGNAL void released();
Q_SLOT void setText(const QString & text) { label.setText(text); }
};
// use Timer and Widget from preceding example
#include <sstream>
#include <string>
#include <functional>
class Controller {
public:
using callback_t = std::function<void(const std::string&)>;
Controller(callback_t && callback) : callback{std::move(callback)} {}
void onElapsed(int ms) {
std::stringstream s;
s << "Pressed for " << ms << " ms";
callback(s.str());
}
private:
callback_t callback;
};
int main(int argc, char ** argv) {
QApplication app{argc, argv};
Timer t;
Widget w;
Controller c{ [&](const std::string & s){ w.setText(QString::fromStdString(s)); } };
QObject::connect(&w, &Widget::pressed, &t, &Timer::start);
QObject::connect(&w, &Widget::released, &t, &Timer::stop);
QObject::connect(&t, &Timer::elapsed, [&](qint64 ms) { c.onElapsed(ms); });
w.show();
return app.exec();
}
#include "main.moc"
#endif
#if 0
#include <QtWidgets>
class Timer : public QObject {
Q_OBJECT
QElapsedTimer timer;
public:
Q_SLOT void start() { timer.start(); }
Q_SLOT void stop() { emit elapsed(timer.elapsed()); }
Q_SIGNAL void elapsed(qint64);
};
class Widget : public QWidget {
Q_OBJECT
QFormLayout layout{this};
QPushButton button{"Press Me"};
QLabel label;
public:
Widget() {
layout.addRow(&button);
layout.addRow(&label);
connect(&button, &QPushButton::pressed, this, &Widget::pressed);
connect(&button, &QPushButton::released, this, &Widget::released);
}
Q_SIGNAL void pressed();
Q_SIGNAL void released();
Q_SLOT void setText(const QString & text) { label.setText(text); }
};
class Controller : public QObject {
Q_OBJECT
public:
Q_SLOT void elapsed(qint64 ms) {
emit hasText(QStringLiteral("Pressed for %1 ms").arg(ms));
}
Q_SIGNAL void hasText(const QString &);
};
int main(int argc, char ** argv) {
QApplication app{argc, argv};
Timer t;
Widget w;
Controller c;
QObject::connect(&w, &Widget::pressed, &t, &Timer::start);
QObject::connect(&w, &Widget::released, &t, &Timer::stop);
QObject::connect(&t, &Timer::elapsed, &c, &Controller::elapsed);
QObject::connect(&c, &Controller::hasText, &w, &Widget::setText);
w.show();
return app.exec();
}
#include "main.moc"
#endif
#if 0
#include <QtWidgets>
class Widget : public QWidget {
QFormLayout layout{this};
QPushButton button{"Press Me"};
QLabel label;
QElapsedTimer timer;
public:
Widget() {
layout.addRow(&button);
layout.addRow(&label);
}
};
int main(int argc, char ** argv) {
QApplication app{argc, argv};
Widget w;
w.show();
return app.exec();
}
#endif
#if 0
#include <QtWidgets>
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
QFormLayout layout{&w};
QPushButton button{"Press Me"};
QLabel label;
layout.addRow(&button);
layout.addRow(&label);
QElapsedTimer timer;
QObject::connect(&button, &QPushButton::pressed, [&]{ timer.start(); });
QObject::connect(&button, &QPushButton::released, [&]{
label.setText(QStringLiteral("Pressed for %1 ms").arg(timer.elapsed()));
});
w.show();
return app.exec();
}
#endif
| 24.145455 | 87 | 0.6501 | SammyEnigma |
ecc285734c6431dddcc9839cec5ce843d8c2ab51 | 159 | cpp | C++ | Source/FSDEngine/Private/CSGCircleDuplicatorProperties.cpp | trumank/DRG-Mods | 2febc879f2ffe83498ac913c114d0e933427e93e | [
"MIT"
] | 8 | 2021-07-10T20:06:05.000Z | 2022-03-04T19:03:50.000Z | Source/FSDEngine/Private/CSGCircleDuplicatorProperties.cpp | trumank/DRG-Mods | 2febc879f2ffe83498ac913c114d0e933427e93e | [
"MIT"
] | 9 | 2022-01-13T20:49:44.000Z | 2022-03-27T22:56:48.000Z | Source/FSDEngine/Private/CSGCircleDuplicatorProperties.cpp | trumank/DRG-Mods | 2febc879f2ffe83498ac913c114d0e933427e93e | [
"MIT"
] | 2 | 2021-07-10T20:05:42.000Z | 2022-03-14T17:05:35.000Z | #include "CSGCircleDuplicatorProperties.h"
FCSGCircleDuplicatorProperties::FCSGCircleDuplicatorProperties() {
this->Num = 0;
this->Radius = 0.00f;
}
| 19.875 | 66 | 0.748428 | trumank |
ecc30d71863c58c6d76be2ac7f1ce8bcdce39af1 | 822 | hpp | C++ | cpp-source/tls-epoll-server.hpp | bwackwat/event-spiral | 177331035a23f68a0294a0f3e9af948779eef794 | [
"MIT"
] | 3 | 2016-12-08T02:28:27.000Z | 2019-05-15T23:16:11.000Z | cpp-source/tls-epoll-server.hpp | bwackwat/event-spiral | 177331035a23f68a0294a0f3e9af948779eef794 | [
"MIT"
] | 3 | 2017-02-10T18:21:28.000Z | 2017-09-21T00:06:44.000Z | cpp-source/tls-epoll-server.hpp | bwackwat/event-spiral | 177331035a23f68a0294a0f3e9af948779eef794 | [
"MIT"
] | 3 | 2017-02-04T01:37:24.000Z | 2019-05-15T23:17:43.000Z | #pragma once
#include <unordered_map>
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "tcp-server.hpp"
class TlsEpollServer : public EpollServer{
private:
SSL_CTX* ctx;
std::unordered_map<int, SSL*> client_ssl;
void close_client(int* fd, std::function<void(int*)> callback);
public:
TlsEpollServer(std::string certificate, std::string private_key, uint16_t port, size_t max_connections, std::string new_name = "TlsEpollServer");
~TlsEpollServer();
virtual bool accept_continuation(int* new_client_fd);
virtual bool send(int fd, const char* data, size_t data_length);
virtual ssize_t send(int fd, std::string data);
virtual ssize_t recv(int fd, char* data, size_t data_length);
virtual ssize_t recv(int fd, char* data, size_t data_length, std::function<ssize_t(int, char*, size_t)> callback);
};
| 31.615385 | 146 | 0.756691 | bwackwat |
ecc90a195b2c23533e38ab29f2058fc49afa0c10 | 14,279 | cpp | C++ | MongoDB/samples/SQLToMongo/src/SQLToMongo.cpp | abyss7/poco | a651a78c76eebd414b37745f7dd8539460154cab | [
"BSL-1.0"
] | null | null | null | MongoDB/samples/SQLToMongo/src/SQLToMongo.cpp | abyss7/poco | a651a78c76eebd414b37745f7dd8539460154cab | [
"BSL-1.0"
] | 3 | 2021-06-02T02:59:06.000Z | 2021-09-16T04:35:06.000Z | MongoDB/samples/SQLToMongo/src/SQLToMongo.cpp | abyss7/poco | a651a78c76eebd414b37745f7dd8539460154cab | [
"BSL-1.0"
] | 6 | 2021-06-02T02:39:34.000Z | 2022-03-29T05:51:57.000Z | //
// main.cpp
//
// $Id$
//
// This sample shows SQL to mongo Shell to C++ examples.
//
// Copyright (c) 2013, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/MongoDB/MongoDB.h"
#include "Poco/MongoDB/Connection.h"
#include "Poco/MongoDB/Database.h"
#include "Poco/MongoDB/Cursor.h"
#include "Poco/MongoDB/Array.h"
// INSERT INTO players
// VALUES( "Messi", "Lionel", 1987)
void sample1(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 1 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertPlayerRequest = db.createInsertRequest("players");
// With one insert request, we can add multiple documents
insertPlayerRequest->addNewDocument()
.add("lastname", "Valdes")
.add("firstname", "Victor")
.add("birthyear", 1982);
insertPlayerRequest->addNewDocument()
.add("lastname", "Alves")
.add("firstname", "Daniel")
.add("birthyear", 1983);
insertPlayerRequest->addNewDocument()
.add("lastname", "Bartra")
.add("firstname", "Marc")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Alba")
.add("firstname", "Jordi")
.add("birthyear", 1989);
insertPlayerRequest->addNewDocument()
.add("lastname", "Montoya")
.add("firstname", "Martin")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Abidal")
.add("firstname", "Eric")
.add("birthyear", 1979);
insertPlayerRequest->addNewDocument()
.add("lastname", "Fontas")
.add("firstname", "Andreu")
.add("birthyear", 1989);
insertPlayerRequest->addNewDocument()
.add("lastname", "Messi")
.add("firstname", "Lionel")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Puyol")
.add("firstname", "Carles")
.add("birthyear", 1978);
insertPlayerRequest->addNewDocument()
.add("lastname", "Piqué")
.add("firstname", "Gerard")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Muniesa")
.add("firstname", "Marc")
.add("birthyear", 1992);
insertPlayerRequest->addNewDocument()
.add("lastname", "Fabrégas")
.add("firstname", "Cesc")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Hernandez")
.add("firstname", "Xavi")
.add("birthyear", 1980);
insertPlayerRequest->addNewDocument()
.add("lastname", "Iniesta")
.add("firstname", "Andres")
.add("birthyear", 1984);
insertPlayerRequest->addNewDocument()
.add("lastname", "Alcantara")
.add("firstname", "Thiago")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Dos Santos")
.add("firstname", "Jonathan")
.add("birthyear", 1990);
insertPlayerRequest->addNewDocument()
.add("lastname", "Mascherano")
.add("firstname", "Javier")
.add("birthyear", 1984);
insertPlayerRequest->addNewDocument()
.add("lastname", "Busquets")
.add("firstname", "Sergio")
.add("birthyear", 1988);
insertPlayerRequest->addNewDocument()
.add("lastname", "Adriano")
.add("firstname", "")
.add("birthyear", 1984);
insertPlayerRequest->addNewDocument()
.add("lastname", "Song")
.add("firstname", "Alex")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Villa")
.add("firstname", "David")
.add("birthyear", 1981);
insertPlayerRequest->addNewDocument()
.add("lastname", "Sanchez")
.add("firstname", "Alexis")
.add("birthyear", 1988);
insertPlayerRequest->addNewDocument()
.add("lastname", "Pedro")
.add("firstname", "")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Cuenca")
.add("firstname", "Isaac")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Tello")
.add("firstname", "Cristian")
.add("birthyear", 1991);
std::cout << insertPlayerRequest->documents().size() << std::endl;
connection.sendRequest(*insertPlayerRequest);
std::string lastError = db.getLastError(connection);
if (!lastError.empty())
{
std::cout << "Last Error: " << db.getLastError(connection) << std::endl;
}
}
// SELECT lastname, birthyear FROM players
void sample2(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 2 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
// Selecting fields is done by adding them to the returnFieldSelector
// Use 1 as value of the element.
cursor.query().returnFieldSelector().add("lastname", 1);
cursor.query().returnFieldSelector().add("birthyear", 1);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
}
}
// SELECT * FROM players
void sample3(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 3 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players WHERE birthyear = 1978
void sample4(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 4 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
cursor.query().selector().add("birthyear", 1978);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players WHERE birthyear = 1987 ORDER BY name
void sample5(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 5 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
// When orderby is needed, use 2 separate documents in the query selector
cursor.query().selector().addNewDocument("$query").add("birthyear", 1987);
cursor.query().selector().addNewDocument("$orderby").add("lastname", 1);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players WHERE birthyear > 1969 and birthyear <= 1980
void sample6(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 6 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
cursor.query().selector().addNewDocument("birthyear")
.add("$gt", 1969)
.add("$lte", 1980);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// CREATE INDEX playername
// ON players(lastname)
void sample7(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 7 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::MongoDB::Document::Ptr keys = new Poco::MongoDB::Document();
keys->add("lastname", 1);
Poco::MongoDB::Document::Ptr errorDoc = db.ensureIndex(connection, "players", "lastname", keys);
/* Sample above is the same as the following code:
Poco::MongoDB::Document::Ptr index = new Poco::MongoDB::Document();
index->add("ns", "sample.players");
index->add("name", "lastname");
index->addNewDocument("key").add("lastname", 1);
Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertRequest = db.createInsertRequest("system.indexes");
insertRequest->documents().push_back(index);
connection.sendRequest(*insertRequest);
Poco::MongoDB::Document::Ptr errorDoc = db.getLastErrorDoc(connection);
*/
std::cout << errorDoc->toString(2);
}
// SELECT * FROM players LIMIT 10 SKIP 20
void sample8(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 8 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
cursor.query().setNumberToReturn(10);
cursor.query().setNumberToSkip(20);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players LIMIT 1
void sample9(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 9 ***" << std::endl;
// QueryRequest can be used directly
Poco::MongoDB::QueryRequest query("sample.players");
query.setNumberToReturn(1);
Poco::MongoDB::ResponseMessage response;
connection.sendRequest(query, response);
if (response.hasDocuments())
{
std::cout << response.documents()[0]->toString(2) << std::endl;
}
// QueryRequest can be created using the Database class
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::QueryRequest> queryPtr = db.createQueryRequest("players");
queryPtr->setNumberToReturn(1);
connection.sendRequest(*queryPtr, response);
if (response.hasDocuments())
{
std::cout << response.documents()[0]->toString(2) << std::endl;
}
}
// SELECT DISTINCT birthyear FROM players WHERE birthyear > 1980
void sample10(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 10 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = db.createCommand();
command->selector()
.add("distinct", "players")
.add("key", "birthyear")
.addNewDocument("query")
.addNewDocument("birthyear")
.add("$gt", 1980);
Poco::MongoDB::ResponseMessage response;
connection.sendRequest(*command, response);
if (response.hasDocuments())
{
Poco::MongoDB::Array::Ptr values = response.documents()[0]->get<Poco::MongoDB::Array::Ptr>("values");
for (int i = 0; i < values->size(); ++i )
{
std::cout << values->get<int>(i) << std::endl;
}
}
}
// SELECT COUNT(*) FROM players WHERE birthyear > 1980
void sample11(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 11 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::QueryRequest> count = db.createCountRequest("players");
count->selector().addNewDocument("query")
.addNewDocument("birthyear")
.add("$gt", 1980);
Poco::MongoDB::ResponseMessage response;
connection.sendRequest(*count, response);
if (response.hasDocuments())
{
std::cout << "Count: " << response.documents()[0]->getInteger("n") << std::endl;
}
}
//UPDATE players SET birthyear = birthyear + 1 WHERE firstname = 'Victor'
void sample12(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 12 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::UpdateRequest> request = db.createUpdateRequest("players");
request->selector().add("firstname", "Victor");
request->update().addNewDocument("$inc").add("birthyear", 1);
connection.sendRequest(*request);
Poco::MongoDB::Document::Ptr lastError = db.getLastErrorDoc(connection);
std::cout << "LastError: " << lastError->toString(2) << std::endl;
}
//DELETE players WHERE firstname = 'Victor'
void sample13(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 13 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::DeleteRequest> request = db.createDeleteRequest("players");
request->selector().add("firstname", "Victor");
connection.sendRequest(*request);
Poco::MongoDB::Document::Ptr lastError = db.getLastErrorDoc(connection);
std::cout << "LastError: " << lastError->toString(2) << std::endl;
}
int main(int argc, char** argv)
{
Poco::MongoDB::Connection connection("localhost", 27017);
try
{
sample1(connection);
sample2(connection);
sample3(connection);
sample4(connection);
sample5(connection);
sample6(connection);
sample7(connection);
sample8(connection);
sample9(connection);
sample10(connection);
sample11(connection);
sample12(connection);
sample13(connection);
}
catch (Poco::Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
}
return 0;
}
| 29.810021 | 159 | 0.663702 | abyss7 |
ecca2c85028fc214c245c0c32dc1e89412bb87c1 | 594 | cc | C++ | test/asan/TestCases/use-after-poison.cc | crystax/android-toolchain-compiler-rt-3-7 | 6b848d1e7d55df3227b212aa229f8b60b16bdd5d | [
"MIT"
] | 21 | 2015-04-19T20:47:50.000Z | 2019-03-08T18:39:41.000Z | test/asan/TestCases/use-after-poison.cc | crystax/android-toolchain-compiler-rt-3-7 | 6b848d1e7d55df3227b212aa229f8b60b16bdd5d | [
"MIT"
] | 1 | 2016-02-10T15:40:03.000Z | 2016-02-10T15:40:03.000Z | test/asan/TestCases/use-after-poison.cc | crystax/android-toolchain-compiler-rt-3-7 | 6b848d1e7d55df3227b212aa229f8b60b16bdd5d | [
"MIT"
] | 12 | 2019-06-21T03:33:51.000Z | 2021-12-13T09:08:31.000Z | // Check that __asan_poison_memory_region works.
// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
//
// Check that we can disable it
// RUN: env ASAN_OPTIONS=$ASAN_OPTIONS:allow_user_poisoning=0 %run %t
#include <stdlib.h>
extern "C" void __asan_poison_memory_region(void *, size_t);
int main(int argc, char **argv) {
char *x = new char[16];
x[10] = 0;
__asan_poison_memory_region(x, 16);
int res = x[argc * 10]; // BOOOM
// CHECK: ERROR: AddressSanitizer: use-after-poison
// CHECK: main{{.*}}use-after-poison.cc:[[@LINE-2]]
delete [] x;
return res;
}
| 28.285714 | 69 | 0.6633 | crystax |
eccacdbde2cec28a56457d2153fe83d95c2b79b9 | 1,207 | cpp | C++ | PTA/PAT(Advanced Level)/c++/A1068.dfs.cpp | Sunrisepeak/AC-Online-Judge | 5b5ea2eefa2ba48d718957720158fb79134a8fa7 | [
"Apache-2.0"
] | 3 | 2019-03-17T11:47:05.000Z | 2021-12-10T03:41:42.000Z | PTA/PAT(Advanced Level)/c++/A1068.dfs.cpp | Sunrisepeak/AC-Online-Judge | 5b5ea2eefa2ba48d718957720158fb79134a8fa7 | [
"Apache-2.0"
] | null | null | null | PTA/PAT(Advanced Level)/c++/A1068.dfs.cpp | Sunrisepeak/AC-Online-Judge | 5b5ea2eefa2ba48d718957720158fb79134a8fa7 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N, M;
vector<int> coins, ans;
bool isOk = false;
void DFS(int begin, int sum) {
if (sum == M) {
isOk = true;
} else if (sum < M) {
for (int i = begin; i < coins.size(); i++) {
ans.push_back(coins[i]);
DFS(i + 1, sum + coins[i]);
if (isOk) break;
ans.pop_back();
}
}
}
void choiceSortOfRange(int range) {
int j = 0;
for (int i = 0; i < range; i++) {
int minIndex = i;
for (int j = i; j < coins.size(); j++) {
if (coins[j] < coins[minIndex]) {
minIndex = j;
}
}
swap(coins[i], coins[minIndex]);
}
}
int main() {
cin >> N >> M;
for (int i = 0; i < N; i++) {
int temp;
cin >> temp;
coins.push_back(temp);
}
choiceSortOfRange(min(N, 100));
DFS(0, 0); // ---> TLE
if (isOk == false) {
cout << "No Solution";
} else {
cout << ans[0];
for (int i = 1; i < ans.size(); i++) {
cout << " " << ans[i];
}
}
return 0;
}
/**
* score: 29
* case 6: TLE
*/ | 20.457627 | 52 | 0.432477 | Sunrisepeak |
eccd481033b7ae318e7b4df53c8de1083fd9e584 | 289 | cpp | C++ | src/CEditEd.cpp | colinw7/CQEd | 4a22e8027df9710ec19ac3a5082a8c2906d95a26 | [
"MIT"
] | 1 | 2021-12-23T02:20:57.000Z | 2021-12-23T02:20:57.000Z | src/CEditEd.cpp | colinw7/CQEdit | 4a22e8027df9710ec19ac3a5082a8c2906d95a26 | [
"MIT"
] | null | null | null | src/CEditEd.cpp | colinw7/CQEdit | 4a22e8027df9710ec19ac3a5082a8c2906d95a26 | [
"MIT"
] | null | null | null | #include <CEditEd.h>
#include <CEditFile.h>
CEditEd::
CEditEd(CEditFile *file) :
CEd(file), file_(file)
{
}
CEditEd::
~CEditEd()
{
}
void
CEditEd::
output(const std::string &msg)
{
file_->addMsgLine(msg);
}
void
CEditEd::
error(const std::string &msg)
{
file_->addErrLine(msg);
}
| 10.321429 | 30 | 0.66436 | colinw7 |
ecd1295805faf1e6eef13cac5780ee657a541e73 | 738 | cpp | C++ | Failed/B920_failed.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | Failed/B920_failed.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | Failed/B920_failed.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | #include <bits/stdc++.h>
using namespace std;
class Soln{
private:
int n,l,r, T;
public:
Soln(){
scanf("%d",&T);
while(T--){
scanf("%d",&n);
int time = 1;
for(int i=0; i<n; i++){
scanf("%d %d",&l,&r);
if(time>r){
printf("0 ");
}else if(time>=l && time <=r){
printf("%d ",time);
time++;
}else {
printf("%d ",l);
time=l+1;
}
}
printf("\n");
}
}
~Soln(){
}
};
int main(int argc, char const *argv[])
{
/* code */
Soln soln;
return 0;
} | 18.923077 | 46 | 0.317073 | fahimfarhan |
ecd1c7d45f0a7bf93de565fc9066c60fb36f06b2 | 229 | cpp | C++ | books/tech/cpp/std-14/s_meyers-effective_modern_cpp/code/ch_08-tweaks/item_42-consider_emplacement_instead_of_insertion/01-emplacement_example-01/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | 1 | 2017-05-04T08:23:46.000Z | 2017-05-04T08:23:46.000Z | books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_8-TWEAKS/item_42-consider_emplacement_instead_of_insertion/01-emplacement_example-01/main.cpp | ordinary-developer/lin_education | 13d65b20cdbc3e5467b2383e5c09c73bbcdcb227 | [
"MIT"
] | null | null | null | books/techno/cpp/__intermediate/effective_modern_cpp_s_meyers/code/ch_8-TWEAKS/item_42-consider_emplacement_instead_of_insertion/01-emplacement_example-01/main.cpp | ordinary-developer/lin_education | 13d65b20cdbc3e5467b2383e5c09c73bbcdcb227 | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
int main() {
std::vector<std::string> vs;
vs.push_back("xyzzy");
vs.push_back(std::string("xyzzy"));
vs.emplace_back("xyzzy");
vs.emplace_back(50, 'x');
return 0;
}
| 15.266667 | 39 | 0.598253 | ordinary-developer |
ecd362a4100bf815d2c2b50f074575bd8f6cff07 | 4,365 | cpp | C++ | source/Reeval/MMASib_experiments.cpp | fq00/noisyLandscapes | 5866a6f523e4e99f9b1ab68b08b2443821ec10dd | [
"MIT"
] | null | null | null | source/Reeval/MMASib_experiments.cpp | fq00/noisyLandscapes | 5866a6f523e4e99f9b1ab68b08b2443821ec10dd | [
"MIT"
] | null | null | null | source/Reeval/MMASib_experiments.cpp | fq00/noisyLandscapes | 5866a6f523e4e99f9b1ab68b08b2443821ec10dd | [
"MIT"
] | null | null | null | //
// rAnalysis.cpp
// Reeval
//
// Created by Francesco Quinzan on 26.11.15.
// Copyright © 2015 Francesco Quinzan. All rights reserved.
//
#include "MMASib_experiments.hpp"
void MMASib_experiments::parameter_calibration(string dir, int seed){
randomEngine::set_seed(seed);
int sample_size = 100;
typedef std::numeric_limits< double > dbl;
/* variables */
int dimension = 100;
double sigma = ::sqrt(10);
int r = 1;
/* output file */
ofstream MMASib_results;
MMASib_results.precision(dbl::max_digits10);
MMASib_results.open(dir + "/MMASib_parameter_calibration.txt");
header::make_header(&MMASib_results, "MMASib", seed);
MMASib_experiments::make_legend(&MMASib_results);
for (int n_ants = 2; n_ants < 15; n_ants++){
for (double evaporation = 0.03; evaporation < 0.06; evaporation = evaporation + 0.002){
ACO ACO(dimension, n_ants, evaporation);
ACO.posteriorNoise(sigma, r);
/* run for given number of steps */
for (int k = 0; k < sample_size; k++){
MMASib_results << dimension << " ";
MMASib_results << n_ants << " ";
MMASib_results << evaporation << " ";
MMASib_results << sigma << " ";
MMASib_results << r << " ";
MMASib_results << ACO.run()*n_ants*r << endl;
}
}
}
MMASib_results.close();
return;
};
void MMASib_experiments::r_analysis(string dir, int seed){
randomEngine::set_seed(seed);
int sample_size = 100;
/* variables */
int dimension = 100;
double evaporation = 0.045;
int n_ants = 5;
double sigma = ::sqrt(100);
int results = 0;
/* output file */
ofstream MMASib_results;
MMASib_results.open(dir + "/MMASib_r_analysis.txt");
header::make_header(&MMASib_results, "MMASib", seed);
MMASib_experiments::make_legend(&MMASib_results);
for (int r = 1; r < 100; r++){
ACO ACO(dimension, n_ants, evaporation);
ACO.posteriorNoise(sigma, r);
/* run for given number of steps */
for (int k = 0; k < sample_size; k++){
results = ACO.run();
results = results*n_ants*r;
cout << results << endl;
MMASib_results << dimension << " ";
MMASib_results << n_ants << " ";
MMASib_results << evaporation << " ";
MMASib_results << sigma << " ";
MMASib_results << r << " ";
MMASib_results << results << endl;
}
}
MMASib_results.close();
return;
};
void MMASib_experiments::variance_analysis(string dir, int seed){
randomEngine::set_seed(seed);
int sample_size = 100;
/* variables */
int dimension = 100;
double evaporation = 0.045;
int n_ants = 5;
int r = 5;
int results = 0;
/* output file */
ofstream MMASib_results;
MMASib_results.open(dir + "/MMASib_variance_analysis.txt");
header::make_header(&MMASib_results, "MMASib", seed);
MMASib_experiments::make_legend(&MMASib_results);
for (double sigma = ::sqrt(0); sigma < ::sqrt(10)*14; sigma = sigma + ::sqrt(10)/2){
ACO ACO(dimension, n_ants, evaporation);
ACO.posteriorNoise(sigma, r);
/* run for given number of steps */
for (int k = 10; k < sample_size; k++){
results = ACO.run()*n_ants*r;
cout << results << endl;
MMASib_results << dimension << " ";
MMASib_results << n_ants << " ";
MMASib_results << evaporation << " ";
MMASib_results << sigma << " ";
MMASib_results << r << " ";
MMASib_results << results << endl;
}
}
MMASib_results.close();
return;
};
void MMASib_experiments::make_legend(ofstream* file){
*file << "DIMENSION" << " ";
*file << "N_ANTS" << " ";
*file << "EVAPORATION" << " ";
*file << "SIGMA" << " ";
*file << "N_RE_EVALUATIONS" << " ";
*file << "N_FITNESS_EVALUATIONS" << endl;
}; | 26.779141 | 95 | 0.529439 | fq00 |
ecd3aae26ea04430c1ff48dcc3b931f294fa0f57 | 915 | cpp | C++ | Backends/System/Windows/Sources/Kore/Input/Mouse.cpp | psmtec/Kore | 3665641e1c411bfafbf55aa946dc8636eb379a12 | [
"Zlib"
] | null | null | null | Backends/System/Windows/Sources/Kore/Input/Mouse.cpp | psmtec/Kore | 3665641e1c411bfafbf55aa946dc8636eb379a12 | [
"Zlib"
] | null | null | null | Backends/System/Windows/Sources/Kore/Input/Mouse.cpp | psmtec/Kore | 3665641e1c411bfafbf55aa946dc8636eb379a12 | [
"Zlib"
] | null | null | null | #include "../pch.h"
#include <Kore/Input/Mouse.h>
#include <Kore/System.h>
#include <Kore/Window.h>
#include <Windows.h>
using namespace Kore;
void Mouse::_lock(int windowId, bool truth) {
show(!truth);
if (truth) {
HWND handle = Kore::Window::get(windowId)->_data.handle;
SetCapture(handle);
RECT rect;
GetWindowRect(handle, &rect);
ClipCursor(&rect);
}
else {
ReleaseCapture();
ClipCursor(nullptr);
}
}
bool Mouse::canLock(int windowId) {
return true;
}
void Mouse::show(bool truth) {
ShowCursor(truth);
}
void Mouse::setPosition(int windowId, int x, int y) {
POINT point;
point.x = x;
point.y = y;
ClientToScreen(Window::get(windowId)->_data.handle, &point);
SetCursorPos(point.x, point.y);
}
void Mouse::getPosition(int windowId, int& x, int& y) {
POINT point;
GetCursorPos(&point);
ScreenToClient(Window::get(windowId)->_data.handle, &point);
x = point.x;
y = point.y;
}
| 18.673469 | 61 | 0.68306 | psmtec |
ecd48d99a78f6aacdb6798713d2c0aa136742fb2 | 2,780 | hxx | C++ | include/occutils/ListUtils.hxx | ulikoehler/OCCUtil | 39d72ecf35dd3840ed23efac0b335bd4c9d16dad | [
"Apache-2.0"
] | 29 | 2019-08-12T14:03:11.000Z | 2022-03-11T17:38:47.000Z | include/occutils/ListUtils.hxx | ulikoehler/OCCUtil | 39d72ecf35dd3840ed23efac0b335bd4c9d16dad | [
"Apache-2.0"
] | 1 | 2021-12-09T02:28:10.000Z | 2021-12-09T02:28:10.000Z | include/occutils/ListUtils.hxx | ulikoehler/OCCUtil | 39d72ecf35dd3840ed23efac0b335bd4c9d16dad | [
"Apache-2.0"
] | 6 | 2020-07-28T15:57:11.000Z | 2022-02-24T01:52:34.000Z | #pragma once
#include <NCollection_List.hxx>
#include <utility> // std::pair<>
#include <vector>
#include <list>
#include <initializer_list>
namespace OCCUtils {
namespace ListUtils {
/**
* Split a NCollection_List<T> into
* a head list and a tail list.
*/
template<typename T>
std::pair<NCollection_List<T>, NCollection_List<T>> SplitIntoHeadAndTail(
const NCollection_List<T>& arg,
size_t headSize
) {
auto ret = std::make_pair(NCollection_List<T>(), NCollection_List<T>());
// Iterate arg
for(const T& value : arg) {
if(headSize > 0) {
ret.first.Append(value);
headSize--;
} else {
ret.second.Append(value);
}
}
return ret;
}
/**
* Convert any STL or STL-like container of type T
* to a NCollection_List<T>.
*/
template<template<typename, typename> typename Container, typename T, typename Allocator>
NCollection_List<T> ToOCCList(const Container<T, Allocator>& args) {
NCollection_List<T> ret;
for(const T& arg : args) {
ret.Append(arg);
}
return ret;
}
/**
* Convert any STL or STL-like container of type T
* to a NCollection_List<T>.
*/
template<typename T>
NCollection_List<T> ToOCCList(const std::initializer_list<T>& args) {
NCollection_List<T> ret;
for(const T& arg : args) {
ret.Append(arg);
}
return ret;
}
/**
* Convert any simple-style template container to an OCC list.
* Also: Convenience to convert an initializer list,
* e.g. {arg1, arg2, arg3} to an OCC list
*/
template<template<typename> typename Container, typename T>
NCollection_List<T> ToOCCList(const Container<T>& args) {
NCollection_List<T> ret;
for(const T& arg : args) {
ret.Append(arg);
}
return ret;
}
template<typename T>
std::vector<T> ToSTLVector(const NCollection_List<T>& args) {
std::vector<T> ret;
ret.reserve(args.size());
for(const T& arg : args) {
ret.push_back(arg);
}
return ret;
}
template<typename T>
std::list<T> ToSTLList(const NCollection_List<T>& args) {
std::list<T> ret;
for(const T& arg : args) {
ret.push_back(arg);
}
return ret;
}
}
} | 29.892473 | 97 | 0.503237 | ulikoehler |
ecd6361fb7eb8012b86da23f244376a3df282638 | 3,958 | cpp | C++ | engine/utils/grabfont.cpp | jpmorris33/ire | d6a0a9468c1f98010c5959be301b717f02336895 | [
"BSD-3-Clause"
] | null | null | null | engine/utils/grabfont.cpp | jpmorris33/ire | d6a0a9468c1f98010c5959be301b717f02336895 | [
"BSD-3-Clause"
] | 8 | 2020-03-29T21:03:23.000Z | 2020-04-11T23:28:14.000Z | engine/utils/grabfont.cpp | jpmorris33/ire | d6a0a9468c1f98010c5959be301b717f02336895 | [
"BSD-3-Clause"
] | 1 | 2020-06-11T16:54:37.000Z | 2020-06-11T16:54:37.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IRE_FNT1 0x31544e46
#define IRE_FNT2 0x32544e46
int Getpixel(int x, int y);
int FindNextRow(int start, int *height);
int FindNextCharacter(int x, int y, int *width);
int W,H;
int nullcolour=0;
unsigned char buffer[131072];
int main(int argc, char *argv[])
{
FILE *fpo,*fpi;
char filename[256];
int ctr;
unsigned char Pal[768];
int val,w,h,mw,mh,x,y;
int GotPal=0;
int colour=0;
mw=mh=0;
memset(Pal,0,768);
if(argc < 3 || (argv[1][0] == '-'))
{
printf("Usage: grabfont <input.cel> <output.fnt> [-colour]\n");
printf(" Attempts to extract a font from a single large .CEL grid\n");
exit(1);
}
// Colour or monochrome?
if(argc > 3)
if(strcmp(argv[3],"-colour") == 0 || strcmp(argv[3],"-color") == 0)
colour=1;
fpi=fopen(argv[1],"rb");
if(!fpi)
{
printf("Error opening input file '%s'\n",argv[1]);
exit(1);
}
val=0;
fread(&val,1,2,fpi);
if(val != 0x9119)
{
printf("Error: File is not a valid Animator 1 CEL file\n");
exit(1);
}
w=0;
fread(&w,1,2,fpi);
h=0;
fread(&h,1,2,fpi);
// Global size
W=w;
H=h;
val=w*h;
if(val > 131071)
{
printf("Error: %s is %d bytes long, exceeds 128k!\n",filename,val);
exit(1);
}
fseek(fpi,32L,SEEK_SET); // Skip to the raw data
fread(Pal,1,768,fpi);
fread(buffer,1,val,fpi);
fclose(fpi);
// Read in the CEL file, now try and create an output file
fpo=fopen(argv[2],"wb");
if(!fpo)
{
printf("Error: Could not create file '%s'\n",argv[2]);
exit(1);
}
// Write header
if(colour)
val=IRE_FNT2;
else
val=IRE_FNT1;
fwrite(&val,1,4,fpo);
// Write blank characters up to SPACE
val=0; // W&H = 0 for a null entry
for(ctr=0;ctr<32;ctr++)
fwrite(&val,1,4,fpo); // W&H
nullcolour=buffer[0]; // This is the invalid colour
ctr=32; // start from SPACE
y=0;
do
{
if(ctr>255)
break; // Too many characters
y=FindNextRow(y,&h);
if(y == -1 || h < 1)
break;
// printf("Row start at %d for %d pixels\n",y,h);
x=0;
do
{
if(ctr>255)
break; // Too many characters
x=FindNextCharacter(x,y,&w);
if(x == -1 || w < 1)
break;
// printf("Col start at %d for %d pixels\n",x,w);
// Okay, we have a character
if(w>mw)
mw=w;
if(h>mh)
mh=h;
fwrite(&w,1,2,fpo); // Width
fwrite(&h,1,2,fpo); // Height
for(int vy=0;vy<h;vy++)
for(int vx=0;vx<w;vx++)
fputc(Getpixel(vx+x,vy+y),fpo);
printf("Added %d (%c)\n",ctr,ctr);
ctr++; // Another character written
x+=w;
} while(x < W);
y+=h;
} while(y < H);
// Okay, now write the remaining entries, starting from whatever ctr is at the moment
val=0; // W&H = 0 for a null entry
for(;ctr<256;ctr++)
fwrite(&val,1,4,fpo); // W&H
// Palette conversion
for(ctr=0;ctr<768;ctr++)
Pal[ctr]=Pal[ctr]<<2;
if(colour)
fwrite(Pal,1,768,fpo);
fclose(fpo);
printf("Wrote %s font file %s\n",colour?"colour":"monochrome",argv[1]);
printf("Largest character was %dx%d pixels\n",mw,mh);
}
int Getpixel(int x, int y)
{
if(x<0 || x>=W)
return -1;
if(y<0 || y>=H)
return -1;
return buffer[(y*W)+x];
}
//
// Find a row of characters
//
int FindNextRow(int start, int *height)
{
int x,y;
int startrow=-1;
int endrow=-1;
int found;
*height=0;
found=0;
for(y=start;y<H;y++)
{
for(x=0;x<W;x++)
if(Getpixel(x,y) != nullcolour)
{
found=1;
break;
}
if(found)
{
startrow=y;
break;
}
}
if(startrow == -1)
return -1;
// Find end of row
for(y=startrow;y<H;y++)
{
found=0;
for(x=0;x<W;x++)
if(Getpixel(x,y) != nullcolour)
found=1;
if(!found)
{
endrow=y;
break;
}
}
if(endrow == -1)
return -1;
*height=endrow-startrow;
return startrow;
}
int FindNextCharacter(int x, int y, int *width)
{
int ctr;
int st=-1;
int nd=-1;
*width=0;
for(ctr=x;ctr<W;ctr++)
if(Getpixel(ctr,y) != nullcolour)
{
st=ctr;
break;
}
if(st == -1)
return -1;
for(ctr=st;ctr<W;ctr++)
if(Getpixel(ctr,y) == nullcolour)
{
nd=ctr;
break;
}
if(nd == -1)
return -1;
*width=nd-st;
return st;
} | 15.281853 | 85 | 0.602072 | jpmorris33 |
ecd9dde3446b314caf24c7374a0cbd70cf1a7f97 | 1,366 | cpp | C++ | soil.cpp | ZacharyWesterman/pico-sandbox | 4ab83b7a52242a6a684bf5aef3cd39fb1b4d9c30 | [
"Unlicense"
] | null | null | null | soil.cpp | ZacharyWesterman/pico-sandbox | 4ab83b7a52242a6a684bf5aef3cd39fb1b4d9c30 | [
"Unlicense"
] | null | null | null | soil.cpp | ZacharyWesterman/pico-sandbox | 4ab83b7a52242a6a684bf5aef3cd39fb1b4d9c30 | [
"Unlicense"
] | null | null | null | #include "soil.hpp"
#include "pico/stdlib.h"
soil::soil(i2c_inst_t* i2c_instance, uint i2c_address) noexcept
{
i2c = i2c_instance;
address = i2c_address;
}
float soil::temperature(char degrees) const noexcept
{
//Request temperature
const uint8_t txdata[2] = { 0x00, 0x04 };
i2c_write_blocking(i2c, address, txdata, 2, false);
sleep_ms(1);//wait a little bit for response.
//Read temperature
uint8_t rxdata[4];
i2c_read_blocking(i2c, address, rxdata, 4, false);
//Convert to Celcius
int32_t tempdata = ((int32_t)rxdata[0] << 24) | ((int32_t)rxdata[1] << 16) | ((int32_t)rxdata[2] << 8) | (int32_t)rxdata[3];
float temp = (1.0f / (1UL << 16)) * tempdata;
//Convert to chosen scale.
//Note "efficiency" doesn't really matter here,
//since we're already waiting 1ms above.
if (degrees == 'C') return temp; //Celcius
if (degrees == 'F') return (temp * 1.8) + 32; //Fahrenheit
if (degrees == 'R') return temp * 1.8; //Rankine
return temp + 273; //Default to Kelvin.
}
uint16_t soil::moisture() const noexcept
{
//Request moisture measurement
const uint8_t txdata[2] = { 0x0F, 0x10 };
i2c_write_blocking(i2c, address, txdata, 2, false);
sleep_ms(10); //delay to allow sampling
//Read moisture measurement
uint8_t rxdata[2];
i2c_read_blocking(i2c, address, rxdata, 2, false);
return ((uint16_t)rxdata[0] << 8) | (uint16_t)rxdata[1];
}
| 27.32 | 125 | 0.688141 | ZacharyWesterman |
ecdbd986f8b950e695d4919071ecaa7cd73a1e7c | 1,919 | hpp | C++ | include/elemental/matrices/Identity.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/matrices/Identity.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/matrices/Identity.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef MATRICES_IDENTITY_HPP
#define MATRICES_IDENTITY_HPP
#include "elemental/blas-like/level1/Zero.hpp"
namespace elem {
template<typename T>
inline void
Identity( Matrix<T>& I, int m, int n )
{
#ifndef RELEASE
CallStackEntry entry("Identity");
#endif
I.ResizeTo( m, n );
MakeIdentity( I );
}
template<typename T,Distribution U,Distribution V>
inline void
Identity( DistMatrix<T,U,V>& I, int m, int n )
{
#ifndef RELEASE
CallStackEntry entry("Identity");
#endif
I.ResizeTo( m, n );
MakeIdentity( I );
}
template<typename T>
inline void
MakeIdentity( Matrix<T>& I )
{
#ifndef RELEASE
CallStackEntry entry("MakeIdentity");
#endif
Zero( I );
const int m = I.Height();
const int n = I.Width();
for( int j=0; j<std::min(m,n); ++j )
I.Set( j, j, T(1) );
}
template<typename T,Distribution U,Distribution V>
inline void
MakeIdentity( DistMatrix<T,U,V>& I )
{
#ifndef RELEASE
CallStackEntry entry("MakeIdentity");
#endif
Zero( I.Matrix() );
const int localHeight = I.LocalHeight();
const int localWidth = I.LocalWidth();
const int colShift = I.ColShift();
const int rowShift = I.RowShift();
const int colStride = I.ColStride();
const int rowStride = I.RowStride();
for( int jLocal=0; jLocal<localWidth; ++jLocal )
{
const int j = rowShift + jLocal*rowStride;
for( int iLocal=0; iLocal<localHeight; ++iLocal )
{
const int i = colShift + iLocal*colStride;
if( i == j )
I.SetLocal( iLocal, jLocal, T(1) );
}
}
}
} // namespace elem
#endif // ifndef MATRICES_IDENTITY_HPP
| 23.120482 | 73 | 0.647733 | ahmadia |
ecdc6d90eb6a1c1ced869705a88cc0f91f038414 | 1,530 | cpp | C++ | leet/ac/1008.construct-binary-search-tree-from-preorder-traversal.cpp | vitorgt/problem-solving | 11fa59de808f7a113c08454b4aca68b01410892e | [
"MIT"
] | null | null | null | leet/ac/1008.construct-binary-search-tree-from-preorder-traversal.cpp | vitorgt/problem-solving | 11fa59de808f7a113c08454b4aca68b01410892e | [
"MIT"
] | null | null | null | leet/ac/1008.construct-binary-search-tree-from-preorder-traversal.cpp | vitorgt/problem-solving | 11fa59de808f7a113c08454b4aca68b01410892e | [
"MIT"
] | null | null | null | #include "../TreeNode.hpp"
class Solution { // O(n)
public:
const int INF = 0x3f3f3f3f;
int i = 0;
TreeNode *bstFromPreorder(vector<int> &preorder, int key, int min,
int max) {
if (i < preorder.size() && min < key && key < max) {
TreeNode *root = new TreeNode(key);
i++;
if (i < preorder.size()) {
root->left = bstFromPreorder(preorder, preorder[i], min, key);
root->right = bstFromPreorder(preorder, preorder[i], key, max);
}
return root;
}
return NULL;
}
TreeNode *bstFromPreorder(vector<int> &preorder) {
return bstFromPreorder(preorder, preorder[i], -INF, INF);
}
};
class solutionB { // O(n^2)
public:
TreeNode *bstFromPreorder(vector<int> &preorder) {
TreeNode *root = new TreeNode(preorder[0]), *aux = root;
for (int i = 1; i < preorder.size(); i++, aux = root) {
while (true) {
if (preorder[i] < aux->val) {
if (!aux->left) {
aux->left = new TreeNode(preorder[i]);
break;
}
aux = aux->left;
} else {
if (!aux->right) {
aux->right = new TreeNode(preorder[i]);
break;
}
aux = aux->right;
}
}
}
return root;
}
};
| 31.22449 | 79 | 0.434641 | vitorgt |
ecdcd7a2bf47ea5e9081e0e6b305cd7101aeb747 | 1,603 | hpp | C++ | third_party/boost/simd/constant/signmask.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/constant/signmask.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/constant/signmask.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_SIGNMASK_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_SIGNMASK_HPP_INCLUDED
/*!
@ingroup group-constant
@defgroup constant-Signmask Signmask (function template)
Generates a constant able to mask the sign bit of any value.
@headerref{<boost/simd/constant/signmask.hpp>}
@par Description
1. @code
template<typename T> T Signmask();
@endcode
2. @code
template<typename T> T Signmask( boost::simd::as_<T> const& target );
@endcode
Generates a value of type @c T that evaluates to a value where the most significant bit is set
to 1 (includign for unsigned type).
@par Parameters
| Name | Description |
|--------------------:|:--------------------------------------------------------------------|
| **target** | a [placeholder](@ref type-as) value encapsulating the constant type |
@par Return Value
A value of type @c T that evaluates to `bitwise_cast<T>(1 << sizeof(scalar_of_t<T>)*8-1)`
@par Requirements
- **T** models Value
**/
#include <boost/simd/constant/scalar/signmask.hpp>
#include <boost/simd/constant/simd/signmask.hpp>
#endif
| 30.826923 | 100 | 0.547723 | SylvainCorlay |
ecde0c61eed21d8e946bb7adf80b461bab2844d0 | 935 | hpp | C++ | src/Enums.hpp | jason-markham/pinchot-c-api | 6b28f2b021a249e02b0a9ac87abad4e289cfbd9e | [
"BSD-3-Clause"
] | null | null | null | src/Enums.hpp | jason-markham/pinchot-c-api | 6b28f2b021a249e02b0a9ac87abad4e289cfbd9e | [
"BSD-3-Clause"
] | null | null | null | src/Enums.hpp | jason-markham/pinchot-c-api | 6b28f2b021a249e02b0a9ac87abad4e289cfbd9e | [
"BSD-3-Clause"
] | 2 | 2020-11-24T00:56:02.000Z | 2021-12-07T04:12:53.000Z | /**
* Copyright (c) JoeScan Inc. All Rights Reserved.
*
* Licensed under the BSD 3 Clause License. See LICENSE.txt in the project
* root for license information.
*/
#ifndef JOESCAN_ENUMS_H
#define JOESCAN_ENUMS_H
#include "enum.h"
namespace joescan {
// This enum has to agree with the `ConnectionType` enum in the C# API
BETTER_ENUM(ConnectionType, uint8_t, Normal = 0, Mappler = 1)
BETTER_ENUM(ServerConnectionStatus, uint8_t, Disconnected = 0, Connected = 1,
Scanning = 2)
BETTER_ENUM(
UdpPacketType, uint8_t, Invalid = 0,
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// This field is deprecated and kept for historical purposes. Do not use.
Connect = 1,
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
StartScanning = 2, Status = 3, SetWindow = 4, GetMappleTable = 5,
Disconnect = 6, BroadcastConnect = 7)
} // namespace joescan
#endif
| 30.16129 | 77 | 0.59893 | jason-markham |
ecde30044bc1faec52caa12086edf74dc8236e7f | 2,683 | cpp | C++ | tests/Waves/SignerTests.cpp | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | 2 | 2020-11-16T08:06:30.000Z | 2021-06-18T03:21:44.000Z | tests/Waves/SignerTests.cpp | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | null | null | null | tests/Waves/SignerTests.cpp | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | null | null | null | // Copyright © 2017-2020 Khaos Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "HexCoding.h"
#include "PublicKey.h"
#include "Waves/Signer.h"
#include "Waves/Transaction.h"
#include <TrezorCrypto/sodium/keypair.h>
#include <gtest/gtest.h>
using namespace TW;
using namespace TW::Waves;
TEST(WavesSigner, SignTransaction) {
const auto privateKey =
PrivateKey(parse_hex("9864a747e1b97f131fabb6b447296c9b6f0201e79fb3c5356e6c77e89b6a806a"));
const auto publicKeyCurve25519 = privateKey.getPublicKey(TWPublicKeyTypeCURVE25519);
ASSERT_EQ(hex(Data(publicKeyCurve25519.bytes.begin(), publicKeyCurve25519.bytes.end())),
"559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d");
// 3P2uzAzX9XTu1t32GkWw68YFFLwtapWvDds
const auto address = Address(publicKeyCurve25519);
auto input = Proto::SigningInput();
input.set_timestamp(int64_t(1526641218066));
input.set_private_key(privateKey.bytes.data(), privateKey.bytes.size());
auto &message = *input.mutable_transfer_message();
message.set_amount(int64_t(100000000));
message.set_asset(Transaction::WAVES);
message.set_fee(int64_t(100000000));
message.set_fee_asset(Transaction::WAVES);
message.set_to(address.string());
message.set_attachment("falafel");
auto tx1 = Transaction(
input,
/* pub_key */
parse_hex("559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d"));
auto signature = Signer::sign(privateKey, tx1);
EXPECT_EQ(hex(tx1.serializeToSign()),
"0402559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d00000000016372e8"
"52120000000005f5e1000000000005f5e10001570acc4110b78a6d38b34d879b5bba38806202ecf1732f"
"8542000766616c6166656c");
EXPECT_EQ(hex(signature), "af7989256f496e103ce95096b3f52196dd9132e044905fe486da3b829b5e403bcba9"
"5ab7e650a4a33948c2d05cfca2dce4d4df747e26402974490fb4c49fbe8f");
ASSERT_TRUE(publicKeyCurve25519.verify(signature, tx1.serializeToSign()));
}
TEST(WavesSigner, curve25519_pk_to_ed25519) {
const auto publicKeyCurve25519 =
parse_hex("559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d");
auto r = Data();
r.resize(32);
curve25519_pk_to_ed25519(r.data(), publicKeyCurve25519.data());
EXPECT_EQ(hex(r), "ff84c4bfc095df25b01e48807715856d95af93d88c5b57f30cb0ce567ca4ce56");
}
| 43.274194 | 106 | 0.740962 | Khaos-Labs |
ecde5f4777f94c406c33ef92760ed81620808356 | 5,497 | cpp | C++ | FKCore/FKServerConnectionManager.cpp | FajraKatviro/FKFramework2 | 0b55b402c255b50fe07ee568bbf46acd6617a6e4 | [
"MIT"
] | 2 | 2015-10-01T07:25:36.000Z | 2015-11-02T23:14:10.000Z | FKCore/FKServerConnectionManager.cpp | FajraKatviro/FKFramework2 | 0b55b402c255b50fe07ee568bbf46acd6617a6e4 | [
"MIT"
] | 13 | 2015-11-02T22:15:14.000Z | 2015-11-03T21:08:51.000Z | FKCore/FKServerConnectionManager.cpp | FajraKatviro/FKFramework2 | 0b55b402c255b50fe07ee568bbf46acd6617a6e4 | [
"MIT"
] | null | null | null | #include "FKServerConnectionManager.h"
#include "FKServerInfrastructure.h"
#include "FKClientInfrastructureReferent.h"
#include "FKMessage.h"
#include "FKBasicEvent.h"
#include "FKEventObject.h"
#include "FKLogger.h"
#include "FKBasicEventSubjects.h"
/*!
\class FKServerConnectionManager
\brief This class used to process guest connectors at server-side
*/
/*!
* \brief Create manager for \i connector at \i server with \i parent
*/
FKServerConnectionManager::FKServerConnectionManager(FKServerInfrastructure *server, FKConnector *connector, QObject *parent):
FKConnectionManager(connector,parent),_server(server){
FK_CBEGIN
FK_CEND
}
/*!
* \brief Deletes manager
*/
FKServerConnectionManager::~FKServerConnectionManager(){
FK_DBEGIN
FK_DEND
}
void FKServerConnectionManager::processMessage(FKMessage* msg){
FK_MLOGV("Unexpected message from guest to server",msg->subject())
msg->deleteLater();
}
void FKServerConnectionManager::processGuestEvent(FKBasicEvent* ev){
const QString subject=ev->subject();
const QVariant value=ev->value();
ev->deleteLater();
if(subject==FKBasicEventSubject::login){
_server->syncRequest(this,value);
}else{
FK_MLOGV("Unexpected guest event subject from guest to server",subject)
_server->stopGuestConnection(this);
}
}
void FKServerConnectionManager::processBasicEvent(FKBasicEvent* ev){
FK_MLOGV("Unexpected basic event from guest to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManager::processEvent(FKEventObject* ev){
FK_MLOGV("Unexpected event from guest to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManager::incomeMessageError(const QString& msgType, const QString& reason){
FK_MLOGV(QString("Income message error from guest to server: ")+reason,msgType)
}
/*!
\class FKServerConnectionManagerR
\brief This class used to process realm connector at server-side
*/
/*!
* \brief Create manager for \i connector at \i server with \i parent
*/
FKServerConnectionManagerR::FKServerConnectionManagerR(FKServerInfrastructure *server, FKConnector *connector, QObject *parent):
FKConnectionManager(connector,parent),_server(server){
FK_CBEGIN
FK_CEND
}
/*!
* \brief Deletes manager
*/
FKServerConnectionManagerR::~FKServerConnectionManagerR(){
FK_DBEGIN
FK_DEND
}
void FKServerConnectionManagerR::processMessage(FKMessage* msg){
_server->messageFromRealm(msg->subject());
msg->deleteLater();
}
void FKServerConnectionManagerR::processGuestEvent(FKBasicEvent* ev){
FK_MLOGV("Unexpected guest event from realm to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManagerR::processBasicEvent(FKBasicEvent* ev){
const QString subject=ev->subject();
const QVariant value=ev->value();
ev->deleteLater();
if(subject==FKBasicEventSubject::login){
_server->submitLoginRealm(value);
}else if(subject==FKBasicEventSubject::registerRoomType){
_server->registerRoomTypeRespond(value);
}else if(subject==FKBasicEventSubject::removeRoomType){
_server->removeRoomTypeRespond(value);
}else if(subject==FKBasicEventSubject::createRoom){
_server->createRoomRequested(value);
}else if(subject==FKBasicEventSubject::joinRoom){
_server->clientInvited(value);
}else if(subject==FKBasicEventSubject::roomTypeList){
_server->roomTypesNotification(value);
}else{
FK_MLOGV("Unexpected basic event subject from realm to server",subject)
}
}
void FKServerConnectionManagerR::processEvent(FKEventObject* ev){
FK_MLOGV("Unexpected event from realm to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManagerR::incomeMessageError(const QString& msgType, const QString& reason){
FK_MLOGV(QString("Income message error from realm to server: ")+reason,msgType)
}
/*!
\class FKServerConnectionManagerU
\brief This class used to process connectors from users at server-side
*/
/*!
* \brief Create manager for \i connector at \i userSlot with \i parent
*/
FKServerConnectionManagerU::FKServerConnectionManagerU(FKClientInfrastructureReferent* referent, FKConnector *connector, QObject *parent):
FKConnectionManager(connector,parent),_referent(referent){
FK_CBEGIN
FK_CEND
}
/*!
* \brief Deletes manager
*/
FKServerConnectionManagerU::~FKServerConnectionManagerU(){
FK_DBEGIN
FK_DEND
}
void FKServerConnectionManagerU::processMessage(FKMessage* msg){
FK_MLOGV("Unexpected message from user to client referent",msg->subject())
msg->deleteLater();
}
void FKServerConnectionManagerU::processGuestEvent(FKBasicEvent* ev){
FK_MLOGV("Unexpected guest event from user to client referent",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManagerU::processBasicEvent(FKBasicEvent* ev){
const QString subject=ev->subject();
const QVariant value=ev->value();
ev->deleteLater();
if(false/*subject==FKBasicEventSubject::_____*/){
todo;// reconnect event, quit event
}else{
FK_MLOGV("Unexpected basic event subject from user to client referent",subject)
}
}
void FKServerConnectionManagerU::processEvent(FKEventObject* ev){
//_referent->incomeAction(ev);
}
void FKServerConnectionManagerU::incomeMessageError(const QString& msgType, const QString& reason){
FK_MLOGV(QString("Income message error from user to client referent: ")+reason,msgType)
}
| 30.038251 | 138 | 0.744588 | FajraKatviro |
ecde884684663576fef3f92ae1d4f7a5c2ffc33e | 4,811 | hpp | C++ | core/lgraphbase.hpp | MikeAnj/LiveHD_clone | d725a3bebc04457be7eb356f27e3b93969ee8d60 | [
"BSD-3-Clause"
] | 1 | 2022-01-30T03:06:22.000Z | 2022-01-30T03:06:22.000Z | core/lgraphbase.hpp | MikeAnj/LiveHD_clone | d725a3bebc04457be7eb356f27e3b93969ee8d60 | [
"BSD-3-Clause"
] | null | null | null | core/lgraphbase.hpp | MikeAnj/LiveHD_clone | d725a3bebc04457be7eb356f27e3b93969ee8d60 | [
"BSD-3-Clause"
] | null | null | null | // This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#pragma once
#include <iostream>
#include <map>
#include <type_traits>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "iassert.hpp"
#include "lgedge.hpp"
#include "lgraph_base_core.hpp"
#include "mmap_vector.hpp"
class Fwd_edge_iterator;
class Bwd_edge_iterator;
class Fast_edge_iterator;
class Graph_library;
class LGraph_Base : public Lgraph_base_core {
private:
protected:
mmap_lib::vector<Node_internal> node_internal;
static inline constexpr std::string_view unknown_io = "unknown";
Graph_library * library;
absl::flat_hash_map<uint32_t, uint32_t> idx_insert_cache;
Index_ID create_node_space(const Index_ID idx, const Port_ID dst_pid, const Index_ID master_nid, const Index_ID root_nid);
Index_ID get_space_output_pin(const Index_ID idx, const Port_ID dst_pid, Index_ID &root_nid);
Index_ID get_space_output_pin(const Index_ID master_nid, const Index_ID idx, const Port_ID dst_pid, const Index_ID root_nid);
// Index_ID get_space_input_pin(const Index_ID master_nid, const Index_ID idx, bool large = false);
Index_ID create_node_int();
Index_ID add_edge_int(Index_ID dst_nid, Port_ID dst_pid, Index_ID src_nid, Port_ID inp_pid);
Port_ID recompute_io_ports(const Index_ID track_nid);
Index_ID find_idx_from_pid_int(const Index_ID nid, const Port_ID pid) const;
Index_ID find_idx_from_pid(const Index_ID nid, const Port_ID pid) const {
if (likely(node_internal[nid].get_dst_pid() == pid)) { // Common case
return nid;
}
return find_idx_from_pid_int(nid, pid);
}
Index_ID setup_idx_from_pid(const Index_ID nid, const Port_ID pid);
Index_ID get_master_nid(Index_ID idx) const { return node_internal[idx].get_master_root_nid(); }
uint32_t get_bits(Index_ID idx) const {
I(idx < node_internal.size());
I(node_internal[idx].is_root());
return node_internal[idx].get_bits();
}
void set_bits(Index_ID idx, uint32_t bits) {
I(idx < node_internal.size());
I(node_internal[idx].is_root());
node_internal.ref(idx)->set_bits(bits);
}
public:
LGraph_Base() = delete;
LGraph_Base(const LGraph_Base &) = delete;
explicit LGraph_Base(std::string_view _path, std::string_view _name, Lg_type_id lgid) noexcept;
virtual ~LGraph_Base();
virtual void clear();
virtual void sync();
void emplace_back();
#if 1
// WARNING: deprecated: Use get/set_bits(const Node_pin)
void set_bits_pid(Index_ID nid, Port_ID pid, uint32_t bits);
uint32_t get_bits_pid(Index_ID nid, Port_ID pid) const;
uint32_t get_bits_pid(Index_ID nid, Port_ID pid);
#endif
void add_edge(const Index_ID dst_idx, const Index_ID src_idx) {
I(src_idx < node_internal.size());
I(node_internal[src_idx].is_root());
I(dst_idx < node_internal.size());
I(node_internal[dst_idx].is_root());
I(src_idx != dst_idx);
add_edge_int(dst_idx, node_internal[dst_idx].get_dst_pid(), src_idx, node_internal[src_idx].get_dst_pid());
}
void print_stats() const;
const Node_internal &get_node_int(Index_ID idx) const {
I(static_cast<Index_ID>(node_internal.size()) > idx);
return node_internal[idx];
}
/*
Node_internal &get_node_int(Index_ID idx) {
I(static_cast<Index_ID>(node_internal.size()) > idx);
return node_internal[idx];
}
*/
bool is_valid_node(Index_ID nid) const {
if (nid >= node_internal.size())
return false;
return node_internal[nid].is_valid() && node_internal[nid].is_master_root();
}
bool is_valid_node_pin(Index_ID idx) const {
if (idx >= node_internal.size())
return false;
return node_internal[idx].is_valid() && node_internal[idx].is_root();
}
Port_ID get_dst_pid(Index_ID idx) const {
I(static_cast<Index_ID>(node_internal.size()) > idx);
I(node_internal[idx].is_root());
return node_internal[idx].get_dst_pid();
}
bool is_root(Index_ID idx) const {
I(static_cast<Index_ID>(node_internal.size()) > idx);
return node_internal[idx].is_root();
}
static size_t max_size() { return (((size_t)1) << Index_bits) - 1; }
size_t size() const { return node_internal.size(); }
class _init {
public:
_init();
} _static_initializer;
const Graph_library &get_library() const { return *library; }
Graph_library * ref_library() const { return library; }
static void error_int(std::string_view text);
static void warn_int(std::string_view text);
template <typename S, typename... Args>
static void error(const S& format, Args&&... args) {
error_int(fmt::format(format, args...));
}
template <typename S, typename... Args>
static void warn(const S& format, Args&&... args) {
warn_int(fmt::format(format, args...));
}
};
| 31.03871 | 127 | 0.717314 | MikeAnj |
ecdf3edf5748efc3a3def4f73fba7235dc90b9cc | 2,729 | hpp | C++ | src/IceRay/geometry/flat/box.hpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | 2 | 2020-09-04T12:27:15.000Z | 2022-01-17T14:49:40.000Z | src/IceRay/geometry/flat/box.hpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | null | null | null | src/IceRay/geometry/flat/box.hpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | 1 | 2020-09-04T12:27:52.000Z | 2020-09-04T12:27:52.000Z | #ifndef _DDMM_IceRAY_geometry_box_HPP_
#define _DDMM_IceRAY_geometry_box_HPP_
// GS_DDMRM::S_IceRay::S_geometry::GC_box
#include "../_pure/_base.hpp"
#include "../_pure/intersect.hpp"
#include "../_pure/normal.hpp"
#include "../_pure/inside.hpp"
#include "../_pure/distance.hpp"
namespace GS_DDMRM
{
namespace S_IceRay
{
namespace S_geometry
{
class GC_box
: public GS_DDMRM::S_IceRay::S_geometry::S__pure::GC_intersect
, public GS_DDMRM::S_IceRay::S_geometry::S__pure::GC_normal
, public GS_DDMRM::S_IceRay::S_geometry::S__pure::GC_inside
, public GS_DDMRM::S_IceRay::S_geometry::S__pure::GC_distance
{
public:
typedef GS_DDMRM::S_IceRay::S_type::GT_scalar T_scalar;
typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D T_coord;
typedef GS_DDMRM::S_IceRay::S_geometry::S__pure::GC__base T__base;
public:
GC_box( );
GC_box( T_coord const& P_lo, T_coord const& P_hi );
explicit GC_box( T_box const& P_interval );
~GC_box( ){}
public:
void Fv_reset( T_state &P_state )const;
T_size Fv_weight( )const;
bool Fv_box( T_box const& P_box );
public:
bool Fv_intersect( T_scalar &P_lambda, T_state &P_state, T_ray const& P_ray )const;
void Fv_normal ( T_coord &P_normal, T_coord const& P_point, T_state const& P_state )const;
T_location Fv_inside ( T_coord const& P_point/*, T_state const& P_state*/ )const;
T_scalar Fv_distance ( T_coord const& P_point )const;
public:
bool F_load( T_box const& P_box );
bool F_load( T_coord const& P_lo, T_coord const& P_hi );
public:
T_coord const& F_lo()const{ return F_box().lo(); }
bool F_lo( T_coord const& P_lo ){ Fv_box( T_box{ P_lo, F_box().hi() } ); return true; }
public:
T_coord const& F_hi()const{ return F_box().hi(); }
bool F_hi( T_coord const& P_hi ){ Fv_box( T_box{ F_box().lo(), P_hi } ); return true; }
public:
using T__base::F_box;
static bool Fs_valid( T_state const&P_intersect );
static int Fs_side( T_state const&P_intersect );
static T_scalar Fs_min( T_state const&P_intersect );
static T_scalar Fs_max( T_state const&P_intersect );
private:
struct C_intersect;
};
}
}
}
#endif
| 34.544304 | 113 | 0.563576 | dmilos |
ecdf978c6a6c76859033d608991561bffaf574c7 | 108 | cpp | C++ | Engine/source/EtEditor/Rendering/EpoxyGlContext.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | 552 | 2017-08-21T18:12:52.000Z | 2022-03-31T15:41:56.000Z | Engine/source/EtEditor/Rendering/EpoxyGlContext.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | 14 | 2017-08-07T23:36:13.000Z | 2021-05-10T08:41:19.000Z | Engine/source/EtEditor/Rendering/EpoxyGlContext.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | 40 | 2017-10-10T14:42:22.000Z | 2022-03-10T07:14:33.000Z | #include "stdafx.h"
#include "EpoxyGlContext.h"
#include <EtRendering/GraphicsContext/GlContextImpl.hpp>
| 15.428571 | 56 | 0.787037 | NeroBurner |
ece1eff65c6bb09da113047b761b6e7f13020cf3 | 13,135 | cpp | C++ | src/dedicated/console/TextConsoleWin32.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/dedicated/console/TextConsoleWin32.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/dedicated/console/TextConsoleWin32.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// CTextConsoleWin32.cpp: Win32 implementation of the TextConsole class.
//
//////////////////////////////////////////////////////////////////////
#include "TextConsoleWin32.h"
#include "tier0/dbg.h"
#include "utlvector.h"
// Could possibly switch all this code over to using readline. This:
// http://mingweditline.sourceforge.net/?Description
// readline() / add_history(char *)
#ifdef _WIN32
BOOL WINAPI ConsoleHandlerRoutine( DWORD CtrlType )
{
NOTE_UNUSED( CtrlType );
/* TODO ?
if ( CtrlType != CTRL_C_EVENT && CtrlType != CTRL_BREAK_EVENT )
m_System->Stop(); // don't quit on break or ctrl+c
*/
return TRUE;
}
// GetConsoleHwnd() helper function from MSDN Knowledge Base Article Q124103
// needed, because HWND GetConsoleWindow(VOID) is not avaliable under Win95/98/ME
HWND GetConsoleHwnd(void)
{
typedef HWND (WINAPI *PFNGETCONSOLEWINDOW)( VOID );
static PFNGETCONSOLEWINDOW s_pfnGetConsoleWindow = (PFNGETCONSOLEWINDOW) GetProcAddress( GetModuleHandle("kernel32"), "GetConsoleWindow" );
if ( s_pfnGetConsoleWindow )
return s_pfnGetConsoleWindow();
HWND hwndFound; // This is what is returned to the caller.
char pszNewWindowTitle[1024]; // Contains fabricated WindowTitle
char pszOldWindowTitle[1024]; // Contains original WindowTitle
// Fetch current window title.
GetConsoleTitle( pszOldWindowTitle, 1024 );
// Format a "unique" NewWindowTitle.
wsprintf( pszNewWindowTitle,"%d/%d", GetTickCount(), GetCurrentProcessId() );
// Change current window title.
SetConsoleTitle(pszNewWindowTitle);
// Ensure window title has been updated.
Sleep(40);
// Look for NewWindowTitle.
hwndFound = FindWindow( NULL, pszNewWindowTitle );
// Restore original window title.
SetConsoleTitle( pszOldWindowTitle );
return hwndFound;
}
CTextConsoleWin32::CTextConsoleWin32()
{
hinput = NULL;
houtput = NULL;
Attrib = 0;
statusline[0] = '\0';
}
bool CTextConsoleWin32::Init()
{
(void) AllocConsole();
SetTitle( "SOURCE DEDICATED SERVER" );
hinput = GetStdHandle ( STD_INPUT_HANDLE );
houtput = GetStdHandle ( STD_OUTPUT_HANDLE );
if ( !SetConsoleCtrlHandler( &ConsoleHandlerRoutine, TRUE) )
{
Print( "WARNING! TextConsole::Init: Could not attach console hook.\n" );
}
Attrib = FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY ;
SetWindowPos( GetConsoleHwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW );
memset( m_szConsoleText, 0, sizeof( m_szConsoleText ) );
m_nConsoleTextLen = 0;
m_nCursorPosition = 0;
memset( m_szSavedConsoleText, 0, sizeof( m_szSavedConsoleText ) );
m_nSavedConsoleTextLen = 0;
memset( m_aszLineBuffer, 0, sizeof( m_aszLineBuffer ) );
m_nTotalLines = 0;
m_nInputLine = 0;
m_nBrowseLine = 0;
// these are log messages, not related to console
Msg( "\n" );
Msg( "Console initialized.\n" );
return CTextConsole::Init();
}
void CTextConsoleWin32::ShutDown( void )
{
FreeConsole();
}
void CTextConsoleWin32::SetVisible( bool visible )
{
ShowWindow ( GetConsoleHwnd(), visible ? SW_SHOW : SW_HIDE );
m_ConsoleVisible = visible;
}
char * CTextConsoleWin32::GetLine( int index, char *buf, int buflen )
{
while ( 1 )
{
INPUT_RECORD recs[ 1024 ];
unsigned long numread;
unsigned long numevents;
if ( !GetNumberOfConsoleInputEvents( hinput, &numevents ) )
{
Error("CTextConsoleWin32::GetLine: !GetNumberOfConsoleInputEvents");
return NULL;
}
if ( numevents <= 0 )
break;
if ( !ReadConsoleInput( hinput, recs, ARRAYSIZE( recs ), &numread ) )
{
Error("CTextConsoleWin32::GetLine: !ReadConsoleInput");
return NULL;
}
if ( numread == 0 )
return NULL;
for ( int i=0; i < (int)numread; i++ )
{
INPUT_RECORD *pRec = &recs[i];
if ( pRec->EventType != KEY_EVENT )
continue;
if ( pRec->Event.KeyEvent.bKeyDown )
{
// check for cursor keys
if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_UP )
{
ReceiveUpArrow();
}
else if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_DOWN )
{
ReceiveDownArrow();
}
else if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_LEFT )
{
ReceiveLeftArrow();
}
else if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_RIGHT )
{
ReceiveRightArrow();
}
else
{
char ch;
int nLen;
ch = pRec->Event.KeyEvent.uChar.AsciiChar;
switch ( ch )
{
case '\r': // Enter
nLen = ReceiveNewline();
if ( nLen )
{
strncpy( buf, m_szConsoleText, buflen );
buf[ buflen - 1 ] = 0;
return buf;
}
break;
case '\b': // Backspace
ReceiveBackspace();
break;
case '\t': // TAB
ReceiveTab();
break;
default:
if ( ( ch >= ' ') && ( ch <= '~' ) ) // dont' accept nonprintable chars
{
ReceiveStandardChar( ch );
}
break;
}
}
}
}
}
return NULL;
}
void CTextConsoleWin32::Print( char * pszMsg )
{
if ( m_nConsoleTextLen )
{
int nLen;
nLen = m_nConsoleTextLen;
while ( nLen-- )
{
PrintRaw( "\b \b" );
}
}
PrintRaw( pszMsg );
if ( m_nConsoleTextLen )
{
PrintRaw( m_szConsoleText, m_nConsoleTextLen );
}
UpdateStatus();
}
void CTextConsoleWin32::PrintRaw( const char * pszMsg, int nChars )
{
unsigned long dummy;
if ( houtput == NULL )
{
houtput = GetStdHandle ( STD_OUTPUT_HANDLE );
if ( houtput == NULL )
return;
}
if ( nChars <= 0 )
{
nChars = strlen( pszMsg );
if ( nChars <= 0 )
return;
}
// filter out ASCII BEL characters because windows actually plays a
// bell sound, which can be used to lag the server in a DOS attack.
char * pTempBuf = NULL;
for ( int i = 0; i < nChars; ++i )
{
if ( pszMsg[i] == 0x07 /*BEL*/ )
{
if ( !pTempBuf )
{
pTempBuf = ( char * ) malloc( nChars );
memcpy( pTempBuf, pszMsg, nChars );
}
pTempBuf[i] = '.';
}
}
WriteFile( houtput, pTempBuf ? pTempBuf : pszMsg, nChars, &dummy, NULL );
free( pTempBuf ); // usually NULL
}
int CTextConsoleWin32::GetWidth( void )
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
int nWidth;
nWidth = 0;
if ( GetConsoleScreenBufferInfo( houtput, &csbi ) )
{
nWidth = csbi.dwSize.X;
}
if ( nWidth <= 1 )
nWidth = 80;
return nWidth;
}
void CTextConsoleWin32::SetStatusLine( char * pszStatus )
{
strncpy( statusline, pszStatus, 80 );
statusline[ 79 ] = '\0';
UpdateStatus();
}
void CTextConsoleWin32::UpdateStatus( void )
{
COORD coord;
DWORD dwWritten = 0;
WORD wAttrib[ 80 ];
for ( int i = 0; i < 80; i++ )
{
wAttrib[i] = Attrib; //FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY ;
}
coord.X = coord.Y = 0;
WriteConsoleOutputAttribute( houtput, wAttrib, 80, coord, &dwWritten );
WriteConsoleOutputCharacter( houtput, statusline, 80, coord, &dwWritten );
}
void CTextConsoleWin32::SetTitle( char * pszTitle )
{
SetConsoleTitle( pszTitle );
}
void CTextConsoleWin32::SetColor(WORD attrib)
{
Attrib = attrib;
}
int CTextConsoleWin32::ReceiveNewline( void )
{
int nLen = 0;
PrintRaw( "\n" );
if ( m_nConsoleTextLen )
{
nLen = m_nConsoleTextLen;
m_szConsoleText[ m_nConsoleTextLen ] = 0;
m_nConsoleTextLen = 0;
m_nCursorPosition = 0;
// cache line in buffer, but only if it's not a duplicate of the previous line
if ( ( m_nInputLine == 0 ) || ( strcmp( m_aszLineBuffer[ m_nInputLine - 1 ], m_szConsoleText ) ) )
{
strncpy( m_aszLineBuffer[ m_nInputLine ], m_szConsoleText, MAX_CONSOLE_TEXTLEN );
m_nInputLine++;
if ( m_nInputLine > m_nTotalLines )
m_nTotalLines = m_nInputLine;
if ( m_nInputLine >= MAX_BUFFER_LINES )
m_nInputLine = 0;
}
m_nBrowseLine = m_nInputLine;
}
return nLen;
}
void CTextConsoleWin32::ReceiveBackspace( void )
{
int nCount;
if ( m_nCursorPosition == 0 )
{
return;
}
m_nConsoleTextLen--;
m_nCursorPosition--;
PrintRaw( "\b" );
for ( nCount = m_nCursorPosition; nCount < m_nConsoleTextLen; nCount++ )
{
m_szConsoleText[ nCount ] = m_szConsoleText[ nCount + 1 ];
PrintRaw( m_szConsoleText + nCount, 1 );
}
PrintRaw( " " );
nCount = m_nConsoleTextLen;
while ( nCount >= m_nCursorPosition )
{
PrintRaw( "\b" );
nCount--;
}
m_nBrowseLine = m_nInputLine;
}
void CTextConsoleWin32::ReceiveTab( void )
{
CUtlVector<char *> matches;
m_szConsoleText[ m_nConsoleTextLen ] = 0;
if ( matches.Count() == 0 )
{
return;
}
if ( matches.Count() == 1 )
{
char * pszCmdName;
char * pszRest;
pszCmdName = matches[0];
pszRest = pszCmdName + strlen( m_szConsoleText );
if ( pszRest )
{
PrintRaw( pszRest );
strcat( m_szConsoleText, pszRest );
m_nConsoleTextLen += strlen( pszRest );
PrintRaw( " " );
strcat( m_szConsoleText, " " );
m_nConsoleTextLen++;
}
}
else
{
int nLongestCmd;
int nTotalColumns;
int nCurrentColumn;
char * pszCurrentCmd;
int i = 0;
nLongestCmd = 0;
pszCurrentCmd = matches[0];
while ( pszCurrentCmd )
{
if ( (int)strlen( pszCurrentCmd) > nLongestCmd )
{
nLongestCmd = strlen( pszCurrentCmd);
}
i++;
pszCurrentCmd = (char *)matches[i];
}
nTotalColumns = ( GetWidth() - 1 ) / ( nLongestCmd + 1 );
nCurrentColumn = 0;
PrintRaw( "\n" );
// Would be nice if these were sorted, but not that big a deal
pszCurrentCmd = matches[0];
i = 0;
while ( pszCurrentCmd )
{
char szFormatCmd[ 256 ];
nCurrentColumn++;
if ( nCurrentColumn > nTotalColumns )
{
PrintRaw( "\n" );
nCurrentColumn = 1;
}
Q_snprintf( szFormatCmd, sizeof(szFormatCmd), "%-*s ", nLongestCmd, pszCurrentCmd );
PrintRaw( szFormatCmd );
i++;
pszCurrentCmd = matches[i];
}
PrintRaw( "\n" );
PrintRaw( m_szConsoleText );
// TODO: Tack on 'common' chars in all the matches, i.e. if I typed 'con' and all the
// matches begin with 'connect_' then print the matches but also complete the
// command up to that point at least.
}
m_nCursorPosition = m_nConsoleTextLen;
m_nBrowseLine = m_nInputLine;
}
void CTextConsoleWin32::ReceiveStandardChar( const char ch )
{
int nCount;
// If the line buffer is maxed out, ignore this char
if ( m_nConsoleTextLen >= ( sizeof( m_szConsoleText ) - 2 ) )
{
return;
}
nCount = m_nConsoleTextLen;
while ( nCount > m_nCursorPosition )
{
m_szConsoleText[ nCount ] = m_szConsoleText[ nCount - 1 ];
nCount--;
}
m_szConsoleText[ m_nCursorPosition ] = ch;
PrintRaw( m_szConsoleText + m_nCursorPosition, m_nConsoleTextLen - m_nCursorPosition + 1 );
m_nConsoleTextLen++;
m_nCursorPosition++;
nCount = m_nConsoleTextLen;
while ( nCount > m_nCursorPosition )
{
PrintRaw( "\b" );
nCount--;
}
m_nBrowseLine = m_nInputLine;
}
void CTextConsoleWin32::ReceiveUpArrow( void )
{
int nLastCommandInHistory;
nLastCommandInHistory = m_nInputLine + 1;
if ( nLastCommandInHistory > m_nTotalLines )
{
nLastCommandInHistory = 0;
}
if ( m_nBrowseLine == nLastCommandInHistory )
{
return;
}
if ( m_nBrowseLine == m_nInputLine )
{
if ( m_nConsoleTextLen > 0 )
{
// Save off current text
strncpy( m_szSavedConsoleText, m_szConsoleText, m_nConsoleTextLen );
// No terminator, it's a raw buffer we always know the length of
}
m_nSavedConsoleTextLen = m_nConsoleTextLen;
}
m_nBrowseLine--;
if ( m_nBrowseLine < 0 )
{
m_nBrowseLine = m_nTotalLines - 1;
}
while ( m_nConsoleTextLen-- ) // delete old line
{
PrintRaw( "\b \b" );
}
// copy buffered line
PrintRaw( m_aszLineBuffer[ m_nBrowseLine ] );
strncpy( m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN );
m_nConsoleTextLen = strlen( m_aszLineBuffer[ m_nBrowseLine ] );
m_nCursorPosition = m_nConsoleTextLen;
}
void CTextConsoleWin32::ReceiveDownArrow( void )
{
if ( m_nBrowseLine == m_nInputLine )
{
return;
}
m_nBrowseLine++;
if ( m_nBrowseLine > m_nTotalLines )
{
m_nBrowseLine = 0;
}
while ( m_nConsoleTextLen-- ) // delete old line
{
PrintRaw( "\b \b" );
}
if ( m_nBrowseLine == m_nInputLine )
{
if ( m_nSavedConsoleTextLen > 0 )
{
// Restore current text
strncpy( m_szConsoleText, m_szSavedConsoleText, m_nSavedConsoleTextLen );
// No terminator, it's a raw buffer we always know the length of
PrintRaw( m_szConsoleText, m_nSavedConsoleTextLen );
}
m_nConsoleTextLen = m_nSavedConsoleTextLen;
}
else
{
// copy buffered line
PrintRaw( m_aszLineBuffer[ m_nBrowseLine ] );
strncpy( m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN );
m_nConsoleTextLen = strlen( m_aszLineBuffer[ m_nBrowseLine ] );
}
m_nCursorPosition = m_nConsoleTextLen;
}
void CTextConsoleWin32::ReceiveLeftArrow( void )
{
if ( m_nCursorPosition == 0 )
{
return;
}
PrintRaw( "\b" );
m_nCursorPosition--;
}
void CTextConsoleWin32::ReceiveRightArrow( void )
{
if ( m_nCursorPosition == m_nConsoleTextLen )
{
return;
}
PrintRaw( m_szConsoleText + m_nCursorPosition, 1 );
m_nCursorPosition++;
}
#endif // _WIN32
| 20.364341 | 140 | 0.659536 | DeadZoneLuna |
ece3bc32ec565796b3f4da56d7fe87f6c8c112bd | 974 | cpp | C++ | src/engine/EngineInterface.cpp | Arkshine/PrototypeEngine | 6833b931ca02934dd5f68377fc8c486f01103841 | [
"Unlicense"
] | 2 | 2018-10-09T14:42:39.000Z | 2021-02-07T21:41:00.000Z | src/engine/EngineInterface.cpp | Arkshine/PrototypeEngine | 6833b931ca02934dd5f68377fc8c486f01103841 | [
"Unlicense"
] | null | null | null | src/engine/EngineInterface.cpp | Arkshine/PrototypeEngine | 6833b931ca02934dd5f68377fc8c486f01103841 | [
"Unlicense"
] | 1 | 2018-10-09T14:42:41.000Z | 2018-10-09T14:42:41.000Z | #include "Platform.h"
#include "Engine.h"
#include "FilePaths.h"
#include "EngineInterface.h"
#ifdef WIN32
//See post VS 2015 update 3 delayimp.h for the reason why this has to be defined. - Solokiller
#define DELAYIMP_INSECURE_WRITABLE_HOOKS
#include <delayimp.h>
FARPROC WINAPI DelayHook(
unsigned dliNotify,
PDelayLoadInfo pdli
)
{
if( dliNotify == dliNotePreLoadLibrary )
{
if( strcmp( pdli->szDll, "Tier1.dll" ) == 0 )
{
char szPath[ MAX_PATH ];
if( !( *g_Engine.GetMyGameDir() ) )
return nullptr;
const int iResult = snprintf( szPath, sizeof( szPath ), "%s/%s/%s", g_Engine.GetMyGameDir(), filepaths::BIN_DIR, pdli->szDll );
if( iResult < 0 || static_cast<size_t>( iResult ) >= sizeof( szPath ) )
return nullptr;
HMODULE hLib = LoadLibraryA( szPath );
return ( FARPROC ) hLib;
}
}
return nullptr;
}
ExternC PfnDliHook __pfnDliNotifyHook2 = DelayHook;
ExternC PfnDliHook __pfnDliFailureHook2 = nullptr;
#endif
| 22.136364 | 130 | 0.693018 | Arkshine |
ece58171e099594ed65ee2ba0214810bedaf06b5 | 4,068 | cpp | C++ | PythonAPI/src/ctypeswrappers/jetfuelmediactypes.cpp | InsightGit/JetfuelGameEngine | 3ea0bf2fb5e09aadf304b7b5a16882d72336c408 | [
"Apache-2.0"
] | 4 | 2018-02-05T03:40:10.000Z | 2021-06-18T16:22:13.000Z | PythonAPI/src/ctypeswrappers/jetfuelmediactypes.cpp | InsightGit/JetfuelGameEngine | 3ea0bf2fb5e09aadf304b7b5a16882d72336c408 | [
"Apache-2.0"
] | null | null | null | PythonAPI/src/ctypeswrappers/jetfuelmediactypes.cpp | InsightGit/JetfuelGameEngine | 3ea0bf2fb5e09aadf304b7b5a16882d72336c408 | [
"Apache-2.0"
] | null | null | null | /*
* Jetfuel Game Engine- A SDL-based 2D game-engine
* Copyright (C) 2018 InfernoStudios
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <jetfuelmedia.h>
#define MAX_FILE_NAME_SIZE 4096
#if defined(_MSC_VER) // If on Visual Studio, export function
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
extern "C"{
// Wrapper for jetfuel::media::Music
EXPORT jetfuel::media::Music *Music_new(){
return new jetfuel::media::Music();
}
EXPORT void Music_delete(jetfuel::media::Music *music){
delete music;
}
EXPORT bool Music_is_music_playing(){
return Mix_PlayingMusic();
}
EXPORT bool Music_is_music_paused(){
return Mix_PausedMusic();
}
EXPORT bool Music_load_audio_file(jetfuel::media::Music *music,
const wchar_t *musicfilepath){
char musicfilepathchar[MAX_FILE_NAME_SIZE];
wcstombs(musicfilepathchar,musicfilepath,
MAX_FILE_NAME_SIZE);
if(!music->Load_audio_file(musicfilepathchar)){
return false;
}
return true;
}
EXPORT bool Music_play(jetfuel::media::Music *music){
return music->Play();
}
EXPORT void Music_pause(jetfuel::media::Music *music){
music->Pause();
}
EXPORT void Music_resume(jetfuel::media::Music *music){
music->Resume();
}
EXPORT wchar_t *Get_sdl_error(){
const char *sdlerror = Mix_GetError();
wchar_t returnvalue[4096];
mbstowcs(returnvalue, sdlerror, 4096);
return returnvalue;
}
// Wrapper for jetfuel::media::Sound_effect
EXPORT jetfuel::media::Sound_effect *Sound_effect_new(){
return new jetfuel::media::Sound_effect();
}
EXPORT void Sound_effect_delete(jetfuel::media::Sound_effect *sfx){
delete sfx;
}
EXPORT bool Sound_effect_is_sound_effect_or_music_playing(){
return jetfuel::media::Sound_effect::Is_sound_effect_or_music_playing();
}
EXPORT wchar_t *Sound_effect_get_loaded_sound_effect_file(jetfuel::media::
Sound_effect *sfx){
const char *soundeffectfile = sfx->Get_loaded_audio_file_path().c_str();
wchar_t returnvalue[MAX_FILE_NAME_SIZE];
mbstowcs(returnvalue, soundeffectfile, MAX_FILE_NAME_SIZE);
return returnvalue;
}
EXPORT bool Sound_effect_load_audio_file(jetfuel::media::Sound_effect *sfx,
const wchar_t *musicfilepath){
char musicfilepathchar[MAX_FILE_NAME_SIZE];
wcstombs(musicfilepathchar,musicfilepath,
MAX_FILE_NAME_SIZE);
if(!sfx->Load_audio_file(musicfilepathchar)){
return false;
}
return true;
}
EXPORT unsigned int Sound_effect_get_times_to_repeat(jetfuel::media::
Sound_effect *sfx){
return sfx->Get_times_to_repeat();
}
EXPORT void Sound_effect_set_times_to_repeat(jetfuel::media::Sound_effect
*sfx,unsigned int timestorepeat){
return sfx->Set_times_to_repeat(timestorepeat);
}
EXPORT bool Sound_effect_play(jetfuel::media::Sound_effect *sfx){
return sfx->Play();
}
EXPORT void Sound_effect_pause(jetfuel::media::Sound_effect *sfx){
sfx->Pause();
}
EXPORT void Sound_effect_resume(jetfuel::media::Sound_effect *sfx){
sfx->Resume();
}
}
| 28.447552 | 81 | 0.644051 | InsightGit |
ece5c5993b62ac96455e64e2039b2e4f929ea31d | 6,340 | hpp | C++ | esp/logging/logginglib/logconfigptree.hpp | asselitx/HPCC-Platform | b13c1a368d132f0282323667313afd647ede63c9 | [
"Apache-2.0"
] | null | null | null | esp/logging/logginglib/logconfigptree.hpp | asselitx/HPCC-Platform | b13c1a368d132f0282323667313afd647ede63c9 | [
"Apache-2.0"
] | null | null | null | esp/logging/logginglib/logconfigptree.hpp | asselitx/HPCC-Platform | b13c1a368d132f0282323667313afd647ede63c9 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2021 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#ifndef _LOGCONFIGPTREE_HPP_
#define _LOGCONFIGPTREE_HPP_
#include "jptree.hpp"
#include "jstring.hpp"
#include "tokenserialization.hpp"
namespace LogConfigPTree
{
/**
* When relying upon a default value, check and report if the default value is not compatibile
* with the requested value type. Most mismatches are errors. Some may be recorded as warnings
* if a reasonable use case, e.g., defaulting an unsigned value to -1, exists to justify it.
* In all cases, recorded findings should be addressed by either changing the default value or
* casting the intended value correctly.
*/
template <typename value_t, typename default_t>
value_t applyDefault(const default_t& defaultValue, const char* xpath)
{
auto report = [&](bool isError)
{
StringBuffer msg;
msg << "unexpected default value '" << defaultValue << "'";
if (!isEmptyString(xpath))
msg << " for configuration XPath '" << xpath << "'";
if (isError)
IERRLOG("%s", msg.str());
else
IWARNLOG("%s", msg.str());
};
if (std::is_integral<value_t>() == std::is_integral<default_t>())
{
if (std::is_signed<value_t>() == std::is_signed<default_t>())
{
if (defaultValue < std::numeric_limits<value_t>::min())
report(true);
else if (defaultValue > std::numeric_limits<value_t>::max())
report(true);
}
else if (std::is_signed<value_t>())
{
if (defaultValue > std::numeric_limits<value_t>::max())
report(true);
}
else
{
if (defaultValue < 0 || defaultValue > std::numeric_limits<value_t>::max())
report(false);
}
}
else if (std::is_floating_point<value_t>() == std::is_floating_point<default_t>())
{
if (defaultValue < -std::numeric_limits<value_t>::max())
report(true);
else if (defaultValue > std::numeric_limits<value_t>::max())
report(true);
}
else
{
report(false);
}
return value_t(defaultValue);
}
/**
* Access a configuration property value, supporting legacy configurations that use element
* content and newer configurations relying on attributes.
*
* Preferring new configurations instead of legacy, consider a request for an attribute to be
* just that and a request for element content to be a request for either an attribute or an
* element. A request for "A/@B" will be viewed as only a request for attribute B in element A,
* while a request for "A/B" will be viewed first as a request for "A/@B" and as a request for
* "A/B" only if "A/@B" is not found.
*/
inline const char* queryConfigValue(const IPTree& node, const char* xpath)
{
const char* value = nullptr;
if (!isEmptyString(xpath))
{
const char* delim = strrchr(xpath, '/');
size_t attrIndex = (delim ? delim - xpath + 1 : 0);
if (xpath[attrIndex] != '@')
{
StringBuffer altXPath(xpath);
altXPath.insert(attrIndex, '@');
value = node.queryProp(altXPath);
if (value)
return value;
}
value = node.queryProp(xpath);
}
return value;
}
inline const char* queryConfigValue(const IPTree* node, const char* xpath)
{
if (node)
return queryConfigValue(*node, xpath);
return nullptr;
}
inline bool getConfigValue(const IPTree& node, const char* xpath, StringBuffer& value)
{
const char* raw = queryConfigValue(node, value);
if (raw)
{
value.set(raw);
return true;
}
return false;
}
inline bool getConfigValue(const IPTree* node, const char* xpath, StringBuffer& value)
{
if (node)
return getConfigValue(*node, xpath, value);
return false;
}
template <typename value_t, typename default_t>
value_t getConfigValue(const IPTree& node, const char* xpath, const default_t& defaultValue)
{
const char* raw = queryConfigValue(node, xpath);
if (raw)
{
static TokenDeserializer deserializer;
value_t value;
if (deserializer(raw, value) == Deserialization_SUCCESS)
return value;
}
return applyDefault<value_t>(defaultValue, xpath);
}
template <typename value_t>
value_t getConfigValue(const IPTree& node, const char* xpath)
{
value_t defaultValue = value_t(0);
return getConfigValue<value_t>(node, xpath, defaultValue);
}
template <typename value_t, typename default_t>
value_t getConfigValue(const IPTree* node, const char* xpath, const default_t& defaultValue)
{
if (node)
return getConfigValue<value_t>(*node, xpath, defaultValue);
return applyDefault<value_t>(defaultValue, xpath);
}
template <typename value_t>
value_t getConfigValue(const IPTree* node, const char* xpath)
{
if (node)
return getConfigValue<value_t>(*node, xpath);
return value_t(0);
}
} // namespace LogConfigPTree
#endif // _LOGCONFIGPTREE_HPP_ | 35.617978 | 99 | 0.579653 | asselitx |
ece61a786b25557969da5a4009fa858ce8754175 | 5,197 | cpp | C++ | src/config/TOMLConfigBuilder.cpp | smangano/theoria | 216c3edb5973cee60d3381881071e0a32428fee5 | [
"Apache-2.0"
] | null | null | null | src/config/TOMLConfigBuilder.cpp | smangano/theoria | 216c3edb5973cee60d3381881071e0a32428fee5 | [
"Apache-2.0"
] | 1 | 2016-10-09T15:40:16.000Z | 2016-10-20T03:11:38.000Z | src/config/TOMLConfigBuilder.cpp | smangano/theoria | 216c3edb5973cee60d3381881071e0a32428fee5 | [
"Apache-2.0"
] | null | null | null | #include <theoria/config/TOMLConfigBuilder.h>
#include <theoria/config/Config.h>
#include <theoria/except/except.h>
#include <utility>
#include <cpptoml.h>
#include <iostream>
using namespace theoria ;
using namespace config ;
TOMLConfigBuilder::~TOMLConfigBuilder()
{
}
std::unique_ptr<const Config> TOMLConfigBuilder::parse(std::istream& stream)
{
try {
cpptoml::parser parser_(stream) ;
auto config = parser_.parse();
auto application = config->get_as<std::string>("application").value_or("") ;
auto appdesc = config->get_as<std::string>("desc").value_or("") ;
pushConfig(application, appdesc) ;
_recursive_build(*config) ;
}
catch(const cpptoml::parse_exception& parseEx) {
throw RUNTIME_ERROR("Could not parse TOML config: %s", parseEx.what()) ;
}
return std::unique_ptr<const Config>(releaseAll()) ;
}
std::unique_ptr<const Config> TOMLConfigBuilder::parse_file(const std::string& filename)
{
try {
auto config = cpptoml::parse_file(filename);
if (!config)
throw RUNTIME_ERROR("Could not parse TOML config: %s", filename.c_str()) ;
auto application = config->get_as<std::string>("application").value_or(filename) ;
auto appdesc = config->get_as<std::string>("desc").value_or("") ;
pushConfig(application, appdesc) ;
_recursive_build(*config) ;
}
catch(const cpptoml::parse_exception& parseEx) {
throw RUNTIME_ERROR("Could not parse TOML config: %s: %s", filename.c_str(), parseEx.what()) ;
}
return std::unique_ptr<const Config>(releaseAll()) ;
}
void TOMLConfigBuilder::_recursive_build(cpptoml::table& table)
{
for (auto iter = table.begin(), end = table.end(); iter != end; ++iter)
{
if (iter->second->is_value())
{
if (iter->first == "desc")
setDesc(*table.get_as<std::string>(iter->first)) ;
else {
//attributes
auto val_type = _getValueAndTypeAsString(table, iter->first) ;
auto value = val_type.first ;
auto type = val_type.second ;
_addAttr(iter->first, value, type) ;
}
}
if (iter->second->is_array())
{
throw RUNTIME_ERROR("TOML array support not implemented yet") ;
}
else
if (iter->second->is_table_array())
{
pushConfigArray(iter->first + "_Array") ;
auto tarr = table.get_table_array(iter->first);
for (const auto& tableElem : *tarr) {
pushConfig(iter->first, iter->first) ;
_recursive_build(*tableElem) ;
popAsChild(true) ;
}
popAsChild() ;
}
else
if (iter->second->is_table())
{
pushConfig(iter->first, iter->first) ;
_recursive_build(*(iter->second->as_table())) ;
popAsChild() ;
}
else
{
}
}
}
void TOMLConfigBuilder::_addAttr(const std::string& name, const std::string& value, const std::string& type)
{
addAttr(name, value, type) ;
}
void TOMLConfigBuilder::_addAttrWithResolve(
const std::string& name,
const std::string& value,
const std::string& type)
{
//TODO
}
std::pair<std::string, std::string> TOMLConfigBuilder::_getValueAndTypeAsString(const cpptoml::table& owner,const std::string& name)
{
std::ostringstream oss ;
auto strVal = owner.get_as<std::string>(name) ;
if (strVal) {
return std::make_pair(*strVal, std::string("string")) ;
}
auto intVal = owner.get_as<int64_t>(name) ;
if (intVal) {
oss << *intVal ;
return std::make_pair(oss.str(), std::string("int")) ;
}
auto doubleVal = owner.get_as<double>(name) ;
if (doubleVal) {
oss << *doubleVal ;
return std::make_pair(oss.str(), std::string("double")) ;
}
auto boolVal = owner.get_as<bool>(name) ;
if (boolVal) {
oss << *boolVal ;
return std::make_pair(oss.str(), std::string("bool")) ;
}
auto dateVal = owner.get_as<cpptoml::datetime>(name) ;
if (dateVal)
{
auto dt = *dateVal ;
oss << std::setfill('0') ;
oss << std::setw(4) << dt.year << "-" << std::setw(2) << dt.month << "-" << std::setw(2) << dt.day ;
if (dt.hour || dt.minute || dt.second || dt.microsecond)
{
oss << "T" << std::setw(2) << dt.hour << ":" << std::setw(2) << dt.minute << ":" << std::setw(2)
<< dt.second ;
if (dt.microsecond)
oss << std::setw(6) << dt.microsecond ;
if (dt.hour_offset || dt.minute_offset) {
if (dt.hour_offset < 0) {
oss << "-" ;
dt.hour_offset *= -1 ;
}
oss << std::setw(2) << dt.hour_offset << ":" << std::setw(2) << dt.minute_offset ;
}
return std::make_pair(oss.str(), "datetime") ;
}
else {
return std::make_pair(oss.str(),"date") ;
}
}
return std::make_pair("" , "") ;
}
| 32.48125 | 132 | 0.552242 | smangano |
ece7f17340f89d425515401fa2efc6389a433ef5 | 25,596 | cpp | C++ | 01_Develop/libXMFFmpeg/Source/libavformat/wav.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMFFmpeg/Source/libavformat/wav.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMFFmpeg/Source/libavformat/wav.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
* WAV muxer and demuxer
* Copyright (c) 2001, 2002 Fabrice Bellard
*
* Sony Wave64 demuxer
* RF64 demuxer
* Copyright (c) 2009 Daniel Verkamp
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "XMFFmpeg/libavutil/avassert.h"
#include "XMFFmpeg/libavutil/dict.h"
#include "XMFFmpeg/libavutil/log.h"
#include "XMFFmpeg/libavutil/mathematics.h"
#include "XMFFmpeg/libavutil/opt.h"
#include "internal.h"
#include "avio_internal.h"
#include "pcm.h"
#include "riff.h"
#include "metadata.h"
typedef struct {
const AVClass *av_class;
int64_t data;
int64_t data_end;
int64_t minpts;
int64_t maxpts;
int last_duration;
int w64;
int write_bext;
int64_t smv_data_ofs;
int smv_block_size;
int smv_frames_per_jpeg;
int smv_block;
int smv_last_stream;
int smv_eof;
int audio_eof;
int ignore_length;
} WAVContext;
#if CONFIG_WAV_MUXER
static av_always_inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
{
AVDictionaryEntry *tag;
int len = 0;
if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
len = strlen(tag->value);
len = FFMIN(len, maxlen);
avio_write(s->pb, (const unsigned char *)tag->value, len);
}
ffio_fill(s->pb, 0, maxlen - len);
}
static void bwf_write_bext_chunk(AVFormatContext *s)
{
AVDictionaryEntry *tmp_tag;
uint64_t time_reference = 0;
int64_t bext = ff_start_tag(s->pb, "bext");
bwf_write_bext_string(s, "description", 256);
bwf_write_bext_string(s, "originator", 32);
bwf_write_bext_string(s, "originator_reference", 32);
bwf_write_bext_string(s, "origination_date", 10);
bwf_write_bext_string(s, "origination_time", 8);
if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
time_reference = strtoll(tmp_tag->value, NULL, 10);
avio_wl64(s->pb, time_reference);
avio_wl16(s->pb, 1); // set version to 1
if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
unsigned char umidpart_str[17] = {0};
int i;
uint64_t umidpart;
int len = strlen(tmp_tag->value+2);
for (i = 0; i < len/16; i++) {
memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
umidpart = strtoll((char*)umidpart_str, NULL, 16);
avio_wb64(s->pb, umidpart);
}
ffio_fill(s->pb, 0, 64 - i*8);
} else
ffio_fill(s->pb, 0, 64); // zero UMID
ffio_fill(s->pb, 0, 190); // Reserved
if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
avio_put_str(s->pb, tmp_tag->value);
ff_end_tag(s->pb, bext);
}
static int wav_write_header(AVFormatContext *s)
{
WAVContext *wav = (WAVContext *)s->priv_data;
AVIOContext *pb = s->pb;
int64_t fmt, fact;
ffio_wfourcc(pb, (const uint8_t *)"RIFF");
avio_wl32(pb, 0); /* file length */
ffio_wfourcc(pb, (const uint8_t *)"WAVE");
/* format header */
fmt = ff_start_tag(pb, "fmt ");
if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {
av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
return -1;
}
ff_end_tag(pb, fmt);
if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
&& s->pb->seekable) {
fact = ff_start_tag(pb, "fact");
avio_wl32(pb, 0);
ff_end_tag(pb, fact);
}
if (wav->write_bext)
bwf_write_bext_chunk(s);
avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
wav->maxpts = wav->last_duration = 0;
wav->minpts = INT64_MAX;
/* data header */
wav->data = ff_start_tag(pb, "data");
avio_flush(pb);
return 0;
}
static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
{
AVIOContext *pb = s->pb;
WAVContext *wav = (WAVContext *)s->priv_data;
avio_write(pb, pkt->data, pkt->size);
if(pkt->pts != AV_NOPTS_VALUE) {
wav->minpts = FFMIN(wav->minpts, pkt->pts);
wav->maxpts = FFMAX(wav->maxpts, pkt->pts);
wav->last_duration = pkt->duration;
} else
av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
return 0;
}
static int wav_write_trailer(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
WAVContext *wav = (WAVContext *)s->priv_data;
int64_t file_size;
avio_flush(pb);
if (s->pb->seekable) {
ff_end_tag(pb, wav->data);
/* update file size */
file_size = avio_tell(pb);
avio_seek(pb, 4, SEEK_SET);
avio_wl32(pb, (uint32_t)(file_size - 8));
avio_seek(pb, file_size, SEEK_SET);
avio_flush(pb);
if(s->streams[0]->codec->codec_tag != 0x01) {
/* Update num_samps in fact chunk */
int number_of_samples;
number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
s->streams[0]->time_base.den);
avio_seek(pb, wav->data-12, SEEK_SET);
avio_wl32(pb, number_of_samples);
avio_seek(pb, file_size, SEEK_SET);
avio_flush(pb);
}
}
return 0;
}
#define OFFSET(x) offsetof(WAVContext, x)
#define ENC AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
{ "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, 0, NULL, 0, 1, ENC },
{ NULL },
};
static const AVClass wav_muxer_class = {
/*.class_name = */ "WAV muxer",
/*.item_name = */ av_default_item_name,
/*.option = */ options,
/*.version = */ LIBAVUTIL_VERSION_INT,
};
static const AVCodecTag* const _ff_wav_muxer[] = {ff_codec_wav_tags, 0};
AVOutputFormat ff_wav_muxer = {
/*.name = */ "wav",
/*.long_name = */ NULL_IF_CONFIG_SMALL("WAV format"),
/*.mime_type = */ "audio/x-wav",
/*.extensions = */ "wav",
/*.priv_data_size = */ sizeof(WAVContext),
/*.audio_codec = */ CODEC_ID_PCM_S16LE,
/*.video_codec = */ CODEC_ID_NONE,
/*.write_header = */ wav_write_header,
/*.write_packet = */ wav_write_packet,
/*.write_trailer = */ wav_write_trailer,
/*.flags = */ 0,
/*.dummy = */ 0,
/*.interleave_packet = */ 0,
/*.codec_tag = */ _ff_wav_muxer,
/*.subtitle_codec = */ CODEC_ID_NONE,
#if FF_API_OLD_METADATA2
/*.metadata_conv = */ 0,
#endif
/*.priv_class = */ &wav_muxer_class,
};
#endif /* CONFIG_WAV_MUXER */
#if CONFIG_WAV_DEMUXER
static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
{
*tag = avio_rl32(pb);
return avio_rl32(pb);
}
/* return the size of the found tag */
static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
{
uint32_t tag;
int64_t size;
for (;;) {
if (url_feof(pb))
return -1;
size = next_tag(pb, &tag);
if (tag == tag1)
break;
avio_skip(pb, size);
}
return size;
}
static int wav_probe(AVProbeData *p)
{
/* check file header */
if (p->buf_size <= 32)
return 0;
if (!memcmp(p->buf + 8, "WAVE", 4)) {
if (!memcmp(p->buf, "RIFF", 4))
/*
Since ACT demuxer has standard WAV header at top of it's own,
returning score is decreased to avoid probe conflict
between ACT and WAV.
*/
return AVPROBE_SCORE_MAX - 1;
else if (!memcmp(p->buf, "RF64", 4) &&
!memcmp(p->buf + 12, "ds64", 4))
return AVPROBE_SCORE_MAX;
}
return 0;
}
static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
{
AVIOContext *pb = s->pb;
int ret;
/* parse fmt header */
*st = avformat_new_stream(s, NULL);
if (!*st)
return AVERROR(ENOMEM);
ret = ff_get_wav_header(pb, (*st)->codec, size);
if (ret < 0)
return ret;
(*st)->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
return 0;
}
static av_always_inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
int length)
{
char temp[257];
int ret;
av_assert0(length <= sizeof(temp));
if ((ret = avio_read(s->pb, (unsigned char *)temp, length)) < 0)
return ret;
temp[length] = 0;
if (strlen(temp))
return av_dict_set(&s->metadata, key, temp, 0);
return 0;
}
static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
{
char temp[131], *coding_history;
int ret, x;
uint64_t time_reference;
int64_t umid_parts[8], umid_mask = 0;
if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
(ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
(ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
(ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
(ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
return ret;
time_reference = avio_rl64(s->pb);
snprintf(temp, sizeof(temp), "%" PRIu64, time_reference);
if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
return ret;
/* check if version is >= 1, in which case an UMID may be present */
if (avio_rl16(s->pb) >= 1) {
for (x = 0; x < 8; x++)
umid_mask |= umid_parts[x] = avio_rb64(s->pb);
if (umid_mask) {
/* the string formatting below is per SMPTE 330M-2004 Annex C */
if (umid_parts[4] == 0 && umid_parts[5] == 0 && umid_parts[6] == 0 && umid_parts[7] == 0) {
/* basic UMID */
snprintf(temp, sizeof(temp), "0x%016" PRIX64"%016" PRIX64"%016" PRIX64"%016" PRIX64,
umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3]);
} else {
/* extended UMID */
snprintf(temp, sizeof(temp), "0x%016" PRIX64"%016" PRIX64"%016" PRIX64"%016" PRIX64
"%016" PRIX64"%016" PRIX64"%016" PRIX64"%016" PRIX64,
umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3],
umid_parts[4], umid_parts[5], umid_parts[6], umid_parts[7]);
}
if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
return ret;
}
avio_skip(s->pb, 190);
} else
avio_skip(s->pb, 254);
if (size > 602) {
/* CodingHistory present */
size -= 602;
if (!(coding_history = (char *)av_malloc(size+1)))
return AVERROR(ENOMEM);
if ((ret = avio_read(s->pb, (unsigned char *)coding_history, size)) < 0)
return ret;
coding_history[size] = 0;
if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
AV_DICT_DONT_STRDUP_VAL)) < 0)
return ret;
}
return 0;
}
static const AVMetadataConv wav_metadata_conv[] = {
{"description", "comment" },
{"originator", "encoded_by" },
{"origination_date", "date" },
{"origination_time", "creation_time"},
{0},
};
/* wav input */
static int wav_read_header(AVFormatContext *s,
AVFormatParameters *ap)
{
int64_t size, av_uninit(data_size);
int64_t sample_count=0;
int rf64;
uint32_t tag, list_type;
AVIOContext *pb = s->pb;
AVStream *st = NULL;
WAVContext *wav = (WAVContext *)s->priv_data;
int ret, got_fmt = 0;
int64_t next_tag_ofs, data_ofs = -1;
wav->smv_data_ofs = -1;
/* check RIFF header */
tag = avio_rl32(pb);
rf64 = tag == MKTAG('R', 'F', '6', '4');
if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
return -1;
avio_rl32(pb); /* file size */
tag = avio_rl32(pb);
if (tag != MKTAG('W', 'A', 'V', 'E'))
return -1;
if (rf64) {
if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
return -1;
size = avio_rl32(pb);
if (size < 24)
return -1;
avio_rl64(pb); /* RIFF size */
data_size = avio_rl64(pb);
sample_count = avio_rl64(pb);
if (data_size < 0 || sample_count < 0) {
av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
"ds64: data_size = %" PRId64 ", sample_count = %" PRId64 "\n",
data_size, sample_count);
return AVERROR_INVALIDDATA;
}
avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
}
for (;;) {
AVStream *vst;
size = next_tag(pb, &tag);
next_tag_ofs = avio_tell(pb) + size;
if (url_feof(pb))
break;
switch (tag) {
case MKTAG('f', 'm', 't', ' '):
/* only parse the first 'fmt ' tag found */
if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
return ret;
} else if (got_fmt)
av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
got_fmt = 1;
break;
case MKTAG('d', 'a', 't', 'a'):
if (!got_fmt) {
av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
return AVERROR_INVALIDDATA;
}
if (rf64) {
next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
} else {
data_size = size;
next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
}
data_ofs = avio_tell(pb);
/* don't look for footer metadata if we can't seek or if we don't
* know where the data tag ends
*/
if (!pb->seekable || (!rf64 && !size))
goto break_loop;
break;
case MKTAG('f','a','c','t'):
if (!sample_count)
sample_count = avio_rl32(pb);
break;
case MKTAG('b','e','x','t'):
if ((ret = wav_parse_bext_tag(s, size)) < 0)
return ret;
break;
case MKTAG('S','M','V','0'):
// SMV file, a wav file with video appended.
if (size != MKTAG('0','2','0','0')) {
av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
goto break_loop;
}
av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
vst = avformat_new_stream(s, NULL);
if (!vst)
return AVERROR(ENOMEM);
avio_r8(pb);
vst->id = 1;
vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
vst->codec->codec_id = CODEC_ID_MJPEG;
vst->codec->width = avio_rl24(pb);
vst->codec->height = avio_rl24(pb);
size = avio_rl24(pb);
wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
avio_rl24(pb);
wav->smv_block_size = avio_rl24(pb);
avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
vst->duration = avio_rl24(pb);
avio_rl24(pb);
avio_rl24(pb);
wav->smv_frames_per_jpeg = avio_rl24(pb);
goto break_loop;
case MKTAG('L', 'I', 'S', 'T'):
list_type = avio_rl32(pb);
if (size < 4) {
av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
return AVERROR_INVALIDDATA;
}
switch (list_type) {
case MKTAG('I', 'N', 'F', 'O'):
if ((ret = ff_read_riff_info(s, size - 4)) < 0)
return ret;
}
break;
}
/* seek to next tag unless we know that we'll run into EOF */
if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {
break;
}
}
break_loop:
if (data_ofs < 0) {
av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
return AVERROR_INVALIDDATA;
}
avio_seek(pb, data_ofs, SEEK_SET);
if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
if (sample_count)
st->duration = sample_count;
ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
return 0;
}
/** Find chunk with w64 GUID by skipping over other chunks
* @return the size of the found chunk
*/
static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
{
uint8_t guid[16];
int64_t size;
while (!url_feof(pb)) {
avio_read(pb, guid, 16);
size = avio_rl64(pb);
if (size <= 24)
return -1;
if (!memcmp(guid, guid1, 16))
return size;
avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
}
return -1;
}
static const uint8_t guid_data[16] = { 'd', 'a', 't', 'a',
0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
#define MAX_SIZE 4096
static int wav_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
int ret, size;
int64_t left;
AVStream *st;
WAVContext *wav = (WAVContext *)s->priv_data;
if (wav->smv_data_ofs > 0) {
int64_t audio_dts, video_dts;
smv_retry:
audio_dts = s->streams[0]->cur_dts;
video_dts = s->streams[1]->cur_dts;
if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
wav->smv_last_stream = video_dts >= audio_dts;
}
wav->smv_last_stream = !wav->smv_last_stream;
wav->smv_last_stream |= wav->audio_eof;
wav->smv_last_stream &= !wav->smv_eof;
if (wav->smv_last_stream) {
uint64_t old_pos = avio_tell(s->pb);
uint64_t new_pos = wav->smv_data_ofs +
wav->smv_block * wav->smv_block_size;
if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
ret = AVERROR_EOF;
goto smv_out;
}
size = avio_rl24(s->pb);
ret = av_get_packet(s->pb, pkt, size);
if (ret < 0)
goto smv_out;
pkt->pos -= 3;
pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
wav->smv_block++;
pkt->stream_index = 1;
smv_out:
avio_seek(s->pb, old_pos, SEEK_SET);
if (ret == AVERROR_EOF) {
wav->smv_eof = 1;
goto smv_retry;
}
return ret;
}
}
st = s->streams[0];
left = wav->data_end - avio_tell(s->pb);
if (wav->ignore_length)
left= INT_MAX;
if (left <= 0){
if (CONFIG_W64_DEMUXER && wav->w64)
left = find_guid(s->pb, guid_data) - 24;
else
left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
if (left < 0) {
wav->audio_eof = 1;
if (wav->smv_data_ofs > 0 && !wav->smv_eof)
goto smv_retry;
return AVERROR_EOF;
}
wav->data_end= avio_tell(s->pb) + left;
}
size = MAX_SIZE;
if (st->codec->block_align > 1) {
if (size < st->codec->block_align)
size = st->codec->block_align;
size = (size / st->codec->block_align) * st->codec->block_align;
}
size = FFMIN(size, left);
ret = av_get_packet(s->pb, pkt, size);
if (ret < 0)
return ret;
pkt->stream_index = 0;
return ret;
}
static int wav_read_seek(AVFormatContext *s,
int stream_index, int64_t timestamp, int flags)
{
WAVContext *wav = (WAVContext *)s->priv_data;
AVStream *st;
wav->smv_eof = 0;
wav->audio_eof = 0;
if (wav->smv_data_ofs > 0) {
int64_t smv_timestamp = timestamp;
if (stream_index == 0)
smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
else
timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
}
st = s->streams[0];
switch (st->codec->codec_id) {
case CODEC_ID_MP2:
case CODEC_ID_MP3:
case CODEC_ID_AC3:
case CODEC_ID_DTS:
/* use generic seeking with dynamically generated indexes */
return -1;
default:
break;
}
return pcm_read_seek(s, stream_index, timestamp, flags);
}
#define OFFSET(x) offsetof(WAVContext, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM
static const AVOption demux_options[] = {
{ "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, 0, NULL, 0, 1, DEC },
{ NULL },
};
static const AVClass wav_demuxer_class = {
/*.class_name = */ "WAV demuxer",
/*.item_name = */ av_default_item_name,
/*.option = */ demux_options,
/*.version = */ LIBAVUTIL_VERSION_INT,
};
static const AVCodecTag* const _ff_wav_demuxer[] = {ff_codec_wav_tags, 0};
AVInputFormat ff_wav_demuxer = {
/*.name = */ "wav",
/*.long_name = */ NULL_IF_CONFIG_SMALL("WAV format"),
/*.priv_data_size = */ sizeof(WAVContext),
/*.read_probe = */ wav_probe,
/*.read_header = */ wav_read_header,
/*.read_packet = */ wav_read_packet,
/*.read_close = */ 0,
/*.read_seek = */ wav_read_seek,
/*.read_timestamp = */ 0,
/*.flags = */ AVFMT_GENERIC_INDEX,
/*.extensions = */ 0,
/*.value = */ 0,
/*.read_play = */ 0,
/*.read_pause = */ 0,
/*.codec_tag = */ _ff_wav_demuxer,
/*.read_seek2 = */ 0,
/*.metadata_conv = */ 0,
/*.priv_class = */ &wav_demuxer_class,
};
#endif /* CONFIG_WAV_DEMUXER */
#if CONFIG_W64_DEMUXER
static const uint8_t guid_riff[16] = { 'r', 'i', 'f', 'f',
0x2E, 0x91, 0xCF, 0x11, 0xA5, 0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00 };
static const uint8_t guid_wave[16] = { 'w', 'a', 'v', 'e',
0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
static const uint8_t guid_fmt [16] = { 'f', 'm', 't', ' ',
0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
static int w64_probe(AVProbeData *p)
{
if (p->buf_size <= 40)
return 0;
if (!memcmp(p->buf, guid_riff, 16) &&
!memcmp(p->buf + 24, guid_wave, 16))
return AVPROBE_SCORE_MAX;
else
return 0;
}
static int w64_read_header(AVFormatContext *s, AVFormatParameters *ap)
{
int64_t size;
AVIOContext *pb = s->pb;
WAVContext *wav = (WAVContext *)s->priv_data;
AVStream *st;
uint8_t guid[16];
int ret;
avio_read(pb, guid, 16);
if (memcmp(guid, guid_riff, 16))
return -1;
if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
return -1;
avio_read(pb, guid, 16);
if (memcmp(guid, guid_wave, 16)) {
av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
return -1;
}
size = find_guid(pb, guid_fmt);
if (size < 0) {
av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
return -1;
}
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
/* subtract chunk header size - normal wav file doesn't count it */
ret = ff_get_wav_header(pb, st->codec, size - 24);
if (ret < 0)
return ret;
avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
st->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
size = find_guid(pb, guid_data);
if (size < 0) {
av_log(s, AV_LOG_ERROR, "could not find data guid\n");
return -1;
}
wav->data_end = avio_tell(pb) + size - 24;
wav->w64 = 1;
return 0;
}
static const AVCodecTag* const _ff_w64_demuxer[] = {ff_codec_wav_tags, 0};
AVInputFormat ff_w64_demuxer = {
/*.name = */ "w64",
/*.long_name = */ NULL_IF_CONFIG_SMALL("Sony Wave64 format"),
/*.priv_data_size = */ sizeof(WAVContext),
/*.read_probe = */ w64_probe,
/*.read_header = */ w64_read_header,
/*.read_packet = */ wav_read_packet,
/*.read_close = */ 0,
/*.read_seek = */ wav_read_seek,
/*.read_timestamp = */ 0,
/*.flags = */ AVFMT_GENERIC_INDEX,
/*.extensions = */ 0,
/*.value = */ 0,
/*.read_play = */ 0,
/*.read_pause = */ 0,
/*.codec_tag = */ _ff_w64_demuxer,
};
#endif /* CONFIG_W64_DEMUXER */
| 31.176614 | 118 | 0.56294 | mcodegeeks |
ecef06aa5811d7e2a8dc5e6fe6a6e2de24bc04c8 | 3,872 | cpp | C++ | libs/network/src/muddle/muddle_register.cpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/network/src/muddle/muddle_register.cpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/network/src/muddle/muddle_register.cpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "network/muddle/muddle_register.hpp"
#include "network/management/abstract_connection.hpp"
#include "network/muddle/dispatcher.hpp"
namespace fetch {
namespace muddle {
/**
* Construct the connection register
*
* @param dispatcher The reference to the dispatcher
*/
MuddleRegister::MuddleRegister(Dispatcher &dispatcher)
: dispatcher_(dispatcher)
{}
/**
* Execute a specified callback over all elements of the connection map
*
* @param cb The specified callback to execute
*/
void MuddleRegister::VisitConnectionMap(MuddleRegister::ConnectionMapCallback const &cb)
{
LOG_STACK_TRACE_POINT;
FETCH_LOCK(connection_map_lock_);
cb(connection_map_);
}
/**
* Broadcast data to all active connections
*
* @param data The data to be broadcast
*/
void MuddleRegister::Broadcast(ConstByteArray const &data) const
{
LOG_STACK_TRACE_POINT;
FETCH_LOCK(connection_map_lock_);
FETCH_LOG_DEBUG(LOGGING_NAME, "Broadcasting message.");
// loop through all of our current connections
for (auto const &elem : connection_map_)
{
// ensure the connection is valid
auto connection = elem.second.lock();
if (connection)
{
// schedule sending of the data
connection->Send(data);
}
}
}
/**
* Lookup a connection given a specified handle
*
* @param handle The handle of the requested connection
* @return A valid connection if successful, otherwise an invalid one
*/
MuddleRegister::ConnectionPtr MuddleRegister::LookupConnection(ConnectionHandle handle) const
{
LOG_STACK_TRACE_POINT;
ConnectionPtr conn;
{
FETCH_LOCK(connection_map_lock_);
auto it = connection_map_.find(handle);
if (it != connection_map_.end())
{
conn = it->second;
}
}
return conn;
}
/**
* Callback triggered when a new connection is established
*
* @param ptr The new connection pointer
*/
void MuddleRegister::Enter(ConnectionPtr const &ptr)
{
LOG_STACK_TRACE_POINT;
FETCH_LOCK(connection_map_lock_);
auto strong_conn = ptr.lock();
#ifndef NDEBUG
// extra level of debug
if (connection_map_.find(strong_conn->handle()) != connection_map_.end())
{
FETCH_LOG_INFO(LOGGING_NAME, "Trying to update an existing connection ID");
return;
}
#endif // !NDEBUG
FETCH_LOG_DEBUG(LOGGING_NAME, "### Connection ", strong_conn->handle(),
" started type: ", strong_conn->Type());
// update
connection_map_[strong_conn->handle()] = ptr;
}
/**
* Callback triggered when a connection is destroyed
*
* @param id The handle of the dying connection
*/
void MuddleRegister::Leave(connection_handle_type id)
{
LOG_STACK_TRACE_POINT;
{
FETCH_LOCK(connection_map_lock_);
FETCH_LOG_DEBUG(LOGGING_NAME, "### Connection ", id, " ended");
auto it = connection_map_.find(id);
if (it != connection_map_.end())
{
connection_map_.erase(it);
}
}
// inform the dispatcher that the connection has failed (this can clear up all of the pending
// promises)
dispatcher_.NotifyConnectionFailure(id);
}
} // namespace muddle
} // namespace fetch
| 25.642384 | 95 | 0.684401 | devjsc |
ecf282b05d74a86c9e9ab28fa8f37754ea41f60a | 745 | cpp | C++ | Test/Expect/test046.cpp | archivest/spin2cpp | 8541238366076777717e683efac35458e3796859 | [
"MIT"
] | 2 | 2021-05-27T18:22:01.000Z | 2021-05-29T13:40:38.000Z | Test/Expect/test046.cpp | archivest/spin2cpp | 8541238366076777717e683efac35458e3796859 | [
"MIT"
] | 1 | 2020-10-24T22:25:37.000Z | 2020-10-24T22:25:37.000Z | Test/Expect/test046.cpp | archivest/spin2cpp | 8541238366076777717e683efac35458e3796859 | [
"MIT"
] | null | null | null | #include <propeller.h>
#include "test046.h"
void test046::Fun(int32_t X, int32_t Y)
{
int32_t _tmp__0000, _tmp__0001;
_tmp__0001 = X;
if (_tmp__0001 == 0) {
goto _case__0005;
}
if ((_tmp__0001 >= 10) && (_tmp__0001 <= 12)) {
goto _case__0006;
}
goto _case__0007;
_case__0005: ;
_tmp__0000 = Y;
if (_tmp__0000 == 0) {
goto _case__0002;
}
if (_tmp__0000 == 1) {
goto _case__0003;
}
goto _endswitch_0001;
_case__0002: ;
_OUTA ^= 0x1;
goto _endswitch_0001;
_case__0003: ;
_OUTA ^= 0x2;
goto _endswitch_0001;
_endswitch_0001: ;
goto _endswitch_0004;
_case__0006: ;
_OUTA ^= 0x4;
goto _endswitch_0004;
_case__0007: ;
_OUTA ^= 0x8;
goto _endswitch_0004;
_endswitch_0004: ;
}
| 18.170732 | 49 | 0.64698 | archivest |
ecf63bfdab2b037a2d5f8534c38e4858a146a757 | 7,584 | cpp | C++ | shared/lib_pv_incidence_modifier.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 61 | 2017-08-09T15:10:59.000Z | 2022-02-15T21:45:31.000Z | shared/lib_pv_incidence_modifier.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 462 | 2017-07-31T21:26:46.000Z | 2022-03-30T22:53:50.000Z | shared/lib_pv_incidence_modifier.cpp | JordanMalan/ssc | cadb7a9f3183d63c600b5c33f53abced35b6b319 | [
"BSD-3-Clause"
] | 73 | 2017-08-24T17:39:31.000Z | 2022-03-28T08:37:47.000Z | /**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <math.h>
#include "lib_pv_incidence_modifier.h"
///Supporting function for IAM functions to calculate transmissance of a module cover at a specific angle- reference: duffie & beckman, Ch 5.3
double transmittance(double theta1_deg, /* incidence angle of incoming radiation (deg) */
double n_cover, /* refractive index of cover material, n_glass = 1.586 */
double n_incoming, /* refractive index of incoming material, typically n_air = 1.0 */
double k, /* proportionality constant assumed to be 4 (1/m) for derivation of Bouguer's law (set to zero to skip bougeur's law */
double l_thick, /* thickness of cover material (m), usually 2 mm for typical module (set to zero to skip Bouguer's law) */
double *_theta2_deg) /* returns angle of refraction in degrees */
{
// calculate angle of refraction
double theta1 = theta1_deg * M_PI / 180.0;
double theta2 = asin(n_incoming / n_cover * sin(theta1)); // angle of refraction, calculated using snell's law
if (_theta2_deg) *_theta2_deg = theta2 * 180 / M_PI; // return angle of refraction in degrees if requested in function call
// fresnel's equation for non-reflected unpolarized radiation as an average of perpendicular and parallel components
// reference https://pvpmc.sandia.gov/modeling-steps/1-weather-design-inputs/shading-soiling-and-reflection-losses/incident-angle-reflection-losses/physical-model-of-iam/
double tr = 1 - 0.5 *
(pow(sin(theta2 - theta1), 2) / pow(sin(theta2 + theta1), 2)
+ pow(tan(theta2 - theta1), 2) / pow(tan(theta2 + theta1), 2));
return tr * exp(-k * l_thick / cos(theta2));
}
///Incidence angle modifier not normalized relative to normal incidence (used as a supporting function to normalized IAM function)
double iam_nonorm(double theta, bool ar_glass)
{
if (theta < AOI_MIN) theta = AOI_MIN;
if (theta > AOI_MAX) theta = AOI_MAX;
if (ar_glass)
{
double theta2 = 1;
double tau_coating = transmittance(theta, n_arc, n_air, k_arc, l_arc, &theta2);
double tau_glass = transmittance(theta2, n_glass, n_arc, k_glass, l_glass);
return tau_coating * tau_glass;
}
else
{
return transmittance(theta, n_glass, n_air, k_glass, l_glass);
}
}
///Incidence angle modifier normalized relative to normal incidence- used by 61853 model and PVWatts
double iam(double theta, bool ar_glass) //jmf- we should rename this to something more descriptive
{
if (theta < AOI_MIN) theta = AOI_MIN;
if (theta > AOI_MAX) theta = AOI_MAX;
double normal = iam_nonorm(1, ar_glass);
double actual = iam_nonorm(theta, ar_glass);
return actual / normal;
}
///Only used in a test to compare against bifacial model
double iamSjerpsKoomen(double n2, double incidenceAngleRadians)
{
// Only calculates valid value for 0 <= inc <= 90 degrees
double cor = -9999.0;
// Reflectance at normal incidence, Beckman p217
double r0 = pow((n2 - 1.0) / (n2 + 1), 2);
if (incidenceAngleRadians == 0) {
cor = 1.0;
}
else if (incidenceAngleRadians > 0.0 && incidenceAngleRadians <= M_PI / 2.0) {
double refrAng = asin(sin(incidenceAngleRadians) / n2);
double r1 = (pow(sin(refrAng - incidenceAngleRadians), 2.0) / pow(sin(refrAng + incidenceAngleRadians), 2.0));
double r2 = (pow(tan(refrAng - incidenceAngleRadians), 2.0) / pow(tan(refrAng + incidenceAngleRadians), 2.0));
cor = 1.0 - 0.5 * (r1 + r2);
cor /= 1.0 - r0;
}
return cor;
}
///DeSoto IAM model used by CEC model
double calculateIrradianceThroughCoverDeSoto(
double theta, /* incidence angle in degrees */
double tilt, /* tilt angle in degrees */
double G_beam, /* poa beam */
double G_sky, /* poa sky diffuse */
double G_gnd, /* poa ground reflected diffuse */
bool antiReflectiveGlass)
{
// establish limits on incidence angle and zenith angle
if (theta < 1) theta = 1.0;
if (theta > 89) theta = 89.0;
// transmittance at angle normal to surface (0 deg), use 1 (deg) to avoid numerical probs.
// need to check for anti-reflective coating on glass here in order to avoid IAM > 1 below
double tau_norm = 1.0; //start with a factor of 1 to be modified
double theta_norm_after_coating = 1.0; //initialize this to an angle of 1.0 degrees for the calculation of tau_norm without AR coating
if (antiReflectiveGlass)
{
double tau_coating = transmittance(1.0, n_arc, 1.0, k_arc, l_arc, &theta_norm_after_coating);
tau_norm *= tau_coating;
}
tau_norm *= transmittance(theta_norm_after_coating, n_glass, 1.0, k_glass, l_glass);
// transmittance of beam radiation, at incidence angle
double tau_beam = 1.0; //start with a factor of 1 to be modified
double theta_after_coating = theta;
if (antiReflectiveGlass)
{
double tau_coating = transmittance(theta, n_arc, 1.0, k_arc, l_arc, &theta_after_coating);
tau_beam *= tau_coating;
}
tau_beam *= transmittance(theta_after_coating, n_glass, (antiReflectiveGlass ? n_arc : 1.0), k_glass, l_glass);
// transmittance of sky diffuse, at modified angle by (D&B Eqn 5.4.2)
double theta_sky = 59.7 - 0.1388*tilt + 0.001497*tilt*tilt;
double tau_sky = transmittance(theta_sky, n_glass, 1.0, k_glass, l_glass);
// transmittance of ground diffuse, at modified angle by (D&B Eqn 5.4.1)
double theta_gnd = 90.0 - 0.5788*tilt + 0.002693*tilt*tilt;
double tau_gnd = transmittance(theta_gnd, n_glass, 1.0, k_glass, l_glass);
// calculate component incidence angle modifiers, D&B Chap. 5 eqn 5.12.1, DeSoto'04
// check that the component incidence angle modifiers are not > 1 in case there's some funkiness with the calculations
double Kta_beam = tau_beam / tau_norm;
if (Kta_beam > 1.0) Kta_beam = 1.0;
double Kta_sky = tau_sky / tau_norm;
if (Kta_sky > 1.0) Kta_sky = 1.0;
double Kta_gnd = tau_gnd / tau_norm;
if (Kta_gnd > 1.0) Kta_gnd = 1.0;
// total effective irradiance absorbed by solar cell
double Geff_total = G_beam * Kta_beam + G_sky * Kta_sky + G_gnd * Kta_gnd;
if (Geff_total < 0) Geff_total = 0;
return Geff_total;
}
| 47.698113 | 174 | 0.734045 | JordanMalan |
ecf8754e50232012c40a4cf5311e853562ff70f0 | 2,251 | cpp | C++ | src/ripple_websocket/autosocket/LogWebsockets.cpp | latcoin/rippled | ca0740de23ec4366d53b0d3770d9a05fc83072db | [
"BSL-1.0"
] | null | null | null | src/ripple_websocket/autosocket/LogWebsockets.cpp | latcoin/rippled | ca0740de23ec4366d53b0d3770d9a05fc83072db | [
"BSL-1.0"
] | null | null | null | src/ripple_websocket/autosocket/LogWebsockets.cpp | latcoin/rippled | ca0740de23ec4366d53b0d3770d9a05fc83072db | [
"BSL-1.0"
] | null | null | null | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
// VFALCO NOTE this looks like some facility for giving websocket
// a way to produce logging output.
//
namespace websocketpp
{
namespace log
{
using namespace ripple;
LogPartition websocketPartition ("WebSocket");
void websocketLog (websocketpp::log::alevel::value v, const std::string& entry)
{
using namespace ripple;
if ((v == websocketpp::log::alevel::DEVEL) || (v == websocketpp::log::alevel::DEBUG_CLOSE))
{
if (websocketPartition.doLog (lsTRACE))
Log (lsDEBUG, websocketPartition) << entry;
}
else if (websocketPartition.doLog (lsDEBUG))
Log (lsDEBUG, websocketPartition) << entry;
}
void websocketLog (websocketpp::log::elevel::value v, const std::string& entry)
{
using namespace ripple;
LogSeverity s = lsDEBUG;
if ((v & websocketpp::log::elevel::INFO) != 0)
s = lsINFO;
else if ((v & websocketpp::log::elevel::FATAL) != 0)
s = lsFATAL;
else if ((v & websocketpp::log::elevel::RERROR) != 0)
s = lsERROR;
else if ((v & websocketpp::log::elevel::WARN) != 0)
s = lsWARNING;
if (websocketPartition.doLog (s))
Log (s, websocketPartition) << entry;
}
}
}
// vim:ts=4
| 33.102941 | 95 | 0.627721 | latcoin |
ecf90e7d34f9f7c983fe02322941359ff1a9b32e | 5,640 | cpp | C++ | Source/Runtime/Memory.cpp | EOSIO/WAVM | 940ec12d2c1df715602c58db3a7305af10003db9 | [
"BSD-3-Clause"
] | 21 | 2018-03-21T22:40:22.000Z | 2021-05-21T06:42:31.000Z | Source/Runtime/Memory.cpp | EOSIO/WAVM | 940ec12d2c1df715602c58db3a7305af10003db9 | [
"BSD-3-Clause"
] | null | null | null | Source/Runtime/Memory.cpp | EOSIO/WAVM | 940ec12d2c1df715602c58db3a7305af10003db9 | [
"BSD-3-Clause"
] | 9 | 2018-06-04T11:44:35.000Z | 2019-01-09T03:10:37.000Z | #include "Inline/BasicTypes.h"
#include "Runtime.h"
#include "RuntimePrivate.h"
namespace Runtime
{
// Global lists of memories; used to query whether an address is reserved by one of them.
static Platform::Mutex* memoriesMutex = Platform::createMutex();
static std::vector<MemoryInstance*> memories;
enum { numGuardPages = 1 };
static Uptr getPlatformPagesPerWebAssemblyPageLog2()
{
errorUnless(Platform::getPageSizeLog2() <= IR::numBytesPerPageLog2);
return IR::numBytesPerPageLog2 - Platform::getPageSizeLog2();
}
MemoryInstance* createMemory(Compartment* compartment,MemoryType type)
{
MemoryInstance* memory = new MemoryInstance(compartment,type);
// On a 64-bit runtime, allocate 8GB of address space for the memory.
// This allows eliding bounds checks on memory accesses, since a 32-bit index + 32-bit offset will always be within the reserved address-space.
const Uptr pageBytesLog2 = Platform::getPageSizeLog2();
const Uptr memoryMaxBytes = Uptr(8ull * 1024 * 1024 * 1024);
const Uptr memoryMaxPages = memoryMaxBytes >> pageBytesLog2;
memory->baseAddress = Platform::allocateVirtualPages(memoryMaxPages + numGuardPages);
memory->endOffset = memoryMaxBytes;
if(!memory->baseAddress) { delete memory; return nullptr; }
// Grow the memory to the type's minimum size.
assert(type.size.min <= UINTPTR_MAX);
if(growMemory(memory,Uptr(type.size.min)) == -1) { delete memory; return nullptr; }
// Add the memory to the compartment.
if(compartment)
{
Platform::Lock compartmentLock(compartment->mutex);
if(compartment->memories.size() >= maxMemories) { delete memory; return nullptr; }
memory->id = compartment->memories.size();
compartment->memories.push_back(memory);
compartment->runtimeData->memories[memory->id] = memory->baseAddress;
}
// Add the memory to the global array.
{
Platform::Lock memoriesLock(memoriesMutex);
memories.push_back(memory);
}
return memory;
}
void MemoryInstance::finalize()
{
Platform::Lock compartmentLock(compartment->mutex);
assert(compartment->memories[id] == this);
assert(compartment->runtimeData->memories[id] == baseAddress);
compartment->memories[id] = nullptr;
compartment->runtimeData->memories[id] = nullptr;
}
MemoryInstance::~MemoryInstance()
{
// Decommit all default memory pages.
if(numPages > 0) { Platform::decommitVirtualPages(baseAddress,numPages << getPlatformPagesPerWebAssemblyPageLog2()); }
// Free the virtual address space.
const Uptr pageBytesLog2 = Platform::getPageSizeLog2();
if(endOffset > 0)
{
Platform::freeVirtualPages(baseAddress,(endOffset >> pageBytesLog2) + numGuardPages);
}
baseAddress = nullptr;
// Remove the memory from the global array.
{
Platform::Lock memoriesLock(memoriesMutex);
for(Uptr memoryIndex = 0;memoryIndex < memories.size();++memoryIndex)
{
if(memories[memoryIndex] == this) { memories.erase(memories.begin() + memoryIndex); break; }
}
}
}
bool isAddressOwnedByMemory(U8* address)
{
// Iterate over all memories and check if the address is within the reserved address space for each.
Platform::Lock memoriesLock(memoriesMutex);
for(auto memory : memories)
{
U8* startAddress = memory->baseAddress;
U8* endAddress = memory->baseAddress + memory->endOffset;
if(address >= startAddress && address < endAddress) { return true; }
}
return false;
}
Uptr getMemoryNumPages(MemoryInstance* memory) { return memory->numPages; }
Uptr getMemoryMaxPages(MemoryInstance* memory)
{
assert(memory->type.size.max <= UINTPTR_MAX);
return Uptr(memory->type.size.max);
}
Iptr growMemory(MemoryInstance* memory,Uptr numNewPages)
{
const Uptr previousNumPages = memory->numPages;
if(numNewPages > 0)
{
// If the number of pages to grow would cause the memory's size to exceed its maximum, return -1.
if(numNewPages > memory->type.size.max || memory->numPages > memory->type.size.max - numNewPages) { return -1; }
// Try to commit the new pages, and return -1 if the commit fails.
if(!Platform::commitVirtualPages(
memory->baseAddress + (memory->numPages << IR::numBytesPerPageLog2),
numNewPages << getPlatformPagesPerWebAssemblyPageLog2()
))
{
return -1;
}
memory->numPages += numNewPages;
}
return previousNumPages;
}
Iptr shrinkMemory(MemoryInstance* memory,Uptr numPagesToShrink)
{
const Uptr previousNumPages = memory->numPages;
if(numPagesToShrink > 0)
{
// If the number of pages to shrink would cause the memory's size to drop below its minimum, return -1.
if(numPagesToShrink > memory->numPages
|| memory->numPages - numPagesToShrink < memory->type.size.min)
{ return -1; }
memory->numPages -= numPagesToShrink;
// Decommit the pages that were shrunk off the end of the memory.
Platform::decommitVirtualPages(
memory->baseAddress + (memory->numPages << IR::numBytesPerPageLog2),
numPagesToShrink << getPlatformPagesPerWebAssemblyPageLog2()
);
}
return previousNumPages;
}
U8* getMemoryBaseAddress(MemoryInstance* memory)
{
return memory->baseAddress;
}
U8* getValidatedMemoryOffsetRange(MemoryInstance* memory,Uptr offset,Uptr numBytes)
{
// Validate that the range [offset..offset+numBytes) is contained by the memory's reserved pages.
U8* address = memory->baseAddress + Platform::saturateToBounds(offset,memory->endOffset);
if( !memory
|| address < memory->baseAddress
|| address + numBytes < address
|| address + numBytes > memory->baseAddress + memory->endOffset)
{
throwException(Exception::accessViolationType,{});
}
return address;
}
}
| 33.176471 | 145 | 0.725709 | EOSIO |
ecf9f4fe21b28770fc69e0cb86863a2ffabadcfc | 1,058 | cpp | C++ | 12791/12791.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 14 | 2017-05-02T02:00:42.000Z | 2021-11-16T07:25:29.000Z | 12791/12791.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 1 | 2017-12-25T14:18:14.000Z | 2018-02-07T06:49:44.000Z | 12791/12791.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 9 | 2016-03-03T22:06:52.000Z | 2020-04-30T22:06:24.000Z | #include <cstdio>
#include <algorithm>
using namespace std;
int main() {
int q, s, e;
scanf("%d", &q);
int years[] = { 1967,1969,1970,1971,1972,1973,1973,1974,1975,1976,1977,1977,1979, 1980,1983,1984,1987,1993,1995,1997,1999,2002,2003,2013,2016,9999 };
char album[][51] = { "DavidBowie","SpaceOddity","TheManWhoSoldTheWorld","HunkyDory","TheRiseAndFallOfZiggyStardustAndTheSpidersFromMars","AladdinSane","PinUps","DiamondDogs","YoungAmericans","StationToStation","Low","Heroes","Lodger","ScaryMonstersAndSuperCreeps","LetsDance","Tonight","NeverLetMeDown","BlackTieWhiteNoise","1.Outside","Earthling","Hours","Heathen","Reality","TheNextDay","BlackStar" };
while (q--) {
scanf("%d %d", &s, &e);
int b = 0, l = 0;
for (int i = 1; i < 26; i++) {
if (s > years[i - 1] && s <= years[i]) b = i;
if (e >= years[i - 1] && e < years[i]) l = i - 1;
}
if (years[l] > e) l = -1;
if (b <= l) {
printf("%d\n", l - b + 1);
for (int i = b; i <= l; i++) {
printf("%d %s\n", years[i], album[i]);
}
}
else {
puts("0");
}
}
} | 32.060606 | 404 | 0.598299 | isac322 |
ecfb927497c22a6d3fb71ce0e9631df2140cadcb | 3,063 | hpp | C++ | ThirdParty-mod/java2cpp/android/content/ActivityNotFoundException.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/android/content/ActivityNotFoundException.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/android/content/ActivityNotFoundException.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.content.ActivityNotFoundException
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_CONTENT_ACTIVITYNOTFOUNDEXCEPTION_HPP_DECL
#define J2CPP_ANDROID_CONTENT_ACTIVITYNOTFOUNDEXCEPTION_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class RuntimeException; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
namespace j2cpp {
namespace android { namespace content {
class ActivityNotFoundException;
class ActivityNotFoundException
: public object<ActivityNotFoundException>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
explicit ActivityNotFoundException(jobject jobj)
: object<ActivityNotFoundException>(jobj)
{
}
operator local_ref<java::lang::RuntimeException>() const;
ActivityNotFoundException();
ActivityNotFoundException(local_ref< java::lang::String > const&);
}; //class ActivityNotFoundException
} //namespace content
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_CONTENT_ACTIVITYNOTFOUNDEXCEPTION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_CONTENT_ACTIVITYNOTFOUNDEXCEPTION_HPP_IMPL
#define J2CPP_ANDROID_CONTENT_ACTIVITYNOTFOUNDEXCEPTION_HPP_IMPL
namespace j2cpp {
android::content::ActivityNotFoundException::operator local_ref<java::lang::RuntimeException>() const
{
return local_ref<java::lang::RuntimeException>(get_jobject());
}
android::content::ActivityNotFoundException::ActivityNotFoundException()
: object<android::content::ActivityNotFoundException>(
call_new_object<
android::content::ActivityNotFoundException::J2CPP_CLASS_NAME,
android::content::ActivityNotFoundException::J2CPP_METHOD_NAME(0),
android::content::ActivityNotFoundException::J2CPP_METHOD_SIGNATURE(0)
>()
)
{
}
android::content::ActivityNotFoundException::ActivityNotFoundException(local_ref< java::lang::String > const &a0)
: object<android::content::ActivityNotFoundException>(
call_new_object<
android::content::ActivityNotFoundException::J2CPP_CLASS_NAME,
android::content::ActivityNotFoundException::J2CPP_METHOD_NAME(1),
android::content::ActivityNotFoundException::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
{
}
J2CPP_DEFINE_CLASS(android::content::ActivityNotFoundException,"android/content/ActivityNotFoundException")
J2CPP_DEFINE_METHOD(android::content::ActivityNotFoundException,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::content::ActivityNotFoundException,1,"<init>","(Ljava/lang/String;)V")
} //namespace j2cpp
#endif //J2CPP_ANDROID_CONTENT_ACTIVITYNOTFOUNDEXCEPTION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 28.896226 | 114 | 0.739145 | kakashidinho |
a601d99ec6c3fd43f4caf1cfde442e51d739667d | 2,642 | cpp | C++ | src/core/visual/win32/krmovie/ogg/iBE_Math.cpp | miahmie/krkrz | e4948f61393ca4a2acac0301a975165dd4efc643 | [
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null | src/core/visual/win32/krmovie/ogg/iBE_Math.cpp | miahmie/krkrz | e4948f61393ca4a2acac0301a975165dd4efc643 | [
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null | src/core/visual/win32/krmovie/ogg/iBE_Math.cpp | miahmie/krkrz | e4948f61393ca4a2acac0301a975165dd4efc643 | [
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null | //===========================================================================
//Copyright (C) 2003, 2004 Zentaro Kavanagh
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
//- Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
//- Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
//- Neither the name of Zentaro Kavanagh nor the names of contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
//PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ORGANISATION OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//===========================================================================
#include "oggstdafx.h"
#include <iBE_Math.h>
iBE_Math::iBE_Math(void)
{
}
iBE_Math::~iBE_Math(void)
{
}
unsigned long iBE_Math::charArrToULong(unsigned char* inCharArray)
{
//Turns the next four bytes from the pointer in a long MSB (most sig. byte first/leftmost)
unsigned long locVal = 0;
for (int i = 0; i < 4; i++) {
locVal <<= 8;
locVal += inCharArray[i];
}
return locVal;
}
void iBE_Math::ULongToCharArr(unsigned long inLong, unsigned char* outCharArray)
{
//Writes a long MSB (Most sig. byte first/leftmost) out to the char arr
outCharArray[0] = (unsigned char) (inLong >> 24);
outCharArray[1] = (unsigned char) ((inLong << 8) >> 24);
outCharArray[2] = (unsigned char) ((inLong << 16) >> 24);
outCharArray[3] = (unsigned char) ((inLong << 24) >> 24);
}
unsigned short iBE_Math::charArrToUShort(unsigned char* inCharArray) {
unsigned short retShort = inCharArray[0];
retShort = (retShort << 8) + inCharArray[1];
return retShort;
} | 38.852941 | 91 | 0.700227 | miahmie |
a60642ea3e29e8f63955d27ec24f3f6fb83d7b7d | 3,997 | cpp | C++ | Engine/Source/Runtime/Engine/Private/DataBunch.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Engine/Private/DataBunch.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Engine/Private/DataBunch.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
DataBunch.cpp: Unreal bunch (sub-packet) functions.
=============================================================================*/
#include "Net/DataBunch.h"
#include "Engine/NetConnection.h"
#include "Engine/ControlChannel.h"
static const int32 MAX_BUNCH_SIZE = 1024 * 1024;
/*-----------------------------------------------------------------------------
FInBunch implementation.
-----------------------------------------------------------------------------*/
FInBunch::FInBunch( UNetConnection* InConnection, uint8* Src, int64 CountBits )
: FNetBitReader (InConnection->PackageMap, Src, CountBits)
, PacketId ( 0 )
, Next ( NULL )
, Connection ( InConnection )
, ChIndex ( 0 )
, ChType ( 0 )
, ChSequence ( 0 )
, bOpen ( 0 )
, bClose ( 0 )
, bDormant ( 0 )
, bReliable ( 0 )
, bPartial ( 0 )
, bPartialInitial ( 0 )
, bPartialFinal ( 0 )
, bHasPackageMapExports ( 0 )
{
check(Connection);
// Match the byte swapping settings of the connection
SetByteSwapping(Connection->bNeedsByteSwapping);
// Copy network version info
ArEngineNetVer = InConnection->EngineNetworkProtocolVersion;
ArGameNetVer = InConnection->GameNetworkProtocolVersion;
// Crash protection: the max string size serializable on this archive
ArMaxSerializeSize = MAX_STRING_SERIALIZE_SIZE;
}
/** Copy constructor but with optional parameter to not copy buffer */
FInBunch::FInBunch( FInBunch &InBunch, bool CopyBuffer )
{
// Copy fields
FMemory::Memcpy(&PacketId,&InBunch.PacketId,sizeof(FInBunch) - sizeof(FNetBitReader));
// Copy network version info
ArEngineNetVer = InBunch.ArEngineNetVer;
ArGameNetVer = InBunch.ArGameNetVer;
PackageMap = InBunch.PackageMap;
ArMaxSerializeSize = MAX_STRING_SERIALIZE_SIZE;
if (CopyBuffer)
FBitReader::operator=(InBunch);
Pos = 0;
}
/*-----------------------------------------------------------------------------
FOutBunch implementation.
-----------------------------------------------------------------------------*/
//
// Construct an outgoing bunch for a channel.
// It is ok to either send or discard an FOutbunch after construction.
//
FOutBunch::FOutBunch()
: FNetBitWriter( 0 )
{}
FOutBunch::FOutBunch( UChannel* InChannel, bool bInClose )
: FNetBitWriter ( InChannel->Connection->PackageMap, InChannel->Connection->GetMaxSingleBunchSizeBits())
, Next ( NULL )
, Channel ( InChannel )
, Time ( 0 )
, ReceivedAck ( false )
, ChIndex ( InChannel->ChIndex )
, ChType ( InChannel->ChType )
, ChSequence ( 0 )
, PacketId ( 0 )
, bOpen ( 0 )
, bClose ( bInClose )
, bDormant ( 0 )
, bIsReplicationPaused ( 0 )
, bReliable ( 0 )
, bPartial ( 0 )
, bPartialInitial ( 0 )
, bPartialFinal ( 0 )
, bHasPackageMapExports ( 0 )
, bHasMustBeMappedGUIDs ( 0 )
{
checkSlow(!Channel->Closing);
checkSlow(Channel->Connection->Channels[Channel->ChIndex]==Channel);
// Match the byte swapping settings of the connection
SetByteSwapping(Channel->Connection->bNeedsByteSwapping);
// Reserve channel and set bunch info.
if( Channel->NumOutRec >= RELIABLE_BUFFER-1+bClose )
{
SetOverflowed(-1);
return;
}
}
FOutBunch::FOutBunch( UPackageMap *InPackageMap, int64 MaxBits )
: FNetBitWriter ( InPackageMap, MaxBits )
, Next ( NULL )
, Channel ( NULL )
, Time ( 0 )
, ReceivedAck ( false )
, ChIndex ( 0 )
, ChType ( 0 )
, ChSequence ( 0 )
, PacketId ( 0 )
, bOpen ( 0 )
, bClose ( 0 )
, bDormant ( 0 )
, bIsReplicationPaused ( 0 )
, bReliable ( 0 )
, bPartial ( 0 )
, bPartialInitial ( 0 )
, bPartialFinal ( 0 )
, bHasPackageMapExports ( 0 )
, bHasMustBeMappedGUIDs ( 0 )
{
}
FControlChannelOutBunch::FControlChannelOutBunch(UChannel* InChannel, bool bClose)
: FOutBunch(InChannel, bClose)
{
checkSlow(Cast<UControlChannel>(InChannel) != NULL);
// control channel bunches contain critical handshaking/synchronization and should always be reliable
bReliable = true;
}
| 27.376712 | 104 | 0.629972 | windystrife |
a607057f41683c7a0b919ac86a7b44c3ee7a58f7 | 11,127 | cpp | C++ | sdk/storage/azure-storage-files-datalake/src/datalake_directory_client.cpp | RickWinter/azure-sdk-for-cpp | b4fe751310f53669a941e00aa93072f2d10a4eba | [
"MIT"
] | 96 | 2020-03-19T07:49:39.000Z | 2022-03-20T14:22:41.000Z | sdk/storage/azure-storage-files-datalake/src/datalake_directory_client.cpp | RickWinter/azure-sdk-for-cpp | b4fe751310f53669a941e00aa93072f2d10a4eba | [
"MIT"
] | 2,572 | 2020-03-18T22:54:53.000Z | 2022-03-31T22:09:59.000Z | sdk/storage/azure-storage-files-datalake/src/datalake_directory_client.cpp | RickWinter/azure-sdk-for-cpp | b4fe751310f53669a941e00aa93072f2d10a4eba | [
"MIT"
] | 81 | 2020-03-19T09:42:00.000Z | 2022-03-24T05:11:05.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include "azure/storage/files/datalake/datalake_directory_client.hpp"
#include <azure/core/http/policies/policy.hpp>
#include <azure/storage/common/crypt.hpp>
#include <azure/storage/common/internal/constants.hpp>
#include <azure/storage/common/internal/shared_key_policy.hpp>
#include <azure/storage/common/internal/storage_switch_to_secondary_policy.hpp>
#include <azure/storage/common/storage_common.hpp>
#include "azure/storage/files/datalake/datalake_file_client.hpp"
#include "private/datalake_utilities.hpp"
namespace Azure { namespace Storage { namespace Files { namespace DataLake {
DataLakeDirectoryClient DataLakeDirectoryClient::CreateFromConnectionString(
const std::string& connectionString,
const std::string& fileSystemName,
const std::string& directoryName,
const DataLakeClientOptions& options)
{
auto parsedConnectionString = _internal::ParseConnectionString(connectionString);
auto directoryUrl = std::move(parsedConnectionString.DataLakeServiceUrl);
directoryUrl.AppendPath(_internal::UrlEncodePath(fileSystemName));
directoryUrl.AppendPath(_internal::UrlEncodePath(directoryName));
if (parsedConnectionString.KeyCredential)
{
return DataLakeDirectoryClient(
directoryUrl.GetAbsoluteUrl(), parsedConnectionString.KeyCredential, options);
}
else
{
return DataLakeDirectoryClient(directoryUrl.GetAbsoluteUrl(), options);
}
}
DataLakeDirectoryClient::DataLakeDirectoryClient(
const std::string& directoryUrl,
std::shared_ptr<StorageSharedKeyCredential> credential,
const DataLakeClientOptions& options)
: DataLakePathClient(directoryUrl, credential, options)
{
}
DataLakeDirectoryClient::DataLakeDirectoryClient(
const std::string& directoryUrl,
std::shared_ptr<Core::Credentials::TokenCredential> credential,
const DataLakeClientOptions& options)
: DataLakePathClient(directoryUrl, credential, options)
{
}
DataLakeDirectoryClient::DataLakeDirectoryClient(
const std::string& directoryUrl,
const DataLakeClientOptions& options)
: DataLakePathClient(directoryUrl, options)
{
}
DataLakeFileClient DataLakeDirectoryClient::GetFileClient(const std::string& fileName) const
{
auto builder = m_pathUrl;
builder.AppendPath(_internal::UrlEncodePath(fileName));
auto blobClient = m_blobClient;
blobClient.m_blobUrl.AppendPath(_internal::UrlEncodePath(fileName));
return DataLakeFileClient(std::move(builder), std::move(blobClient), m_pipeline);
}
DataLakeDirectoryClient DataLakeDirectoryClient::GetSubdirectoryClient(
const std::string& subdirectoryName) const
{
auto builder = m_pathUrl;
builder.AppendPath(_internal::UrlEncodePath(subdirectoryName));
auto blobClient = m_blobClient;
blobClient.m_blobUrl.AppendPath(_internal::UrlEncodePath(subdirectoryName));
return DataLakeDirectoryClient(std::move(builder), std::move(blobClient), m_pipeline);
}
Azure::Response<DataLakeFileClient> DataLakeDirectoryClient::RenameFile(
const std::string& fileName,
const std::string& destinationFilePath,
const RenameFileOptions& options,
const Azure::Core::Context& context) const
{
std::string destinationFileSystem;
if (options.DestinationFileSystem.HasValue())
{
destinationFileSystem = options.DestinationFileSystem.Value();
}
else
{
const std::string& currentPath = m_pathUrl.GetPath();
destinationFileSystem = currentPath.substr(0, currentPath.find('/'));
}
auto sourceDfsUrl = m_pathUrl;
sourceDfsUrl.AppendPath(_internal::UrlEncodePath(fileName));
auto destinationDfsUrl = m_pathUrl;
destinationDfsUrl.SetPath(_internal::UrlEncodePath(destinationFileSystem));
destinationDfsUrl.AppendPath(_internal::UrlEncodePath(destinationFilePath));
_detail::DataLakeRestClient::Path::CreateOptions protocolLayerOptions;
protocolLayerOptions.Mode = _detail::PathRenameMode::Legacy;
protocolLayerOptions.SourceLeaseId = options.SourceAccessConditions.LeaseId;
protocolLayerOptions.LeaseIdOptional = options.AccessConditions.LeaseId;
protocolLayerOptions.IfMatch = options.AccessConditions.IfMatch;
protocolLayerOptions.IfNoneMatch = options.AccessConditions.IfNoneMatch;
protocolLayerOptions.IfModifiedSince = options.AccessConditions.IfModifiedSince;
protocolLayerOptions.IfUnmodifiedSince = options.AccessConditions.IfUnmodifiedSince;
protocolLayerOptions.SourceIfMatch = options.SourceAccessConditions.IfMatch;
protocolLayerOptions.SourceIfNoneMatch = options.SourceAccessConditions.IfNoneMatch;
protocolLayerOptions.SourceIfModifiedSince = options.SourceAccessConditions.IfModifiedSince;
protocolLayerOptions.SourceIfUnmodifiedSince = options.SourceAccessConditions.IfUnmodifiedSince;
protocolLayerOptions.RenameSource = "/" + sourceDfsUrl.GetPath();
auto result = _detail::DataLakeRestClient::Path::Create(
destinationDfsUrl, *m_pipeline, context, protocolLayerOptions);
auto renamedBlobClient
= Blobs::BlobClient(_detail::GetBlobUrlFromUrl(destinationDfsUrl), m_pipeline);
auto renamedFileClient = DataLakeFileClient(
std::move(destinationDfsUrl), std::move(renamedBlobClient), m_pipeline);
return Azure::Response<DataLakeFileClient>(
std::move(renamedFileClient), std::move(result.RawResponse));
}
Azure::Response<DataLakeDirectoryClient> DataLakeDirectoryClient::RenameSubdirectory(
const std::string& subdirectoryName,
const std::string& destinationDirectoryPath,
const RenameSubdirectoryOptions& options,
const Azure::Core::Context& context) const
{
std::string destinationFileSystem;
if (options.DestinationFileSystem.HasValue())
{
destinationFileSystem = options.DestinationFileSystem.Value();
}
else
{
const std::string& currentPath = m_pathUrl.GetPath();
destinationFileSystem = currentPath.substr(0, currentPath.find('/'));
}
auto sourceDfsUrl = m_pathUrl;
sourceDfsUrl.AppendPath(_internal::UrlEncodePath(subdirectoryName));
auto destinationDfsUrl = m_pathUrl;
destinationDfsUrl.SetPath(_internal::UrlEncodePath(destinationFileSystem));
destinationDfsUrl.AppendPath(_internal::UrlEncodePath(destinationDirectoryPath));
_detail::DataLakeRestClient::Path::CreateOptions protocolLayerOptions;
protocolLayerOptions.Mode = _detail::PathRenameMode::Legacy;
protocolLayerOptions.SourceLeaseId = options.SourceAccessConditions.LeaseId;
protocolLayerOptions.LeaseIdOptional = options.AccessConditions.LeaseId;
protocolLayerOptions.IfMatch = options.AccessConditions.IfMatch;
protocolLayerOptions.IfNoneMatch = options.AccessConditions.IfNoneMatch;
protocolLayerOptions.IfModifiedSince = options.AccessConditions.IfModifiedSince;
protocolLayerOptions.IfUnmodifiedSince = options.AccessConditions.IfUnmodifiedSince;
protocolLayerOptions.SourceIfMatch = options.SourceAccessConditions.IfMatch;
protocolLayerOptions.SourceIfNoneMatch = options.SourceAccessConditions.IfNoneMatch;
protocolLayerOptions.SourceIfModifiedSince = options.SourceAccessConditions.IfModifiedSince;
protocolLayerOptions.SourceIfUnmodifiedSince = options.SourceAccessConditions.IfUnmodifiedSince;
protocolLayerOptions.RenameSource = "/" + sourceDfsUrl.GetPath();
auto result = _detail::DataLakeRestClient::Path::Create(
destinationDfsUrl, *m_pipeline, context, protocolLayerOptions);
auto renamedBlobClient
= Blobs::BlobClient(_detail::GetBlobUrlFromUrl(destinationDfsUrl), m_pipeline);
auto renamedDirectoryClient = DataLakeDirectoryClient(
std::move(destinationDfsUrl), std::move(renamedBlobClient), m_pipeline);
return Azure::Response<DataLakeDirectoryClient>(
std::move(renamedDirectoryClient), std::move(result.RawResponse));
}
Azure::Response<Models::DeleteDirectoryResult> DataLakeDirectoryClient::Delete(
bool recursive,
const DeleteDirectoryOptions& options,
const Azure::Core::Context& context) const
{
DeletePathOptions deleteOptions;
deleteOptions.AccessConditions = options.AccessConditions;
deleteOptions.Recursive = recursive;
return DataLakePathClient::Delete(deleteOptions, context);
}
Azure::Response<Models::DeleteDirectoryResult> DataLakeDirectoryClient::DeleteIfExists(
bool recursive,
const DeleteDirectoryOptions& options,
const Azure::Core::Context& context) const
{
DeletePathOptions deleteOptions;
deleteOptions.AccessConditions = options.AccessConditions;
deleteOptions.Recursive = recursive;
return DataLakePathClient::DeleteIfExists(deleteOptions, context);
}
ListPathsPagedResponse DataLakeDirectoryClient::ListPaths(
bool recursive,
const ListPathsOptions& options,
const Azure::Core::Context& context) const
{
_detail::DataLakeRestClient::FileSystem::ListPathsOptions protocolLayerOptions;
protocolLayerOptions.Resource = _detail::FileSystemResource::Filesystem;
protocolLayerOptions.Upn = options.UserPrincipalName;
protocolLayerOptions.MaxResults = options.PageSizeHint;
protocolLayerOptions.RecursiveRequired = recursive;
const std::string currentPath = m_pathUrl.GetPath();
auto firstSlashPos = std::find(currentPath.begin(), currentPath.end(), '/');
const std::string fileSystemName(currentPath.begin(), firstSlashPos);
if (firstSlashPos != currentPath.end())
{
++firstSlashPos;
}
const std::string directoryPath(firstSlashPos, currentPath.end());
if (!directoryPath.empty())
{
protocolLayerOptions.Directory = directoryPath;
}
auto fileSystemUrl = m_pathUrl;
fileSystemUrl.SetPath(fileSystemName);
auto clientCopy = *this;
std::function<ListPathsPagedResponse(std::string, const Azure::Core::Context&)> func;
func = [func, clientCopy, protocolLayerOptions, fileSystemUrl](
std::string continuationToken, const Azure::Core::Context& context) {
auto protocolLayerOptionsCopy = protocolLayerOptions;
if (!continuationToken.empty())
{
protocolLayerOptionsCopy.ContinuationToken = continuationToken;
}
auto response = _detail::DataLakeRestClient::FileSystem::ListPaths(
fileSystemUrl,
*clientCopy.m_pipeline,
_internal::WithReplicaStatus(context),
protocolLayerOptionsCopy);
ListPathsPagedResponse pagedResponse;
pagedResponse.Paths = std::move(response.Value.Items);
pagedResponse.m_onNextPageFunc = func;
pagedResponse.CurrentPageToken = continuationToken;
pagedResponse.NextPageToken = response.Value.ContinuationToken;
pagedResponse.RawResponse = std::move(response.RawResponse);
return pagedResponse;
};
return func(options.ContinuationToken.ValueOr(std::string()), context);
}
}}}} // namespace Azure::Storage::Files::DataLake
| 43.127907 | 100 | 0.764986 | RickWinter |
a6091729a24fe205bc2cc6e473e989fa8480d769 | 1,836 | cpp | C++ | src/condor_startd.V6/StartdPluginManager.cpp | datadvance/htcondor | aa9cc9e87832003fb2533e6be5bc95ead4222318 | [
"Apache-2.0"
] | 217 | 2015-01-08T04:49:42.000Z | 2022-03-27T10:11:58.000Z | src/condor_startd.V6/StartdPluginManager.cpp | datadvance/htcondor | aa9cc9e87832003fb2533e6be5bc95ead4222318 | [
"Apache-2.0"
] | 185 | 2015-05-03T13:26:31.000Z | 2022-03-28T03:08:59.000Z | src/condor_startd.V6/StartdPluginManager.cpp | datadvance/htcondor | aa9cc9e87832003fb2533e6be5bc95ead4222318 | [
"Apache-2.0"
] | 133 | 2015-02-11T09:17:45.000Z | 2022-03-31T07:28:54.000Z | /*
* Copyright 2008 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "condor_common.h"
#include "PluginManager.h"
#include "StartdPlugin.h"
#include "condor_config.h"
void
StartdPluginManager::Initialize()
{
StartdPlugin *plugin;
SimpleList<StartdPlugin *> plugins = getPlugins();
plugins.Rewind();
while (plugins.Next(plugin)) {
plugin->initialize();
}
}
void
StartdPluginManager::Shutdown()
{
StartdPlugin *plugin;
SimpleList<StartdPlugin *> plugins = getPlugins();
plugins.Rewind();
while (plugins.Next(plugin)) {
plugin->shutdown();
}
}
void
StartdPluginManager::Update(const ClassAd *publicAd, const ClassAd *privateAd)
{
StartdPlugin *plugin;
SimpleList<StartdPlugin *> plugins = getPlugins();
plugins.Rewind();
while (plugins.Next(plugin)) {
plugin->update(publicAd, privateAd);
}
}
void
StartdPluginManager::Invalidate(const ClassAd *ad)
{
StartdPlugin *plugin;
SimpleList<StartdPlugin *> plugins = getPlugins();
plugins.Rewind();
while (plugins.Next(plugin)) {
plugin->invalidate(ad);
}
}
StartdPlugin::StartdPlugin()
{
if (PluginManager<StartdPlugin>::registerPlugin(this)) {
dprintf(D_ALWAYS, "StartdPlugin registration succeeded\n");
} else {
dprintf(D_ALWAYS, "StartdPlugin registration failed\n");
}
}
StartdPlugin::~StartdPlugin() { }
| 22.95 | 78 | 0.729303 | datadvance |
a611437d2f6c1d9a6d439591540f5a3692af13c9 | 540 | hpp | C++ | Sources/OskGadgetCWrap/include/OskGadgetCWrap.hpp | opensmartkitchen/OSK-Bridge | 42bb222f6db74dda43ea86849862f338efb72339 | [
"Apache-2.0"
] | null | null | null | Sources/OskGadgetCWrap/include/OskGadgetCWrap.hpp | opensmartkitchen/OSK-Bridge | 42bb222f6db74dda43ea86849862f338efb72339 | [
"Apache-2.0"
] | null | null | null | Sources/OskGadgetCWrap/include/OskGadgetCWrap.hpp | opensmartkitchen/OSK-Bridge | 42bb222f6db74dda43ea86849862f338efb72339 | [
"Apache-2.0"
] | null | null | null | #ifndef OSK_GADGET_CWRAP_
#define OSK_GADGET_CWRAP_
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// Class Memory Management
void * oskGadgetCreate();
void oskGadgetDestroy(void* oskGadget);
bool oskGadgetInit(void* oskGadget);
void oskGadgetRun(void* oskGadget);
// Class Methods()
//float oskGadgetGetScaleWeight(void* oskGadget);
long oskGadgetGetLastTimestamp(void* oskGadget);
#ifdef __cplusplus
}
#endif
#endif // OSK_GADGET_CWRAP_
| 18.62069 | 53 | 0.716667 | opensmartkitchen |
a611e4e2ae22cbdbe3729bf20d7e9959001ca527 | 1,789 | cpp | C++ | solid/utility/test/test_workpool_context.cpp | solidoss/solidframe | 92fa8ce5737b9e88f3df3f549a38e9df79b7bf96 | [
"BSL-1.0"
] | 4 | 2020-12-05T23:33:32.000Z | 2021-10-04T02:59:41.000Z | solid/utility/test/test_workpool_context.cpp | solidoss/solidframe | 92fa8ce5737b9e88f3df3f549a38e9df79b7bf96 | [
"BSL-1.0"
] | 1 | 2020-03-22T20:38:05.000Z | 2020-03-22T20:38:05.000Z | solid/utility/test/test_workpool_context.cpp | solidoss/solidframe | 92fa8ce5737b9e88f3df3f549a38e9df79b7bf96 | [
"BSL-1.0"
] | 2 | 2021-01-30T09:08:52.000Z | 2021-02-20T03:33:33.000Z | #include "solid/system/exception.hpp"
#include "solid/system/log.hpp"
#include "solid/utility/function.hpp"
#include "solid/utility/workpool.hpp"
#include <atomic>
#include <future>
#include <iostream>
using namespace solid;
using namespace std;
namespace {
const LoggerT logger("test_context");
struct Context {
string s_;
atomic<size_t> v_;
const size_t c_;
Context(const string& _s, const size_t _v, const size_t _c)
: s_(_s)
, v_(_v)
, c_(_c)
{
}
~Context()
{
}
};
} //namespace
int test_workpool_context(int argc, char* argv[])
{
solid::log_start(std::cerr, {".*:EWXS", "test_context:VIEWS"});
int wait_seconds = 500;
int loop_cnt = 5;
const size_t cnt{50000};
auto lambda = [&]() {
#if 1
for (int i = 0; i < loop_cnt; ++i) {
Context ctx{"test", 1, cnt + 1};
{
CallPool<void(Context&)> wp{
WorkPoolConfiguration(), 2,
std::ref(ctx)};
solid_log(generic_logger, Verbose, "wp started");
for (size_t i = 0; i < cnt; ++i) {
auto l = [](Context& _rctx) {
++_rctx.v_;
};
wp.push(l);
};
}
solid_check(ctx.v_ == ctx.c_, ctx.v_ << " != " << ctx.c_);
solid_log(logger, Verbose, "after loop");
}
#endif
};
auto fut = async(launch::async, lambda);
if (fut.wait_for(chrono::seconds(wait_seconds)) != future_status::ready) {
solid_throw(" Test is taking too long - waited " << wait_seconds << " secs");
}
fut.get();
solid_log(logger, Verbose, "after async wait");
return 0;
}
| 24.506849 | 85 | 0.515931 | solidoss |
a6140feaed8ba2fb2b40bedf8c886301415d5aa3 | 668 | cpp | C++ | DSA1_gfg/05_insertion_sort.cpp | yashlad27/codeforce-codechef-problems | 4223dccb668e1d9ecabce4740178bc1bfe468023 | [
"MIT"
] | null | null | null | DSA1_gfg/05_insertion_sort.cpp | yashlad27/codeforce-codechef-problems | 4223dccb668e1d9ecabce4740178bc1bfe468023 | [
"MIT"
] | null | null | null | DSA1_gfg/05_insertion_sort.cpp | yashlad27/codeforce-codechef-problems | 4223dccb668e1d9ecabce4740178bc1bfe468023 | [
"MIT"
] | null | null | null | // INSERTION SORT:-
#include<bits/stdc++.h>
using namespace std;
void insertion_sort(int arr[], int n)
{
int i, key, j;
for (i = 0; i < n; i++)
{
key = arr[i];
j=i-1;
while(j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j=j-1;
}
arr[j+1] = key;
}
}
void display(int arr[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
cout << arr[i] <<" ";
}
cout<<endl;
}
int main()
{
int arr[]={12,1,11,4,13,67,8};
int n = sizeof(arr)/sizeof(arr[0]);
insertion_sort(arr, n);
display(arr, n);
return 0;
} | 15.904762 | 40 | 0.399701 | yashlad27 |
a614cafd6c222ddcd37f6c1322341ba447edfa48 | 686 | cpp | C++ | common.cpp | FrozenCow/nzbtotar | c9760337c8cb690608149d71c107bebccad3dabc | [
"MIT"
] | null | null | null | common.cpp | FrozenCow/nzbtotar | c9760337c8cb690608149d71c107bebccad3dabc | [
"MIT"
] | null | null | null | common.cpp | FrozenCow/nzbtotar | c9760337c8cb690608149d71c107bebccad3dabc | [
"MIT"
] | null | null | null | #include "common.h"
#define PRINTFILE "/tmp/trace2"
void printrarread(const char *buf,size_t size, size_t offset) {
FILE *f = fopen(PRINTFILE,"a");
fprintf(f,"RAR_READ %lld @ %lld\n",size,offset);
for(int i=0;i<size;i++) {
fprintf(f,"%02x ", buf[i] & 0xff);
}
fprintf(f,"\n");
fclose(f);
sleep(1);
}
void printrarseek(size_t nr, int type, size_t offset) {
FILE *f = fopen(PRINTFILE,"a");
size_t newoffset = offset;
switch(type) {
case SEEK_SET: newoffset = nr; break;
case SEEK_CUR: newoffset += nr; break;
case SEEK_END: newoffset = 999999; break;
}
fprintf(f,"RAR_SEEK %lld > %lld (%d)\n", offset, newoffset, type);
fclose(f);
sleep(1);
} | 26.384615 | 68 | 0.632653 | FrozenCow |
a6173c72e9a7b0d13e2615d5f286865c730d4a6c | 3,541 | cc | C++ | src/core/lib/gpr/sync_windows.cc | warlock135/grpc | 81e13e4fa9c0cdf7dc131ce548e1604c895b738c | [
"Apache-2.0"
] | 36,552 | 2015-02-26T17:30:13.000Z | 2022-03-31T22:41:33.000Z | src/core/lib/gpr/sync_windows.cc | SanjanaSingh897/grpc | 2d858866eb95ce5de8ccc8c35189a12733d8ca79 | [
"Apache-2.0"
] | 23,536 | 2015-02-26T17:50:56.000Z | 2022-03-31T23:39:42.000Z | src/core/lib/gpr/sync_windows.cc | SanjanaSingh897/grpc | 2d858866eb95ce5de8ccc8c35189a12733d8ca79 | [
"Apache-2.0"
] | 11,050 | 2015-02-26T17:22:10.000Z | 2022-03-31T10:12:35.000Z | /*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* Win32 code for gpr synchronization support. */
#include <grpc/support/port_platform.h>
#if defined(GPR_WINDOWS) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC)
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
void gpr_mu_init(gpr_mu* mu) {
InitializeCriticalSection(&mu->cs);
mu->locked = 0;
}
void gpr_mu_destroy(gpr_mu* mu) { DeleteCriticalSection(&mu->cs); }
void gpr_mu_lock(gpr_mu* mu) {
EnterCriticalSection(&mu->cs);
GPR_ASSERT(!mu->locked);
mu->locked = 1;
}
void gpr_mu_unlock(gpr_mu* mu) {
mu->locked = 0;
LeaveCriticalSection(&mu->cs);
}
int gpr_mu_trylock(gpr_mu* mu) {
int result = TryEnterCriticalSection(&mu->cs);
if (result) {
if (mu->locked) { /* This thread already holds the lock. */
LeaveCriticalSection(&mu->cs); /* Decrement lock count. */
result = 0; /* Indicate failure */
}
mu->locked = 1;
}
return result;
}
/*----------------------------------------*/
void gpr_cv_init(gpr_cv* cv) { InitializeConditionVariable(cv); }
void gpr_cv_destroy(gpr_cv* cv) {
/* Condition variables don't need destruction in Win32. */
}
int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
int timeout = 0;
DWORD timeout_max_ms;
mu->locked = 0;
if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
0) {
SleepConditionVariableCS(cv, &mu->cs, INFINITE);
} else {
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
gpr_timespec now = gpr_now(abs_deadline.clock_type);
int64_t now_ms = (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
int64_t deadline_ms =
(int64_t)abs_deadline.tv_sec * 1000 + abs_deadline.tv_nsec / 1000000;
if (now_ms >= deadline_ms) {
timeout = 1;
} else {
if ((deadline_ms - now_ms) >= INFINITE) {
timeout_max_ms = INFINITE - 1;
} else {
timeout_max_ms = (DWORD)(deadline_ms - now_ms);
}
timeout = (SleepConditionVariableCS(cv, &mu->cs, timeout_max_ms) == 0 &&
GetLastError() == ERROR_TIMEOUT);
}
}
mu->locked = 1;
return timeout;
}
void gpr_cv_signal(gpr_cv* cv) { WakeConditionVariable(cv); }
void gpr_cv_broadcast(gpr_cv* cv) { WakeAllConditionVariable(cv); }
/*----------------------------------------*/
static void* phony;
struct run_once_func_arg {
void (*init_function)(void);
};
static BOOL CALLBACK run_once_func(gpr_once* once, void* v, void** pv) {
struct run_once_func_arg* arg = (struct run_once_func_arg*)v;
(*arg->init_function)();
return 1;
}
void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
struct run_once_func_arg arg;
arg.init_function = init_function;
InitOnceExecuteOnce(once, run_once_func, &arg, &phony);
}
#endif /* defined(GPR_WINDOWS) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC) */
| 29.264463 | 78 | 0.664502 | warlock135 |
a6179bb570e97ba9b4b934c0623c27b7eebde47d | 305 | cpp | C++ | suda/0511/test.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | suda/0511/test.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | suda/0511/test.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
cout << 1 << endl;
const int MAXN = 5e5;
cout << MAXN << " " << MAXN << endl;
for(int i = 1; i <= MAXN; ++i) {
cout << i + 1 << " ";
}
cout << endl;
for(int i = 1; i <= MAXN; ++i) {
cout << i + 1 << " ";
}
cout << endl;
return 0;
} | 17.941176 | 37 | 0.468852 | tusikalanse |
a617f4a4ee62a911cc221a084f7daa20d3b66ded | 4,417 | cpp | C++ | src/midi_player.cpp | Fadis/ifm | 8e538c67e756cfc4056bf406e578809dc2b462f9 | [
"MIT"
] | 20 | 2020-02-08T08:51:42.000Z | 2021-05-28T04:44:24.000Z | src/midi_player.cpp | Fadis/ifm | 8e538c67e756cfc4056bf406e578809dc2b462f9 | [
"MIT"
] | 1 | 2020-04-01T18:31:50.000Z | 2020-04-01T18:31:50.000Z | src/midi_player.cpp | Fadis/ifm | 8e538c67e756cfc4056bf406e578809dc2b462f9 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2020 Naomasa Matsubayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <array>
#include <iostream>
#include <boost/program_options.hpp>
#include "ifm/midi_player.h"
#include "ifm/midi_sequencer2.h"
#include <sndfile.h>
class wavesink {
public:
wavesink( const char *filename ) {
config.frames = 0;
config.samplerate = ifm::synth_sample_rate;
config.channels = 1;
config.format = SF_FORMAT_WAV|SF_FORMAT_PCM_16;
config.sections = 0;
config.seekable = 1;
file = sf_open( filename, SFM_WRITE, &config );
}
~wavesink() {
sf_write_sync( file );
sf_close( file );
}
void play_if_not_playing() const {
}
bool buffer_is_ready() const {
return true;
}
void operator()( const float data ) {
int16_t ibuf[ 1 ];
std::transform( &data, &data + 1, ibuf, []( const float &value ) { return int16_t( value * 32767 ); } );
sf_write_short( file, ibuf, 1 );
}
template< size_t i >
void operator()( const std::array< int16_t, i > &data ) {
sf_write_short( file, data.data(), i );
}
template< size_t i >
void operator()( const std::array< float, i > &data ) {
std::array< int16_t, i > idata;
std::transform( data.begin(), data.end(), idata.begin(), []( const float &value ) { return int16_t( value * 32767 ); } );
sf_write_short( file, idata.data(), i );
}
private:
SF_INFO config;
SNDFILE* file;
};
int main( int argc, char* argv[] ) {
boost::program_options::options_description options("オプション");
options.add_options()
("help,h", "ヘルプを表示")
("config,c", boost::program_options::value<std::string>(), "設定ファイル")
("input,i", boost::program_options::value<std::string>(), "入力ファイル")
("output,o", boost::program_options::value<std::string>(), "出力ファイル");
boost::program_options::variables_map params;
boost::program_options::store( boost::program_options::parse_command_line( argc, argv, options ), params );
boost::program_options::notify( params );
if( params.count("help") || !params.count("config") || !params.count("input") || !params.count("output") ) {
std::cout << options << std::endl;
return 0;
}
const std::string input_filename = params["input"].as<std::string>();
const std::string output_filename = params["output"].as<std::string>();
wavesink sink( output_filename.c_str() );
nlohmann::json config;
{
std::ifstream config_file( params[ "config" ].as< std::string >() );
config_file >> config;
}
auto fm_params = ifm::load_fm_params< 4 >( config );
ifm::midi_sequencer< const uint8_t*, 4 > seq( fm_params );
const int fd = open( input_filename.c_str(), O_RDONLY );
if( fd < 0 ) {
return -1;
}
struct stat buf;
if( fstat( fd, &buf ) < 0 ) {
return -1;
}
void * const mapped = mmap( NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0 );
if( mapped == nullptr ) {
return -1;
}
const auto midi_begin = reinterpret_cast< uint8_t* >( mapped );
const auto midi_end = std::next( midi_begin, buf.st_size );
std::cout << std::string( midi_begin, midi_begin + 4 ) << std::endl;
if( !seq.load( midi_begin, midi_end ) ) {
return -1;
}
std::array< float, ifm::synth_block_size > buffer;
while( !seq.is_end() ) {
seq( buffer.data() );
sink( buffer );
}
}
| 35.336 | 125 | 0.678741 | Fadis |
a6192185a52c12a39daa89aeb06409cf43b90df1 | 11,733 | cpp | C++ | src/owPhysicsFluidSimulator.cpp | ranr01/pySibernetic | 82fee81c90b10c0135a10b710964a1b6ef0fc7c2 | [
"MIT"
] | 1 | 2021-08-31T01:49:37.000Z | 2021-08-31T01:49:37.000Z | src/owPhysicsFluidSimulator.cpp | ranr01/pySibernetic | 82fee81c90b10c0135a10b710964a1b6ef0fc7c2 | [
"MIT"
] | null | null | null | src/owPhysicsFluidSimulator.cpp | ranr01/pySibernetic | 82fee81c90b10c0135a10b710964a1b6ef0fc7c2 | [
"MIT"
] | 1 | 2022-02-19T16:20:27.000Z | 2022-02-19T16:20:27.000Z | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2011, 2013 OpenWorm.
* http://openworm.org
*
* Copyright (c) 2017, Ran Rubin.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/MIT
*
* Contributors:
* OpenWorm - http://openworm.org/people.html
* Ran Rubin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
#include <fstream>
#include <iostream>
#include <stdexcept>
#include "owPhysicsFluidSimulator.h"
//#include "owSignalSimulator.h"
//#include "owVtkExport.h"
/** Constructor method for owPhysicsFluidSimulator.
*
* @param helper
* pointer to owHelper object with helper function.
* @param dev_type
* defines preferable device type for current configuration
*/
owPhysicsFluidSimulator::owPhysicsFluidSimulator(owConfigProperty * sim_config) {
// int generateInitialConfiguration = 1;//1 to generate initial configuration,
// 0 - load from file
try {
iterationCount = 0;
config = sim_config;
this->helper = new owHelper();
init_config();
} catch (std::runtime_error &ex) {
/* Clearing all allocated buffers and created object only not ocl_solver
* case it wont be created yet only if exception is throwing from its
* constructor
* but in this case ocl_solver wont be created
* */
destroy();
delete helper;
delete ocl_solver;
throw;
}
}
void owPhysicsFluidSimulator::init_config(){
// LOAD FROM FILE
owHelper::preLoadConfiguration(config);
config->initGridCells();
position_cpp_size = 4 * config->getParticleCount();
position_cpp = new float[position_cpp_size];
velocity_cpp_size = 4 * config->getParticleCount();
velocity_cpp = new float[velocity_cpp_size];
muscle_activation_signal_cpp_size = config->MUSCLE_COUNT;
muscle_activation_signal_cpp = new float[muscle_activation_signal_cpp_size];
elasticConnectionsData_cpp_size = 4 * config->numOfElasticP * MAX_NEIGHBOR_COUNT;
if (config->numOfElasticP != 0)
elasticConnectionsData_cpp = new float[elasticConnectionsData_cpp_size];
membraneData_cpp_size = config->numOfMembranes * 3;
if (config->numOfMembranes <= 0)
membraneData_cpp = NULL;
else
membraneData_cpp = new int[membraneData_cpp_size];
if (config->numOfElasticP <= 0)
particleMembranesList_cpp = NULL;
else
particleMembranesList_cpp =
new int[config->numOfElasticP *
MAX_MEMBRANES_INCLUDING_SAME_PARTICLE];
for (unsigned int i = 0; i < config->MUSCLE_COUNT; ++i) {
muscle_activation_signal_cpp[i] = 0.f;
}
// The buffers listed below are only for usability and debug
density_cpp_size = 1 * config->getParticleCount();
density_cpp = new float[density_cpp_size];
particleIndex_cpp_size = config->getParticleCount() * 2;
particleIndex_cpp = new unsigned int[particleIndex_cpp_size];
// LOAD FROM FILE
owHelper::loadConfiguration(
position_cpp, velocity_cpp, elasticConnectionsData_cpp,
membraneData_cpp, particleMembranesList_cpp,
config); // Load configuration from file to buffer
if (config->numOfElasticP != 0) {
ocl_solver = new owOpenCLSolver(
position_cpp, velocity_cpp, config, elasticConnectionsData_cpp,
membraneData_cpp,
particleMembranesList_cpp); // Create new openCLsolver instance
} else
ocl_solver =
new owOpenCLSolver(position_cpp, velocity_cpp,config); // Create new openCLsolver instance
}
/** Reset simulation
*
* Restart simulation with new or current simulation configuration.
* It redefines all required data buffers and restart owOpenCLSolver
* by run owOpenCLSolver::reset(...).
*/
void owPhysicsFluidSimulator::reset() {
// Free all buffers
destroy();
delete ocl_solver;
//config->resetNeuronSimulation();
iterationCount = 0;
config->numOfBoundaryP = 0;
config->numOfElasticP = 0;
config->numOfLiquidP = 0;
config->numOfMembranes = 0;
init_config();
}
/** Run one simulation step
*
* Run simulation step in pipeline manner.
* It starts with neighbor search algorithm than
* physic simulation algorithms: PCI SPH [1],
* elastic matter simulation, boundary handling [2],
* membranes handling and finally numerical integration.
* [1] http://www.ifi.uzh.ch/vmml/publications/pcisph/pcisph.pdf
* [2] http://en.cppreference.com/w/cpp/language/function_templateM. Ihmsen, N. Akinci, M. Gissler, M. Teschner,
* Boundary Handling and Adaptive Time-stepping for PCISPH
* Proc. VRIPHYS, Copenhagen, Denmark, pp. 79-88, Nov 11-12, 2010
*
* @param looad_to
* If it's true than Sibernetic works "load simulation data in file" mode.
*/
double owPhysicsFluidSimulator::simulationStep(const bool load_to) {
int iter = 0; // PCISPH prediction-correction iterations counter
//
// now we will implement sensory system of the c. elegans worm, mechanosensory
// one
// here we plan to implement the part of openworm sensory system, which is
// still
// one of the grand challenges of this project
// if(iterationCount==0) return 0.0;//uncomment this line to stop movement of
// the scene
helper->refreshTime();
std::cout << "\n[[ Step " << iterationCount << " ]]\n";
// SEARCH FOR NEIGHBOURS PART
// ocl_solver->_runClearBuffers();
// helper->watch_report("_runClearBuffers: \t%9.3f ms\n");
ocl_solver->_runHashParticles(config);
helper->watch_report("_runHashParticles: \t%9.3f ms\n");
ocl_solver->_runSort(config);
helper->watch_report("_runSort: \t\t%9.3f ms\n");
ocl_solver->_runSortPostPass(config);
helper->watch_report("_runSortPostPass: \t%9.3f ms\n");
ocl_solver->_runIndexx(config);
helper->watch_report("_runIndexx: \t\t%9.3f ms\n");
ocl_solver->_runIndexPostPass(config);
helper->watch_report("_runIndexPostPass: \t%9.3f ms\n");
ocl_solver->_runFindNeighbors(config);
helper->watch_report("_runFindNeighbors: \t%9.3f ms\n");
// PCISPH PART
if (config->getIntegrationMethod() == LEAPFROG) { // in this case we should
// remmember value of
// position on stem i - 1
// Calc next time (t+dt) positions x(t+dt)
ocl_solver->_run_pcisph_integrate(iterationCount, 0 /*=positions_mode*/,
config);
}
ocl_solver->_run_pcisph_computeDensity(config);
ocl_solver->_run_pcisph_computeForcesAndInitPressure(config);
ocl_solver->_run_pcisph_computeElasticForces(config);
do {
// printf("\n^^^^ iter %d ^^^^\n",iter);
ocl_solver->_run_pcisph_predictPositions(config);
ocl_solver->_run_pcisph_predictDensity(config);
ocl_solver->_run_pcisph_correctPressure(config);
ocl_solver->_run_pcisph_computePressureForceAcceleration(config);
iter++;
} while (iter < maxIteration);
// and finally calculate v(t+dt)
if (config->getIntegrationMethod() == LEAPFROG) {
ocl_solver->_run_pcisph_integrate(iterationCount, 1 /*=velocities_mode*/,
config);
helper->watch_report("_runPCISPH: \t\t%9.3f ms\t3 iteration(s)\n");
} else {
ocl_solver->_run_pcisph_integrate(iterationCount, 2, config);
helper->watch_report("_runPCISPH: \t\t%9.3f ms\t3 iteration(s)\n");
}
// Handling of Interaction with membranes
if (config->numOfMembranes > 0) {
ocl_solver->_run_clearMembraneBuffers(config);
ocl_solver->_run_computeInteractionWithMembranes(config);
// compute change of coordinates due to interactions with membranes
ocl_solver->_run_computeInteractionWithMembranes_finalize(config);
helper->watch_report("membraneHadling: \t%9.3f ms\n");
}
// END
ocl_solver->read_position_buffer(position_cpp, config);
helper->watch_report("_readBuffer: \t\t%9.3f ms\n");
// END PCISPH algorithm
printf("------------------------------------\n");
printf("_Total_step_time:\t%9.3f ms\n", helper->getElapsedTime());
printf("------------------------------------\n");
if (load_to) {
if (iterationCount == 0) {
owHelper::loadConfigurationToFile(position_cpp, config,
elasticConnectionsData_cpp,
membraneData_cpp, true);
} else {
if (iterationCount % config->getLogStep() == 0) {
owHelper::loadConfigurationToFile(position_cpp, config, NULL, NULL,
false);
}
}
}
// if (owVtkExport::isActive) {
// if (iterationCount % config->getLogStep() == 0) {
// getvelocity_cpp();
// owVtkExport::exportState(iterationCount, config, position_cpp,
// elasticConnectionsData_cpp, velocity_cpp,
// membraneData_cpp, muscle_activation_signal_cpp);
// }
// }
/* Not clear what this part of the code does */
float correction_coeff;
for (unsigned int i = 0; i < config->MUSCLE_COUNT; ++i) {
correction_coeff = sqrt(
1.f - ((1 + i % 24 - 12.5f) / 12.5f) * ((1 + i % 24 - 12.5f) / 12.5f));
// printf("\n%d\t%d\t%f\n",i,1+i%24,correction_coeff);
muscle_activation_signal_cpp[i] *= correction_coeff;
}
/* ****************************************** */
//config->updateNeuronSimulation(muscle_activation_signal_cpp);
//
iterationCount++;
return helper->getElapsedTime();
}
/** Prepare data and log it to special configuration
* file you can run your simulation from place you snapshoted it
*
* @param fileName - name of file where saved configuration will be stored
*/
void owPhysicsFluidSimulator::makeSnapshot() {
getvelocity_cpp();
std::string fileName = config->getSnapshotFileName();
owHelper::loadConfigurationToFile(
position_cpp, velocity_cpp, elasticConnectionsData_cpp, membraneData_cpp,
particleMembranesList_cpp, fileName.c_str(), config);
}
// Destructor
owPhysicsFluidSimulator::~owPhysicsFluidSimulator(void) {
destroy();
delete helper;
delete ocl_solver;
}
void owPhysicsFluidSimulator::destroy() {
delete[] position_cpp;
delete[] velocity_cpp;
delete[] density_cpp;
delete[] particleIndex_cpp;
if (elasticConnectionsData_cpp != NULL)
delete[] elasticConnectionsData_cpp;
delete[] muscle_activation_signal_cpp;
if (membraneData_cpp != NULL) {
delete[] membraneData_cpp;
delete[] particleMembranesList_cpp;
}
}
| 37.726688 | 113 | 0.677491 | ranr01 |
a619763bda3f8ac8dd0bc1c935305855eafc0d91 | 3,527 | hpp | C++ | src/lib/driver/Driver.hpp | psrebniak/css-preprocessor | 7b54fe3d47c22039239e0690eab39f5ebf027b83 | [
"MIT"
] | null | null | null | src/lib/driver/Driver.hpp | psrebniak/css-preprocessor | 7b54fe3d47c22039239e0690eab39f5ebf027b83 | [
"MIT"
] | null | null | null | src/lib/driver/Driver.hpp | psrebniak/css-preprocessor | 7b54fe3d47c22039239e0690eab39f5ebf027b83 | [
"MIT"
] | null | null | null | #ifndef __DRIVER_HPP__
#define __DRIVER_HPP__
#include <string>
#include <cstddef>
#include <istream>
#include <iostream>
#include <utility>
#include <map>
#include <queue>
#include "lib/types.hpp"
#include "lib/lexer/Lexer.hpp"
#include "lib/logger/Logger.hpp"
#include "lib/ast/node/Node.hpp"
#include "lib/generator/Generator.hpp"
#include "generated/parser.hpp"
namespace CSSP {
class Driver {
friend class Parser;
public:
/**
* Create new Driver
* @param os info/warning output stream
*/
Driver(std::ostream &os) :
log(os, Logger::colorCyan),
error(std::cerr, Logger::colorRed) {}
~Driver();
/**
* parse - parse from a file
* @param filename - valid string with input file
*/
int parse(const char *const filename);
/**
* parse - parse from a c++ input stream
* @param is - std::istream&, valid input stream
*/
int parse(std::istream &iss);
/**
* Create new generator with current fileToFreeMap
* @param minify should be output minified
* @return new Generator instance
*/
CSSP::Generator *getGenerator(bool minify = false);
/**
* Get access to fileToTreeMap
* @return fileToTreeMap
*/
const FileToTreeMapType *getFileToTreeMap() const;
protected:
/**
* helper method, parse given stream
* @param stream
* @return
*/
int parseHelper(std::istream &stream);
/**
* return true if file is already parsed
* @param filename
* @return
*/
bool isFileInTree(std::string filename);
/**
* main file directory name or current working directory in stream parse case
*/
std::string directory;
/**
* main file realpath
*/
std::string mainFileName;
/**
* current processed filename
*/
std::string currentFileName;
/**
* file to process queue
*/
std::queue<std::string> fileQueue;
/**
* realpath to tree map
*/
FileToTreeMapType fileToTreeMap;
/**
* warning logger
*/
Logger log;
/**
* error logger
*/
Logger error;
/**
* Parser instance
*/
CSSP::Parser *parser = nullptr;
/**
* Lexer instance
*/
CSSP::Lexer *lexer = nullptr;
/**
* get realpath of given file (as cwd is used directory parameter)
* @param path
* @return
*/
std::string getRealPath(std::string path);
/**
* run queue and proceed used files
* @return
*/
int processQueue();
/**
* run queue and use DebugString method instead of generate
* @return
*/
int debugQueue();
/**
* Parse partial with given filename
* @return
*/
int parsePartial(std::string);
/**
* Push new file to queue
* @param filename
*/
void pushFileToQueue(std::string filename);
/**
* Set tree for currently parsed element (used by lexer)
* @param nodes
*/
void setNodesAsCurrentTreeElement(NodeListType *nodes);
};
}
#endif
| 22.322785 | 85 | 0.516019 | psrebniak |
a619981023bae18c2816d723dde2a121c4af02a8 | 3,246 | cpp | C++ | Codeforces/Codeforces Round #492 (Div. 2)/C. Tesla.cpp | edwinsun98/Competitive-Programming-Solutions | 67d79a2193e6912a644d27b9a399ba02a60766b7 | [
"MIT"
] | null | null | null | Codeforces/Codeforces Round #492 (Div. 2)/C. Tesla.cpp | edwinsun98/Competitive-Programming-Solutions | 67d79a2193e6912a644d27b9a399ba02a60766b7 | [
"MIT"
] | null | null | null | Codeforces/Codeforces Round #492 (Div. 2)/C. Tesla.cpp | edwinsun98/Competitive-Programming-Solutions | 67d79a2193e6912a644d27b9a399ba02a60766b7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define f first
#define s second
#define all(vec) begin(vec), end(vec)
#define pf push_front
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define mk make_pair
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ll,int> pli;
void solve(){
int n, k;
cin >> n >> k;
vector<vector<int>> a(5, vector<int>(n+1));
for(int i = 1; i <= 4; i++){
for(int j = 1; j <= n; j++){
cin >> a[i][j];
}
}
if(k == 2*n){
bool ok = 0;
for(int j = 1; j <= n; j++){
if(a[1][j] == a[2][j])ok = 1;
}
for(int j = 1; j <= n; j++){
if(a[4][j] == a[3][j])ok = 1;
}
if(!ok){
cout << -1 << '\n';
return;
}
}
vector<int> ansi, ansr, ansc;
int cnt = 0;
while(1){
for(int j = 1; j <= n; j++){
if(a[2][j] == 0)continue;
if(a[1][j] == a[2][j]){
ansi.pb(a[2][j]);
ansr.pb(1);
ansc.pb(j);
a[2][j] = 0;
cnt++;
}
}
for(int j = 1; j <= n; j++){
if(a[3][j] == 0)continue;
if(a[4][j] == a[3][j]){
ansi.pb(a[3][j]);
ansr.pb(4);
ansc.pb(j);
a[3][j] = 0;
cnt++;
}
}
if(cnt == k)break;
vector<vector<bool>> vis(5, vector<bool>(n+1));
for(int j = 1; j <= n; j++){
if(a[2][j] == 0 || vis[2][j])continue;
if(j < n){
if(a[2][j+1] == 0){
ansi.pb(a[2][j]);
ansr.pb(2);
ansc.pb(j+1);
swap(a[2][j], a[2][j+1]);
vis[2][j+1] = 1;
}
}else{
if(a[3][j] == 0){
ansi.pb(a[2][j]);
ansr.pb(3);
ansc.pb(j);
swap(a[2][j], a[3][j]);
vis[3][j] = 1;
}
}
}
for(int j = n; j >= 1; j--){
if(a[3][j] == 0 || vis[3][j])continue;
if(j > 1){
if(a[3][j-1] == 0){
ansi.pb(a[3][j]);
ansr.pb(3);
ansc.pb(j-1);
swap(a[3][j], a[3][j-1]);
vis[3][j-1] = 1;
}
}else{
if(a[2][j] == 0){
ansi.pb(a[3][j]);
ansr.pb(2);
ansc.pb(j);
swap(a[3][j], a[2][j]);
vis[2][j] = 1;
}
}
}
}
cout << ansi.size() << '\n';
for(int i = 0; i < ansi.size(); i++){
cout << ansi[i] << " " << ansr[i] << " " << ansc[i] << '\n';
}
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
int tc = 1;
// cin >> tc;
while(tc--){
solve();
}
}
| 26.826446 | 68 | 0.331793 | edwinsun98 |
a61b6a138ac8e68efeb4a51c09296590cac9cc0d | 2,323 | hpp | C++ | ngraph/core/include/openvino/core/preprocess/input_network_info.hpp | tpwrules/openvino | 6addc0d535e9ab0b591dcefa2f771997a477ba4f | [
"Apache-2.0"
] | 1 | 2020-11-19T15:53:18.000Z | 2020-11-19T15:53:18.000Z | ngraph/core/include/openvino/core/preprocess/input_network_info.hpp | tpwrules/openvino | 6addc0d535e9ab0b591dcefa2f771997a477ba4f | [
"Apache-2.0"
] | 44 | 2020-12-09T12:38:22.000Z | 2022-03-28T13:18:29.000Z | ngraph/core/include/openvino/core/preprocess/input_network_info.hpp | evkotov/openvino | edb98aeb8eedc5ee2d1cc4bc03a0c5eae3fa85c8 | [
"Apache-2.0"
] | 4 | 2021-09-29T20:44:49.000Z | 2021-10-20T13:02:12.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "openvino/core/core_visibility.hpp"
#include "openvino/core/layout.hpp"
#include "openvino/core/type/element_type.hpp"
namespace ov {
namespace preprocess {
/// \brief Information about network's input tensor. If all information is already included to loaded network, this info
/// may not be needed. However it can be set to specify additional information about network, like 'layout'.
///
/// Example of usage of network 'layout':
/// Support network has input parameter with shape {1, 3, 224, 224} and user needs to resize input image to network's
/// dimensions It can be done like this
///
/// \code{.cpp}
/// <network has input parameter with shape {1, 3, 224, 224}>
/// auto proc =
/// PrePostProcessor(function)
/// .input(InputInfo()
/// .tensor(<input tensor info>)
/// .preprocess(PreProcessSteps().resize(ResizeAlgorithm::RESIZE_LINEAR))
/// .network(InputNetworkInfo()
/// .set_layout("NCHW"))
/// );
/// \endcode
class OPENVINO_API InputNetworkInfo final {
class InputNetworkInfoImpl;
std::unique_ptr<InputNetworkInfoImpl> m_impl;
friend class InputInfo;
public:
/// \brief Default empty constructor
InputNetworkInfo();
/// \brief Default move constructor
InputNetworkInfo(InputNetworkInfo&&) noexcept;
/// \brief Default move assignment
InputNetworkInfo& operator=(InputNetworkInfo&&) noexcept;
/// \brief Default destructor
~InputNetworkInfo();
/// \brief Set layout for network's input tensor
/// This version allows chaining for Lvalue objects
///
/// \param layout Layout for network's input tensor.
///
/// \return Reference to 'this' to allow chaining with other calls in a builder-like manner
InputNetworkInfo& set_layout(const ov::Layout& layout) &;
/// \brief Set layout for network's input tensor
/// This version allows chaining for Rvalue objects
///
/// \param layout Layout for network's input tensor.
///
/// \return Rvalue reference to 'this' to allow chaining with other calls in a builder-like manner
InputNetworkInfo&& set_layout(const ov::Layout& layout) &&;
};
} // namespace preprocess
} // namespace ov
| 33.666667 | 120 | 0.687904 | tpwrules |
a61dc97200203ca53ebbdc1b2128cf2b22fcedb3 | 1,596 | cpp | C++ | test/test_ultrasonic_sensor.cpp | nr-parikh/acme_robotics_perception_module | c681454b8b77c5e0aa7f990cc1fd6345f717920f | [
"MIT"
] | null | null | null | test/test_ultrasonic_sensor.cpp | nr-parikh/acme_robotics_perception_module | c681454b8b77c5e0aa7f990cc1fd6345f717920f | [
"MIT"
] | null | null | null | test/test_ultrasonic_sensor.cpp | nr-parikh/acme_robotics_perception_module | c681454b8b77c5e0aa7f990cc1fd6345f717920f | [
"MIT"
] | 2 | 2017-10-16T03:16:35.000Z | 2020-12-12T20:18:20.000Z | /**
* @file test_ultrasonic_sensor.cpp
* @author nrparikh
* @copyright MIT license
*
* @brief DESCRIPTION
* Testing file for the UltrasonicSensor.
*/
#include <gtest/gtest.h>
#include <stdlib.h>
#include <ctime>
#include <iostream>
#include "ultrasonic_sensor.hpp"
/**
* @brief Class to test the working of Ultrasonic sensor. Create an
* instance of ultrasonic sensor which can be used for testing
*/
class TestUltrasonicSensor : public ::testing::Test {
protected:
UltrasonicSensor sensor; // Create an instance of Ultrasonic sensor
};
/**
* @brief Dummy test to check the working of tests
*/
TEST_F(TestUltrasonicSensor, dummyTest) {
EXPECT_EQ(1, 1); // Dummy test to check the working of tests
}
/**
* @brief Test to check the working of ultrasonic sensor
*/
TEST_F(TestUltrasonicSensor, isAlive) {
// Test to check whether ultrasonic sensor is working or not
EXPECT_EQ(sensor.isAlive(), true);
}
/**
* @brief Test to check the method of setting maximum distance
*/
TEST_F(TestUltrasonicSensor, setMaxDistance) {
sensor.setMaxDistance(10.03); // Set the max distance using the method
// Test to check if setter and getter methods work correctly
EXPECT_NEAR(sensor.getMaxDistance(), 10.03, 0.0001);
}
/**
* @brief Test to check the reading of ultrasonic sensor
*/
TEST_F(TestUltrasonicSensor, sensorReading) {
sensor.setSeed(0); // Set the seed to a constant value
sensor.process(); // Take the reading of the sensor
// Test the closeness of the two readings
EXPECT_NEAR(sensor.getOutput(), 5.000471475, 0.00001);
}
| 29.555556 | 73 | 0.714912 | nr-parikh |
a61f93b8b0f87f7c287a1b62cb396dfac256b0ec | 269 | cpp | C++ | problems/problem152/main.cpp | PoH314/Algorithms-and-Data-Structures | b295379d6b6515921702e2dc358b02680df3960a | [
"MIT"
] | 1 | 2022-03-01T15:47:08.000Z | 2022-03-01T15:47:08.000Z | problems/problem152/main.cpp | PoH314/Algorithms-and-Data-Structures | b295379d6b6515921702e2dc358b02680df3960a | [
"MIT"
] | 1 | 2022-03-21T20:01:08.000Z | 2022-03-21T20:01:08.000Z | problems/problem152/main.cpp | PoH314/Algorithms-and-Data-Structures | b295379d6b6515921702e2dc358b02680df3960a | [
"MIT"
] | 1 | 2022-03-21T17:53:34.000Z | 2022-03-21T17:53:34.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c;
int v[3];
cin >> a >> b >> c;
v[0] = b*2 + c*4;
v[1] = a*2 + c*2;
v[2] = b*2 + a*4;
sort(v, v + 3);
cout << v[0] << endl;
return 0;
}
| 12.809524 | 25 | 0.36803 | PoH314 |
a62635804f19de3c2e0d50b6b8cbf0d128cb5a75 | 1,595 | cpp | C++ | third_party/wds/src/libwds/rtsp/clientrtpports.cpp | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/wds/src/libwds/rtsp/clientrtpports.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/wds/src/libwds/rtsp/clientrtpports.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* This file is part of Wireless Display Software for Linux OS
*
* Copyright (C) 2014 Intel Corporation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "libwds/rtsp/clientrtpports.h"
namespace wds {
namespace rtsp {
namespace {
const char profile[] = "RTP/AVP/UDP;unicast";
const char mode[] = "mode=play";
}
ClientRtpPorts::ClientRtpPorts(unsigned short rtp_port_0,
unsigned short rtp_port_1)
: Property(ClientRTPPortsPropertyType),
rtp_port_0_(rtp_port_0),
rtp_port_1_(rtp_port_1) {
}
ClientRtpPorts::~ClientRtpPorts() {
}
std::string ClientRtpPorts::ToString() const {
return PropertyName::wfd_client_rtp_ports + std::string(SEMICOLON)
+ std::string(SPACE) + profile
+ std::string(SPACE) + std::to_string(rtp_port_0_)
+ std::string(SPACE) + std::to_string(rtp_port_1_)
+ std::string(SPACE) + mode;
}
} // namespace rtsp
} // namespace wds
| 30.09434 | 70 | 0.729781 | zipated |
98a98143a7087d89cf0af185e135c112ea5b1610 | 1,503 | cpp | C++ | demo/cpp/cppver.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 57 | 2015-02-16T06:43:24.000Z | 2022-03-16T06:21:36.000Z | demo/cpp/cppver.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 4 | 2016-03-08T09:51:09.000Z | 2021-03-29T10:18:55.000Z | demo/cpp/cppver.cpp | berak/opencv_smallfry | fd8f64980dff0527523791984d6cb3dfcd2bc9bc | [
"BSD-3-Clause"
] | 27 | 2015-03-28T19:55:34.000Z | 2022-01-09T15:03:15.000Z | #include <iostream>
using namespace std;
#include <windows.h>
#if (defined(_M_ARM) || defined(_M_X64) || defined(WINRT)) && _WIN32_WINNT >= 0x501
const char *s="arm";
#else
const char *s="bein";
#endif
int getNumberOfCPUs(void)
{
#if defined WIN32 || defined _WIN32
SYSTEM_INFO sysinfo;
#if (defined(_M_ARM) || defined(_M_X64) || defined(WINRT)) && _WIN32_WINNT >= 0x501
GetNativeSystemInfo( &sysinfo );
#else
GetSystemInfo( &sysinfo );
#endif
return (int)sysinfo.dwNumberOfProcessors;
#elif defined ANDROID
static int ncpus = getNumberOfCPUsImpl();
return ncpus;
#elif defined __linux__
return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
int numCPU=0;
int mib[4];
size_t len = sizeof(numCPU);
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
/* get the number of CPUs from the system */
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if( numCPU < 1 )
{
mib[1] = HW_NCPU;
sysctl( mib, 2, &numCPU, &len, NULL, 0 );
if( numCPU < 1 )
numCPU = 1;
}
return (int)numCPU;
#else
return 1;
#endif
}
int main(int argc, char* argv[]) {
cerr << __cplusplus << endl;
cerr << s << endl;
cerr << getNumberOfCPUs() << endl;
#if defined(WIN32)
cerr << "WIN32" << endl;
#else
cerr << "no WIN32" << endl;
#endif
#if defined(_WIN32)
cerr << "_WIN32" << endl;
#else
cerr << "no _WIN32" << endl;
#endif
return 0;
}
| 20.310811 | 83 | 0.617432 | berak |
98acb8216244257b95c2cc18842cdb5a27ee5ccb | 510 | cpp | C++ | Basic/Check Leap Year/SolutionByGourav.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 261 | 2019-09-30T19:47:29.000Z | 2022-03-29T18:20:07.000Z | Basic/Check Leap Year/SolutionByGourav.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 647 | 2019-10-01T16:51:29.000Z | 2021-12-16T20:39:44.000Z | Basic/Check Leap Year/SolutionByGourav.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 383 | 2019-09-30T19:32:07.000Z | 2022-03-24T16:18:26.000Z | // Program to check if entered year is a leap year.
// Author: Gourav Khunger(https://github.com/GouravKhunger)
#include <iostream>
using namespace std;
bool isLeap(int year)
{
if (year % 400 == 0)
return true;
else if (year % 100 == 0)
return false;
else if (year % 4 == 0)
return true;
return false;
}
main()
{
ios::sync_with_stdio(false);
int year;
cin >> year;
if (isLeap(year)) {
cout << "Yes";
} else {
cout << "No";
}
}
| 17.586207 | 59 | 0.55098 | Mdanish777 |
98adf7ff814aa83fac119ab52e0d90c05920eb7d | 1,071 | cpp | C++ | CodeForces/Solutions/1029D.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 5 | 2020-10-03T17:15:26.000Z | 2022-03-29T21:39:22.000Z | CodeForces/Solutions/1029D.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | null | null | null | CodeForces/Solutions/1029D.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 1 | 2021-03-01T12:56:50.000Z | 2021-03-01T12:56:50.000Z | #include <bits/stdc++.h>
using namespace std;
#define ll long long
map <ll, ll> cnt[12];
ll ara[200009], ln[200009];
int main()
{
ll n, k;
cin >> n >> k;
for(ll i = 1; i <= n; i++) {
scanf("%lld", &ara[i]);
ll tmp = ara[i];
ll len = 0;
while(tmp != 0) {
tmp /= 10;
len++;
}
ll rem = ara[i] % k;
ln[i] = len;
cnt[len][rem]++;
}
ll ans = 0;
for(ll i = 1; i <= n; i++) {
ll need = ara[i] % k;
for(ll j = 1; j <= 10; j++) {
need = (need * 10) % k;
if(need > 0) {
ans += cnt[j][k - need];
if( (k - need) == ara[i] % k && j == ln[i])
ans--;
}
else {
ans += cnt[j][0];
if(0 == ara[i] % k && j == ln[i])
ans--;
}
//cout << j << " " << need << " " << cnt[j][need] << endl;
}
//cout << ans << endl;
}
cout << ans << endl;
return 0;
} | 18.789474 | 72 | 0.316527 | Shefin-CSE16 |
98ae9b01ba3e47e3f7efdb0c534d05cdfaf7b976 | 3,832 | hpp | C++ | libstm/algs/RedoRAWUtils.hpp | nmadduri/rstm | 5f4697f987625379d99bca1f32b33ee8e821c8a5 | [
"BSD-3-Clause"
] | 8 | 2016-12-05T19:39:55.000Z | 2021-07-22T07:00:40.000Z | libstm/algs/RedoRAWUtils.hpp | hlitz/rstm_zsim_tm | 1c66824b124f84c8812ca25f4a9aa225f9f1fa34 | [
"BSD-3-Clause"
] | null | null | null | libstm/algs/RedoRAWUtils.hpp | hlitz/rstm_zsim_tm | 1c66824b124f84c8812ca25f4a9aa225f9f1fa34 | [
"BSD-3-Clause"
] | 2 | 2018-06-02T07:46:33.000Z | 2020-06-26T02:12:34.000Z | /**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
#ifndef STM_REDO_RAW_CHECK_HPP
#define STM_REDO_RAW_CHECK_HPP
#include <stm/config.h>
/**
* Redo-log TMs all need to perform a read-after-write check in their read_rw
* barriers in order to find any previous transactional writes. This is
* complicated when we're byte logging, because we may have written only part
* of a word, and be attempting to read a superset of the word bytes.
*
* This file provides three config-dependent macros to assist in dealing with
* the case where we need to merge a read an write to get the "correct" value.
*/
#if defined(STM_WS_WORDLOG)
/**
* When we're word logging the RAW check is trivial. If we found the value it
* was returned as log.val, so we can simply return it.
*/
#define REDO_RAW_CHECK(found, log, mask) \
if (__builtin_expect(found, false)) \
return log.val;
/**
* When we're word logging the RAW check is trivial. If we found the value
* it was returned as log.val, so we can simply return it. ProfileApp
* version logs the event.
*/
#define REDO_RAW_CHECK_PROFILEAPP(found, log, mask) \
if (__builtin_expect(found, false)) { \
++profiles[0].read_rw_raw; \
return log.val; \
}
/**
* No RAW cleanup is required when word logging, we can just return the
* unadulterated value from the log. ProfileApp version logs the event.
*/
#define REDO_RAW_CLEANUP(val, found, log, mask)
#elif defined(STM_WS_BYTELOG)
/**
* When we are byte logging and the writeset says that it found the address
* we're looking for, it could mean one of two things. We found the requested
* address, and the requested mask is a subset of the logged mask, or we found
* some of the bytes that were requested. The log.mask tells us which of the
* returned bytes in log.val are valid.
*
* We perform a subset test (i.e., mask \in log.mask) and just return log.val
* if it's successful. If mask isn't a subset of log.mask we'll deal with it
* during REDO_RAW_CLEANUP.
*/
#define REDO_RAW_CHECK(found, log, pmask) \
if (__builtin_expect(found, false)) \
if ((pmask & log.mask) == pmask) \
return log.val;
/**
* ProfileApp version logs the event.
*
* NB: Byte logging exposes new possible statistics, should we record them?
*/
#define REDO_RAW_CHECK_PROFILEAPP(found, log, pmask) \
if (__builtin_expect(found, false)) { \
if ((pmask & log.mask) == pmask) { \
++profiles[0].read_rw_raw; \
return log.val; \
} \
}
/**
* When we're byte logging we may have had a partial RAW hit, i.e., the
* write log had some of the bytes that we needed, but not all.
*
* Check for a partial hit. If we had one, we need to mask out the recently
* read bytes that correspond to the valid bytes from the log, and then merge
* in the logged bytes.
*/
#define REDO_RAW_CLEANUP(value, found, log, mask) \
if (__builtin_expect(found, false)) { \
/* can't do masking on a void* */ \
uintptr_t v = reinterpret_cast<uintptr_t>(value); \
v &= ~log.mask; \
v |= reinterpret_cast<uintptr_t>(log.val) & log.mask; \
value = reinterpret_cast<void*>(v); \
}
#else
#error "Preprocessor configuration error: STM_WS_(WORD|BYTE)LOG not defined."
#endif
#endif // STM_REDO_RAW_CHECK_HPP
| 36.495238 | 79 | 0.634656 | nmadduri |
98af66ad112c887b8ceae40f93ebf51354227d01 | 1,045 | cpp | C++ | src/widget-wifi-signal.cpp | 9ae8sdf76/odbii-pilot | 8ea5ba7c7001d5b9c293ab4d3a375d44bfd2d145 | [
"MIT"
] | null | null | null | src/widget-wifi-signal.cpp | 9ae8sdf76/odbii-pilot | 8ea5ba7c7001d5b9c293ab4d3a375d44bfd2d145 | [
"MIT"
] | 1 | 2021-05-11T16:04:44.000Z | 2021-05-11T16:04:44.000Z | src/widget-wifi-signal.cpp | 9ae8sdf76/odbii-pilot | 8ea5ba7c7001d5b9c293ab4d3a375d44bfd2d145 | [
"MIT"
] | 2 | 2021-01-31T13:04:05.000Z | 2022-01-12T12:01:17.000Z | #include "widget-wifi-signal.h"
using namespace dbuddy;
extern "C" void cb_time_change_task_handler(lv_task_t *);
void WifiSignal::init() {
Widget * time_container = get_ui()->get_widget(WIDGET_TIME_CONTAINER);
Widget * time_label = get_ui()->get_widget(WIDGET_TIME_LABEL);
set_self(lv_label_create(time_container->get_self(), time_label->get_self()));
set_pos(time_label->get_width() + DEFAULT_PADDING, DEFAULT_PADDING / 2);
lv_label_set_text(get_self(), LV_SYMBOL_WIFI);
add_style(LV_LABEL_PART_MAIN, get_ui()->get_styles()->get_text_color_gray(LV_STATE_DEFAULT));
// Keep the symbol to the right of the time label
get_ui()->create_task(cb_time_change_task_handler, 500);
}
void cb_time_change_task_handler(lv_task_t * task) {
auto * ui = (Ui *)task->user_data;
Widget * wifi_signal = ui->get_widget(WIDGET_WIFI_SIGNAL);
Widget * time_label = ui->get_widget(WIDGET_TIME_LABEL);
lv_obj_set_pos(wifi_signal->get_self(), time_label->get_width() + DEFAULT_PADDING, DEFAULT_PADDING / 2);
}
| 34.833333 | 108 | 0.742584 | 9ae8sdf76 |
98af7427c8ca690220e45fe77f99a0609f05e9d9 | 6,610 | cpp | C++ | gvsoc/gvsoc_gap/models/pulp/udma/uart/v2/udma_uart.cpp | mfkiwl/gap_sdk | 642b798dfdc7b85ccabe6baba295033f0eadfcd4 | [
"Apache-2.0"
] | null | null | null | gvsoc/gvsoc_gap/models/pulp/udma/uart/v2/udma_uart.cpp | mfkiwl/gap_sdk | 642b798dfdc7b85ccabe6baba295033f0eadfcd4 | [
"Apache-2.0"
] | null | null | null | gvsoc/gvsoc_gap/models/pulp/udma/uart/v2/udma_uart.cpp | mfkiwl/gap_sdk | 642b798dfdc7b85ccabe6baba295033f0eadfcd4 | [
"Apache-2.0"
] | 1 | 2021-11-11T02:12:25.000Z | 2021-11-11T02:12:25.000Z | /*
* Copyright (C) 2021 GreenWaves Technologies, SAS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "../udma_impl.hpp"
#include "archi/utils.h"
#include "vp/itf/uart.hpp"
#include "udma_uart.hpp"
using namespace std::placeholders;
Uart_periph::Uart_periph(udma *top, int id, int itf_id)
: Udma_periph(top, id),
rx_fsm(top, this),
tx_fsm(top, this),
tx_bit(1),
rx_rts(1)
{
std::string itf_name = "uart" + std::to_string(itf_id);
/* create trace utility */
top->traces.new_trace(itf_name, &trace, vp::DEBUG);
/* create udma channels */
this->rx_channel = new Uart_rx_channel(top, this, itf_name + "_rx");
this->tx_channel = new Uart_tx_channel(top, this, itf_name + "_tx");
/* register UART external port */
top->new_master_port(this, itf_name, &(this->uart_itf));
/* setup pad synchronization method */
this->uart_itf.set_sync_full_meth(&Uart_periph::rx_sync);
/* build the register map */
this->regmap.build(top, &this->trace, itf_name);
/* setup register callbacks */
this->regmap.rx_dest.register_callback(std::bind(&Uart_periph::rx_dest_req, this, _1, _2, _3, _4));
this->regmap.tx_dest.register_callback(std::bind(&Uart_periph::tx_dest_req, this, _1, _2, _3, _4));
this->regmap.status.register_callback(std::bind(&Uart_periph::status_req, this, _1, _2, _3, _4));
this->regmap.error.register_callback(std::bind(&Uart_periph::error_req, this, _1, _2, _3, _4));
this->regmap.misc.register_callback(std::bind(&Uart_periph::misc_req, this, _1, _2, _3, _4));
/* get soc event numbers */
{
this->error_soc_event = -1;
js::config *config = this->top->get_js_config()->get("uart/err_events");
if (config)
{
this->error_soc_event = config->get_elem(itf_id)->get_int();
}
}
{
this->rx_soc_event = -1;
js::config *config = this->top->get_js_config()->get("uart/rx_events");
if (config)
{
this->rx_soc_event = config->get_elem(itf_id)->get_int();
}
}
{
this->tx_soc_event = -1;
js::config *config = this->top->get_js_config()->get("uart/tx_events");
if (config)
{
this->tx_soc_event = config->get_elem(itf_id)->get_int();
}
}
}
void Uart_periph::rx_dest_req(uint64_t reg_offset, int size, uint8_t *value, bool is_write)
{
this->regmap.rx_dest.update(reg_offset, size, value, is_write);
if (is_write)
{
this->trace.msg(vp::trace::LEVEL_INFO, "Setting RX channel (id: %d)\n", this->regmap.rx_dest.rx_dest_get());
this->top->channel_register(this->regmap.rx_dest.rx_dest_get(), this->rx_channel);
}
}
void Uart_periph::tx_dest_req(uint64_t reg_offset, int size, uint8_t *value, bool is_write)
{
this->regmap.tx_dest.update(reg_offset, size, value, is_write);
if (is_write)
{
this->trace.msg(vp::trace::LEVEL_INFO, "Setting TX channel (id: %d)\n", this->regmap.tx_dest.tx_dest_get());
this->top->channel_register(this->regmap.tx_dest.tx_dest_get(), this->tx_channel);
/* kickstart transfer */
// TODO add guards
this->trace.msg(vp::trace::LEVEL_TRACE, "getting 1 byte of data\n");
this->tx_channel->get_data(1);
}
}
void Uart_periph::status_req(uint64_t reg_offset, int size, uint8_t *value, bool is_write)
{
this->regmap.status.update(reg_offset, size, value, is_write);
//TODO do what ?
}
void Uart_periph::error_req(uint64_t reg_offset, int size, uint8_t *value, bool is_write)
{
/* any read (or write, but register is not write-able) clears the register */
this->regmap.error.set(0);
}
void Uart_periph::misc_req(uint64_t reg_offset, int size, uint8_t *value, bool is_write)
{
this->regmap.misc.update(reg_offset, size, value, is_write);
if (this->regmap.misc.tx_fifo_clear_event_o_get() != 0)
{
this->tx_fsm.clear_fifo();
this->regmap.misc.tx_fifo_clear_event_o_set(0);
}
if (this->regmap.misc.tx_fsm_reset_event_o_get() != 0)
{
this->tx_fsm.clear_fsm();
this->regmap.misc.tx_fsm_reset_event_o_set(0);
}
if (this->regmap.misc.rx_fifo_clear_event_o_get() != 0)
{
this->rx_fsm.clear_fifo();
this->regmap.misc.rx_fifo_clear_event_o_set(0);
}
if (this->regmap.misc.rx_fsm_reset_event_o_get() != 0)
{
this->rx_fsm.clear_fsm();
this->regmap.misc.rx_fsm_reset_event_o_set(0);
}
}
void Uart_periph::reset(bool active)
{
Udma_periph::reset(active);
this->tx_fsm.reset(active);
this->rx_fsm.reset(active);
}
vp::io_req_status_e Uart_periph::custom_req(vp::io_req *req, uint64_t offset)
{
if (this->regmap.access(offset, req->get_size(), req->get_data(), req->get_is_write()))
{
return vp::IO_REQ_INVALID;
}
return vp::IO_REQ_OK;
}
void Uart_periph::send_bit(int bit)
{
this->tx_bit = bit;
this->sync_pins();
}
void Uart_periph::send_rts(int rts)
{
this->rx_rts = rts;
this->sync_pins();
}
void Uart_periph::sync_pins(void)
{
if (this->uart_itf.is_bound())
{
this->uart_itf.sync_full(this->tx_bit, 2, this->rx_rts);
}
}
void Uart_periph::rx_sync(void *__this, int data, int sck, int cts)
{
Uart_periph *_this = (Uart_periph *)__this;
_this->trace.msg(vp::trace::LEVEL_TRACE, "rx_sync (%d, %d, %d)\n", data, sck, cts);
_this->rx_fsm.handle_rx_bits(data, sck);
_this->tx_fsm.update_cts(cts);
}
Uart_tx_channel::Uart_tx_channel(udma *top, Uart_periph *periph, string name)
: Udma_tx_channel(top, name), periph(periph)
{
}
void Uart_tx_channel::push_data(uint8_t* data, int size)
{
this->periph->tx_fsm.push_bytes(data, size);
}
Uart_rx_channel::Uart_rx_channel(udma *top, Uart_periph *periph, string name)
: Udma_rx_channel(top, name), periph(periph)
{
}
void Uart_rx_channel::wait_active_done(void)
{
this->periph->rx_fsm.notify_active();
}
| 29.247788 | 116 | 0.661725 | mfkiwl |
98b18d6b66815637b76fe5242075360f32657839 | 2,365 | cpp | C++ | DistributedTrees/ForestManager.cpp | palvaradomoya/forests | eec6a5e003a2849367fdeef18b7b5340b6d0e480 | [
"BSD-3-Clause"
] | null | null | null | DistributedTrees/ForestManager.cpp | palvaradomoya/forests | eec6a5e003a2849367fdeef18b7b5340b6d0e480 | [
"BSD-3-Clause"
] | null | null | null | DistributedTrees/ForestManager.cpp | palvaradomoya/forests | eec6a5e003a2849367fdeef18b7b5340b6d0e480 | [
"BSD-3-Clause"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: TreeManager.cpp
* Author: gabo
*
* Created on May 17, 2018, 4:24 PM
*/
#include "ForestManager.h"
rdf::ForestManager::ForestManager() {
_status=false;
}
rdf::ForestManager::ForestManager(const ForestManager& orig) {
}
rdf::ForestManager::~ForestManager() {
}
void rdf::ForestManager::initializeForest() {
for(int i = 0; i < TREE_AMOUNT; i++){
rdf::Task newTask;
newTask.setRank(0);
newTask.setTree(i);
newTask.setNode(1);
newTask.setStatus(false);
_matrixSteps.push_back(newTask);
rdf::NodeResult node;
_resultMap.insert(std::make_pair(newTask,node));
}
}
void rdf::ForestManager::showQueue() {
for(int i=0; i<_matrixSteps.size(); i++){
rdf::Task temp = _matrixSteps[i];
temp.showTask();
}
}
rdf::Task & rdf::ForestManager::getNextTask() {
std::cout << "Queue Size: " << _matrixSteps.size()<< "\n";
rdf::Task &test = _matrixSteps[0];
//_matrixSteps.erase(_matrixSteps.begin());
return test;
}
bool rdf::ForestManager::addResuld(NodeResult& pResult) {
std::cout<<"REDUCE: " << pResult.getResultSize() << "\n";
_resultMap.find(pResult.getTask())->second.reduce(pResult);
//_result.reduce(pResult);
//_result.showTask();
Task leftChild;
Task rightChild;
leftChild.setRank(pResult.getTask().getRank());
leftChild.setTree(pResult.getTask().getTree());
leftChild.setNode(2 * pResult.getTask().getNode());
leftChild.setStatus(pResult.getTask().isStatus());
rightChild.setRank(pResult.getTask().getRank());
rightChild.setTree(pResult.getTask().getTree());
rightChild.setNode(2 * pResult.getTask().getNode()-1);
rightChild.setStatus(pResult.getTask().isStatus());
_matrixSteps.push_back(leftChild);
_matrixSteps.push_back(rightChild);
std::cout<< "Adding child nodes, size: "<<_matrixSteps.size()<<"\n";
NodeResult result;
_resultMap.insert(std::make_pair(leftChild,result));
_resultMap.insert(std::make_pair(leftChild,result));
//leftChild.showTask();
//rightChild.showTask();
return true;
}
| 25.430108 | 79 | 0.645666 | palvaradomoya |
98b4dc002fe27045decc8563ec701ed5f9504dbc | 6,921 | cxx | C++ | tomviz/ModuleThreshold.cxx | utkarshayachit/tomviz | 02efc26a14965602cced2343fe6d058c4a0ff903 | [
"BSD-3-Clause"
] | null | null | null | tomviz/ModuleThreshold.cxx | utkarshayachit/tomviz | 02efc26a14965602cced2343fe6d058c4a0ff903 | [
"BSD-3-Clause"
] | null | null | null | tomviz/ModuleThreshold.cxx | utkarshayachit/tomviz | 02efc26a14965602cced2343fe6d058c4a0ff903 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "ModuleThreshold.h"
#include "DataSource.h"
#include "pqProxiesWidget.h"
#include "Utilities.h"
#include "vtkNew.h"
#include "vtkSmartPointer.h"
#include "vtkSMParaViewPipelineControllerWithRendering.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMPVRepresentationProxy.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMViewProxy.h"
namespace tomviz
{
ModuleThreshold::ModuleThreshold(QObject* parentObject)
: Superclass(parentObject)
{
}
ModuleThreshold::~ModuleThreshold()
{
this->finalize();
}
QIcon ModuleThreshold::icon() const
{
return QIcon(":/pqWidgets/Icons/pqThreshold24.png");
}
bool ModuleThreshold::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
if (!this->Superclass::initialize(data, vtkView))
{
return false;
}
vtkSMSourceProxy* producer = data->producer();
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
vtkSMSessionProxyManager* pxm = producer->GetSessionProxyManager();
// Create the contour filter.
vtkSmartPointer<vtkSMProxy> proxy;
proxy.TakeReference(pxm->NewProxy("filters", "Threshold"));
this->ThresholdFilter = vtkSMSourceProxy::SafeDownCast(proxy);
Q_ASSERT(this->ThresholdFilter);
controller->PreInitializeProxy(this->ThresholdFilter);
vtkSMPropertyHelper(this->ThresholdFilter, "Input").Set(producer);
controller->PostInitializeProxy(this->ThresholdFilter);
controller->RegisterPipelineProxy(this->ThresholdFilter);
// Update min/max to avoid thresholding the full dataset.
vtkSMPropertyHelper rangeProperty(this->ThresholdFilter, "ThresholdBetween");
double range[2], newRange[2];
rangeProperty.Get(range, 2);
double delta = (range[1] - range[0]);
double mid = ((range[0] + range[1]) / 2.0);
newRange[0] = mid - 0.1 * delta;
newRange[1] = mid + 0.1 * delta;
rangeProperty.Set(newRange, 2);
this->ThresholdFilter->UpdateVTKObjects();
// Create the representation for it.
this->ThresholdRepresentation = controller->Show(this->ThresholdFilter, 0,
vtkView);
Q_ASSERT(this->ThresholdRepresentation);
vtkSMRepresentationProxy::SetRepresentationType(this->ThresholdRepresentation,
"Surface");
vtkSMPropertyHelper(this->ThresholdRepresentation, "Position").Set(data->displayPosition(), 3);
this->updateColorMap();
this->ThresholdRepresentation->UpdateVTKObjects();
return true;
}
void ModuleThreshold::updateColorMap()
{
Q_ASSERT(this->ThresholdRepresentation);
// by default, use the data source's color/opacity maps.
vtkSMPropertyHelper(this->ThresholdRepresentation,
"LookupTable").Set(this->colorMap());
vtkSMPropertyHelper(this->ThresholdRepresentation,
"ScalarOpacityFunction").Set(this->opacityMap());
this->ThresholdRepresentation->UpdateVTKObjects();
}
bool ModuleThreshold::finalize()
{
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
controller->UnRegisterProxy(this->ThresholdRepresentation);
controller->UnRegisterProxy(this->ThresholdFilter);
this->ThresholdFilter = nullptr;
this->ThresholdRepresentation = nullptr;
return true;
}
bool ModuleThreshold::setVisibility(bool val)
{
Q_ASSERT(this->ThresholdRepresentation);
vtkSMPropertyHelper(this->ThresholdRepresentation,
"Visibility").Set(val? 1 : 0);
this->ThresholdRepresentation->UpdateVTKObjects();
return true;
}
bool ModuleThreshold::visibility() const
{
Q_ASSERT(this->ThresholdRepresentation);
return vtkSMPropertyHelper(this->ThresholdRepresentation,
"Visibility").GetAsInt() != 0;
}
void ModuleThreshold::addToPanel(pqProxiesWidget* panel)
{
Q_ASSERT(this->ThresholdFilter);
Q_ASSERT(this->ThresholdRepresentation);
QStringList fprops;
fprops << "SelectInputScalars" << "ThresholdBetween";
panel->addProxy(this->ThresholdFilter, "Threshold", fprops, true);
QStringList representationProperties;
representationProperties
<< "Representation"
<< "Opacity"
<< "Specular";
panel->addProxy(this->ThresholdRepresentation, "Appearance", representationProperties, true);
this->Superclass::addToPanel(panel);
}
bool ModuleThreshold::serialize(pugi::xml_node& ns) const
{
QStringList fprops;
fprops << "SelectInputScalars" << "ThresholdBetween";
pugi::xml_node tnode = ns.append_child("Threshold");
QStringList representationProperties;
representationProperties
<< "Representation"
<< "Opacity"
<< "Specular"
<< "Visibility";
pugi::xml_node rnode = ns.append_child("ThresholdRepresentation");
return tomviz::serialize(this->ThresholdFilter, tnode, fprops) &&
tomviz::serialize(this->ThresholdRepresentation, rnode, representationProperties) &&
this->Superclass::serialize(ns);
}
bool ModuleThreshold::deserialize(const pugi::xml_node& ns)
{
return tomviz::deserialize(this->ThresholdFilter, ns.child("Threshold")) &&
tomviz::deserialize(this->ThresholdRepresentation,
ns.child("ThresholdRepresentation")) &&
this->Superclass::deserialize(ns);
}
void ModuleThreshold::dataSourceMoved(double newX, double newY, double newZ)
{
double pos[3] = {newX, newY, newZ};
vtkSMPropertyHelper(this->ThresholdRepresentation, "Position").Set(pos, 3);
this->ThresholdRepresentation->UpdateVTKObjects();
}
//-----------------------------------------------------------------------------
bool ModuleThreshold::isProxyPartOfModule(vtkSMProxy *proxy)
{
return (proxy == this->ThresholdFilter.Get()) ||
(proxy == this->ThresholdRepresentation.Get());
}
std::string ModuleThreshold::getStringForProxy(vtkSMProxy *proxy)
{
if (proxy == this->ThresholdFilter.Get())
{
return "Threshold";
}
else if (proxy == this->ThresholdRepresentation.Get())
{
return "Representation";
}
else
{
qWarning("Unknown proxy passed to module threshold in save animation");
return "";
}
}
vtkSMProxy *ModuleThreshold::getProxyForString(const std::string& str)
{
if (str == "Threshold")
{
return this->ThresholdFilter.Get();
}
else if (str == "Representation")
{
return this->ThresholdRepresentation.Get();
}
else
{
return nullptr;
}
}
}
| 30.355263 | 97 | 0.699754 | utkarshayachit |
98b624f55ebfdb877a0c5786e34067036f1a48de | 2,714 | cpp | C++ | src/game/systems/KeyboardInputSystem.cpp | MrBattary/darkest-castle | f5980f3f9167533197f711b79a852103a88a4569 | [
"MIT"
] | 2 | 2020-11-19T19:50:22.000Z | 2020-11-19T19:51:01.000Z | src/game/systems/KeyboardInputSystem.cpp | MrBattary/darkest-castle | f5980f3f9167533197f711b79a852103a88a4569 | [
"MIT"
] | null | null | null | src/game/systems/KeyboardInputSystem.cpp | MrBattary/darkest-castle | f5980f3f9167533197f711b79a852103a88a4569 | [
"MIT"
] | null | null | null | //
// Created by Battary on 26.05.2020.
//
#include "game/systems/KeyboardInputSystem.h"
KeyboardInputSystem::KeyboardInputSystem() {
setID(0);
setKeys(TK_ESCAPE, TK_UP, TK_DOWN, TK_LEFT, TK_RIGHT, TK_ENTER, TK_SPACE, TK_H, TK_I);
setKeysNames();
}
void KeyboardInputSystem::setKeys(int back = 0, int up = 0, int down = 0, int left = 0, int right = 0, int forward = 0,
int stay = 0, int help = 0, int inventory = 0) {
keys_.insert(std::make_pair(up, std::make_shared<PlayerMoveUpKey>()));
keys_.insert(std::make_pair(down, std::make_shared<PlayerMoveDownKey>()));
keys_.insert(std::make_pair(left, std::make_shared<PlayerMoveLeftKey>()));
keys_.insert(std::make_pair(right, std::make_shared<PlayerMoveRightKey>()));
keys_.insert(std::make_pair(back, std::make_shared<ExitKey>()));
keys_.insert(std::make_pair(stay, std::make_shared<StayKey>()));
keys_.insert(std::make_pair(forward, std::make_shared<ContinueKey>()));
keys_.insert(std::make_pair(help, std::make_shared<HelpKey>()));
keys_.insert(std::make_pair(inventory, std::make_shared<InventoryKey>()));
}
void KeyboardInputSystem::setKeysNames() {
keysNames_.insert(std::make_pair(TK_ESCAPE, "Esc"));
keysNames_.insert(std::make_pair(TK_UP, "Up"));
keysNames_.insert(std::make_pair(TK_DOWN, "Down"));
keysNames_.insert(std::make_pair(TK_LEFT, "Left"));
keysNames_.insert(std::make_pair(TK_RIGHT, "Right"));
keysNames_.insert(std::make_pair(TK_ENTER, "Enter"));
keysNames_.insert(std::make_pair(TK_SPACE, "Space"));
keysNames_.insert(std::make_pair(TK_H, "H"));
keysNames_.insert(std::make_pair(TK_I, "I"));
}
std::vector<std::shared_ptr<IKey>> KeyboardInputSystem::findKeysRealisation(const int key) {
std::vector<std::shared_ptr<IKey>> keysRealisation;
auto pos = keys_.find(key);
if (pos == keys_.end()) {
keysRealisation.push_back(nothing_);
} else {
for (auto it = keys_.begin(); it != keys_.end(); ++it) {
if (it->first == key) {
keysRealisation.push_back(it->second);
}
}
}
return keysRealisation;
}
void KeyboardInputSystem::updateSystem(ecs::World& world) {
if (!inputBuffer_) inputBuffer_ = terminal_read();
std::vector<std::shared_ptr<IKey>> realisation = findKeysRealisation(inputBuffer_);
for (auto current : realisation) {
current->execute(world);
}
inputBuffer_ = 0;
}
std::string KeyboardInputSystem::getKeyName(std::string name) {
for (auto it = keys_.begin(); it != keys_.end(); ++it) {
if (!it->second->name_.compare(name)) {
auto keyName = keysNames_.find(it->first);
return keyName->second;
}
}
return "";
}
void KeyboardInputSystem::skipInput() {
inputBuffer_ = -1;
}
| 36.186667 | 119 | 0.686072 | MrBattary |
98b69334f8d37209679dae8aa2d2a95d43a38499 | 377 | cpp | C++ | acmicpc.net/source/11869.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 7 | 2019-06-26T07:03:32.000Z | 2020-11-21T16:12:51.000Z | acmicpc.net/source/11869.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | null | null | null | acmicpc.net/source/11869.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 9 | 2019-02-28T03:34:54.000Z | 2020-12-18T03:02:40.000Z | // 11869. 님블
// 2021.05.11
// 게임 이론, 스프라그–그런디 정리
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int ans = 0;
int k;
for (int i = 0; i < n; i++)
{
cin >> k;
ans ^= k;
}
if (ans > 0)
{
cout << "koosaga" << endl;
}
else
{
cout << "cubelover" << endl;
}
return 0;
}
| 12.16129 | 36 | 0.408488 | tdm1223 |
98b895494a7782ca9424df19781bdb1caf0ce80d | 6,884 | cpp | C++ | rest/src/database/tests/TestDatabase.cpp | cisocrgroup/pocoweb | 93546d026321744602f6ee90fd82503da56da3b7 | [
"Apache-2.0"
] | 10 | 2018-04-09T20:46:49.000Z | 2021-08-07T17:29:02.000Z | rest/src/database/tests/TestDatabase.cpp | cisocrgroup/pocoweb | 93546d026321744602f6ee90fd82503da56da3b7 | [
"Apache-2.0"
] | 61 | 2018-01-03T09:49:16.000Z | 2022-02-18T12:26:11.000Z | rest/src/database/tests/TestDatabase.cpp | cisocrgroup/pocoweb | 93546d026321744602f6ee90fd82503da56da3b7 | [
"Apache-2.0"
] | 3 | 2020-01-10T15:44:18.000Z | 2021-05-19T13:39:53.000Z | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestDatabase
#include "core/Book.hpp"
#include "core/Line.hpp"
#include "core/Page.hpp"
#include "database/Database.hpp"
#include "database/Tables.h"
#include "utils/MockDb.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <sqlpp11/sqlpp11.h>
using namespace sqlpp;
using namespace pcw;
struct UsersFixture {
int user;
MockDb db;
UsersFixture() : user(42), db() {}
};
////////////////////////////////////////////////////////////////////////////////
BOOST_FIXTURE_TEST_SUITE(Users, UsersFixture)
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(SelectProjectEntry) {
db.expect("SELECT "
"projects.id,projects.origin,projects.owner,projects.pages "
"FROM projects WHERE (projects.id=42)");
// db.expect("SELECT projects.origin,projects.owner FROM projects "
// "WHERE (projects.projectid=42)");
auto projects = select_project_entry(db, 42);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(UpdateProjectOwner) {
db.expect("UPDATE projects SET owner=42 WHERE (projects.id=13)");
update_project_owner(db, 13, 42);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(SelectBook) {
db.expect(
"SELECT books.bookid,books.year,books.title,books.author,"
"books.description,books.uri,books.profilerurl,books.histpatterns,books."
"directory,books.lang,books.profiled,books.extendedlexicon,books."
"postcorrected,books.pooled "
"FROM books "
"INNER JOIN projects ON (books.bookid=projects.origin) "
"WHERE (books.bookid=13)");
select_book(db, user, 13);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_SUITE_END()
struct BooksFixture : public UsersFixture {
BookSptr book;
PageSptr page;
LineSptr line;
BooksFixture() {
LineBuilder lbuilder;
lbuilder.set_box({2, 3, 4, 5});
lbuilder.set_image_path("image");
lbuilder.append("text", 4, 1.0);
line = lbuilder.build();
PageBuilder pbuilder;
pbuilder.set_image_path("image");
pbuilder.set_ocr_path("ocr");
pbuilder.set_box({1, 2, 3, 4});
pbuilder.append(*line);
page = pbuilder.build();
BookBuilder bbuilder;
bbuilder.set_author("author");
bbuilder.set_title("title");
bbuilder.set_directory("directory");
bbuilder.set_year(2017);
bbuilder.set_uri("uri");
bbuilder.set_language("language");
bbuilder.set_description("description");
bbuilder.set_owner(user);
bbuilder.append(*page);
book = bbuilder.build();
}
};
////////////////////////////////////////////////////////////////////////////////
BOOST_FIXTURE_TEST_SUITE(Books, BooksFixture)
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(InsertProject) {
db.expect("INSERT INTO projects (origin,pages,owner) VALUES(0,1,42)");
db.expect("INSERT INTO project_pages "
"(projectid,pageid,nextpageid,prevpageid) VALUES(0,1,1,1)");
auto view = insert_project(db, *book);
BOOST_CHECK_EQUAL(view, book);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(InsertBook) {
db.expect("INSERT INTO projects (origin,owner,pages) VALUES(0,42,1)");
db.expect("UPDATE projects SET origin=0 WHERE (projects.id=0)");
db.expect("INSERT INTO books (author,title,directory,year,uri,bookid,"
"description,profilerurl,pooled,histpatterns,lang) "
"VALUES('author','title','directory',2017,"
"'uri',0,'description','',0,'','language')");
db.expect("INSERT INTO project_pages "
"(projectid,pageid,nextpageid,prevpageid) VALUES(0,1,1,1)");
db.expect("INSERT INTO pages (bookid,pageid,imagepath,ocrpath,filetype,pleft,"
"ptop,pright,pbottom) VALUES(0,1,'image','ocr',0,1,2,3,4)");
db.expect("INSERT INTO textlines (bookid,pageid,lineid,imagepath,lleft,"
"ltop,lright,lbottom) VALUES(0,1,1,'image',2,3,4,5)");
// t
db.expect(
"INSERT INTO contents (bookid,pageid,lineid,seq,cid,ocr,cor,cut,conf) "
"VALUES(0,1,1,0,0,116,0,2,1)");
// e
db.expect(
"INSERT INTO contents (bookid,pageid,lineid,seq,cid,ocr,cor,cut,conf) "
"VALUES(0,1,1,1,1,101,0,2,1)");
// x
db.expect(
"INSERT INTO contents (bookid,pageid,lineid,seq,cid,ocr,cor,cut,conf) "
"VALUES(0,1,1,2,2,120,0,2,1)");
// t
db.expect(
"INSERT INTO contents (bookid,pageid,lineid,seq,cid,ocr,cor,cut,conf) "
"VALUES(0,1,1,3,3,116,0,2,1)");
auto view = insert_book(db, *book);
BOOST_CHECK_EQUAL(view, book);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(UpdateBook) {
book->data.author = "new-author";
book->data.title = "new-title";
book->data.dir = "new-directory";
book->data.year = 1917;
book->data.uri = "new-uri";
book->data.description = "new-description";
book->data.lang = "new-language";
book->data.histPatterns = "a:b,c:d";
book->data.pooled = true;
db.expect(
"UPDATE books SET author='new-author',title='new-title',"
"directory='new-directory',year=1917,uri='new-uri',"
"description='new-description',profilerurl='',histpatterns='a:b,c:d',"
"pooled=1,profiled=0,extendedlexicon=0,postcorrected=0,lang='new-"
"language' "
"WHERE (books.bookid=0)");
update_book(db, book->origin().id(), book->data);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(SelectProject) {
db.expect("SELECT project_pages.pageid FROM project_pages "
"WHERE (project_pages.projectid=42)");
select_project(db, *book, 42);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(SelectProjectIds) {
db.expect("SELECT "
"projects.id,projects.origin,projects.owner,projects.pages,"
"books.bookid,books.year,books.title,books.author,books."
"description,books.uri,books.profilerurl,books.histpatterns,"
"books.directory,books.lang,books.profiled,books.extendedlexicon,"
"books.postcorrected,books.pooled "
"FROM books INNER "
"JOIN projects ON (books.bookid=projects.origin) WHERE "
"(projects.owner=42)");
// db.expect("SELECT projects.id FROM projects "
// "WHERE ((projects.owner=42) OR (projects.owner=0))");
select_all_projects(db, user);
db.validate();
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_SUITE_END()
| 36.041885 | 80 | 0.579895 | cisocrgroup |
98be8a2b186d1c350434bba3bbef42aee864e222 | 4,770 | cpp | C++ | applicationsSrc/simpleCatoms3D/simpleCatom3DBlockCode.cpp | claytronics/visiblesim | 2762a88a23e50516d0f166dd9629f1ac7290fded | [
"Apache-2.0"
] | 4 | 2016-08-18T03:19:49.000Z | 2020-09-20T03:29:26.000Z | applicationsSrc/simpleCatoms3D/simpleCatom3DBlockCode.cpp | claytronics/visiblesim | 2762a88a23e50516d0f166dd9629f1ac7290fded | [
"Apache-2.0"
] | 2 | 2016-08-18T03:25:07.000Z | 2016-08-29T17:51:50.000Z | applicationsSrc/simpleCatoms3D/simpleCatom3DBlockCode.cpp | claytronics/visiblesim | 2762a88a23e50516d0f166dd9629f1ac7290fded | [
"Apache-2.0"
] | 3 | 2015-05-14T07:29:55.000Z | 2021-07-18T23:45:36.000Z | /*
* catom2D1BlockCode.cpp
*
* Created on: 12 avril 2013
* Author: ben
*/
#include <iostream>
#include <sstream>
#include "catoms3DWorld.h"
#include "simpleCatom3DBlockCode.h"
#include "scheduler.h"
#include "events.h"
#include <memory>
#define verbose 1
using namespace std;
using namespace Catoms3D;
SimpleCatom3DBlockCode::SimpleCatom3DBlockCode(Catoms3DBlock *host):Catoms3DBlockCode(host) {
cout << "SimpleCatom3DBlockCode constructor" << endl;
scheduler = getScheduler();
catom = (Catoms3DBlock*)hostBlock;
}
SimpleCatom3DBlockCode::~SimpleCatom3DBlockCode() {
cout << "SimpleCatom3DBlockCode destructor" << endl;
}
void SimpleCatom3DBlockCode::startup() {
stringstream info;
info << "Starting ";
/*int n=0;
for (int i=0; i<12; i++) {
if (catom->getInterface(i)->connectedInterface!=NULL) {
n++;
}
}
switch (n) {
case 0 : catom->setColor(DARKGREY); break;
case 1 : catom->setColor(RED); break;
case 2 : catom->setColor(ORANGE); break;
case 3 : catom->setColor(PINK); break;
case 4 : catom->setColor(YELLOW); break;
case 5 : catom->setColor(GREEN); break;
case 6 : catom->setColor(LIGHTGREEN); break;
case 7 : catom->setColor(LIGHTBLUE); break;
case 8 : catom->setColor(BLUE); break;
case 9 : catom->setColor(MAGENTA); break;
case 10 : catom->setColor(GOLD); break;
case 11 : catom->setColor(DARKORANGE); break;
case 12 : catom->setColor(WHITE); break;
}*/
/* skeleton test */
Catoms3DWorld*wrl = Catoms3DWorld::getWorld();
Vector3D pos(catom->ptrGlBlock->position[0],catom->ptrGlBlock->position[1],catom->ptrGlBlock->position[2]);
potentiel = wrl->getSkeletonPotentiel(pos);
catom->setColor(potentiel>1.0?YELLOW:DARKORANGE);
info << potentiel;
scheduler->trace(info.str(),hostBlock->blockId);
if (catom->blockId==1) {
Vector3D position=wrl->lattice->gridToWorldPosition(Cell3DPosition(2,1,0));
int id=1000000;
int i=0;
Catoms3DBlock *voisin=NULL;
P2PNetworkInterface *p2p;
while (i<12) {
p2p = catom->getInterface(i);
if(p2p->connectedInterface && p2p->connectedInterface->hostBlock->blockId<id) {
voisin = (Catoms3DBlock*)p2p->connectedInterface->hostBlock;
id = voisin->blockId;
}
i++;
}
Matrix m_1;
voisin->getGlBlock()->mat.inverse(m_1);
// recherche le voisin d'indice minimum
//Rotations3D rotations(catom,voisin,m_1*Vector3D(0,1,0),35.2643896828,m_1*Vector3D(-1,1, -M_SQRT2),35.2643896828);
Rotations3D rotations(catom,voisin,m_1*Vector3D(0,0,1),45.0,m_1*Vector3D(-1,1,0),45.0);
Time t = scheduler->now()+2000;
scheduler->schedule(new Rotation3DStartEvent(t,catom,rotations));
#ifdef verbose
stringstream info;
info.str("");
info << "Rotation3DStartEvent(" << t << ") around #" << voisin->blockId;
scheduler->trace(info.str(),catom->blockId,LIGHTGREY);
#endif
}
}
void SimpleCatom3DBlockCode::processLocalEvent(EventPtr pev) {
MessagePtr message;
stringstream info;
switch (pev->eventType) {
case EVENT_ROTATION3D_END: {
#ifdef verbose
info.str("");
info << "rec.: EVENT_MOTION_END";
scheduler->trace(info.str(),hostBlock->blockId);
#endif
Catoms3DBlock *voisin=NULL;
P2PNetworkInterface *p2p;
int i=0,id=10000;
while (i<12) {
p2p = catom->getInterface(i);
if(p2p->connectedInterface && p2p->connectedInterface->hostBlock->blockId<id) {
voisin = (Catoms3DBlock*)p2p->connectedInterface->hostBlock;
id = voisin->blockId;
}
i++;
}
Matrix m_1;
voisin->getGlBlock()->mat.inverse(m_1);
// Rotations3D rotations(catom,voisin,m_1*Vector3D(-1,1,M_SQRT2),35.26,m_1*Vector3D(-1,-1, -M_SQRT2),35.26);
Rotations3D rotations(catom,voisin,m_1*Vector3D(-1,-1,0),45.0,m_1*Vector3D(0,0,1),45.0);
Time t = scheduler->now()+1002000;
// scheduler->schedule(new Rotation3DStartEvent(t,catom,rotations));
}
break;
case EVENT_NI_RECEIVE: {
message = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message;
P2PNetworkInterface * recv_interface = message->destinationInterface;
}
break;
}
}
// bool SimpleCatom3DBlockCode::getAttribute(const string &att,ostringstream &sout) {
// if (att=="potentiel") {
// sout << potentiel << endl;
// return true;
// }
// return Catoms3DBlockCode::getAttribute(att,sout);
// }
| 32.896552 | 123 | 0.621593 | claytronics |
98bf4134e6cd2192628fcc10118ac305f981d354 | 3,085 | cpp | C++ | local.1.genesis/app.loaderTest/c_getopt.cpp | manxinator/aok | b8d7908dec4c04508f6eabf252684b105c14608b | [
"MIT"
] | null | null | null | local.1.genesis/app.loaderTest/c_getopt.cpp | manxinator/aok | b8d7908dec4c04508f6eabf252684b105c14608b | [
"MIT"
] | null | null | null | local.1.genesis/app.loaderTest/c_getopt.cpp | manxinator/aok | b8d7908dec4c04508f6eabf252684b105c14608b | [
"MIT"
] | null | null | null | /*------------------------------------------------------------------------------
Copyright (c) 2015 manxinator
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--------------------------------------------------------------------------------
c_getopt.cpp
------------------------------------------------------------------------------*/
#include "c_getopt.h"
#include <unistd.h>
#include <libgen.h>
//------------------------------------------------------------------------------
char g_progName[SML_STR_SIZE] = "GetOptions";
char g_fileName[SML_STR_SIZE] = "NOT_DEFINED";
int optv = 0;
int opth = 0;
//------------------------------------------------------------------------------
extern int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
//------------------------------------------------------------------------------
void printUsage(int exitVal)
{
printf("Usage: %s <options>\n",g_progName);
printf(" -f <s> Input Filename (%s)\n",g_fileName);
printf("--------------------------------------------------\n");
printf(" -v increase verbosity: 0x%x\n",optv);
printf(" -h print help and exit\n");
exit(exitVal);
}
void parseArgs (int argc, char *argv[])
{
strcpy(g_progName,basename(argv[0]));
int c = 0;
opterr = 0;
while ((c = getopt(argc,argv,"f:vh")) != -1)
switch (c)
{
case 'f':
strcpy(g_fileName,optarg);
break;
case 'v':
optv = (optv<<1) | 1;
break;
case '?':
switch (optopt)
{
case 'f':
break;
default:
if (isprint(optopt))
fprintf(stderr,"ERROR: Unknown option `-%c'.\n",optopt);
else
fprintf(stderr,"ERROR: Unknown option character `\\x%x'.\n",optopt);
break;
}
printf("\n\n");
printUsage(-1);
break;
default:
printUsage(-1);
}
for (int index = optind; index < argc; index++)
printf("Extra Argument: %s\n",argv[index]);
if (opth)
printUsage(EXIT_SUCCESS);
}
| 31.161616 | 80 | 0.544246 | manxinator |
98c05af6895832daab7d7259165ff6ad855e7bec | 1,196 | cxx | C++ | all-tests/test-dblbuff.cxx | Hungerarray/winbgim | 4a0bc7da71cacba61bcf6dcb7d3e2ad1ef8ebb82 | [
"MIT"
] | null | null | null | all-tests/test-dblbuff.cxx | Hungerarray/winbgim | 4a0bc7da71cacba61bcf6dcb7d3e2ad1ef8ebb82 | [
"MIT"
] | null | null | null | all-tests/test-dblbuff.cxx | Hungerarray/winbgim | 4a0bc7da71cacba61bcf6dcb7d3e2ad1ef8ebb82 | [
"MIT"
] | null | null | null | // FILE: dblbuff.cpp
// Demostrates double-buffering with the winbgim library.
// Michael Main -- Nov 25, 1998
#include <stdio.h> // Provides sprintf function
#include "winbgim.h" // Provides Windows BGI functions
int main( )
{
const int COLUMNS = 8;
const int ROWS = 16;
int x, y; // x and y pixel locations
int row, column; // Row and column number
int box_width; // Width of a color box in pixels
int box_height; // Height of a color box in pixels
int color; // Color number, now ranging from 0 to 127
// Initialize the graphics window and set the box size.
initwindow(400,300);
box_width = getmaxx( ) / COLUMNS;
box_height = getmaxy( ) / ROWS;
// Draw some items on pages 1 and 0:
setactivepage(1);
line(0, 0, getmaxx( ), getmaxy( ));
outtextxy(100, 100, "This is page #1.");
outtextxy(100, 120, "Press a key to end the program.");
setactivepage(0);
line(getmaxx( ), 0, 0, getmaxy( ));
outtextxy(100, 100, "This is page #0.");
outtextxy(100, 120, "Press a key to see page #1.");
// Get the user to press a key to move to page 1:
getch( );
setvisualpage(1);
getch( );
}
| 28.47619 | 63 | 0.620401 | Hungerarray |
98c2aa70232b5d4dd162b5e94617f00768c9c321 | 286 | cpp | C++ | api/games/OnlineMultiplayer.cpp | Paragoumba/Sships | 08dd8bb6e6d5cc6763771f22f2e3d04abaefc739 | [
"MIT"
] | null | null | null | api/games/OnlineMultiplayer.cpp | Paragoumba/Sships | 08dd8bb6e6d5cc6763771f22f2e3d04abaefc739 | [
"MIT"
] | null | null | null | api/games/OnlineMultiplayer.cpp | Paragoumba/Sships | 08dd8bb6e6d5cc6763771f22f2e3d04abaefc739 | [
"MIT"
] | null | null | null | //
// Created by paragoumba on 16/10/2019.
//
#include "OnlineMultiplayer.hpp"
OnlineMultiplayer::OnlineMultiplayer() = default;
Game* OnlineMultiplayer::newInstance(){
delete(instance);
return instance = new OnlineMultiplayer();
}
void OnlineMultiplayer::update(){
}
| 13 | 49 | 0.713287 | Paragoumba |
98c2f3d6736670bb307f7d0dda5a6ad941ba850f | 10,524 | cpp | C++ | FamilyTree.cpp | TomerDvir123/ancestor-tree-b | 013b89ae3c47408f177abf6fa94de53a01a8013e | [
"MIT"
] | null | null | null | FamilyTree.cpp | TomerDvir123/ancestor-tree-b | 013b89ae3c47408f177abf6fa94de53a01a8013e | [
"MIT"
] | null | null | null | FamilyTree.cpp | TomerDvir123/ancestor-tree-b | 013b89ae3c47408f177abf6fa94de53a01a8013e | [
"MIT"
] | null | null | null | //#include "FamilyTree.hpp"
//#include <iostream>
//#include <string>
//
//
//
//using namespace std;
//using namespace family;
#include "FamilyTree.hpp"
#include <string>
#include <stdexcept>
#include <iostream>
#include <cstring>
using namespace std;
using namespace family;
Tree::Tree(string name) {
this->MyName = name;
this->Father = NULL;
this->Mother = NULL;
this->depth = 0;
this->key = 0;
this->rel = "";
this->found=false;
}
// Tree::~Tree()
// {
// if()
// delete this->Father;
// delete this->Mother;
// // cout << "ETEDE";
// }
Tree *Tree::curr(Tree *where, string who) {
if (where == NULL)
{
return NULL;
}
if (who.compare(where->MyName) == 0)
{
return where;
}
else
{
Tree *f = curr(where->Father, who);
if (f != NULL)
{
return f;
}
Tree *m = curr(where->Mother, who);
if (m != NULL)
{
return m;
}
}
return NULL;
}
Tree &Tree::addFather(string name, string father) {
Tree *temp = this;
Tree *temp2 = curr(this, name);
if(temp2 == NULL)
{
throw std::invalid_argument(name + " doesnt exist\n");
}
this->key = 0;
if (temp2->MyName.compare(name) == 0) {
if (temp2->Father == NULL) {
temp2->Father = new Tree(father);
temp2->Father->MyName = father;
string temp3 = curr2(this, name, "");
this->key = 0;
int i = 0;
while (temp->MyName != name) {
if (temp3[i] == 'f') {
temp = temp->Father;
i++;
}
if (temp3[i] == 'm') {
temp = temp->Mother;
i++;
}
}
temp2->Father->depth = i + 1;
int r = i + 1;
if (r == 0) {
cout << name + " it's me";
} else if (r == 1) {
temp2->Father->rel = "father";
} else if (r == 2) {
temp2->Father->rel = "grandfather";
} else if (r > 2) {
string times = "";
int k = 2;
while (k < r) {
times = times + "great-";
k++;
}
temp2->Father->rel = times + "grandfather";
}
temp->Father = temp2->Father;
}
else {
// cout << name + " has father\n";
throw std::invalid_argument(name + " has a father\n");
}
}
else {
cout << name + " doesnt exist\n";
throw std::invalid_argument(name + " doesnt exist\n");
}
return *this;
}
Tree &Tree::addMother(string name, string mother) {
Tree *temp = this;
Tree *temp4 = curr(temp, name);
if(temp4 == NULL)
{
throw std::invalid_argument(name + " doesnt exist\n");
}
this->key = 0;
if (temp4->MyName == name) {
if (temp4->Mother == NULL) {
temp4->Mother = new Tree(mother);
temp4->Mother->MyName = mother;
string temp3 = curr2(temp, name, "");
this->key = 0;
int i = 0;
while (temp->MyName != name) {
if (temp3[i] == 'f') {
temp = temp->Father;
i++;
}
if (temp3[i] == 'm') {
temp = temp->Mother;
i++;
}
}
temp4->Mother->depth = i + 1;
int r = i + 1;
if (r == 0) {
cout << name + " it's me";
} else if (r == 1) {
temp4->Mother->rel = "mother";
} else if (r == 2) {
temp4->Mother->rel = "grandmother";
} else if (r > 2) {
string times = "";
int k = 2;
while (k < r) {
times = times + "great-";
k++;
}
temp4->Mother->rel = times + "grandmother";
}
temp->Mother = temp4->Mother;
}
else {
throw std::invalid_argument(name + " has a mother\n");
}
}
else {
throw std::invalid_argument(name + " doesnt exist\n");
}
return *this;
}
string Tree::relation(string name) {
// this->key=0;
// cout << name +" is ";
if(this->MyName.compare(name)==0)
{
return "me";
}
Tree *temp = this;
Tree *temp2 = curr(temp, name);
if(temp2 == NULL)
{
// throw std::invalid_argument(name + " doesnt exist\n");
return "unrelated";
}
this->key = 0;
this->found = false;
return temp2->rel;
//cout << temp2.MyName << " is: " << temp2.depth << "\n";
// string temp3 = curr2(temp, name, "");
// this->key = 0;
// this->found = false;
//cout << temp3;
// int i = 2;
// int r = 0;
// r = temp2->depth;
// if (r == 0) {
// cout << name + " it's me\n";
// return name;
// } else if (r == 1) {
// if (temp3[0] == 'm') {
// cout << name + " it's the mother of " + temp->MyName+"\n";
// return "mother";
// } else {
// cout << name + " it's the father of " + temp->MyName+"\n";
// return "father";
// }
// } else if (r == 2) {
// if (temp3[1] == 'm') {
// cout << name + " it's the grandmother of " + temp->MyName+"\n";
// return "grandmother";
// } else {
// cout << name + " it's the grandfather of " + temp->MyName+"\n";
// return "grandfather";
// }
// } else if (r > 2)
// {
// string times = "";
// while(i<r)
// {
// times = times + "great-";
// i++;
// }
// if (temp3[(temp2->depth)-1] == 'm') {
// cout << name + " it's the "+ times +"grandmother of " + temp->MyName+"\n";
// return times + "grandmother";
// } else {
// cout << name + " it's the "+ times +"grandfather of " + temp->MyName+"\n";
// return times + "grandfather";
// }
// }
}
////////////////
string Tree::find_helper(Tree *now, string name ) {
//Tree temp = *now;
string n = now->MyName;
if ((now->rel).compare(name) == 0) {
this->key = 1;
this->found = true;
return n;
}
if (now->Mother != NULL && now->rel != name && this->key != 1 && this->found!=true) {
n = find_helper(now->Mother, name);
}
if (now->Father != NULL && now->rel != name && this->key != 1 && this->found!=true) {
n = find_helper(now->Father, name);
}
if (now->rel == name) {
this->found = true;
return n;
}
if (this->key == 1) {
this->found = true;
return n;
}
if(this->found==false )
{
return "";
}
return "";
}
/////////////////
string Tree::find(string rel) {
// string p = new string();
string p = find_helper(this, rel);
this->key=0;
this->found=false;
if(p.compare("")==0)
{
//cout << "\nnot found";
//string test = "Could'nt find '" + rel + "'";
// throw invalid_argument("test");
throw runtime_error("asd");
}
//cout << p;
// delete &rel;
return p;
}
void Tree:: printT(Tree *temp) {
if (temp != nullptr)
{
cout << temp->rel + ": " + temp->MyName << endl;
if (temp->Father != NULL && temp->Mother != NULL)
{
printT(temp->Father);
printT(temp->Mother);
}
else if (temp->Father != NULL)
{
printT(temp->Father);
}
else if (temp->Mother != NULL)
{
printT(temp->Mother);
}
}
}
void Tree::display() {
Tree *temp = this;
printT(temp);
}
void Tree::del(Tree *root) {
if(root != nullptr) {
if (root->Mother != nullptr) {
root->Mother = nullptr;
}
if (root->Father != nullptr) {
root->Father = nullptr;
}
delete root;
}
}
void Tree::remove(string name) {
Tree *temp = this;
Tree *temp9 = this;
int i = 0;
// Tree temp2 = curr(temp, name);
this->key=0;
string temp2 = curr2(temp,name,"");
if(temp2.length()==0 || this->MyName.compare(name)==0 )
{
throw std::invalid_argument(name + " cant delete\n");
}
else{
while (temp->MyName != name) {
if (temp2[i] == 'f') {
temp = temp->Father;
i++;
}
if (temp2[i] == 'm') {
temp = temp->Mother;
i++;
}
}
i = 0;
if(temp2.length()==1)
{
//f
}
else {
while (i<temp2.length()-1) {
if (temp2[i] == 'f') {
temp9 = temp9->Father;
i++;
}
else {
temp9 = temp9->Mother;
i++;
}
}
}
//temp = &temp2;
this->found = false;
this->key = 0;
// delete temp;
// del(temp);
// delete temp9;
if(temp2[i]=='f'){
delete temp9->Father;
temp9->Father = nullptr;
}
if(temp2[i]=='m')
{
delete temp9->Mother;
temp9->Mother = nullptr;
}
//cout<<"a";
}
this->key=0;
this->found=false;
}
/**
* Tree temp = *now;
if(now->MyName==name)
{
this->key=1;
return temp;
}
if(now->Mother!=NULL && now->MyName!=name && this->key!=1)
{
temp = curr(now->Mother,name);
}
if(now->Father!=NULL && now->MyName!=name && this->key!=1 )
{
temp = curr(now->Father,name);
}
if(temp.MyName==name)
return temp;
*/
string Tree::curr2(Tree *now, string name, string ans) {
//Tree temp = *now;
string t = ans;
if (now->MyName.compare(name)==0) {
this->key = 1;
return t;
}
if (now->Father != NULL && now->MyName != name && this->key != 1) {
t = curr2(now->Father, name, ans + "f");
}
if (now->Mother != NULL && now->MyName != name && this->key != 1) {
t = curr2(now->Mother, name, ans + "m");
}
if (this->key == 1) {
return t;
}
return "";
}
| 22.779221 | 90 | 0.418757 | TomerDvir123 |
98c3b175988236bcb60c1ce5cf9f831b9a1788ba | 1,614 | cpp | C++ | thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.cpp | andywei/fbthrift | 59330df4969ecde98c09a5e2ae6e78a31735418f | [
"Apache-2.0"
] | null | null | null | thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.cpp | andywei/fbthrift | 59330df4969ecde98c09a5e2ae6e78a31735418f | [
"Apache-2.0"
] | null | null | null | thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.cpp | andywei/fbthrift | 59330df4969ecde98c09a5e2ae6e78a31735418f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdexcept>
#include <utility>
#include <folly/Portability.h>
#include <thrift/lib/cpp2/protocol/nimble/ControlBitHelpers.h>
#include <thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.h>
namespace apache {
namespace thrift {
namespace detail {
namespace {
constexpr NimbleBlockEncodeData encodeDataForControlByte(std::uint8_t byte) {
NimbleBlockEncodeData result;
result.sum = 0;
for (int i = 0; i < kChunksPerBlock; ++i) {
int size = controlBitPairToSize(byte, i);
result.sizes[i] = size;
result.sum += size;
}
return result;
}
template <std::size_t... Indices>
constexpr std::array<NimbleBlockEncodeData, 256> encodeDataFromIndices(
std::index_sequence<Indices...>) {
return {{encodeDataForControlByte(Indices)...}};
}
} // namespace
FOLLY_STORAGE_CONSTEXPR const std::array<NimbleBlockEncodeData, 256>
nimbleBlockEncodeData =
encodeDataFromIndices(std::make_index_sequence<256>{});
} // namespace detail
} // namespace thrift
} // namespace apache
| 28.821429 | 77 | 0.737299 | andywei |
98c48edaf8079e3633fca88e0dac2b69c771448a | 6,349 | cc | C++ | src/post.cc | smirolo/tero | 8db171a22e6723bc1eed0b235f17cc962528b93d | [
"BSD-3-Clause"
] | 1 | 2020-06-27T00:27:10.000Z | 2020-06-27T00:27:10.000Z | src/post.cc | smirolo/tero | 8db171a22e6723bc1eed0b235f17cc962528b93d | [
"BSD-3-Clause"
] | null | null | null | src/post.cc | smirolo/tero | 8db171a22e6723bc1eed0b235f17cc962528b93d | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2009-2013, Fortylines LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of fortylines nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Fortylines LLC ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Fortylines LLC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#include "mail.hh"
#include "markup.hh"
#include "decorator.hh"
#include "contrib.hh"
#include "composer.hh"
/** Posts.
Primary Author(s): Sebastien Mirolo <smirolo@fortylines.com>
*/
namespace tero {
sessionVariable titleVar("title","title of a post");
sessionVariable authorVar("author","author of a post");
sessionVariable authorEmail("authorEmail","email for the author of a post");
sessionVariable descrVar("descr","content of a post");
void
postAddSessionVars( boost::program_options::options_description& opts,
boost::program_options::options_description& visible )
{
using namespace boost::program_options;
options_description localOptions("posts");
localOptions.add(titleVar.option());
localOptions.add(authorVar.option());
localOptions.add(authorEmail.option());
localOptions.add(descrVar.option());
opts.add(localOptions);
visible.add(localOptions);
}
void post::normalize() {
title = tero::normalize(title);
guid = tero::strip(guid);
content = tero::strip(content);
}
bool post::valid() const {
/* If there are any whitespaces in the guid, Thunderbird 3 will
hang verifying the rss feed... */
for( size_t i = 0; i < guid.size(); ++i ) {
if( isspace(guid[i]) ) {
return false;
}
}
return (!title.empty() & !author->email.empty() & !content.empty());
}
void passThruFilter::flush() {
if( next ) next->flush();
}
void retainedFilter::provide() {
first = posts.begin();
last = posts.end();
}
void retainedFilter::flush()
{
if( next ) {
provide();
for( const_iterator p = first; p != last; ++p ) {
next->filters(*p);
}
next->flush();
}
}
void contentHtmlwriter::filters( const post& p ) {
*ostr << html::div().classref("postBody");
*ostr << p.content;
*ostr << html::div::end;
}
void titleHtmlwriter::filters( const post& p ) {
/* caption for the post */
*ostr << html::div().classref("postCaption");
if( !p.link.empty() ) {
*ostr << p.link << std::endl;
} else if( !p.title.empty() ) {
*ostr << html::a().href(p.guid)
<< html::h(1) << p.title << html::h(1).end()
<< html::a::end << std::endl;
}
*ostr << by(p.author) << " on " << p.time;
*ostr << html::div::end;
if( next ) {
next->filters(p);
}
}
void contactHtmlwriter::filters( const post& p ) {
if( next ) {
next->filters(p);
}
*ostr << html::div().classref("postContact");
*ostr << html::div().classref("contactAuthor");
*ostr << "Contact the author "
<< html::div() << contact(p.author) << html::div::end;
*ostr << html::div::end << html::div::end;
}
void stripedHtmlwriter::filters( const post& p ) {
(*ostr).imbue(std::locale((*ostr).getloc(), pubDate::shortFormat()));
*ostr << html::div().classref( (postNum % 2 == 0) ?
"postEven" : "postOdd");
if( next ) {
next->filters(p);
}
*ostr << html::div::end;
++postNum;
}
void htmlwriter::filters( const post& p ) {
striped.filters(p);
}
void mailwriter::filters( const post& p ) {
(*ostr).imbue(std::locale((*ostr).getloc(), pubDate::format()));
*ostr << "From " << from(p.author) << std::endl;
*ostr << "Subject: " << (!p.title.empty() ? p.title : "(No Subject)")
<< std::endl;
*ostr << "Date: " << p.time << std::endl;
*ostr << "From: " << from(p.author) << std::endl;
*ostr << "Score: " << p.score << std::endl;
for( post::headersMap::const_iterator header = p.moreHeaders.begin();
header != p.moreHeaders.end(); ++header ) {
*ostr << header->first << ": " << header->second << std::endl;
}
*ostr << std::endl << std::endl;
if( !p.link.empty() ) {
*ostr << p.link << std::endl;
}
/* \todo avoid description starting with "From " */
*ostr << p.content << std::endl << std::endl;
}
void rsswriter::filters( const post& p ) {
htmlEscaper esc;
*ostr << item();
*ostr << title() << p.title << title::end;
*ostr << rsslink() << p.guid << rsslink::end;
*ostr << description() << "<![CDATA[";
if( !p.link.empty() ) {
*ostr << p.link << std::endl;
}
*ostr << html::p()
<< by(p.author) << ":" << "<br />"
<< p.content << html::p::end
<< "]]>" << description::end;
*ostr << author();
esc.attach(*ostr);
*ostr << p.author->email;
esc.detach();
*ostr << author::end;
#if 0
*ostr << "<guid isPermaLink=\"true\">";
#endif
*ostr << guid() << p.guid << guid::end;
*ostr << pubDate(p.time);
*ostr << item::end;
}
void subjectWriter::filters( const post& p ) {
*ostr << html::a().href(p.guid) << p.title << html::a::end
<< "<br/>" << std::endl;
}
}
| 28.34375 | 80 | 0.606867 | smirolo |
98c5aa208506bbc593f4d18ce839c305dc7ab179 | 10,983 | cpp | C++ | src/3rdparty/qt-components/src/mx/qmxtoplevelitem.cpp | qtmediahub/qtmediahub-ruins | 844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67 | [
"BSD-3-Clause"
] | null | null | null | src/3rdparty/qt-components/src/mx/qmxtoplevelitem.cpp | qtmediahub/qtmediahub-ruins | 844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67 | [
"BSD-3-Clause"
] | null | null | null | src/3rdparty/qt-components/src/mx/qmxtoplevelitem.cpp | qtmediahub/qtmediahub-ruins | 844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Components project on Qt Labs.
**
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions contained
** in the Technology Preview License Agreement accompanying this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
****************************************************************************/
#include "qmxtoplevelitem.h"
#include "qmxtoplevelitem_p.h"
#include <QGraphicsScene>
QMxTopLevelItemPrivate::QMxTopLevelItemPrivate() :
targetItem(0), transformDirty(0), keepInside(0)
{
}
QMxTopLevelItemPrivate::~QMxTopLevelItemPrivate()
{
}
void QMxTopLevelItemPrivate::clearDependencyList()
{
Q_Q(QMxTopLevelItem);
for (int i = dependencyList.count() - 1; i >= 0; --i) {
dependencyList.takeAt(i)->disconnect(this);
}
q->setTransform(QTransform());
q->setOpacity(1);
q->setVisible(false);
}
/*!
\internal
Set data bindings between the TopLevelItem and all the items it depend upon,
including the targetItem and its ancestors.
*/
void QMxTopLevelItemPrivate::initDependencyList()
{
Q_Q(QMxTopLevelItem);
if (!targetItem || !targetItem->parentItem())
return;
// ### We are not listening for childrenChange signals in our parent
// but that seems a little bit too much overhead. It can be done if
// required in the future.
setZFromSiblings();
// The width of the TopLevelItem is the width of the targetItem
connect(targetItem, SIGNAL(widthChanged()), SLOT(updateWidthFromTarget()));
connect(targetItem, SIGNAL(heightChanged()), SLOT(updateHeightFromTarget()));
// Now bind to events that may change the position and/or transforms of
// the TopLevelItem
// ### If we had access to QDeclarativeItem private we could do this
// in a better way, by adding ourselves to the changeListeners list
// in each item.
// The benefit is that we could update our data based on the change
// rather than having to recalculate the whole tree.
QDeclarativeItem *item = targetItem;
while (item->parentItem()) {
dependencyList << item;
// We listen for events that can change the visibility and/or geometry
// of the targetItem or its ancestors.
connect(item, SIGNAL(opacityChanged()), SLOT(updateOpacity()));
connect(item, SIGNAL(visibleChanged()), SLOT(updateVisible()));
// ### We are not listening to changes in the "transform" property
// 'updateTransform' may be expensive, so instead of calling it several
// times, we call the schedule method instead, that also compresses
// these events.
connect(item, SIGNAL(xChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(yChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(rotationChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(scaleChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(transformOriginChanged(TransformOrigin)), SLOT(scheduleUpdateTransform()));
// parentChanged() may be emitted from destructors and other sensible code regions.
// By making this connection Queued we wait for the control to reach the event loop
// allow for the scene to be in a stable state before doing our changes.
connect(item, SIGNAL(parentChanged()), SLOT(updateParent()), Qt::QueuedConnection);
item = item->parentItem();
}
// 'item' is the root item in the scene, make it our parent
q->setParentItem(item);
// Note that we did not connect to signals regarding opacity, visibility or
// transform changes of our parent, that's because we take that effect
// automatically, as it is our parent
// OTOH we need to listen to changes in its size to re-evaluate the keep-inside
// functionality.
connect(item, SIGNAL(widthChanged()), SLOT(updateWidthFromTarget()));
// Call slots for the first time
updateHeightFromTarget();
updateTransform();
updateOpacity();
updateVisible();
}
void QMxTopLevelItemPrivate::scheduleUpdateTransform()
{
if (transformDirty)
return;
transformDirty = 1;
QMetaObject::invokeMethod(this, "updateTransform", Qt::QueuedConnection);
}
void QMxTopLevelItemPrivate::updateTransform()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setTransform(targetItem->itemTransform(q->parentItem()));
updateWidthFromTarget();
transformDirty = 0;
}
void QMxTopLevelItemPrivate::updateOpacity()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setOpacity(targetItem->effectiveOpacity());
}
void QMxTopLevelItemPrivate::updateVisible()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setVisible(targetItem->isVisibleTo(q->parentItem()));
}
void QMxTopLevelItemPrivate::updateParent()
{
Q_ASSERT(targetItem);
clearDependencyList();
initDependencyList();
}
void QMxTopLevelItemPrivate::updateWidthFromTarget()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
// Reset position and size to those of the targetItem
qreal newX = 0;
qreal newWidth = targetItem->width();
if (!keepInside) {
q->setX(newX);
q->setWidth(newWidth);
return;
}
const QTransform screenToParentTransform = q->parentItem()->sceneTransform().inverted();
const QTransform itemToParentTransform = q->QGraphicsItem::transform();
if (screenToParentTransform.isRotating() || itemToParentTransform.isRotating()) {
qWarning() << "QMxTopLevelItem: KeepInside feature is not supported together with rotation transforms";
q->setX(newX);
q->setWidth(newWidth);
return;
}
// We use a compromise solution here. The real deal is that we have a scene with items
// and possibly one or more views to that scene. We don't know exactly where these
// views are, but we need a reference to constrain the items.
// So we assume from current "qml runtime" implementation that usually the scene
// has only one view and that view has the size of the root-item in the scene.
const qreal screenWidth = q->parentItem()->width();
// Now we map to _root item coordinates_ the following info:
// 1) The edges of the "screen".
// 2) The edges of our transformed item, ie. the place where our targetItem is.
// 3) The respective widths
const qreal leftScreenEdgeAtParent = screenToParentTransform.map(QPointF(0, 0)).x();
const qreal rightScreenEdgeAtParent = screenToParentTransform.map(QPointF(screenWidth, 0)).x();
const qreal leftItemEdgeAtParent = itemToParentTransform.map(QPointF(0, 0)).x();
const qreal rightItemEdgeAtParent = itemToParentTransform.map(QPointF(newWidth, 0)).x();
const qreal screenWidthAtParent = rightScreenEdgeAtParent - leftScreenEdgeAtParent;
const qreal itemWidthAtParent = rightItemEdgeAtParent - leftItemEdgeAtParent;
// Now with all sizes in the same coordinate system we can apply offsets to
// our item's width and/or position to keep it inside the screen.
if (itemWidthAtParent > screenWidthAtParent) {
// Is the item too large?
newWidth *= screenWidthAtParent / itemWidthAtParent;
newX = leftScreenEdgeAtParent - leftItemEdgeAtParent;
} else if (leftScreenEdgeAtParent > leftItemEdgeAtParent) {
// Does item go beyond left edge ?
newX = leftScreenEdgeAtParent - leftItemEdgeAtParent;
} else if (rightItemEdgeAtParent > rightScreenEdgeAtParent) {
// Does item go beyond right edge ?
newX = rightScreenEdgeAtParent - rightItemEdgeAtParent;
}
q->setX(newX);
q->setWidth(newWidth);
}
void QMxTopLevelItemPrivate::updateHeightFromTarget()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setHeight(targetItem->height());
}
void QMxTopLevelItemPrivate::setZFromSiblings()
{
Q_Q(QMxTopLevelItem);
int maxZ = 0;
const QList<QGraphicsItem *> siblings = q->parentItem()->childItems();
for (int i = siblings.count() - 1; i >= 0; --i) {
// Skip other topLevelItems
QGraphicsObject *obj = siblings[i]->toGraphicsObject();
if (qobject_cast<QMxTopLevelItem *>(obj))
continue;
if (siblings[i]->zValue() > maxZ)
maxZ = siblings[i]->zValue();
}
q->setZValue(maxZ + 1);
}
QMxTopLevelItem::QMxTopLevelItem(QDeclarativeItem *parent) :
QDeclarativeItem(parent), d_ptr(new QMxTopLevelItemPrivate)
{
d_ptr->q_ptr = this;
}
QMxTopLevelItem::QMxTopLevelItem(QMxTopLevelItemPrivate &dd, QDeclarativeItem *parent) :
QDeclarativeItem(parent), d_ptr(&dd)
{
d_ptr->q_ptr = this;
}
QMxTopLevelItem::~QMxTopLevelItem()
{
}
bool QMxTopLevelItem::keepInside() const
{
Q_D(const QMxTopLevelItem);
return d->keepInside;
}
void QMxTopLevelItem::setKeepInside(bool keepInside)
{
Q_D(QMxTopLevelItem);
if (keepInside == d->keepInside)
return;
d->keepInside = keepInside;
if (d->targetItem)
d->updateWidthFromTarget();
emit keepInsideChanged(keepInside);
}
QVariant QMxTopLevelItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
Q_D(QMxTopLevelItem);
if (d->targetItem == 0) {
// The original parent of this item (declared in QML) will be our
// 'target' item, ie, the item which size and position we will follow.
// ### To find that parent, we could listen to ItemParentChange but that
// does not work due to the fact QDeclarativeItem::data adds children
// w/o trigerring such event. (QGraphicsItem::get(child)->setParentItemHelper())
// Our workarround is to assume that the parent is set before the item is
// added to the scene, so we listen for the latter and get the info we need.
if (change == ItemSceneHasChanged)
d->targetItem = parentItem();
// Let the changes be finished before we start initDependencyList
QMetaObject::invokeMethod(d, "initDependencyList", Qt::QueuedConnection);
}
return QDeclarativeItem::itemChange(change, value);
}
| 35.201923 | 111 | 0.688792 | qtmediahub |
98c9dd552d306a0b0642eff4e09097777e3a0f7e | 1,729 | hpp | C++ | include/Utilities/MoveList.hpp | NicolasAlmerge/chess_game | 5f10d911cea40ac8d09cf418bdc14facaa1ecd4e | [
"MIT"
] | 1 | 2022-02-05T10:38:48.000Z | 2022-02-05T10:38:48.000Z | include/Utilities/MoveList.hpp | NicolasAlmerge/chess_game | 5f10d911cea40ac8d09cf418bdc14facaa1ecd4e | [
"MIT"
] | null | null | null | include/Utilities/MoveList.hpp | NicolasAlmerge/chess_game | 5f10d911cea40ac8d09cf418bdc14facaa1ecd4e | [
"MIT"
] | null | null | null | #pragma once
#include <list>
#include <iterator>
#include <SFML/Graphics.hpp>
#include "../Components/Board.hpp"
#include "Move.hpp"
#include "PieceTransition.hpp"
using namespace sf;
class MoveList
{
public:
MoveList(Board&, PieceTransition&);
list<shared_ptr<Move>>::iterator getNewIterator() { return m_moves.begin(); }
list<shared_ptr<Move>>::iterator getIterator() { return m_moveIterator; }
list<shared_ptr<Move>> getMoves() const { return m_moves; }
PieceTransition& getTransitioningPiece() const { return m_transitioningPiece; }
int getIteratorIndex() { return std::distance(m_moves.begin(), m_moveIterator); }
int getMoveListSize() const { return m_moves.size(); }
void highlightLastMove(RenderWindow&) const;
void reset() { m_moves.clear(); m_moveIterator = m_moves.begin(); };
void goToPreviousMove(bool, vector<Arrow>&);
void goToNextMove(bool, vector<Arrow>&);
void goToCurrentMove(vector<Arrow>& arrowList) { while(hasMovesAfter()) goToNextMove(false, arrowList); }
void goToInitialMove(vector<Arrow>& arrowList) { while(hasMovesBefore()) goToPreviousMove(false, arrowList); }
void addMove(shared_ptr<Move>&, vector<Arrow>& arrowList);
bool hasMovesBefore() const { return m_moveIterator != m_moves.end(); }
bool hasMovesAfter() const { return m_moveIterator != m_moves.begin(); }
private:
list<shared_ptr<Move>> m_moves;
list<shared_ptr<Move>>::iterator m_moveIterator = m_moves.begin();
PieceTransition& m_transitioningPiece;
Board& game;
void applyMove(shared_ptr<Move>&, bool, bool, vector<Arrow>&); // called inside GameThread ?
void applyMove(bool, vector<Arrow>&);
void undoMove(bool, vector<Arrow>&);
};
| 39.295455 | 114 | 0.716021 | NicolasAlmerge |
98cb18f4fa2d6fe4ee76e9133bf2eecbdb51b72c | 3,337 | cpp | C++ | MineFLTKDRM/Minesweeper.cpp | i-anton/MineFLTK | 70e268b5559f982e666c63bfae808e3476c9b503 | [
"Unlicense"
] | 1 | 2019-12-01T20:23:05.000Z | 2019-12-01T20:23:05.000Z | MineFLTKDRM/Minesweeper.cpp | i-anton/MineFLTK | 70e268b5559f982e666c63bfae808e3476c9b503 | [
"Unlicense"
] | null | null | null | MineFLTKDRM/Minesweeper.cpp | i-anton/MineFLTK | 70e268b5559f982e666c63bfae808e3476c9b503 | [
"Unlicense"
] | null | null | null | #include "Minesweeper.h"
#include <queue>
#include "Vector2i.h"
Cell::Cell() :
marked(false),
opened(false),
neighbours(0)
{}
Minesweeper::Minesweeper() :
current_state(GameState::Playing),
unmarked_mines(0),
not_mined(TABLE_ROWS*TABLE_ROWS),
total_cells(not_mined)
{}
Minesweeper::~Minesweeper()
{}
bool Minesweeper::reveal(unsigned int x, unsigned int y)
{
if (cells[y][x].marked)
{
return true;
}
if (cells[y][x].neighbours == MINE_VALUE)
{
//fail
for (size_t y_inn = 0; y_inn < TABLE_ROWS; ++y_inn)
{
for (size_t x_inn = 0; x_inn < TABLE_ROWS; x_inn++)
{
cells[y_inn][x_inn].opened = true;
}
}
current_state = GameState::Lose;
return false;
}
reveal_wave(x, y);
if (not_mined == 0)
{
for (size_t y_inn = 0; y_inn < TABLE_ROWS; ++y_inn)
{
for (size_t x_inn = 0; x_inn < TABLE_ROWS; x_inn++)
{
cells[y_inn][x_inn].opened = true;
}
}
current_state = GameState::Win;
}
return true;
}
void Minesweeper::mark(unsigned int x, unsigned int y)
{
cells[y][x].marked = !cells[y][x].marked;
}
void Minesweeper::generate(unsigned int x, unsigned int y, unsigned int mines_count)
{
unmarked_mines = mines_count;
not_mined = total_cells - mines_count;
assert(unmarked_mines > 0);
assert(not_mined + mines_count > not_mined);
std::vector<unsigned int> v_not_mined;
v_not_mined.reserve(total_cells);
unsigned int exclude_id = x + y * TABLE_ROWS;
for (size_t i = 0; i < total_cells; ++i)
{
if (i != exclude_id)
v_not_mined.push_back(i);
}
for (size_t i = 0; i < mines_count; ++i)
{
int idx = rand() % v_not_mined.size();
int id = v_not_mined[idx];
int y = id / TABLE_ROWS;
int x = id - y * TABLE_ROWS;
assert(x >= 0);
assert(x < TABLE_ROWS);
v_not_mined.erase(v_not_mined.begin() + idx);
cells[y][x].neighbours = MINE_VALUE;
mark_neighbours(x, y);
}
}
void Minesweeper::reveal_wave(int x, int y)
{
std::queue<Vector2i> q;
q.push(Vector2i(x, y));
while (!q.empty())
{
auto vect = q.front();
q.pop();
if (cells[vect.y][vect.x].opened)
continue;
not_mined--;
cells[vect.y][vect.x].opened = true;
cells[vect.y][vect.x].marked = false;
if (cells[vect.y][vect.x].neighbours > 0)
continue;
int ymax = MIN(vect.y + 1, TABLE_ROWS - 1);
int ymin = MAX(vect.y - 1, 0);
int xmin = MAX(vect.x - 1, 0);
int xmax = MIN(vect.x + 1, TABLE_ROWS - 1);
for (int y_i = ymin; y_i <= ymax; ++y_i)
{
for (int x_i = xmin; x_i <= xmax; ++x_i)
{
auto cell = cells[y_i][x_i];
if (y_i == vect.y && x_i == vect.x) continue;
if (!cell.opened && cell.neighbours != MINE_VALUE)
q.push(Vector2i(x_i, y_i));
}
}
}
}
void Minesweeper::mark_neighbours(unsigned int x, unsigned int y)
{
mark_neighbour_one(x - 1, y - 1);
mark_neighbour_one(x, y - 1);
mark_neighbour_one(x + 1, y - 1);
mark_neighbour_one(x - 1, y);
mark_neighbour_one(x + 1, y);
mark_neighbour_one(x - 1, y + 1);
mark_neighbour_one(x, y + 1);
mark_neighbour_one(x + 1, y + 1);
}
void Minesweeper::mark_neighbour_one(unsigned int x, unsigned int y)
{
if (x < 0 || x >= TABLE_ROWS ||
y < 0 || y >= TABLE_ROWS) return;
if (cells[y][x].neighbours != MINE_VALUE)
{
cells[y][x].neighbours++;
}
}
| 23.666667 | 85 | 0.611328 | i-anton |
98cd6c7f68e741510ffc669f2385e806cdeb8e0c | 83 | cpp | C++ | raygame/Condition.cpp | MatthewRagas/AI_Agents | 7c513fe63956929bb55ee1f5e6fdf756422497fc | [
"MIT"
] | null | null | null | raygame/Condition.cpp | MatthewRagas/AI_Agents | 7c513fe63956929bb55ee1f5e6fdf756422497fc | [
"MIT"
] | null | null | null | raygame/Condition.cpp | MatthewRagas/AI_Agents | 7c513fe63956929bb55ee1f5e6fdf756422497fc | [
"MIT"
] | null | null | null | #include "Condition.h"
Condition::Condition()
{
}
Condition::~Condition()
{
}
| 6.384615 | 23 | 0.638554 | MatthewRagas |
98cdd283af66eece5017b11bef8424da853301d5 | 609 | cpp | C++ | Source/Zmey/Graphics/Features/FeatureTemplate.cpp | nikoladimitroff/Zmey | 4bcea8d66cd3452c532fa68286aa03ad8528a3b4 | [
"MIT"
] | 22 | 2017-05-06T18:08:48.000Z | 2022-01-12T02:10:22.000Z | Source/Zmey/Graphics/Features/FeatureTemplate.cpp | nikoladimitroff/Zmey | 4bcea8d66cd3452c532fa68286aa03ad8528a3b4 | [
"MIT"
] | 21 | 2017-12-11T18:42:49.000Z | 2018-08-27T23:13:47.000Z | Source/Zmey/Graphics/Features/FeatureTemplate.cpp | nikoladimitroff/Zmey | 4bcea8d66cd3452c532fa68286aa03ad8528a3b4 | [
"MIT"
] | null | null | null | #pragma once
#include <Zmey/Graphics/Features/FEATURE_NAME.h>
#include <Zmey/Graphics/Backend/CommandList.h>
#include <Zmey/Graphics/Renderer.h>
#include <Zmey/World.h>
#include <Zmey/Components/TransformManager.h>
namespace Zmey
{
namespace Graphics
{
namespace Features
{
void FEATURE_NAME::GatherData(FrameData& frameData, World& world)
{
}
void FEATURE_NAME::PrepareData(FrameData& frameData, RendererData& data)
{
}
void FEATURE_NAME::GenerateCommands(FrameData& frameData, RenderPass pass, ViewType view, Backend::CommandList* list, RendererData& data)
{
}
}
}
} | 18.454545 | 138 | 0.73399 | nikoladimitroff |
98d24ada6d0581a80f79fa313d4ebafb8cb975c0 | 1,348 | cpp | C++ | system/zombie/backup_dancer.cpp | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 1 | 2022-03-29T23:49:55.000Z | 2022-03-29T23:49:55.000Z | system/zombie/backup_dancer.cpp | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 2 | 2021-03-10T18:17:07.000Z | 2021-05-11T13:59:22.000Z | system/zombie/backup_dancer.cpp | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 1 | 2021-10-18T18:29:47.000Z | 2021-10-18T18:29:47.000Z | #include <cmath>
#include "zombie.h"
namespace pvz_emulator::system {
using namespace pvz_emulator::object;
void zombie_backup_dancer::update(zombie& z) {
if (z.is_eating) {
return;
}
if (z.status == zombie_status::backup_spawning) {
z.dy = static_cast<float>(round(z.countdown.action * (-4/3)));
if (z.countdown.action) {
return;
}
}
auto next_status = get_status_by_clock(z);
if (next_status != z.status) {
z.status = next_status;
switch (next_status) {
case zombie_status::dancing_walking:
reanim.set(z, zombie_reanim_name::anim_walk, reanim_type::repeat, 0);
break;
case zombie_status::dancing_armrise1:
reanim.set(z, zombie_reanim_name::anim_armraise, reanim_type::repeat, 18);
z.reanim.progress = 0.60000002f;
break;
default:
reanim.set(z, zombie_reanim_name::anim_armraise, reanim_type::repeat, 18);
break;
}
}
}
void zombie_backup_dancer::init(zombie& z, unsigned int row) {
z._ground = _ground.data();
zombie_base::init(z, zombie_type::backup_dancer, row);
z.status = zombie_status::dancing_walking;
reanim.set(z, zombie_reanim_name::anim_armraise, reanim_type::repeat, 12);
set_common_fields(z);
}
} | 24.962963 | 86 | 0.626113 | dnartz |
98d496eb24f8642f90d9d4326a5049bac96ce92e | 3,488 | cxx | C++ | python/kwiver/sprokit/pipeline/version.cxx | mwoehlke-kitware/kwiver | 614a488bd2b7fe551ac75eec979766d882709791 | [
"BSD-3-Clause"
] | 176 | 2015-07-31T23:33:37.000Z | 2022-03-21T23:42:44.000Z | python/kwiver/sprokit/pipeline/version.cxx | mwoehlke-kitware/kwiver | 614a488bd2b7fe551ac75eec979766d882709791 | [
"BSD-3-Clause"
] | 1,276 | 2015-05-03T01:21:27.000Z | 2022-03-31T15:32:20.000Z | python/kwiver/sprokit/pipeline/version.cxx | mwoehlke-kitware/kwiver | 614a488bd2b7fe551ac75eec979766d882709791 | [
"BSD-3-Clause"
] | 85 | 2015-01-25T05:13:38.000Z | 2022-01-14T14:59:37.000Z | // This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
#include <pybind11/pybind11.h>
#include <sprokit/pipeline/version.h>
#include <vital/version.h>
/**
* \file version.cxx
*
* \brief Python bindings for version.
*/
using namespace pybind11;
namespace kwiver{
namespace sprokit{
namespace python{
class compile
{
public:
typedef ::sprokit::version::version_t version_t;
static version_t const major;
static version_t const minor;
static version_t const patch;
static std::string const version_string;
static bool const git_build;
static std::string const git_hash;
static std::string const git_hash_short;
static std::string const git_dirty;
static bool check(version_t major_, version_t minor_, version_t patch_);
};
::sprokit::version::version_t const compile::major = KWIVER_VERSION_MAJOR;
::sprokit::version::version_t const compile::minor = KWIVER_VERSION_MINOR;
::sprokit::version::version_t const compile::patch = KWIVER_VERSION_PATCH;
std::string const compile::version_string = KWIVER_VERSION;
bool const compile::git_build =
#ifdef KWIVER_BUILT_FROM_GIT
true;
#else
false;
#endif
std::string const compile::git_hash = KWIVER_GIT_HASH;
std::string const compile::git_hash_short = KWIVER_GIT_HASH_SHORT;
std::string const compile::git_dirty = KWIVER_GIT_DIRTY;
class runtime
{
};
}
}
}
using namespace kwiver::sprokit::python;
PYBIND11_MODULE(version, m)
{
class_<compile>(m,"compile"
, "Compile-time version information.")
.def_readonly_static("major", &compile::major)
.def_readonly_static("minor", &compile::minor)
.def_readonly_static("patch", &compile::patch)
.def_readonly_static("version_string", &compile::version_string)
.def_readonly_static("git_build", &compile::git_build)
.def_readonly_static("git_hash", &compile::git_hash)
.def_readonly_static("git_hash_short", &compile::git_hash_short)
.def_readonly_static("git_dirty", &compile::git_dirty)
.def_static("check", &compile::check
, arg("major"), arg("minor"), arg("patch")
, "Check for a sprokit of at least the given version.")
;
class_<runtime>(m, "runtime"
, "Runtime version information.")
.def_readonly_static("major", &sprokit::version::major)
.def_readonly_static("minor", &sprokit::version::minor)
.def_readonly_static("patch", &sprokit::version::patch)
.def_readonly_static("version_string", &sprokit::version::version_string)
.def_readonly_static("git_build", &sprokit::version::git_build)
.def_readonly_static("git_hash", &sprokit::version::git_hash)
.def_readonly_static("git_hash_short", &sprokit::version::git_hash_short)
.def_readonly_static("git_dirty", &sprokit::version::git_dirty)
.def_static("check", &sprokit::version::check
, arg("major"), arg("minor"), arg("patch")
, "Check for a sprokit of at least the given version.")
;
}
// If any of the version components are 0, we get compare warnings. Turn
// them off here.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
namespace kwiver{
namespace sprokit{
namespace python{
bool
compile
::check(version_t major_, version_t minor_, version_t patch_)
{
return KWIVER_VERSION_CHECK(major_, minor_, patch_);
}
}
}
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
| 30.596491 | 77 | 0.733372 | mwoehlke-kitware |
98d8e2d19b2350c7ebdbcdfa7c1a74983942dfea | 21,492 | cpp | C++ | Info/Info/Quests/QuestsInfo.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | Info/Info/Quests/QuestsInfo.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | Info/Info/Quests/QuestsInfo.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | #include <Info/Info/Quests/QuestsInfo.h>
namespace Lunia {
namespace XRated {
namespace Database {
namespace Info {
const int QuestInfo::Condition::NonUseGuildLevel = -1;
QuestInfo::QuestInfo()
{
}
void QuestInfo::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo");
out.Write(L"AcceptCondition", AcceptCondition);
out.Write(L"CompleteCondition", CompleteCondition);
out.Write(L"AcceptReward", AcceptReward);
out.Write(L"CompleteReward", CompleteReward);
out.Write(L"Objectives", Objectives);
out.Write(L"MaximumCompleteableCount", MaximumCompleteableCount);
out.Write(L"AcceptLocation", AcceptLocation);
out.Write(L"AcceptSourceHash", AcceptSourceHash);
out.Write(L"CompleteTarget", CompleteTarget);
out.Write(L"PlayingStage", PlayingStage);
out.Write(L"PossibleToShare", PossibleToShare);
out.Write(L"EventQuestType", EventQuestType);
out.Write(L"QuestLumpComplete", QuestLumpComplete);
//ResetWeekField
bool temp;
if ((ResetWeekField & (0x01 << DateTime::Week::Sunday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekSunday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Monday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekMonday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Tuesday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekTuesday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Wednesday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekWednesday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Thursday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekThursday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Friday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekFriday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Saturday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekSaturday", temp);
out.Write(L"Tags", Tags);
}
void QuestInfo::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo");
in.Read(L"AcceptCondition", AcceptCondition, Condition());
in.Read(L"CompleteCondition", CompleteCondition, Condition());
in.Read(L"AcceptReward", AcceptReward, Reward());
in.Read(L"CompleteReward", CompleteReward, Reward());
in.Read(L"Objectives", Objectives, std::vector<Objective>());
in.Read(L"MaximumCompleteableCount", MaximumCompleteableCount, uint32(1));
in.Read(L"AcceptLocation", AcceptLocation);
in.Read(L"AcceptSourceHash", AcceptSourceHash);
in.Read(L"CompleteTarget", CompleteTarget);
in.Read(L"PlayingStage", PlayingStage, XRated::StageLocation(0, 0));
in.Read(L"PossibleToShare", PossibleToShare, true);
in.Read(L"EventQuestType", EventQuestType, uint8(0));
in.Read(L"QuestLumpComplete", QuestLumpComplete, true);
ResetWeekField = 0;
bool temp;
in.Read(L"ResetWeekSunday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Sunday;
in.Read(L"ResetWeekMonday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Monday;
in.Read(L"ResetWeekTuesday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Tuesday;
in.Read(L"ResetWeekWednesday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Wednesday;
in.Read(L"ResetWeekThursday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Thursday;
in.Read(L"ResetWeekFriday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Friday;
in.Read(L"ResetWeekSaturday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Saturday;
if (AcceptCondition.Quests.empty() == false) {
PossibleToShare = false;
}
in.Read(L"Tags", Tags, std::vector< std::wstring >());
}
void QuestInfo::Condition::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition");
out.Write(L"ScriptOnly", ScriptOnly);
out.Write(L"Class", Class);
out.Write(L"Level", Level);
out.Write(L"MaxLevel", MaxLevel);
out.Write(L"PvpLevel", PvpLevel);
out.Write(L"PvpMaxLevel", PvpMaxLevel);
out.Write(L"WarLevel", WarLevel);
out.Write(L"WarMaxLevel", WarMaxLevel);
out.Write(L"StoredLevel", StoredLevel);
out.Write(L"StoredMaxLevel", StoredMaxLevel);
out.Write(L"RebirthCount", RebirthCount);
out.Write(L"RebirthMaxCount", RebirthMaxCount);
out.Write(L"Life", Life);
out.Write(L"Money", Money);
out.Write(L"GuildLevel", GuildLevel);
out.Write(L"Items", Items);
out.Write(L"Licenses", Licenses);
out.Write(L"Quests", Quests);
}
void QuestInfo::Condition::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition");
in.Read(L"ScriptOnly", ScriptOnly, false);
in.Read(L"Class", Class, uint16(XRated::Constants::ClassType::AnyClassType));
in.Read(L"Level", Level, uint16(0));
in.Read(L"MaxLevel", MaxLevel, uint16(99));
in.Read(L"PvpLevel", PvpLevel, uint16(0));
in.Read(L"PvpMaxLevel", PvpMaxLevel, uint16(99));
in.Read(L"WarLevel", WarLevel, uint16(1));
in.Read(L"WarMaxLevel", WarMaxLevel, uint16(99));
in.Read(L"StoredLevel", StoredLevel, uint16(1));
in.Read(L"StoredMaxLevel", StoredMaxLevel, Constants::StoredMaxLevel);
in.Read(L"RebirthCount", RebirthCount, uint16(0));
in.Read(L"RebirthMaxCount", RebirthMaxCount, Constants::RebirthMaxCount);
in.Read(L"Life", Life, uint16(0));
in.Read(L"Money", Money, uint32(0));
in.Read(L"GuildLevel", GuildLevel, NonUseGuildLevel);
in.Read(L"Items", Items, std::vector<Condition::Item>());
in.Read(L"Licenses", Licenses, std::vector<StageLicense>());
in.Read(L"Quests", Quests, std::vector< uint32>());
}
bool QuestInfo::Condition::IsGuildQuest() const
{
if (NonUseGuildLevel < GuildLevel) {
return true;
}
return false;
}
bool QuestInfo::IsShareQuest() const
{
return PossibleToShare;
}
bool QuestInfo::IsPlayingStage() const
{
if (PlayingStage.StageGroupHash != 0) {
return true;
}
return false;
}
bool QuestInfo::IsEventQuest() const
{
return EventQuestType != 0;
}
uint8 QuestInfo::GetEventType() const
{
return EventQuestType;
}
bool QuestInfo::IsQuestLumpComplete() const
{
return QuestLumpComplete;
}
void QuestInfo::Condition::Item::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition::Item");
out.Write(L"ItemHash", ItemHash);
out.Write(L"Count", Count);
}
void QuestInfo::Condition::Item::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition::Item");
in.Read(L"ItemHash", ItemHash);
in.Read(L"Count", Count);
}
void QuestInfo::Objective::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective");
out.Write(L"Type", Condition->GetType());
out.Write(L"Condition", *Condition);
}
void QuestInfo::Objective::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective");
String type;
in.Read(L"Type", type, String());
if (type.empty()) return;
/* TODO: make condition factory to create detail condition */
if (type == L"DefeatNpcs")
Condition = std::make_shared<DefeatNpcs>();
else if (type == L"ProtectNpc")
Condition = std::make_shared<ProtectNpc>();
else
throw Exception(L"invalid obective type : [{}]", type.c_str());
in.Read(L"Condition", *Condition.get());
}
uint32 QuestInfo::Objective::Condition::UpdateParameter(const String& conditionName, uint32 oldParameter, uint32 target, int count) const
{
if (conditionName != GetConditionName()) return oldParameter;
if (std::find(Targets.begin(), Targets.end(), target) == Targets.end()) return oldParameter; // nothing matched
return (oldParameter + count) >= Count ? Count : (oldParameter + count);
}
void QuestInfo::Objective::Condition::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective::Condition");
out.Write(L"Targets", Targets);
out.Write(L"Count", Count);
}
void QuestInfo::Objective::Condition::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective::Condition");
in.Read(L"Targets", Targets);
in.Read(L"Count", Count);
}
void QuestInfo::Reward::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward");
out.Write(L"Exp", Exp);
out.Write(L"WarExp", WarExp);
out.Write(L"StateBundleHash", StateBundleHash);
out.Write(L"Money", Money);
out.Write(L"Items", Items);
out.Write(L"Licenses", Licenses);
out.Write(L"SelectableItems", SelectableItems);
}
void QuestInfo::Reward::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward");
in.Read(L"Exp", Exp, uint32(0));
in.Read(L"WarExp", WarExp, uint32(0));
in.Read(L"StateBundleHash", StateBundleHash, uint32(0));
in.Read(L"Money", Money, int(0));
in.Read(L"Items", Items, std::vector<Reward::Item>());
in.Read(L"Licenses", Licenses, std::vector<StageLicense>());
in.Read(L"SelectableItems", SelectableItems, std::vector<Reward::Item>());
}
void QuestInfo::Reward::Item::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward::Item");
out.Write(L"ItemHash", ItemHash);
out.Write(L"Count", Count);
out.Write(L"Instance", Instance);
out.Write(L"TakeAway", TakeAway);
}
void QuestInfo::Reward::Item::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward::Item");
in.Read(L"ItemHash", ItemHash);
in.Read(L"Count", Count);
//in.Read(L"Instance", Instance);
in.Read(L"TakeAway", TakeAway);
}
bool QuestInfo::Condition::IsValid(const PlayerData& player) const
{
BasicCharacterInfo info;
info.Class = player.Job;
info.Level = player.BaseCharacter.Level;
info.PvpLevel = player.PvpLevel;
info.WarLevel = player.WarLevel;
info.Life = player.Life;
info.Money = player.BaseCharacter.Money;
info.StoredLevel = player.StoredLevel;
info.RebirthCount = player.RebirthCount;
return IsValid(info);
}
bool QuestInfo::Condition::IsValid(const BasicCharacterInfo& player) const
{
if (Level > player.Level || MaxLevel < player.Level)// stage level should be in the range
return false;
if (PvpLevel > player.PvpLevel || PvpMaxLevel < player.PvpLevel)// pvp level should be in the range
return false;
if (WarLevel > player.WarLevel || WarMaxLevel < player.WarLevel)// war level should be in the range
return false;
if (StoredLevel > player.StoredLevel || StoredMaxLevel < player.StoredLevel)// stored level should be in the range
return false;
if (RebirthCount > player.RebirthCount || RebirthMaxCount < player.RebirthCount)// trans count should be in the range
return false;
if (Life > player.Life)// life should be enough
return false;
if (Money > player.Money)// money should be enough
return false;
if (Class != (uint16)XRated::Constants::ClassType::AnyClassType && Class != (uint16)player.Class)// this class cannot work for this quest
return false;
return true;
}
uint8 QuestInfo::UpdateParameter(const String& conditionName, uint32 target, int count, bool isSameTeam, std::vector<uint32>& param/*out*/) const
{
int totalCount(0), failCount(0), successCount(0);
for (std::vector<Objective>::const_iterator i = Objectives.begin(); i != Objectives.end(); ++i)
{
if (i->Condition->GetType() == std::wstring(L"DefeatNpcs") && isSameTeam)
{
++totalCount;
continue;
}
uint32 val(param[totalCount] = i->Condition->UpdateParameter(conditionName, param[totalCount], target, count));
if (i->Condition->IsFailed(val))
{
if (i->Condition->MakeAllFail())
{
return Quest::State::Failed;
}
++failCount;
}
else if (i->Condition->IsSucceeded(val))
{
if (i->Condition->MakeAllSuccess())
{
return Quest::State::Succeeded;
}
++successCount;
}
++totalCount;
}
if (totalCount > failCount + successCount)
{
return Quest::State::Working;
}
else if (totalCount == successCount)
{
return Quest::State::Succeeded;
}
else if (totalCount == failCount)
{
return Quest::State::Failed;
}
LoggerInstance().Error("unalbe to decide the quest result. temporarily treated as FAIL");
return Quest::State::Failed;
}
bool QuestInfo::IsRelayQuest() const
{
if (AcceptCondition.Quests.empty() == false || Next.first != 0) return true;
return false;
}
bool QuestInfo::IsFirstQuest() const
{
if (AcceptCondition.Quests.empty()) return true;
return false;
}
bool QuestInfo::IsLastQuest() const
{
if (Next.first == 0) return true;
return false;
}
bool QuestInfo::IsRepeatQuest() const
{
return MaximumCompleteableCount > 1;
}
bool QuestInfo::IsRepeatQuest(uint32 completeCount) const
{
return MaximumCompleteableCount > completeCount;
}
bool QuestInfo::IsGuildQuest() const
{
return (AcceptCondition.IsGuildQuest() || CompleteCondition.IsGuildQuest());
}
uint32 QuestInfo::GetLeftDay(const DateTime& now, const DateTime& expiredDate) const
{
if (ResetWeekField == 0) {
return 0;
}
if (now.GetDate() <= expiredDate.GetDate()) {
return static_cast<int>(expiredDate.GetDate().GetCumulatedDay()) - static_cast<int>(now.GetDate().GetCumulatedDay()) + 1;
}
return 0;
}
bool QuestInfo::IsPossibleDate(const DateTime& now, const DateTime& ExpiredDate) const
{
if (ResetWeekField == 0) {
return true;
}
if (now.GetDate() > ExpiredDate.GetDate()) {
return true;
}
return false;
}
bool QuestInfo::IsPossibleWeek(DateTime::Week::type type) const
{
if ((0x01 << type) & ResetWeekField) {
return true;
}
return false;
}
bool QuestInfo::IsHaveResetDate() const
{
if (ResetWeekField == 0) {
return false;
}
return true;
}
DateTime QuestInfo::GetExpiredDate(const DateTime& acceptDate) const
{
if (ResetWeekField == 0) {
return DateTime(XRated::Quest::NotUsedDate);
}
const uint32 MaxWeek = DateTime::Week::Saturday + 1;
uint32 week = acceptDate.GetDate().GetDayOfWeek();
for (uint32 i = 0; i < MaxWeek; ++i)
{
week = (week + 1) % MaxWeek;
if ((0x01 << week) & ResetWeekField) {
DateTime::Date returnDate(acceptDate.GetDate());
returnDate.SetCumulatedDay(i, true, acceptDate.GetDate());
return DateTime(returnDate, acceptDate.GetTime());
//return true;
}
}
return DateTime(XRated::Quest::NotUsedDate);
}
void QuestInfo::SetResetweek(const std::wstring& value, DateTime::Week::type day)
{
bool boolValue = false;
if ((!value.compare(L"1")) || (!value.compare(L"true")) || (!value.compare(L"TRUE")))
{
boolValue = true;
}
else if ((!value.compare(L"0")) || (!value.compare(L"false")) || (!value.compare(L"FALSE")))
{
boolValue = false;
}
else
{
throw Exception(L"Invalid value in Day of Week. ");
}
uint32 temp = 0xff ^ (0x01 << day); //11011111
uint32 temp2 = ResetWeekField & temp;
if (boolValue == false) ResetWeekField = temp2;
else
{
ResetWeekField = temp2 | (0x01 << day);
}
}
void QuestInfo::SetResetweek(bool sunday, bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday)
{
uint32 temp;
temp = temp & 0x00;
if (sunday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Sunday);
}
if (monday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Monday);
}
if (tuesday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Tuesday);
}
if (wednesday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Wednesday);
}
if (thursday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Thursday);
}
if (friday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Friday);
}
if (saturday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Saturday);
}
ResetWeekField = temp;
}
bool QuestInfo::IsResetday(DateTime::Week::type day) const
{
bool temp;
if ((ResetWeekField & (0x01 << day))) { temp = true; }
else { temp = false; }
return temp;
}
void ClientQuestInfo::AcceptEvent::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::AcceptEvent");
out.Write(L"Type", Type);
out.Write(L"Param_1", Param_1);
out.Write(L"Param_2", Param_2);
out.Write(L"Param_3", Param_3);
}
void ClientQuestInfo::AcceptEvent::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::AcceptEvent");
in.Read(L"Type", Type);
in.Read(L"Param_1", Param_1);
in.Read(L"Param_2", Param_2);
in.Read(L"Param_3", Param_3);
}
void ClientQuestInfo::SuccessEvent::Serialize(Serializer::IStreamWriter& out) const///by kpongky( 09.07.09 ) BMS 6691
{
out.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::SuccessEvent");
out.Write(L"Type", Type);
out.Write(L"Param_1", Param_1);
out.Write(L"Param_2", Param_2);///by kpongky( 09.07.10 ) BMS 6691
}
void ClientQuestInfo::SuccessEvent::Deserialize(Serializer::IStreamReader& in)///by kpongky( 09.07.09 ) BMS 6691
{
in.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::SuccessEvent");
in.Read(L"Type", Type);
in.Read(L"Param_1", Param_1);
in.Read(L"Param_2", Param_2);///by kpongky( 09.07.10 ) BMS 6691
}
//////////////////////////////////////////////////////////////////////////////////////////////
// ClientQuestInfo
void ClientQuestInfo::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo");
out.Write(L"Type", Type);
out.Write(L"ShortComment", ShortComment);
out.Write(L"MainTopic", MainTopic);
out.Write(L"Category", Category);
out.Write(L"DisplayName", DisplayName);
out.Write(L"BeginDescription", BeginDescription);
out.Write(L"EndDescription", EndDescription);
out.Write(L"ClearConditionDescription", ClearConditionDescription);
out.Write(L"AcceptInfo", AcceptInfo);
out.Write(L"FlashPath", FlashPath);
out.Write(L"ShowNextQuest", ShowNextQuest);
out.Write(L"ShowNoticeArrow", ShowNoticeArrow);
out.Write(L"AutomaticAddQuestProgress", AutomaticAddQuestProgress);
//out.Write(L"ShowAutomaticAddQuestProgressExplain", ShowAutomaticAddQuestProgressExplain);
out.Write(L"ShowAddQuickSlotItemExplain", ShowAddQuickSlotItemExplain);
out.Write(L"QuestAcceptEvent", QuestAcceptEvent);
out.Write(L"QuestSuccessEvent", QuestSuccessEvent);
out.Write(L"Tags", Tags);
}
void ClientQuestInfo::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo");
in.Read(L"Type", Type);
in.Read(L"ShortComment", ShortComment);
in.Read(L"MainTopic", MainTopic);
in.Read(L"Category", Category);
in.Read(L"DisplayName", DisplayName);
in.Read(L"BeginDescription", BeginDescription);
in.Read(L"EndDescription", EndDescription);
in.Read(L"ClearConditionDescription", ClearConditionDescription);
in.Read(L"AcceptInfo", AcceptInfo, std::wstring());
in.Read(L"FlashPath", FlashPath);
in.Read(L"ShowNextQuest", ShowNextQuest, false);
in.Read(L"ShowNoticeArrow", ShowNoticeArrow, false);
in.Read(L"AutomaticAddQuestProgress", AutomaticAddQuestProgress, false);
//in.Read(L"ShowAutomaticAddQuestProgressExplain", ShowAutomaticAddQuestProgressExplain, false);
in.Read(L"ShowAddQuickSlotItemExplain", ShowAddQuickSlotItemExplain, false);
in.Read(L"QuestAcceptEvent", QuestAcceptEvent, AcceptEvent());
in.Read(L"QuestSuccessEvent", QuestSuccessEvent, SuccessEvent());
in.Read(L"Tags", Tags, std::vector< std::wstring >());
}
}
}
}
} | 35.348684 | 149 | 0.640238 | Teles1 |
98daca3368b733539d9fab918f657c1c1c477cf7 | 1,015 | cpp | C++ | p173_Binary_Search_Tree_Iterator/p173.cpp | Song1996/Leetcode | ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb | [
"MIT"
] | null | null | null | p173_Binary_Search_Tree_Iterator/p173.cpp | Song1996/Leetcode | ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb | [
"MIT"
] | null | null | null | p173_Binary_Search_Tree_Iterator/p173.cpp | Song1996/Leetcode | ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <vector>
#include <stack>
#include <map>
#include <string>
#include <assert.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
public:
TreeNode* ans;
TreeNode* r;
BSTIterator(TreeNode *root) {
r = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(r==NULL) return false;
if(r->left==NULL) {
ans = r;
r = r->right;
return true;
}
TreeNode* par = r;
ans = par->left;
while(ans->left!=NULL) {
par = ans;
ans = ans->left;
}
par->left = ans->right;
return true;
}
/** @return the next smallest number */
int next() {
return ans->val;
}
};
int main () {
return 0;
} | 19.150943 | 57 | 0.529064 | Song1996 |
98dd474cc006efd11bf59e94f1eefd4b99d8da0c | 1,818 | cpp | C++ | Graph/GetPath_BFS.cpp | ayushhsinghh/DSASolutions | f898b35484b86519f73fdca969f7d579be98804e | [
"MIT"
] | null | null | null | Graph/GetPath_BFS.cpp | ayushhsinghh/DSASolutions | f898b35484b86519f73fdca969f7d579be98804e | [
"MIT"
] | null | null | null | Graph/GetPath_BFS.cpp | ayushhsinghh/DSASolutions | f898b35484b86519f73fdca969f7d579be98804e | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<utility>
#include<map>
using namespace std;
vector<int> getPath(int **edges , int nVertex , int start , int end){
bool *visited = new bool[nVertex];
for(int i = 0 ; i < nVertex ; i++){
visited[i] = false;
}
map<int , int> mpp;
queue<int> q;
bool found = false;
vector<int> ans;
q.push(start);
while(q.size() != 0){
int front = q.front();
if(front == end){
found = true;
break;
}
visited[front] = true;
q.pop();
for(int i = 0 ; i<nVertex ; i++){
if(i==0){
continue;
}
if(visited[i]){
continue;
}
if(edges[i][front] == 1){
q.push(i);
mpp[i] = front;
}
}
}
if(found){
ans.push_back(end);
while(end != start){
ans.push_back(mpp[end]);
end = mpp[end];
}
}
return ans;
}
int main(){
int nVertex , nEdge;
cout<<"Enter no of Vertex ";
cin>>nVertex;
cout<< "Enter no of Edge ";
cin>>nEdge;
int **edges = new int*[nVertex];
for(int i = 0 ; i < nVertex ; i++){
edges[i] = new int[nVertex];
for(int j = 0 ; j<nVertex ;++j){
edges[i][j] = 0;
}
}
for(int i = 0 ; i < nEdge ; i++){
int fVertex , sVertex;
cout<<"Enter"<<i<<"th Edge ";
cin>>fVertex>>sVertex;
edges[fVertex][sVertex] = 1;
edges[sVertex][fVertex] = 1;
}
int start = 2;
int end = 5;
vector<int> ans = getPath(edges , nVertex , start , end);
if(ans.size() == 0) cout<<"No Path";
for(int it: ans){
cout<<it<<" ";
}
return 0;
} | 20.659091 | 69 | 0.459296 | ayushhsinghh |
98e287c837bad8a95e763c62d94662568007a21f | 10,774 | cpp | C++ | production/libs/fog/Fog/Src/Fog/Core/Math/Solve_Polynomial_Analytic.cpp | Lewerow/DetailIdentifier | bd5e0b3b55b5ce5b24db51ae45ed53298d331687 | [
"MIT"
] | null | null | null | production/libs/fog/Fog/Src/Fog/Core/Math/Solve_Polynomial_Analytic.cpp | Lewerow/DetailIdentifier | bd5e0b3b55b5ce5b24db51ae45ed53298d331687 | [
"MIT"
] | null | null | null | production/libs/fog/Fog/Src/Fog/Core/Math/Solve_Polynomial_Analytic.cpp | Lewerow/DetailIdentifier | bd5e0b3b55b5ce5b24db51ae45ed53298d331687 | [
"MIT"
] | null | null | null | // [Fog-Core]
//
// [License]
// MIT, See COPYING file in package
// [Precompiled Headers]
#if defined(FOG_PRECOMP)
#include FOG_PRECOMP
#endif // FOG_PRECOMP
// [Dependencies]
#include <Fog/Core/Global/Init_p.h>
#include <Fog/Core/Global/Private.h>
#include <Fog/Core/Math/Fuzzy.h>
#include <Fog/Core/Math/Math.h>
#include <Fog/Core/Math/Solve.h>
#include <Fog/Core/Tools/Swap.h>
namespace Fog {
// ============================================================================
// [Fog::SolvePolynomialA - Constant]
// ============================================================================
template<typename NumT>
static int FOG_CDECL MathT_solvePolynomialA_Constant(NumT* dst, const NumT* polynomial, const NumT_(Interval)* interval)
{
FOG_UNUSED(dst);
FOG_UNUSED(polynomial);
FOG_UNUSED(interval);
return 0;
}
// ============================================================================
// [Fog::SolvePolynomialA - Linear]
// ============================================================================
// x = -b / a.
template<typename NumT>
static int FOG_CDECL MathT_solvePolynomialA_Linear(NumT* dst, const NumT* polynomial, const NumT_(Interval)* interval)
{
double a = double(polynomial[0]);
double b = double(polynomial[1]);
if (Math::isFuzzyZero(a))
return 0;
NumT x = NumT(-b / a);
if (interval != NULL)
{
if (x < interval->getMin() || x > interval->getMax())
return 0;
}
*dst = x;
return 1;
}
// ============================================================================
// [Fog::SolvePolynomialA - Quadratic]
// ============================================================================
// I found one message on stackoverflow forum which noted that the standard
// equation to solve the quadratic function may be inaccurate. It's
// completely correct so I kept the message also here for developers who
// want to better understand the problem.
//
// URL to the problem:
//
// http://stackoverflow.com/questions/4503849/quadratic-equation-in-ada/4504415#4504415
//
// The standard equation:
//
// x0 = (-b + sqrt(delta)) / 2a
// x1 = (-b - sqrt(delta)) / 2a
//
// When 4*a*c < b*b, computing x0 involves substracting close numbers, and
// makes you lose accuracy, so you use the following instead:
//
// x0 = 2c / (-b - sqrt(delta))
// x1 = 2c / (-b + sqrt(delta))
//
// Which yields a better x0, but whose x1 has the same problem as x0 had
// above. The correct way to compute the roots is therefore:
//
// q = -0.5 * (b + sign(b) * sqrt(delta))
// x0 = q / a
// x1 = c / q
template<typename NumT>
static int FOG_CDECL MathT_solvePolynomialA_Quadratic(NumT* dst, const NumT* polynomial, const NumT_(Interval)* interval)
{
double a = double(polynomial[0]);
double b = double(polynomial[1]);
double c = double(polynomial[2]);
// Catch the A and B near zero.
if (Math::isFuzzyZero(a))
{
// A~=0 && B~=0.
if (Math::isFuzzyZero(b))
return 0;
NumT x0 = NumT(-c / b);
if (interval != NULL && (x0 < interval->getMin() || x0 > interval->getMax()))
return 0;
dst[0] = x0;
return 1;
}
else
{
// The proposed solution.
double d = b * b - 4.0 * a * c;
if (d < 0.0)
return 0;
// D~=0
if (Math::isFuzzyPositiveZero(d))
{
// D~=0 && B~=0.
if (Math::isFuzzyZero(b))
return 0;
NumT x0 = NumT(-c / b);
if (interval != NULL && (x0 < interval->getMin() || x0 > interval->getMax()))
return 0;
dst[0] = x0;
return 1;
}
else
{
double s = Math::sqrt(d);
double q = -0.5 * (b + ((b < 0.0) ? -s : s));
NumT x0 = NumT(q / a);
NumT x1 = NumT(c / q);
// Sort.
if (x0 > x1)
swap(x0, x1);
if (interval != NULL)
{
NumT tMin = interval->getMin();
NumT tMax = interval->getMax();
int roots = 0;
if (x0 >= tMin && x0 <= tMax)
dst[roots++] = x0;
if (x1 >= tMin && x1 <= tMax)
dst[roots++] = x1;
return roots;
}
else
{
dst[0] = x0;
dst[1] = x1;
return 2;
}
}
}
}
// ============================================================================
// [Fog::SolvePolynomialA - Cubic]
// ============================================================================
// Roots3And4.c: Graphics Gems, original author Jochen Schwarze (schwarze@isa.de).
// See also the wiki article at http://en.wikipedia.org/wiki/Cubic_function for
// other equations.
template<typename NumT>
static int FOG_CDECL MathT_solvePolynomialA_Cubic(NumT* dst, const NumT* polynomial, const NumT_(Interval)* interval)
{
int roots = 0;
static const double _2_DIV_27 = 2.0 / 27.0;
if (polynomial[0] == NumT(0.0))
return Math::solvePolynomial(dst, polynomial + 1, MATH_POLYNOMIAL_DEGREE_QUADRATIC, interval);
// Convert to a normal form: x^3 + Ax^2 + Bx + C == 0.
double _norm = (double)polynomial[0];
double a = (double)polynomial[1] / _norm;
double b = (double)polynomial[2] / _norm;
double c = (double)polynomial[3] / _norm;
// Substitute x = y - A/3 to eliminate quadric term:
//
// x^3 + px + q = 0
double sa = a * a;
double p = -MATH_1_DIV_9 * sa + MATH_1_DIV_3 * b;
double q = 0.5 * ((_2_DIV_27 * sa - MATH_1_DIV_3 * b) * a + c);
// Use Cardano's formula.
double p3 = p * p * p;
double d = q * q + p3;
// Resubstitution constant.
double sub = -MATH_1_DIV_3 * a;
if (Math::isFuzzyZero(d))
{
// One triple solution.
if (Math::isFuzzyZero(q))
{
roots = 1;
dst[0] = NumT(sub);
}
// One single and one double solution.
else
{
double u = Math::cbrt(-q);
roots = 2;
dst[0] = NumT(sub + 2.0 * u);
dst[1] = NumT(sub - u );
// Sort.
if (dst[0] > dst[1])
swap(dst[0], dst[1]);
}
}
// Three real solutions.
else if (d < 0.0)
{
double phi = MATH_1_DIV_3 * Math::acos(-q / Math::sqrt(-p3));
double t = 2.0 * sqrt(-p);
roots = 3;
dst[0] = NumT(sub + t * Math::cos(phi ));
dst[1] = NumT(sub - t * Math::cos(phi + MATH_THIRD_PI));
dst[2] = NumT(sub - t * Math::cos(phi - MATH_THIRD_PI));
// Sort.
if (dst[0] > dst[1])
swap(dst[0], dst[1]);
if (dst[1] > dst[2])
swap(dst[1], dst[2]);
if (dst[0] > dst[1])
swap(dst[0], dst[1]);
}
// One real solution.
else
{
double sqrt_d = sqrt(d);
double u = Math::cbrt(sqrt_d - q);
double v = -Math::cbrt(sqrt_d + q);
roots = 1;
dst[0] = NumT(sub + u + v);
}
if (interval != NULL)
{
NumT tMin = interval->getMin();
NumT tMax = interval->getMax();
int interestingRoots = 0;
for (int i = 0; i < roots; i++)
{
if (dst[i] < tMin || dst[i] > tMax)
continue;
dst[interestingRoots++] = dst[i];
}
return interestingRoots;
}
return roots;
}
// ============================================================================
// [Fog::SolvePolynomialA - Quartic]
// ============================================================================
template<typename NumT>
static int FOG_CDECL MathT_solvePolynomialA_Quartic(NumT* dst, const NumT* polynomial, const NumT_(Interval)* interval)
{
if (Math::isFuzzyZero(polynomial[0]))
Math::solvePolynomial(dst, polynomial + 1, MATH_POLYNOMIAL_DEGREE_CUBIC);
double _norm = polynomial[0];
double a = double(polynomial[1]) / _norm;
double b = double(polynomial[2]) / _norm;
double c = double(polynomial[3]) / _norm;
double d = double(polynomial[4]) / _norm;
double _aa = a * a;
double _2b = b * 2.0;
double _cc = c * c;
double _4d = d * 4.0;
double base = a * (-0.25);
double q0 = _aa * 0.75 - _2b;
double q1;
{
double cFunction[4];
double cRoots[4];
cFunction[0] = 1.0;
cFunction[1] =-b;
cFunction[2] =-_4d + a * c;
cFunction[3] = _4d * b - _cc - _aa * d;
uint cRootsCount = Math::solvePolynomial(cRoots, cFunction, MATH_POLYNOMIAL_DEGREE_CUBIC);
if (cRootsCount == 0)
return 0;
double x = cRoots[cRootsCount - 1];
double w = _aa * 0.25 - b + x;
if (w > MATH_EPSILON_D)
{
double r = Math::sqrt(w);
base += 0.5 * r;
q0 -= w;
w = (a * (b - _aa * 0.25) - c * 2.0) / r;
}
else
{
w = 2.0 * Math::sqrt(x * x - _4d);
}
q1 = q0 + w;
q0 = q0 - w;
if (q0 < 0.0 || (q0 > q1 && q1 >= 0.0))
swap(q0, q1);
}
int roots = 0;
if (q0 >= 0.0)
{
double v = Math::sqrt(q0) * 0.5;
if (v >= MATH_EPSILON_D)
{
dst[roots++] = NumT(base - v);
dst[roots++] = NumT(base + v);
}
else
{
dst[roots++] = NumT(base);
}
}
if (q1 >= 0.0 && !Math::isFuzzyEq(q0, q1))
{
double v = Math::sqrt(q1) * 0.5;
if (roots == 2)
dst[2] = dst[1];
dst[1] = dst[0];
roots++;
if (v >= MATH_EPSILON_D)
{
dst[0] = NumT(base - v);
dst[roots++] = NumT(base + v);
}
else
{
dst[0] = NumT(base);
}
}
if (interval != NULL)
{
NumT tMin = interval->getMin();
NumT tMax = interval->getMax();
int interestingRoots = 0;
for (int i = 0; i < roots; i++)
{
if (dst[i] < tMin || dst[i] > tMax)
continue;
dst[interestingRoots++] = dst[i];
}
return interestingRoots;
}
return roots;
}
// ============================================================================
// [Init / Fini]
// ============================================================================
FOG_NO_EXPORT void Math_init_solvePolynomialAnalytic(void)
{
fog_api.mathf_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_NONE ] = MathT_solvePolynomialA_Constant <float>;
fog_api.mathf_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_LINEAR ] = MathT_solvePolynomialA_Linear <float>;
fog_api.mathf_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_QUADRATIC] = MathT_solvePolynomialA_Quadratic<float>;
fog_api.mathf_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_CUBIC ] = MathT_solvePolynomialA_Cubic <float>;
fog_api.mathf_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_QUARTIC ] = MathT_solvePolynomialA_Quartic <float>;
fog_api.mathd_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_NONE ] = MathT_solvePolynomialA_Constant <double>;
fog_api.mathd_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_LINEAR ] = MathT_solvePolynomialA_Linear <double>;
fog_api.mathd_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_QUADRATIC] = MathT_solvePolynomialA_Quadratic<double>;
fog_api.mathd_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_CUBIC ] = MathT_solvePolynomialA_Cubic <double>;
fog_api.mathd_solvePolynomialA[MATH_POLYNOMIAL_DEGREE_QUARTIC ] = MathT_solvePolynomialA_Quartic <double>;
}
} // Fog namespace
| 26.278049 | 121 | 0.542417 | Lewerow |
98e43dc5cec0add6ee5418aa39dc5042224c1779 | 871 | hpp | C++ | test/mock/core/consensus/grandpa/chain_mock.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | test/mock/core/consensus/grandpa/chain_mock.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | test/mock/core/consensus/grandpa/chain_mock.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_TEST_MOCK_CORE_CONSENSUS_GRANDPA_CHAIN_MOCK_HPP
#define KAGOME_TEST_MOCK_CORE_CONSENSUS_GRANDPA_CHAIN_MOCK_HPP
#include <gmock/gmock.h>
#include "consensus/grandpa/chain.hpp"
namespace kagome::consensus::grandpa {
struct ChainMock : public Chain {
~ChainMock() override = default;
MOCK_CONST_METHOD2(getAncestry,
outcome::result<std::vector<primitives::BlockHash>>(
const primitives::BlockHash &base,
const BlockHash &block));
MOCK_CONST_METHOD1(bestChainContaining,
outcome::result<BlockInfo>(const BlockHash &base));
};
} // namespace kagome::consensus::grandpa
#endif // KAGOME_TEST_MOCK_CORE_CONSENSUS_GRANDPA_CHAIN_MOCK_HPP
| 30.034483 | 75 | 0.692308 | FlorianFranzen |
98e486358337d37f335709045df2b528399ecccc | 3,511 | hpp | C++ | sdk/cpp/core/src/netconf_provider.hpp | YDK-Solutions/ydk | 7ab961284cdc82de8828e53fa4870d3204d7730e | [
"ECL-2.0",
"Apache-2.0"
] | 125 | 2016-03-15T17:04:13.000Z | 2022-03-22T02:46:17.000Z | sdk/cpp/core/src/netconf_provider.hpp | YDK-Solutions/ydk | 7ab961284cdc82de8828e53fa4870d3204d7730e | [
"ECL-2.0",
"Apache-2.0"
] | 818 | 2016-03-17T17:06:00.000Z | 2022-03-28T03:56:17.000Z | sdk/cpp/core/src/netconf_provider.hpp | YDK-Solutions/ydk | 7ab961284cdc82de8828e53fa4870d3204d7730e | [
"ECL-2.0",
"Apache-2.0"
] | 93 | 2016-03-15T19:18:55.000Z | 2022-02-24T13:55:07.000Z | /* ----------------------------------------------------------------
Copyright 2016 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------*/
#ifndef _NETCONF_PROVIDER_H_
#define _NETCONF_PROVIDER_H_
#include <memory>
#include <string>
#include "netconf_client.hpp"
#include "path_api.hpp"
#include "service_provider.hpp"
namespace ydk {
class NetconfServiceProvider : public ServiceProvider {
public:
NetconfServiceProvider(path::Repository & repo,
const std::string& address,
const std::string& username,
const std::string& password,
int port = 830,
const std::string& protocol = "ssh",
bool on_demand = true,
int timeout = -1);
NetconfServiceProvider(const std::string& address,
const std::string& username,
const std::string& password,
int port = 830,
const std::string& protocol = "ssh",
bool on_demand = true,
bool common_cache = false,
int timeout = -1);
NetconfServiceProvider(path::Repository& repo,
const std::string& address,
const std::string& username,
const std::string& private_key_path,
const std::string& public_key_path,
int port = 830,
bool on_demand = true,
int timeout = -1);
NetconfServiceProvider(const std::string& address,
const std::string& username,
const std::string& private_key_path,
const std::string& public_key_path,
int port = 830,
bool on_demand = true,
bool common_cache = false,
int timeout = -1);
~NetconfServiceProvider();
EncodingFormat get_encoding() const;
const path::Session& get_session() const;
std::vector<std::string> get_capabilities() const;
inline const std::string get_provider_type() const {
return "NetconfServiceProvider";
}
std::shared_ptr<Entity> execute_operation(const std::string & operation, Entity & entity, std::map<std::string,std::string> params);
std::vector<std::shared_ptr<Entity>> execute_operation(const std::string & operation, std::vector<Entity*> entity_list, std::map<std::string,std::string> params);
private:
const path::NetconfSession session;
};
}
#endif /*_NETCONF_PROVIDER_H_*/
| 42.817073 | 170 | 0.522928 | YDK-Solutions |
98e6387f57e12ab0a0cd9d3adaba20e2137c9c5a | 297 | cpp | C++ | src/Support/ContextTransition.cpp | G-o-T-o/CircuitOS | 383bd4794b4f3f55f8249d602f1f7bd10b336a84 | [
"MIT"
] | 14 | 2020-03-22T13:21:46.000Z | 2021-12-10T04:28:44.000Z | src/Support/ContextTransition.cpp | G-o-T-o/CircuitOS | 383bd4794b4f3f55f8249d602f1f7bd10b336a84 | [
"MIT"
] | 5 | 2020-04-14T19:35:16.000Z | 2021-08-30T03:02:36.000Z | src/Support/ContextTransition.cpp | G-o-T-o/CircuitOS | 383bd4794b4f3f55f8249d602f1f7bd10b336a84 | [
"MIT"
] | 5 | 2021-02-10T09:02:43.000Z | 2021-08-24T04:56:04.000Z | #include "../../Setup.hpp"
#include "ContextTransition.h"
bool ContextTransition::transitionRunning = false;
bool ContextTransition::isRunning(){
return transitionRunning;
}
#ifdef CIRCUITOS_LOWRAM
#include "LowRamContextTransition.impl"
#else
#include "StandardContextTransition.impl"
#endif | 22.846154 | 50 | 0.794613 | G-o-T-o |
98e691599abd777f53fa861969a4e6c64dec5037 | 790 | cpp | C++ | src/cxx11-detection-idiom.cpp | mariokonrad/cppug-sfinae-concepts | aeb633261d15fe5f63bf36c79e30247c8db88cfc | [
"CC-BY-4.0"
] | null | null | null | src/cxx11-detection-idiom.cpp | mariokonrad/cppug-sfinae-concepts | aeb633261d15fe5f63bf36c79e30247c8db88cfc | [
"CC-BY-4.0"
] | null | null | null | src/cxx11-detection-idiom.cpp | mariokonrad/cppug-sfinae-concepts | aeb633261d15fe5f63bf36c79e30247c8db88cfc | [
"CC-BY-4.0"
] | 1 | 2019-05-29T05:08:30.000Z | 2019-05-29T05:08:30.000Z | #include <iostream>
#include <type_traits>
namespace cxx11_detection_idom
{
template <class T>
struct has_add
{
template <class U>
static constexpr decltype(std::declval<U>().add(int(), int()), bool()) test(int)
{ return true; }
template <class U>
static constexpr bool test(...)
{ return false; }
static constexpr bool value = test<T>(int());
};
template <class T, typename std::enable_if<has_add<T>::value, int>::type = 0>
void func(T t, int a, int b)
{ std::cout << __PRETTY_FUNCTION__ << ": " << t.add(a, b) << '\n'; }
}
struct foo { int add(int a, int b) { return a + b; } };
struct bar { int sub(int a, int b) { return a - b; } };
int main(int, char **)
{
//cxx11_detection_idom::func(bar(), 1, 2); // ERROR
cxx11_detection_idom::func(foo(), 1, 2); // OK
return 0;
}
| 22.571429 | 81 | 0.634177 | mariokonrad |
98e71ba74173ebce8c049d3fc3b1191557f7db94 | 4,923 | cpp | C++ | src/Utils/Utils.cpp | district10/learning-opencv | 485c1b632fab8522646f93f5ace19664c4ecfb7e | [
"MIT"
] | null | null | null | src/Utils/Utils.cpp | district10/learning-opencv | 485c1b632fab8522646f93f5ace19664c4ecfb7e | [
"MIT"
] | null | null | null | src/Utils/Utils.cpp | district10/learning-opencv | 485c1b632fab8522646f93f5ace19664c4ecfb7e | [
"MIT"
] | null | null | null | #include "Utils.h"
#include <QImage>
#include <QDebug>
#include <vector>
#include <cv.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "Configs.h"
#ifndef DEFAULT_INPUT_IMAGE_DIR
#define DEFAULT_INPUT_IMAGE_DIR ""
#endif
using namespace cv;
cv::RNG Utils::rng(12345);
// from: http://blog.csdn.net/liyuanbhu/article/details/46662115
QImage Utils::cvMat2QImage(const cv::Mat& mat)
{
// 8-bits unsigned, NO. OF CHANNELS = 1
if(mat.type() == CV_8UC1) {
QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
// Set the color table (used to translate colour indexes to qRgb values)
image.setColorCount(256);
for(int i = 0; i < 256; i++) {
image.setColor(i, qRgb(i, i, i));
}
// Copy input Mat
uchar *pSrc = mat.data;
for(int row = 0; row < mat.rows; row ++) {
uchar *pDest = image.scanLine(row);
memcpy(pDest, pSrc, mat.cols);
pSrc += mat.step;
}
return image;
} else if(mat.type() == CV_8UC3) {
// 8-bits unsigned, NO. OF CHANNELS = 3
// Copy input Mat
const uchar *pSrc = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
return image.rgbSwapped();
} else if(mat.type() == CV_8UC4) {
qDebug() << "CV_8UC4";
// Copy input Mat
const uchar *pSrc = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
return image.copy();
} else {
qDebug() << "ERROR: Mat could not be converted to QImage.";
return QImage();
}
}
// from: http://blog.csdn.net/liyuanbhu/article/details/46662115
cv::Mat Utils::QImage2cvMat( const QImage &image )
{
cv::Mat mat;
qDebug() << image.format();
switch(image.format()) {
case QImage::Format_ARGB32:
case QImage::Format_RGB32:
case QImage::Format_ARGB32_Premultiplied:
mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());
break;
case QImage::Format_RGB888:
mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());
cv::cvtColor(mat, mat, CV_BGR2RGB);
break;
case QImage::Format_Indexed8:
mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
break;
}
return mat;
}
// based on LU XiaoHu's code
void Utils::drawContours( const cv::Mat &src, cv::Mat &dst, int step /* = 32 */ )
{
cv::Mat gray;
cvtColor( src, gray, cv::COLOR_RGB2GRAY );
int levelStep = step < 0 ? 10 : step > 255? 255 : step;
std::vector<std::vector<std::vector<cv::Point> > > levelLines; // all contours
int curLevel = levelStep;
while( curLevel <= 255 ) {
// gray mask
cv::Mat mask( gray.rows, gray.cols, CV_8UC1, cv::Scalar(0) );
uchar *ptrI = gray.data;
uchar *ptrM = mask.data;
int imgSize = gray.rows * gray.cols;
int count = 0;
for ( int i=0; i<imgSize; ++i ) {
if ( *ptrI < curLevel ) {
*ptrM = 255;
++count;
}
++ptrI;
++ptrM;
}
// static char filepath[1000];
// sprintf( filepath, "%s-mask-%03d.bmp", DATA_DIR "/lena", curLevel );
// cv::imwrite( filepath, mask );
// find contours on mask
std::vector<std::vector<cv::Point> > contours;
cv::findContours( mask, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );
levelLines.push_back( contours );
curLevel += levelStep;
}
vector<Vec4i> hierarchy;
for ( int i=0; i<levelLines.size(); ++i ) {
for ( int j=0; j<levelLines.at(i).size(); ++j ) {
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
cv::drawContours( dst, levelLines.at(i), j, color, 1, 8, hierarchy, 0, Point() );
}
}
/*
uchar *ptr = dst.data;
for ( int i=0; i<levelLines.size(); ++i ) {
// draw with random color
int R = rand() % 255;
int G = rand() % 255;
int B = rand() % 255;
for ( int j=0; j<levelLines[i].size(); ++j ) {
for ( int m=0; m<levelLines[i][j].size(); ++m ) {
int x = levelLines[i][j][m].x;
int y = levelLines[i][j][m].y;
int loc = y * dst.cols + x;
ptr[3*loc+0] = B;
ptr[3*loc+1] = G;
ptr[3*loc+2] = R;
}
}
}
*/
} | 31.356688 | 112 | 0.540727 | district10 |
98e8e9340270c099a7277cbb4a0848b58a2ce121 | 983 | hpp | C++ | Include/vtb/BuilderBase.hpp | cschladetsch/VulkanDemo | ea3ebd86f47c2d8f37b9eb790253e0a55284e943 | [
"MIT"
] | null | null | null | Include/vtb/BuilderBase.hpp | cschladetsch/VulkanDemo | ea3ebd86f47c2d8f37b9eb790253e0a55284e943 | [
"MIT"
] | null | null | null | Include/vtb/BuilderBase.hpp | cschladetsch/VulkanDemo | ea3ebd86f47c2d8f37b9eb790253e0a55284e943 | [
"MIT"
] | null | null | null | #pragma once
#include "Vulkan.hpp"
VTB_BEGIN
// Provides a `heap` that always increases in size, so that objects
// can be referenced by pointer across method calls without using the runtime heap.
// This is only suitable for PODs.
struct BuilderBase
{
protected:
BuilderBase(size_t size = heapSize_) : heap_(new char[size]), offset_(0) { }
~BuilderBase() { delete[] heap_; }
protected:
template <class Struct>
Struct &Alloc()
{
static_assert(std::is_pod<Struct>::value, "A must be a POD type.");
// we can't realloc because there may be external pointers to objects in
// our `heap`.
if (offset_ + sizeof(Struct) > heapSize_)
throw new std::bad_alloc();
auto top = offset_;
// TODO: alignment(?)
offset_ += sizeof(Struct);
return *reinterpret_cast<Struct *>(heap_ + top);
}
private:
static const size_t heapSize_ = 8000;
char *heap_;
size_t offset_;
};
VTB_END
| 23.97561 | 83 | 0.639878 | cschladetsch |
98e91a8fdf1b1ff993647939f3947f4b38b4af23 | 2,843 | cpp | C++ | GCanvas/core/src/support/Util.cpp | nicholasalx/GCanvas | b65dc955e62cad69b65cad35c1e7c920eaf9cdfd | [
"Apache-2.0"
] | 1 | 2019-08-29T07:30:19.000Z | 2019-08-29T07:30:19.000Z | GCanvas/core/src/support/Util.cpp | nicholasalx/GCanvas | b65dc955e62cad69b65cad35c1e7c920eaf9cdfd | [
"Apache-2.0"
] | null | null | null | GCanvas/core/src/support/Util.cpp | nicholasalx/GCanvas | b65dc955e62cad69b65cad35c1e7c920eaf9cdfd | [
"Apache-2.0"
] | null | null | null | /**
* Created by G-Canvas Open Source Team.
* Copyright (c) 2017, Alibaba, Inc. All rights reserved.
*
* This source code is licensed under the Apache Licence 2.0.
* For the full copyright and license information, please view
* the LICENSE file in the root directory of this source tree.
*/
#include "Util.h"
#include "Log.h"
#include <string.h>
#ifdef ANDROID
#include <linux/time.h>
#include <sys/time.h>
#include <semaphore.h>
#endif
namespace gcanvas
{
// flip the pixels by y axis
void FlipPixel(unsigned char *pixels, int w, int h)
{
// taken from example here:
// http://www.codesampler.com/2010/11/02/introduction-to-opengl-es-2-0/
// Flip and invert the PNG image since OpenGL likes to load everything
// backwards from what is considered normal!
int halfTheHeightInPixels = h / 2;
int heightInPixels = h;
// Assuming RGBA for 4 components per pixel.
int numColorComponents = 4;
// Assuming each color component is an unsigned char.
int widthInChars = w * numColorComponents;
unsigned char *top = nullptr;
unsigned char *bottom = nullptr;
unsigned char temp = 0;
for (int h = 0; h < halfTheHeightInPixels; ++h)
{
top = pixels + h * widthInChars;
bottom = pixels + (heightInPixels - h - 1) * widthInChars;
for (int w = 0; w < widthInChars; ++w)
{
// Swap the chars around.
temp = *top;
*top = *bottom;
*bottom = temp;
++top;
++bottom;
}
}
}
// get a part of pixel from rgba datas
void GetSegmentPixel(const unsigned char *srcPx, unsigned int sw,
unsigned int x, unsigned int y, unsigned int dw,
unsigned int dh, unsigned char *destPx)
{
srcPx += (sw * y + x) * 4;
for (unsigned int i = 0; i < dh; ++i)
{
memcpy(destPx, srcPx, dw * 4);
srcPx += sw * 4;
destPx += dw * 4;
}
}
bool IsSupportNeon() { return false; }
#ifdef ANDROID
void timeraddMS(struct timeval *a, uint ms)
{
a->tv_usec += ms * 1000;
if(a->tv_usec >= 1000000)
{
a->tv_sec += a->tv_usec / 1000000;
a->tv_usec %= 1000000;
}
}
void waitUtilTimeout(sem_t *sem,uint ms){
int ret;
struct timeval now;
struct timespec outtime;
gettimeofday(&now, NULL);
// LOG_D("start to wait,sec=%d,usec=%d\n",now.tv_sec,now.tv_usec);
timeraddMS(&now, ms);
outtime.tv_sec = now.tv_sec;
outtime.tv_nsec = now.tv_usec * 1000;
ret = sem_timedwait(sem,&outtime);
if (ret == -1)
{
gettimeofday(&now, NULL);
LOG_D("wait time out,sec=%d,usec=%d\n",now.tv_sec,now.tv_usec);
}
else
{
gettimeofday(&now, NULL);
// LOG_D("success wait response,sec=%d,usec=%d\n",now.tv_sec,now.tv_usec);
}
}
#endif
} | 25.159292 | 81 | 0.600422 | nicholasalx |
98edbef3d21fd3c0d7e5ce8b7e9aae68809cef84 | 349 | cpp | C++ | Recursion/Sort_a_stack.cpp | Razdeep/GeeksforGeeks | 32f471932f1c17eb538e0376d141a8fbf303cf55 | [
"MIT"
] | null | null | null | Recursion/Sort_a_stack.cpp | Razdeep/GeeksforGeeks | 32f471932f1c17eb538e0376d141a8fbf303cf55 | [
"MIT"
] | null | null | null | Recursion/Sort_a_stack.cpp | Razdeep/GeeksforGeeks | 32f471932f1c17eb538e0376d141a8fbf303cf55 | [
"MIT"
] | null | null | null | // https://practice.geeksforgeeks.org/problems/sort-a-stack/1
void SortedStack :: sort()
{
//Your code here
vector<int> arr;
while(int(this->s.size()))
{
arr.push_back(this->s.top());
this->s.pop();
}
std::sort(arr.begin(), arr.end());
for (int i = 0; i < int(arr.size()); ++i)
this->s.push(arr[i]);
}
| 23.266667 | 61 | 0.544413 | Razdeep |
98eeaee5dbb9d6687efcf9789bd08c67f5654c54 | 1,058 | hpp | C++ | makepad/ChakraCore/pal/src/include/pal/event.hpp | makepaddev/makepad | 25d2f18c8a7c190fd1b199762817b6514118e045 | [
"MIT"
] | 8,664 | 2016-01-13T17:33:19.000Z | 2019-05-06T19:55:36.000Z | makepad/ChakraCore/pal/src/include/pal/event.hpp | makepaddev/makepad | 25d2f18c8a7c190fd1b199762817b6514118e045 | [
"MIT"
] | 5,058 | 2016-01-13T17:57:02.000Z | 2019-05-04T15:41:54.000Z | makepad/ChakraCore/pal/src/include/pal/event.hpp | makepaddev/makepad | 25d2f18c8a7c190fd1b199762817b6514118e045 | [
"MIT"
] | 1,367 | 2016-01-13T17:54:57.000Z | 2019-04-29T18:16:27.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Module Name:
event.hpp
Abstract:
Event object structure definition.
--*/
#ifndef _PAL_EVENT_H_
#define _PAL_EVENT_H_
#include "corunix.hpp"
namespace CorUnix
{
extern CObjectType otManualResetEvent;
extern CObjectType otAutoResetEvent;
PAL_ERROR
InternalCreateEvent(
CPalThread *pThread,
LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset,
BOOL bInitialState,
LPCWSTR lpName,
HANDLE *phEvent
);
PAL_ERROR
InternalSetEvent(
CPalThread *pThread,
HANDLE hEvent,
BOOL fSetEvent
);
PAL_ERROR
InternalOpenEvent(
CPalThread *pThread,
DWORD dwDesiredAccess,
BOOL bInheritHandle,
LPCWSTR lpName,
HANDLE *phEvent
);
}
#endif //PAL_EVENT_H_
| 15.114286 | 71 | 0.646503 | makepaddev |
98eefbe0c57de60318f9579bd07ee5dfe66172c8 | 930 | hpp | C++ | source/quantum-script.lib/quantum-script-iterator.hpp | g-stefan/quantum-script | 479c7c9bc3831ecafa79071c40fa766985130b59 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script.lib/quantum-script-iterator.hpp | g-stefan/quantum-script | 479c7c9bc3831ecafa79071c40fa766985130b59 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script.lib/quantum-script-iterator.hpp | g-stefan/quantum-script | 479c7c9bc3831ecafa79071c40fa766985130b59 | [
"MIT",
"Unlicense"
] | null | null | null | //
// Quantum Script
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#ifndef QUANTUM_SCRIPT_ITERATOR_HPP
#define QUANTUM_SCRIPT_ITERATOR_HPP
#ifndef QUANTUM_SCRIPT_VARIABLE_HPP
#include "quantum-script-variable.hpp"
#endif
namespace Quantum {
namespace Script {
class Iterator;
};
};
namespace XYO {
namespace ManagedMemory {
template<>
class TMemory<Quantum::Script::Iterator>:
public TMemoryPoolActive<Quantum::Script::Iterator> {};
};
};
namespace Quantum {
namespace Script {
using namespace XYO;
class Iterator :
public virtual Object {
XYO_DISALLOW_COPY_ASSIGN_MOVE(Iterator);
public:
inline Iterator() {
};
QUANTUM_SCRIPT_EXPORT virtual bool next(Variable *out);
};
};
};
#endif
| 16.909091 | 63 | 0.673118 | g-stefan |
98f00cbc4f5031658cec1d50210652783d5be6fc | 10,343 | cpp | C++ | src/exactextract/test/test_raster_cell_intersection.cpp | dbaston/exactextractr | 15ec58e8b40d5ea84752e51d0b914376b5122d5d | [
"Apache-2.0"
] | null | null | null | src/exactextract/test/test_raster_cell_intersection.cpp | dbaston/exactextractr | 15ec58e8b40d5ea84752e51d0b914376b5122d5d | [
"Apache-2.0"
] | null | null | null | src/exactextract/test/test_raster_cell_intersection.cpp | dbaston/exactextractr | 15ec58e8b40d5ea84752e51d0b914376b5122d5d | [
"Apache-2.0"
] | null | null | null | #include <geos_c.h>
#include "catch.hpp"
#include "geos_utils.h"
#include "raster_cell_intersection.h"
using namespace exactextract;
void check_cell_intersections(const RasterCellIntersection & rci, const std::vector<std::vector<float>> & v) {
const Matrix<float>& actual = rci.overlap_areas();
Matrix<float> expected{v};
REQUIRE( expected.rows() == actual.rows() );
REQUIRE( expected.cols() == actual.cols() );
for (size_t i = 0; i < expected.rows(); i++) {
for (size_t j = 0; j < expected.cols(); j++) {
CHECK ( actual(i, j) == expected(i, j) );
}
}
}
static void init_geos() {
static bool initialized = false;
if (!initialized) {
initGEOS(nullptr, nullptr);
initialized = true;
}
}
TEST_CASE("Basic", "[raster-cell-intersection]" ) {
init_geos();
Extent ex{0, 0, 3, 3, 1, 1}; // 3x3 grid
auto g = GEOSGeom_read("POLYGON ((0.5 0.5, 2.5 0.5, 2.5 2.5, 0.5 2.5, 0.5 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.25},
{0.50, 1.0, 0.50},
{0.25, 0.5, 0.25}
});
}
TEST_CASE("Diagonals", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 3, 1, 1}; // 3x3 grid
auto g = GEOSGeom_read("POLYGON ((1.5 0.5, 2.5 1.5, 1.5 2.5, 0.5 1.5, 1.5 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.00, 0.25, 0.00},
{0.25, 1.00, 0.25},
{0.00, 0.25, 0.00},
});
}
TEST_CASE("Starting on cell boundary", "[raster-cell-intersection]") {
init_geos();
// Situation found in Canada using 0.5-degree global grid
Extent ex{0, 0, 2, 2, 1, 1}; // 2x2 grid
auto g = GEOSGeom_read("POLYGON ((1 1.5, 1.5 1.5, 1.5 0.5, 0.5 0.5, 0.5 1.5, 1 1.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.25},
{0.25, 0.25},
});
}
TEST_CASE("Bouncing off boundary", "[raster-cell-intersection]") {
init_geos();
// Situation found in Trinidad and Tobago using 0.5-degree global grid
Extent ex{0, -1, 2, 2, 1, 1}; // 3x2 grid
auto g = GEOSGeom_read("POLYGON ((0.5 1.5, 0.5 0.5, 0.5 0, 1.5 0.5, 1.5 1.5, 0.5 1.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.25},
{0.4375, 0.3125},
{0.0, 0.0},
});
}
TEST_CASE("Bouncing off boundary (2)", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 2, 2, 1, 1};
auto g = GEOSGeom_read("POLYGON ((0.5 0.5, 1.5 0.5, 1.5 1.5, 0.5 1.5, 1 1.2, 0.5 0.5))");
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
TEST_CASE("Follows grid boundary", "[raster-cell-intersection]") {
init_geos();
// Occurs on the Libya-Egypt border, for example
Extent ex{0, 0, 3, 3, 1, 1};
auto g = GEOSGeom_read("POLYGON ((0.5 0.5, 2 0.5, 2 1.5, 2 2.5, 0.5 2.5, 0.5 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.0},
{0.50, 1.0, 0.0},
{0.25, 0.5, 0.0},
});
}
TEST_CASE("Starts on vertical boundary, moving up", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 4, 3, 1, 1}; // 4x3 grid
auto g = GEOSGeom_read("POLYGON ((3 0.5, 3 2.5, 0.5 2.5, 0.5 0.5, 3 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.5, 0.0},
{0.50, 1.0, 1.0, 0.0},
{0.25, 0.5, 0.5, 0.0},
});
}
TEST_CASE("Starts on vertical boundary, moving down", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 4, 3, 1, 1}; // 4x3 grid
auto g = GEOSGeom_read("POLYGON ((0.5 2.5, 0.5 0.5, 3 0.5, 3 2.5, 0.5 2.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.5, 0.0},
{0.50, 1.0, 1.0, 0.0},
{0.25, 0.5, 0.5, 0.0},
});
}
TEST_CASE("Starts on vertical boundary, moving down at rightmost extent of grid", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 3, 1, 1}; // 3x3 grid
auto g = GEOSGeom_read("POLYGON ((3 2.5, 3 0.5, 0.5 0.5, 0.5 2.5, 3 2.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.5},
{0.50, 1.0, 1.0},
{0.25, 0.5, 0.5},
});
}
TEST_CASE("Starts on horizontal boundary, moving right", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 4, 1, 1}; // 3x4 grid
auto g = GEOSGeom_read("POLYGON ((0.5 1, 2.5 1, 2.5 3.5, 0.5 3.5, 0.5 1))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.25},
{0.50, 1.0, 0.50},
{0.50, 1.0, 0.50},
{0.00, 0.0, 0.00},
});
}
TEST_CASE("Starts on horizontal boundary, moving left", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 4, 1, 1}; // 3x4 grid
auto g = GEOSGeom_read("POLYGON ((2.5 3, 0.5 3, 0.5 3.5, 0.25 3.5, 0.25 0.5, 2.5 0.5, 2.5 3))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.125, 0.00, 0.00},
{0.750, 1.00, 0.50},
{0.750, 1.00, 0.50},
{0.375, 0.50, 0.25},
});
}
TEST_CASE("Regression test - Fiji", "[raster-cell-intersection]") {
init_geos();
// Just make sure this polygon doesn't throw an exception. It caused some problems where the
// rightmost edge was interpreted to be exactly on a cell wall.
Extent ex{-180.5, -90.5, 180.5, 90.5, 0.5, 0.5};
auto g = GEOSGeom_read("MULTIPOLYGON (((178.3736000000001 -17.33992000000002, 178.71806000000007 -17.62845999999996, 178.5527099999999 -18.150590000000008, 177.93266000000008 -18.287990000000036, 177.38145999999992 -18.164319999999975, 177.28504000000007 -17.72464999999997, 177.67087 -17.381139999999974, 178.12557000000007 -17.50480999999995, 178.3736000000001 -17.33992000000002)), ((179.36414266196417 -16.801354076946836, 178.7250593629972 -17.012041674368007, 178.5968385951172 -16.63915000000003, 179.0966093629972 -16.43398427754741, 179.4135093629972 -16.379054277547382, 180.00000000000003 -16.06713266364241, 180.00000000000003 -16.555216566639146, 179.36414266196417 -16.801354076946836)), ((-179.91736938476527 -16.501783135649347, -179.99999999999997 -16.555216566639146, -179.99999999999997 -16.06713266364241, -179.79332010904858 -16.020882256741217, -179.91736938476527 -16.501783135649347)))");
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
TEST_CASE("Small polygon", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 10, 10, 10, 10}; // Single cell
auto g = GEOSGeom_read("POLYGON ((3 3, 4 3, 4 4, 3 4, 3 3))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {{0.01}});
}
TEST_CASE("Fill handled correctly", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 5, 1, 1}; // 3x5 grid
auto g = GEOSGeom_read("POLYGON ((0.5 0.2, 2.2 0.2, 2.2 0.4, 0.7 0.4, 0.7 2.2, 2.2 2.2, 2.2 0.6, 2.4 0.6, 2.4 4.8, 0.5 4.8, 0.5 0.2))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.40, 0.80, 0.32},
{0.50, 1.00, 0.40},
{0.44, 0.80, 0.36},
{0.20, 0.00, 0.20},
{0.22, 0.20, 0.12},
});
}
TEST_CASE("Result indexing is correct", "[raster-cell-intersection]") {
init_geos();
Extent ex{-20, -15, 40, 30, 0.5, 1};
auto g = GEOSGeom_read("POLYGON ((0.25 0.20, 2.75 0.20, 2.75 4.5, 0.25 4.5, 0.25 0.20))");
RasterCellIntersection rci{ex, g.get()};
size_t n_rows = rci.max_row() - rci.min_row();
size_t n_cols = rci.max_col() - rci.min_col();
CHECK( n_rows == 5 );
CHECK( n_cols == 6 );
CHECK( rci.min_col() == 40 );
CHECK( rci.max_col() == 46 );
CHECK( rci.min_row() == 25 );
CHECK( rci.max_row() == 30 );
Matrix<float> actual{n_rows, n_cols};
for (size_t i = rci.min_row(); i < rci.max_row(); i++) {
for (size_t j = rci.min_col(); j < rci.max_col(); j++) {
actual(i - rci.min_row(), j - rci.min_col()) = rci.get(i, j);
}
}
Matrix<float> expected{{
{0.25, 0.50, 0.50, 0.50, 0.50, 0.25},
{0.50, 1.00, 1.00, 1.00, 1.00, 0.50},
{0.50, 1.00, 1.00, 1.00, 1.00, 0.50},
{0.50, 1.00, 1.00, 1.00, 1.00, 0.50},
{0.40, 0.80, 0.80, 0.80, 0.80, 0.40}
}};
CHECK( actual == expected );
}
TEST_CASE("Sensible error when geometry extent is larger than raster", "[raster-cell-intersection]") {
init_geos();
Extent ex{-180, -90, 180, 90, 0.5, 0.5};
auto g = GEOSGeom_read("POLYGON ((-179 0, 180.000000004 0, 180 1, -179 0))");
CHECK_THROWS_WITH( RasterCellIntersection(ex, g.get()),
Catch::Matchers::Contains("geometry extent larger than the raster") );
}
TEST_CASE("Sensible error when hole is outside of shell", "[raster-cell-intersection]") {
init_geos();
Extent ex{-180, -90, 180, 90, 0.5, 0.5};
auto g = GEOSGeom_read("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (9 9, 9 9.1, 10.6 9.1, 9 9))");
CHECK_THROWS_WITH( RasterCellIntersection(ex, g.get()),
Catch::Matchers::Contains("hole outside of its shell") );
}
TEST_CASE("Robustness regression test #1", "[raster-cell-intersection]") {
// This test exercises some challenging behavior where a polygon follows
// ymin, but the grid resolution is such that ymin < (ymax - ny*dy)
init_geos();
Extent ex{-180, -90, 180, 90, 1.0/6, 1.0/6};
auto g = GEOSGeom_read(
#include "resources/antarctica.wkt"
);
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
TEST_CASE("Robustness regression test #2", "[raster-cell-intersection]") {
// This test exercises some challenging behavior where a polygon follows
// xmax, but the grid resolution is such that xmax < (xmin + nx*dx)
init_geos();
Extent ex{-180, -90, 180, 90, 1.0/6, 1.0/6};
auto g = GEOSGeom_read(
#include "resources/russia.wkt"
);
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
| 30.510324 | 916 | 0.580102 | dbaston |
98f34c7cb2bb2d82586beb57f2a72bd53f11a4cb | 1,565 | cpp | C++ | src/libsignalflows/delay_vector.cpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 17 | 2019-03-12T14:52:22.000Z | 2021-11-09T01:16:23.000Z | src/libsignalflows/delay_vector.cpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | null | null | null | src/libsignalflows/delay_vector.cpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 2 | 2019-08-11T12:53:07.000Z | 2021-06-22T10:08:08.000Z | /* Copyright Institute of Sound and Vibration Research - All rights reserved */
#include "delay_vector.hpp"
#include <algorithm>
#include <vector>
namespace visr
{
namespace signalflows
{
DelayVector::DelayVector( SignalFlowContext const & context,
const char * name,
CompositeComponent * parent,
std::size_t numberOfChannels,
std::size_t interpolationPeriod,
char const * interpolationMethod )
: CompositeComponent( context, "", parent )
, mDelay( context, "DelayVector", this )
, mInput( "input", *this )
, mOutput( "output", *this )
, mGainInput( "globalGainInput", *this, pml::VectorParameterConfig(numberOfChannels) )
, mDelayInput( "globalDelayInput", *this, pml::VectorParameterConfig( numberOfChannels ) )
{
// Initialise and configure audio components
mDelay.setup( numberOfChannels, interpolationPeriod, 0.02f, interpolationMethod,
rcl::DelayVector::MethodDelayPolicy::Limit,
rcl::DelayVector::ControlPortConfig::All,
0.0f, 1.0f );
mInput.setWidth( numberOfChannels );
mOutput.setWidth( numberOfChannels );
audioConnection( mInput, mDelay.audioPort("in") );
audioConnection( mDelay.audioPort( "out" ), mOutput );
parameterConnection( mGainInput, mDelay.parameterPort("gainInput") );
parameterConnection( mDelayInput, mDelay.parameterPort( "delayInput" ) );
}
DelayVector::~DelayVector()
{
}
} // namespace signalflows
} // namespace visr
| 33.297872 | 92 | 0.663259 | s3a-spatialaudio |
98f371c857935fc189e6b85e571ea24df47ec046 | 9,706 | cpp | C++ | src/Library/Core/FileSystem/Path.cpp | cowlicks/library-core | 9a872ab7aa6bc4aba22734705b72dc22ea35ee77 | [
"Apache-2.0"
] | null | null | null | src/Library/Core/FileSystem/Path.cpp | cowlicks/library-core | 9a872ab7aa6bc4aba22734705b72dc22ea35ee77 | [
"Apache-2.0"
] | null | null | null | src/Library/Core/FileSystem/Path.cpp | cowlicks/library-core | 9a872ab7aa6bc4aba22734705b72dc22ea35ee77 | [
"Apache-2.0"
] | 1 | 2020-12-01T14:50:50.000Z | 2020-12-01T14:50:50.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Core
/// @file Library/Core/FileSystem/Path.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Core/FileSystem/Path.hpp>
#include <Library/Core/Error.hpp>
#include <Library/Core/Utilities.hpp>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace library
{
namespace core
{
namespace fs
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Path::Impl
{
public:
boost::filesystem::path path_ ;
Impl ( const boost::filesystem::path& aPath ) ;
} ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Path::Impl::Impl ( const boost::filesystem::path& aPath )
: path_(aPath)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Path::Path ( const Path& aPath )
: implUPtr_((aPath.implUPtr_ != nullptr) ? std::make_unique<Path::Impl>(*aPath.implUPtr_) : nullptr)
{
}
Path::~Path ( )
{
}
Path& Path::operator = ( const Path& aPath )
{
if (this != &aPath)
{
implUPtr_.reset((aPath.implUPtr_ != nullptr) ? new Path::Impl(*aPath.implUPtr_) : nullptr) ;
}
return *this ;
}
bool Path::operator == ( const Path& aPath ) const
{
if ((!this->isDefined()) || (!aPath.isDefined()))
{
return false ;
}
return implUPtr_->path_ == aPath.implUPtr_->path_ ;
}
bool Path::operator != ( const Path& aPath ) const
{
return !((*this) == aPath) ;
}
Path Path::operator + ( const Path& aPath ) const
{
Path path = { *this } ;
path += aPath ;
return path ;
}
Path& Path::operator += ( const Path& aPath )
{
if (!aPath.isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
try
{
implUPtr_->path_ /= aPath.implUPtr_->path_ ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return *this ;
}
std::ostream& operator << ( std::ostream& anOutputStream,
const Path& aPath )
{
library::core::utils::Print::Header(anOutputStream, "Path") ;
library::core::utils::Print::Line(anOutputStream) << (aPath.isDefined() ? aPath.toString() : "Undefined") ;
library::core::utils::Print::Footer(anOutputStream) ;
return anOutputStream ;
}
bool Path::isDefined ( ) const
{
return implUPtr_ != nullptr ;
}
bool Path::isAbsolute ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
return implUPtr_->path_.is_absolute() ;
}
bool Path::isRelative ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
return implUPtr_->path_.is_relative() ;
}
Path Path::getParentPath ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(implUPtr_->path_.parent_path()) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
String Path::getLastElement ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
try
{
return implUPtr_->path_.filename().string() ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return String::Empty() ;
}
Path Path::getNormalizedPath ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(boost::filesystem::weakly_canonical(implUPtr_->path_)) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
Path Path::getAbsolutePath ( const Path& aBasePath ) const
{
if (!aBasePath.isDefined())
{
throw library::core::error::runtime::Undefined("Base path") ;
}
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(boost::filesystem::absolute(implUPtr_->path_, aBasePath.implUPtr_->path_)) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
// Path Path::getRelativePathTo ( const Path& aReferencePath ) const
// {
// }
String Path::toString ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
try
{
return implUPtr_->path_.string() ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return String::Empty() ;
}
Path Path::Undefined ( )
{
return {} ;
}
Path Path::Root ( )
{
Path path ;
path.implUPtr_ = std::make_unique<Path::Impl>("/") ;
return path ;
}
Path Path::Current ( )
{
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(boost::filesystem::current_path()) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
Path Path::Parse ( const String& aString )
{
if (aString.isEmpty())
{
throw library::core::error::runtime::Undefined("String") ;
}
Path path ;
path.implUPtr_ = std::make_unique<Path::Impl>(aString) ;
return path ;
}
// Path Path::Strings ( const std::initializer_list<types::String> aStringList )
// {
// }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Path::Path ( )
: implUPtr_(nullptr)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 26.961111 | 170 | 0.360396 | cowlicks |
98f6b6d9e5042144e5430e5364c8dae30a9ce48c | 827 | hpp | C++ | alignment/datastructures/anchoring/AnchorParameters.hpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 4 | 2015-07-03T11:59:54.000Z | 2018-05-17T00:03:22.000Z | alignment/datastructures/anchoring/AnchorParameters.hpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 79 | 2015-06-29T18:07:21.000Z | 2018-09-19T13:38:39.000Z | alignment/datastructures/anchoring/AnchorParameters.hpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 19 | 2015-06-23T08:43:29.000Z | 2021-04-28T18:37:47.000Z | #ifndef _BLASR_ANCHOR_PARAMETERS_HPP_
#define _BLASR_ANCHOR_PARAMETERS_HPP_
#include <fstream>
#include <iostream>
#include <pbdata/DNASequence.hpp>
#include <pbdata/qvs/QualityValue.hpp>
class AnchorParameters
{
public:
QualityValue branchQualityThreshold;
DNALength minMatchLength;
int maxMatchScore;
int expand;
int contextAlignLength;
bool useLookupTable;
int numBranches;
UInt maxAnchorsPerPosition;
int advanceExactMatches;
int maxLCPLength;
bool stopMappingOnceUnique;
int verbosity;
bool removeEncompassedMatches;
std::ostream *lcpBoundsOutPtr;
int branchExpand;
AnchorParameters();
AnchorParameters &Assign(const AnchorParameters &rhs);
AnchorParameters &operator=(const AnchorParameters &rhs);
};
#endif // _BLASR_ANCHOR_PARAMETERS_HPP_
| 22.351351 | 61 | 0.76179 | ggraham |
98f8a704a0b525a01c23915877bac44396e8be00 | 2,523 | cpp | C++ | src/MentalMux8.cpp | CommanderAsdasd/asdasd_modules | b3270044623430f3a5e5565327b89296bcbfd181 | [
"BSD-3-Clause"
] | null | null | null | src/MentalMux8.cpp | CommanderAsdasd/asdasd_modules | b3270044623430f3a5e5565327b89296bcbfd181 | [
"BSD-3-Clause"
] | null | null | null | src/MentalMux8.cpp | CommanderAsdasd/asdasd_modules | b3270044623430f3a5e5565327b89296bcbfd181 | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////
//
// 8 to 1 Mux with Binary Decoder selector VCV Module
//
// Strum 2017
//
///////////////////////////////////////////////////
#include "mental.hpp"
struct MentalMux8 : Module {
enum ParamIds {
NUM_PARAMS
};
enum InputIds {
INPUT_1,
INPUT_2,
INPUT_4,
SIG_INPUT,
NUM_INPUTS = SIG_INPUT + 8
};
enum OutputIds {
OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
INPUT_LEDS,
NUM_LIGHTS = INPUT_LEDS + 8
};
float in_1 = 0.0;
float in_2 = 0.0;
float in_4 = 0.0;
int one, two, four, decoded;
MentalMux8() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {}
void step() override;
};
void MentalMux8::step()
{
for ( int i = 0 ; i < 8 ; i ++)
{
lights[INPUT_LEDS + i].value = 0.0;
}
outputs[OUTPUT].value = 0.0;
in_1 = inputs[INPUT_1].value;
in_2 = inputs[INPUT_2].value;
in_4 = inputs[INPUT_4].value;
if (in_1 > 0.0 )
{
one = 1;
} else
{
one = 0;
}
if (in_2 > 0.0)
{
two = 2;
} else
{
two = 0;
}
if (in_4 > 0.0)
{
four = 4;
} else
{
four = 0;
}
decoded = one + two + four;
outputs[OUTPUT].value = inputs[SIG_INPUT + decoded].value;
lights[INPUT_LEDS + decoded].value = 1.0;
}
//////////////////////////////////////////////////////////////
struct MentalMux8Widget : ModuleWidget {
MentalMux8Widget(MentalMux8 *module);
};
MentalMux8Widget::MentalMux8Widget(MentalMux8 *module) : ModuleWidget(module)
{
setPanel(SVG::load(assetPlugin(plugin, "res/MentalMux8.svg")));
int spacing = 25;
int top_space = 15;
addInput(Port::create<GateInPort>(Vec(3, top_space), Port::INPUT, module, MentalMux8::INPUT_1));
addInput(Port::create<GateInPort>(Vec(3, top_space + spacing), Port::INPUT, module, MentalMux8::INPUT_2));
addInput(Port::create<GateInPort>(Vec(3, top_space + spacing * 2), Port::INPUT, module, MentalMux8::INPUT_4));
for (int i = 0; i < 8 ; i++)
{
addInput(Port::create<InPort>(Vec(3, top_space + spacing * i + 100), Port::INPUT, module, MentalMux8::SIG_INPUT + i));
addChild(ModuleLightWidget::create<MedLight<BlueLED>>(Vec(33, top_space + spacing * i + 8 + 100), module, MentalMux8::INPUT_LEDS + i));
}
addOutput(Port::create<OutPort>(Vec(30, top_space + spacing), Port::OUTPUT, module, MentalMux8::OUTPUT));
}
Model *modelMentalMux8 = Model::create<MentalMux8, MentalMux8Widget>("mental", "MentalMux8", "8 Way Multiplexer", UTILITY_TAG); | 23.579439 | 139 | 0.584621 | CommanderAsdasd |
98fa4ff52209303b062549ba0ae526fc9d2dcbe8 | 7,261 | cpp | C++ | Test/PikeVM.cpp | AirGuanZ/Utils | 6ededbd838697682430a2c0746bfd3b36ff14a5b | [
"MIT"
] | 10 | 2018-10-30T14:19:57.000Z | 2021-12-06T07:46:59.000Z | Test/PikeVM.cpp | AirGuanZ/Utils | 6ededbd838697682430a2c0746bfd3b36ff14a5b | [
"MIT"
] | null | null | null | Test/PikeVM.cpp | AirGuanZ/Utils | 6ededbd838697682430a2c0746bfd3b36ff14a5b | [
"MIT"
] | 3 | 2019-04-24T13:42:02.000Z | 2021-06-28T08:17:28.000Z | #include <AGZUtils/Utils/String.h>
#include "Catch.hpp"
using namespace AGZ;
void P8(const WStr &str)
{
(void)StrImpl::PikeVM::Parser<WUTF>().Parse(str);
}
void Gen(const WStr &str)
{
size_t slotCount;
(void)StrImpl::PikeVM::Backend<WUTF>().Generate(
StrImpl::PikeVM::Parser<WUTF>().Parse(str), &slotCount);
}
TEST_CASE("VMEngEx")
{
SECTION("Parser")
{
REQUIRE_NOTHROW(P8("minecraft"));
REQUIRE_NOTHROW(P8("a|b|c|d|e"));
REQUIRE_NOTHROW(P8("[abc]|[a-zA-Zdef0-9.\\\\..\\\\][m-x]"));
REQUIRE_NOTHROW(P8("[abcA-Z]+*??*+"));
REQUIRE_NOTHROW(P8("^abcde(abc$|[def]$)"));
REQUIRE_NOTHROW(P8("abc&def&ghi"));
REQUIRE_NOTHROW(P8("abc.\\.def.ghi\\..\\\\\\.."));
REQUIRE_NOTHROW(P8("(abcdef)[xyz]{ 10 }"));
REQUIRE_NOTHROW(P8("(abcdef)[xyz]{3, 18}"));
REQUIRE_NOTHROW(P8("(abcdef)[xyz]{0, 18}"));
REQUIRE_NOTHROW(P8("abc&@{![a-zA-Z]|([d-f]&(A|Z))}"));
REQUIRE_NOTHROW(P8("abc\\d\\c\\w\\s\\h\\\\\\.\\\\\\...\\d"));
}
SECTION("Backend")
{
REQUIRE_NOTHROW(Gen("minecraft"));
REQUIRE_NOTHROW(Gen("a|b|c|d|e"));
REQUIRE_NOTHROW(Gen("[abc]|[a-zA-Zdef0-9.\\\\..\\\\][m-x]"));
REQUIRE_NOTHROW(Gen("[abcA-Z]+*??*+"));
REQUIRE_NOTHROW(Gen("^abcde(abc$|[def]$)"));
REQUIRE_NOTHROW(Gen("abc&def&ghi"));
REQUIRE_NOTHROW(Gen("abc.\\.def.ghi\\..\\\\\\.."));
REQUIRE_NOTHROW(Gen("(abcdef)[xyz]{ 10 }"));
REQUIRE_NOTHROW(Gen("(abcdef)[xyz]{3, 18}"));
REQUIRE_NOTHROW(Gen("(abcdef)[xyz]{0, 18}"));
REQUIRE_NOTHROW(Gen("a&@{![a-z]|([d-f]&(A|Z))}"));
REQUIRE_NOTHROW(Gen("abc\\d\\c\\w\\s\\h\\\\\\.\\\\\\...\\d"));
}
SECTION("Match")
{
REQUIRE(Regex8(u8"abc").Match(u8"abc"));
REQUIRE(!Regex8(u8"abc").Match(u8"ac"));
REQUIRE(Regex8(u8"abc[def]").Match(u8"abcd"));
REQUIRE(Regex8(u8"abc*").Match(u8"abccc"));
REQUIRE(Regex8(u8"abc*").Match(u8"ab"));
REQUIRE(Regex8(u8"ab.\\.c+").Match(u8"abe.cc"));
REQUIRE(Regex8(u8"abc?").Match(u8"ab"));
REQUIRE(Regex8(u8"ab[def]+").Match(u8"abdefdeffeddef"));
REQUIRE(Regex16(u8"今天(天气)+不错啊?\\?").Match(u8"今天天气天气天气天气不错?"));
REQUIRE(Regex8(u8".*").Match(u8"今天天气不错啊"));
REQUIRE(Regex8(u8"今天.*啊").Match(u8"今天天气不错啊"));
REQUIRE(Regex8(u8"今天{ 5 \t }天气不错啊").Match(L"今天天天天天天气不错啊"));
REQUIRE(WRegex(L"今天{ 3 , 5 }气不错啊").Match(u8"今天天天气不错啊"));
REQUIRE(Regex16(u8"今天{3, 5\t}气不错啊").Match(u8"今天天天天气不错啊"));
REQUIRE(Regex32(u8"今天{3,\t5}气不错啊").Match(u8"今天天天天天气不错啊"));
REQUIRE(!Regex8(u8"今天{3, 5}气不错啊").Match(u8"今天天气不错啊"));
REQUIRE(!Regex8(u8"今天{3, 5}气不错啊").Match(u8"今天天天天天天气不错啊"));
REQUIRE_THROWS(Regex8(u8"今天{2, 1}天气不错啊").Match(u8"今天气不错啊"));
REQUIRE_THROWS(Regex8(u8"今天{0, 0}天气不错啊").Match(u8"今天气不错啊"));
REQUIRE_THROWS(Regex8(u8"今天{0}天气不错啊").Match(u8"今气不错啊"));
REQUIRE_NOTHROW(Regex8(u8"今天{0, 1}天气不错啊").Match(u8"今天气不错啊"));
{
auto m = Regex8(u8"&abc&(def)+&xyz&").Match(u8"abcdefdefxyz");
REQUIRE((m && m(0, 1) == u8"abc" && m(1, 2) == u8"defdef" && m(2, 3) == u8"xyz"));
}
REQUIRE(Regex8("mine|craft").Match("mine"));
REQUIRE(Regex8("mine|craft").Match("craft"));
REQUIRE(!Regex8("mine|craft").Match("minecraft"));
REQUIRE(Regex8("[a-z]+").Match("minecraft"));
REQUIRE(Regex8("\\d+").Match("123456"));
REQUIRE(!Regex8("\\d+").Match("12a3456"));
REQUIRE(Regex8("\\w+").Match("variableName"));
REQUIRE(Regex8("\\w+").Match("variable_name"));
REQUIRE(Regex8("\\w+").Match("0_variable_name_1"));
REQUIRE(!Regex8("\\w+").Match("0_va riable_name_1"));
REQUIRE(Regex8("\\s+").Match("\n \t \r "));
REQUIRE(!Regex8("\\s+").Match("\n !\t \r "));
REQUIRE(!Regex8("[a-z]+").Match("Minecraft"));
REQUIRE(!Regex8("@{![a-z]}+").Match("abcDefg"));
{
auto m = Regex8("&.*&\\.&@{!\\.}*&").Match("abc.x.y.z");
REQUIRE((m && m(0, 1) == "abc.x.y" && m(2, 3) == "z"));
}
REQUIRE(Regex8("@{[a-p]&[h-t]&!k|[+*?]}+").Match("hi?jl+mn*op"));
REQUIRE(!Regex8("@{[a-p]&[h-t]&!k}+").Match("hijklmnop"));
{
Str8 s0 = R"__("minecraft")__";
Str8 s1 = R"__("")__";
Str8 s2 = R"__("mine\"cr\"aft")__";
Str8 s3 = R"__("mine\"cr\"aft\")__";
Regex8 regex(R"__("&((@{!"}|\\")*@{!\\})?&")__");
REQUIRE(regex.Match(s0));
REQUIRE(regex.Match(s1));
REQUIRE(regex.Match(s2));
REQUIRE(!regex.Match(s3));
REQUIRE(regex.SearchPrefix(s0));
REQUIRE(regex.SearchPrefix(s1));
REQUIRE(regex.SearchPrefix(s2));
REQUIRE(!regex.SearchPrefix(s3));
REQUIRE(!regex.SearchPrefix("x" + s0));
REQUIRE(!regex.SearchPrefix("y" + s1));
REQUIRE(!regex.SearchPrefix("z" + s2));
REQUIRE(!regex.SearchPrefix("w" + s3));
}
{
Regex8 regex(R"__(&(\w|-)+&)__");
Str8 s0 = "-_abcdefg xsz0-";
REQUIRE(!regex.Match(s0));
REQUIRE(regex.SearchPrefix(s0)(0, 1) == "-_abcdefg");
REQUIRE(regex.SearchSuffix(s0)(0, 1) == "xsz0-");
}
}
SECTION("Search")
{
REQUIRE(Regex8(u8"今天天气不错").Search(u8"GoodMorning今天天气不错啊"));
REQUIRE(Regex8(u8"b").Search(u8"abc"));
REQUIRE(Regex16(u8"b+").Search(u8"abbbc"));
{
auto m = Regex8(u8"&b+&").Search(u8"abbbc");
REQUIRE((m && m(0, 1) == u8"bbb"));
}
{
auto m = Regex16(u8"&abcde&$").Search(u8"minecraftabcde");
REQUIRE((m && m(0, 1) == u8"abcde"));
}
{
auto m = Regex8("&[def]+&").Search("abcddeeffxyz");
auto n = m;
REQUIRE((n && n(0, 1) == "ddeeff"));
}
REQUIRE(Regex8(u8"mine").Search(u8"abcminecraft"));
REQUIRE(Regex32(u8"^mine").Search(u8"abcminecraft") == false);
}
SECTION("README")
{
// Example of basic usage
// Regex<...>::Match/Search returns a Result object
// which can be implicitly converted to a boolean value
// indicating whether the match/search succeeds
REQUIRE(Regex8(u8"今天天气不错minecraft").Match(u8"今天天气不错minecraft"));
REQUIRE(Regex8(u8"不错mine").Search(u8"今天天气不错minecraft"));
// Example of boolean expression
// Matches a non-empty string with each character satisfying one of the following:
// 1. in { +, *, ? }
// 2. in { c, d, e, ..., m, n } \ { h, k }
REQUIRE(Regex8("@{[+*?]|[c-n]&![hk]}+").Match("cde+fm?n"));
// Example of submatches tracking
// Each '&' defines a save point and can store a matched location.
// We can use two save points to slice the matched string.
auto result = Regex8("&abc&([def]|\\d)+&abc").Match("abcddee0099ff44abc");
REQUIRE(result);
REQUIRE(result(0, 1) == "abc");
REQUIRE(result(1, 2) == "ddee0099ff44");
REQUIRE(result(0, 2) == "abcddee0099ff44");
}
}
| 37.045918 | 94 | 0.519488 | AirGuanZ |