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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7039ece264b7e3551da7c515cc67c054eaab9fab | 196 | cpp | C++ | loom/script/native/lsLuaBridge.cpp | ellemenno/LoomSDK | c6ff83f99b313f402326948c57661908933dabdd | [
"ECL-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | 109 | 2015-01-04T00:32:38.000Z | 2022-02-06T22:59:30.000Z | loom/script/native/lsLuaBridge.cpp | RichardRanft/LoomSDK | 7f12b9d572f2ca409b9070ba92a284a82263ae97 | [
"ECL-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | 237 | 2015-01-10T19:42:56.000Z | 2017-01-02T21:23:32.000Z | loom/script/native/lsLuaBridge.cpp | RichardRanft/LoomSDK | 7f12b9d572f2ca409b9070ba92a284a82263ae97 | [
"ECL-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | 34 | 2015-01-01T21:45:01.000Z | 2020-07-19T15:33:25.000Z | #include "loom/script/native/lsLuaBridge.h"
#include "loom/script/reflection/lsType.h"
#include "loom/script/runtime/lsLuaState.h"
namespace LS {
const char *Namespace::currentPackageName = 0;
}
| 24.5 | 46 | 0.77551 | ellemenno |
703b02d15777e9efc4672b462315d3c6ac932e11 | 3,064 | hpp | C++ | test/propertyaccess.hpp | IRCAD/camp | fbbada73d6fd25c30f22a69f195c871757e362dd | [
"MIT"
] | 6 | 2017-12-27T03:13:29.000Z | 2021-01-04T15:07:18.000Z | test/propertyaccess.hpp | fw4spl-org/camp | e70eca1d2bf7f20df782dacc5d6baa51ce364e12 | [
"MIT"
] | 1 | 2021-10-19T14:03:39.000Z | 2021-10-19T14:03:39.000Z | test/propertyaccess.hpp | IRCAD/camp | fbbada73d6fd25c30f22a69f195c871757e362dd | [
"MIT"
] | 1 | 2019-08-30T15:20:46.000Z | 2019-08-30T15:20:46.000Z | /****************************************************************************
**
** This file is part of the CAMP library.
**
** The MIT License (MIT)
**
** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company.
** Contact: Tegesoft Information (contact@tegesoft.com)
**
** 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.
**
****************************************************************************/
#ifndef CAMPTEST_PROPERTYACCESS_HPP
#define CAMPTEST_PROPERTYACCESS_HPP
#include <camp/camptype.hpp>
#include <camp/class.hpp>
namespace PropertyAccessTest
{
struct MyClass
{
MyClass(bool b = true)
: m_b(b)
{
}
void set(int x) {p = x;}
int get() const {return p;}
int& ref() {return p;}
int p;
bool m_b;
bool b1() {return true;}
bool b2() const {return false;}
};
void declare()
{
camp::Class::declare<MyClass>("PropertyAccessTest::MyClass")
// ***** constant value *****
.property("p0", &MyClass::p).readable(false).writable(true)
.property("p1", &MyClass::p).readable(true).writable(false)
.property("p2", &MyClass::p).readable(false).writable(false)
// ***** function *****
.property("p3", &MyClass::p).readable(&MyClass::b1)
.property("p4", &MyClass::p).readable(&MyClass::b2)
.property("p5", &MyClass::p).readable(boost::bind(&MyClass::b1, _1))
.property("p6", &MyClass::p).readable(&MyClass::m_b)
.property("p7", &MyClass::p).readable(boost::function<bool (MyClass&)>(&MyClass::m_b))
// ***** implicit - based on the availability of a getter/setter *****
.property("p8", &MyClass::get)
.property("p9", &MyClass::ref)
.property("p10", &MyClass::get, &MyClass::set)
;
}
}
CAMP_AUTO_TYPE(PropertyAccessTest::MyClass, &PropertyAccessTest::declare)
#endif // CAMPTEST_PROPERTYACCESS_HPP
| 37.365854 | 98 | 0.613251 | IRCAD |
703d242e34177ae85614f512fc8a8780fe99174b | 865 | cc | C++ | src/results/output.cc | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 12 | 2018-03-14T12:30:53.000Z | 2022-01-23T14:46:44.000Z | src/results/output.cc | jsrehak/BART | 0460dfffbcf5671a730448de7f45cce39fd4a485 | [
"MIT"
] | 194 | 2017-07-07T01:38:15.000Z | 2021-05-19T18:21:19.000Z | src/results/output.cc | jsrehak/BART | 0460dfffbcf5671a730448de7f45cce39fd4a485 | [
"MIT"
] | 10 | 2017-07-06T22:58:59.000Z | 2021-03-15T07:01:21.000Z | #include "results/output.h"
#include <deal.II/base/exceptions.h>
namespace bart {
namespace results {
void Output::WriteVector(std::ostream &output_stream,
const std::vector<double> to_write) const {
for (std::vector<double>::size_type i =0 ; i < to_write.size(); ++i)
output_stream << i << ", " << to_write.at(i) << "\n";
}
void Output::WriteVector(std::ostream &output_stream,
std::vector<double> to_write,
std::vector<std::string> headers) const {
AssertThrow(static_cast<int>(headers.size()) == 2,
dealii::ExcMessage("Error in WriteVector, header size must be "
"size 2"))
output_stream << headers.at(0) << "," << headers.at(1) << "\n";
WriteVector(output_stream, to_write);
}
} // namespace results
} // namespace bart
| 30.892857 | 77 | 0.587283 | SlaybaughLab |
703d7de100fc7ff71c7f7ff64f600c2140011fa0 | 11,355 | cpp | C++ | src/find_relatives_table.cpp | jjmccollum/open-cbgm | c231b1fa0b5ff86c0701c0f7f2b389c3a60434f4 | [
"MIT"
] | 21 | 2020-01-17T21:45:28.000Z | 2022-03-29T07:24:45.000Z | src/find_relatives_table.cpp | jjmccollum/open-cbgm | c231b1fa0b5ff86c0701c0f7f2b389c3a60434f4 | [
"MIT"
] | 4 | 2020-03-05T03:33:44.000Z | 2020-10-16T23:29:44.000Z | src/find_relatives_table.cpp | jjmccollum/open-cbgm | c231b1fa0b5ff86c0701c0f7f2b389c3a60434f4 | [
"MIT"
] | 1 | 2020-01-30T16:17:08.000Z | 2020-01-30T16:17:08.000Z | /*
* find_relatives_table.cpp
*
* Created on: Sept 18, 2020
* Author: jjmccollum
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <list>
#include <set>
#include <algorithm>
#include <limits>
#include "variation_unit.h"
#include "witness.h"
#include "find_relatives_table.h"
using namespace std;
/**
* Default constructor.
*/
find_relatives_table::find_relatives_table() {
}
/**
* Constructs a find relatives table relative to a given witness at a given variation unit,
* given a list of witness IDs in input order and a set of readings by which to filter the rows.
*/
find_relatives_table::find_relatives_table(const witness & wit, const variation_unit & vu, const list<string> list_wit, const set<string> & filter_rdgs) {
rows = list<find_relatives_table_row>();
id = wit.get_id();
label = vu.get_label();
connectivity = vu.get_connectivity();
unordered_map<string, string> reading_support = vu.get_reading_support();
primary_rdg = reading_support.find(id) != reading_support.end() ? reading_support.at(id) : "-";
//Start by populating the table completely with this witness's comparisons to all other witnesses:
for (string secondary_wit_id : list_wit) {
//Get the genealogical comparison of the primary witness to this witness:
genealogical_comparison comp = wit.get_genealogical_comparison_for_witness(secondary_wit_id);
//For the primary witness, copy the number of passages where it is extant and move on:
if (secondary_wit_id == id) {
primary_extant = (int) comp.extant.cardinality();
continue;
}
find_relatives_table_row row;
row.id = secondary_wit_id;
row.rdg = reading_support.find(row.id) != reading_support.end() ? reading_support.at(row.id) : "-";
row.pass = (int) comp.extant.cardinality();
row.eq = (int) comp.agreements.cardinality();
row.perc = row.pass > 0 ? (100 * float(row.eq) / float(row.pass)) : 0;
row.prior = (int) comp.prior.cardinality();
row.posterior = (int) comp.posterior.cardinality();
row.norel = (int) comp.norel.cardinality();
row.uncl = (int) comp.unclear.cardinality();
row.expl = (int) comp.explained.cardinality();
row.cost = row.prior >= row.posterior ? -1 : comp.cost;
rows.push_back(row);
}
//Sort the list of rows from highest number of agreements to lowest:
rows.sort([](const find_relatives_table_row & r1, const find_relatives_table_row & r2) {
return r1.eq > r2.eq;
});
//Pass through the sorted list of comparisons to assign relationship directions and ancestral ranks:
int nr = 0;
int nr_value = numeric_limits<int>::max();
for (find_relatives_table_row & row : rows) {
//Only assign positive ancestral ranks to witnesses prior to this one:
if (row.posterior > row.prior) {
//Only increment the rank if the number of agreements is lower than that of the previous potential ancestor:
if (row.eq < nr_value) {
nr_value = row.eq;
nr++;
}
row.dir = 1;
row.nr = nr;
}
else if (row.posterior == row.prior) {
row.dir = 0;
row.nr = 0;
}
else {
row.dir = -1;
row.nr = -1;
}
}
//If the filter set is not empty, then filter the rows:
if (!filter_rdgs.empty()) {
rows.remove_if([&](const find_relatives_table_row & row) {
return filter_rdgs.find(row.rdg) == filter_rdgs.end();
});
}
}
/**
* Default destructor.
*/
find_relatives_table::~find_relatives_table() {
}
/**
* Returns the ID of the primary witness for which this table provides comparisons.
*/
string find_relatives_table::get_id() const {
return id;
}
/**
* Returns the label of the variation unit at which this table provides comparisons.
*/
string find_relatives_table::get_label() const {
return label;
}
/**
* Returns the connectivity limit of the variation unit at which this table provides comparisons.
*/
int find_relatives_table::get_connectivity() const {
return connectivity;
}
/**
* Returns the number of passages at which this table's primary witness is extant.
*/
int find_relatives_table::get_primary_extant() const {
return primary_extant;
}
/**
* Returns the reading of the primary witness at the variation unit under consideration.
*/
string find_relatives_table::get_primary_rdg() const {
return primary_rdg;
}
/**
* Returns this table's list of rows.
*/
list<find_relatives_table_row> find_relatives_table::get_rows() const {
return rows;
}
/**
* Given an output stream, prints this find relatives table in fixed-width format.
*/
void find_relatives_table::to_fixed_width(ostream & out) {
//Print the caption:
out << "Genealogical comparisons for W1 = " << id << " (" << primary_extant << " extant passages):";
out << "\n\n";
//Print the header row:
out << std::left << std::setw(8) << "W2";
out << std::left << std::setw(4) << "DIR";
out << std::right << std::setw(4) << "NR";
out << std::setw(4) << ""; //buffer space between right-aligned and left-aligned columns
out << std::left << std::setw(8) << "RDG";
out << std::right << std::setw(8) << "PASS";
out << std::right << std::setw(8) << "EQ";
out << std::right << std::setw(12) << ""; //percentage of agreements among mutually extant passages
out << std::right << std::setw(8) << "W1>W2";
out << std::right << std::setw(8) << "W1<W2";
out << std::right << std::setw(8) << "NOREL";
out << std::right << std::setw(8) << "UNCL";
out << std::right << std::setw(8) << "EXPL";
out << std::right << std::setw(12) << "COST";
out << "\n\n";
//Print the subsequent rows:
for (find_relatives_table_row row : rows) {
out << std::left << std::setw(8) << row.id;
out << std::left << std::setw(4) << (row.dir == -1 ? "<" : (row.dir == 1 ? ">" : "="));
out << std::right << std::setw(4) << (row.nr > 0 ? to_string(row.nr) : "");
out << std::setw(4) << ""; //buffer space between right-aligned and left-aligned columns
out << std::left << std::setw(8) << row.rdg;
out << std::right << std::setw(8) << row.pass;
out << std::right << std::setw(8) << row.eq;
out << std::right << std::setw(3) << "(" << std::setw(7) << fixed << std::setprecision(3) << row.perc << std::setw(2) << "%)";
out << std::right << std::setw(8) << row.prior;
out << std::right << std::setw(8) << row.posterior;
out << std::right << std::setw(8) << row.norel;
out << std::right << std::setw(8) << row.uncl;
out << std::right << std::setw(8) << row.expl;
if (row.cost >= 0) {
out << std::right << std::setw(12) << fixed << std::setprecision(3) << row.cost;
}
else {
out << std::right << std::setw(12) << "";
}
out << "\n";
}
out << endl;
return;
}
/**
* Given an output stream, prints this find relatives table in comma-separated value (CSV) format.
* The witness IDs are assumed not to contain commas; if they do, then they will need to be manually escaped in the output.
*/
void find_relatives_table::to_csv(ostream & out) {
//Print the header row:
out << "W2" << ",";
out << "DIR" << ",";
out << "NR" << ",";
out << "RDG" << ",";
out << "PASS" << ",";
out << "EQ" << ",";
out << "" << ","; //percentage of agreements among mutually extant passages
out << "W1>W2" << ",";
out << "W1<W2" << ",";
out << "NOREL" << ",";
out << "UNCL" << ",";
out << "EXPL" << ",";
out << "COST" << "\n";
//Print the subsequent rows:
for (find_relatives_table_row row : rows) {
out << row.id << ",";
out << (row.dir == -1 ? "<" : (row.dir == 1 ? ">" : "=")) << ",";
out << (row.nr > 0 ? to_string(row.nr) : "") << ",";
out << row.rdg << ",";
out << row.pass << ",";
out << row.eq << ",";
out << "(" << row.perc << "%)" << ",";
out << row.prior << ",";
out << row.posterior << ",";
out << row.norel << ",";
out << row.uncl << ",";
out << row.expl << ",";
if (row.cost >= 0) {
out << row.cost << "\n";
}
else {
out << "" << "\n";
}
}
out << endl;
return;
}
/**
* Given an output stream, prints this find relatives table in tab-separated value (TSV) format.
* The witness IDs are assumed not to contain tabs; if they do, then they will need to be manually escaped in the output.
*/
void find_relatives_table::to_tsv(ostream & out) {
//Print the header row:
out << "W2" << "\t";
out << "DIR" << "\t";
out << "NR" << "\t";
out << "RDG" << "\t";
out << "PASS" << "\t";
out << "EQ" << "\t";
out << "" << "\t"; //percentage of agreements among mutually extant passages
out << "W1>W2" << "\t";
out << "W1<W2" << "\t";
out << "NOREL" << "\t";
out << "UNCL" << "\t";
out << "EXPL" << "\t";
out << "COST" << "\n";
//Print the subsequent rows:
for (find_relatives_table_row row : rows) {
out << row.id << "\t";
out << (row.dir == -1 ? "<" : (row.dir == 1 ? ">" : "=")) << "\t";
out << (row.nr > 0 ? to_string(row.nr) : "") << "\t";
out << row.rdg << "\t";
out << row.pass << "\t";
out << row.eq << "\t";
out << "(" << row.perc << "%)" << "\t";
out << row.prior << "\t";
out << row.posterior << "\t";
out << row.norel << "\t";
out << row.uncl << "\t";
out << row.expl << "\t";
if (row.cost >= 0) {
out << row.cost << "\n";
}
else {
out << "" << "\n";
}
}
out << endl;
return;
}
/**
* Given an output stream, prints this find relatives table in JavaScript Object Notation (JSON) format.
* The witness IDs are assumed not to contain characters that need to be escaped in URLs.
*/
void find_relatives_table::to_json(ostream & out) {
//Open the root object:
out << "{";
//Add the metadata fields:
out << "\"primary_wit\":" << "\"" << id << "\"" << ",";
out << "\"primary_extant\":" << primary_extant << ",";
out << "\"label\":" << "\"" << label << "\"" << ",";
out << "\"connectivity\":" << connectivity << ",";
out << "\"primary_rdg\":" << "\"" << primary_rdg << "\"" << ",";
//Open the rows array:
out << "\"rows\":" << "[";
//Print each row as an object:
unsigned int row_num = 0;
for (find_relatives_table_row row : rows) {
//Open the row object:
out << "{";
//Add its key-value pairs:
out << "\"id\":" << "\"" << row.id << "\"" << ",";
out << "\"dir\":" << row.dir << ",";
out << "\"nr\":" << "\"" << (row.nr > 0 ? to_string(row.nr) : "") << "\"" << ",";
out << "\"rdg\":" << "\"" << row.rdg << "\"" << ",";
out << "\"pass\":" << row.pass << ",";
out << "\"eq\":" << row.eq << ",";
out << "\"perc\":" << row.perc << ",";
out << "\"prior\":" << row.prior << ",";
out << "\"posterior\":" << row.posterior << ",";
out << "\"norel\":" << row.norel << ",";
out << "\"uncl\":" << row.uncl << ",";
out << "\"expl\":" << row.expl << ",";
if (row.cost >= 0) {
out << "\"cost\":" << "\"" << row.cost << "\"";
}
else {
out << "\"cost\":" << "\"" << "" << "\"";
}
//Close the row object:
out << "}";
//Add a comma if this is not the last row:
if (row_num < rows.size() - 1) {
out << ",";
}
row_num++;
}
//Close the rows array:
out << "]";
//Close the root object:
out << "}";
return;
}
| 33.594675 | 155 | 0.559401 | jjmccollum |
703d8f3b61a17e7b445f7c162fda17d78e4130b6 | 1,627 | cpp | C++ | NoteHandler/midi.cpp | vikbez/PlayerPianoController | 098e0a9df2be3d029490986eedd1bf2eac0a44ca | [
"MIT"
] | 27 | 2019-07-23T21:13:27.000Z | 2022-03-26T09:51:58.000Z | ProMicro/midi.cpp | anodeaday/PianoProject | ff31af5d5eaa72ee6dbe8b1f445979bc1ab84e90 | [
"MIT"
] | 4 | 2020-11-05T16:41:14.000Z | 2022-02-07T20:31:11.000Z | ProMicro/midi.cpp | anodeaday/PianoProject | ff31af5d5eaa72ee6dbe8b1f445979bc1ab84e90 | [
"MIT"
] | 10 | 2019-07-24T01:00:22.000Z | 2022-02-09T17:36:04.000Z | #include <MIDIUSB.h>
#include "midi.h"
#include "shiftRegister.h"
#include "serial.h"
void decodeMidi(uint8_t header, uint8_t byte1, uint8_t byte2, uint8_t byte3);
extern const bool DEBUG_MODE;
void checkForMidiUSB()
{
midiEventPacket_t rx; //midi data struct from midiUSB libray
do
{
rx = MidiUSB.read(); //get queued info from USB
if(rx.header != 0)
{
decodeMidi(rx.header, rx.byte1, rx.byte2, rx.byte3);
}
} while(rx.header != 0);
}
void decodeMidi(uint8_t header, uint8_t byte1, uint8_t byte2, uint8_t byte3)
{
if(DEBUG_MODE)
{
String message[] =
{
"-----------",
static_cast<String>(header),
static_cast<String>(byte1),
static_cast<String>(byte2),
static_cast<String>(byte3),
"-----------"
};
sendSerialToUSB(message, 6);
}
const uint8_t NOTE_ON_HEADER = 9;
const uint8_t NOTE_OFF_HEADER = 8;
const uint8_t CONTROL_CHANGE_HEADER = 8;
const uint8_t SUSTAIN_STATUS_BYTE = 176;
const uint8_t MIN_NOTE_PITCH = 21;
const uint8_t MAX_NOTE_PITCH = 108;
switch(header)
{
case NOTE_ON_HEADER:
if(byte2 >= MIN_NOTE_PITCH && byte2 <= MAX_NOTE_PITCH &&
byte3 >= 0 && byte3 <= 127)
{
uint8_t note = (byte2 - MIN_NOTE_PITCH) * -1 + 87;
activateNote(note, byte3);
}
break;
case NOTE_OFF_HEADER:
if(byte2 >= MIN_NOTE_PITCH && byte2 <= MAX_NOTE_PITCH)
{
uint8_t note = (byte2 - MIN_NOTE_PITCH) * -1 + 87;
activateNote(note, 0);
}
break;
case SUSTAIN_STATUS_BYTE:
if(byte1 == SUSTAIN_STATUS_BYTE)
{
extern const uint8_t SUSTAIN_HEADER;
sendSerialToMain(SUSTAIN_HEADER, byte3, byte3);
}
break;
}
} | 23.242857 | 77 | 0.664413 | vikbez |
703daf3b8d47d740b87fe5f729ce93d3a076e569 | 1,620 | cpp | C++ | Coding projects/proj2/Project-Two-Related-Files/my_test.cpp | bingcheng1998/VE280 | 5e2fe301910865b7aea186a302eacf90b5fec457 | [
"Apache-2.0"
] | null | null | null | Coding projects/proj2/Project-Two-Related-Files/my_test.cpp | bingcheng1998/VE280 | 5e2fe301910865b7aea186a302eacf90b5fec457 | [
"Apache-2.0"
] | null | null | null | Coding projects/proj2/Project-Two-Related-Files/my_test.cpp | bingcheng1998/VE280 | 5e2fe301910865b7aea186a302eacf90b5fec457 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "recursive.h"
#include "p2.h"
using namespace std;
int Product(int x, int y){
return x*y;
}
int Add(int x, int y){
return x+y;
}
bool odd(int odd){
if (odd%2 == 0) return false;
return true;
}
int main(int argc, char const *argv[])
{
int i = 0;
list_t listA, listA_answer;
list_t listB, listB_answer;
listA = list_make();
listB = list_make();
listA_answer = list_make();
listB_answer = list_make();
for(i = 5; i>0; i--)
{
listA = list_make(i, listA);
listA_answer = list_make(6-i, listA_answer);
listB = list_make(i+10, listB);
listB_answer = list_make(i+10, listB_answer);
}
list_print(listA);
cout << endl;
list_print(listB);
cout << endl;
cout <<"size of listA = " << size(listA)<<endl;
cout << "sum of listA = " << sum(listA) <<endl;
cout << "product of listA = " << product(listA) <<endl;
cout << "accumulate(listA, add, 0) = " << accumulate(listA, Add, 0) << endl;
cout << "accumulate(listA, product, 1) = " << accumulate(listA, Product, 1) << endl;
cout<<"listA : ";
list_print(listA);
cout << "\n listA~: ";
list_print(reverse(listA));
cout << endl;
list_print(list_make(9, listA));
cout<<endl;
list_print(append(listA, listB));
cout<<endl;
list_print(filter_odd(append(listA, listB)));
cout<<endl;
list_print(filter_even(append(listA, listB)));
cout<<endl;
list_print(filter(append(listA, listB), odd));
cout<<endl;
list_print(chop(listA, 2));
cout<<endl;
list_print(insert_list(listA, listB, 2));
return 0;
} | 24.923077 | 85 | 0.605556 | bingcheng1998 |
703fa38c7280501c98858c29beec0029573ece45 | 6,475 | cpp | C++ | gSpiderMac/testv8/testv8/main.cpp | reichtiger/grampusSpider | d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7 | [
"Apache-2.0"
] | 87 | 2015-08-05T12:49:16.000Z | 2021-09-23T03:24:40.000Z | gSpiderMac/testv8/testv8/main.cpp | reichtiger/grampusSpider | d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7 | [
"Apache-2.0"
] | null | null | null | gSpiderMac/testv8/testv8/main.cpp | reichtiger/grampusSpider | d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7 | [
"Apache-2.0"
] | 52 | 2015-09-24T05:19:29.000Z | 2020-10-14T07:14:22.000Z | //
// main.cpp
// testv8
//
// Created by reich on 14/11/18.
// Copyright (c) 2014年 chupeng. All rights reserved.
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <v8.h>
#include <assert.h>
#include <wchar.h>
using namespace std;
using namespace v8;
/*****************************************************************
* exception functions
*/
const char* ToCString(const v8::String::Utf8Value& value)
{
return *value ? *value : "<string conversion failed>";
}
void ReportException(Isolate* isolate, v8::TryCatch* try_catch)
{
HandleScope handle_scope(isolate);
v8::String::Utf8Value exception(try_catch->Exception());
const char* exception_string = ToCString(exception);
v8::Handle<v8::Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn""t provide any extra information about this error; just
// print the exception.
printf("%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(message->GetScriptResourceName());
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber();
printf("%s:%i: %s\n", filename_string, linenum, exception_string);
// Print line of source code.
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceline_string = ToCString(sourceline);
printf("%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
printf(" ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
printf("^");
}
printf("\n");
v8::String::Utf8Value stack_trace(try_catch->StackTrace());
if (stack_trace.length() > 0) {
const char* stack_trace_string = ToCString(stack_trace);
printf("%s\n", stack_trace_string);
}
}
}
std::string executeString(v8::Isolate* isolate, v8::Handle<v8::String> source,
v8::Handle<v8::Value> name,
bool print_result,
bool report_exceptions)
{
HandleScope handle_scope(isolate);
v8::TryCatch try_catch; //’‚¿Ô…Ë÷√“Ï≥£ª˙÷∆
v8::ScriptOrigin origin(name);
v8::Handle<v8::Script> script = v8::Script::Compile(source, &origin);
if (script.IsEmpty()) {
// Print errors that happened during compilation.
if (report_exceptions)
ReportException(isolate, &try_catch);
return "";
} else {
v8::Handle<v8::Value> result = script->Run();
if (result.IsEmpty()) {
//ASSERT(try_catch.HasCaught());
// Print errors that happened during execution.
if (report_exceptions)
ReportException(isolate, &try_catch);
return "";
} else {
assert(!try_catch.HasCaught());
if (print_result && !result->IsUndefined()) {
// If all went well and the result wasn""t undefined then print
// the returned value.
v8::String::Utf8Value ret(result);
printf("%s\n", *ret);
std::string gbk;
//ConvertUtf8ToGBK(gbk, *ret);
return gbk;
}
return "";
}
}
}
void runJSCode(v8::Handle<v8::Context> context, char* jscode)
{
Local<String> source = String::NewFromUtf8(context->GetIsolate(), jscode);
v8::Local<v8::String> name(v8::String::NewFromUtf8(context->GetIsolate(), "(tigerv8)"));
v8::HandleScope handle_scope(context->GetIsolate());
std::string gbkStr3 = executeString(context->GetIsolate(), source, name, true, true);
}
static void log_Callback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
bool first = true;
for (int i = 0; i < args.Length(); i++) {
if (first) {
first = false;
} else {
printf(" ");
}
String::Utf8Value str(args[i]);
if (args[i]->IsString()) {
printf("LOG (string) --->%s\n", *str);
}
else if (args[i]->IsInt32()){
int x = args[i]->Int32Value();
printf("LOG (int) --> %d\n", x);
}
else if (args[i]->IsObject()){
printf("LOG (Object) --> %s\n", *str);
}
}
printf("\n");
fflush(stdout);
}
static void win_Callback(const v8::FunctionCallbackInfo<v8::Value>& args){
}
class HTMLWindow{
};
Handle<Object> WrapHTMLWindowObject(Isolate* isolate, HTMLWindow* htmlWin) {
EscapableHandleScope handle_scope(isolate);
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetInternalFieldCount(1);
Local<Object> result = templ->NewInstance();
result->SetInternalField(0, External::New(isolate, htmlWin));
return handle_scope.Escape(result);
}
/******************************************************************************
* main func start
*
******************************************************************************/
int main(int argc, const char * argv[]) {
Isolate* isolate = Isolate::GetCurrent();
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Handle<ObjectTemplate> global = ObjectTemplate::New(isolate);
v8::Handle<v8::FunctionTemplate> log_ft = v8::FunctionTemplate::New(isolate, log_Callback);
log_ft->InstanceTemplate()->SetInternalFieldCount(1);
global->Set(String::NewFromUtf8(isolate, "alert"), log_ft);
Handle<Context> context = Context::New(isolate, NULL, global);
v8::Handle<v8::Object> v8RealGlobal = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
Context::Scope context_scope(context);
HTMLWindow* htmWin = new HTMLWindow;
Local<Object> jsWin = WrapHTMLWindowObject(isolate, htmWin);
v8RealGlobal->Set(String::NewFromUtf8(isolate, "window"), jsWin);
v8RealGlobal->SetPrototype(jsWin);
// set global objects and functions
runJSCode(context, (char*)"alert(window);window.asdf=44; alert(asdf);");
std::cout << "********* v8 executed finished !! ********** \n";
return 0;
}
| 30.980861 | 106 | 0.567104 | reichtiger |
70463fb71fc008da1202390d5184e486c6289e33 | 7,158 | cpp | C++ | src/gui/src/windows/TableDisplayWindowColumns.cpp | ScottMastro/RVS | c9263e8e354c3edefff21aeb2badcdfd91e2ed80 | [
"MIT"
] | 2 | 2018-11-13T20:22:20.000Z | 2019-06-26T01:26:51.000Z | src/gui/src/windows/TableDisplayWindowColumns.cpp | AngelaQChen/VikNGS | c9263e8e354c3edefff21aeb2badcdfd91e2ed80 | [
"MIT"
] | 15 | 2017-11-02T16:27:33.000Z | 2018-05-03T20:42:39.000Z | src/gui/src/windows/TableDisplayWindowColumns.cpp | AngelaQChen/VikNGS | c9263e8e354c3edefff21aeb2badcdfd91e2ed80 | [
"MIT"
] | 2 | 2019-11-18T17:17:11.000Z | 2020-06-26T17:22:13.000Z | #include "TableDisplayWindow.h"
#include "ui_tabledisplaywindow.h"
void TableDisplayWindow::addSampleInfo(int nrow, QStringList &titles, QVector<QVector<QTableWidgetItem*>>& table){
titles.append("index");
titles.append("Cohort");
titles.append("Group ID");
QVector<QTableWidgetItem*> index(nrow);
QVector<QTableWidgetItem*> caseControl(nrow);
QVector<QTableWidgetItem*> groupID(nrow);
QVector<QTableWidgetItem*> readDepth(nrow);
for (int i = 0; i < nrow ; i++){
index[i] = new QTableWidgetItem(QString::number(i));
caseControl[i] = new QTableWidgetItem((abs(y[i]) < 1e-4 ? "control":"case"));
groupID[i] = new QTableWidgetItem(QString::number(g[i]));
}
table.push_back(index);
table.push_back(caseControl);
table.push_back(groupID);
}
void TableDisplayWindow::addSampleGenotypes(int nrow, QStringList &titles, QVector<QVector<QTableWidgetItem*>>& table, Variant* variant){
QColor gtColour = QColor(194, 214, 211);
QColor missing = QColor(255, 135, 135);
VectorXd* X;
for(GenotypeSource gt : variant->getAllGenotypes()){
titles.append(QString::fromStdString(genotypeToString(gt) + " GT"));
X = variant->getGenotype(gt);
QVector<QTableWidgetItem*> gtValues(nrow);
for(int i = 0; i < nrow; i++){
QString genotype = "Missing";
if(!std::isnan(X->coeff(i)))
genotype = QString::number(X->coeff(i));
QTableWidgetItem* gtcell = new QTableWidgetItem(genotype);
if(!std::isnan(X->coeff(i))){
gtColour.setAlpha( std::min(255.0, (X->coeff(i)/2)*255 ) );
gtcell->setBackgroundColor(gtColour);
}
else
gtcell->setBackgroundColor(missing);
gtValues[i]=gtcell;
}
table.push_back(gtValues);
}
}
void TableDisplayWindow::addInfo(int nrow, QStringList &titles, QVector<QVector<QTableWidgetItem*>>& table){
titles.append("index");
titles.append("CHROM");
titles.append("POS");
titles.append("REF");
titles.append("ALT");
QVector<QTableWidgetItem*> index(nrow);
QVector<QTableWidgetItem*> chr(nrow);
QVector<QTableWidgetItem*> pos(nrow);
QVector<QTableWidgetItem*> ref(nrow);
QVector<QTableWidgetItem*> alt(nrow);
int i = 0;
for(size_t n = 0; n < variants->size(); n++){
for(size_t m = 0; m < variants->at(n).size(); m++){
index[i] = new QTableWidgetItem(QString::number(i));
chr[i] = new QTableWidgetItem(QString::fromStdString(variants->at(n).getVariants()->at(m).getChromosome()));
pos[i] = new QTableWidgetItem(QString::number(variants->at(n).getVariants()->at(m).getPosition()));
ref[i] = new QTableWidgetItem(QString::fromStdString(variants->at(n).getVariants()->at(m).getRef()));
alt[i] = new QTableWidgetItem(QString::fromStdString(variants->at(n).getVariants()->at(m).getAlt()));
i++;
}
}
table.push_back(index);
table.push_back(chr);
table.push_back(pos);
table.push_back(ref);
table.push_back(alt);
}
void TableDisplayWindow::addPvals(int nrow, QStringList &titles, QVector<QVector<QTableWidgetItem*>>& table){
QColor pvalColour = QColor(234, 183, 53, 255);
for (size_t j = 0; j < tests->size(); j++){
bool contains = false;
for(int idx : testIndexes)
if (idx == static_cast<int>(j))
contains = true;
if(!contains)
continue;
titles.append(QString::fromStdString(tests->at(j).toShortString()) + " pval");
QVector<QTableWidgetItem*> pvals(nrow);
int i = 0;
for(size_t n = 0; n < variants->size(); n++){
for(size_t m = 0; m < variants->at(n).size(); m++){
double pval = variants->at(n).getPval(j);
pvalColour.setAlpha( std::min(255.0, (-log(pval+1e-14)/10)*255.0 ));
QTableWidgetItem* pcell = new QTableWidgetItem(QString::number(pval));
pcell->setBackgroundColor(pvalColour);
pvals[i] = pcell;
i++;
}
}
table.push_back(pvals);
}
}
double TableDisplayWindow::calculateMaf(VectorXd* gt, bool caseOnly, bool controlOnly){
double maf = 0;
double denom = 0;
int sampleSize = nsamples;
if (sampleSize < 0) sampleSize = gt->rows();
if(sampleSize > gt->rows()) sampleSize = gt->rows();
for (int i = 0; i < sampleSize; i++){
if(std::isnan(gt->coeff(i)))
continue;
else if(caseOnly && abs(y[i]) < 1e-4)
continue;
else if(controlOnly && abs(y[i]-1) < 1e-4)
continue;
maf += gt->coeff(i);
denom+=2;
}
return maf/std::max(1.0,denom);
}
void TableDisplayWindow::addMafsCaseControl(int nrow, QStringList &titles, QVector<QVector<QTableWidgetItem*>>& table, bool useCases){
QColor mafColour = QColor(194, 214, 211);
std::string caseControl = useCases ? " case MAF" : " control MAF";
for(size_t j = 0; j < testIndexes.size(); j++){
GenotypeSource genotype = tests->at(testIndexes[j]).getGenotype();
titles.append(QString::fromStdString(genotypeToString(genotype) + caseControl));
QVector<QTableWidgetItem*> mafs(nrow);
int i = 0;
for(size_t n = 0; n < variants->size(); n++){
for(size_t m = 0; m < variants->at(n).size(); m++){
if(!variants->at(n).hasGenotypes()){
QTableWidgetItem* mcell = new QTableWidgetItem("Unknown");
mafs[i] = mcell; i++;
continue;
}
double maf = calculateMaf(variants->at(n).getVariants()->at(m).getGenotype(genotype), useCases, !useCases);
mafColour.setAlpha(std::min(255.0, maf*255.0*2.0));
QTableWidgetItem* mcell = new QTableWidgetItem(QString::number(maf));
mcell->setBackgroundColor(mafColour);
mafs[i] = mcell;
i++;
}
}
table.push_back(mafs);
}
}
void TableDisplayWindow::addMafs(int nrow, QStringList &titles, QVector<QVector<QTableWidgetItem*>>& table){
QColor mafColour = QColor(194, 214, 211);
for(size_t j = 0; j < tests->size(); j++){
GenotypeSource genotype = tests->at(j).getGenotype();
titles.append(QString::fromStdString(genotypeToString(genotype) + " MAF"));
QVector<QTableWidgetItem*> mafs(nrow);
int i = 0;
for(size_t n = 0; n < variants->size(); n++){
for(size_t m = 0; m < variants->at(n).size(); m++){
double maf = calculateMaf(variants->at(n).getVariants()->at(m).getGenotype(genotype), false, false);
mafColour.setAlpha(std::min(255.0, maf*255.0*2.0));
QTableWidgetItem* mcell = new QTableWidgetItem(QString::number(maf));
mcell->setBackgroundColor(mafColour);
mafs[i] = mcell;
i++;
}
}
table.push_back(mafs);
}
}
| 34.917073 | 137 | 0.583822 | ScottMastro |
704687f51a5d25683a21da0cfe97488a3dc540d2 | 3,734 | cpp | C++ | samples/parser.cpp | tlammi/upp | 480615e11b8dd12b36fee0e78b984e1b5051183d | [
"MIT"
] | null | null | null | samples/parser.cpp | tlammi/upp | 480615e11b8dd12b36fee0e78b984e1b5051183d | [
"MIT"
] | null | null | null | samples/parser.cpp | tlammi/upp | 480615e11b8dd12b36fee0e78b984e1b5051183d | [
"MIT"
] | null | null | null | #include "upp/parser.hpp"
#include <iterator>
#include <iostream>
#include <fstream>
#include <string_view>
#include <map>
#include <vector>
#include <variant>
struct Value;
using Obj = std::map<std::string, Value>;
// Deque to avoid relocation on assignment
using List = std::deque<Value>;
using ValueBase = std::variant<std::monostate, int, std::string, Obj, List>;
struct Value: public ValueBase {
using ValueBase::ValueBase;
};
struct ObjFactory{
ObjFactory(){}
void push_value(Value&& val){
if(current_key == ""){
std::get<List>(*stack.back()).push_back(std::move(val));
} else {
std::get<Obj>(*stack.back())[current_key] = val;
current_key = "";
}
}
void push_container(Value&& container){
if(!stack.size()){
root = std::move(container);
stack.push_back(&root);
} else if(current_key != ""){
auto& obj = std::get<Obj>(*stack.back());
obj[current_key] = std::move(container);
stack.push_back(&obj.at(current_key));
current_key = "";
} else {
auto& list = std::get<List>(*stack.back());
list.push_back(std::move(container));
stack.push_back(&list.back());
}
}
void push_key(std::string&& str){
current_key = str;
}
void move_up(){
stack.pop_back();
}
Value root{};
std::deque<Value*> stack{};
std::string current_key{""};
};
namespace p = upp::parser;
int main(int argc, char** argv){
if(argc != 2)
throw std::runtime_error("Input JSON file required");
std::ifstream fs{argv[1]};
std::string str{std::istreambuf_iterator<char>(fs), std::istreambuf_iterator<char>()};
auto json = ObjFactory();
// Utility object so <Iter> does not need to be specified each time
auto factory = p::Factory<std::string::const_iterator>();
// Matches literal '{' and invokes callback on match
auto obj_begin = factory.lit('{', [&](auto begin, auto end){
(void)begin;
(void)end;
json.push_container(Obj());
});
auto obj_end = factory.lit('}', [&](auto begin, auto end){
(void)begin;
(void)end;
json.move_up();
});
auto list_begin = factory.lit('[', [&](auto begin, auto end){
(void)begin;
(void)end;
std::cerr << "list begin\n";
json.push_container(List());
});
auto list_end = factory.lit(']', [&](auto begin, auto end){
(void)begin;
(void)end;
std::cerr << "list end\n";
json.move_up();
});
// Regex for matching quoted strings
auto quoted = factory.regex(R"(".*?[^\\]")", "quoted string", [&](auto begin, auto end){
json.push_value(std::string(begin+1, end-1));
});
// Copy matcher from quoted but override the callback
auto key = factory.ast(quoted, [&](auto begin, auto end){
json.push_key(std::string(begin+1, end-1));
});
// Match integer
auto integer = factory.regex(R"(0|[1-9][0-9]*)", "integer", [&](auto begin, auto end){
int i = std::stoi(std::string(begin, end));
json.push_value(i);
});
// Forward declarations to allow recursive matching
auto obj = factory.dyn_ast();
auto list = factory.dyn_ast([](auto begin, auto end){
std::cerr << "list: " << std::string(begin, end) << '\n';
});
// Match any of the alternatives
auto value = (quoted | integer | obj | list);
// Match "quoted str": <value>
auto key_value = (key, factory.lit(':'), value);
// Declaration of a JSON object
// - -> zero or one
// * -> zero to inf
obj = (obj_begin, -(key_value), *(factory.lit(','), key_value), obj_end);
list = (list_begin, -(value), *(factory.lit(','), value), list_end);
auto obj_or_list = (obj | list);
auto result = p::parse(str.cbegin(), str.cend(), obj_or_list, p::whitespaces);
if(result)
std::cerr << "Successfull parse\n";
else{
std::cerr << "failed to parse\n";
std::cerr << argv[1] << ":" << p::error_msg(str.cbegin(), str.cend(), result) << '\n';
}
}
| 24.405229 | 89 | 0.633369 | tlammi |
704762ae42702157acd11411a5a7c08b295231cb | 727 | cpp | C++ | Project_2DGameSDK/src/world/GameWorld.cpp | markoczy/2DGameSDK | 53da378d604ace1d931dfe6ec336241045675667 | [
"MIT"
] | 1 | 2020-12-15T08:20:44.000Z | 2020-12-15T08:20:44.000Z | Project_2DGameSDK/src/world/GameWorld.cpp | markoczy/2DGameSDK | 53da378d604ace1d931dfe6ec336241045675667 | [
"MIT"
] | 8 | 2019-09-14T10:05:33.000Z | 2019-09-25T18:47:59.000Z | Project_2DGameSDK/src/world/GameWorld.cpp | markoczy/2DGameSDK | 53da378d604ace1d931dfe6ec336241045675667 | [
"MIT"
] | null | null | null | #include <2DGameSDK/world/GameWorld.h>
using namespace sf;
namespace game {
GameWorld::GameWorld(Game* game, Tilemap* tilemap, MaterialMap* materialMap) : mGame(game), mTilemap(tilemap), mMaterialMap(materialMap) {
mBounds.width = mTilemap->TileWidth * mTilemap->TilesWide;
mBounds.height = mTilemap->TileHeight * mTilemap->TilesHigh;
loadTilemap();
}
GameWorld::~GameWorld() {
helpers::safeDelete(mTilemap);
helpers::safeDelete(mMaterialMap);
}
sf::IntRect GameWorld::GetBounds() {
return mBounds;
}
void GameWorld::loadTilemap() {
for(auto layer : mTilemap->Layers) {
mGame->GetStateManager()->AddVisualObject(layer);
}
}
} // namespace game | 27.961538 | 141 | 0.672627 | markoczy |
704762bbea39ca538bc9a11e63ab64e74555bfec | 2,381 | cc | C++ | src/plugin/graphics/windowing/src/platform=pc/window-p=posix.cc | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/windowing/src/platform=pc/window-p=posix.cc | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/windowing/src/platform=pc/window-p=posix.cc | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | /* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#include <motor/plugin.graphics.windowing/stdafx.h>
#include <motor/plugin.graphics.3d/rendertarget/rendertarget.meta.hh>
#include <motor/plugin.graphics.windowing/renderer.hh>
#include <motor/plugin.graphics.windowing/window.hh>
#include <X11/X.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <posix/platformrenderer.hh>
namespace Motor { namespace Windowing {
class Window::PlatformWindow : public minitl::refcountable
{
friend class Window;
private:
::Display* m_display;
::Window m_window;
public:
PlatformWindow(::Display* display, ::Window window);
~PlatformWindow();
};
Window::PlatformWindow::PlatformWindow(::Display* display, ::Window window)
: m_display(display)
, m_window(window)
{
}
Window::PlatformWindow::~PlatformWindow()
{
XDestroyWindow(m_display, m_window);
}
Window::Window(weak< const RenderWindowDescription > renderWindowDescription,
weak< const Renderer > renderer)
: IRenderTarget(renderWindowDescription, renderer)
, m_window()
{
}
Window::~Window()
{
}
void Window::load(weak< const Resource::IDescription > /*renderWindowDescription*/)
{
m_window.reset(
scoped< PlatformWindow >::create(m_renderer->arena(),
motor_checked_cast< const Renderer >(m_renderer)
->m_platformRenderer->m_platformData.display,
motor_checked_cast< const Renderer >(m_renderer)
->m_platformRenderer->createWindow(0, 0, 200, 200)));
Window* w = this;
XChangeProperty(
motor_checked_cast< const Renderer >(m_renderer)
->m_platformRenderer->m_platformData.display,
m_window->m_window,
motor_checked_cast< const Renderer >(m_renderer)->m_platformRenderer->m_windowProperty,
XA_INTEGER, 8, PropModeReplace, (unsigned char*)&w, sizeof(w));
}
void Window::unload()
{
m_window.reset(scoped< PlatformWindow >());
}
void* Window::getWindowHandle() const
{
motor_assert_recover(m_window, "no window implementation is created", return 0);
return (void*)&m_window->m_window;
}
uint2 Window::getDimensions() const
{
return make_uint2(1920, 1200);
}
}} // namespace Motor::Windowing
| 28.345238 | 98 | 0.662747 | motor-dev |
7047d9081bbcce2afa557b1a5ff2bed38e8bc510 | 6,263 | hpp | C++ | lcm-types/cpp/rpc_outputs_t.hpp | Chenaah/Cheetah-Software-RL | bdb7bbaf07bea32337a58ede6fde9479929f7c67 | [
"MIT"
] | null | null | null | lcm-types/cpp/rpc_outputs_t.hpp | Chenaah/Cheetah-Software-RL | bdb7bbaf07bea32337a58ede6fde9479929f7c67 | [
"MIT"
] | null | null | null | lcm-types/cpp/rpc_outputs_t.hpp | Chenaah/Cheetah-Software-RL | bdb7bbaf07bea32337a58ede6fde9479929f7c67 | [
"MIT"
] | 2 | 2022-02-25T07:58:20.000Z | 2022-03-02T01:33:06.000Z | /** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY
* BY HAND!!
*
* Generated by lcm-gen
**/
#include <lcm/lcm_coretypes.h>
#ifndef __rpc_outputs_t_hpp__
#define __rpc_outputs_t_hpp__
class rpc_outputs_t
{
public:
double cpu_opt_time_microseconds;
double t_sent;
double time_start;
double dt_pred[5];
double x_opt[60];
double u_opt[120];
double p_opt[12];
public:
/**
* Encode a message into binary form.
*
* @param buf The output buffer.
* @param offset Encoding starts at thie byte offset into @p buf.
* @param maxlen Maximum number of bytes to write. This should generally be
* equal to getEncodedSize().
* @return The number of bytes encoded, or <0 on error.
*/
inline int encode(void *buf, int offset, int maxlen) const;
/**
* Check how many bytes are required to encode this message.
*/
inline int getEncodedSize() const;
/**
* Decode a message from binary form into this instance.
*
* @param buf The buffer containing the encoded message.
* @param offset The byte offset into @p buf where the encoded message starts.
* @param maxlen The maximum number of bytes to reqad while decoding.
* @return The number of bytes decoded, or <0 if an error occured.
*/
inline int decode(const void *buf, int offset, int maxlen);
/**
* Retrieve the 64-bit fingerprint identifying the structure of the message.
* Note that the fingerprint is the same for all instances of the same
* message type, and is a fingerprint on the message type definition, not on
* the message contents.
*/
inline static int64_t getHash();
/**
* Returns "rpc_outputs_t"
*/
inline static const char* getTypeName();
// LCM support functions. Users should not call these
inline int _encodeNoHash(void *buf, int offset, int maxlen) const;
inline int _getEncodedSizeNoHash() const;
inline int _decodeNoHash(const void *buf, int offset, int maxlen);
inline static uint64_t _computeHash(const __lcm_hash_ptr *p);
};
int rpc_outputs_t::encode(void *buf, int offset, int maxlen) const
{
int pos = 0, tlen;
int64_t hash = (int64_t)getHash();
tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = this->_encodeNoHash(buf, offset + pos, maxlen - pos);
if (tlen < 0) return tlen; else pos += tlen;
return pos;
}
int rpc_outputs_t::decode(const void *buf, int offset, int maxlen)
{
int pos = 0, thislen;
int64_t msg_hash;
thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1);
if (thislen < 0) return thislen; else pos += thislen;
if (msg_hash != getHash()) return -1;
thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos);
if (thislen < 0) return thislen; else pos += thislen;
return pos;
}
int rpc_outputs_t::getEncodedSize() const
{
return 8 + _getEncodedSizeNoHash();
}
int64_t rpc_outputs_t::getHash()
{
static int64_t hash = _computeHash(NULL);
return hash;
}
const char* rpc_outputs_t::getTypeName()
{
return "rpc_outputs_t";
}
int rpc_outputs_t::_encodeNoHash(void *buf, int offset, int maxlen) const
{
int pos = 0, tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->cpu_opt_time_microseconds, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->t_sent, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->time_start, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->dt_pred[0], 5);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->x_opt[0], 60);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->u_opt[0], 120);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_encode_array(buf, offset + pos, maxlen - pos, &this->p_opt[0], 12);
if(tlen < 0) return tlen; else pos += tlen;
return pos;
}
int rpc_outputs_t::_decodeNoHash(const void *buf, int offset, int maxlen)
{
int pos = 0, tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->cpu_opt_time_microseconds, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->t_sent, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->time_start, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->dt_pred[0], 5);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->x_opt[0], 60);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->u_opt[0], 120);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __double_decode_array(buf, offset + pos, maxlen - pos, &this->p_opt[0], 12);
if(tlen < 0) return tlen; else pos += tlen;
return pos;
}
int rpc_outputs_t::_getEncodedSizeNoHash() const
{
int enc_size = 0;
enc_size += __double_encoded_array_size(NULL, 1);
enc_size += __double_encoded_array_size(NULL, 1);
enc_size += __double_encoded_array_size(NULL, 1);
enc_size += __double_encoded_array_size(NULL, 5);
enc_size += __double_encoded_array_size(NULL, 60);
enc_size += __double_encoded_array_size(NULL, 120);
enc_size += __double_encoded_array_size(NULL, 12);
return enc_size;
}
uint64_t rpc_outputs_t::_computeHash(const __lcm_hash_ptr *)
{
uint64_t hash = 0xc89e670023d70089LL;
return (hash<<1) + ((hash>>63)&1);
}
#endif
| 31.472362 | 103 | 0.641386 | Chenaah |
704b287c3fb15089d13601b52d15e9d22b1a8727 | 2,215 | cpp | C++ | leetcode/problems/hard/1293-shortest-path-in-a-grid-with-obstacles-elimination.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/hard/1293-shortest-path-in-a-grid-with-obstacles-elimination.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/hard/1293-shortest-path-in-a-grid-with-obstacles-elimination.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Shortest Path in a Grid with Obstacles Elimination
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.
Example 1:
Input:
grid =
[[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
Example 2:
Input:
grid =
[[0,1,1],
[1,1,1],
[1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 40
1 <= k <= m * n
grid[i][j] == 0 or 1
grid[0][0] == grid[m - 1][n - 1] == 0
*/
class Solution {
public:
int shortestPath(vector<vector<int>> &grid, int k) {
const int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0};
int m = grid.size(), n = grid[0].size(), step = 0;
vector<vector<int>> remains(m, vector<int>(n, INT_MIN));
queue<vector<int>> q;
q.push({0, 0, k}), remains[0][0] = k;
while(!q.empty()) {
for(int it = q.size(); it > 0; it--) {
auto cur = q.front();
q.pop();
if(cur[0] == m - 1 && cur[1] == n - 1) return step;
for(int i = 0; i < 4; i++) {
int x = cur[0] + dx[i], y = cur[1] + dy[i];
if(x < 0 || x >= m || y < 0 || y >= n) continue;
int remain = cur[2] - grid[x][y];
if(remain >= 0 && remain > remains[x][y]) {
q.push({x, y, remain});
remains[x][y] = remain;
}
}
}
step++;
}
return -1;
}
};
| 28.766234 | 218 | 0.506998 | wingkwong |
704c0f47f9e2a1552f926a54281972ea39ee9ad8 | 1,380 | cpp | C++ | medium/5_longest_palindromic_substring.cpp | pdu/leetcode_cpp | c487df7561f92562b20a31317957f47e0a20c485 | [
"Apache-2.0"
] | 4 | 2019-07-22T03:53:23.000Z | 2019-10-17T01:37:41.000Z | medium/5_longest_palindromic_substring.cpp | pdu/leetcode_cpp | c487df7561f92562b20a31317957f47e0a20c485 | [
"Apache-2.0"
] | null | null | null | medium/5_longest_palindromic_substring.cpp | pdu/leetcode_cpp | c487df7561f92562b20a31317957f47e0a20c485 | [
"Apache-2.0"
] | 2 | 2020-03-10T03:30:41.000Z | 2020-11-10T06:51:34.000Z | // step 1: clarify
//
// Q: how long is the string?
// A: at most 1000
//
// step 2: solutions
//
// the naive way is to enumate all the substrings, and check whether it's palindromic or not
// time complexity: O(n^3)
// space complexity: O(1)
//
// for the palindromic string, it's substring s[1, n-1) must be palindromic string and s[0] == s[n-1]
// so we can use dynamic programming to solve the problem.
// time complexity: O(n^2)
// space complexity: O(n^2), can optimise to O(n)
//
// step 3: coding
//
// step 4: testing
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty())
return s;
int n = s.length();
int ret_start = 0;
int ret_len = 1;
vector<vector<bool>> f(3, vector<bool>(n, true));
for (int len = 2; len <= n; ++len) {
if (ret_len < len - 2)
break;
int row = len % 3;
int prev_row = (len - 2) % 3;
for (int start = 0, end = start + len - 1; end < n; ++start, ++end) {
f[row][start] = s[start] == s[end] && f[prev_row][start + 1];
if (f[row][start]) {
ret_len = len;
ret_start = start;
}
}
}
return s.substr(ret_start, ret_len);
}
};
| 27.058824 | 101 | 0.521739 | pdu |
704c927c2bbd2973fbf5ae0ae6aaff4785688780 | 6,873 | cpp | C++ | XivAlexander/AutoLoadAsDependencyModule.cpp | retaker/XivAlexander | 03b64118500c3e6e7c3a035af473ef2bd0303bff | [
"Apache-2.0"
] | 345 | 2021-02-08T18:11:24.000Z | 2022-03-25T04:01:23.000Z | XivAlexander/AutoLoadAsDependencyModule.cpp | retaker/XivAlexander | 03b64118500c3e6e7c3a035af473ef2bd0303bff | [
"Apache-2.0"
] | 376 | 2021-02-12T07:23:57.000Z | 2022-03-31T00:05:35.000Z | XivAlexander/AutoLoadAsDependencyModule.cpp | retaker/XivAlexander | 03b64118500c3e6e7c3a035af473ef2bd0303bff | [
"Apache-2.0"
] | 65 | 2021-02-12T05:47:14.000Z | 2022-03-25T03:08:23.000Z | #include "pch.h"
#define DIRECTINPUT_VERSION 0x0800 // NOLINT(cppcoreguidelines-macro-usage)
#include <dinput.h>
#include <XivAlexander/XivAlexander.h>
#include <XivAlexanderCommon/Sqex_CommandLine.h>
#include <XivAlexanderCommon/Utils_Win32.h>
#include "App_ConfigRepository.h"
#include "DllMain.h"
static WORD s_wLanguage = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
static Utils::Win32::LoadedModule EnsureOriginalDependencyModule(const char* szDllName, std::filesystem::path originalDllPath);
static std::set<std::filesystem::path> s_ignoreDlls;
static bool s_useSystemDll = false;
template<typename T_Fn, typename Ret>
Ret ChainCall(const char* szDllName, const char* szFunctionName, std::vector<std::filesystem::path> chainLoadDlls, std::function<Ret(T_Fn, bool discardImmediately)> cb) {
const auto systemDll = Utils::Win32::GetSystem32Path() / szDllName;
if (s_useSystemDll) {
chainLoadDlls.clear();
} else {
std::vector<std::filesystem::path> temp;
for (auto& path : chainLoadDlls)
if (!path.empty())
temp.emplace_back(App::Config::Config::TranslatePath(path));
chainLoadDlls = std::move(temp);
}
if (chainLoadDlls.empty())
chainLoadDlls.emplace_back(systemDll);
for (size_t i = 0; i < chainLoadDlls.size(); ++i) {
const auto& dll = chainLoadDlls[i];
const auto isLast = i == chainLoadDlls.size() - 1;
if (s_ignoreDlls.find(dll) != s_ignoreDlls.end())
continue;
try {
const auto mod = Utils::Win32::LoadedModule(dll);
const auto pOriginalFunction =
EnsureOriginalDependencyModule(szDllName, dll).GetProcAddress<T_Fn>(szFunctionName, true);
mod.SetPinned();
if (isLast)
return cb(pOriginalFunction, !isLast);
else
cb(pOriginalFunction, !isLast);
} catch (const std::exception& e) {
const auto activationContextCleanup = Dll::ActivationContext().With();
const auto choice = Dll::MessageBoxF(
Dll::FindGameMainWindow(false), MB_ICONWARNING | MB_ABORTRETRYIGNORE,
L"Failed to load {}.\nReason: {}\n\nPress Abort to exit.\nPress Retry to keep on loading.\nPress Ignore to skip right ahead to system DLL.",
dll, e.what());
switch (choice) {
case IDRETRY:
s_ignoreDlls.insert(dll);
return ChainCall(szDllName, szFunctionName, std::move(chainLoadDlls), cb);
case IDIGNORE:
s_useSystemDll = true;
chainLoadDlls = {systemDll};
i = static_cast<size_t>(-1);
break;
case IDABORT:
TerminateProcess(GetCurrentProcess(), -1);
}
}
if (isLast && std::ranges::find(chainLoadDlls, systemDll) == chainLoadDlls.end())
chainLoadDlls.emplace_back(systemDll);
}
const auto activationContextCleanup = Dll::ActivationContext().With();
Dll::MessageBoxF(
Dll::FindGameMainWindow(false), MB_ICONERROR,
L"Failed to load any of the possible {}. Aborting.",
szDllName);
TerminateProcess(GetCurrentProcess(), -1);
ExitProcess(-1); // Mark noreturn
}
#if INTPTR_MAX == INT64_MAX
#include <d3d11.h>
#include <dxgi1_3.h>
HRESULT WINAPI FORWARDER_D3D11CreateDevice(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext
) {
return ChainCall<decltype(&D3D11CreateDevice), HRESULT>("d3d11.dll", "D3D11CreateDevice", App::Config::Acquire()->Runtime.ChainLoadPath_d3d11.Value(), [&](auto pfn, auto discardImmediately) {
const auto res = pfn(pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext);
if (res == S_OK && discardImmediately) {
if (ppDevice)
(*ppDevice)->Release();
if (ppImmediateContext)
(*ppImmediateContext)->Release();
}
return res;
});
}
HRESULT WINAPI FORWARDER_CreateDXGIFactory(
REFIID riid,
IDXGIFactory** ppFactory
) {
return ChainCall<decltype(&CreateDXGIFactory), HRESULT>("dxgi.dll", "CreateDXGIFactory", App::Config::Acquire()->Runtime.ChainLoadPath_dxgi.Value(), [&](auto pfn, auto discardImmediately) {
const auto res = pfn(riid, reinterpret_cast<void**>(ppFactory));
if (res == S_OK && discardImmediately) {
if (ppFactory)
(*ppFactory)->Release();
}
return res;
});
}
HRESULT WINAPI FORWARDER_CreateDXGIFactory1(
REFIID riid,
IDXGIFactory1** ppFactory
) {
return ChainCall<decltype(&CreateDXGIFactory1), HRESULT>("dxgi.dll", "CreateDXGIFactory1", App::Config::Acquire()->Runtime.ChainLoadPath_dxgi.Value(), [&](auto pfn, auto discardImmediately) {
const auto res = pfn(riid, reinterpret_cast<void**>(ppFactory));
if (res == S_OK && discardImmediately) {
if (ppFactory)
(*ppFactory)->Release();
}
return res;
});
}
HRESULT WINAPI FORWARDER_CreateDXGIFactory2(
UINT Flags,
REFIID riid,
IDXGIFactory2** ppFactory
) {
return ChainCall<decltype(&CreateDXGIFactory2), HRESULT>("dxgi.dll", "CreateDXGIFactory1", App::Config::Acquire()->Runtime.ChainLoadPath_dxgi.Value(), [&](auto pfn, auto discardImmediately) {
const auto res = pfn(Flags, riid, reinterpret_cast<void**>(ppFactory));
if (res == S_OK && discardImmediately) {
if (ppFactory)
(*ppFactory)->Release();
}
return res;
});
}
#elif INTPTR_MAX == INT32_MAX
#include <d3d9.h>
void WINAPI FORWARDER_D3DPERF_SetOptions(DWORD dwOptions) {
return ChainCall<decltype(&D3DPERF_SetOptions), void>("d3d9.dll", "D3DPERF_SetOptions", App::Config::Acquire()->Runtime.ChainLoadPath_d3d9.Value(), [&](auto pfn, auto discardImmediately) {
pfn(dwOptions);
});
}
IDirect3D9* WINAPI FORWARDER_Direct3DCreate9(UINT SDKVersion) {
return ChainCall<decltype(&Direct3DCreate9), IDirect3D9*>("d3d9.dll", "Direct3DCreate9", App::Config::Acquire()->Runtime.ChainLoadPath_d3d9.Value(), [&](auto pfn, auto discardImmediately) {
const auto res = pfn(SDKVersion);
if (res && discardImmediately)
res->Release();
return res;
});
}
#endif
HRESULT WINAPI FORWARDER_DirectInput8Create(
HINSTANCE hinst,
DWORD dwVersion,
REFIID riidltf,
IUnknown** ppvOut,
LPUNKNOWN punkOuter
) {
return ChainCall<decltype(&DirectInput8Create), HRESULT>("dinput8.dll", "DirectInput8Create", App::Config::Acquire()->Runtime.ChainLoadPath_dinput8.Value(), [&](auto pfn, auto discardImmediately) {
const auto res = pfn(hinst, dwVersion, riidltf, reinterpret_cast<void**>(ppvOut), punkOuter);
if (res == S_OK && discardImmediately) {
if (ppvOut)
(*ppvOut)->Release();
}
return res;
});
}
static Utils::Win32::LoadedModule EnsureOriginalDependencyModule(const char* szDllName, std::filesystem::path originalDllPath) {
static std::mutex preventDuplicateLoad;
std::lock_guard lock(preventDuplicateLoad);
if (originalDllPath.empty())
originalDllPath = Utils::Win32::GetSystem32Path() / szDllName;
auto mod = Utils::Win32::LoadedModule(originalDllPath);
mod.SetPinned();
return mod;
}
| 32.419811 | 198 | 0.729521 | retaker |
704ec269c666e188c069d16a14b832138f56ff3c | 21,254 | cpp | C++ | tests/ami_test/no_module/client.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 20 | 2019-11-13T12:31:20.000Z | 2022-02-27T12:30:39.000Z | tests/ami_test/no_module/client.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 46 | 2019-11-15T20:40:18.000Z | 2022-03-31T19:04:36.000Z | tests/ami_test/no_module/client.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 5 | 2019-11-12T15:00:50.000Z | 2022-01-17T17:33:05.000Z | /**
* @file client.cpp
* @author Marijke Hengstmengel
*
* @brief CORBA C++11 client ami test
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "ace/Get_Opt.h"
#include "ace/Task.h"
#include "ami_testAmiC.h"
#include <thread>
#include "testlib/taox11_testlog.h"
const ACE_TCHAR *ior = ACE_TEXT("file://server.ior");
int16_t result = 0;
int16_t callback_attrib = 0;
int16_t callback_operation = 0;
int16_t callback_attrib_der = 0;
int16_t callback_operation_der = 0;
int16_t callback_excep = 0;
// Flag indicates that all replies have been received
static int16_t received_all_replies = 0;
bool
parse_args (int argc, ACE_TCHAR *argv[])
{
ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:"));
int c;
while ((c = get_opts ()) != -1)
switch (c)
{
case 'k':
ior = get_opts.opt_arg ();
break;
case '?':
default:
TAOX11_TEST_ERROR << "usage: -k <ior>"
<< std::endl;
return false;
}
// Indicates successful parsing of the command line
return true;
}
class Handler
: public virtual CORBA::amic_traits<MyFoo>::replyhandler_base_type
{
public:
/// Constructor.
Handler () = default;
/// Destructor.
~Handler () = default;
void foo (int32_t ami_return_val, int32_t out_l) override
{
TAOX11_TEST_INFO << "Callback method <Handler::foo> called: result <"
<< ami_return_val
<< ">, out_arg <" << out_l << ">"<< std::endl;
callback_operation++;
// Last reply flips the flag.
if (out_l == 931235)
{
received_all_replies = 1;
}
else if (out_l != 931233)
{
TAOX11_TEST_ERROR <<"ERROR: method <Handler::foo> out_l not 931233: "
<< out_l
<< std::endl;
result = 1;
}
if (ami_return_val != 931234)
{
TAOX11_TEST_ERROR << "ERROR: method <Handler::foo> ami_return_val not 931234: "
<< ami_return_val << std::endl;
result = 1;
}
}
void foo_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
TAOX11_TEST_INFO
<< "Callback method <foo_excep> called:"
<< " Testing proper exception handling."<< std::endl;
callback_excep++;
try
{
excep_holder->raise_exception ();
}
catch (const DidTheRightThing& ex)
{
TAOX11_TEST_INFO
<< "Callback method <Handler::foo_excep> received successfully <"
<< ex.id() << "> and <" << ex.whatDidTheRightThing() << ">."
<< std::endl;
if (ex.id() != 42)
{
TAOX11_TEST_ERROR << "ERROR: method <Handler::foo_excep> ex.id not 42 but "
<< ex.id() << std::endl;
result = 1;
}
if (ex.whatDidTheRightThing () != "Hello world")
{
TAOX11_TEST_ERROR
<< "ERROR: method <Handler::foo_excep> ex.whatDidTheRightThing not ok: "
<< ex.whatDidTheRightThing() << std::endl;
result = 1;
}
}
catch (const CORBA::Exception&)
{
TAOX11_TEST_ERROR << "Callback method <Handler::foo_excep> "
<< "caught the wrong exception -> ERROR" << std::endl;
result = 1;
}
}
void get_yadda (int32_t ret) override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <Handler::get_yadda> called: ret " << ret
<< std::endl;
};
void get_yadda_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
callback_excep++;
TAOX11_TEST_INFO << "Callback method <Handler::get_yadda_excep> called:"
<< std::endl;
try
{
excep_holder->raise_exception ();
}
catch (const CORBA::Exception& ex)
{
TAOX11_TEST_INFO << "... caught expected exception -> " << ex << std::endl;
std::stringstream excep_c;
excep_c << ex;
std::string excep_cstr = excep_c.str();
if (excep_cstr.find ("NO_IMPLEMENT") == std::string::npos)
{
TAOX11_TEST_ERROR << "ERROR: Callback method <Handler::get_yadda_excep>"
<< " returned wrong CORBA::exception! -"
<< excep_cstr << std::endl;
result = 1;
}
}
}
void set_yadda () override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <Handler::set_yadda> called:"<< std::endl;
}
void set_yadda_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
TAOX11_TEST_INFO << "Callback method <Handler::set_yadda_excep> called:"
<< std::endl;
callback_excep++;
try
{
excep_holder->raise_exception ();
}
catch (const CORBA::Exception& ex)
{
TAOX11_TEST_INFO << "... caught expected exception -> " << ex
<< std::endl;
std::stringstream excep_s;
excep_s << ex;
std::string excep_str = excep_s.str();
if (excep_str.find ("NO_IMPLEMENT") == std::string::npos)
{
TAOX11_TEST_ERROR << "ERROR: Callback method <Handler::set_yadda_excep> "
<< "returned wrong std::exception info! -"
<< excep_str << std::endl;
result = 1;
}
}
}
void get_bool_attr (bool result) override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <Handler::get_bool_attr> called:" << result
<< std::endl;
};
void get_bool_attr_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
TAOX11_TEST_INFO << "Callback method <Handler::get_bool_attr_excep> called:"
<< std::endl;
callback_excep++;
try
{
excep_holder->raise_exception ();
}
catch (const DidTheRightThing& ex)
{
TAOX11_TEST_INFO << "Callback method <Handler::get_bool_attr_excep> exception"
<< "received successfully <"
<< ex.id() << "> and <" << ex.whatDidTheRightThing()
<< ">."<< std::endl;
if (ex.id() != 42)
{
TAOX11_TEST_ERROR << "ERROR: ex.id not 42 but "<< ex.id()
<< std::endl;
result = 1;
}
if (ex.whatDidTheRightThing () != "Hello world")
{
TAOX11_TEST_ERROR << "ERROR: method <Handler::get_bool_attr_excep> "
<< "ex.whatDidTheRightThing not ok: "
<< ex.whatDidTheRightThing() << std::endl;
result = 1;
}
}
catch (const CORBA::Exception&)
{
TAOX11_TEST_ERROR << "Callback method <Handler::get_bool_attr_excep> "
<< "caught the wrong exception -> ERROR" << std::endl;
}
}
void set_bool_attr () override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <Handler::set_bool_attr> called:"
<< std::endl;
}
void set_bool_attr_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override
{
callback_excep++;
TAOX11_TEST_INFO << "Callback method <Handler::set_bool_attr_excep> called:"
<< std::endl;
}
void foo_struct (
const std::string& ami_return_val, const structType& t) override
{
callback_operation++;
TAOX11_TEST_INFO << "Callback method <fHandler::oo_struct> called: t.as = "
<< t.as() << " return = <" << ami_return_val
<< ">" << std::endl;
if ((t.as() != 5) || (ami_return_val != "bye from foo_struct"))
{
TAOX11_TEST_ERROR << "ERROR: ami_return_val not 'bye from foo_struct' but '"
<< ami_return_val
<< "' or t.as not <5> but <" << t.as() << ">" << std::endl;
result = 1;
}
}
void foo_struct_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override
{
}
};
class DerivedHandler
: public virtual CORBA::amic_traits<A::MyDerived>::replyhandler_base_type
{
public:
/// Constructor.
DerivedHandler () = default;
/// Destructor.
~DerivedHandler () = default;
void do_something (int32_t ami_return_val) override
{
callback_operation_der++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::do_something> called."
<< std::endl;
if (ami_return_val != 4)
{
TAOX11_TEST_ERROR << "ERROR: method <DerivedHandler::do_something> ami_return_val not 4: "
<< ami_return_val << std::endl;
result = 1;
}
}
void do_something_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::do_someting_excep> called."
<< std::endl;
}
void get_my_derived_attrib (int32_t ret) override
{
callback_attrib_der++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_my_derived_attrib> called: ret "
<< ret << std::endl;
if (ret != 5)
{
TAOX11_TEST_ERROR << "ERROR: method <DerivedHandler::get_my_derived_attrib ret not 5: "
<< ret << std::endl;
result = 1;
}
}
void get_my_derived_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_my_derived_attrib_excep> called."
<< std::endl;
}
void set_my_derived_attrib () override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_my_derived_attrib> called."
<< std::endl;
}
void set_my_derived_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_my_derived_attrib_excep> called:"
<< std::endl;
}
void foo (int32_t ami_return_val,int32_t out_l) override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::foo> called: result <" << ami_return_val
<< ">, out_arg <" << out_l << ">"<< std::endl;
}
void foo_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO
<< "Callback method <DerivedHandler::foo_excep> called:"
<< " Testing proper exception handling."<< std::endl;
}
void get_yadda (int32_t ret) override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_yadda> called: ret " << ret
<< std::endl;
};
void get_yadda_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
callback_excep++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_yadda_excep> called:"<< std::endl;
}
void set_yadda () override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_yadda> called:"<< std::endl;
}
void set_yadda_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_yadda_excep> called:" << std::endl;
callback_excep++;
}
void get_bool_attr (bool result) override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_bool_attr> called:" << result
<< std::endl;
};
void get_bool_attr_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override
{
TAOX11_TEST_INFO << "Callback method <DerivedHandler::get_bool_attr_excep> called:" << std::endl;
callback_excep++;
}
void set_bool_attr () override
{
callback_attrib++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_bool_attr> called:" << std::endl;
}
void set_bool_attr_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override
{
callback_excep++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::set_bool_attr_excep> called:"
<< std::endl;
}
void foo_struct (
const std::string& ami_return_val, const structType& t) override
{
callback_operation++;
TAOX11_TEST_INFO << "Callback method <DerivedHandler::foo_struct> called: t.as = " << t.as()
<< " return = <" << ami_return_val << ">" << std::endl;
}
void foo_struct_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type) override
{
}
};
int main(int argc, char* argv[])
{
try
{
IDL::traits<CORBA::ORB>::ref_type _orb = CORBA::ORB_init (argc, argv);
if (_orb == nullptr)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::ORB_init (argc, argv) returned null ORB."
<< std::endl;
return 1;
}
if (parse_args (argc, argv) == false)
return 1;
IDL::traits<CORBA::Object>::ref_type obj = _orb->string_to_object (ior);
if (!obj)
{
TAOX11_TEST_ERROR << "ERROR: string_to_object(<ior>) returned null reference."
<< std::endl;
return 1;
}
IDL::traits<Hello>::ref_type ami_test_var = IDL::traits<Hello>::narrow (obj);
if (!ami_test_var)
{
TAOX11_TEST_ERROR << "ERROR: IDL::traits<Hello>::narrow (obj) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "narrowed Hello interface" << std::endl;
// Instantiate the ReplyHandler and register that with the POA.
IDL::traits<CORBA::Object>::ref_type poa_obj =
_orb->resolve_initial_references ("RootPOA");
if (!poa_obj)
{
TAOX11_TEST_ERROR
<< "ERROR: resolve_initial_references (\"RootPOA\") returned null reference."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "retrieved RootPOA object reference" << std::endl;
IDL::traits<PortableServer::POA>::ref_type root_poa =
IDL::traits<PortableServer::POA>::narrow (poa_obj);
if (!root_poa)
{
TAOX11_TEST_ERROR
<< "ERROR: IDL::traits<PortableServer::POA>::narrow (obj)"
<<" returned null object." << std::endl;
return 1;
}
TAOX11_TEST_INFO << "narrowed POA interface" << std::endl;
IDL::traits<PortableServer::POAManager>::ref_type poaman =
root_poa->the_POAManager ();
if (!poaman)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->the_POAManager () returned null object."
<< std::endl;
return 1;
}
CORBA::amic_traits<MyFoo>::replyhandler_servant_ref_type test_handler_impl =
CORBA::make_reference<Handler> ();
TAOX11_TEST_INFO << "created MyFoo replyhandler servant" << std::endl;
PortableServer::ObjectId id = root_poa->activate_object (test_handler_impl);
TAOX11_TEST_INFO << "activated MyFoo replyhandler servant" << std::endl;
IDL::traits<CORBA::Object>::ref_type test_handler_obj =
root_poa->id_to_reference (id);
if (test_handler_obj == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->id_to_reference (id) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<MyFoo>::replyhandler_ref_type test_handler =
CORBA::amic_traits<MyFoo>::replyhandler_traits::narrow (test_handler_obj);
if (test_handler == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: CORBA::amic_traits<MyFoo>::replyhandler_traits::narrow"
<< " (test_handler_obj) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyDerived>::replyhandler_servant_ref_type test_handler_der_impl =
CORBA::make_reference<DerivedHandler> ();
TAOX11_TEST_INFO << "created MyDerived replyhandler servant" << std::endl;
PortableServer::ObjectId id_der = root_poa->activate_object (test_handler_der_impl);
TAOX11_TEST_INFO << "activated MyDerived replyhandler servant" << std::endl;
IDL::traits<CORBA::Object>::ref_type test_handler_der_obj =
root_poa->id_to_reference (id_der);
if (test_handler_der_obj == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->id_to_reference (id_der) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyDerived>::replyhandler_ref_type test_handler_der =
CORBA::amic_traits<A::MyDerived>::replyhandler_traits::narrow (test_handler_der_obj);
if (test_handler_der == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: CORBA::amic_traits<A::MyDerived>::replyhandler_traits::narrow"
<< " (test_handler_obj) returned null reference."
<< std::endl;
return 1;
}
poaman->activate ();
A::MyDerived::_ref_type i_der_ref = ami_test_var->get_iMyDerived();
if (!i_der_ref)
{
TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyDerived returned null object."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyDerived>::ref_type i_der =
CORBA::amic_traits<A::MyDerived>::narrow (i_der_ref);
if (!i_der)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<A::MyDerived>::narrow (i_der) "
<< "returned null object."
<< std::endl;
return 1;
}
MyFoo::_ref_type i_foo_ref = ami_test_var->get_iMyFoo();
if (!i_foo_ref)
{
TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyFoo returned null object." << std::endl;
return 1;
}
CORBA::amic_traits<MyFoo>::ref_type i_foo =
CORBA::amic_traits<MyFoo>::narrow (i_foo_ref);
if (!i_foo)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traits<MyFoo>::narrow (i_foo) "
<< " returned null object."
<< std::endl;
return 1;
}
// Trigger the DidTheRightThing exception on the server side
// by sending 0 to it.
TAOX11_TEST_INFO << "Client: Sending asynch message sendc_foo to trigger an exception"
<< std::endl;
i_foo->sendc_foo (test_handler,
0,
"Let's talk AMI.");
int32_t l = 931247;
TAOX11_TEST_INFO << "Client: Sending asynch message foo." << std::endl;
i_foo->sendc_foo (test_handler,
l,
"Let's talk AMI.");
i_der->sendc_do_something(test_handler_der, "Hello");
// Begin test of attributes
TAOX11_TEST_INFO << "Client: Sending asynch message sendc_get_yadda to trigger "
<< "an exception" << std::endl;
i_foo->sendc_get_yadda (test_handler);
TAOX11_TEST_INFO << "Client: Sending asynch attributes yadda." << std::endl;
i_foo->sendc_set_yadda (test_handler, 4711);
i_foo->sendc_get_yadda (test_handler);
TAOX11_TEST_INFO << "Client: Sending asynch message sendc_set_yadda to trigger "
<< "an exception" << std::endl;
i_foo->sendc_set_yadda (test_handler, 0);
TAOX11_TEST_INFO << "Client: Sending asynch message sendc_get_bool_attr to trigger "
<< "an exception" << std::endl;
i_foo->sendc_get_bool_attr (test_handler);
TAOX11_TEST_INFO << "Client: Sending asynch attributes bool_attr." << std::endl;
i_foo->sendc_set_bool_attr (test_handler, false);
i_foo->sendc_get_bool_attr (test_handler);
TAOX11_TEST_INFO << "Client: Sending asynch message sendc_set_yadda to trigger "
<< "an exception" << std::endl;
i_foo->sendc_set_bool_attr (test_handler, true);
i_der->sendc_get_my_derived_attrib (test_handler_der);
// End test of attributes
i_foo->sendc_foo_struct (test_handler);
TAOX11_TEST_INFO << "Client: Sending another asynch message foo." << std::endl;
i_foo->sendc_foo (test_handler,
l,
"Let's talk AMI.");
TAOX11_TEST_INFO << "Client: Sending the last asynch message foo." << std::endl;
i_foo->sendc_foo (test_handler,
931235,
"Let's talk AMI the last time.");
TAOX11_TEST_INFO << "Client: Do something else before coming back for the replies."
<< std::endl;
for (int i = 0; i < 10; i ++)
{
TAOX11_TEST_INFO << " ...";
std::this_thread::sleep_for (std::chrono::milliseconds (10));
}
TAOX11_TEST_INFO << std::endl << "Client: Now let's look for the replies." << std::endl;
std::this_thread::sleep_for (std::chrono::seconds (2));
while (!received_all_replies)
{
std::chrono::seconds tv (1);
_orb->perform_work (tv);
}
if ((callback_operation != 4) ||
(callback_excep != 5 ) ||
(callback_attrib != 4 ) ||
(callback_attrib_der != 1 ) ||
(callback_operation_der != 1 ))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected callbacks."
<< " Foo : expected -4- , received -" << callback_operation << "-"
<< " do_something : expected -1- , received -" << callback_operation_der << "-"
<< " Attrib : expected -4-, received -" << callback_attrib << "-"
<< " Attrib derived : expected -1-, received -" << callback_attrib_der << "-"
<< " Exceptions: expected -5-, received -" << callback_excep << "-."
<< std::endl;
result = 1;
}
ami_test_var->shutdown ();
_orb->destroy ();
}
catch (const std::exception& e)
{
TAOX11_TEST_ERROR << "exception caught: " << e << std::endl;
return 1;
}
return result;
}
| 30.362857 | 100 | 0.605063 | ClausKlein |
7050f2e5980ace3eb9362d575e23d51924b74e39 | 598 | cc | C++ | core/src/counter.cc | avidbots/prometheus-cpp | e7b542c3bd5e68d5377641dd7a90b1a4a9146b0b | [
"MIT"
] | null | null | null | core/src/counter.cc | avidbots/prometheus-cpp | e7b542c3bd5e68d5377641dd7a90b1a4a9146b0b | [
"MIT"
] | 2 | 2020-09-29T14:55:30.000Z | 2021-06-08T16:40:42.000Z | core/src/counter.cc | avidbots/prometheus-cpp | e7b542c3bd5e68d5377641dd7a90b1a4a9146b0b | [
"MIT"
] | null | null | null | #include "prometheus/counter.h"
namespace prometheus {
Counter::Counter(const bool alert_if_no_family) : MetricBase(alert_if_no_family) {};
void Counter::Reset() {
value_ = 0;
last_update_ = std::time(nullptr);
AlertIfNoFamily();
}
void Counter::Increment(const double value) {
if (value < 0.0) return;
value_ = value_ + value;
last_update_ = std::time(nullptr);
AlertIfNoFamily();
}
double Counter::Value() const { return value_; }
ClientMetric Counter::Collect() const {
ClientMetric metric;
metric.counter.value = Value();
return metric;
}
} // namespace prometheus
| 19.933333 | 84 | 0.70903 | avidbots |
7054eadb028169a9fd9e35701f36e16c5d4e20f0 | 678 | cpp | C++ | Bit Algorithm/Check if A Number is Power of Two/SolutionByAkshat.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 261 | 2019-09-30T19:47:29.000Z | 2022-03-29T18:20:07.000Z | Bit Algorithm/Check if A Number is Power of Two/SolutionByAkshat.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 647 | 2019-10-01T16:51:29.000Z | 2021-12-16T20:39:44.000Z | Bit Algorithm/Check if A Number is Power of Two/SolutionByAkshat.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 383 | 2019-09-30T19:32:07.000Z | 2022-03-24T16:18:26.000Z | /*
Program Description:-Finding whether a given number is a power of two or not
->checktwo() function performs the operation of checking that whether a number is a power of two or not
*/
#include <iostream>
using namespace std;
int checktwo(int n)
{
while (n % 2 == 0 && n != 1 && n != 0) {
n /= 2;
}
if (n == 1 || n == -1)
return 1;
else
return 0;
}
int main()
{
int n;
cout << "Enter the number that you want to check" << endl;
cin >> n;
int ans = checktwo(n);
if (ans == 1)
cout << "The given number is a power of two" << endl;
else
cout << "The given number is not a power of two" << endl;
}
| 23.37931 | 104 | 0.563422 | Mdanish777 |
7056d48b5554f5390c94686c59484a028f902958 | 705 | hpp | C++ | food.hpp | cwink87/wsnake | 6d4f3a42d83f6b54312316302dd52cbd80370dd5 | [
"MIT"
] | null | null | null | food.hpp | cwink87/wsnake | 6d4f3a42d83f6b54312316302dd52cbd80370dd5 | [
"MIT"
] | null | null | null | food.hpp | cwink87/wsnake | 6d4f3a42d83f6b54312316302dd52cbd80370dd5 | [
"MIT"
] | null | null | null | #ifndef FOOD_HPP
#define FOOD_HPP
#include "grid.hpp"
class Food final {
public:
explicit Food(const Grid &grid) noexcept;
~Food() noexcept = default;
Food(const Food &) noexcept = default;
Food(Food &&) noexcept = default;
Food &operator=(const Food &) noexcept = default;
Food &operator=(Food &&) noexcept = default;
auto x() const noexcept -> std::int32_t;
auto y() const noexcept -> std::int32_t;
private:
struct Impl;
std::shared_ptr<Impl> impl;
};
auto draw(const Food &food, const Grid &grid, const Display &display, const std::uint8_t red, const std::uint8_t green,
const std::uint8_t blue, const std::uint8_t alpha = 255) noexcept -> void;
#endif // FOOD_HPP
| 25.178571 | 119 | 0.686525 | cwink87 |
7058bd21523d751bcda72d9809aa839f0e9cca5f | 18,574 | cpp | C++ | src/Details/xbmp_tools_atlas.cpp | LIONant-depot/xbmp_tools | 670320ec35470b0204af8413bf34d017aa6e2868 | [
"MIT"
] | null | null | null | src/Details/xbmp_tools_atlas.cpp | LIONant-depot/xbmp_tools | 670320ec35470b0204af8413bf34d017aa6e2868 | [
"MIT"
] | null | null | null | src/Details/xbmp_tools_atlas.cpp | LIONant-depot/xbmp_tools | 670320ec35470b0204af8413bf34d017aa6e2868 | [
"MIT"
] | null | null | null | namespace xbmp::tools{
//-------------------------------------------------------------------------------------------------
static
int Area( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB )
{
int b1 = (*pA)->getArea();
int a1 = (*pB)->getArea();
if( a1 < b1 ) return -1;
return a1>b1;
}
//-------------------------------------------------------------------------------------------------
static
int Perimeter( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB )
{
int b1 = (*pA)->getPerimeter();
int a1 = (*pB)->getPerimeter();
if( a1 < b1 ) return -1;
return a1>b1;
}
//-------------------------------------------------------------------------------------------------
static
int MaxSide( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB )
{
int b1 = std::max( (*pA)->m_W, (*pA)->m_H );
int a1 = std::max( (*pB)->m_W, (*pB)->m_H );
if( a1 < b1 ) return -1;
return a1>b1;
}
//-------------------------------------------------------------------------------------------------
static
int MaxWidth( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB )
{
int b1 = (*pA)->m_W;
int a1 = (*pB)->m_W;
if( a1 < b1 ) return -1;
return a1>b1;
}
//-------------------------------------------------------------------------------------------------
static
int MaxHeight( const atlas::rect_xywhf** pA, const atlas::rect_xywhf** pB )
{
int b1 = (*pA)->m_H;
int a1 = (*pB)->m_H;
if( a1 < b1 ) return -1;
return a1>b1;
}
// just add another comparing function name to cmpf to perform another packing attempt
// more functions == slower but probably more efficient cases covered and hence less area wasted
constexpr static auto comparison_fn_v = std::array
{
Area,
Perimeter,
MaxSide,
MaxWidth,
MaxHeight
};
// if you find the algorithm running too slow you may double this factor to increase speed but also decrease efficiency
// 1 == most efficient, slowest
// efficiency may be still satisfying at 64 or even 256 with nice speedup
constexpr static int s_discard_step_v = 16;
// For every sorting function, algorithm will perform packing attempts beginning with a bin with width
// and height equal to max_side, and decreasing its dimensions if it finds out that rectangles did
// actually fit, increasing otherwise. Although, it's doing that in sort of binary search manner, so
// for every comparing function it will perform at most log2(max_side) packing attempts looking for
// the smallest possible bin size. discard_step means that if the algorithm will break of the searching
// loop if the rectangles fit but "it may be possible to fit them in a bin smaller by discard_step"
//
// may be pretty slow in debug mode anyway (std::vector and stuff like that in debug mode is always slow)
//
// the algorithm was based on http://www.blackpawn.com/texts/lightmaps/default.html
// the algorithm reuses the node tree so it doesn't reallocate them between searching attempts
//
//
// please let me know about bugs at <----
// unknownunreleased@gmail.com |
// |
// |
// ps. I'm 16 so take this --------------- more than seriously, though I made some realtime tests
// with packing several hundreds of rectangles every frame, no crashes, no memory leaks, good results
// Thank you.
struct node
{
struct pnode
{
node* m_pNode;
bool m_Fill;
pnode() : m_Fill(false), m_pNode( nullptr ) {}
void setup( int L, int T, int R, int B )
{
if( m_pNode )
{
m_pNode->m_RC = atlas::rect_ltrb( L, T, R, B );
m_pNode->m_pID = nullptr;
}
else
{
m_pNode = new node();
m_pNode->setup( atlas::rect_ltrb( L, T, R, B ) );
}
m_Fill = true;
}
};
pnode m_C[2];
atlas::rect_ltrb m_RC;
atlas::rect_xywhf* m_pID;
~node()
{
if( m_C[0].m_pNode ) delete m_C[0].m_pNode;
if( m_C[1].m_pNode ) delete m_C[1].m_pNode;
}
node( void )
{
setup( atlas::rect_ltrb(0,0,0,0) );
}
void setup( const atlas::rect_ltrb& RC )
{
m_pID = nullptr;
m_RC = RC;
}
void Reset( const atlas::rect_wh& R )
{
m_pID = nullptr;
m_RC = atlas::rect_ltrb( 0, 0, R.m_W, R.m_H );
DelCheck();
}
void DelCheck( void )
{
if( m_C[0].m_pNode ) { m_C[0].m_Fill = false; m_C[0].m_pNode->DelCheck(); }
if( m_C[1].m_pNode ) { m_C[1].m_Fill = false; m_C[1].m_pNode->DelCheck(); }
}
node* Insert( atlas::rect_xywhf& ImageRect )
{
if( m_C[0].m_pNode && m_C[0].m_Fill )
{
node* pNewNode = m_C[0].m_pNode->Insert( ImageRect );
if( pNewNode ) return pNewNode;
pNewNode = m_C[1].m_pNode->Insert( ImageRect );
return pNewNode;
}
if( m_pID ) return nullptr;
int f = ImageRect.Fits( atlas::rect_xywh(m_RC) );
switch( f )
{
case 0: return 0;
case 1: ImageRect.m_bFlipped = false; break;
case 2: ImageRect.m_bFlipped = true; break;
case 3: m_pID = &ImageRect; ImageRect.m_bFlipped = false; return this;
case 4: m_pID = &ImageRect; ImageRect.m_bFlipped = true; return this;
}
int iW = (ImageRect.m_bFlipped ? ImageRect.m_H : ImageRect.m_W);
int iH = (ImageRect.m_bFlipped ? ImageRect.m_W : ImageRect.m_H);
if( ( m_RC.getWidth() - iW) > ( m_RC.getHeight() - iH) )
{
m_C[0].setup( m_RC.m_Left, m_RC.m_Top, m_RC.m_Left + iW, m_RC.m_Bottom );
m_C[1].setup( m_RC.m_Left + iW, m_RC.m_Top, m_RC.m_Right, m_RC.m_Bottom );
}
else
{
m_C[0].setup( m_RC.m_Left, m_RC.m_Top, m_RC.m_Right, m_RC.m_Top + iH );
m_C[1].setup( m_RC.m_Left, m_RC.m_Top + iH, m_RC.m_Right, m_RC.m_Bottom );
}
return m_C[0].m_pNode->Insert( ImageRect );
}
};
//-------------------------------------------------------------------------------------------------
static
atlas::rect_wh TheRect2D( atlas::rect_xywhf* const* pV
, atlas::pack_mode Mode
, int n
, int MaxS
, xcore::vector<atlas::rect_xywhf*>& Succ
, xcore::vector<atlas::rect_xywhf*>& UnSucc )
{
node Root;
const int nFuncs = 5;
atlas::rect_xywhf** Order[ nFuncs ];
const int Multiple = (Mode == atlas::pack_mode::MULTIPLE_OF_4)?4:8;
for( int f = 0; f < nFuncs; ++f )
{
Order[f] = new atlas::rect_xywhf*[n]{};
std::memcpy( Order[f], pV, sizeof(atlas::rect_xywhf*) * n);
std::qsort( (void*)Order[f], n, sizeof(atlas::rect_xywhf*), (int(*)(const void*, const void*))comparison_fn_v[f] );
}
atlas::rect_wh MinBin = atlas::rect_wh( MaxS, MaxS );
int MinFunc = -1;
int BestFunc = 0;
int BestArea = 0;
int TheArea = 0;
bool bFail = false;
int Step, Fit;
for( int f = 0; f < nFuncs; ++f )
{
pV = Order[f];
Step = MinBin.m_W / 2;
Root.Reset( MinBin );
while(1)
{
if( Root.m_RC.getWidth() > MinBin.m_W )
{
if( MinFunc > -1 )
break;
TheArea = 0;
Root.Reset( MinBin );
for( int i = 0; i < n; ++i )
{
if( Root.Insert( *pV[i]) )
TheArea += pV[i]->getArea();
}
bFail = true;
break;
}
Fit = -1;
for( int i = 0; i < n; ++i )
{
if( !Root.Insert( *pV[i]) )
{
Fit = 1;
break;
}
}
if( Fit == -1 && Step <= s_discard_step_v )
break;
int OldW = Root.m_RC.getWidth();
int OldH = Root.m_RC.getHeight();
int NewW = OldW + Fit*Step;
int NewH = OldH + Fit*Step;
if( Mode == atlas::pack_mode::MULTIPLE_OF_4 ||
Mode == atlas::pack_mode::MULTIPLE_OF_8 )
{
NewW = xcore::bits::Align( NewW, Multiple );
NewH = xcore::bits::Align( NewH, Multiple );
xassert( xcore::bits::Align( OldW, Multiple) == OldW );
xassert( xcore::bits::Align( OldH, Multiple) == OldH );
}
else if( Mode == atlas::pack_mode::POWER_OF_TWO ||
Mode == atlas::pack_mode::POWER_OF_TWO_SQUARE )
{
NewW = xcore::bits::RoundToNextPowOfTwo( NewW );
NewH = xcore::bits::RoundToNextPowOfTwo( NewH );
xassert( xcore::bits::RoundToNextPowOfTwo( OldW ) == OldW );
xassert( xcore::bits::RoundToNextPowOfTwo( OldH ) == OldH );
}
//
// Try to choose the search in the right dimension
//
if( Mode != atlas::pack_mode::ANY_SIZE )
{
if( Fit == 1 )
{
if( OldW < OldH ) NewH = OldH;
else NewW = OldW;
}
else
{
if( OldW < OldH ) NewW = OldW;
else NewH = OldH;
}
}
//
// For square sizes we need to pick the best dimension for all
//
if( Mode == atlas::pack_mode::POWER_OF_TWO_SQUARE )
{
if( Fit == 1 )
{
NewH = NewW = std::max( NewW, NewH );
}
else
{
NewH = NewW = std::min( NewW, NewH );
}
}
//
// Ok now we can change the size
//
Root.Reset( atlas::rect_wh( NewW, NewH ) );
//
// Keep searching
//
Step /= 2;
if( !Step )
Step = 1;
}
if( !bFail && ( MinBin.getArea() >= Root.m_RC.getArea()) )
{
MinBin = atlas::rect_wh( Root.m_RC );
MinFunc = f;
}
else if( bFail && ( TheArea > BestArea) )
{
BestArea = TheArea;
BestFunc = f;
}
bFail = false;
}
pV = Order[ MinFunc == -1 ? BestFunc : MinFunc ];
int ClipX = 0, ClipY = 0;
node* pRet;
Root.Reset( MinBin );
for( int i = 0; i < n; ++i )
{
pRet = Root.Insert( *pV[i]);
if( pRet )
{
pV[i]->m_X = pRet->m_RC.m_Left;
pV[i]->m_Y = pRet->m_RC.m_Top;
if( pV[i]->m_bFlipped )
{
pV[i]->m_bFlipped = false;
pV[i]->Flip();
}
ClipX = std::max( ClipX, pRet->m_RC.m_Right );
ClipY = std::max( ClipY, pRet->m_RC.m_Bottom );
Succ.append() = pV[i];
}
else
{
UnSucc.append() = pV[i];
pV[i]->m_bFlipped = false;
}
}
for( int f = 0; f < nFuncs; ++f )
{
delete Order[f];
}
// Make sure that we do return a power of two texture
if( Mode == atlas::pack_mode::POWER_OF_TWO ||
Mode == atlas::pack_mode::POWER_OF_TWO_SQUARE )
{
return atlas::rect_wh( xcore::bits::RoundToNextPowOfTwo(ClipX), xcore::bits::RoundToNextPowOfTwo(ClipY) );
}
else if( Mode == atlas::pack_mode::MULTIPLE_OF_4 ||
Mode == atlas::pack_mode::MULTIPLE_OF_8 )
{
const int Multiple = (Mode == atlas::pack_mode::MULTIPLE_OF_4)?4:8;
return atlas::rect_wh( xcore::bits::Align(ClipX, Multiple), xcore::bits::Align(ClipY,Multiple) );
}
return atlas::rect_wh( (ClipX), (ClipY) );
}
//-------------------------------------------------------------------------------------------------
bool atlas::Pack( rect_xywhf* const* pV, int nRects, int MaxSize, xcore::vector<bin>& Bins, pack_mode Mode )
{
rect_wh TheRect( MaxSize, MaxSize );
// make sure that all the rectangles fit in the given MaxSize
for( int i = 0; i < nRects; ++i )
{
if( !pV[i]->Fits(TheRect) )
return false;
}
// Create a double buffer array of pointers
xcore::vector<rect_xywhf*> Vec[2];
xcore::vector<rect_xywhf*>* pVec[2] = { &Vec[0], &Vec[1] };
// Set one pointer per rectangle past by the user
Vec[0].appendList( nRects );
// Initialize the firt array to zero
std::memcpy( &Vec[0][0], pV, sizeof(rect_xywhf*) * nRects );
while(1)
{
bin& NewBin = Bins.append();
NewBin.m_Size = TheRect2D( &((*pVec[0])[0]), Mode, static_cast<int>(pVec[0]->size()), MaxSize, NewBin.m_Rects, *pVec[1] );
pVec[0]->clear();
if( pVec[1]->size() == 0 ) break;
std::swap( pVec[0], pVec[1] );
}
return true;
}
//-------------------------------------------------------------------------------------------------
atlas::rect_wh::rect_wh(const rect_ltrb& rr) : m_W(rr.getWidth()), m_H(rr.getHeight()) {}
atlas::rect_wh::rect_wh(const rect_xywh& rr) : m_W(rr.getWidth()), m_H(rr.getHeight()) {}
atlas::rect_wh::rect_wh(int w, int h) : m_W(w), m_H(h) {}
//-------------------------------------------------------------------------------------------------
int atlas::rect_wh::Fits( const rect_wh& r ) const
{
if( m_W == r.m_W && m_H == r.m_H ) return 3;
if( m_H == r.m_W && m_W == r.m_H ) return 4;
if( m_W <= r.m_W && m_H <= r.m_H ) return 1;
if( m_H <= r.m_W && m_W <= r.m_H ) return 2;
return 0;
}
//-------------------------------------------------------------------------------------------------
atlas::rect_ltrb::rect_ltrb( void ) : m_Left(0), m_Top(0), m_Right(0), m_Bottom(0) {}
atlas::rect_ltrb::rect_ltrb( int l, int t, int r, int b) : m_Left(l), m_Top(t), m_Right(r), m_Bottom(b) {}
//-------------------------------------------------------------------------------------------------
int atlas::rect_ltrb::getWidth( void ) const
{
return m_Right - m_Left;
}
//-------------------------------------------------------------------------------------------------
int atlas::rect_ltrb::getHeight( void ) const
{
return m_Bottom - m_Top;
}
//-------------------------------------------------------------------------------------------------
int atlas::rect_ltrb::getArea( void ) const
{
return getWidth() * getHeight();
}
//-------------------------------------------------------------------------------------------------
int atlas::rect_ltrb::getPerimeter( void ) const
{
return 2*getWidth() + 2*getHeight();
}
//-------------------------------------------------------------------------------------------------
void atlas::rect_ltrb::setWidth( int Width )
{
m_Right = m_Left + Width;
}
//-------------------------------------------------------------------------------------------------
void atlas::rect_ltrb::setHeight( int Height )
{
m_Bottom = m_Top + Height;
}
//-------------------------------------------------------------------------------------------------
atlas::rect_xywh::rect_xywh( void ) : m_X(0), m_Y(0) {}
atlas::rect_xywh::rect_xywh( const rect_ltrb& rc ) :
m_X( rc.m_Left ), m_Y( rc.m_Top )
{
m_H = rc.m_Bottom - rc.m_Top;
m_W = rc.m_Right - rc.m_Left;
}
//-------------------------------------------------------------------------------------------------
atlas::rect_xywh::rect_xywh( int x, int y, int w, int h ) : m_X(x), m_Y(y), rect_wh( w, h ) {}
//-------------------------------------------------------------------------------------------------
atlas::rect_xywh::operator atlas::rect_ltrb( void )
{
rect_ltrb rr( m_X, m_Y, 0, 0 );
rr.setWidth ( m_W );
rr.setHeight( m_H );
return rr;
}
//-------------------------------------------------------------------------------------------------
int atlas::rect_xywh::getRight( void ) const
{
return m_X + m_W;
};
//-------------------------------------------------------------------------------------------------
int atlas::rect_xywh::getBottom( void ) const
{
return m_Y + m_H;
}
//-------------------------------------------------------------------------------------------------
void atlas::rect_xywh::setWidth( int Right )
{
m_W = Right - m_X;
}
//-------------------------------------------------------------------------------------------------
void atlas::rect_xywh::setHeight( int Bottom )
{
m_H = Bottom - m_Y;
}
//-------------------------------------------------------------------------------------------------
int atlas::rect_wh::getArea( void ) const
{
return m_W * m_H;
}
//-------------------------------------------------------------------------------------------------
int atlas::rect_wh::getPerimeter( void ) const
{
return 2 * m_W + 2 * m_H;
}
//-------------------------------------------------------------------------------------------------
atlas::rect_xywhf::rect_xywhf( const rect_ltrb& rr ) : rect_xywh(rr), m_bFlipped( false ) {}
atlas::rect_xywhf::rect_xywhf( int x, int y, int width, int height ) : rect_xywh( x, y, width, height ), m_bFlipped( false ) {}
atlas::rect_xywhf::rect_xywhf() : m_bFlipped( false ) {}
//-------------------------------------------------------------------------------------------------
void atlas::rect_xywhf::Flip( void )
{
m_bFlipped = !m_bFlipped;
std::swap( m_W, m_H );
}
} // end of namespace xbmp::tools | 31.750427 | 130 | 0.428233 | LIONant-depot |
705b97c5b3556c629ef061ce743bb0f610a7d684 | 33,769 | cpp | C++ | tcpclientcom/TCPClient.cpp | lasellers/IntrafoundationTCPClient | 4e9b9666b914d229335ef534972a94594e93be2b | [
"Intel",
"DOC",
"NTP",
"Unlicense"
] | null | null | null | tcpclientcom/TCPClient.cpp | lasellers/IntrafoundationTCPClient | 4e9b9666b914d229335ef534972a94594e93be2b | [
"Intel",
"DOC",
"NTP",
"Unlicense"
] | null | null | null | tcpclientcom/TCPClient.cpp | lasellers/IntrafoundationTCPClient | 4e9b9666b914d229335ef534972a94594e93be2b | [
"Intel",
"DOC",
"NTP",
"Unlicense"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
//
// Intrafoundation.Tcpclient.3
//
// Copyright 1999, 200, 2001, 2003, 2004 by Lewis A. Sellers (AKA Min)
// http://www.intrafoundation.com
// webmaster@intrafoundation.com
//
// Software Homepage: http://www.intrafoundation.com/software/tcpclient.htm
//
//
/////////////////////////////////////////////////////////////////////////////
// TCPClient.cpp : Implementation of CTcpclientcomApp and DLL registration.
/*
ORIGINAL 2.X:
send stats
secs kbps
x 1 3636 277.56
x 2 1983 508.945
x 4 1202 839.63
x 8 741 1361.995
x 16 24755 40.76
x 64 2587
-----
x 128 318
x 256 704
x 512 1229
x 1024 969
recv stats
secs kbps
x 1 82909 12.17
x 2 42070 23.98
x 4 20449 48.19
x 8 10786 93.56
x 16 5548 181.91
x 32 349
x 64 618 (32768)
----------------- 32708
x 128 847
x 256 1185
x 512 1975
x 1024 2242
recv blocksize 30mb
blocksize kbps
32768 639 22
262144 562 159
1048576 642 611
*/
#if !defined(_MT)
#error This software requires a multithreaded C run-time library.
#endif
//
#include "stdafx.h"
#include "tcpclientcom.h"
#include "TCPClient.h"
/////////////////////////////////////////////////////////////////////////////
//
// _open file handling
#include "io.h"
#include <fcntl.h>
//bstr
#include <comdef.h>
// _stat
#include "sys\stat.h"
//
#define MAX_DWORDEXPANSION 32
#define MAX_IPEXPANSION (26+60)
#define MAX_PORTEXPANSION (5+16)
#define MAX_URLEXPANSION (26+60+1+5)
//
#include "Mutex.h"
#include "Log.h"
#include "BSTR.h"
#include "ErrorStringWSA.h"
#include "MD5.h"
/////////////////////////////////////////////////////////////////////////////
//
//
const char *description="Intrafoundation.TCPClient.3";
const char *copyright="Copyright (c) 2000, 20001, 2003, 2004, 2012 by Lewis Sellers. <a href=\"http://www.intrafoundation.com\">http://intrafoundation.com</a>";
const char *version="3.2, August 30th 2012";
// TRUE and FALSE defined as ints to support old version of CF that don't understand boolean types.
// Annoying.
//const int TRUE=1;
//const int FALSE=0;
/////////////////////////////////////////////////////////////////////////////
//
//
/*
statics
*/
int CTCPClient::m_last_instance=0;
CMutex CTCPClient::mutex;
/*
*/
unsigned _int64 CTCPClient::bitmask[64]={
0x1,
0x3,
0x7,
0xf,
0x1f,
0x3f,
0x7f,
0xff,
0x1ff,
0x3ff,
0x7ff,
0xfff,
0x1fff,
0x3fff,
0x7fff,
0xffff,
0x1ffff,
0x3ffff,
0x7ffff,
0xfffff,
0x1fffff,
0x3fffff,
0x7fffff,
0xffffff,
0x1ffffff,
0x3ffffff,
0x7ffffff,
0xfffffff,
0x1fffffff,
0x3fffffff,
0x7fffffff,
0xffffffff,
0x1ffffffff,
0x3ffffffff,
0x7ffffffff,
0xfffffffff,
0x1fffffffff,
0x3fffffffff,
0x7fffffffff,
0xffffffffff,
0x1ffffffffff,
0x3ffffffffff,
0x7ffffffffff,
0xfffffffffff,
0x1fffffffffff,
0x3fffffffffff,
0x7fffffffffff,
0xffffffffffff,
0x1ffffffffffff,
0x3ffffffffffff,
0x7ffffffffffff,
0xfffffffffffff,
0x1fffffffffffff,
0x3fffffffffffff,
0x7fffffffffffff,
0xffffffffffffff,
0x1ffffffffffffff,
0x3ffffffffffffff,
0x7ffffffffffffff,
0xfffffffffffffff,
0x1fffffffffffffff,
0x3fffffffffffffff,
0x7fffffffffffffff,
0xffffffffffffffff
};
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
CTCPClient::CTCPClient()
{
m_instance=++m_last_instance;
//
if(mutex.Try())
{
w=NULL;
}
}
/*
*/
CTCPClient::~CTCPClient()
{
Close();
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
Returns:
a boolean in the form of a long (because old versions of CF4 are too stupid to use a true boolean.)
*/
STDMETHODIMP CTCPClient::Open(
BSTR strhost,
BSTR strport,
long *pconnected
)
{
#ifdef _DEBUG
printf("CTCPClient::Open strhost=%S strport=%S (thread %lu)\n",strhost,strport,GetCurrentThreadId());
#endif
//
*pconnected=TRUE;
//
mutex.Lock();
//
if(mutex.Try())
{
//
if(!w)
{
//
char ip[MAX_IPEXPANSION+1];
char port[MAX_PORTEXPANSION+1];
wcstombs(ip,strhost,min(wcslen(strhost)+1,MAX_IPEXPANSION));
wcstombs(port,strport,min(wcslen(strport)+1,MAX_PORTEXPANSION));
w=new tcp(
(char* const)ip,
(char* const)port
);
if(w)
{
if(w->is_connected())
*pconnected=TRUE;
else
{
*pconnected=FALSE;
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Open",
L"Low-level tcp class is_connected (%s) failed on host %S:%S.",
w->is_connected()?L"true":L"false",ip,port);
delete w;
w=NULL;
}
}
}
//
mutex.Untry();
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::Close()
{
#ifdef _DEBUG
printf("CTCPClient::Close (thread %lu)\n",GetCurrentThreadId());
#endif
//
mutex.Unlock();
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Close",
L"Socket not open.");
}
else
{
delete w;
w=NULL;
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::Send(BSTR inText)
{
#ifdef _DEBUG
CBSTR bstr_fns;
printf("CTCPClient::Send inText=%S inText_length=%d\n",inText,bstr_fns.character_length(inText));
#endif
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Send",
L"Socket not open.");
}
else
{
if(inText!=NULL)
{
CBSTR bstr;
const int inText_length=bstr.character_length(inText);
char *pszstr=new char[inText_length+1];
if(pszstr)
{
wcstombs(pszstr,inText,inText_length);
#ifdef _DEBUG
printf("inText_length=%d\n",inText_length);
printf("pszstr=%s\n",pszstr);
#endif
w->Send(pszstr,inText_length);
delete[] pszstr;
pszstr=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Send",
L"Memory allocation failure (%d bytes).",inText_length);
retval=E_OUTOFMEMORY;
}
}
else
retval=E_POINTER;
}
//
mutex.Untry();
}
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::Recv(BSTR *poutText)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Recv",
L"Socket not open.");
*poutText=SysAllocString(L"");
}
else
{
char *buf=NULL;
const int buf_length=w->Recv(buf);
if(buf_length<=0)
*poutText=SysAllocString(L"");
else
{
BSTR bstr=new wchar_t[buf_length+1]; //new bstr section to get around iis5's 256kb stack limit
if(bstr)
{
const size_t w_buf_length=mbstowcs(bstr,buf,buf_length+1);
*poutText=SysAllocStringLen(bstr,(unsigned int)w_buf_length);
delete[] bstr;
bstr=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Recv",
L"Memory allocation failure (%d bytes).",
buf_length);
retval=E_OUTOFMEMORY;
}
}
delete[] buf;
buf=NULL;
}
//
mutex.Untry();
}
else
*poutText=SysAllocString(L"");
return retval;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::SendRN(BSTR inText)
{
#ifdef _DEBUG
CBSTR bstr_fns;
printf("CTCPClient::SendRN inText=%S inText_length=%d\n",inText,bstr_fns.sz_length(inText));
printf(" sz_length=%d\n",bstr_fns.sz_length(inText));
printf(" character_length=%d\n",bstr_fns.character_length(inText));
printf(" bytes=%d\n",bstr_fns.bytes(inText));
#endif
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::SendRN",
L"Socket not open.");
}
else
{
if(inText!=NULL)
{
CBSTR bstr;
const int inText_length=bstr.sz_length(inText);
char *pszstr=new char[inText_length+1];
if(pszstr)
{
wcstombs(pszstr,inText,inText_length+1);
#ifdef _DEBUG
printf("inText_length=%d\n",inText_length);
printf("pszstr=%s\n",pszstr);
#endif
w->SendCRLF(pszstr,inText_length);
delete[] pszstr;
pszstr=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::SendRN",
L"Memory allocation failure (%d bytes).",
inText_length);
retval=E_OUTOFMEMORY;
}
}
else
w->SendCRLF(NULL,0);
}
//
mutex.Untry();
}
//
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::RecvRN(BSTR * poutText)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvRN",
L"Socket not open.");
*poutText=SysAllocString(L"");
}
else
{
char *buf=NULL;
const int buf_length=w->RecvCRLF(buf);
if(buf_length<=0)
*poutText=SysAllocString(L"");
else
{
BSTR bstr=new wchar_t[buf_length+1]; //new bstr section to get around iis5's 256kb stack limit
if(bstr)
{
const size_t w_buf_length=mbstowcs(bstr,buf,buf_length+1);
*poutText=SysAllocStringLen(bstr,(unsigned int)w_buf_length);
delete[] bstr;
bstr=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvRN",
L"Memory allocation failure (%d bytes).",
buf_length);
retval=E_OUTOFMEMORY;
}
}
delete[] buf;
buf=NULL;
}
//
mutex.Untry();
}
else
*poutText=SysAllocString(L"");
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::FlushRN()
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::FlushRN",
L"Socket not open.");
}
else
w->EmptyRecvBuffer();
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::SendFile(BSTR strFilename)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::SendFile",
L"Socket not open.");
}
else
{
//get filename contents
char filename[MAX_PATH+1];
wcstombs(filename,strFilename,wcslen(strFilename)+1);
// call optimized network file send function.
w->SendFile(filename);
}
//
mutex.Untry();
}
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::RecvFile(BSTR strFilename)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvFile",
L"Socket not open.");
}
else
{
//get filename contents
char filename[MAX_PATH+1];
wcstombs(filename,strFilename,wcslen(strFilename)+1);
// call optimized network file recv function. no append.
w->RecvFile(filename,false);
}
//
mutex.Untry();
}
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::RecvFileAppend(BSTR strFilename)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvFileAppend",
L"Socket not open.");
}
else
{
//get filename contents
char filename[MAX_PATH+1];
wcstombs(filename,strFilename,wcslen(strFilename)+1);
// call optimized network file revc function. append file.
w->RecvFile(filename,true);
}
//
mutex.Untry();
}
return retval;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::SendCSV(BSTR inText)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::SendCSV",
L"Socket not open.");
}
else
{
if(inText!=NULL)
{
//
const size_t inText_length=wcslen(inText)+1;
char *csv=new char[inText_length];
if(csv)
{
wcstombs(csv,inText,inText_length);
//
char *decsv=new char[inText_length];
if(decsv==NULL)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::SendCSV",
L"Memory allocation failure (%d bytes).",
inText_length);
retval=E_OUTOFMEMORY;
}
else
{
//
char *s=csv;
char *d=decsv;
int count=0;
char *c=NULL;
do
{
const int i=atoi(s);
*d=(BYTE)i;
d++;
c=strchr(s,',');
if(c)
s=c+1;
count++;
} while(c!=NULL);
//
w->Send( decsv, count);
//
delete[] decsv;
decsv=NULL;
}
//
delete[] csv;
csv=NULL;
}
}
else
retval=E_POINTER;
}
//
mutex.Untry();
}
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::RecvCSV(BSTR * poutText)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvCSV",
L"Socket not open.");
*poutText=SysAllocString(L"");
}
else
{
int buflength=0;
// get data
char *buf=NULL;
buflength=w->Recv(buf);
// decode raw data to csv
if(buflength<=0)
*poutText=SysAllocString(L"");
else
{
//
const int newbuflength=buflength*4;
char *newbuf=new char[newbuflength];
if(newbuf)
{
newbuf[0]='\0';
char *s=buf;
for(int i=0;i<buflength;i++)
{
char tmp[MAX_DWORDEXPANSION];
_itoa((BYTE)*s,tmp,10);
if(i!=0)
strcat(newbuf,",");
strcat(newbuf,tmp);
s++;
}
//new bstr section to get around iis5's 256kb stack limit
BSTR wbuf=new wchar_t[newbuflength+1];
if(wbuf)
{
mbstowcs(wbuf,newbuf,newbuflength+1);
*poutText=SysAllocString(wbuf);
delete[] wbuf;
wbuf=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvCSV",
L"Memory allocation failure (%d bytes).",
newbuflength);
retval=E_OUTOFMEMORY;
}
//
delete[] newbuf;
newbuf=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvCSV",
L"Memory allocation failure (%d bytes).",
newbuflength);
retval=E_OUTOFMEMORY;
}
}
//
delete[] buf;
buf=NULL;
}
//
mutex.Untry();
}
else
*poutText=SysAllocString(L"");
return retval;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::put_timeout(double secs)
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::put_timeout",
L"Socket not open.");
}
else
{
int s,ms;
s=(int)secs;
ms=(int)((secs-(double)s)*1000);
w->timeout(s,ms);
}
//
mutex.Untry();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::put_cutoff(long bytes)
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::put_cutoff",
L"Socket not open.");
}
else
w->cutoff(bytes);
//
mutex.Untry();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::put_blocksize(long bytes)
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::put_blocksize",
L"Socket not open.");
}
else
w->blocksize(bytes);
//
mutex.Untry();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::put_packetsize(long bytes)
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::put_packetsize",
L"Socket not open.");
}
else
w->packetsize(bytes);
//
mutex.Untry();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::put_keepalives(long flag)
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::put_keepalives",
L"Socket not open.");
}
else
w->keepalives(flag!=0);
//
mutex.Untry();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::put_nagledelay(long flag)
{
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::put_nagledelay",
L"Socket not open.");
}
else
w->nagledelay(flag!=0);
//
mutex.Untry();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::put_set_timeout(double secs)
{
return put_timeout(secs);
}
/*
*/
STDMETHODIMP CTCPClient::put_set_cutoff(long bytes)
{
return put_cutoff(bytes);
}
/*
*/
STDMETHODIMP CTCPClient::put_set_blocksize(long bytes)
{
return put_blocksize(bytes);
}
/*
*/
STDMETHODIMP CTCPClient::put_set_packetsize(long bytes)
{
return put_packetsize(bytes);
}
/*
*/
STDMETHODIMP CTCPClient::put_set_keepalives(long flag)
{
return put_keepalives(flag);
}
/*
*/
STDMETHODIMP CTCPClient::put_set_nagledelay(long flag)
{
return put_nagledelay(flag);
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_timeout(double *psecs)
{
if(w)
*psecs=(double)w->timeout();
else
*psecs=0.0;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_last_timeout(double *psecs)
{
if(w)
*psecs=(double)w->last_timeout();
else
*psecs=0.0;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_cutoff(long *pstatus)
{
if(w)
*pstatus=(long)w->cutoff();
else
*pstatus=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_blocksize(long *pbytes)
{
if(w)
*pbytes=(long)w->blocksize();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_packetsize(long *pbytes)
{
if(w)
*pbytes=(long)w->packetsize();
else
*pbytes=0L;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_description(BSTR* pstr)
{
CComBSTR bstrtmp(description);
if(!bstrtmp)
return E_POINTER;
else
{
*pstr=bstrtmp.Detach();
return S_OK;
}
}
/*
*/
STDMETHODIMP CTCPClient::get_copyright(BSTR* pstr)
{
CComBSTR bstrtmp(copyright);
if(!bstrtmp)
return E_POINTER;
else
{
*pstr=bstrtmp.Detach();
return S_OK;
}
}
/*
*/
STDMETHODIMP CTCPClient::get_version(BSTR* pstr)
{
CComBSTR bstrtmp(version);
if(!bstrtmp)
return E_POINTER;
else
{
*pstr=bstrtmp.Detach();
return S_OK;
}
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_thread(long* pthread)
{
DWORD tid=GetCurrentThreadId();
*pthread=(long)tid;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_local(BSTR* pstr)
{
HRESULT retval=S_OK;
char tmp[MAX_URLEXPANSION+1];
if(w)
{
char ip[MAX_IPEXPANSION+1];
int port;
w->localName(ip,port);
_snprintf(tmp,MAX_URLEXPANSION,"%S:%d",ip,port);
}
else
tmp[0]='\0';
CComBSTR bstrtmp(tmp);
if(!bstrtmp)
retval=E_OUTOFMEMORY;
else
*pstr=bstrtmp.Detach();
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::get_remote(BSTR* pstr)
{
HRESULT retval=S_OK;
char tmp[MAX_URLEXPANSION+1];
if(w)
{
char ip[MAX_IPEXPANSION+1];
int port;
w->peerName(ip,port);
_snprintf(tmp,MAX_URLEXPANSION,"%S:%d",ip,port);
}
else
tmp[0]='\0';
CComBSTR bstrtmp(tmp);
if(!bstrtmp)
retval=E_OUTOFMEMORY;
else
*pstr=bstrtmp.Detach();
return retval;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_is_completed(long* pstatus)
{
if(w)
*pstatus=(long)w->is_completed();
else
*pstatus=FALSE;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_is_connected(long* pstatus)
{
if(w)
*pstatus=(long)w->is_connected();
else
*pstatus=FALSE;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_is_cutoff(long* pstatus)
{
if(w)
*pstatus=(long)w->is_cutoff();
else
*pstatus=FALSE;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_is_keepalives(long* pstatus)
{
if(w)
*pstatus=(long)w->is_keepalives();
else
*pstatus=FALSE;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_is_nagledelay(long* pstatus)
{
if(w)
*pstatus=(long)w->is_nagledelay();
else
*pstatus=FALSE;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_socket(long* psock)
{
if(w)
*psock=(long)w->socket();
else
*psock=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_bytessent(long* pbytes)
{
if(w)
*pbytes=(long)w->bytes_sent();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_bytesreceived(long* pbytes)
{
if(w)
*pbytes=(long)w->bytes_received();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_byteslastreceived(long* pbytes)
{
if(w)
*pbytes=(long)w->last_bytes_received();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_byteslastsent(long* pbytes)
{
if(w)
*pbytes=(long)w->last_bytes_sent();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_stack_recv_buffer(long* pbytes)
{
if(w)
*pbytes=(long)w->stack_recv_buffer();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_stack_send_buffer(long* pbytes)
{
if(w)
*pbytes=(long)w->stack_send_buffer();
else
*pbytes=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_send_packets(long* pcount)
{
if(w)
*pcount=(long)w->send_packets();
else
*pcount=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_recv_packets(long* pcount)
{
if(w)
*pcount=(long)w->recv_packets();
else
*pcount=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_recv_faults(long* pcount)
{
if(w)
*pcount=(long)w->recv_faults();
else
*pcount=0L;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_recvbuffer_faults(long* pcount)
{
if(w)
*pcount=(long)w->recvbuffer_faults();
else
*pcount=0L;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_kbpssent(double* pkbps)
{
if(w)
*pkbps=(double)w->kbps_sent();
else
*pkbps=0.0;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_kbpsreceived(double* pkbps)
{
if(w)
*pkbps=(double)w->kbps_received();
else
*pkbps=0.0;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_kbpslastsent(double* pkbps)
{
if(w)
*pkbps=(double)w->last_kbps_sent();
else
*pkbps=0.0;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_kbpslastreceived(double* pkbps)
{
if(w)
*pkbps=(double)w->last_kbps_received();
else
*pkbps=0.0;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_ping(long* pVal)
{
if(w)
*pVal=(long)w->ping();
else
*pVal=0L;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::get_Log(BSTR* pstr)
{
CComBSTR bstrtmp(log.Logs());
if(!bstrtmp)
return E_OUTOFMEMORY;
else
{
*pstr=bstrtmp.Detach();
return S_OK;
}
}
/*
*/
STDMETHODIMP CTCPClient::ClearLog()
{
//
if(mutex.Try())
{
log.Clear();
}
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_instance(long* pVal)
{
*pVal=(long)m_instance;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_instances(long* pVal)
{
*pVal=(long)m_last_instance;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_mutex_locks(long* pVal)
{
*pVal=(long)mutex.get_lock_count();
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::get_mutex_sleep(long* pVal)
{
*pVal=(long)mutex.get_sleep_milliseconds();
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::SendFrame(
BSTR strFrame,
long FrameSize
)
{
#ifdef _DEBUG
CBSTR bstr_fns;
printf("CTCPClient::SendFrame strFrame=%S FrameSize=%d (szlen strFrame=%d)\n",
strFrame,FrameSize,bstr_fns.character_length(strFrame));
#endif
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::SendFrame",
L"Socket not open.");
}
else
{
if(strFrame!=NULL)
{
CBSTR bstr;
int const strFrame_length=bstr.character_length(strFrame);
int const frame_length=(FrameSize<strFrame_length)?FrameSize:strFrame_length;
#ifdef _DEBUG
printf("strFrame_length=%d\n",strFrame_length);
#endif
w->Send((char *)strFrame,frame_length);
}
else
retval=E_POINTER;
}
//
mutex.Untry();
}
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::RecvFrame(
long FrameSize,
BSTR* pstrFrame
)
{
//
HRESULT retval=S_OK;
//
if(mutex.Try())
{
//
if(!w)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvFrame",
L"Socket not open.");
*pstrFrame=SysAllocString(L"");
}
else
{
char *buf=NULL;
int const buf_length=w->RecvFrame(buf,FrameSize);
if(buf_length<=0)
*pstrFrame=SysAllocString(L"");
else
{
BSTR bstr=new wchar_t[buf_length+1];
if(bstr)
{
const size_t w_buf_length=mbstowcs(bstr,buf,buf_length+1);
*pstrFrame=SysAllocStringLen(bstr,(unsigned int)w_buf_length);
delete[] bstr;
bstr=NULL;
}
else
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::RecvFrame",
L"Memory allocation failure (%d bytes).",
buf_length);
retval=E_OUTOFMEMORY;
}
}
delete[] buf;
buf=NULL;
}
//
mutex.Untry();
}
else
*pstrFrame=SysAllocString(L"");
return retval;
}
/*
*/
// 8 16 24 32 40 48 56 64
_int64 CTCPClient::changeEndian(
_int64 d,
short bits
)
{
if((bits&7)==0)
{
int const bytes=(int)(bits>>3);
BYTE b[8];
int i;
BYTE *p=(BYTE *)&d;
for(i=0;i<bytes;i++)
{
b[i]=*(p+bytes-i-1);
}
for(;i<8;i++)
{
b[i]=0;
}
return *(_int64 *)b;
}
else
{
return d;
}
}
/*
*/
STDMETHODIMP CTCPClient::FrameSize(
BSTR strFrameDefinition,
long* pFrameSize
)
{
//
if(strFrameDefinition==NULL)
{
if(pFrameSize==NULL)
return S_OK;
else
{
*pFrameSize=0;
return S_OK;
}
}
//
CBSTR bstr;
const int length=bstr.sz_length(strFrameDefinition);
wchar_t *p=strFrameDefinition;
wchar_t *pend=strFrameDefinition+length;
long sum=0;
if(strFrameDefinition!=NULL)
{
while(p<pend)
{
wchar_t *next;
wchar_t c=*p++;
int num=_wtoi(p);
next=wcschr(p,' ');
if(next==NULL) break;
p=next+1;
next=wcschr(p,',');
if(next==NULL) p=pend; else p=next+1;
switch(c)
{
case '+':
sum+=num;
break;
case 's':
sum+=8*num;
break;
case 'u':
sum+=16*num;
break;
case ' ':
case '-':
sum+=num;
break;
default:
p=pend;
}
}
}
//
*pFrameSize=(long)sum;
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::DecodeFrame(
BSTR strFrameDefinition,
BSTR strFieldName,
BSTR strFrame,
BSTR* pstrValue
)
{
//
if(strFrameDefinition==NULL || strFrame==NULL || strFieldName==NULL || pstrValue==NULL)
{
if(pstrValue==NULL)
return S_OK;
else
{
*pstrValue=SysAllocString(L"");
return S_OK;
}
}
//
CBSTR bstr;
int const length=bstr.sz_length(strFrameDefinition);
wchar_t *p=strFrameDefinition;
wchar_t *pend=strFrameDefinition+length;
//
long sum=0;
while(p<pend)
{
wchar_t *next;
wchar_t c=*p++;
int num=_wtoi(p);
next=wcschr(p,' ');
if(next==NULL) break;
p=next+1;
wchar_t *fieldname=p;
next=wcschr(p,',');
int fieldname_length;
if(next==NULL)
{
p=pend;
fieldname_length=(int)(p-fieldname);
}
else
{
p=next+1;
fieldname_length=(int)(p-fieldname-1);
}
if(wcsncmp(strFieldName,fieldname,fieldname_length)==0)
{
const int byte_offset=(sum>>3);
const bool aligned=((sum&7)==0);
const int shift=sum&7;
const int index=(num-1)&63;
BYTE *source=(BYTE *)strFrame;
_int64 dd;
_int64 d;
wchar_t wbuffer[22];
switch(c)
{
case ' ':
case '-':
dd=*(_int64 *)(source+byte_offset);
d=(_int64)((dd>>shift)&bitmask[index]);
_i64tow(d,wbuffer,10);
*pstrValue=SysAllocString(wbuffer);
return S_OK;
case '+':
dd=*(_int64 *)(source+byte_offset);
d=(_int64)((dd>>shift)&bitmask[index]);
d=changeEndian(d,num);
_i64tow(d,wbuffer,10);
*pstrValue=SysAllocString(wbuffer);
return S_OK;
case 's':
{
wchar_t *tmp=new wchar_t[num+1];
if(tmp)
{
const size_t wlength=mbstowcs(tmp,(const char *)(source+byte_offset),num);
*(tmp+num)=L'\0';
*pstrValue=SysAllocString(tmp);
delete[] tmp;
}
}
return S_OK;
case 'u':
{
wchar_t *tmp=new wchar_t[num+1];
if(tmp)
{
wcsncpy(tmp,(const wchar_t*)(source+byte_offset),num);
*(tmp+num)=L'\0';
*pstrValue=SysAllocString(tmp);
delete[] tmp;
}
}
return S_OK;
default:
*pstrValue=SysAllocString(L"");
return S_OK;
}
break;
}
switch(c)
{
case '+':
sum+=num;
break;
case 's':
sum+=8*num;
break;
case 'u':
sum+=16*num;
break;
case ' ':
case '-':
sum+=num;
break;
default:
p=pend;
}
}
//
if(pstrValue) *pstrValue=SysAllocString(L"");
return S_OK;
}
/*
*/
STDMETHODIMP CTCPClient::EncodeFrame(
BSTR strFrameDefinition,
BSTR strFieldName,
BSTR strFieldValue,
BSTR strFrame,
BSTR* pstrFrame
)
{
//
if(strFrameDefinition==NULL || strFieldName==NULL || strFieldValue==NULL || strFrame==NULL || pstrFrame==NULL)
{
if(pstrFrame==NULL)
return S_OK;
else
{
*pstrFrame=SysAllocString(L"");
return S_OK;
}
}
//
CBSTR bstr;
const int length=bstr.sz_length(strFrameDefinition);
wchar_t *p=strFrameDefinition;
wchar_t *pend=strFrameDefinition+length;
//
long framesize;
FrameSize(strFrameDefinition,&framesize);
const int framebytes=(framesize>>3)+(((framesize&7)==0)?0:1);
BYTE *Frame=new BYTE[framebytes+2+sizeof(_int64)];
if(Frame==NULL)
{
//memory allocation error
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::EncodeFrame",
L"Memory allocation failure (%d bytes)",framebytes+2+sizeof(_int64));
return E_OUTOFMEMORY;
}
else
{
//
memset(Frame,0,framebytes+2+sizeof(_int64));
//
CBSTR bstr;
const int strFrame_bytes=bstr.bytes(strFrame);
if(strFrame) memcpy(Frame,strFrame,(strFrame_bytes<=framebytes)?strFrame_bytes:framebytes);
//
long sum=0;
while(p<pend)
{
wchar_t *next;
wchar_t c=*p++;
int num=_wtoi(p);
next=wcschr(p,' ');
if(next==NULL) break;
p=next+1;
wchar_t *fieldname=p;
next=wcschr(p,',');
int fieldname_length;
if(next==NULL)
{
p=pend;
fieldname_length=(int)(p-fieldname);
}
else
{
p=next+1;
fieldname_length=(int)(p-fieldname-1);
}
//
if(wcsncmp(strFieldName,fieldname,fieldname_length)==0)
{
const int byte_offset=(sum>>3);
const bool aligned=((sum&7)==0);
const int shift=sum&7;
const int index=(num-1)&63;
BYTE *destination=(BYTE *)Frame;
_int64 dd;
_int64 dd_stream;
_int64 d;
_int64 inverse_bitmask;
switch(c)
{
case ' ':
case '-':
d=_wtoi(strFieldValue);
dd_stream=*(_int64 *)(destination+byte_offset);
inverse_bitmask=~(bitmask[index]<<shift);
dd=(dd_stream&inverse_bitmask)|(d<<shift);
*(_int64 *)(destination+byte_offset)=dd;
p=pend;
break;
case '+':
d=changeEndian(_wtoi(strFieldValue),num);
dd_stream=*(_int64 *)(destination+byte_offset);
inverse_bitmask=~(bitmask[index]<<shift);
dd=(dd_stream&inverse_bitmask)|(d<<shift);
*(_int64 *)(destination+byte_offset)=dd;
p=pend;
break;
case 's':
{
char *tmp=new char[num];
if(tmp)
{
const size_t wlength=wcstombs(tmp,strFieldValue,num);
memset((char*)(destination+byte_offset),0,num);
strncpy((char*)(destination+byte_offset),tmp,num);
delete[] tmp;
}
p=pend;
}
break;
case 'u':
memset((char*)(destination+byte_offset),0,num*2);
wcsncpy((wchar_t *)(destination+byte_offset),strFieldValue,num);
p=pend;
break;
}
}
switch(c)
{
case '+':
sum+=num;
break;
case 's':
sum+=8*num;
break;
case 'u':
sum+=16*num;
break;
case ' ':
case '-':
sum+=num;
break;
default:
p=pend;
}
}
if(pstrFrame) SysFreeString(*pstrFrame);
*pstrFrame=::SysAllocStringByteLen((const char*)Frame,framebytes);
delete[] Frame;
Frame=NULL;
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
//
//
/*
*/
STDMETHODIMP CTCPClient::Hash(
BSTR strHashType,
BSTR strInput,
BSTR* pstrHash
)
{
//
HRESULT retval=S_OK;
CMD5 md5;
if(strInput!=NULL)
{
//
const size_t strInput_length=wcslen(strInput)+1;
char *szInput=new char[strInput_length];
if(szInput==NULL)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Hash",
L"Memory allocation failure (%d bytes).",
strInput_length);
retval=E_OUTOFMEMORY;
}
else
{
//
wcstombs(szInput,strInput,strInput_length);
char md5hash[32+1];
md5.Hash(szInput,md5hash);
BSTR bstr=new wchar_t[32+1];
if(bstr==NULL)
{
log.AddLog(
_T(__FILE__),
__LINE__,
L"CTCPClient::Hash",
L"Memory allocation failure (%d bytes).",32+1);
retval=E_OUTOFMEMORY;
}
else
{
const size_t w_length=mbstowcs(bstr,md5hash,32+1);
*pstrHash=SysAllocString(bstr);
delete[] bstr;
}
delete[] szInput;
szInput=NULL;
}
}
return retval;
}
/*
*/
STDMETHODIMP CTCPClient::HashFile(
BSTR strHashType,
BSTR strFilename,
BSTR *pstrHash
)
{
//
HRESULT retval=S_OK;
CMD5 md5;
CBSTR bstr;
//
char szFilename[_MAX_PATH+1];
const int strFilename_length=bstr.sz_length(strFilename);
wcstombs(szFilename,strFilename,strFilename_length+1);
//
char hash[32+1];
const int blocksize=65536;
md5.HashFile(szFilename,hash,blocksize);
wchar_t bstr_hash[32+1];
mbstowcs(bstr_hash,hash,32+1);
*pstrHash=SysAllocString(bstr_hash);
//
return retval;
}
| 14.772091 | 160 | 0.585922 | lasellers |
705ee583c9ec2c7aebba4b87273e5c9d6550652e | 2,456 | cpp | C++ | src/aijack/collaborative/secureboost/core/main.cpp | Koukyosyumei/AIJack | 9545d3828907b54965ede85e0e12cb32eef54294 | [
"MIT"
] | 24 | 2021-11-17T02:16:47.000Z | 2022-03-27T01:04:08.000Z | src/aijack/collaborative/secureboost/core/main.cpp | Koukyosyumei/AIJack | 9545d3828907b54965ede85e0e12cb32eef54294 | [
"MIT"
] | 9 | 2021-12-03T06:09:27.000Z | 2022-03-29T06:33:53.000Z | src/aijack/collaborative/secureboost/core/main.cpp | Koukyosyumei/AIJack | 9545d3828907b54965ede85e0e12cb32eef54294 | [
"MIT"
] | 5 | 2022-01-12T09:58:04.000Z | 2022-03-17T09:29:04.000Z | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <cmath>
#include <iostream>
#include <vector>
#include "secureboost.h"
#define STRINGIFY(x) #x
#define MACRO_STRINGIFY(x) STRINGIFY(x)
using namespace std;
namespace py = pybind11;
PYBIND11_MODULE(aijack_secureboost, m)
{
m.doc() = R"pbdoc(
core of SecureBoost
)pbdoc";
py::class_<Party>(m, "Party")
.def(py::init<vector<vector<double>>, vector<int>, int, int, double>())
.def("get_lookup_table", &Party::get_lookup_table)
.def("get_percentiles", &Party::get_percentiles)
.def("is_left", &Party::is_left)
.def("greedy_search_split", &Party::greedy_search_split)
.def("split_rows", &Party::split_rows)
.def("insert_lookup_table", &Party::insert_lookup_table);
py::class_<Node>(m, "Node")
.def(py::init<vector<Party> &, vector<double>, vector<double>,
vector<double>, vector<int>,
double, double, double, double,
int>())
.def("get_idxs", &Node::get_idxs)
.def("get_party_id", &Node::get_party_id)
.def("get_record_id", &Node::get_record_id)
.def("get_val", &Node::get_val)
.def("get_score", &Node::get_score)
.def("get_left", &Node::get_left)
.def("get_right", &Node::get_right)
.def("get_parties", &Node::get_parties)
.def("is_leaf", &Node::is_leaf)
.def("print", &Node::print, py::arg("binary_color") = true);
py::class_<XGBoostTree>(m, "XGBoostTree")
.def("get_root_node", &XGBoostTree::get_root_node);
py::class_<SecureBoostClassifier>(m, "SecureBoostClassifier")
.def(py::init<double, double, int, int, double, int, double, double, double>())
.def("fit", &SecureBoostClassifier::fit)
.def("get_grad", &SecureBoostClassifier::get_grad)
.def("get_hess", &SecureBoostClassifier::get_hess)
.def("get_init_pred", &SecureBoostClassifier::get_init_pred)
.def("load_estimators", &SecureBoostClassifier::load_estimators)
.def("get_estimators", &SecureBoostClassifier::get_estimators)
.def("predict_raw", &SecureBoostClassifier::predict_raw)
.def("predict_proba", &SecureBoostClassifier::predict_proba);
#ifdef VERSION_INFO
m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO);
#else
m.attr("__version__") = "dev";
#endif
}
| 36.656716 | 87 | 0.639251 | Koukyosyumei |
70618ea657d3a1d713e90acc5ae66bf39cc96dc8 | 442 | cc | C++ | lab5/aufgabe4/src/drawingobject2.cc | FreeGeronimo/OOS1 | c04718534b539089680c7e9164c954f0962c5e4e | [
"MIT"
] | null | null | null | lab5/aufgabe4/src/drawingobject2.cc | FreeGeronimo/OOS1 | c04718534b539089680c7e9164c954f0962c5e4e | [
"MIT"
] | null | null | null | lab5/aufgabe4/src/drawingobject2.cc | FreeGeronimo/OOS1 | c04718534b539089680c7e9164c954f0962c5e4e | [
"MIT"
] | null | null | null | #include "drawingobject2.hh"
#include <iostream>
using namespace std;
extern bool debugConstructor;
DrawingObject::DrawingObject()
: ObjectCounter()
{
if (debugConstructor)
{
cout << "Konstrutor der Klasse DrawingObject, Object: " << GetId() << endl;
}
}
DrawingObject::~DrawingObject()
{
if (debugConstructor)
{
cout << "Destruktor der Klasse DrawingObject, Object: " << GetId() << endl;
}
}
| 17.68 | 83 | 0.642534 | FreeGeronimo |
7062009380ad83bfeb972203adf99dd8426568ff | 11,107 | cpp | C++ | modules/core/sensor/src/PinholeCamera.cpp | MobilePerceptionLab/EventCameraCalibration | debd774ac989674b500caf27641b7ad4e94681e9 | [
"Apache-2.0"
] | 22 | 2021-08-06T03:21:03.000Z | 2022-02-25T03:40:54.000Z | modules/core/sensor/src/PinholeCamera.cpp | MobilePerceptionLab/MultiCamCalib | 2f0e94228c2c4aea7f20c26e3e8daa6321ce8022 | [
"Apache-2.0"
] | 1 | 2022-02-25T02:55:13.000Z | 2022-02-25T15:18:45.000Z | modules/core/sensor/src/PinholeCamera.cpp | MobilePerceptionLab/MultiCamCalib | 2f0e94228c2c4aea7f20c26e3e8daa6321ce8022 | [
"Apache-2.0"
] | 7 | 2021-08-11T12:29:35.000Z | 2022-02-25T03:41:01.000Z | //
// Created by huangkun on 2020/8/11.
//
#include <Eigen/Eigen>
#include <opencv2/core/eigen.hpp>
#include <opencv2/opencv.hpp>
#include <nanoflann.hpp>
#include <KDTreeVectorOfVectorsAdaptor.h>
#include <opengv2/sensor/PinholeCamera.hpp>
#include <opengv2/utility/utility.hpp>
opengv2::PinholeCamera::PinholeCamera(const Eigen::Ref<const Eigen::Vector2d> &size,
const Eigen::Ref<const Eigen::Matrix3d> &K,
const Eigen::Ref<const Eigen::VectorXd> &distCoeffs,
cv::Mat mask) :
CameraBase(size, mask), K_(K), invK_(K.inverse()), distCoeffs_(distCoeffs),
inverseRadialPoly_(Eigen::VectorXd()) {}
inline Eigen::Vector2d opengv2::PinholeCamera::project(const Eigen::Ref<const Eigen::Vector3d> &Xc) const {
if (distCoeffs_.size() == 0) {
Eigen::Vector3d p = K_ * Xc;
p /= p(2);
return p.block<2, 1>(0, 0);
} else {
// TODO: implement using Eigen
std::vector<cv::Point3f> objectPoints(1, cv::Point3f(Xc[0], Xc[1], Xc[2]));
cv::Mat tvec = cv::Mat::zeros(3, 1, CV_32F), rvec, distCoeffs, cameraMatrix;
cv::Rodrigues(cv::Mat::eye(3, 3, CV_32F), rvec);
cv::eigen2cv(distCoeffs_, distCoeffs);
cv::eigen2cv(K_, cameraMatrix);
std::vector<cv::Point2f> imagePoints;
cv::projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints);
return Eigen::Vector2d(imagePoints[0].x, imagePoints[0].y);
}
}
inline Eigen::Vector3d opengv2::PinholeCamera::invProject(const Eigen::Ref<const Eigen::Vector2d> &p) const {
Eigen::Vector3d Xc;
if (inverseRadialPoly_.size() != 0) {
Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1);
Xc /= Xc[2];
Eigen::VectorXd r_coeff(inverseRadialPoly_.size());
r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1];
for (int i = 1; i < inverseRadialPoly_.size(); ++i) {
r_coeff[i] = r_coeff[i - 1] * r_coeff[0];
}
Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly_;
Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly_;
} else if (distCoeffs_.size() != 0) {
// TODO: implement using Eigen
std::vector<cv::Point2f> src, dst;
src.emplace_back(p[0], p[1]);
cv::Mat cameraMatrix, distCoeffs;
cv::eigen2cv(K_, cameraMatrix);
cv::eigen2cv(distCoeffs_, distCoeffs);
cv::undistortPoints(src, dst, cameraMatrix, distCoeffs);
Xc = Eigen::Vector3d(dst[0].x, dst[0].y, 1);
} else {
Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1);
}
Xc.normalize();
return Xc;
}
Eigen::VectorXd
opengv2::PinholeCamera::inverseRadialDistortion(const Eigen::Ref<const Eigen::Vector4d> &radialDistortion) {
const Eigen::Ref<const Eigen::VectorXd> &k = radialDistortion;
Eigen::VectorXd b(5);
double k00 = k[0] * k[0];
double k000 = k[0] * k00;
double k0000 = k[0] * k000;
double k00000 = k[0] * k0000;
double k01 = k[0] * k[1];
double k001 = k[0] * k01;
double k0001 = k[0] * k001;
double k11 = k[1] * k[1];
double k011 = k[0] * k11;
double k02 = k[0] * k[2];
double k002 = k[0] * k02;
double k12 = k[1] * k[2];
double k03 = k[0] * k[3];
b[0] = -k[0];
b[1] = 3 * k00 - k[1];
b[2] = -12 * k000 + 8 * k01 - k[2];
b[3] = 55 * k0000 - 55 * k001 + 5 * k11 + 10 * k02 - k[3];
b[4] = -273 * k00000 + 364 * k0001 - 78 * k011 - 78 * k002 + 12 * k12 + 12 * k03;
return b;
}
Eigen::Vector2d opengv2::PinholeCamera::undistortPoint(const Eigen::Ref<const Eigen::Vector2d> &p) const {
Eigen::Vector3d Xc;
if (inverseRadialPoly_.size() != 0) {
Xc = invK_ * Eigen::Vector3d(p(0), p(1), 1);
Xc /= Xc[2];
Eigen::VectorXd r_coeff(inverseRadialPoly_.size());
r_coeff[0] = Xc[0] * Xc[0] + Xc[1] * Xc[1];
for (int i = 1; i < inverseRadialPoly_.size(); ++i) {
r_coeff[i] = r_coeff[i - 1] * r_coeff[0];
}
Xc[0] *= 1 + r_coeff.transpose() * inverseRadialPoly_;
Xc[1] *= 1 + r_coeff.transpose() * inverseRadialPoly_;
} else if (distCoeffs_.size() != 0) {
// TODO: implement using Eigen
std::vector<cv::Point2f> src, dst;
src.emplace_back(p[0], p[1]);
cv::Mat cameraMatrix, distCoeffs;
cv::eigen2cv(K_, cameraMatrix);
cv::eigen2cv(distCoeffs_, distCoeffs);
cv::undistortPoints(src, dst, cameraMatrix, distCoeffs);
Xc = Eigen::Vector3d(dst[0].x, dst[0].y, 1);
} else {
return p;
}
Eigen::Vector3d p_c = K_ * Xc;
p_c /= p_c[2];
return p_c.block<2, 1>(0, 0);
}
cv::Mat opengv2::PinholeCamera::undistortImage(cv::Mat src) {
if (inverseRadialPoly_.size() != 0) {
if (undistortMap_.empty()) {
// Initialization
int dstRows = std::round(size_[1] * 1.2);
int dstCols = std::round(size_[0] * 1.2);
int emptyEdge_r = std::round(size_[1] * 0.1);
int emptyEdge_c = std::round(size_[0] * 0.1);
undistortMap_.assign(dstRows, std::vector(dstCols, std::pair(std::vector<std::pair<int, int>>(),
std::vector<double>())));
vectorofEigenMatrix<Eigen::Vector2d> correctedSet;
correctedSet.reserve(size_[0] * size_[1]);
const int step = size_[0]; // width
for (int idx = 0; idx < size_[0] * size_[1]; ++idx) { // index of cv::Mat, row major
int row = idx / step; // y
int col = idx % step; // x
correctedSet.push_back(
undistortPoint(Eigen::Vector2d(col, row)) + Eigen::Vector2d(emptyEdge_c, emptyEdge_r));
}
KDTreeVectorOfVectorsAdaptor<vectorofEigenMatrix<Eigen::Vector2d>, double, 2, nanoflann::metric_L2_Simple>
kdTree(2, correctedSet, 10);
std::vector<std::pair<size_t, double>> indicesDists;
for (int i = 0; i < dstRows; ++i) { // y, height
for (int j = 0; j < dstCols; ++j) { // x, width
Eigen::Vector2d p(j, i);
kdTree.index->radiusSearch(p.data(), 2 * 2 /*square pixel unit*/,
indicesDists, nanoflann::SearchParams(32, 0, false));
for (const auto &pair: indicesDists) {
int idx = pair.first;
double d = pair.second;
int row = idx / step;
int col = idx % step;
if (d < 100 * std::numeric_limits<double>::epsilon()) {
d = 100 * std::numeric_limits<double>::epsilon();
}
undistortMap_[i][j].first.emplace_back(row, col);
undistortMap_[i][j].second.push_back(1 / d);
}
}
}
}
if (src.type() != CV_8UC3) {
throw std::logic_error("only support CV_8UC3 for now.");
}
cv::Mat dst(undistortMap_.size(), undistortMap_[0].size(), CV_32FC3, cv::Vec3f(0, 0, 0));
for (int i = 0; i < dst.rows; ++i) {
for (int j = 0; j < dst.cols; ++j) {
int len = undistortMap_[i][j].first.size();
double w_sum = 0;
for (int k = 0; k < len; ++k) {
int row = undistortMap_[i][j].first[k].first;
int col = undistortMap_[i][j].first[k].second;
double w = undistortMap_[i][j].second[k];
// convert to float, since opencv didn't do that(uchar * double, return uchar).
cv::Vec3f temp = src.at<cv::Vec3b>(row, col);
dst.at<cv::Vec3f>(i, j) += w * temp;
w_sum += w;
}
if (len != 0) {
dst.at<cv::Vec3f>(i, j) /= w_sum;
}
}
}
cv::normalize(dst, dst, 0, 255, cv::NORM_MINMAX, CV_8UC3);
return dst;
} else if (distCoeffs_.size() != 0) {
if (map1_.empty()) {
cv::Size imageSize(size_[0], size_[1]);
cv::Mat cameraMatrix, distCoeffs;
cv::eigen2cv(K_, cameraMatrix);
cv::eigen2cv(distCoeffs_, distCoeffs);
cv::initUndistortRectifyMap(
cameraMatrix, distCoeffs, cv::Mat(),
getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),
imageSize, CV_32FC1, map1_, map2_);
}
cv::Mat dst;
remap(src, dst, map1_, map2_, cv::INTER_LINEAR);
return dst;
} else {
return src;
}
}
opengv2::PinholeCamera::PinholeCamera(const cv::FileNode &sensorNode) : CameraBase(sensorNode) {
std::vector<double> v;
cv::FileNode data;
data = sensorNode["principal_point"];
if (!data.isSeq())
throw std::invalid_argument(sensorNode.name() + ": principal_point");
for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) {
v.push_back(*dataItr);
}
if (v.size() != 2)
throw std::invalid_argument(sensorNode.name() + ": principal_point");
Eigen::Vector2d principal_point(v.data());
std::cout << "principal_point: " << principal_point.transpose() << std::endl;
v.clear();
data = sensorNode["distortion_type"];
if (!data.isString())
throw std::invalid_argument(sensorNode.name() + ": distortion_type");
std::string distortion_type = data.string();
std::cout << "distortion_type: " << distortion_type << std::endl;
v.clear();
data = sensorNode["distortion"];
if (!data.isSeq())
throw std::invalid_argument(sensorNode.name() + ": distortion");
for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) {
v.push_back(*dataItr);
}
Eigen::Map<Eigen::VectorXd, Eigen::Unaligned> distortion_tmp(v.data(), v.size());
Eigen::VectorXd distortion(distortion_tmp);
std::cout << "distortion: " << distortion.transpose() << std::endl;
v.clear();
data = sensorNode["focal_length"];
if (!data.isSeq())
throw std::invalid_argument(sensorNode.name() + ": focal_length");
for (cv::FileNodeIterator dataItr = data.begin(); dataItr != data.end(); dataItr++) {
v.push_back(*dataItr);
}
if (v.size() != 2)
throw std::invalid_argument(sensorNode.name() + ": focal_length");
Eigen::Vector2d focal_length(v.data());
std::cout << "focal_length: " << focal_length.transpose() << std::endl;
K_ << focal_length[0], 0, principal_point[0], 0, focal_length[1], principal_point[1], 0, 0, 1;
invK_ = K_.inverse();
if (distortion_type == "OpenCV") {
distCoeffs_ = distortion;
inverseRadialPoly_ = Eigen::VectorXd();
} else {
distCoeffs_ = Eigen::VectorXd();
inverseRadialPoly_ = distortion;
}
} | 41.137037 | 118 | 0.544431 | MobilePerceptionLab |
7067790723a609a8a5c5bfac60cf9bd9229aee21 | 3,491 | cpp | C++ | LambdaEngine/Source/Game/ECS/Components/Rendering/CameraComponent.cpp | IbexOmega/CrazyCanvas | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 18 | 2020-09-04T08:00:54.000Z | 2021-08-29T23:04:45.000Z | LambdaEngine/Source/Game/ECS/Components/Rendering/CameraComponent.cpp | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 32 | 2020-09-12T19:24:50.000Z | 2020-12-11T14:29:44.000Z | LambdaEngine/Source/Game/ECS/Components/Rendering/CameraComponent.cpp | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 2 | 2020-12-15T15:36:13.000Z | 2021-03-27T14:27:02.000Z | #include "Audio/AudioAPI.h"
#include "Audio/FMOD/AudioDeviceFMOD.h"
#include "Audio/FMOD/SoundInstance3DFMOD.h"
#include "Game/ECS/Components/Rendering/CameraComponent.h"
#include "Game/ECS/Components/Audio/AudibleComponent.h"
#include "Game/ECS/Components/Audio/ListenerComponent.h"
#include "Game/ECS/Components/Physics/Transform.h"
#include "Game/ECS/Components/Physics/Collision.h"
#include "Game/ECS/Components/Misc/Components.h"
#include "Game/ECS/Systems/Physics/PhysicsSystem.h"
#include "Resources/ResourceManager.h"
namespace LambdaEngine
{
Entity CreateFreeCameraEntity(const CameraDesc& cameraDesc)
{
Entity entity = CreateCameraEntity(cameraDesc);
FreeCameraComponent freeCamComp;
ECSCore::GetInstance()->AddComponent<FreeCameraComponent>(entity, freeCamComp);
return entity;
}
Entity CreateFPSCameraEntity(const CameraDesc& cameraDesc)
{
ECSCore* pECS = ECSCore::GetInstance();
Entity entity = CreateCameraEntity(cameraDesc);
FPSControllerComponent FPSCamComp;
FPSCamComp.SpeedFactor = 2.4f;
pECS->AddComponent<FPSControllerComponent>(entity, FPSCamComp);
const CharacterColliderCreateInfo colliderInfo = {
.Entity = entity,
.Position = pECS->GetComponent<PositionComponent>(entity),
.Rotation = pECS->GetComponent<RotationComponent>(entity),
.CollisionGroup = FCollisionGroup::COLLISION_GROUP_DYNAMIC,
.CollisionMask = UINT32_MAX, // The player collides with everything
.EntityID = entity
};
constexpr const float capsuleHeight = 1.8f;
constexpr const float capsuleRadius = 0.2f;
CharacterColliderComponent characterColliderComponent = PhysicsSystem::GetInstance()->CreateCharacterCapsule(colliderInfo, std::max(0.0f, capsuleHeight - 2.0f * capsuleRadius), capsuleRadius);
pECS->AddComponent<CharacterColliderComponent>(entity, characterColliderComponent);
// Listener
pECS->AddComponent<ListenerComponent>(entity, { AudioAPI::GetDevice()->GetAudioListener(false) });
return entity;
}
Entity CreateCameraTrackEntity(const LambdaEngine::CameraDesc& cameraDesc, const TArray<glm::vec3>& track)
{
ECSCore* pECS = ECSCore::GetInstance();
Entity entity = CreateCameraEntity(cameraDesc);
TrackComponent camTrackComp;
camTrackComp.Track = track;
pECS->AddComponent<TrackComponent>(entity, camTrackComp);
return entity;
}
Entity CreateCameraEntity(const CameraDesc& cameraDesc)
{
ECSCore* pECS = ECSCore::GetInstance();
const Entity entity = pECS->CreateEntity();
const ViewProjectionMatricesComponent viewProjComp = {
.Projection = glm::perspective(glm::radians(cameraDesc.FOVDegrees), cameraDesc.Width / cameraDesc.Height, cameraDesc.NearPlane, cameraDesc.FarPlane),
.View = glm::lookAt(cameraDesc.Position, cameraDesc.Position + cameraDesc.Direction, g_DefaultUp)
};
pECS->AddComponent<ViewProjectionMatricesComponent>(entity, viewProjComp);
const CameraComponent camComp = {
.NearPlane = cameraDesc.NearPlane,
.FarPlane = cameraDesc.FarPlane,
.FOV = cameraDesc.FOVDegrees
};
pECS->AddComponent<CameraComponent>(entity, camComp);
pECS->AddComponent<PositionComponent>(entity, PositionComponent{ .Position = cameraDesc.Position });
pECS->AddComponent<RotationComponent>(entity, RotationComponent{ .Quaternion = glm::quatLookAt(cameraDesc.Direction, g_DefaultUp) });
pECS->AddComponent<ScaleComponent>(entity, ScaleComponent{ .Scale = {1.f, 1.f, 1.f} });
pECS->AddComponent<VelocityComponent>(entity, VelocityComponent());
return entity;
}
}
| 37.138298 | 194 | 0.776282 | IbexOmega |
0ad95262691006f828c7ab59ec531b1a305c14ac | 2,422 | cpp | C++ | test/test_zip_iterator_sort.cpp | cjatin/rocThrust | ae487ed39147c4cb2461b16f4b51cc96950bb3af | [
"Apache-2.0"
] | null | null | null | test/test_zip_iterator_sort.cpp | cjatin/rocThrust | ae487ed39147c4cb2461b16f4b51cc96950bb3af | [
"Apache-2.0"
] | null | null | null | test/test_zip_iterator_sort.cpp | cjatin/rocThrust | ae487ed39147c4cb2461b16f4b51cc96950bb3af | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2008-2013 NVIDIA Corporation
* Modifications Copyright© 2019 Advanced Micro Devices, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/iterator/zip_iterator.h>
#include <thrust/sort.h>
#include "test_header.hpp"
TESTS_DEFINE(ZipIteratorStableSortTests, UnsignedIntegerTestsParams);
TYPED_TEST(ZipIteratorStableSortTests, TestZipIteratorStableSort)
{
using namespace thrust;
using T = typename TestFixture::input_type;
const std::vector<size_t> sizes = get_sizes();
for(auto size : sizes)
{
SCOPED_TRACE(testing::Message() << "with size= " << size);
for(size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++)
{
unsigned int seed_value
= seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count];
SCOPED_TRACE(testing::Message() << "with seed= " << seed_value);
thrust::host_vector<T> h1 = get_random_data<T>(
size, std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), seed_value);
thrust::host_vector<T> h2 = get_random_data<T>(
size,
std::numeric_limits<T>::min(),
std::numeric_limits<T>::max(),
seed_value + seed_value_addition
);
device_vector<T> d1 = h1;
device_vector<T> d2 = h2;
// sort on host
stable_sort(make_zip_iterator(make_tuple(h1.begin(), h2.begin())),
make_zip_iterator(make_tuple(h1.end(), h2.end())));
// sort on device
stable_sort(make_zip_iterator(make_tuple(d1.begin(), d2.begin())),
make_zip_iterator(make_tuple(d1.end(), d2.end())));
ASSERT_EQ_QUIET(h1, d1);
ASSERT_EQ_QUIET(h2, d2);
}
}
}
| 36.69697 | 100 | 0.632122 | cjatin |
0ad9c04cde103c4b2b3e44eb333468555cbd4fd6 | 1,710 | cpp | C++ | src/MyMaterial.cpp | nicholaschiasson/N3DIL | 5b598b340c4850cb06f92194f48aa10c76a578aa | [
"MIT"
] | null | null | null | src/MyMaterial.cpp | nicholaschiasson/N3DIL | 5b598b340c4850cb06f92194f48aa10c76a578aa | [
"MIT"
] | 5 | 2015-10-19T03:35:56.000Z | 2015-11-03T22:19:26.000Z | src/MyMaterial.cpp | nicholaschiasson/N3DIL | 5b598b340c4850cb06f92194f48aa10c76a578aa | [
"MIT"
] | null | null | null | #include "MyMaterial.h"
#include "MyDefines.h"
#include <algorithm>
MyMaterial::MyMaterial(MyTexture2D * texture, MyColorRGBA const & ambient, MyColorRGBA const & diffuse, MyColorRGBA const & specular, float const & shine, bool const & toon) :
tex(texture), a(ambient), d(diffuse), s(specular), sh(shine), t(toon)
{
}
MyMaterial::~MyMaterial()
{
}
MyTexture2D * MyMaterial::GetTexture() const
{
return tex;
}
const MyColorRGBA & MyMaterial::GetAmbient() const
{
return a;
}
const MyColorRGBA & MyMaterial::GetDiffuse() const
{
return d;
}
const MyColorRGBA & MyMaterial::GetSpecular() const
{
return s;
}
const float & MyMaterial::GetShine() const
{
return sh;
}
const bool & MyMaterial::GetToon() const
{
return t;
}
bool MyMaterial::HasTexture() const
{
return tex != 0;
}
void MyMaterial::SetTexture(MyTexture2D * texture)
{
tex = texture;
}
void MyMaterial::SetAmbient(float const & red, float const & green, float const & blue, float const & alpha)
{
a = MyColorRGBA(red, green, blue, alpha);
}
void MyMaterial::SetAmbient(MyColorRGBA const & ambient)
{
a = ambient;
}
void MyMaterial::SetDiffuse(float const & red, float const & green, float const & blue, float const & alpha)
{
d = MyColorRGBA(red, green, blue, alpha);
}
void MyMaterial::SetDiffuse(MyColorRGBA const & diffuse)
{
d = diffuse;
}
void MyMaterial::SetSpecular(float const & red, float const & green, float const & blue, float const & alpha)
{
s = MyColorRGBA(red, green, blue, alpha);
}
void MyMaterial::SetSpecular(MyColorRGBA const & specular)
{
s = specular;
}
void MyMaterial::SetShine(float const & shine)
{
sh = std::max(shine, 0.0f);
}
void MyMaterial::SetToon(bool const & toon)
{
t = toon;
}
| 18 | 175 | 0.704678 | nicholaschiasson |
0adb4715fed4338c2bc04fc8b68daba3dd0520c4 | 3,003 | hh | C++ | AssocTools/AstSTLMap2.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | AssocTools/AstSTLMap2.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | AssocTools/AstSTLMap2.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | //-------------------------------------------------------------------
// File and Version Information:
// $Id: AstSTLMap2.hh 436 2010-01-13 16:51:56Z stroili $
//
// Description:
// two -directional association map between two data types.
//
//
// Author List:
// Luca Lista 27 Mar 97
//
//-------------------------------------------------------------------
#ifndef ASTSTLMAP2_HH
#define ASTSTLMAP2_HH
//-------------
// C Headers --
//-------------
//---------------
// C++ Headers --
//---------------
#include <iostream>
#include <vector>
using std::vector;
#include <map>
using std::map;
#include "BbrStdUtils/CollectionUtils.hh"
//----------------------
// Base Class Headers --
//----------------------
#include "AbsEvent/AbsEvtObj.hh"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
// ---------------------
// -- Class Interface --
// ---------------------
template<class T1, class T2>
class AstSTLMap2 :
public AbsEvtObj
{
//--------------------
// Declarations --
//--------------------
// Typedefs, consts, and enums
public:
typedef std::map< T1*, vector<T2*>, BbrPtrLess > Map1;
typedef std::map< T2*, vector<T1*>, BbrPtrLess > Map2;
//--------------------
// Instance Members --
//--------------------
public:
// Constructors
AstSTLMap2();
AstSTLMap2(unsigned (*)(T1 *const&), unsigned (*)(T2 *const&));
// Detsructor
virtual ~AstSTLMap2();
// Selectors (const)
inline const Map1& map1() const
{ return _map1; }
inline const Map2& map2() const
{ return _map2; }
bool findValue1(T1*, vector<T2*>& retval) const;
bool findValue2(T2*, vector<T1*>& retval) const;
// Return the associated list
T2* findFirstValue1(const T1*) const;
T1* findFirstValue2(const T2*) const;
// Return the first item in the associated list, or 0 if there is no match.
int members1() const {return _map1.size();}
int members2() const {return _map2.size();}
int entries1(T1* ) const;
int entries2(T2*) const;
size_t removeMatchesForKey1(const T1 *);
size_t removeMatchesForKey2(const T2 *);
// Return the number of matches removed, 0 if the key was not found.
// Helpers (const)
bool contains(T1*, T2*) const ;
// Note that the search for T2 is linear.
bool containsT1(T1*) const ;
bool containsT2(T2*) const ;
// Modifiers
void append(T1*, T2*);
size_t remove(T1*, T2*);
// Returns 0 if either T1 or T2 cannot be found.
// Note that the search for T2 is linear.
void clear();
// Clear map of entries. Does not delete contents.
protected:
private:
static unsigned hashFunction1(T1 *const & p);
static unsigned hashFunction2(T2 *const & p);
Map1 _map1;
Map2 _map2;
Map1& notConstMap1() const;
Map2& notConstMap2() const;
};
#ifdef BABAR_COMP_INST
#include "AssocTools/AstSTLMap2.icc"
#endif // BABAR_COMP_INST
#endif // TEMPLATE_HH
| 21.604317 | 77 | 0.549784 | brownd1978 |
0adc04a5f4216f27f8a88e4921256229b1e1fd4c | 7,057 | cpp | C++ | 1/localsearch.cpp | GhostofGoes/evo-comp | 744874da4621f086df8172a6c596c46f23eff58c | [
"MIT"
] | null | null | null | 1/localsearch.cpp | GhostofGoes/evo-comp | 744874da4621f086df8172a6c596c46f23eff58c | [
"MIT"
] | null | null | null | 1/localsearch.cpp | GhostofGoes/evo-comp | 744874da4621f086df8172a6c596c46f23eff58c | [
"MIT"
] | null | null | null | // Project: Assignment 1 - Local Search
// Author: Christopher Goes
// Course: CS 572 Evolutionary Computation
// Semester: Fall 2016
// Github: https://github.com/GhostofGoes/cgoes-cs572
// License: MITv2
// If you're in the class, don't copy the code
// You're welcome to use it to get un-stuck, or learn things like I/O, C++ syntax, libary functions, etc
#include <stdio.h>
#include <iostream>
#include <bitset>
#include "rand.h"
#include "bitHelpers.h"
#define TESTING 0
typedef unsigned long long int Bit64;
typedef unsigned int Bit32;
int encoding = -1, mutation = -1;
inline double fitness( double x, double y ); // Single-peak fitness function that evaluates quality of x and y
inline Bit64 randomJump( Bit64 chromosome, int size ); // Mutation randomly jumps to somewhere in search space
inline Bit64 bitFlip( Bit64 chromosome ); // Mutation randomly flips exactly one bit in the 20 bit chromosome
Bit64 sdIncDec( Bit64 chromosome ); // Mutation increments or decrements one of the fields of 10 bits fields for x or for y (4 possible changes/neighbors)
Bit32 extractX( Bit64 genome ); // Gets x chromosome from the genome
Bit32 extractY( Bit64 genome ); // Gets y chromosome from the genome
inline Bit64 randomGenotype();
double map(double value, double low1, double high1, double low2, double high2);
void printBinary( Bit64 value ); // Prints the binary representation of value
int main( int argc, char *argv[] ) {
if(argc < 3) { // so we don't segfault on something silly like forgetting arguments
printf("Not enough arguments: need encoding(0|1) and mutation(0|1|2).");
return 1;
}
encoding = *argv[1] - '0'; // 0 = identity, 1 = Grey ( the -'0' is ASCII conversion)
mutation = *argv[2] - '0'; // 0 = random jump, 1 = bit flip, 2 = int/dec
initRand(); // Initialize random number generator
int runs = 1000; // Number of times to run the program
if(TESTING) runs = 5;
for( int i = 0; i < runs; i++ ) { // Used to average behavior of program across many runs
Bit64 genotype = randomGenotype(); // Represents chromosome, 20 Least-signifigant Bits (LSB) of an UUL
Bit32 x = 0, y = 0; // x = 10 Most-signifigant bits (MSB), y = 10 LSB of chromosome
double xprime = 0, yprime = 0; // Used to represent decimal value of x/y for fitness function (x:[0, 10], y:[-10, 10])
double fit_xprime = 0.0, fit_yprime = 0.0; // x/y prime values used for best fitness
double currentFitness = 0.0; // Current fitness to compare against best
double bestFitness = 0.0; // Best fitness found
int numImproveMoves = 0; // Number of times fitness was improved
int numFitEvalsBest = 0; // Number of fitness evaluations it took to get best fitness
int evals = 10000; // Number of times to evaluate the fitness function
if(TESTING) evals = 5;
if(TESTING) printBinary(genotype);
for( int fitEvals = 0; fitEvals < evals; fitEvals++ ) { // Fitness evaluation loop
if(TESTING) {
printf("Pre-mutation Genotype: \t");
printBinary(genotype);
printf("Pre-mutation X:\t %d\t\tY:\t %d\n", extractX(genotype), extractY(genotype));
}
// Mutate: 0 = random jump, 1 = bit flip, 2 = single-dimension inc/dec
if( mutation == 0 ) {
genotype = randomJump(genotype, 20);
} else if( mutation == 1 ) {
genotype = bitFlip(genotype);
} else if( mutation == 2 ) {
genotype = sdIncDec(genotype);
}
if(TESTING) {
printf("Post-mutation Genotype: \t");
printBinary(genotype);
}
// Genotype to phenotype mapping
x = extractX(genotype);
y = extractY(genotype);
xprime = map(double(x), 0.0, 1023.0, 0.0, 10.0); // x range = [0, 10]
yprime = map(double(y), 0.0, 1023.0, -10.0, 10.0); // y range = [-10, 10]
if(TESTING) { printf("Post-mutation\tx:\t %d\ty:\t %d\n", x, y); }
// Evaluate fitness
currentFitness = fitness(xprime, yprime);
// If the fitness we found is better, save it's genotype, fitness, and iterations taken
if( currentFitness > bestFitness ) {
bestFitness = currentFitness;
numFitEvalsBest = fitEvals;
fit_xprime = xprime;
fit_yprime = yprime;
numImproveMoves++;
}
} // end fitness eval loop
// Output results of the run
printf("%d %d %f %f %f\n", numFitEvalsBest, numImproveMoves, fit_xprime, fit_yprime, bestFitness);
} // end program loop
return 0;
} // end main
// Calculates the fitness of decoded X and Y values of the chromosome
inline double fitness( double x, double y ) {
return 1.0 / ( pow((x - 1.0), 2) + pow((y - 3.0), 2) + 1.0 );
}
// Randomly jumps to anywhere in the search space, which is defined by the size.
inline Bit64 randomJump( Bit64 chromosome, int size ) {
return randMask((1ULL << size) - 1); // Mask is number of bits in chromosome
}
// Randomly flips a bit in the chromosome
inline Bit64 bitFlip( Bit64 chromosome ) { // Assumes a 20 bit chromosome
return chromosome ^ (1ULL << randMod(20)); // Flip a random bit in the chromosome
}
// Single-dimension Increment or Decrement
// Randomly increments or decrements X or Y of chromosome by 1.
// This results in a very small neighborhood. Alternate encodings will only improve range, not size, of this neighborhood.
Bit64 sdIncDec( Bit64 chromosome ) {
Bit32 x = chromosome >> 10;
Bit32 y = chromosome & ((1ULL << 10) - 1);
Bit64 newChromosome = 0;
int change = randMod(4); // 0 = x + inc, 1 = x + dec, 2 = y + inc, 3 = y + dec
if( change == 0 ) { // Increment X (MSD of genotype)
if( x == 1023 ) x = 0; // 1024 == 2^10 (or 2**10 in python its handy)
else x += 1;
} else if( change == 1 ) { // Decrement X (MSD of genotype)
if( x == 0 ) x = 1023;
else x -= 1;
} else if( change == 2 ) { // Increment Y (LSD of genotype)
if( y == 1023 ) y = 0;
else y += 1;
} else if( change == 3 ) { // Decrement Y (LSD of genotype)
if( y == 0 ) y = 1023;
else y -= 1;
}
// Recombine modified X and Y
newChromosome = x << 10;
newChromosome |= y;
return newChromosome;
}
Bit32 extractX( Bit64 genome ) {
Bit32 x = genome >> 10; // Get the 10 Most signifigant bits in genome
if( encoding == 1 ) // Grey code mapping
x = bitDeGray(x);
return x;
}
Bit32 extractY( Bit64 genome ) {
Bit32 y = genome & ((1ULL << 10) - 1); // Get the 10 Least signifigant bits out of genome
if( encoding == 1 ) // Grey code mapping
y = bitDeGray(y);
return y;
}
// Gives a random 20-bit genotype
inline Bit64 randomGenotype() {
return randULL() & 1048575; // 2^20 - 1
}
// map value from [low1, high2] -> [low2, high2]
// This basically maps from range of, say, [0,10] to [0,1023]
// Function Copyright Robert Heckendorn
double map(double value, double low1, double high1, double low2, double high2) {
double denom, a, b;
denom = high1 - low1;
a = (high2 - low2)/denom;
b = (high1 * low2 - high2 * low1)/denom;
return a * value + b;
}
// Prints the binary representation of a ULL for testing purposes
void printBinary( Bit64 value ) {
std::bitset<20> binaryValue ((unsigned long) value);
std::cout << binaryValue.to_string() << std::endl;
}
| 38.353261 | 159 | 0.663596 | GhostofGoes |
0ade3fa514c18931177c702ef1f57baefe1c50c9 | 835 | cpp | C++ | Atum/Support/MetaData/ColorWidget.cpp | ENgineE777/Atum | 3e9417e2a7deda83bf937612fd070566eb932484 | [
"Zlib"
] | 23 | 2017-11-01T14:47:26.000Z | 2021-12-30T08:04:31.000Z | Atum/Support/MetaData/ColorWidget.cpp | ENgineE777/Atum | 3e9417e2a7deda83bf937612fd070566eb932484 | [
"Zlib"
] | 1 | 2018-12-06T14:19:55.000Z | 2018-12-07T04:06:35.000Z | Atum/Support/MetaData/ColorWidget.cpp | ENgineE777/Atum | 3e9417e2a7deda83bf937612fd070566eb932484 | [
"Zlib"
] | 4 | 2017-11-30T10:25:58.000Z | 2019-04-21T14:11:40.000Z |
#include "ColorWidget.h"
void ColorWidget::Init(EUICategories* parent, const char* catName, const char* labelName)
{
ProperyWidget::Init(parent, catName, labelName);
ecolor = new EUILabel(panel, "", 90, 5, 95, 20);
ecolor->SetListener(-1, this, 0);
}
void ColorWidget::SetData(void* owner, void* set_data)
{
data = (Color*)set_data;
int clr[3];
clr[0] = (int)(data->r * 255.0f);
clr[1] = (int)(data->g * 255.0f);
clr[2] = (int)(data->b * 255.0f);
ecolor->SetBackgroundColor(true, clr);
}
void ColorWidget::OnLeftDoubliClick(EUIWidget* sender, int mx, int my)
{
if (EUI::OpenColorDialog(ecolor->GetRoot()->GetNative(), &data->r))
{
int clr[3];
clr[0] = (int)(data->r * 255.0f);
clr[1] = (int)(data->g * 255.0f);
clr[2] = (int)(data->b * 255.0f);
ecolor->SetBackgroundColor(true, clr);
changed = true;
}
} | 23.194444 | 89 | 0.640719 | ENgineE777 |
0ae0f6253de6e035a276845c24110d086db66b27 | 2,267 | cpp | C++ | TDEngine2/source/graphics/UI/CImageComponent.cpp | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-15T01:14:15.000Z | 2019-07-15T01:14:15.000Z | TDEngine2/source/graphics/UI/CImageComponent.cpp | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 76 | 2018-10-27T16:59:36.000Z | 2022-03-30T17:40:39.000Z | TDEngine2/source/graphics/UI/CImageComponent.cpp | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-29T02:02:08.000Z | 2019-07-29T02:02:08.000Z | #include "../../../include/graphics/UI/CImageComponent.h"
namespace TDEngine2
{
struct TImageArchiveKeys
{
};
CImage::CImage() :
CBaseComponent()
{
}
E_RESULT_CODE CImage::Init()
{
if (mIsInitialized)
{
return RC_FAIL;
}
mImageResourceId = TResourceId::Invalid;
mImageSpriteId = Wrench::StringUtils::GetEmptyStr();
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CImage::Load(IArchiveReader* pReader)
{
if (!pReader)
{
return RC_FAIL;
}
return RC_OK;
}
E_RESULT_CODE CImage::Save(IArchiveWriter* pWriter)
{
if (!pWriter)
{
return RC_FAIL;
}
return RC_OK;
}
E_RESULT_CODE CImage::SetImageId(const std::string& id)
{
if (id.empty())
{
return RC_INVALID_ARGS;
}
mImageSpriteId = id;
return RC_OK;
}
E_RESULT_CODE CImage::SetImageResourceId(TResourceId resourceId)
{
if (TResourceId::Invalid == resourceId)
{
return RC_INVALID_ARGS;
}
mImageResourceId = resourceId;
return RC_OK;
}
const std::string& CImage::GetImageId() const
{
return mImageSpriteId;
}
TResourceId CImage::GetImageResourceId() const
{
return mImageResourceId;
}
IComponent* CreateImage(E_RESULT_CODE& result)
{
return CREATE_IMPL(IComponent, CImage, result);
}
CImageFactory::CImageFactory() :
CBaseObject()
{
}
E_RESULT_CODE CImageFactory::Init()
{
if (mIsInitialized)
{
return RC_FAIL;
}
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CImageFactory::Free()
{
if (!mIsInitialized)
{
return RC_FAIL;
}
mIsInitialized = false;
delete this;
return RC_OK;
}
IComponent* CImageFactory::Create(const TBaseComponentParameters* pParams) const
{
if (!pParams)
{
return nullptr;
}
const TImageParameters* params = static_cast<const TImageParameters*>(pParams);
E_RESULT_CODE result = RC_OK;
return CreateImage(result);
}
IComponent* CImageFactory::CreateDefault(const TBaseComponentParameters& params) const
{
E_RESULT_CODE result = RC_OK;
return CreateImage(result);
}
TypeId CImageFactory::GetComponentTypeId() const
{
return CImage::GetTypeId();
}
IComponentFactory* CreateImageFactory(E_RESULT_CODE& result)
{
return CREATE_IMPL(IComponentFactory, CImageFactory, result);
}
} | 14.720779 | 87 | 0.698721 | bnoazx005 |
0ae15dc548989815c4b739d02d072d022d7897d1 | 2,607 | hxx | C++ | opencascade/HLRAppli_ReflectLines.hxx | valgur/OCP | 2f7d9da73a08e4ffe80883614aedacb27351134f | [
"Apache-2.0"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/HLRAppli_ReflectLines.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 66 | 2019-12-20T16:07:36.000Z | 2022-03-15T21:56:10.000Z | opencascade/HLRAppli_ReflectLines.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // File: HLRAppli_ReflectLines.cdl
// Created: 05.12.12 15:53:35
// Created by: Julia GERASIMOVA
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _HLRAppli_ReflectLines_HeaderFile
#define _HLRAppli_ReflectLines_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <HLRAlgo_Projector.hxx>
#include <HLRBRep_Algo.hxx>
#include <HLRBRep_TypeOfResultingEdge.hxx>
#include <TopoDS_Shape.hxx>
#include <Standard_Real.hxx>
class TopoDS_Shape;
//! This class builds reflect lines on a shape
//! according to the axes of view defined by user.
//! Reflect lines are represented by edges in 3d.
class HLRAppli_ReflectLines
{
public:
DEFINE_STANDARD_ALLOC
//! Constructor
Standard_EXPORT HLRAppli_ReflectLines(const TopoDS_Shape& aShape);
//! Sets the normal to the plane of visualisation,
//! the coordinates of the view point and
//! the coordinates of the vertical direction vector.
Standard_EXPORT void SetAxes (const Standard_Real Nx, const Standard_Real Ny, const Standard_Real Nz, const Standard_Real XAt, const Standard_Real YAt, const Standard_Real ZAt, const Standard_Real XUp, const Standard_Real YUp, const Standard_Real ZUp);
Standard_EXPORT void Perform();
//! returns resulting compound of reflect lines
//! represented by edges in 3d
Standard_EXPORT TopoDS_Shape GetResult() const;
//! returns resulting compound of lines
//! of specified type and visibility
//! represented by edges in 3d or 2d
Standard_EXPORT TopoDS_Shape GetCompoundOf3dEdges(const HLRBRep_TypeOfResultingEdge type,
const Standard_Boolean visible,
const Standard_Boolean In3d) const;
protected:
private:
HLRAlgo_Projector myProjector;
Handle(HLRBRep_Algo) myHLRAlgo;
TopoDS_Shape myShape;
//TopoDS_Shape myCompound;
};
#endif // _HLRAppli_ReflectLines_HeaderFile
| 28.966667 | 254 | 0.739547 | valgur |
0ae1e5cb12c6d0b8f7e0165ff950ad9198842ba4 | 2,087 | hpp | C++ | include/termox/widget/widgets/horizontal_slider.hpp | skvl/TermOx | 35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934 | [
"MIT"
] | null | null | null | include/termox/widget/widgets/horizontal_slider.hpp | skvl/TermOx | 35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934 | [
"MIT"
] | null | null | null | include/termox/widget/widgets/horizontal_slider.hpp | skvl/TermOx | 35761f9ba0e300b7d8edd4e2a0c7dd33ef8fb934 | [
"MIT"
] | 1 | 2021-08-06T10:17:28.000Z | 2021-08-06T10:17:28.000Z | #ifndef TERMOX_WIDGET_WIDGETS_HORIZONTAL_SLIDER_HPP
#define TERMOX_WIDGET_WIDGETS_HORIZONTAL_SLIDER_HPP
#include <cstddef>
#include <signals_light/signal.hpp>
#include <termox/painter/color.hpp>
#include <termox/painter/glyph.hpp>
#include <termox/painter/painter.hpp>
#include <termox/system/key.hpp>
#include <termox/system/mouse.hpp>
#include <termox/widget/focus_policy.hpp>
#include <termox/widget/pipe.hpp>
#include <termox/widget/widget.hpp>
namespace ox {
// TODO this can probably be removed, scroll bar replaces it.
class Horizontal_slider : public Widget {
public:
sl::Signal<void(float)> percent_changed;
sl::Signal<void()> scrolled_up;
sl::Signal<void()> scrolled_down;
public:
Horizontal_slider()
{
using namespace pipe;
*this | fixed_height(1) | strong_focus() |
wallpaper(L' ' | bg(Color::Light_gray));
}
void set_percent(float percent);
auto percent() const -> float { return percent_progress_; }
protected:
auto paint_event() -> bool override
{
auto const x = percent_to_position(percent_progress_);
Painter{*this}.put(indicator_, x, 0);
return Widget::paint_event();
}
auto mouse_press_event(Mouse const& m) -> bool override;
auto mouse_wheel_event(Mouse const& m) -> bool override;
auto key_press_event(Key k) -> bool override;
private:
Glyph indicator_ = L'░';
float percent_progress_ = 0.0;
private:
auto position_to_percent(std::size_t position) -> float;
auto percent_to_position(float percent) -> std::size_t;
};
/// Helper function to create an instance.
template <typename... Args>
auto horizontal_slider(Args&&... args) -> std::unique_ptr<Horizontal_slider>
{
return std::make_unique<Horizontal_slider>(std::forward<Args>(args)...);
}
namespace slot {
auto set_percent(Horizontal_slider& s) -> sl::Slot<void(float)>;
auto set_percent(Horizontal_slider& s, float percent) -> sl::Slot<void(void)>;
} // namespace slot
} // namespace ox
#endif // TERMOX_WIDGET_WIDGETS_HORIZONTAL_SLIDER_HPP
| 27.460526 | 78 | 0.703402 | skvl |
0ae24cf263f367d8460b5612c853eeda781029c5 | 70 | cpp | C++ | sprint00/t06/main.cpp | Hvvang/CppTrack | 3e1854d626d153f5597459200f715a91f6a03107 | [
"MIT"
] | 1 | 2020-08-27T23:41:48.000Z | 2020-08-27T23:41:48.000Z | sprint00/t06/main.cpp | Hvvang/CppTrack | 3e1854d626d153f5597459200f715a91f6a03107 | [
"MIT"
] | null | null | null | sprint00/t06/main.cpp | Hvvang/CppTrack | 3e1854d626d153f5597459200f715a91f6a03107 | [
"MIT"
] | null | null | null | #include "meadSong.h"
int main(void) {
showLyrics();
return 0;
}
| 10 | 21 | 0.628571 | Hvvang |
0ae69f1eeb6ed74a8c946c9194f0d558aaf1f9bf | 13,299 | hpp | C++ | include/xul/net/http/http_client.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | 2 | 2018-03-16T07:06:48.000Z | 2018-04-02T03:02:14.000Z | include/xul/net/http/http_client.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | null | null | null | include/xul/net/http/http_client.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | 1 | 2019-08-12T05:15:29.000Z | 2019-08-12T05:15:29.000Z | #pragma once
#include <xul/net/http/http_connection.hpp>
#include <xul/net/url_request.hpp>
#include <xul/net/uri.hpp>
#include <xul/util/timer_holder.hpp>
#include <xul/util/runnable_callback.hpp>
#include <xul/net/http/http_content_type.hpp>
#include <xul/net/http/http_method.hpp>
#include <xul/net/url_messages.hpp>
#include <xul/net/url_response.hpp>
#include <xul/data/printables.hpp>
#include <xul/data/buffer.hpp>
#include <xul/util/log.hpp>
#include <xul/lang/object_ptr.hpp>
#include <xul/lang/object_impl.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio/error.hpp>
#include <string>
namespace xul {
class http_client : public object_impl<object>
{
public:
typedef boost::function<void (http_client*, uri*, int, url_response*, uint8_t*, int)> download_data_callback_type;
typedef boost::function<void (http_client*, uri*, int, url_response*, int64_t)> query_head_callback_type;
enum error_code
{
error_general = -1,
error_timeout = -2,
};
class http_handler : private boost::noncopyable, public timer_listener, public http_connection_listener_adapter
{
public:
explicit http_handler(http_client& owner) : m_owner(owner)
{
m_xul_logger = owner.m_xul_logger;
m_content_length = 0;
}
virtual ~http_handler()
{
}
void set_extra_header(const string_table* extra_headers)
{
m_extra_headers = extra_headers;
}
void request(uri* u)
{
m_url = u;
m_owner.m_connection->request(m_method.c_str(), m_url->get_original_string(), m_extra_headers.get());
}
virtual void on_timer_elapsed(timer* sender)
{
handle_error(error_timeout);
}
virtual void do_handle_response() = 0;
virtual bool on_http_response(http_connection* sender, url_response* resp, const char* real_url)
{
m_response = resp;
m_content_length = url_messages::get_content_length(*resp);
XUL_DEBUG("on_http_response content_length=" << m_content_length << " " << *resp);
do_handle_response();
return true;
}
virtual bool on_http_data(http_connection* sender, const uint8_t* data, int size)
{
return false;
}
virtual void on_http_complete(http_connection* sender, int64_t size)
{
}
virtual void on_http_error(http_connection* sender, int errcode)
{
handle_error(errcode);
}
virtual void handle_error(int errcode) = 0;
protected:
XUL_LOGGER_DEFINE();
http_client& m_owner;
boost::intrusive_ptr<uri> m_url;
boost::intrusive_ptr<url_response> m_response;
int64_t m_content_length;
boost::intrusive_ptr<const string_table> m_extra_headers;
std::string m_method;
//timer_ptr m_timeout_timer;
};
class http_download_data_handler : public http_handler
{
public:
explicit http_download_data_handler(http_client& owner, int maxSize, download_data_callback_type callback)
: http_handler(owner), m_callback(callback)
{
m_method = http_method::get();
m_max_size = maxSize;
m_recv_size = 0;
}
virtual void do_handle_response()
{
m_data.resize(0);
if (m_content_length < 0)
{
XUL_WARN("http_client do_handle_response no content-length from " << m_url->get_original_string());
}
if (m_content_length > m_max_size)
{
XUL_WARN("content_length is too large " << xul::make_tuple(m_content_length, m_max_size));
handle_error(-1);
return;
}
if (m_content_length > 0)
m_data.reserve(m_content_length);
}
virtual bool on_http_data(http_connection* sender, const uint8_t* data, int size)
{
m_data.append(data, size);
if (m_data.size() > m_max_size)
{
XUL_REL_ERROR("recv_size is too large " << xul::make_tuple(m_data.size(), m_max_size));
handle_error(-1);
return false;
}
return true;
}
virtual void on_http_complete(http_connection* sender, int64_t size)
{
invoke_callback(0);
}
virtual void handle_error(int errcode)
{
m_owner.close_connection();
if (boost::asio::error::eof == errcode && m_content_length < 0)
{
invoke_callback(0);
return;
}
invoke_callback(errcode);
}
protected:
void invoke_callback(int errcode)
{
m_owner.handle_complete();
m_callback(&m_owner, m_url.get(), errcode, m_response.get(), m_data.data(), m_data.size());
}
private:
download_data_callback_type m_callback;
byte_buffer m_data;
int m_max_size;
int m_recv_size;
};
class http_query_head_handler : public http_handler
{
public:
explicit http_query_head_handler(http_client& owner, query_head_callback_type callback)
: http_handler(owner), m_callback(callback)
{
m_method = http_method::head();
}
virtual void do_handle_response()
{
m_owner.handle_complete();
m_callback(&m_owner, m_url.get(), 0, m_response.get(), m_content_length);
}
virtual void handle_error(int errcode)
{
m_owner.handle_complete();
m_callback(&m_owner, m_url.get(), errcode, m_response.get(), 0);
}
private:
query_head_callback_type m_callback;
};
class http_post_data_handler : public http_download_data_handler
{
public:
explicit http_post_data_handler(http_client& owner, int maxSize, download_data_callback_type callback
, const std::string& bodyData, const std::string& contentType = std::string())
: http_download_data_handler(owner, maxSize, callback)
, m_post_body_data(bodyData)
, m_content_type(contentType)
{
m_method = http_method::post();
if (m_content_type.empty())
{
m_content_type = http_content_type::octet_stream();
}
}
virtual void on_http_put_content(http_connection* sender)
{
sender->send_data(reinterpret_cast<const uint8_t*>(m_post_body_data.data()), m_post_body_data.size());
}
private:
std::string m_post_body_data;
std::string m_content_type;
};
explicit http_client(io_service* ios, bool http11 = false, bool gzip_enabled = false)
: m_ios(ios)
, m_connection(create_http_connection(ios))
, m_keepalive(false)
{
XUL_LOGGER_INIT("http_client");
m_receive_buffer_size = 32 * 1024;
set_keepalive(false);
m_connection->ref_options()->set("gzip", gzip_enabled ? "on" : "off");
m_connection->ref_options()->set_protocol_version(http11 ? "1.1" : "1.0");
m_connection->set_receive_buffer_size(m_receive_buffer_size);
m_connection->set_decoder_buffer_size(m_receive_buffer_size + 1000);
}
virtual ~http_client()
{
if (m_connection)
{
m_connection->set_listener(NULL);
}
this->clear();
}
void set_keepalive(bool keepalive)
{
set_keep_alive(keepalive);
}
void set_keep_alive(bool keepalive)
{
m_keepalive = keepalive;
if (m_connection)
m_connection->ref_options()->set_keep_alive(m_keepalive);
}
void clear()
{
m_http_handler.reset();
this->close();
}
bool is_started() const
{
return m_connection && m_connection->is_started();
}
void set_receive_buffer_size(size_t bufsize)
{
if (bufsize < 1024 || bufsize > 2 * 1024 * 1024)
return;
m_receive_buffer_size = bufsize;
if (m_connection)
m_connection->set_receive_buffer_size(m_receive_buffer_size);
}
void handle_complete()
{
XUL_DEBUG("handle_complete");
if (!m_keepalive)
{
close_connection();
}
}
void close_connection()
{
if (m_connection)
{
m_connection->set_listener(NULL);
m_connection->close();
}
}
void close()
{
XUL_DEBUG("close");
close_connection();
//m_http_handler.reset();
}
//void async_download_data(const char* host, int port, const url_request* req, int maxSize, download_data_callback_type callback)
//{
// close();
// m_http_handler.reset(new http_download_data_handler(*this, maxSize, callback));
// async_execute(host, port, req);
//}
void async_download_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback,
const string_table* extra_header = NULL)
{
download_data(urlstr, maxSize, callback, extra_header);
}
void download_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback,
const string_table* extra_header = NULL)
{
boost::intrusive_ptr<uri> u = create_uri();
if (false == u->parse(urlstr.c_str()))
{
uint8_t* buf = NULL;
boost::intrusive_ptr<runnable> r = make_runnable(boost::bind(callback, this, u.get(), -1, (xul::url_response*)NULL, buf, 0));
m_ios->post(r.get());
return;
}
async_download_uri_data(u.get(), maxSize, callback, extra_header);
}
void async_download_uri_data(uri* u, size_t maxSize, download_data_callback_type callback,
const string_table* extra_header = NULL)
{
XUL_DEBUG("async_download_uri_data " << u->get_original_string());
//close();
m_http_handler.reset(new http_download_data_handler(*this, maxSize, callback));
if (extra_header)
{
m_http_handler->set_extra_header(extra_header);
}
async_download(u);
}
void async_query_head(uri* u, query_head_callback_type callback)
{
//close();
m_http_handler.reset(new http_query_head_handler(*this, callback));
async_download(u);
}
void async_post_data(uri* u, size_t maxSize, download_data_callback_type callback,
const std::string& body, const std::string& contentType = std::string(),
const string_table* extra_header = NULL)
{
post_data(u->get_original_string(), maxSize, callback, body, contentType, extra_header);
}
void async_post_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback,
const std::string& body, const std::string& contentType = std::string(),
const string_table* extra_header = NULL)
{
post_data(urlstr, maxSize, callback, body, contentType, extra_header);
}
void post_data(const std::string& urlstr, size_t maxSize, download_data_callback_type callback,
const std::string& body, const std::string& contentType = std::string(),
const string_table* extra_header = NULL)
{
boost::intrusive_ptr<uri> u = create_uri();
u->parse(urlstr.c_str());
//close();
m_http_handler.reset(new http_post_data_handler(*this, maxSize, callback, body, contentType));
boost::intrusive_ptr<string_table> headers;
if (extra_header)
headers = extra_header->clone();
else
headers = create_associative_istring_array();
headers->set("Content-Length", numerics::format<int>(body.size()).c_str());
m_http_handler->set_extra_header(headers.get());
async_download(u.get());
}
const http_connection* get_connection() const { return m_connection.get(); }
protected:
void async_download(uri* u)
{
XUL_DEBUG("async_download " << u->get_original_string());
if (!m_http_handler)
{
assert(false);
return;
}
m_connection->set_listener(m_http_handler.get());
m_http_handler->request(u);
}
//void async_execute(const char* host, int port, const url_request* req)
//{
// XUL_DEBUG("async_execute " << xul::make_tuple(host, port, req->get_url()));
// if (!m_http_handler)
// {
// assert(false);
// return;
// }
// m_connection->set_listener(m_http_handler.get());
// m_connection->execute(host, port, req);
//}
private:
XUL_LOGGER_DEFINE();
boost::intrusive_ptr<io_service> m_ios;
size_t m_receive_buffer_size;
boost::intrusive_ptr<http_connection> m_connection;
boost::shared_ptr<http_handler> m_http_handler;
bool m_keepalive;
};
}
| 33.498741 | 137 | 0.609219 | hindsights |
0aee68ed3261bbc11f994664754f9d0544f656e5 | 6,803 | cpp | C++ | lv_demos/src/lv_demo_graphing/lv_demo_graphing.cpp | mov-rax/Smart_Symbolic_Graphing_Calculator | 2ebd2e1cb12da1a826a9aa650027c11e239bfe4a | [
"MIT"
] | null | null | null | lv_demos/src/lv_demo_graphing/lv_demo_graphing.cpp | mov-rax/Smart_Symbolic_Graphing_Calculator | 2ebd2e1cb12da1a826a9aa650027c11e239bfe4a | [
"MIT"
] | null | null | null | lv_demos/src/lv_demo_graphing/lv_demo_graphing.cpp | mov-rax/Smart_Symbolic_Graphing_Calculator | 2ebd2e1cb12da1a826a9aa650027c11e239bfe4a | [
"MIT"
] | null | null | null | #include "lv_demo_graphing.hxx"
#include "graph.hxx"
#include <math.h>
static mpf_class plot_sin(mpf_class x) {
return mpf_class(sin(x.get_d()*0.1) * 50.0);
}
static void zoom_btnmatrix_cb(lv_event_t* event){
uint32_t id = lv_btnmatrix_get_selected_btn(event->target);
if (id == 0) {
static_cast<graphing::Graph*>(event->user_data)->scale_delta(mpf_class(-0.1));
} else {
static_cast<graphing::Graph*>(event->user_data)->scale_delta(mpf_class(+0.1));
}
}
static void dropdown_button_cb(lv_event_t* event){
char buf[10];
std::cout << "DROPDOWN_BUTTON_CB\n";
//std::stringstream ss;
int id = lv_dropdown_get_selected(event->target);
lv_dropdown_get_selected_str(event->target, buf, sizeof(buf)); // C function, so no std::string
//ss << buf;
auto graph = static_cast<graphing::Graph*>(event->user_data);
// Check if user selected to add a function to the graph.
if (buf[0]=='+'){
graph->add_function("");
lv_dropdown_set_selected(event->target, id);
graph->set_function_textarea_str("");
return;
}
graph->switch_to_bold(id);
// Finds user-selected plot.
graphing::Plot* plot = graph->get_plot(id);
if (plot == nullptr)
graph->set_function_textarea_str("NULL");
else {
// std::cout << "ID: " << id << "\n";
// std::cout << "EXPR: " << plot->function_expression << "\n";
graph->set_function_textarea_str(plot->function_expression);
}
//graph->update();
//std::cout << buf << "\n";
}
static void textarea_cb(lv_event_t* event){
auto graph = static_cast<graphing::Graph*>(event->user_data);
auto func_str = graph->get_function_button_selected_str();
auto func_id = graph->get_function_button_selected_id();
auto func_expression = std::string(lv_textarea_get_text(event->target));
auto plot = graph->get_plot(func_id);
std::cout << "TEXTAREA_CB: " << func_str << " " << func_expression << " " << func_id << "\n";
graph->update_function(func_str + "(x):=" + func_expression);
plot->name = std::move(func_str);
plot->function_expression = std::move(func_expression);
graph->update();
}
DEFINE_GRAPH {
#if ENABLE_GIAC == 1
static graphing::Graph graph(lv_scr_act(), ctx);
#else
static graphing::Graph graph(lv_scr_act());
#endif
static lv_style_t zoom_style_bg;
static lv_style_t zoom_style;
static lv_style_t textarea_style;
static lv_style_t function_button_style;
static const char* map[] = {"+", "-"};
static lv_obj_t* zoom_buttons = lv_btnmatrix_create(graph.get_canvas());
static lv_obj_t* function_text_area = lv_textarea_create(graph.get_canvas());
static lv_obj_t* function_button = lv_dropdown_create(graph.get_canvas());
// zoom button setup
lv_style_init(&zoom_style_bg);
lv_style_set_pad_all(&zoom_style_bg, 10);
//lv_style_set_pad_gap(&zoom_style_bg, 0);
//lv_style_set_clip_corner(&zoom_style_bg, true);
//lv_style_set_radius(&zoom_style_bg, LV_RADIUS_CIRCLE);
lv_style_set_border_width(&zoom_style_bg, 0);
lv_style_set_bg_opa(&zoom_style_bg, LV_OPA_0);
//lv_style_set_size(&zoom_style_bg, 50);
lv_style_init(&zoom_style);
//lv_style_set_radius(&zoom_style, 0);
//lv_style_set_border_width(&zoom_style, 1);
lv_style_set_border_opa(&zoom_style, LV_OPA_50);
lv_style_set_shadow_color(&zoom_style, lv_color_black());
lv_style_set_shadow_spread(&zoom_style, 1);
lv_style_set_shadow_width(&zoom_style, 20);
lv_style_set_shadow_ofs_y(&zoom_style, 0);
lv_style_set_shadow_opa(&zoom_style, LV_OPA_70);
lv_style_set_text_font(&zoom_style, &lv_font_dejavu_16_persian_hebrew);
//lv_style_set_border_color(&zoom_style, lv_palette_main(LV_PALETTE_GREY));
//lv_style_set_border_side(&zoom_style, LV_BORDER_SIDE_INTERNAL);
//lv_style_set_radius(&zoom_style, 0);
lv_btnmatrix_set_map(zoom_buttons, map);
lv_btnmatrix_set_btn_ctrl_all(zoom_buttons, LV_BTNMATRIX_CTRL_CLICK_TRIG);
lv_obj_add_style(zoom_buttons, &zoom_style_bg, 0);
lv_obj_add_style(zoom_buttons, &zoom_style, LV_PART_ITEMS);
lv_obj_set_size(zoom_buttons, 80, 50);
lv_obj_align(zoom_buttons, LV_ALIGN_TOP_RIGHT, 0, 0);
lv_obj_add_event_cb(zoom_buttons, zoom_btnmatrix_cb, LV_EVENT_VALUE_CHANGED, &graph);
// function text area setup
lv_style_init(&textarea_style);
lv_style_set_text_font(&textarea_style, &lv_font_montserrat_12_subpx);
lv_style_set_border_width(&textarea_style, 1);
lv_style_set_border_opa(&textarea_style, LV_OPA_50);
lv_style_set_shadow_color(&textarea_style, lv_color_black());
lv_style_set_shadow_spread(&textarea_style, 1);
lv_style_set_shadow_width(&textarea_style, 20);
lv_style_set_shadow_ofs_y(&textarea_style, 0);
lv_style_set_shadow_opa(&textarea_style, LV_OPA_70);
lv_style_set_pad_top(&textarea_style, 5);
lv_style_set_pad_right(&textarea_style, 40);
//lv_style_set_pad_left(&textarea_style, 3);
lv_style_set_text_align(&textarea_style, LV_ALIGN_LEFT_MID);
//lv_style_set_text_color(&textarea_style, lv_color_make(255, 0, 0));
lv_textarea_set_one_line(function_text_area, true);
lv_obj_add_style(function_text_area, &textarea_style, 0);
lv_obj_set_size(function_text_area, 180, 30);
lv_obj_align(function_text_area, LV_ALIGN_TOP_MID, -20, 10);
lv_obj_add_event_cb(function_text_area, textarea_cb, LV_EVENT_VALUE_CHANGED, &graph);
// function button setup
lv_style_init(&function_button_style);
lv_style_set_text_font(&function_button_style, &lv_font_montserrat_12_subpx);
lv_style_set_text_align(&function_button_style, LV_ALIGN_CENTER);
lv_style_set_pad_all(&function_button_style, 6);
//lv_style_set_align(&function_button_style, LV_ALIGN_TOP_MID);
//lv_dropdown_add_option(function_button, "f(x)", 0);
//lv_dropdown_set_options(function_button, "f(x)\ng(x)\nh(x)");
lv_dropdown_set_symbol(function_button , NULL);
lv_obj_add_style(function_button, &function_button_style, 0);
lv_obj_add_style(function_button, &function_button_style, LV_PART_ITEMS);
lv_obj_set_size(function_button, 40, 30);
lv_obj_align(function_button, LV_ALIGN_TOP_MID, 50, 10);
lv_obj_add_event_cb(function_button, dropdown_button_cb, LV_EVENT_VALUE_CHANGED, &graph);
// graph setup
graph.set_function_button(function_button);
graph.set_function_textarea(function_text_area);
graph.set_scale(mpf_class("0.5"));
graph.add_function("");
// graph.add_function(plot_sin, LV_COLOR_MAKE16(255, 0, 0), "sin(x)");
// graph.add_function([](mpf_class x){return x;}, LV_COLOR_MAKE16(0, 255, 0), "x");
std::cout <<"EVERYTHING ADDED\n";
graph.update();
}
| 41.993827 | 99 | 0.721446 | mov-rax |
0af0040150be21d39134aa89a76ca7b88410cc2b | 358 | cpp | C++ | 02_code/20_sdl_show_bmp_change_target/mainwindow.cpp | okFancy/audio-video-dev-tutorial | 2cee9e530b402d13a3b84acac6d25bc3b5bd4dc2 | [
"MIT"
] | null | null | null | 02_code/20_sdl_show_bmp_change_target/mainwindow.cpp | okFancy/audio-video-dev-tutorial | 2cee9e530b402d13a3b84acac6d25bc3b5bd4dc2 | [
"MIT"
] | null | null | null | 02_code/20_sdl_show_bmp_change_target/mainwindow.cpp | okFancy/audio-video-dev-tutorial | 2cee9e530b402d13a3b84acac6d25bc3b5bd4dc2 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "playthread.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow) {
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_playButton_clicked() {
PlayThread *thread = new PlayThread(this);
thread->start();
}
| 18.842105 | 46 | 0.681564 | okFancy |
0af2a24c515740fceb1225d3bc42fa245c8d3e41 | 29,148 | cc | C++ | tests/math/gtest_matrix_svd.cc | lemony-fresh/mve | d90cc2c813fef026f7732c5a26f6c15973a36042 | [
"BSD-3-Clause"
] | 1 | 2019-05-30T13:19:21.000Z | 2019-05-30T13:19:21.000Z | tests/math/gtest_matrix_svd.cc | MasterShockwave/mve | 7a96751db098bb6f5c0b4075921b0e8e43a69bb6 | [
"BSD-3-Clause"
] | null | null | null | tests/math/gtest_matrix_svd.cc | MasterShockwave/mve | 7a96751db098bb6f5c0b4075921b0e8e43a69bb6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Test cases for matrix singular value decomposition (SVD).
* Written by Simon Fuhrmann and Daniel Thuerck.
*/
#include <limits>
#include <gtest/gtest.h>
#include "math/matrix_svd.h"
TEST(MatrixSVDTest, MatrixSimpleTest1)
{
math::Matrix<double, 3, 2> A;
A(0, 0) = 1.0; A(0, 1) = 4.0;
A(1, 0) = 2.0; A(1, 1) = 5.0;
A(2, 0) = 3.0; A(2, 1) = 6.0;
math::Matrix<double, 3, 2> U;
math::Matrix<double, 2, 2> S;
math::Matrix<double, 2, 2> V;
math::matrix_svd(A, &U, &S, &V, 1e-10);
math::Matrix<double, 3, 2> A_svd = U * S * V.transposed();
for (int i = 0; i < 6; ++i)
EXPECT_NEAR(A_svd[i], A[i], 1e-13);
}
TEST(MatrixSVDTest, MatrixSimpleTest2)
{
math::Matrix<double, 2, 3> A;
A(0, 0) = 1.0; A(0, 1) = 2.0; A(0, 2) = 3.0;
A(1, 0) = 4.0; A(1, 1) = 5.0; A(1, 2) = 6.0;
math::Matrix<double, 2, 3> U;
math::Matrix<double, 3, 3> S;
math::Matrix<double, 3, 3> V;
math::matrix_svd(A, &U, &S, &V, 1e-10);
math::Matrix<double, 2, 3> A_svd = U * S * V.transposed();
for (int i = 0; i < 6; ++i)
EXPECT_NEAR(A_svd[i], A[i], 1e-13);
}
TEST(MatrixSVDTest, MatrixIsDiagonalTest)
{
float mat[3 * 10];
std::fill(mat, mat + 3 * 10, 0.0f);
EXPECT_TRUE(math::matrix_is_diagonal(mat, 3, 10, 0.0f));
EXPECT_TRUE(math::matrix_is_diagonal(mat, 10, 3, 0.0f));
// Interpret as 3x10 matrix (3 rows, 10 columns).
mat[0 * 10 + 0] = 10.0f;
mat[1 * 10 + 1] = 20.0f;
mat[2 * 10 + 2] = 30.0f;
EXPECT_TRUE(math::matrix_is_diagonal(mat, 3, 10, 0.0f));
mat[2 * 10 + 3] = 40.0f;
EXPECT_FALSE(math::matrix_is_diagonal(mat, 3, 10, 0.0f));
}
TEST(MatrixSVDTest, MatrixIsSubmatrixZeroEnclosed)
{
float mat[4 * 4];
std::fill(mat, mat + 4 * 4, 0.0f);
// Everything is zero.
EXPECT_TRUE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f));
// Doesn't check diagonally.
mat[1 * 4 + 1] = 1.0f;
EXPECT_TRUE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f));
// Damage the upper row.
mat[1 * 4 + 2] = 2.0f;
EXPECT_FALSE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f));
mat[1 * 4 + 2] = 0.0f;
// Damage the left column.
mat[2 * 4 + 1] = 3.0f;
EXPECT_FALSE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 2, 0.0f));
mat[2 * 4 + 1] = 0.0f;
// Check with submatrix as large as full matrix.
EXPECT_TRUE(math::internal::matrix_is_submatrix_zero_enclosed(mat, 4, 4, 0.0f));
}
TEST(MatrixSVDTest, MatrixIsSuperdiagonalNonzero)
{
float mat[3 * 10];
std::fill(mat, mat + 3 * 10, 1.0f);
EXPECT_TRUE(math::internal::matrix_is_superdiagonal_nonzero(mat, 3, 10, 0.0f));
EXPECT_TRUE(math::internal::matrix_is_superdiagonal_nonzero(mat, 10, 3, 0.0f));
// Interpret as 3x10. Inject a zero.
mat[1 * 10 + 2] = 0.0f;
EXPECT_FALSE(math::internal::matrix_is_superdiagonal_nonzero(mat, 3, 10, 0.0f));
}
TEST(MatrixSVDTest, Matrix2x2Eigenvalues)
{
math::Matrix2d mat;
mat(0,0) = 0.318765239858981; mat(0,1) = -0.433592022305684;
mat(1,0) = -1.307688296305273; mat(1,1) = 0.342624466538650;
double smaller_ev, larger_ev;
math::internal::matrix_2x2_eigenvalues(mat.begin(), &smaller_ev, &larger_ev);
EXPECT_NEAR(-0.422395797795416, smaller_ev, 1e-14);
EXPECT_NEAR(1.083785504193047, larger_ev, 1e-14);
}
TEST(MatrixSVDTest, MatrixHouseholderOnZeroTest)
{
double vec_zero[2];
vec_zero[0] = 0;
vec_zero[1] = 0;
double house_vector[2];
double house_beta;
math::internal::matrix_householder_vector(vec_zero, 2, house_vector,
&house_beta, 1e-14, 1.0);
EXPECT_NEAR(1.0, house_vector[0], 1e-14);
EXPECT_NEAR(0.0, house_vector[1], 1e-14);
EXPECT_NEAR(0.0, house_beta, 1e-14);
}
TEST(MatrixSVDTest, MatrixHouseholderNormalTest)
{
double vec[3];
vec[0] = 1;
vec[1] = 4;
vec[2] = 7;
double house_vector[3];
double house_beta;
math::internal::matrix_householder_vector(vec, 3, house_vector, &house_beta,
1e-14, 1.0);
EXPECT_NEAR(1.0, house_vector[0], 1e-14);
EXPECT_NEAR(-0.561479286439136, house_vector[1], 1e-14);
EXPECT_NEAR(-0.982588751268488, house_vector[2], 1e-14);
EXPECT_NEAR(0.876908509020667, house_beta, 1e-14);
}
TEST(MatrixSVDTest, MatrixHouseholderMatrixTest)
{
double house_vector[3];
house_vector[0] = 1.000000000000000;
house_vector[1] = -0.561479286439136;
house_vector[2] = -0.982588751268488;
double house_beta;
house_beta = 0.876908509020667;
double groundtruth_house_matrix[9];
groundtruth_house_matrix[0] = 0.123091490979333;
groundtruth_house_matrix[1] = 0.492365963917331;
groundtruth_house_matrix[2] = 0.861640436855329;
groundtruth_house_matrix[3] = 0.492365963917331;
groundtruth_house_matrix[4] = 0.723546709912780;
groundtruth_house_matrix[5] = -0.483793257652636;
groundtruth_house_matrix[6] = 0.861640436855329;
groundtruth_house_matrix[7] = -0.483793257652636;
groundtruth_house_matrix[8] = 0.153361799107888;
double house_matrix[9];
math::internal::matrix_householder_matrix(house_vector, 3, house_beta,
house_matrix);
for (int i = 0; i < 9; ++i)
{
EXPECT_NEAR(groundtruth_house_matrix[i], house_matrix[i], 1e-14);
}
}
TEST(MatrixSVDTest, MatrixHouseholderApplicationTest)
{
double house_matrix[9];
house_matrix[0] = 0.123091490979333;
house_matrix[1] = 0.492365963917331;
house_matrix[2] = 0.861640436855329;
house_matrix[3] = 0.492365963917331;
house_matrix[4] = 0.723546709912780;
house_matrix[5] = -0.483793257652636;
house_matrix[6] = 0.861640436855329;
house_matrix[7] = -0.483793257652636;
house_matrix[8] = 0.153361799107888;
double groundtruth_mat[9];
groundtruth_mat[0] = 8.124038404635961;
groundtruth_mat[1] = 9.601136296387953;
groundtruth_mat[2] = 11.078234188139946;
groundtruth_mat[3] = 0;
groundtruth_mat[4] = 0.732119416177475;
groundtruth_mat[5] = 1.464238832354949;
groundtruth_mat[6] = 0;
groundtruth_mat[7] = 0.531208978310581;
groundtruth_mat[8] = 1.062417956621162;
double mat[9];
for (int i =0; i < 9; ++i)
{
mat[i] = static_cast<double>(i + 1);
}
math::internal::matrix_apply_householder_matrix(mat, 3, 3, house_matrix, 3, 0, 0);
for (int i = 0; i < 9; ++i)
{
EXPECT_NEAR(groundtruth_mat[i], mat[i], 1e-14);
}
}
TEST(MatrixSVDTest, MatrixBidiagonalizationStandardTest)
{
const int M = 5;
const int N = 4;
double test_matrix[M * N];
for (int i = 0; i < M*N; ++i)
{
test_matrix[i] = static_cast<double>(i + 1);
}
double mat_u[M * M];
double mat_b[M * N];
double mat_v[N * N];
math::internal::matrix_bidiagonalize(test_matrix, M, N, mat_u, mat_b, mat_v, 1e-14);
double groundtruth_mat_u[M * M];
groundtruth_mat_u[0] = 0.042070316191167;
groundtruth_mat_u[1] = 0.773453352501348;
groundtruth_mat_u[2] = -0.565028398052320;
groundtruth_mat_u[3] = -0.167888229103364;
groundtruth_mat_u[4] = 0.229251939845590;
groundtruth_mat_u[5] = 0.210351580955836;
groundtruth_mat_u[6] = 0.505719499712420;
groundtruth_mat_u[7] = 0.667776546677112;
groundtruth_mat_u[8] = 0.448708735648741;
groundtruth_mat_u[9] = 0.229640924620372;
groundtruth_mat_u[10] = 0.378632845720504;
groundtruth_mat_u[11] = 0.237985646923492;
groundtruth_mat_u[12] = 0.312183334193103;
groundtruth_mat_u[13] = -0.623816560842154;
groundtruth_mat_u[14] = -0.559816455877411;
groundtruth_mat_u[15] = 0.546914110485173;
groundtruth_mat_u[16] = -0.029748205865437;
groundtruth_mat_u[17] = -0.367582716208264;
groundtruth_mat_u[18] = 0.573059831151541;
groundtruth_mat_u[19] = -0.486297621488654;
groundtruth_mat_u[20] = 0.715195375249841;
groundtruth_mat_u[21] = -0.297482058654365;
groundtruth_mat_u[22] = -0.047348766609631;
groundtruth_mat_u[23] = -0.230063776854764;
groundtruth_mat_u[24] = 0.587221212900103;
double groundtruth_mat_b[M * N];
std::fill(groundtruth_mat_b, groundtruth_mat_b + M * N, 0);
groundtruth_mat_b[0] = 23.769728648009426;
groundtruth_mat_b[1] = 47.80352488206745;
groundtruth_mat_b[5] = 4.209811764688732;
groundtruth_mat_b[6] = 1.449308026420137;
groundtruth_mat_b[10] = -0.000000000000001;
groundtruth_mat_b[16] = 0.000000000000002;
double groundtruth_mat_v[N * N];
groundtruth_mat_v[0] = 1;
groundtruth_mat_v[1] = 0;
groundtruth_mat_v[2] = 0;
groundtruth_mat_v[3] = 0;
groundtruth_mat_v[4] = 0;
groundtruth_mat_v[5] = 0.536841016220519;
groundtruth_mat_v[6] = -0.738332619241934;
groundtruth_mat_v[7] = 0.408248290463862;
groundtruth_mat_v[8] = 0;
groundtruth_mat_v[9] = 0.576444042007278;
groundtruth_mat_v[10] = -0.032335735149281;
groundtruth_mat_v[11] = -0.816496580927726;
groundtruth_mat_v[12] = 0;
groundtruth_mat_v[13] = 0.616047067794038;
groundtruth_mat_v[14] = 0.673661148943370;
groundtruth_mat_v[15] = 0.408248290463864;
}
TEST(MatrixSVDTest, MatrixBidiagonalizationQuadraticTest)
{
const int M = 3;
double test_matrix[M * M];
for (int i = 0; i < M*M; ++i)
{
test_matrix[i] = static_cast<double>(i + 1);
}
double mat_u[M * M];
double mat_b[M * M];
double mat_v[M * M];
math::internal::matrix_bidiagonalize(test_matrix, M, M, mat_u, mat_b, mat_v, 1e-14);
double groundtruth_mat_u[M * M];
groundtruth_mat_u[0] = 0.123091490979333;
groundtruth_mat_u[1] = 0.904534033733291;
groundtruth_mat_u[2] = -0.408248290463863;
groundtruth_mat_u[3] = 0.492365963917331;
groundtruth_mat_u[4] = 0.301511344577764;
groundtruth_mat_u[5] = 0.816496580927726;
groundtruth_mat_u[6] = 0.861640436855329;
groundtruth_mat_u[7] = -0.301511344577764;
groundtruth_mat_u[8] = -0.408248290463863;
double groundtruth_mat_b[M * M];
groundtruth_mat_b[0] = 8.124038404635961;
groundtruth_mat_b[1] = 14.659777996582722;
groundtruth_mat_b[2] = 0;
groundtruth_mat_b[3] = 0;
groundtruth_mat_b[4] = 1.959499950338375;
groundtruth_mat_b[5] = -0.501267429156329;
groundtruth_mat_b[6] = 0;
groundtruth_mat_b[7] = 0;
groundtruth_mat_b[8] = 0;
double groundtruth_mat_v[M * M];
groundtruth_mat_v[0] = 1;
groundtruth_mat_v[1] = 0;
groundtruth_mat_v[2] = 0;
groundtruth_mat_v[3] = 0;
groundtruth_mat_v[4] = 0.654930538417842;
groundtruth_mat_v[5] = 0.755689082789818;
groundtruth_mat_v[6] = 0;
groundtruth_mat_v[7] = 0.755689082789818;
groundtruth_mat_v[8] = -0.654930538417842;
for (int i = 0; i < M * M; ++i)
{
EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-14);
EXPECT_NEAR(groundtruth_mat_b[i], mat_b[i], 1e-14);
EXPECT_NEAR(groundtruth_mat_v[i], mat_v[i], 1e-14);
}
}
TEST(MatrixSVDTest, MatrixBidiagonalizationScalarTest)
{
double mat_a = 2;
double mat_u, mat_b, mat_v;
math::internal::matrix_bidiagonalize(&mat_a, 1, 1, &mat_u, &mat_b, &mat_v, 1e-14);
EXPECT_NEAR(1, mat_u, 1e-14);
EXPECT_NEAR(2, mat_b, 1e-14);
EXPECT_NEAR(1, mat_v, 1e-14);
}
TEST(MatrixSVDTest, MatrixSVDQuadraticSTest)
{
double mat_a[9];
for (int i = 0; i < 9; ++i)
{
mat_a[i] = static_cast<double>(i + 1);
}
double mat_u[9];
double mat_s[3];
double mat_v[9];
math::internal::matrix_gk_svd(mat_a, 3, 3, mat_u, mat_s, mat_v, 1e-6);
double groundtruth_mat_s[3];
groundtruth_mat_s[0] = 16.848103352614210;
groundtruth_mat_s[1] = 1.068369514554709;
groundtruth_mat_s[2] = 0;
EXPECT_NEAR(groundtruth_mat_s[0], mat_s[0], 1e-14);
EXPECT_NEAR(groundtruth_mat_s[1], mat_s[1], 1e-14);
EXPECT_NEAR(groundtruth_mat_s[2], mat_s[2], 1e-14);
}
TEST(MatrixSVDTest, MatrixSVDQuadraticUVTest)
{
double mat_a[9];
for (int i = 0; i < 9; ++i)
{
mat_a[i] = static_cast<double>(i + 1);
}
double mat_u[9];
double mat_s[3];
double mat_v[9];
math::internal::matrix_gk_svd(mat_a, 3, 3, mat_u, mat_s, mat_v, 1e-14);
double groundtruth_mat_u[9];
groundtruth_mat_u[0] = -0.214837238368396;
groundtruth_mat_u[1] = -0.887230688346370;
groundtruth_mat_u[2] = 0.408248290463863;
groundtruth_mat_u[3] = -0.520587389464737;
groundtruth_mat_u[4] = -0.249643952988298;
groundtruth_mat_u[5] = -0.816496580927726;
groundtruth_mat_u[6] = -0.826337540561078;
groundtruth_mat_u[7] = 0.387942782369775;
groundtruth_mat_u[8] = 0.408248290463863;
double groundtruth_mat_v[9];
groundtruth_mat_v[0] = -0.479671177877772;
groundtruth_mat_v[1] = 0.776690990321559;
groundtruth_mat_v[2] = -0.408248290463863;
groundtruth_mat_v[3] = -0.572367793972062;
groundtruth_mat_v[4] = 0.075686470104559;
groundtruth_mat_v[5] = 0.816496580927726;
groundtruth_mat_v[6] = -0.665064410066353;
groundtruth_mat_v[7] = -0.625318050112443;
groundtruth_mat_v[8] = -0.408248290463863;
for (int i = 0; i < 9; ++i)
{
EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-14);
EXPECT_NEAR(groundtruth_mat_v[i], mat_v[i], 1e-14);
}
}
TEST(MatrixSVDTest, MatrixSVDNonQuadraticFullTest)
{
double mat_a[20];
for (int i = 0; i < 20; ++i)
{
mat_a[i] = static_cast<double>(i + 1);
}
double mat_u[20];
double mat_s[4];
double mat_v[20];
math::internal::matrix_gk_svd(mat_a, 5, 4, mat_u, mat_s, mat_v, 1e-14);
double groundtruth_mat_s[4];
groundtruth_mat_s[0] = 53.520222492850067;
groundtruth_mat_s[1] = 2.363426393147627;
groundtruth_mat_s[2] = 0;
groundtruth_mat_s[3] = 0;
double groundtruth_mat_u[20];
groundtruth_mat_u[0] = -0.096547843444803;
groundtruth_mat_u[1] = -0.768556122821332;
groundtruth_mat_u[2] = 0.565028398052320;
groundtruth_mat_u[3] = 0.167888229103364;
groundtruth_mat_u[4] = -0.245515644353003;
groundtruth_mat_u[5] = -0.489614203611302;
groundtruth_mat_u[6] = -0.667776546677112;
groundtruth_mat_u[7] = -0.448708735648741;
groundtruth_mat_u[8] = -0.394483445261204;
groundtruth_mat_u[9] = -0.210672284401273;
groundtruth_mat_u[10] = -0.312183334193103;
groundtruth_mat_u[11] = 0.623816560842154;
groundtruth_mat_u[12] = -0.543451246169405;
groundtruth_mat_u[13] = 0.068269634808757;
groundtruth_mat_u[14] = 0.367582716208264;
groundtruth_mat_u[15] = -0.573059831151541;
groundtruth_mat_u[16] = -0.692419047077605;
groundtruth_mat_u[17] = 0.347211554018787;
groundtruth_mat_u[18] = 0.047348766609631;
groundtruth_mat_u[19] = 0.230063776854764;
double groundtruth_mat_v[20];
groundtruth_mat_v[0] = -0.443018843508167;
groundtruth_mat_v[1] = 0.709742421091395;
groundtruth_mat_v[2] = 0.547722557505176;
groundtruth_mat_v[3] = 0;
groundtruth_mat_v[4] = -0.479872524872618;
groundtruth_mat_v[5] = 0.264049919281154;
groundtruth_mat_v[6] = -0.730296743340218;
groundtruth_mat_v[7] = 0.408248290463862;
groundtruth_mat_v[8] = -0.516726206237069;
groundtruth_mat_v[9] = -0.181642582529112;
groundtruth_mat_v[10] = -0.182574185835057;
groundtruth_mat_v[11] = -0.816496580927726;
groundtruth_mat_v[12] = -0.553579887601520;
groundtruth_mat_v[13] = -0.627335084339378;
groundtruth_mat_v[14] = 0.365148371670102;
groundtruth_mat_v[15] = 0.408248290463864;
for (int i = 0; i < 4; ++i)
{
EXPECT_NEAR(groundtruth_mat_s[i], mat_s[i], 1e-13);
}
for (int i = 0; i < 20; ++i)
{
EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-13);
}
for (int i = 0; i < 16; ++i)
{
EXPECT_NEAR(std::abs(groundtruth_mat_v[i]), std::abs(mat_v[i]), 1e-13);
}
}
TEST(MatrixSVDTest, MatrixSVDNonQuadraticEconomyTest)
{
double mat_a[20];
for (int i = 0; i < 20; ++i)
{
mat_a[i] = static_cast<double>(i + 1);
}
double mat_u[20];
double mat_s[4];
double mat_v[20];
math::internal::matrix_r_svd(mat_a, 5, 4, mat_u, mat_s, mat_v, 1e-10);
double groundtruth_mat_s[4];
groundtruth_mat_s[0] = 53.520222492850067;
groundtruth_mat_s[1] = 2.363426393147627;
groundtruth_mat_s[2] = 0;
groundtruth_mat_s[3] = 0;
double groundtruth_mat_u[20];
groundtruth_mat_u[0] = -0.096547843444803;
groundtruth_mat_u[1] = -0.768556122821332;
groundtruth_mat_u[2] = 0.632455532033676;
groundtruth_mat_u[3] = 0;
groundtruth_mat_u[4] = -0.245515644353003;
groundtruth_mat_u[5] = -0.489614203611302;
groundtruth_mat_u[6] = -0.632455532033676;
groundtruth_mat_u[7] = 0.547722557505167;
groundtruth_mat_u[8] = -0.394483445261204;
groundtruth_mat_u[9] = -0.210672284401272;
groundtruth_mat_u[10] = -0.316227766016837;
groundtruth_mat_u[11] = -0.730296743340219;
groundtruth_mat_u[12] = -0.543451246169405;
groundtruth_mat_u[13] = 0.068269634808755;
groundtruth_mat_u[14] = -0.000000000000002;
groundtruth_mat_u[15] = -0.182574185835059;
groundtruth_mat_u[16] = -0.692419047077606;
groundtruth_mat_u[17] = 0.347211554018788;
groundtruth_mat_u[18] = 0.316227766016839;
groundtruth_mat_u[19] = 0.365148371670112;
double groundtruth_mat_v[16];
groundtruth_mat_v[0] = -0.443018843508167;
groundtruth_mat_v[1] = 0.709742421091395;
groundtruth_mat_v[2] = 0.547722557505176;
groundtruth_mat_v[3] = 0;
groundtruth_mat_v[4] = -0.479872524872618;
groundtruth_mat_v[5] = 0.264049919281154;
groundtruth_mat_v[6] = -0.730296743340218;
groundtruth_mat_v[7] = 0.408248290463862;
groundtruth_mat_v[8] = -0.516726206237069;
groundtruth_mat_v[9] = -0.181642582529112;
groundtruth_mat_v[10] = -0.182574185835057;
groundtruth_mat_v[11] = -0.816496580927726;
groundtruth_mat_v[12] = -0.553579887601520;
groundtruth_mat_v[13] = -0.627335084339378;
groundtruth_mat_v[14] = 0.365148371670102;
groundtruth_mat_v[15] = 0.408248290463864;
for (int i = 0; i < 4; ++i)
{
EXPECT_NEAR(groundtruth_mat_s[i], mat_s[i], 1e-10);
}
for (int i = 0; i < 20; ++i)
{
EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-10);
}
for (int i = 0; i < 16; ++i)
{
EXPECT_NEAR(std::abs(groundtruth_mat_v[i]), std::abs(mat_v[i]), 1e-10);
}
}
TEST(MatrixSVDTest, MatrixTransposeTest)
{
int mat_a[6];
mat_a[0] = 1;
mat_a[1] = 3;
mat_a[2] = 5;
mat_a[3] = 2;
mat_a[4] = 4;
mat_a[5] = 6;
math::matrix_transpose(mat_a, 2, 3);
int groundtruth_mat_a_t[6];
groundtruth_mat_a_t[0] = 1;
groundtruth_mat_a_t[1] = 2;
groundtruth_mat_a_t[2] = 3;
groundtruth_mat_a_t[3] = 4;
groundtruth_mat_a_t[4] = 5;
groundtruth_mat_a_t[5] = 6;
for (int i = 0; i < 6; ++i)
{
EXPECT_NEAR(groundtruth_mat_a_t[i], mat_a[i], 1e-14);
}
}
TEST(MatrixSVDTest, MatrixSVDUnderdeterminedTest)
{
double mat_a[2 * 3];
mat_a[0] = 1.0;
mat_a[1] = 3.0;
mat_a[2] = 5.0;
mat_a[3] = 2.0;
mat_a[4] = 4.0;
mat_a[5] = 6.0;
double mat_u[2 * 3];
double mat_s[3];
double mat_v[3 * 3];
math::matrix_svd(mat_a, 2, 3, mat_u, mat_s, mat_v, 1e-14);
double groundtruth_mat_u[2 * 3];
groundtruth_mat_u[0] = -0.619629483829340;
groundtruth_mat_u[1] = -0.784894453267053;
groundtruth_mat_u[2] = 0.0;
groundtruth_mat_u[3] = -0.784894453267052;
groundtruth_mat_u[4] = 0.619629483829340;
groundtruth_mat_u[5] = 0.0;
double groundtruth_mat_s[3];
groundtruth_mat_s[0] = 9.525518091565104;
groundtruth_mat_s[1] = 0.514300580658644;
groundtruth_mat_s[2] = 0.0;
double groundtruth_mat_v[3 * 3];
groundtruth_mat_v[0] = -0.229847696400071;
groundtruth_mat_v[1] = 0.883461017698525;
groundtruth_mat_v[2] = -0.408248290463863;
groundtruth_mat_v[3] = -0.524744818760294;
groundtruth_mat_v[4] = 0.240782492132546;
groundtruth_mat_v[5] = 0.816496580927726;
groundtruth_mat_v[6] = -0.819641941120516;
groundtruth_mat_v[7] = -0.401896033433432;
groundtruth_mat_v[8] = -0.408248290463863;
for (int i = 0; i < 6; ++i)
EXPECT_NEAR(groundtruth_mat_u[i], mat_u[i], 1e-13);
for (int i = 0; i < 3; ++i)
EXPECT_NEAR(groundtruth_mat_s[i], mat_s[i], 1e-13);
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(groundtruth_mat_v[i], mat_v[i], 1e-13);
}
TEST(MatrixSVDTest, TestLargeBeforeAfter)
{
const int rows = 100;
const int cols = 50;
double mat_a[rows * cols];
for (int i = 0; i < rows * cols; ++i)
mat_a[i] = static_cast<double>(i + 1);
/* Allocate results on heap to allow SVD of very big matrices. */
double* mat_u = new double[rows * rows];
double* vec_s = new double[cols];
double* mat_s = new double[cols * cols];
double* mat_v = new double[cols * cols];
math::matrix_svd(mat_a, rows, cols, mat_u, vec_s, mat_v, 1e-8);
math::matrix_transpose(mat_v, cols, cols);
std::fill(mat_s, mat_s + cols * cols, 0.0);
for (int i = 0; i < cols; ++i)
mat_s[i * cols + i] = vec_s[i];
double* multiply_temp = new double[cols * cols];
double* multiply_result = new double[rows * cols];
math::matrix_multiply(mat_s, cols, cols, mat_v, cols, multiply_temp);
math::matrix_multiply(mat_u, rows, cols, multiply_temp, cols,
multiply_result);
for (int i = 0; i < rows * cols; ++i)
EXPECT_NEAR(mat_a[i], multiply_result[i], 1e-7);
delete[] mat_u;
delete[] vec_s;
delete[] mat_s;
delete[] mat_v;
delete[] multiply_temp;
delete[] multiply_result;
}
TEST(MatrixSVDTest, BeforeAfter1)
{
math::Matrix<double, 2, 2> A;
A(0,0) = 1.0f; A(0,1) = 2.0f;
A(1,0) = 3.0f; A(1,1) = 4.0f;
math::Matrix<double, 2, 2> U;
math::Matrix<double, 2, 2> S;
math::Matrix<double, 2, 2> V;
math::matrix_svd(A, &U, &S, &V, 1e-12);
EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12));
EXPECT_GT(S(0,0), S(1,1));
}
TEST(MatrixSVDTest, BeforeAfter2)
{
double values[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
math::Matrix<double, 3, 2> A(values);
math::Matrix<double, 3, 2> U;
math::Matrix<double, 2, 2> S;
math::Matrix<double, 2, 2> V;
math::matrix_svd(A, &U, &S, &V, 1e-12);
EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12));
EXPECT_GT(S(0,0), S(1,1));
}
TEST(MatrixSVDTest, BeforeAfter3)
{
double values[] = {1.0, 2.0, 3.0, 4.0 };
math::Matrix<double, 2, 2> A(values);
math::Matrix<double, 2, 2> U;
math::Matrix<double, 2, 2> S(0.0);
math::Matrix<double, 2, 2> V;
math::matrix_svd<double>(*A, 2, 2, *U, *S, *V, 1e-12);
std::swap(S(0,1), S(1,1)); // Swap the eigenvalues into place.
EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12));
EXPECT_GT(S(0,0), S(1,1));
}
TEST(MatrixSVDTest, BeforeAfter4)
{
double values[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
math::Matrix<double, 3, 2> A(values);
math::Matrix<double, 3, 2> U;
math::Matrix<double, 2, 2> S(0.0);
math::Matrix<double, 2, 2> V;
math::matrix_svd(*A, 3, 2, *U, *S, *V, 1e-12);
std::swap(S(0,1), S(1,1)); // Swap the eigenvalues into place.
EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12));
EXPECT_GT(S(0,0), S(1,1));
}
TEST(MatrixSVDTest, BeforeAfter5)
{
math::Matrix<double, 3, 3> A;
A[0] = 1.0; A[1] = 0.0; A[2] = 1.0;
A[3] = 1.0; A[4] = 0.0; A[5] = 1.0;
A[6] = 1.0; A[7] = 0.0; A[8] = 1.0;
math::Matrix<double, 3, 3> U, S, V;
math::matrix_svd<double>(A, &U, &S, &V);
math::Matrix<double, 3, 3> X = U * S * V.transposed();
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i;
}
TEST(MatrixSVDTest, BeforeAfter6)
{
math::Matrix<double, 3, 3> A;
A[0] = 1.0; A[1] = 1.0; A[2] = 0.0;
A[3] = 1.0; A[4] = 1.0; A[5] = 0.0;
A[6] = 1.0; A[7] = 1.0; A[8] = 0.0;
math::Matrix<double, 3, 3> U, S, V;
math::matrix_svd<double>(A, &U, &S, &V);
math::Matrix<double, 3, 3> X = U * S * V.transposed();
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i;
}
TEST(MatrixSVDTest, BeforeAfter7)
{
math::Matrix<double, 3, 3> A;
A[0] = 0.0; A[1] = 1.0; A[2] = 1.0;
A[3] = 0.0; A[4] = 1.0; A[5] = 1.0;
A[6] = 0.0; A[7] = 1.0; A[8] = 1.0;
math::Matrix<double, 3, 3> U, S, V;
math::matrix_svd<double>(A, &U, &S, &V);
math::Matrix<double, 3, 3> X = U * S * V.transposed();
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i;
}
TEST(MatrixSVDTest, BeforeAfter8)
{
math::Matrix<double, 3, 3> A;
A[0] = 0.0; A[1] = 0.0; A[2] = 0.0;
A[3] = 1.0; A[4] = 1.0; A[5] = 1.0;
A[6] = 1.0; A[7] = 1.0; A[8] = 1.0;
math::Matrix<double, 3, 3> U, S, V;
math::matrix_svd<double>(A, &U, &S, &V);
math::Matrix<double, 3, 3> X = U * S * V.transposed();
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i;
}
TEST(MatrixSVDTest, BeforeAfter9)
{
math::Matrix<double, 3, 3> A;
A[0] = 1.0; A[1] = 1.0; A[2] = 1.0;
A[3] = 0.0; A[4] = 0.0; A[5] = 0.0;
A[6] = 1.0; A[7] = 1.0; A[8] = 1.0;
math::Matrix<double, 3, 3> U, S, V;
math::matrix_svd<double>(A, &U, &S, &V);
math::Matrix<double, 3, 3> X = U * S * V.transposed();
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i;
}
TEST(MatrixSVDTest, BeforeAfter10)
{
math::Matrix<double, 3, 3> A;
A[0] = 1.0; A[1] = 1.0; A[2] = 1.0;
A[3] = 1.0; A[4] = 1.0; A[5] = 1.0;
A[6] = 0.0; A[7] = 0.0; A[8] = 0.0;
math::Matrix<double, 3, 3> U, S, V;
math::matrix_svd<double>(A, &U, &S, &V);
math::Matrix<double, 3, 3> X = U * S * V.transposed();
for (int i = 0; i < 9; ++i)
EXPECT_NEAR(A[i], X[i], 1e-6) << " at " << i;
}
TEST(MatrixSVDTest, SortedEigenvalues)
{
double values[] = { 0.0697553, 0.949327, 0.525995, 0.0860558, 0.192214, 0.663227 };
math::Matrix<double, 3, 2> U, mat(values);
math::Matrix<double, 2, 2> S, V;
math::matrix_svd<double, 3, 2>(mat, &U, &S, &V, 1e-12);
EXPECT_GT(S(0,0), S(1,1));
}
#if 0
namespace
{
double
getrand (void)
{
return std::rand() / static_cast<double>(RAND_MAX);
}
} // namespace
TEST(MatrixSVDTest, ForbiddenRandomTestLargeMatrix)
{
#define TEST_ROWS 10000
#define TEST_COLS 10
std::srand(0);
math::Matrix<double, TEST_ROWS, TEST_COLS> A;
for (int i = 0; i < TEST_ROWS * TEST_COLS; ++i)
A[i] = getrand();
math::Matrix<double, TEST_ROWS, TEST_COLS> U;
math::Matrix<double, TEST_COLS, TEST_COLS> S;
math::Matrix<double, TEST_COLS, TEST_COLS> V;
math::matrix_svd(A, &U, &S, &V, 1e-10);
math::Matrix<double, TEST_ROWS, TEST_COLS> X = U * S * V.transposed();
for (int i = 0; i < TEST_ROWS * TEST_COLS; ++i)
EXPECT_NEAR(A[i], X[i], 1e-10);
}
// Note: Random is a bad thing in test cases! Don't do it!
TEST(MatrixSVDTest, ForbiddenRandomTest)
{
std::srand(0);
math::Matrix<double, 3, 2> A;
for (int i = 0; i < 10; ++i)
{
A(0,0) = getrand(); A(0,1) = getrand();
A(1,0) = getrand(); A(1,1) = getrand();
A(2,0) = getrand(); A(2,1) = getrand();
math::Matrix<double, 3, 2> U;
math::Matrix<double, 2, 2> S;
math::Matrix<double, 2, 2> V;
math::matrix_svd(A, &U, &S, &V, 1e-12);
EXPECT_TRUE(A.is_similar(U * S * V.transposed(), 1e-12));
EXPECT_GT(S(0,0), S(1,1));
}
}
#endif
TEST(MatrixSVDTest, TestPseudoInverse)
{
math::Matrix<double, 3, 2> mat;
mat[0] = 1.0; mat[1] = 2.0;
mat[2] = 3.0; mat[3] = 4.0;
mat[4] = 5.0; mat[5] = 6.0;
math::Matrix<double, 2, 3> pinv;
math::matrix_pseudo_inverse(mat, &pinv, 1e-10);
math::Matrix<double, 3, 2> mat2 = mat * pinv * mat;
for (int i = 0; i < 6; ++i)
EXPECT_NEAR(mat2[i], mat[i], 1e-14);
math::Matrix<double, 2, 3> pinv2 = pinv * mat * pinv;
for (int i = 0; i < 6; ++i)
EXPECT_NEAR(pinv2[i], pinv[i], 1e-14);
}
TEST(MatrixSVDTest, TestPseudoInverseGoldenData1)
{
double a_values[] = { 2, -4, 5, 6, 0, 3, 2, -4, 5, 6, 0, 3 };
double a_inv_values[] = { -2, 6, -2, 6, -5, 3, -5, 3, 4, 0, 4, 0 };
math::Matrix<double, 4, 3> A(a_values);
math::Matrix<double, 3, 4> Ainv(a_inv_values);
Ainv /= 72.0;
math::Matrix<double, 3, 4> result;
math::matrix_pseudo_inverse(A, &result, 1e-10);
for (int r = 0; r < 3; ++r)
for (int c = 0; c < 4; ++c)
EXPECT_NEAR(Ainv(r, c), result(r, c), 1e-16);
}
TEST(MatrixSVDTest, TestPseudoInverseGoldenData2)
{
double a_values[] = { 1, 1, 1, 1, 5, 7, 7, 9 };
double a_inv_values[] = { 2, -0.25, 0.25, 0, 0.25, 0, -1.5, 0.25 };
math::Matrix<double, 2, 4> A(a_values);
math::Matrix<double, 4, 2> Ainv(a_inv_values);
math::Matrix<double, 4, 2> result;
math::matrix_pseudo_inverse(A, &result, 1e-10);
for (int r = 0; r < 4; ++r)
for (int c = 0; c < 2; ++c)
EXPECT_NEAR(Ainv(r, c), result(r, c), 1e-13);
}
| 31.207709 | 88 | 0.625257 | lemony-fresh |
0af32920c4b1e61f869a61a1c3ad5ad66e4e69e9 | 2,272 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/client/remote/channels.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/client/remote/channels.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/client/remote/channels.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <functional>
#include <msw/std/memory.hpp>
#include <rubetek/remote_link/channel.hpp>
#include <rubetek/remote_link/channel_set.hpp>
namespace rubetek {
namespace client {
struct remote_channels
: remote_channel_set<unique_client_id::type>
{
typedef std::function<void(unique_channel_id_type, std::string const& ip, unique_client_id::const_reference, remote_link_interface<>*)> channel_open;
remote_channels
(
channel_open channel_open
, channel_close channel_close
, send_payload send_payload
)
: remote_channel_set<unique_client_id::type> ( channel_close, send_payload )
, channel_open_ ( channel_open )
{}
void on_open(unique_channel_id_type channel_id, unique_client_id::const_reference rem_id, std::string const& ip)
{
if (channel_by_remote_id_list_.find(rem_id) != channel_by_remote_id_list_.end())
{
logger_.error("channel to ", rem_id, " already exists");
}
else
{
logger_.info("insert new channel to ", rem_id, ", channel id: ", channel_id);
channel_by_remote_id_list_.insert(std::make_pair(rem_id, channel_id));
auto res = channels_.insert
(
std::make_pair
(
channel_id
, msw::make_unique<remote_channel<remote_id>>
(
rem_id
, [this, channel_id](msw::range<msw::byte const> payload)
{
send_payload_(channel_id, payload);
}
)
)
);
if (!res.second) throw std::runtime_error("adding channel fail");
if (!res.first->second) throw std::runtime_error("remote channel fail ptr");
channel_open_(channel_id, ip, rem_id, res.first->second.get());
}
}
private:
channel_open channel_open_;
};
}}
| 34.424242 | 157 | 0.524648 | yklishevich |
0af41eb9da67f85c0e1ccc80c993334d121b5ac7 | 1,158 | cpp | C++ | libraries/data/test/data_equation_test.cpp | gijskant/mcrl2-pmc | 9ea75755081b20623bc8fc7db27124d084e781fe | [
"BSL-1.0"
] | null | null | null | libraries/data/test/data_equation_test.cpp | gijskant/mcrl2-pmc | 9ea75755081b20623bc8fc7db27124d084e781fe | [
"BSL-1.0"
] | null | null | null | libraries/data/test/data_equation_test.cpp | gijskant/mcrl2-pmc | 9ea75755081b20623bc8fc7db27124d084e781fe | [
"BSL-1.0"
] | null | null | null | // Author(s): Jeroen Keiren
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file data_equation_test.cpp
/// \brief Basic regression test for data equations.
#include <iostream>
#include <boost/test/minimal.hpp>
#include "mcrl2/atermpp/container_utility.h"
#include "mcrl2/data/data_equation.h"
#include "mcrl2/data/basic_sort.h"
#include "mcrl2/data/variable.h"
#include "mcrl2/data/function_symbol.h"
#include "mcrl2/data/data_equation.h"
using namespace mcrl2;
using namespace mcrl2::data;
void data_equation_test()
{
basic_sort s("S");
data::function_symbol c("c", s);
data::function_symbol f("f", s);
variable x("x", s);
variable_list xl = { x };
data_equation e(xl, c, x, f);
BOOST_CHECK(e.variables() == xl);
BOOST_CHECK(e.condition() == c);
BOOST_CHECK(e.lhs() == x);
BOOST_CHECK(e.rhs() == f);
}
int test_main(int argc, char** argv)
{
data_equation_test();
return EXIT_SUCCESS;
}
| 24.125 | 61 | 0.708117 | gijskant |
0af46217160d042fa5933256ae741fc7571b84fc | 3,008 | cpp | C++ | jlp_x11plot/jlp_x11_utils.cpp | jlprieur/jlplib | 6073d7a7eb76d916662b1f8a4eb54f345cf7c772 | [
"MIT"
] | null | null | null | jlp_x11plot/jlp_x11_utils.cpp | jlprieur/jlplib | 6073d7a7eb76d916662b1f8a4eb54f345cf7c772 | [
"MIT"
] | null | null | null | jlp_x11plot/jlp_x11_utils.cpp | jlprieur/jlplib | 6073d7a7eb76d916662b1f8a4eb54f345cf7c772 | [
"MIT"
] | 1 | 2020-07-09T00:20:49.000Z | 2020-07-09T00:20:49.000Z | /*************************************************************************
* jlp_x11_utils.cpp
* Set of programs useful for the JLP_X11 and JLP_Dlg_X11 Classes
*
* JLP
* Version 17/11/2006
**************************************************************************/
#if JLP_USE_X11 /* New flag to disable X11 if necessary */
#include "jlp_x11_utils.h"
/*************************************************************
* Load fonts
* (You can check which fonts are available with the program "xfontsel")
*
* OUTPUT:
* **font_struct
************************************************************/
int JLP_LoadFonts(Display *display, XFontStruct **font_struct)
{
/* Fonts: look for courier-18, if not present use simply 9x15*/
*font_struct = XLoadQueryFont(display,"-*-courier-medium-r-*-*-14-*");
if(*font_struct == NULL) {
printf("LoadFonts/Error loading fonts: courier-medium 14 not found\n");
*font_struct = XLoadQueryFont(display,"9x15");
if(*font_struct == NULL) {
#ifdef DEBUG
printf("LoadFonts/Error loading fonts: courier and 9x15 not found\n");
#endif
*font_struct = XLoadQueryFont(display,"fixed");
if(*font_struct == NULL) {
printf("setup/Fatal error loading fonts: 'fixed' not found\n");
exit(-1);
}
}
}
return(0);
}
/**************************************************************
* Get value of the cell in the colormap corresponding
* to (r,g,b) value
*
* INPUT:
* r,g,b between 0 and 255
*
* OUTPUT:
* xcolor.pixel: full XColor structure of xcolor is initialized
***************************************************************/
int JLP_Xcolor_pixel(Display *display, Colormap& cmap,
unsigned long int &pixel, int r, int g, int b)
{
int status = 0;
XColor xcolor;
pixel = 0;
status = JLP_Xcolor(display, cmap, xcolor, r, g, b);
if(!status) pixel = xcolor.pixel;
return(status);
}
/**************************************************************
* Get value of the cell in the colormap corresponding
* to (r,g,b) value
*
* INPUT:
* r,g,b between 0 and 255
*
* OUTPUT:
* xcolor.pixel: full XColor structure of xcolor is initialized
***************************************************************/
int JLP_Xcolor(Display *display, Colormap& cmap, XColor &xcolor,
int r, int g, int b)
{
int status = 0;
int white_pixel;
white_pixel = WhitePixel(display,DefaultScreen(display));
xcolor.red = (white_pixel * r) / 255;
xcolor.green = (white_pixel * g) / 255;
xcolor.blue = (white_pixel * b) / 255;
xcolor.flags = DoRed | DoGreen | DoBlue;
/* XAllocColor returns the index of the (readonly) colorcell that contains the
* RGB value closest to the one required from the ASCII color data base
* (loaded in xcolor.pixel)
*/
if (XAllocColor(display, cmap, &xcolor) == 0) {
fprintf(stderr," JLP_Xcolor_pixel/Error: can't find color (%d,%d,%d)\n",
r, g, b);
status = -1;
}
return(status);
}
#endif /* End of JLP_USE_X11 */
| 30.383838 | 78 | 0.541888 | jlprieur |
0af9251f3b642a42f2e24744f3ffa6c4325343e8 | 1,510 | cpp | C++ | Endsems/Resources/test.cpp | rishitsaiya/CS314-OS-Lab | 8471bac1e88074bbad29bda58546ca84123129ad | [
"MIT"
] | null | null | null | Endsems/Resources/test.cpp | rishitsaiya/CS314-OS-Lab | 8471bac1e88074bbad29bda58546ca84123129ad | [
"MIT"
] | null | null | null | Endsems/Resources/test.cpp | rishitsaiya/CS314-OS-Lab | 8471bac1e88074bbad29bda58546ca84123129ad | [
"MIT"
] | 4 | 2022-01-21T14:31:00.000Z | 2022-03-20T06:45:09.000Z | #include <bits/stdc++.h>
#include <cmath>
#include <vector>
#include <chrono>
#include <thread>
#include <semaphore.h>
#include <unistd.h> //for fork()
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
sem_t s;
int Sum = 0;
void p1(key_t key, int create_pipe[2], int pid)
{
if(pid>0)
{
return;
}
int shmid = shmget(key, sizeof(int)*2, 0666 | IPC_CREAT);
int *x;
x = (int *)shmat(shmid, NULL, 0);
int to_give[1];
to_give[0]= x[0]*100;
write(create_pipe[1], to_give, sizeof(int));
}
void p2(key_t key, int create_pipe[2], int pid)
{
if(pid>0)
{
return;
}
int shmid = shmget(key, sizeof(int)*2, 0666 | IPC_CREAT);
int *x;
x = (int *)shmat(shmid, NULL, 0);
int to_take[1];
read(create_pipe[0], to_take, sizeof(int));
x[1] = 3*to_take[0];
}
int main()
{
sem_init(&s, 0, 1);
key_t key = ftok("shmfile",65);
int shmid = shmget(key, sizeof(int)*2, 0666 | IPC_CREAT);
int *x;
x = (int*)shmat(shmid, NULL, 0);
x[0] = 5;
printf("%d\n",x[0]);
int create_pipe[2];
int data;
data = pipe(create_pipe);
if (data == -1)
{
perror("pipe");
}
p2(key, create_pipe, fork());
p1(key, create_pipe, fork());
wait(NULL);
wait(NULL);
printf("%d-%d\n",x[0],x[1]);
shmdt(x);
shmctl(shmid,IPC_RMID,NULL);
} | 19.358974 | 62 | 0.563576 | rishitsaiya |
0af9479f817433d44d160f75ed399bbbfa17f9ad | 2,822 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionProductResourceTypeEnum.cpp | promethe42/ifcplusplus | 1c8b51b1f870f0107538dbea5eaa2755c81f5dca | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionProductResourceTypeEnum.cpp | promethe42/ifcplusplus | 1c8b51b1f870f0107538dbea5eaa2755c81f5dca | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionProductResourceTypeEnum.cpp | promethe42/ifcplusplus | 1c8b51b1f870f0107538dbea5eaa2755c81f5dca | [
"MIT"
] | null | null | null | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcConstructionProductResourceTypeEnum.h"
// TYPE IfcConstructionProductResourceTypeEnum = ENUMERATION OF (ASSEMBLY ,FORMWORK ,USERDEFINED ,NOTDEFINED);
IfcConstructionProductResourceTypeEnum::IfcConstructionProductResourceTypeEnum() {}
IfcConstructionProductResourceTypeEnum::~IfcConstructionProductResourceTypeEnum() {}
shared_ptr<BuildingObject> IfcConstructionProductResourceTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcConstructionProductResourceTypeEnum> copy_self( new IfcConstructionProductResourceTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcConstructionProductResourceTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCCONSTRUCTIONPRODUCTRESOURCETYPEENUM("; }
switch( m_enum )
{
case ENUM_ASSEMBLY: stream << ".ASSEMBLY."; break;
case ENUM_FORMWORK: stream << ".FORMWORK."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcConstructionProductResourceTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_ASSEMBLY: return L"ASSEMBLY";
case ENUM_FORMWORK: return L"FORMWORK";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcConstructionProductResourceTypeEnum> IfcConstructionProductResourceTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcConstructionProductResourceTypeEnum>(); }
else if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcConstructionProductResourceTypeEnum>(); }
shared_ptr<IfcConstructionProductResourceTypeEnum> type_object( new IfcConstructionProductResourceTypeEnum() );
if( boost::iequals( arg, L".ASSEMBLY." ) )
{
type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_ASSEMBLY;
}
else if( boost::iequals( arg, L".FORMWORK." ) )
{
type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_FORMWORK;
}
else if( boost::iequals( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_USERDEFINED;
}
else if( boost::iequals( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcConstructionProductResourceTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 42.119403 | 193 | 0.759391 | promethe42 |
0afa9f2e0b92e8c5ef0c5611659f923453a2314c | 1,116 | cpp | C++ | Easy/K-Foldable String/K-Foldable String.cpp | anishsingh42/CodeChef | 50f5c0438516210895e513bc4ee959b9d99ef647 | [
"Apache-2.0"
] | 127 | 2020-10-13T18:04:35.000Z | 2022-02-17T10:56:27.000Z | Easy/K-Foldable String/K-Foldable String.cpp | anishsingh42/CodeChef | 50f5c0438516210895e513bc4ee959b9d99ef647 | [
"Apache-2.0"
] | 132 | 2020-10-13T18:06:53.000Z | 2021-10-17T18:44:26.000Z | Easy/K-Foldable String/K-Foldable String.cpp | anishsingh42/CodeChef | 50f5c0438516210895e513bc4ee959b9d99ef647 | [
"Apache-2.0"
] | 364 | 2020-10-13T18:04:52.000Z | 2022-03-04T14:34:53.000Z | #include <bits/stdc++.h>
using namespace std;
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(NULL); \
cout.tie(NULL);
#define ll long long int
#define f(i, a, b) for (ll i = a; i < b; i++)
int main()
{
fast;
ll t;
cin >> t;
while (t--)
{
ll n, k;
cin >> n >> k;
string s;
cin >> s;
ll a = count(s.begin(), s.end(), '0');
ll b = count(s.begin(), s.end(), '1');
ll z = a / (n / k), y = b / (n / k);
if (n % k == 0 && a % (n / k) == 0 && b % (n / k) == 0)
{
vector<char> v;
f(i, 0, z) v.push_back('0');
f(i, 0, y) v.push_back('1');
ll h = n / k;
while (h > 0)
{
if (h > 0)
f(i, 0, k) cout << v[i];
h--;
if (h > 0)
for (ll i = k - 1; i >= 0; i--)
cout << v[i];
h--;
}
cout << endl;
}
else
cout << "IMPOSSIBLE\n";
}
} | 25.363636 | 63 | 0.312724 | anishsingh42 |
0afb5cf0b93d741a5fc9006a69257006ef471105 | 13,025 | hpp | C++ | packages/utility/core/src/Utility_Measurement.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/utility/core/src/Utility_Measurement.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/utility/core/src/Utility_Measurement.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file Utility_Measurement.hpp
//! \author Alex Robinson
//! \brief The measurement class declaration. This object is based of of the
//! measurement class in the boost::units examples
//!
//---------------------------------------------------------------------------//
#ifndef UTILITY_MEASUREMENT_HPP
#define UTILITY_MEASUREMENT_HPP
// Boost Includes
#include <boost/units/config.hpp>
#include <boost/units/operators.hpp>
#include <boost/typeof/typeof.hpp>
// Trilinos Includes
#include <Teuchos_ScalarTraits.hpp>
// FRENSIE Includes
#include "Utility_PrintableObject.hpp"
#include "Utility_ContractException.hpp"
namespace Utility{
/*! The measurement class
*
* This class wraps is meant to be used as any typical scalar type
* (e.g. double). It is designed to keep track of and propagate the
* uncertainty of a value (like one would with a measured quantity).
*/
template<typename T>
class Measurement : public PrintableObject
{
private:
// The scalar traits typedef
typedef Teuchos::ScalarTraits<T> ST;
public:
//! The typedef for this type
typedef Measurement<T> ThisType;
//! The typedef for the value type
typedef T ValueType;
//! Constructor
Measurement( const ValueType& value = ValueType(),
const ValueType& uncertainty = ValueType() );
//! Copy constructor
Measurement( const ThisType& other_measurement );
//! Destructor
~Measurement()
{ /* ... */ }
//! Print method
void print( std::ostream& os ) const;
//! Return the value of the measurement
const ValueType& getValue() const;
//! Return the uncertainty of the measurement
const ValueType& getUncertainty() const;
//! Return the relative uncertainty of the measurement
const ValueType getRelativeUncertainty() const;
//! Return the lower bound of the measurement
const ValueType getLowerBound() const;
//! Return the upper bound of the measurement
const ValueType getUpperBound() const;
//! Implicit conversion to value type
operator ValueType() const;
//! In-place addition operator
ThisType& operator+=( const ValueType& value );
//! In-place addition operator
ThisType& operator+=( const ThisType& other_measurement );
//! In-place subtraction operator
ThisType& operator-=( const ValueType& value );
//! In-place subtraction operator
ThisType& operator-=( const ThisType& other_measurement );
//! In-place multiplication operator
ThisType& operator*=( const ValueType& value );
//! In-place multiplication operator
ThisType& operator*=( const ThisType& other_measurement );
//! In-place division operator
ThisType& operator/=( const ValueType& value );
//! In-place division operator
ThisType& operator/=( const ThisType& other_measurement );
private:
// The measurement value
ValueType d_value;
// The measurement uncertainty
ValueType d_uncertainty;
};
//! Addition operator
template<typename T>
inline Measurement<T> operator+( T lhs, const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs, T(0) ) += rhs);
testNestedConditionsEnd(1);
}
//! Addition operator
template<typename T>
inline Measurement<T> operator+( const Measurement<T>& lhs, T rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) += Measurement<T>( rhs, T(0) ));
testNestedConditionsEnd(1);
}
//! Addition operator
template<typename T>
inline Measurement<T> operator+( const Measurement<T>& lhs,
const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) += rhs );
testNestedConditionsEnd(1);
}
//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( T lhs, const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs, T(0) ) -= rhs);
testNestedConditionsEnd(1);
}
//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( const Measurement<T>& lhs, T rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) -= Measurement<T>( rhs, T(0) ));
testNestedConditionsEnd(1);
}
//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( const Measurement<T>& lhs,
const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) -= rhs );
testNestedConditionsEnd(1);
}
//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( T lhs, const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs, T(0) ) *= rhs);
testNestedConditionsEnd(1);
}
//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( const Measurement<T>& lhs, T rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) *= Measurement<T>( rhs, T(0) ));
testNestedConditionsEnd(1);
}
//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( const Measurement<T>& lhs,
const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) *= rhs );
testNestedConditionsEnd(1);
}
//! Division operator
template<typename T>
inline Measurement<T> operator/( T lhs, const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
// Make sure nested conditions are met
return (Measurement<T>( lhs, T(0) ) /= rhs);
testNestedConditionsEnd(1);
}
//! Division operator
template<typename T>
inline Measurement<T> operator/( const Measurement<T>& lhs, T rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) /= Measurement<T>( rhs, T(0) ));
testNestedConditionsEnd(1);
}
//! Division operator
template<typename T>
inline Measurement<T> operator/( const Measurement<T>& lhs,
const Measurement<T>& rhs )
{
// Make sure nested conditions are met
testNestedConditionsBegin(1);
return (Measurement<T>( lhs ) /= rhs );
testNestedConditionsEnd(1);
}
//! Overload of sqrt for a measurement
template<typename T>
inline Measurement<T> sqrt( const Measurement<T>& x )
{
// Make sure the measurement is valid
testPrecondition( x.getValue() >= 0.0 );
const T new_value = std::sqrt( x.getValue() );
const T propagated_uncertainty = 0.5*(new_value/x.getValue())*
x.getUncertainty();
// Make sure reasonable values have been calculated
testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) );
testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf(
propagated_uncertainty ) );
return Measurement<T>( new_value, propagated_uncertainty );
}
//! Overload of pow for a measurement
template<typename T, typename ExponentType>
inline Measurement<T> pow( const Measurement<T>& x,
const ExponentType exponent )
{
const T new_value = std::pow( x.getValue(), exponent );
const T propagated_uncertainty = fabs(exponent*(new_value/x.getValue()))*
x.getUncertainty();
// Make sure reasonable values have been calculated
testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) );
testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf(
propagated_uncertainty ) );
testPostcondition( propagated_uncertainty >= 0.0 );
return Measurement<T>( new_value, propagated_uncertainty );
}
} // end Utility namespace
namespace boost{
namespace units{
//! Specialization of the boost::units::power_typeof_helper
template<typename Y, long N, long D>
struct power_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> >
{
typedef Utility::Measurement<typename power_typeof_helper<Y,static_rational<N,D> >::type> type;
static type value( const Utility::Measurement<Y>& x)
{
const static_rational<N,D> rational;
const Y rational_power = Y(rational.numerator())/Y(rational.denominator());
return Utility::pow( x, rational_power );
}
};
//! Specialization of the boost::units::root_typeof_helper
template<typename Y, long N, long D>
struct root_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> >
{
typedef Utility::Measurement<typename root_typeof_helper<Y,static_rational<N,D> >::type> type;
static type value( const Utility::Measurement<Y>& x )
{
const static_rational<N,D> rational;
// Compute D/N instead of N/D since we're interested in the root
const Y rational_power = Y(rational.denominator())/Y(rational.numerator());
return Utility::pow( x, rational_power );
}
};
} // end units namespace
} // end boost namespace
namespace Teuchos{
//! Partial specialization of Teuchos::ScalarTraits for the Measurement class
template<typename T>
struct ScalarTraits<Utility::Measurement<T> >
{
typedef Utility::Measurement<T> Measurement;
typedef T magnitudeType;
typedef typename Teuchos::ScalarTraits<T>::halfPrecision halfPrecision;
typedef typename Teuchos::ScalarTraits<T>::doublePrecision doublePrecision;
static const bool isComplex = Teuchos::ScalarTraits<T>::isComplex;
static const bool isOrdinal = Teuchos::ScalarTraits<T>::isOrdinal;
static const bool isComparable = Teuchos::ScalarTraits<T>::isComparable;
static const bool hasMachineParameters = Teuchos::ScalarTraits<T>::hasMachineParameters;
static inline magnitudeType eps() { return ScalarTraits<magnitudeType>::eps(); }
static inline magnitudeType sfmin() { return ScalarTraits<magnitudeType>::sfmin(); }
static inline magnitudeType base() { return ScalarTraits<magnitudeType>::base(); }
static inline magnitudeType prec() { return ScalarTraits<magnitudeType>::prec(); }
static inline magnitudeType t() { return ScalarTraits<magnitudeType>::t(); }
static inline magnitudeType rnd() { return ScalarTraits<magnitudeType>::rnd(); }
static inline magnitudeType emin() { return ScalarTraits<magnitudeType>::emin(); }
static inline magnitudeType rmin() { return ScalarTraits<magnitudeType>::rmin(); }
static inline magnitudeType emax() { return ScalarTraits<magnitudeType>::emax(); }
static inline magnitudeType rmax() { return ScalarTraits<magnitudeType>::rmax(); }
static inline magnitudeType magnitude(Measurement a) { return ScalarTraits<magnitudeType>::magnitude( a.getValue() ); }
static inline Measurement zero() { return Measurement( ScalarTraits<magnitudeType>::zero(), 0.0 ); }
static inline Measurement one() { return Measurement( ScalarTraits<magnitudeType>::zero(), 1.0 ); }
static inline Measurement conjugate(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::conjugate(a.getValue()), ScalarTraits<magnitudeType>::conjugate(a.getUncertainty()) ); }
static inline Measurement real(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::real(a.getValue()), ScalarTraits<magnitudeType>::real(a.getUncertainty()) ); }
static inline Measurement imag(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::imag(a.getValue()), ScalarTraits<magnitudeType>::imag(a.getUncertainty()) ); }
static inline Measurement nan() { return Measurement( ScalarTraits<magnitudeType>::nan(), ScalarTraits<magnitudeType>::nan() ); }
static inline bool isnaninf(Measurement a){ return ScalarTraits<magnitudeType>::isnaninf(a.getValue()) || ScalarTraits<magnitudeType>::isnaninf(a.getUncertainty()); }
static inline void seedrandom(unsigned int s) { ScalarTraits<magnitudeType>::seedrandom(s); }
static inline Measurement random() { return Measurement( ScalarTraits<magnitudeType>::random(), 0.0 ); }
static inline std::string name() { return std::string("Measurement<")+std::string(ScalarTraits<magnitudeType>::name())+std::string(">"); }
static inline Measurement squareroot(Measurement a) { return Utility::sqrt(a); }
static inline Measurement pow(Measurement a, Measurement b) { return Utility::pow( a, b.getValue() ); }
};
} // end Teuchos namespace
// Register the Measurement class with boost typeof for auto-like type
// deduction when used with the boost::units library
#if BOOST_UNITS_HAS_BOOST_TYPEOF
BOOST_TYPEOF_REGISTER_TEMPLATE(Utility::Measurement, 1)
#endif // end BOOST_UNITS_HAS_BOOST_TYPEOF
//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//
#include "Utility_Measurement_def.hpp"
//---------------------------------------------------------------------------//
#endif // end UTILITY_MEASUREMENT_HPP
//---------------------------------------------------------------------------//
// end Utility_Measurement.hpp
//---------------------------------------------------------------------------//
| 31.614078 | 191 | 0.697889 | lkersting |
0afd9f6b344a4f5e03e4ea8e94b8b1943af8cc90 | 1,741 | cc | C++ | zircon/kernel/lib/lockup_detector/tests/lockup_detector_tests.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | zircon/kernel/lib/lockup_detector/tests/lockup_detector_tests.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | null | null | null | zircon/kernel/lib/lockup_detector/tests/lockup_detector_tests.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 2 | 2020-10-25T01:13:49.000Z | 2020-10-26T02:32:13.000Z | // Copyright 2020 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#include <lib/lockup_detector.h>
#include <lib/unittest/unittest.h>
#include <fbl/auto_call.h>
#include <kernel/auto_preempt_disabler.h>
#include <kernel/percpu.h>
namespace {
bool NestedCriticalSectionTest() {
BEGIN_TEST;
AutoPreemptDisabler<APDInitialState::PREEMPT_DISABLED> ap_disabler;
// For the context of this test, use the maximum threshold to prevent the detector from "firing".
auto cleanup = fbl::MakeAutoCall(
[orig = lockup_get_threshold_ticks()]() { lockup_set_threshold_ticks(orig); });
lockup_set_threshold_ticks(INT64_MAX);
LockupDetectorState* state = &get_local_percpu()->lockup_detector_state;
EXPECT_EQ(0u, state->critical_section_depth);
EXPECT_EQ(0u, state->begin_ticks);
zx_ticks_t now = current_ticks();
lockup_begin();
EXPECT_EQ(1u, state->critical_section_depth);
const zx_ticks_t begin_ticks = state->begin_ticks;
EXPECT_GE(state->begin_ticks, now);
lockup_begin();
EXPECT_EQ(2u, state->critical_section_depth);
// No change because only the outer most critical section is tracked.
EXPECT_EQ(begin_ticks, state->begin_ticks);
lockup_end();
EXPECT_EQ(1u, state->critical_section_depth);
EXPECT_EQ(begin_ticks, state->begin_ticks);
lockup_end();
EXPECT_EQ(0u, state->critical_section_depth);
EXPECT_EQ(0, state->begin_ticks);
END_TEST;
}
} // namespace
UNITTEST_START_TESTCASE(lockup_detetcor_tests)
UNITTEST("nested_critical_section", NestedCriticalSectionTest)
UNITTEST_END_TESTCASE(lockup_detetcor_tests, "lockup_detector", "lockup_detector tests")
| 28.540984 | 99 | 0.768524 | EnderNightLord-ChromeBook |
0aff78f773299058aee13859794856368cd289d0 | 46,547 | cc | C++ | pik/external_image.cc | EwoutH/pik | e4b2c7ac71da9b35a9e45a107077f9d33a228012 | [
"MIT"
] | 855 | 2017-07-24T16:54:42.000Z | 2022-03-11T01:33:14.000Z | pik/external_image.cc | EwoutH/pik | e4b2c7ac71da9b35a9e45a107077f9d33a228012 | [
"MIT"
] | 59 | 2017-07-25T10:34:57.000Z | 2019-11-28T15:16:58.000Z | pik/external_image.cc | EwoutH/pik | e4b2c7ac71da9b35a9e45a107077f9d33a228012 | [
"MIT"
] | 60 | 2017-07-24T17:58:59.000Z | 2022-03-11T01:33:22.000Z | // Copyright 2018 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#include "pik/external_image.h"
#include <string.h>
#include "pik/byte_order.h"
#include "pik/cache_aligned.h"
namespace pik {
namespace {
#define PIK_EXT_VERBOSE 0
#if PIK_EXT_VERBOSE
// For printing RGB values at this X within each line.
constexpr size_t kX = 1;
#endif
// Encoding CodecInOut using other codecs requires format conversions to their
// "External" representation:
// IO -[1]-> Temp01 -[CMS]-> Temp01 -[2dt]-> External
// For External -> IO, we need only demux and rescale.
//
// "Temp01" and "Temp255" are interleaved and have 1 or 3 non-alpha channels.
// Alpha is included in External but not Temp because it is neither color-
// transformed nor included in Image3F.
// "IO" is Image3F (range [0, 255]) + ImageU alpha.
//
// "Temp01" is in range float [0, 1] as required by the CMS, but cannot
// losslessly represent 8-bit integer values [0, 255] due to floating point
// precision, which will reflect as a loss in Image3F which uses float range
// [0, 255] instead, which may cause effects on butteraugli score. Therefore,
// only use Temp01 if CMS transformation to different color space is required.
//
// "Temp255" is in range float [0, 255] and can losslessly represent 8-bit
// integer values [0, 255], but has floating point loss for 16-bit integer
// values [0, 65535]. The latter is not an issue however since Image3F uses
// float [0, 255] so has the same loss (so no butteraugli score effect), and
// the loss is gone when outputting to external integer again.
//
// Summary of formats:
// Name | Bits | Max | Channels | Layout | Alpha
// ---------+---------+----------+----------+-------------+---------
// External | 8,16,32 | 2^Bits-1 | 1,2,3,4 | Interleaved | Included
// Temp01 | 32 | 1 | 1,3 | Interleaved | Separate
// Temp255 | 32 | 255 | 1,3 | Interleaved | Separate
// IO | 32 | 255 | 3,4 | Planar | ImageU
// Number of external channels including alpha.
struct Channels1 {
static const char* Name() { return "1"; }
};
struct Channels2 {
static const char* Name() { return "2"; }
};
struct Channels3 {
static const char* Name() { return "3"; }
};
struct Channels4 {
static const char* Name() { return "4"; }
};
// Step 1: interleaved <-> planar and rescale [0, 1] <-> [0, 255]
struct Interleave {
static PIK_INLINE void Image3ToTemp01(Channels1, const size_t y,
const Image3F& image, const Rect& rect,
float* PIK_RESTRICT row_temp) {
const float* PIK_RESTRICT row_image1 = rect.ConstPlaneRow(image, 1, y);
for (size_t x = 0; x < rect.xsize(); ++x) {
row_temp[x] = row_image1[x] * (1.0f / 255);
}
}
static PIK_INLINE void Image3ToTemp01(Channels3, const size_t y,
const Image3F& image, const Rect& rect,
float* PIK_RESTRICT row_temp) {
const float* PIK_RESTRICT row_image0 = rect.ConstPlaneRow(image, 0, y);
const float* PIK_RESTRICT row_image1 = rect.ConstPlaneRow(image, 1, y);
const float* PIK_RESTRICT row_image2 = rect.ConstPlaneRow(image, 2, y);
for (size_t x = 0; x < rect.xsize(); ++x) {
row_temp[3 * x + 0] = row_image0[x] * (1.0f / 255);
row_temp[3 * x + 1] = row_image1[x] * (1.0f / 255);
row_temp[3 * x + 2] = row_image2[x] * (1.0f / 255);
}
}
// Same implementation for 2/4 because neither Image3 nor Temp have alpha.
static PIK_INLINE void Image3ToTemp01(Channels2, const size_t y,
const Image3F& image, const Rect& rect,
float* PIK_RESTRICT row_temp) {
Image3ToTemp01(Channels1(), y, image, rect, row_temp);
}
static PIK_INLINE void Image3ToTemp01(Channels4, const size_t y,
const Image3F& image, const Rect& rect,
float* PIK_RESTRICT row_temp) {
Image3ToTemp01(Channels3(), y, image, rect, row_temp);
}
static PIK_INLINE void Temp255ToImage3(Channels1,
const float* PIK_RESTRICT row_temp,
size_t y,
const Image3F* PIK_RESTRICT image) {
const size_t xsize = image->xsize();
float* PIK_RESTRICT row0 = const_cast<float*>(image->PlaneRow(0, y));
for (size_t x = 0; x < xsize; ++x) {
row0[x] = row_temp[x];
}
for (size_t c = 1; c < 3; ++c) {
float* PIK_RESTRICT row = const_cast<float*>(image->PlaneRow(c, y));
memcpy(row, row0, xsize * sizeof(float));
}
}
static PIK_INLINE void Temp255ToImage3(Channels3,
const float* PIK_RESTRICT row_temp,
size_t y,
const Image3F* PIK_RESTRICT image) {
float* PIK_RESTRICT row_image0 = const_cast<float*>(image->PlaneRow(0, y));
float* PIK_RESTRICT row_image1 = const_cast<float*>(image->PlaneRow(1, y));
float* PIK_RESTRICT row_image2 = const_cast<float*>(image->PlaneRow(2, y));
for (size_t x = 0; x < image->xsize(); ++x) {
row_image0[x] = row_temp[3 * x + 0];
row_image1[x] = row_temp[3 * x + 1];
row_image2[x] = row_temp[3 * x + 2];
}
}
static PIK_INLINE void Temp255ToImage3(Channels2,
const float* PIK_RESTRICT row_temp,
size_t y,
const Image3F* PIK_RESTRICT image) {
Temp255ToImage3(Channels1(), row_temp, y, image);
}
static PIK_INLINE void Temp255ToImage3(Channels4,
const float* PIK_RESTRICT row_temp,
size_t y,
const Image3F* PIK_RESTRICT image) {
Temp255ToImage3(Channels3(), row_temp, y, image);
}
};
// Step 2t: type conversion
// Same naming convention as Image: B=u8, U=u16, F=f32. kSize enables generic
// functions with Type and Order template arguments.
struct TypeB {
static const char* Name() { return "B"; }
static constexpr size_t kSize = 1;
static constexpr uint16_t kMaxAlpha = 0xFF;
};
struct TypeU {
static const char* Name() { return "U"; }
static constexpr size_t kSize = 2;
static constexpr uint16_t kMaxAlpha = 0xFFFF;
};
struct TypeF {
static const char* Name() { return "F"; }
static constexpr size_t kSize = 4;
static constexpr uint16_t kMaxAlpha = 0xFFFF;
};
// Load/stores float "sample" (gray/color) from/to u8/u16/float.
struct Sample {
template <class Order>
static PIK_INLINE float FromExternal(TypeB, const uint8_t* external) {
return *external;
}
template <class Order>
static PIK_INLINE float FromExternal(TypeU, const uint8_t* external) {
return Load16(Order(), external);
}
template <class Order>
static PIK_INLINE float FromExternal(TypeF, const uint8_t* external) {
const int32_t bits = Load32(Order(), external);
float sample;
memcpy(&sample, &bits, 4);
return sample;
}
template <class Order>
static PIK_INLINE void ToExternal(TypeB, const float sample,
uint8_t* external) {
PIK_ASSERT(0 <= sample && sample < 256);
// Don't need std::round since sample value is positive.
*external = static_cast<int>(sample + 0.5f);
}
template <class Order>
static PIK_INLINE void ToExternal(TypeU, const float sample,
uint8_t* external) {
PIK_ASSERT(0 <= sample && sample < 65536);
// Don't need std::round since sample value is positive.
Store16(Order(), static_cast<int>(sample + 0.5f), external);
}
template <class Order>
static PIK_INLINE void ToExternal(TypeF, const float sample,
uint8_t* external) {
int32_t bits;
memcpy(&bits, &sample, 4);
Store32(Order(), bits, external);
}
};
// Load/stores uint32_t (8/16-bit range) "alpha" from/to u8/u16. Lossless.
struct Alpha {
// Per-thread alpha statistics.
struct Stats {
// Bitwise AND of all alpha values; used to detect all-opaque alpha.
uint32_t and_bits = 0xFFFF;
// Bitwise OR; used to detect out of bounds values (i.e. > 255 for 8-bit).
uint32_t or_bits = 0;
// Prevents false sharing.
uint8_t pad[CacheAligned::kAlignment - sizeof(and_bits) - sizeof(or_bits)];
};
static PIK_INLINE uint32_t FromExternal(TypeB, OrderLE,
const uint8_t* external) {
return *external;
}
// Any larger type implies 16-bit alpha. NOTE: if TypeF, the alpha is smaller
// than other external values (subsequent bytes are uninitialized/ignored).
template <typename Type, class Order>
static PIK_INLINE uint32_t FromExternal(Type, Order,
const uint8_t* external) {
const uint32_t alpha = Load16(Order(), external);
return alpha;
}
static PIK_INLINE void ToExternal(TypeB, OrderLE, const uint32_t alpha,
uint8_t* external) {
PIK_ASSERT(alpha < 256);
*external = alpha;
}
// Any larger type implies 16-bit alpha. NOTE: if TypeF, the alpha is smaller
// than other external values (subsequent bytes are uninitialized/ignored).
template <typename Type, class Order>
static PIK_INLINE void ToExternal(Type, Order, const uint32_t alpha,
uint8_t* external) {
Store16(Order(), alpha, external);
}
};
// Step 2d: demux external into separate (type-converted) color and alpha.
// Supports Temp01 and Temp255, the Cast decides this.
struct Demux {
// 1 plane - copy all.
template <class Type, class Order, class Cast>
static PIK_INLINE void ExternalToTemp(Type type, Order order, Channels1,
const size_t xsize,
const uint8_t* external,
const Cast cast,
float* PIK_RESTRICT row_temp) {
for (size_t x = 0; x < xsize; ++x) {
const float rounded =
Sample::FromExternal<Order>(type, external + x * Type::kSize);
row_temp[x] = cast.FromExternal(rounded, 0);
}
}
template <class Type, class Order, class Cast>
static PIK_INLINE void TempToExternal(Type type, Order order, Channels1,
const size_t xsize,
const float* PIK_RESTRICT row_temp,
const Cast cast,
uint8_t* row_external) {
for (size_t x = 0; x < xsize; ++x) {
const float sample = cast.FromTemp(row_temp[x], 0);
Sample::ToExternal<Order>(type, sample, row_external + x * Type::kSize);
}
}
// 2 planes - ignore alpha.
template <class Type, class Order, class Cast>
static PIK_INLINE void ExternalToTemp(Type type, Order order, Channels2,
const size_t xsize,
const uint8_t* external,
const Cast cast,
float* PIK_RESTRICT row_temp) {
for (size_t x = 0; x < xsize; ++x) {
const float rounded = Sample::FromExternal<Order>(
type, external + (2 * x + 0) * Type::kSize);
row_temp[x] = cast.FromExternal(rounded, 0);
}
}
template <class Type, class Order, class Cast>
static PIK_INLINE void TempToExternal(Type type, Order order, Channels2,
const size_t xsize,
const float* PIK_RESTRICT row_temp,
const Cast cast,
uint8_t* row_external) {
for (size_t x = 0; x < xsize; ++x) {
const float sample = cast.FromTemp(row_temp[x], 0);
Sample::ToExternal<Order>(type, sample,
row_external + (2 * x + 0) * Type::kSize);
}
}
// 3 planes - copy all.
template <class Type, class Order, class Cast>
static PIK_INLINE void ExternalToTemp(Type type, Order order, Channels3,
const size_t xsize,
const uint8_t* external,
const Cast cast,
float* PIK_RESTRICT row_temp) {
for (size_t x = 0; x < xsize; ++x) {
const float rounded0 = Sample::FromExternal<Order>(
type, external + (3 * x + 0) * Type::kSize);
const float rounded1 = Sample::FromExternal<Order>(
type, external + (3 * x + 1) * Type::kSize);
const float rounded2 = Sample::FromExternal<Order>(
type, external + (3 * x + 2) * Type::kSize);
row_temp[3 * x + 0] = cast.FromExternal(rounded0, 0);
row_temp[3 * x + 1] = cast.FromExternal(rounded1, 1);
row_temp[3 * x + 2] = cast.FromExternal(rounded2, 2);
}
}
template <class Type, class Order, class Cast>
static PIK_INLINE void TempToExternal(Type type, Order order, Channels3,
const size_t xsize,
const float* PIK_RESTRICT row_temp,
const Cast cast,
uint8_t* row_external) {
for (size_t x = 0; x < xsize; ++x) {
const float sample0 = cast.FromTemp(row_temp[3 * x + 0], 0);
const float sample1 = cast.FromTemp(row_temp[3 * x + 1], 1);
const float sample2 = cast.FromTemp(row_temp[3 * x + 2], 2);
Sample::ToExternal<Order>(type, sample0,
row_external + (3 * x + 0) * Type::kSize);
Sample::ToExternal<Order>(type, sample1,
row_external + (3 * x + 1) * Type::kSize);
Sample::ToExternal<Order>(type, sample2,
row_external + (3 * x + 2) * Type::kSize);
}
}
// 4 planes - ignore alpha.
template <class Type, class Order, class Cast>
static PIK_INLINE void ExternalToTemp(Type type, Order order, Channels4,
const size_t xsize,
const uint8_t* external,
const Cast cast,
float* PIK_RESTRICT row_temp) {
for (size_t x = 0; x < xsize; ++x) {
const float rounded0 = Sample::FromExternal<Order>(
type, external + (4 * x + 0) * Type::kSize);
const float rounded1 = Sample::FromExternal<Order>(
type, external + (4 * x + 1) * Type::kSize);
const float rounded2 = Sample::FromExternal<Order>(
type, external + (4 * x + 2) * Type::kSize);
row_temp[3 * x + 0] = cast.FromExternal(rounded0, 0);
row_temp[3 * x + 1] = cast.FromExternal(rounded1, 1);
row_temp[3 * x + 2] = cast.FromExternal(rounded2, 2);
}
}
template <class Type, class Order, class Cast>
static PIK_INLINE void TempToExternal(Type type, Order order, Channels4,
const size_t xsize,
const float* PIK_RESTRICT row_temp,
const Cast cast,
uint8_t* row_external) {
for (size_t x = 0; x < xsize; ++x) {
const float sample0 = cast.FromTemp(row_temp[3 * x + 0], 0);
const float sample1 = cast.FromTemp(row_temp[3 * x + 1], 1);
const float sample2 = cast.FromTemp(row_temp[3 * x + 2], 2);
Sample::ToExternal<Order>(type, sample0,
row_external + (4 * x + 0) * Type::kSize);
Sample::ToExternal<Order>(type, sample1,
row_external + (4 * x + 1) * Type::kSize);
Sample::ToExternal<Order>(type, sample2,
row_external + (4 * x + 2) * Type::kSize);
}
}
// Gray only, no alpha.
template <class Type, class Order>
static PIK_INLINE void ExternalToAlpha(Type type, Order order, Channels1,
const size_t xsize,
const uint8_t* external,
uint16_t* PIK_RESTRICT row_alpha,
const size_t thread,
std::vector<Alpha::Stats>* stats) {}
template <class Type, class Order>
static PIK_INLINE void AlphaToExternal(Type type, Order order, Channels1,
const size_t xsize,
const uint16_t* PIK_RESTRICT row_alpha,
uint8_t* row_external) {}
// Gray + alpha.
template <class Type, class Order>
static PIK_INLINE void ExternalToAlpha(Type type, Order order, Channels2,
const size_t xsize,
const uint8_t* external,
uint16_t* PIK_RESTRICT row_alpha,
const size_t thread,
std::vector<Alpha::Stats>* stats) {
if (row_alpha == nullptr) return;
uint32_t and_bits = 0xFFFF;
uint32_t or_bits = 0;
for (size_t x = 0; x < xsize; ++x) {
const uint32_t alpha = Alpha::FromExternal(
type, order, external + (2 * x + 1) * Type::kSize);
and_bits &= alpha;
or_bits |= alpha;
row_alpha[x] = alpha;
}
(*stats)[thread].and_bits &= and_bits;
(*stats)[thread].or_bits |= or_bits;
}
template <class Type, class Order>
static PIK_INLINE void AlphaToExternal(Type type, Order order, Channels2,
const size_t xsize,
const uint16_t* PIK_RESTRICT row_alpha,
uint8_t* row_external) {
if (row_alpha == nullptr) {
for (size_t x = 0; x < xsize; ++x) {
Alpha::ToExternal(type, order, type.kMaxAlpha,
row_external + (2 * x + 1) * Type::kSize);
}
} else {
for (size_t x = 0; x < xsize; ++x) {
Alpha::ToExternal(type, order, row_alpha[x],
row_external + (2 * x + 1) * Type::kSize);
}
}
}
// RGB only, no alpha.
template <class Type, class Order>
static PIK_INLINE void ExternalToAlpha(Type type, Order order, Channels3,
const size_t xsize,
const uint8_t* external,
uint16_t* PIK_RESTRICT row_alpha,
const size_t thread,
std::vector<Alpha::Stats>* stats) {}
template <class Type, class Order>
static PIK_INLINE void AlphaToExternal(Type type, Order order, Channels3,
const size_t xsize,
const uint16_t* PIK_RESTRICT row_alpha,
uint8_t* row_external) {}
// RGBA.
template <class Type, class Order>
static PIK_INLINE void ExternalToAlpha(Type type, Order order, Channels4,
const size_t xsize,
const uint8_t* external,
uint16_t* PIK_RESTRICT row_alpha,
const size_t thread,
std::vector<Alpha::Stats>* stats) {
if (row_alpha == nullptr) return;
uint32_t and_bits = 0xFFFF;
uint32_t or_bits = 0;
for (size_t x = 0; x < xsize; ++x) {
const uint32_t alpha = Alpha::FromExternal(
type, order, external + (4 * x + 3) * Type::kSize);
and_bits &= alpha;
or_bits |= alpha;
row_alpha[x] = alpha;
}
(*stats)[thread].and_bits &= and_bits;
(*stats)[thread].or_bits |= or_bits;
}
template <class Type, class Order>
static PIK_INLINE void AlphaToExternal(Type type, Order order, Channels4,
const size_t xsize,
const uint16_t* PIK_RESTRICT row_alpha,
uint8_t* row_external) {
if (row_alpha == nullptr) {
for (size_t x = 0; x < xsize; ++x) {
Alpha::ToExternal(type, order, type.kMaxAlpha,
row_external + (4 * x + 3) * Type::kSize);
}
} else {
for (size_t x = 0; x < xsize; ++x) {
Alpha::ToExternal(type, order, row_alpha[x],
row_external + (4 * x + 3) * Type::kSize);
}
}
}
};
// Used to select the Transformer::DoRow overload to call.
struct ToExternal1 {}; // first phase: store to temp and compute min/max.
struct ToExternal2 {}; // second phase: rescale temp to external.
struct ToExternal {}; // single-pass, only usable with CastClip.
// For ToExternal - assumes known/static extents of temp values.
struct ExtentsStatic {};
// For ToExternal1 - computes extents of temp values.
class ExtentsDynamic {
public:
ExtentsDynamic(const size_t xsize, const size_t ysize,
const size_t num_threads, const ColorEncoding& c_desired)
: temp_intervals_(c_desired.Channels()) {
// Store all temp pixels here, convert to external in a second phase after
// Finalize computes ChannelIntervals from min_max_.
temp_ = ImageF(xsize * temp_intervals_, ysize);
min_max_.resize(num_threads);
}
float* PIK_RESTRICT RowTemp(const size_t y) { return temp_.Row(y); }
// Row size is obtained from temp_. NOTE: clamps temp values to kMax.
PIK_INLINE void Update(const size_t thread, float* PIK_RESTRICT row_temp) {
// row_temp is interleaved - keep track of current channel.
size_t c = 0;
for (size_t i = 0; i < temp_.xsize(); ++i, ++c) {
if (c == temp_intervals_) c = 0;
if (row_temp[i] > min_max_[thread].max[c]) {
if (row_temp[i] > kMax) row_temp[i] = kMax;
min_max_[thread].max[c] = row_temp[i];
}
if (row_temp[i] < min_max_[thread].min[c]) {
if (row_temp[i] < -kMax) row_temp[i] = -kMax;
min_max_[thread].min[c] = row_temp[i];
}
}
}
void Finalize(CodecIntervals* temp_intervals) const {
// Any other ChannelInterval remains default-initialized.
for (size_t c = 0; c < temp_intervals_; ++c) {
float min = min_max_[0].min[c];
float max = min_max_[0].max[c];
for (size_t i = 1; i < min_max_.size(); ++i) {
min = std::min(min, min_max_[i].min[c]);
max = std::max(max, min_max_[i].max[c]);
}
// Update ensured these are clamped.
PIK_ASSERT(-kMax <= min && min <= max && max <= kMax);
(*temp_intervals)[c] = CodecInterval(min, max);
}
}
private:
// Larger values are probably invalid, so clamp to preserve some precision.
static constexpr float kMax = 1E10;
struct MinMax {
MinMax() {
for (size_t c = 0; c < 4; ++c) {
min[c] = kMax;
max[c] = -kMax;
}
}
float min[4];
float max[4];
// Prevents false sharing.
uint8_t pad[CacheAligned::kAlignment - sizeof(min) - sizeof(max)];
};
const size_t temp_intervals_;
ImageF temp_;
std::vector<MinMax> min_max_;
};
// For ToExternal1, which updates ExtentsDynamic without casting.
struct CastUnused {};
// Returns range of valid values for all channel.
CodecInterval GetInterval(const size_t bits_per_sample) {
if (bits_per_sample == 32) {
// This ensures ConvertImage produces an image with the same [0, 255]
// range as its input, but increases round trip error by ~2x vs [0, 1].
return CodecInterval(0.0f, 255.0f);
} else {
const float max = (1U << bits_per_sample) - 1;
return CodecInterval(0, max);
}
}
// Lossless conversion between [0, 1] and [min, min+width]. Width is 1 or
// > 1 ("unbounded", useful for round trip testing). This is used to scale to
// the external type and back to the arbitrary interval.
class CastRescale01 {
public:
static const char* Name() { return "Rescale01"; }
CastRescale01(const CodecIntervals& temp_intervals,
const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
temp_min_[c] = temp_intervals[c].min;
temp_mul_[c] = ext_interval.width / temp_intervals[c].width;
external_min_[c] = ext_interval.min;
external_mul_[c] = temp_intervals[c].width / ext_interval.width;
}
#if PIK_EXT_VERBOSE >= 2
printf("CastRescale01 min %f width %f %f\n", temp_intervals[0].min,
temp_intervals[0].width, ext_interval.width);
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
return (external - external_min_[c]) * external_mul_[c] + temp_min_[c];
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return (temp - temp_min_[c]) * temp_mul_[c] + external_min_[c];
}
private:
float temp_min_[4];
float temp_mul_[4];
float external_min_[4];
float external_mul_[4];
};
// Lossless conversion between [0, 255] and [min, min+width]. Width is 255 or
// > 255 ("unbounded", useful for round trip testing). This is used to scale to
// the external type and back to the arbitrary interval.
// NOTE: this rescaler exists to make CopyTo match the convention of
// "temp_intervals" used by the color converting constructor. In the external to
// IO case without color conversion, one normally does not use this parameter.
class CastRescale255 {
public:
static const char* Name() { return "Rescale255"; }
CastRescale255(const CodecIntervals& temp_intervals,
const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
temp_min_[c] = 255.0f * temp_intervals[c].min;
temp_mul_[c] =
ext_interval.width / temp_intervals[c].width * (1.0f / 255);
external_min_[c] = ext_interval.min * (1.0f / 255);
external_mul_[c] = 255.0f * temp_intervals[c].width / ext_interval.width;
}
#if PIK_EXT_VERBOSE >= 2
printf("CastRescale255 min %f width %f %f\n", temp_intervals[0].min,
temp_intervals[0].width, ext_interval.width);
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
return (external - external_min_[c]) * external_mul_[c] + temp_min_[c];
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return (temp - temp_min_[c]) * temp_mul_[c] + external_min_[c];
}
private:
float temp_min_[4];
float temp_mul_[4];
float external_min_[4];
float external_mul_[4];
};
// Converts between [0, 1] and the external type's range. Lossy because values
// outside [0, 1] are clamped - this is necessary for codecs that are not able
// to store min/width metadata.
class CastClip01 {
public:
static const char* Name() { return "Clip01"; }
CastClip01(const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
temp_mul_[c] = ext_interval.width;
external_min_[c] = ext_interval.min;
external_mul_[c] = 1.0f / ext_interval.width;
}
#if PIK_EXT_VERBOSE >= 2
printf("CastClip01 width %f\n", ext_interval.width);
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
const float temp01 = (external - external_min_[c]) * external_mul_[c];
return temp01;
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return Clamp01(temp) * temp_mul_[c] + external_min_[c];
}
private:
static PIK_INLINE float Clamp01(const float temp) {
return std::min(std::max(0.0f, temp), 1.0f);
}
float temp_mul_[4];
float external_min_[4];
float external_mul_[4];
};
struct CastFloat {
static const char* Name() { return "Float"; }
CastFloat(const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
PIK_CHECK(ext_interval.min == 0.0f);
PIK_CHECK(ext_interval.width == 255.0f);
}
#if PIK_EXT_VERBOSE >= 2
printf("CastFloat\n");
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
const float temp01 = external * (1.0f / 255);
return temp01;
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return temp * 255.0f;
}
};
// Converts between [0, 255] and the external type's range. Lossy because values
// outside [0, 255] are clamped - this is necessary for codecs that are not able
// to store min/width metadata.
class CastClip255 {
public:
static const char* Name() { return "Clip255"; }
CastClip255(const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
temp_mul_[c] = ext_interval.width;
external_min_[c] = ext_interval.min;
external_mul_[c] = 255.0f / ext_interval.width;
}
#if PIK_EXT_VERBOSE >= 2
printf("CastClip255 width %f\n", ext_interval.width);
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
const float temp255 = (external - external_min_[c]) * external_mul_[c];
return temp255;
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return Clamp255(temp) * temp_mul_[c] + external_min_[c];
}
private:
static PIK_INLINE float Clamp255(const float temp) {
return std::min(std::max(0.0f, temp), 255.0f);
}
float temp_mul_[4];
float external_min_[4];
float external_mul_[4];
};
struct CastFloat01 {
static const char* Name() { return "Float01"; }
CastFloat01(const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
PIK_CHECK(ext_interval.min == 0.0f);
PIK_CHECK(ext_interval.width == 255.0f);
}
#if PIK_EXT_VERBOSE >= 2
printf("CastFloat01\n");
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
const float temp01 = external * (1.0f / 255);
return temp01;
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return temp * 255.0f;
}
};
// No-op
struct CastFloat255 {
static const char* Name() { return "Float255"; }
CastFloat255(const CodecInterval ext_interval) {
for (size_t c = 0; c < 4; ++c) {
PIK_CHECK(ext_interval.min == 0.0f);
PIK_CHECK(ext_interval.width == 255.0f);
}
#if PIK_EXT_VERBOSE >= 2
printf("CastFloat255\n");
#endif
}
PIK_INLINE float FromExternal(const float external, const size_t c) const {
return external;
}
PIK_INLINE float FromTemp(const float temp, const size_t c) const {
return temp;
}
};
// Multithreaded color space transform from IO to ExternalImage.
class Transformer {
public:
Transformer(ThreadPool* pool, const Image3F& color, const Rect& rect,
const bool has_alpha, const ImageU* alpha,
ExternalImage* external)
: pool_(pool),
color_(color),
rect_(rect),
alpha_(alpha),
external_(external),
want_alpha_(has_alpha && external->HasAlpha()) {
PIK_ASSERT(rect.IsInside(color));
PIK_ASSERT(SameSize(rect, *external));
}
// Can fail => separate from ctor.
Status Init(const ColorEncoding& c_src, const ColorEncoding& c_dst) {
#if PIK_EXT_VERBOSE >= 1
printf("%s->%s\n", Description(c_src).c_str(), Description(c_dst).c_str());
#endif
return transform_.Init(c_src, c_dst, rect_.xsize(), NumThreads(pool_));
}
// Converts in the specified direction (To*).
template <class To, class Extent, class Cast>
Status Run(Extent* extents, const Cast& cast) {
const size_t bytes = DivCeil(external_->BitsPerSample(), kBitsPerByte);
const bool big_endian = external_->BigEndian();
if (bytes == 1) {
DispatchType<To, TypeB, OrderLE>(extents, cast);
} else if (bytes == 2 && big_endian) {
DispatchType<To, TypeU, OrderBE>(extents, cast);
} else if (bytes == 2) {
DispatchType<To, TypeU, OrderLE>(extents, cast);
} else if (bytes == 4 && big_endian) {
DispatchType<To, TypeF, OrderBE>(extents, cast);
} else if (bytes == 4) {
DispatchType<To, TypeF, OrderLE>(extents, cast);
} else {
return PIK_FAILURE("Unsupported BitsPerSample");
}
return true;
}
private:
// First pass: only needed for ExtentsDynamic/CastUnused.
template <class Type, class Order, class Channels>
PIK_INLINE void DoRow(ToExternal1, ExtentsDynamic* extents, const CastUnused,
const size_t y, const size_t thread) {
float* PIK_RESTRICT row_temp = extents->RowTemp(y);
Interleave::Image3ToTemp01(Channels(), y, color_, rect_, row_temp);
#if PIK_EXT_VERBOSE
const float in0 = row_temp[3 * kX + 0], in1 = row_temp[3 * kX + 1];
const float in2 = row_temp[3 * kX + 2];
#endif
transform_.Run(thread, row_temp, row_temp);
#if PIK_EXT_VERBOSE
printf("ToExt1: in %.4f %.4f %.4f; xform %.4f %.4f %.4f\n", in0, in1, in2,
row_temp[3 * kX + 0], row_temp[3 * kX + 1], row_temp[3 * kX + 2]);
#endif
extents->Update(thread, row_temp);
}
// Second pass: only needed for ExtentsDynamic/CastRescale.
template <class Type, class Order, class Channels>
PIK_INLINE void DoRow(ToExternal2, ExtentsDynamic* extents,
const CastRescale01& cast, const size_t y,
const size_t thread) {
const float* PIK_RESTRICT row_temp = extents->RowTemp(y);
uint8_t* PIK_RESTRICT row_external = external_->Row(y);
Demux::TempToExternal(Type(), Order(), Channels(), rect_.xsize(), row_temp,
cast, row_external);
#if PIK_EXT_VERBOSE
printf("ToExt2: ext %3d %3d %3d\n", row_external[3 * kX + 0],
row_external[3 * kX + 1], row_external[3 * kX + 2]);
#endif
const uint16_t* PIK_RESTRICT row_alpha =
want_alpha_ ? alpha_->ConstRow(y) : nullptr;
Demux::AlphaToExternal(Type(), Order(), Channels(), rect_.xsize(),
row_alpha, row_external);
}
// Single-pass: only works for ExtentsStatic.
template <class Type, class Order, class Channels, class Cast>
PIK_INLINE void DoRow(ToExternal, ExtentsStatic*, const Cast& cast,
const size_t y, const size_t thread) {
float* PIK_RESTRICT row_temp = transform_.BufDst(thread);
Interleave::Image3ToTemp01(Channels(), y, color_, rect_, row_temp);
#if PIK_EXT_VERBOSE
// Save inputs for printing before in-place transform overwrites them.
const float in0 = row_temp[3 * kX + 0];
const float in1 = row_temp[3 * kX + 1];
const float in2 = row_temp[3 * kX + 2];
#endif
transform_.Run(thread, row_temp, row_temp);
uint8_t* PIK_RESTRICT row_external = external_->Row(y);
Demux::TempToExternal(Type(), Order(), Channels(), rect_.xsize(), row_temp,
cast, row_external);
#if PIK_EXT_VERBOSE
const float tmp0 = row_temp[3 * kX + 0];
const float tmp1 = row_temp[3 * kX + 1];
const float tmp2 = row_temp[3 * kX + 2];
// Convert back so we can print the external values
Demux::ExternalToTemp(Type(), Order(), Channels(), rect_.xsize(),
row_external, cast, row_temp);
printf("ToExt(%s%s %s): tmp %.4f %.4f %.4f|%.4f %.4f %.4f|%.4f %.4f %.4f\n",
Channels::Name(), Type::Name(), Cast::Name(), in0, in1, in2, tmp0,
tmp1, tmp2, row_temp[3 * kX + 0], row_temp[3 * kX + 1],
row_temp[3 * kX + 2]);
#endif
const uint16_t* PIK_RESTRICT row_alpha =
want_alpha_ ? alpha_->ConstRow(y) : nullptr;
Demux::AlphaToExternal(Type(), Order(), Channels(), rect_.xsize(),
row_alpha, row_external);
}
// Closure callable by ThreadPool.
template <class To, class Type, class Order, class Channels, class Extent,
class Cast>
class Bind {
public:
explicit Bind(Transformer* converter, Extent* extents, const Cast& cast)
: xform_(converter), extents_(extents), cast_(cast) {}
PIK_INLINE void operator()(const int task, const int thread) const {
xform_->DoRow<Type, Order, Channels>(To(), extents_, cast_, task, thread);
}
private:
Transformer* xform_; // not owned
Extent* extents_; // not owned
const Cast cast_;
};
template <class To, class Type, class Order, class Channels, class Extent,
class Cast>
void DoRows(Extent* extents, const Cast& cast) {
RunOnPool(
pool_, 0, rect_.ysize(),
Bind<To, Type, Order, Channels, Extent, Cast>(this, extents, cast),
"ExtImg xform");
}
// Calls the instantiation with the matching Type and Order.
template <class To, class Type, class Order, class Extent, class Cast>
void DispatchType(Extent* extents, const Cast& cast) {
if (external_->IsGray()) {
if (external_->HasAlpha()) {
DoRows<To, Type, Order, Channels2>(extents, cast);
} else {
DoRows<To, Type, Order, Channels1>(extents, cast);
}
} else {
if (external_->HasAlpha()) {
DoRows<To, Type, Order, Channels4>(extents, cast);
} else {
DoRows<To, Type, Order, Channels3>(extents, cast);
}
}
}
ThreadPool* pool_; // not owned
const Image3F& color_;
const Rect rect_; // whence in color_ to copy, and output size.
const ImageU* alpha_; // not owned
ExternalImage* external_; // not owned
bool want_alpha_;
ColorSpaceTransform transform_;
};
// Multithreaded deinterleaving/conversion from ExternalImage to Image3.
class Converter {
public:
Converter(ThreadPool* pool, const ExternalImage& external)
: pool_(pool),
external_(&external),
xsize_(external.xsize()),
ysize_(external.ysize()),
color_(xsize_, ysize_) {
const size_t num_threads = NumThreads(pool);
temp_buf_ = ImageF(xsize_ * external.c_current().Channels(), num_threads);
if (external_->HasAlpha()) {
alpha_ = ImageU(xsize_, ysize_);
bits_per_alpha_ = external_->BitsPerAlpha();
alpha_stats_.resize(num_threads);
}
}
template <class Cast>
Status Run(const Cast& cast) {
const size_t bytes = DivCeil(external_->BitsPerSample(), kBitsPerByte);
const bool big_endian = external_->BigEndian();
if (bytes == 1) {
DispatchType<TypeB, OrderLE>(cast);
} else if (bytes == 2 && big_endian) {
DispatchType<TypeU, OrderBE>(cast);
} else if (bytes == 2) {
DispatchType<TypeU, OrderLE>(cast);
} else if (bytes == 4 && big_endian) {
DispatchType<TypeF, OrderBE>(cast);
} else if (bytes == 4) {
DispatchType<TypeF, OrderLE>(cast);
} else {
return PIK_FAILURE("Unsupported BitsPerSample");
}
return true;
}
Status MoveTo(CodecInOut* io) {
io->SetFromImage(std::move(color_), external_->c_current());
// Don't have alpha; during TransformTo, don't remove existing alpha.
if (alpha_stats_.empty()) return true;
const size_t max_alpha = (1 << bits_per_alpha_) - 1;
// Reduce per-thread statistics.
uint32_t and_bits = alpha_stats_[0].and_bits;
uint32_t or_bits = alpha_stats_[0].or_bits;
for (size_t i = 1; i < alpha_stats_.size(); ++i) {
and_bits &= alpha_stats_[i].and_bits;
or_bits |= alpha_stats_[i].or_bits;
}
if (or_bits > max_alpha) {
return PIK_FAILURE("Alpha out of range");
}
// Keep alpha if at least one value is (semi)transparent.
if (and_bits != max_alpha) {
io->SetAlpha(std::move(alpha_), bits_per_alpha_);
} else {
io->RemoveAlpha();
}
return true;
}
private:
template <class Type, class Order, class Channels, class Cast>
PIK_INLINE void DoRow(const Cast& cast, const size_t y, const size_t thread) {
const uint8_t* PIK_RESTRICT row_external = external_->ConstRow(y);
if (!alpha_stats_.empty()) {
// No-op if Channels1/3.
Demux::ExternalToAlpha(Type(), Order(), Channels(), xsize_, row_external,
alpha_.Row(y), thread, &alpha_stats_);
}
float* PIK_RESTRICT row_temp = temp_buf_.Row(thread);
Demux::ExternalToTemp(Type(), Order(), Channels(), xsize_, row_external,
cast, row_temp);
#if PIK_EXT_VERBOSE
printf("ToIO(%s%s %s): ext %3d %3d %3d tmp %.4f %.4f %.4f\n",
Channels::Name(), Type::Name(), Cast::Name(),
row_external[3 * kX + 0], row_external[3 * kX + 1],
row_external[3 * kX + 2], row_temp[3 * kX + 0], row_temp[3 * kX + 1],
row_temp[3 * kX + 2]);
#endif
Interleave::Temp255ToImage3(Channels(), row_temp, y, &color_);
}
// Closure callable by ThreadPool.
template <class Type, class Order, class Channels, class Cast>
class Bind {
public:
explicit Bind(Converter* converter, const Cast& cast)
: converter_(converter), cast_(cast) {}
PIK_INLINE void operator()(const int task, const int thread) const {
converter_->DoRow<Type, Order, Channels>(cast_, task, thread);
}
private:
Converter* converter_; // not owned
const Cast cast_;
};
template <class Type, class Order, class Channels, class Cast>
void DoRows(const Cast& cast) {
RunOnPool(pool_, 0, ysize_, Bind<Type, Order, Channels, Cast>(this, cast),
"ExtImg cvt");
}
// Calls the instantiation with the matching Type and Order.
template <class Type, class Order, class Cast>
void DispatchType(const Cast& cast) {
if (external_->IsGray()) {
if (external_->HasAlpha()) {
DoRows<Type, Order, Channels2>(cast);
} else {
DoRows<Type, Order, Channels1>(cast);
}
} else {
if (external_->HasAlpha()) {
DoRows<Type, Order, Channels4>(cast);
} else {
DoRows<Type, Order, Channels3>(cast);
}
}
}
ThreadPool* pool_; // not owned
const ExternalImage* external_; // not owned
size_t xsize_;
size_t ysize_;
Image3F color_;
ImageF temp_buf_;
// Only initialized if external_->HasAlpha() && want_alpha:
std::vector<Alpha::Stats> alpha_stats_;
ImageU alpha_;
size_t bits_per_alpha_;
};
} // namespace
ExternalImage::ExternalImage(const size_t xsize, const size_t ysize,
const ColorEncoding& c_current,
const bool has_alpha, const size_t bits_per_alpha,
const size_t bits_per_sample,
const bool big_endian)
: xsize_(xsize),
ysize_(ysize),
c_current_(c_current),
channels_(c_current.Channels() + has_alpha),
bits_per_alpha_(bits_per_alpha),
bits_per_sample_(bits_per_sample),
big_endian_(big_endian),
row_size_(xsize * channels_ * DivCeil(bits_per_sample, kBitsPerByte)) {
PIK_ASSERT(1 <= channels_ && channels_ <= 4);
PIK_ASSERT(1 <= bits_per_sample && bits_per_sample <= 32);
if (has_alpha) PIK_ASSERT(1 <= bits_per_alpha && bits_per_alpha <= 32);
bytes_.resize(ysize_ * row_size_);
is_healthy_ = !bytes_.empty();
}
ExternalImage::ExternalImage(const size_t xsize, const size_t ysize,
const ColorEncoding& c_current,
const bool has_alpha, const size_t bits_per_alpha,
const size_t bits_per_sample,
const bool big_endian, const uint8_t* bytes,
const uint8_t* end)
: ExternalImage(xsize, ysize, c_current, has_alpha, bits_per_alpha,
bits_per_sample, big_endian) {
if (is_healthy_) {
if (end != nullptr) PIK_CHECK(bytes + ysize * row_size_ <= end);
memcpy(bytes_.data(), bytes, bytes_.size());
}
}
ExternalImage::ExternalImage(ThreadPool* pool, const Image3F& color,
const Rect& rect, const ColorEncoding& c_current,
const ColorEncoding& c_desired,
const bool has_alpha, const ImageU* alpha,
size_t bits_per_alpha, size_t bits_per_sample,
bool big_endian,
CodecIntervals* temp_intervals)
: ExternalImage(rect.xsize(), rect.ysize(), c_desired, has_alpha,
bits_per_alpha, bits_per_sample, big_endian) {
if (!is_healthy_) return;
Transformer transformer(pool, color, rect, has_alpha, alpha, this);
if (!transformer.Init(c_current, c_desired)) {
is_healthy_ = false;
return;
}
const CodecInterval ext_interval = GetInterval(bits_per_sample);
if (bits_per_sample == 32) {
ExtentsStatic extents;
const CastFloat01 cast(ext_interval); // only multiply by const
is_healthy_ = transformer.Run<ToExternal>(&extents, cast);
} else if (temp_intervals != nullptr) {
// Store temp to separate image and obtain per-channel intervals.
ExtentsDynamic extents(xsize_, ysize_, NumThreads(pool), c_desired);
const CastUnused unused;
is_healthy_ = transformer.Run<ToExternal1>(&extents, unused);
if (!is_healthy_) return;
extents.Finalize(temp_intervals);
// Rescale based on temp_intervals.
const CastRescale01 cast(*temp_intervals, ext_interval);
is_healthy_ = transformer.Run<ToExternal2>(&extents, cast);
} else {
ExtentsStatic extents;
const CastClip01 cast(ext_interval); // clip
is_healthy_ = transformer.Run<ToExternal>(&extents, cast);
}
}
Status ExternalImage::CopyTo(const CodecIntervals* temp_intervals,
ThreadPool* pool, CodecInOut* io) const {
PIK_ASSERT(IsHealthy()); // Caller should have checked beforehand.
Converter converter(pool, *this);
const CodecInterval ext_interval = GetInterval(bits_per_sample_);
if (bits_per_sample_ == 32) {
const CastFloat255 cast(ext_interval);
PIK_RETURN_IF_ERROR(converter.Run(cast));
} else if (temp_intervals != nullptr) {
const CastRescale255 cast(*temp_intervals, ext_interval);
PIK_RETURN_IF_ERROR(converter.Run(cast));
} else {
const CastClip255 cast(ext_interval);
PIK_RETURN_IF_ERROR(converter.Run(cast));
}
return converter.MoveTo(io);
}
} // namespace pik
| 37.904723 | 80 | 0.599523 | EwoutH |
e403bc0dedff958ba0ef76ea4b67175bd370fe3c | 8,887 | cpp | C++ | QuantExt/test/discountratiomodifiedcurve.cpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | null | null | null | QuantExt/test/discountratiomodifiedcurve.cpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | null | null | null | QuantExt/test/discountratiomodifiedcurve.cpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | 1 | 2022-02-07T02:04:10.000Z | 2022-02-07T02:04:10.000Z | /*
Copyright (C) 2018 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include "toplevelfixture.hpp"
#include <boost/assign/list_of.hpp>
#include <boost/make_shared.hpp>
#include <boost/test/unit_test.hpp>
#include <ql/math/comparison.hpp>
#include <ql/settings.hpp>
#include <ql/termstructures/yield/discountcurve.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/termstructures/yield/zerocurve.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <qle/termstructures/discountratiomodifiedcurve.hpp>
using QuantExt::DiscountRatioModifiedCurve;
using namespace QuantLib;
using namespace boost::unit_test_framework;
using namespace boost::assign;
using std::vector;
BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)
BOOST_AUTO_TEST_SUITE(DiscountingRatioModifiedCurveTest)
BOOST_AUTO_TEST_CASE(testStandardCurves) {
BOOST_TEST_MESSAGE("Testing discount ratio modified curve with some standard curves");
SavedSettings backup;
Date today(15, Aug, 2018);
Settings::instance().evaluationDate() = today;
Actual365Fixed dc;
// Base curve with fixed reference date of 15th Aug 2018
vector<Date> baseDates = list_of(today)(today + 1 * Years);
vector<Real> baseDfs = list_of(1.0)(0.98);
Handle<YieldTermStructure> baseCurve(boost::make_shared<DiscountCurve>(baseDates, baseDfs, dc));
baseCurve->enableExtrapolation();
// Numerator curve with fixed reference date of 15th Aug 2018
vector<Date> numDates = list_of(today)(today + 1 * Years)(today + 2 * Years);
vector<Real> numZeroes = list_of(0.025)(0.025)(0.026);
Handle<YieldTermStructure> numCurve(boost::make_shared<ZeroCurve>(numDates, numZeroes, dc));
numCurve->enableExtrapolation();
// Denominator curve with floating reference date
Handle<YieldTermStructure> denCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, dc));
DiscountRatioModifiedCurve curve(baseCurve, numCurve, denCurve);
Date discountDate = today + 18 * Months;
BOOST_CHECK(
close(curve.discount(discountDate),
baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(discountDate)));
discountDate = today + 3 * Years;
BOOST_CHECK(
close(curve.discount(discountDate),
baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(discountDate)));
// When we change evaluation date, we may not get what we expect here because reference date is taken from the
// base curve which has been set up here with a fixed reference date. However, the denominator curve has been
// set up here with a floating reference date. See the warning in the ctor of DiscountRatioModifiedCurve
Settings::instance().evaluationDate() = today + 3 * Months;
BOOST_TEST_MESSAGE("Changed evaluation date to " << Settings::instance().evaluationDate());
BOOST_CHECK(!close(curve.discount(discountDate), baseCurve->discount(discountDate) *
numCurve->discount(discountDate) /
denCurve->discount(discountDate)));
Time t = dc.yearFraction(curve.referenceDate(), discountDate);
BOOST_CHECK(close(curve.discount(discountDate),
baseCurve->discount(discountDate) * numCurve->discount(discountDate) / denCurve->discount(t)));
}
BOOST_AUTO_TEST_CASE(testExtrapolationSettings) {
BOOST_TEST_MESSAGE("Testing extrapolation settings for discount ratio modified curve");
SavedSettings backup;
Date today(15, Aug, 2018);
Settings::instance().evaluationDate() = today;
Actual365Fixed dc;
// Base curve with fixed reference date of 15th Aug 2018
vector<Date> baseDates = list_of(today)(Date(15, Aug, 2019));
vector<Real> baseDfs = list_of(1.0)(0.98);
Handle<YieldTermStructure> baseCurve(boost::make_shared<DiscountCurve>(baseDates, baseDfs, dc));
// Numerator curve with fixed reference date of 15th Aug 2018
vector<Date> numDates = list_of(today)(Date(15, Aug, 2019))(Date(15, Aug, 2020));
vector<Real> numZeroes = list_of(0.025)(0.025)(0.026);
Handle<YieldTermStructure> numCurve(boost::make_shared<ZeroCurve>(numDates, numZeroes, dc));
// Denominator curve with floating reference date
Handle<YieldTermStructure> denCurve(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, dc));
// Create the discount ratio curve
DiscountRatioModifiedCurve curve(baseCurve, numCurve, denCurve);
// Extrapolation is always true
BOOST_CHECK(curve.allowsExtrapolation());
// Max date is maximum possible date
BOOST_CHECK_EQUAL(curve.maxDate(), Date::maxDate());
// Extrapolation is determined by underlying curves
BOOST_CHECK_NO_THROW(curve.discount(Date(15, Aug, 2019)));
BOOST_CHECK_THROW(curve.discount(Date(15, Aug, 2019) + 1 * Days), QuantLib::Error);
baseCurve->enableExtrapolation();
BOOST_CHECK_NO_THROW(curve.discount(Date(15, Aug, 2019) + 1 * Days));
BOOST_CHECK_THROW(curve.discount(Date(15, Aug, 2020) + 1 * Days), QuantLib::Error);
numCurve->enableExtrapolation();
BOOST_CHECK_NO_THROW(curve.discount(Date(15, Aug, 2020) + 1 * Days));
}
BOOST_AUTO_TEST_CASE(testConstructionNullUnderlyingCurvesThrow) {
BOOST_TEST_MESSAGE("Testing construction with null underlying curves throw");
boost::shared_ptr<DiscountRatioModifiedCurve> curve;
// All empty handles throw
Handle<YieldTermStructure> baseCurve;
Handle<YieldTermStructure> numCurve;
Handle<YieldTermStructure> denCurve;
BOOST_CHECK_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve, numCurve, denCurve),
QuantLib::Error);
// Numerator and denominator empty handles throw
Handle<YieldTermStructure> baseCurve_1(
boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed()));
BOOST_CHECK_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve_1, numCurve, denCurve),
QuantLib::Error);
// Denominator empty handles throw
Handle<YieldTermStructure> numCurve_1(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed()));
BOOST_CHECK_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve_1, numCurve_1, denCurve),
QuantLib::Error);
// No empty handles succeeds
Handle<YieldTermStructure> denCurve_1(boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed()));
BOOST_CHECK_NO_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve_1, numCurve_1, denCurve_1));
}
BOOST_AUTO_TEST_CASE(testLinkingNullUnderlyingCurvesThrow) {
BOOST_TEST_MESSAGE("Testing that linking with null underlying curves throw");
boost::shared_ptr<DiscountRatioModifiedCurve> curve;
// All empty handles throw
RelinkableHandle<YieldTermStructure> baseCurve(
boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed()));
RelinkableHandle<YieldTermStructure> numCurve(
boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed()));
RelinkableHandle<YieldTermStructure> denCurve(
boost::make_shared<FlatForward>(0, NullCalendar(), 0.0255, Actual365Fixed()));
// Curve building succeeds since no empty handles
BOOST_CHECK_NO_THROW(curve = boost::make_shared<DiscountRatioModifiedCurve>(baseCurve, numCurve, denCurve));
// Switching base curve to empty handle should give a failure
BOOST_CHECK_THROW(baseCurve.linkTo(boost::shared_ptr<YieldTermStructure>()), QuantLib::Error);
BOOST_CHECK_NO_THROW(baseCurve.linkTo(*numCurve));
// Switching numerator curve to empty handle should give a failure
BOOST_CHECK_THROW(numCurve.linkTo(boost::shared_ptr<YieldTermStructure>()), QuantLib::Error);
BOOST_CHECK_NO_THROW(numCurve.linkTo(*denCurve));
// Switching denominator curve to empty handle should give a failure
BOOST_CHECK_THROW(denCurve.linkTo(boost::shared_ptr<YieldTermStructure>()), QuantLib::Error);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 45.341837 | 120 | 0.738382 | PiotrSiejda |
e4043fd358a98ab0d838f1acaa68aea2e815df92 | 951 | hpp | C++ | microptp/config.hpp | decimad/microptp | bc7e10ddafc9015d480425f3f462ae086bf48c3b | [
"BSL-1.0"
] | 3 | 2015-07-14T19:22:18.000Z | 2015-12-03T01:15:15.000Z | microptp/config.hpp | decimad/microptp | bc7e10ddafc9015d480425f3f462ae086bf48c3b | [
"BSL-1.0"
] | 1 | 2015-12-02T23:46:25.000Z | 2015-12-04T14:17:43.000Z | microptp/config.hpp | decimad/microptp | bc7e10ddafc9015d480425f3f462ae086bf48c3b | [
"BSL-1.0"
] | null | null | null | // Copyright Michael Steinberg 2015
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SYSTEM_MICROPTP_MICROPTP_CONFIG_HPP_
#define SYSTEM_MICROPTP_MICROPTP_CONFIG_HPP_
#include <microptp_config.hpp>
#include <microptp/ptpdatatypes.hpp>
#include <fixed/fixed.hpp>
#ifndef PRINT
#define PRINT(...)
#endif
#ifndef TRACE
#define TRACE(...)
#endif
#ifndef UPTP_SLAVE_ONLY
#define UPTP_SLAVE_ONLY 1
#endif
namespace uptp {
struct Config {
#if !UPTP_SLAVE_ONLY
ClockQuality clock_quality;
#endif
static const bool two_step = true;
static const bool any_domain = false;
static const uint8 preferred_domain = 0;
static constexpr auto kp_ = FIXED_RANGE(0, 0.1, 32)::from(0.005);
static constexpr auto kn_ = FIXED_RANGE(0, 0.01, 32)::from(0.0005);
};
}
#endif /* SYSTEM_MICROPTP_MICROPTP_CONFIG_HPP_ */
| 22.642857 | 69 | 0.741325 | decimad |
e4070845458d6f19ddf0c15ea52dc80f8366e609 | 5,201 | cpp | C++ | Sail/src/API/DX11/shader/DX11InputLayout.cpp | h3nx/Sail | 96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9 | [
"MIT"
] | 1 | 2020-09-03T09:53:45.000Z | 2020-09-03T09:53:45.000Z | Sail/src/API/DX11/shader/DX11InputLayout.cpp | h3nx/Sail | 96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9 | [
"MIT"
] | null | null | null | Sail/src/API/DX11/shader/DX11InputLayout.cpp | h3nx/Sail | 96c13ee50bf9666c01bb8bb263e0c2dc3ba0eff9 | [
"MIT"
] | 1 | 2021-01-31T05:27:36.000Z | 2021-01-31T05:27:36.000Z | #include "pch.h"
#include "../DX11API.h"
#include "DX11InputLayout.h"
#include "Sail/Application.h"
InputLayout* InputLayout::Create() {
return SAIL_NEW DX11InputLayout();
}
DX11InputLayout::DX11InputLayout()
: InputLayout()
{ }
DX11InputLayout::~DX11InputLayout() {
Memory::SafeRelease(m_inputLayout);
}
void DX11InputLayout::pushFloat(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) {
if (m_ied.size() == m_ied.capacity()) {
m_ied.reserve(m_ied.size() + 1);
InputOrder.reserve(InputOrder.size() + 1);
}
UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT;
DXGI_FORMAT format = DXGI_FORMAT_R32_FLOAT;;
/*if (typeid(T) == typeid(glm::vec4)) { format = DXGI_FORMAT_R32G32B32A32_FLOAT; }
if (typeid(T) == typeid(glm::vec3)) { format = DXGI_FORMAT_R32G32B32_FLOAT; }
if (typeid(T) == typeid(glm::vec2)) { format = DXGI_FORMAT_R32G32_FLOAT; }
if (typeid(T) == typeid(float)) { format = DXGI_FORMAT_R32_FLOAT; }*/
auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass);
m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate });
UINT typeSize = sizeof(float);
if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA)
InstanceSize += typeSize;
else
VertexSize += typeSize;
InputLayout::pushFloat(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate);
}
void DX11InputLayout::pushVec2(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) {
if (m_ied.size() == m_ied.capacity()) {
m_ied.reserve(m_ied.size() + 1);
InputOrder.reserve(InputOrder.size() + 1);
}
UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT;
DXGI_FORMAT format = DXGI_FORMAT_R32G32_FLOAT;;
auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass);
m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate });
UINT typeSize = sizeof(glm::vec2);
if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA)
InstanceSize += typeSize;
else
VertexSize += typeSize;
InputLayout::pushVec2(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate);
}
void DX11InputLayout::pushVec3(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) {
if (m_ied.size() == m_ied.capacity()) {
m_ied.reserve(m_ied.size() + 1);
InputOrder.reserve(InputOrder.size() + 1);
}
UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT;
DXGI_FORMAT format = DXGI_FORMAT_R32G32B32_FLOAT;;
auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass);
m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate });
UINT typeSize = sizeof(glm::vec3);
if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA)
InstanceSize += typeSize;
else
VertexSize += typeSize;
InputLayout::pushVec3(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate);
}
void DX11InputLayout::pushVec4(InputType inputType, LPCSTR semanticName, UINT semanticIndex, InputClassification inputSlotClass, UINT instanceDataStepRate) {
if (m_ied.size() == m_ied.capacity()) {
m_ied.reserve(m_ied.size() + 1);
InputOrder.reserve(InputOrder.size() + 1);
}
UINT alignedByteOffset = (m_ied.size() == 0) ? 0 : D3D11_APPEND_ALIGNED_ELEMENT;
DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT;;
auto convertedInputClass = (D3D11_INPUT_CLASSIFICATION)convertInputClassification(inputSlotClass);
m_ied.push_back({ semanticName, semanticIndex, format, 0, alignedByteOffset, convertedInputClass, instanceDataStepRate });
UINT typeSize = sizeof(glm::vec4);
if (convertedInputClass == D3D11_INPUT_PER_INSTANCE_DATA)
InstanceSize += typeSize;
else
VertexSize += typeSize;
InputLayout::pushVec4(inputType, semanticName, semanticIndex, inputSlotClass, instanceDataStepRate);
}
void DX11InputLayout::create(void* vertexShaderBlob) {
if (!vertexShaderBlob) {
Logger::Error("Failed to set up input layout, the ShaderSet does not have a vertex shader!");
return;
}
auto shaderBlob = static_cast<ID3D10Blob*>(vertexShaderBlob);
Application::getInstance()->getAPI<DX11API>()->getDevice()->CreateInputLayout(&m_ied[0], m_ied.size(), shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), &m_inputLayout);
}
void DX11InputLayout::bind() const {
Application::getInstance()->getAPI<DX11API>()->getDeviceContext()->IASetInputLayout(m_inputLayout);
}
int DX11InputLayout::convertInputClassification(InputClassification inputSlotClass) {
switch (inputSlotClass) {
case InputLayout::PER_VERTEX_DATA:
return D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_VERTEX_DATA;
case InputLayout::PER_INSTANCE_DATA:
return D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_INSTANCE_DATA;
default:
Logger::Error("Invalid input classifier specified");
return 0;
}
}
| 43.705882 | 181 | 0.781388 | h3nx |
e40735cc684aa63cc7d27cd32cd035c213ccef19 | 2,869 | cc | C++ | chromium/components/pdf/browser/pdf_web_contents_helper.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/components/pdf/browser/pdf_web_contents_helper.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/components/pdf/browser/pdf_web_contents_helper.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/pdf/browser/pdf_web_contents_helper.h"
#include <utility>
#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "components/pdf/browser/open_pdf_in_reader_prompt_client.h"
#include "components/pdf/browser/pdf_web_contents_helper_client.h"
#include "components/pdf/common/pdf_messages.h"
#include "content/public/browser/navigation_details.h"
DEFINE_WEB_CONTENTS_USER_DATA_KEY(pdf::PDFWebContentsHelper);
namespace pdf {
// static
void PDFWebContentsHelper::CreateForWebContentsWithClient(
content::WebContents* contents,
scoped_ptr<PDFWebContentsHelperClient> client) {
if (FromWebContents(contents))
return;
contents->SetUserData(UserDataKey(),
new PDFWebContentsHelper(contents, std::move(client)));
}
PDFWebContentsHelper::PDFWebContentsHelper(
content::WebContents* web_contents,
scoped_ptr<PDFWebContentsHelperClient> client)
: content::WebContentsObserver(web_contents), client_(std::move(client)) {}
PDFWebContentsHelper::~PDFWebContentsHelper() {
}
void PDFWebContentsHelper::ShowOpenInReaderPrompt(
scoped_ptr<OpenPDFInReaderPromptClient> prompt) {
open_in_reader_prompt_ = std::move(prompt);
UpdateLocationBar();
}
bool PDFWebContentsHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PDFWebContentsHelper, message)
IPC_MESSAGE_HANDLER(PDFHostMsg_PDFHasUnsupportedFeature,
OnHasUnsupportedFeature)
IPC_MESSAGE_HANDLER(PDFHostMsg_PDFSaveURLAs, OnSaveURLAs)
IPC_MESSAGE_HANDLER(PDFHostMsg_PDFUpdateContentRestrictions,
OnUpdateContentRestrictions)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void PDFWebContentsHelper::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (open_in_reader_prompt_.get() &&
open_in_reader_prompt_->ShouldExpire(details)) {
open_in_reader_prompt_.reset();
UpdateLocationBar();
}
}
void PDFWebContentsHelper::UpdateLocationBar() {
client_->UpdateLocationBar(web_contents());
}
void PDFWebContentsHelper::OnHasUnsupportedFeature() {
client_->OnPDFHasUnsupportedFeature(web_contents());
}
void PDFWebContentsHelper::OnSaveURLAs(const GURL& url,
const content::Referrer& referrer) {
client_->OnSaveURL(web_contents());
web_contents()->SaveFrame(url, referrer);
}
void PDFWebContentsHelper::OnUpdateContentRestrictions(
int content_restrictions) {
client_->UpdateContentRestrictions(web_contents(), content_restrictions);
}
} // namespace pdf
| 32.977011 | 79 | 0.765075 | wedataintelligence |
e40747c211e8941c3a1bb4f766431e17b5477028 | 1,243 | cpp | C++ | BZOJ/3875/brute.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | BZOJ/3875/brute.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | BZOJ/3875/brute.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<queue>
#define pli pair<LL,int>
#define mp make_pair
#define fi first
#define se second
#define rg register
#define rep(i,x,y) for(rg int i=(x);i<=(y);++i)
#define per(i,x,y) for(rg int i=(x);i>=(y);--i)
using namespace std;
typedef long long LL;
const int N=2e5+10,M=1e6+10;
int n;
struct Heap{
priority_queue<pli,vector<pli>,greater<pli> >A,B;
int size(){return A.size()-B.size();}
void update(){while(B.size()&&A.top()==B.top())A.pop(),B.pop();}
void push(pli x){A.push(x);}
void del(pli x){B.push(x);}
pli top(){update();return A.top();}
void pop(){update();A.pop();}
}heap;
struct Graph{
int tot,head[N],to[M],next[M];
LL dis[N],mag[N],com[N],tmp[N];
void ins(int a,int b){to[++tot]=b;next[tot]=head[a];head[a]=tot;}
void update(){
rep(i,1,n)tmp[i]=com[i];
rep(i,1,n)for(int p=head[i];p;p=next[p])tmp[to[p]]+=dis[i];
rep(i,1,n)dis[i]=min(dis[i],tmp[i]);
}
}G;
int main(){
freopen("code.in","r",stdin);freopen("brute.out","w",stdout);
scanf("%d",&n);
rep(i,1,n){
LL s,k,r;scanf("%lld%lld%lld",&s,&k,&r);
G.mag[i]=k;G.com[i]=s;
rep(j,1,r){int x;scanf("%d",&x);G.ins(x,i);}
}
rep(i,1,n)G.dis[i]=G.mag[i];
rep(i,1,n)G.update();
printf("%lld",G.dis[1]);
return 0;
}
| 26.446809 | 66 | 0.602574 | sjj118 |
e40a2bf75023cdeec08958fc8fabc796a873f0b1 | 11,743 | hxx | C++ | resip/stack/TransactionUser.hxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | resip/stack/TransactionUser.hxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | resip/stack/TransactionUser.hxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | #if !defined(RESIP_TU_HXX)
#define RESIP_TU_HXX
#include <iosfwd>
#include <set>
#include "rutil/TimeLimitFifo.hxx"
#include "rutil/Data.hxx"
#include "rutil/CongestionManager.hxx"
#include "resip/stack/Message.hxx"
#include "resip/stack/MessageFilterRule.hxx"
namespace resip
{
class SipMessage;
/**
@brief The base-class for an RFC 3261 Transaction User. This is the
"app-layer".
Subclasses of TransactionUser are expected to do the following things:
- Register itself by using SipStack::registerTransactionUser().
- Regularly pull messages out of mFifo, and process them.
- Particularly, every received SIP request MUST be responded to, or
the stack will leak transactions.
- Before the TransactionUser is destroyed, it should ensure that it has
been unregistered from the stack using
SipStack::unregisterTransactionUser(), and gotten a confirmation in
the form of a TransactionUserMessage.
There is also a collection of things you can do to customize how the stack
interacts with your TransactionUser:
- If you wish to restrict the types of SIP traffic your TransactionUser
will receive from the stack, you can do so by setting the
MessageFilterRuleList, either in the constructor, or with
setMessageFilterRuleList() (see MessageFilterRule for more)
- If you need more fine-grained control over what SIP messages your
TransactionUser is willing/able to handle, you can override
TransactionUser::isForMe().
- If you wish your TransactionUser to be notified whenever a
transaction ends, just pass RegisterForTransactionTermination in the
constructor.
- If you wish your TransactionUser to be notified when Connections are
closed, pass RegisterForConnectionTermination in the constructor.
@ingroup resip_crit
*/
class TransactionUser
{
public:
/**
@brief Posts a Message to this TransactionUser's fifo. Ownership of msg
is taken.
@param msg The Message to add to mFifo. (This takes ownership of msg)
*/
void post(Message* msg);
/**
@brief Returns true iff domain matches one of the domains that this
TransactionUser is responsible for. (added with addDomain).
@param domain The domain name to check.
@return True iff this TransactionUser is responsible for domain.
@note The comparison performed is case-sensitive; make sure you
lower-case everything you put in here.
*/
bool isMyDomain(const Data& domain) const;
/**
@brief Adds a domain to the set of domains that this TransactionUser is
responsible for.
@note The comparison performed is case-sensitive; make sure you
lower-case everything you put in here.
@todo Make this case-insensitive.
*/
void addDomain(const Data& domain);
/**
@brief Return the name of this TransactionUser. Used in encode().
@return The name of this TransactionUser, as a Data.
*/
virtual const Data& name() const=0;
/**
@brief Encodes the name of this TransactionUser (as specified by
name()), and the current depth of its fifo.
@param strm The ostream to encode to.
@return strm
*/
virtual EncodeStream& encode(EncodeStream& strm) const;
/**
@brief Sets this TransactionUser's MessageFilterRuleList.
This tells the stack which SIP messages this TransactionUser is
interested in, and which ones it is not. This allows multiple
TransactionUsers to run on top of the same SipStack.
@param rules The MessageFilterRuleList to use.
@see MessageFilterRule
*/
void setMessageFilterRuleList(MessageFilterRuleList &rules);
/**
@internal
@brief Returns true iff this TransactionUser should be notified when
transactions end.
*/
bool isRegisteredForTransactionTermination() const;
/**
@internal
@brief Returns true iff this TransactionUser should be notified when
connections close.
*/
bool isRegisteredForConnectionTermination() const;
bool isRegisteredForKeepAlivePongs() const;
inline CongestionManager::RejectionBehavior getRejectionBehavior() const
{
if(mCongestionManager)
{
return mCongestionManager->getRejectionBehavior(&mFifo);
}
return CongestionManager::NORMAL;
}
virtual void setCongestionManager(CongestionManager* manager)
{
if(mCongestionManager)
{
mCongestionManager->unregisterFifo(&mFifo);
}
mCongestionManager=manager;
if(mCongestionManager)
{
mCongestionManager->registerFifo(&mFifo);
}
}
virtual UInt16 getExpectedWait() const
{
return (UInt16)mFifo.expectedWaitTimeMilliSec();
}
// .bwc. This specifies whether the TU can cope with dropped responses
// (due to congestion). Some TUs may need responses to clean up state,
// while others may rely on TransactionTerminated messages. Those that
// rely on TransactionTerminated messages will be able to return false
// here, meaning that in dire congestion situations, the stack will drop
// responses bound for the TU.
virtual bool responsesMandatory() const {return true;}
protected:
enum TransactionTermination
{
RegisterForTransactionTermination,
DoNotRegisterForTransactionTermination
};
enum ConnectionTermination
{
RegisterForConnectionTermination,
DoNotRegisterForConnectionTermination
};
enum KeepAlivePongs
{
RegisterForKeepAlivePongs,
DoNotRegisterForKeepAlivePongs
};
/**
@brief Constructor that specifies whether this TransactionUser needs to
hear about the completion of transactions, and the closing of
connections.
@param t Whether or not the TransactionUser should be informed when
transactions end (disabled by default).
@param c Whether or not the TransactionUser should be informed when
connections close (disabled by default).
@note The default MessageFilterRuleList used will accept all SIP
requests with either sip: or sips: in the Request-Uri.
@note This is protected to ensure than no-one constructs the
base-class. (Subclasses call this in their constructor)
*/
TransactionUser(TransactionTermination t=DoNotRegisterForTransactionTermination,
ConnectionTermination c=DoNotRegisterForConnectionTermination,
KeepAlivePongs k=DoNotRegisterForKeepAlivePongs);
/**
@brief Constructor that specifies the MessageFilterRuleList, whether
this TransactionUser needs to hear about the completion of
transactions, and the closing of connections.
@param rules The MessageFilterRuleList to use. (A copy is made)
@param t Whether or not the TransactionUser should be informed when
transactions end (disabled by default).
@param c Whether or not the TransactionUser should be informed when
connections close (disabled by default).
@note This is protected to ensure than no-one constructs the
base-class. (Subclasses call this in their constructor)
*/
TransactionUser(MessageFilterRuleList &rules,
TransactionTermination t=DoNotRegisterForTransactionTermination,
ConnectionTermination c=DoNotRegisterForConnectionTermination,
KeepAlivePongs k=DoNotRegisterForKeepAlivePongs);
virtual ~TransactionUser()=0;
/**
@brief Returns true iff this TransactionUser should process msg.
@param msg The SipMessage we received.
@return True iff this TransactionUser should process msg.
@note By default, this uses the MessageFilterRuleList. It can be
overridden for more flexibility.
*/
virtual bool isForMe(const SipMessage& msg) const;
/**
@brief This TransactionUser's fifo. All communication with the
TransactionUser goes through here.
*/
TimeLimitFifo<Message> mFifo;
CongestionManager* mCongestionManager;
private:
void postToTransactionUser(Message* msg, TimeLimitFifo<Message>::DepthUsage usage);
unsigned int size() const;
bool wouldAccept(TimeLimitFifo<Message>::DepthUsage usage) const;
private:
MessageFilterRuleList mRuleList;
typedef std::set<Data> DomainList;
DomainList mDomainList;
bool mRegisteredForTransactionTermination;
bool mRegisteredForConnectionTermination;
bool mRegisteredForKeepAlivePongs;
friend class TuSelector;
};
EncodeStream&
operator<<(EncodeStream& strm, const TransactionUser& tu);
}
#endif
/* ====================================================================
* The Vovida Software License, Version 1.0
*
* Copyright (c) 2000 Vovida Networks, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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. The names "VOCAL", "Vovida Open Communication Application Library",
* and "Vovida Open Communication Application Library (VOCAL)" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact vocal@vovida.org.
*
* 4. Products derived from this software may not be called "VOCAL", nor
* may "VOCAL" appear in their name, without prior written
* permission of Vovida Networks, Inc.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA
* NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
* IN EXCESS OF $1,000, NOR FOR ANY 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.
*
* ====================================================================
*
* This software consists of voluntary contributions made by Vovida
* Networks, Inc. and many individuals on behalf of Vovida Networks,
* Inc. For more information on Vovida Networks, Inc., please see
* <http://www.vovida.org/>.
*
*/
| 39.80678 | 89 | 0.668909 | dulton |
e40bf78aee0b38be1168a99cf5ff5e2f690c0040 | 2,192 | cpp | C++ | src/PhotonComponent/NetworkSystem.cpp | mak1a/SivComponent | 1043cde67a5dc14f2d4e0128aecfee7f54ed7002 | [
"MIT"
] | 1 | 2021-01-24T08:55:59.000Z | 2021-01-24T08:55:59.000Z | src/PhotonComponent/NetworkSystem.cpp | mak1a/SivComponent | 1043cde67a5dc14f2d4e0128aecfee7f54ed7002 | [
"MIT"
] | 2 | 2021-01-24T06:12:12.000Z | 2021-01-24T14:37:10.000Z | src/PhotonComponent/NetworkSystem.cpp | mak1a/SivComponent | 1043cde67a5dc14f2d4e0128aecfee7f54ed7002 | [
"MIT"
] | null | null | null | #define NO_S3D_USING
#include "NetworkSystem.hpp"
namespace ComponentEngine::Photon
{
NetworkSystem* NetworkSystem::instance = nullptr;
std::string NetworkObjectName()
{
return "PhotonSystem";
}
[[nodiscard]] s3d::String ConvertJStringToString(const ExitGames::Common::JString& str) {
return s3d::Unicode::FromWString(std::wstring(str));
}
[[nodiscard]] ExitGames::Common::JString ConvertStringToJString(const s3d::String& str) {
return ExitGames::Common::JString(str.toWstr().c_str());
}
NetworkSystem::NetworkSystem()
: mLoadBalancingClient(*this, ChangeAppIDString(), appVersion, ExitGames::Photon::ConnectionProtocol::UDP)
{
SetPlayerName(L"null player");
mLogger.setDebugOutputLevel(ExitGames::Common::DebugLevel::ALL);
mLogger.setListener(*this);
//しっかりとしたシングルトンにしたい
instance = this;
}
NetworkSystem::~NetworkSystem()
{
Disconnect();
instance = nullptr;
}
void NetworkSystem::Connect(void)
{
mLoadBalancingClient.setAutoJoinLobby(true);
// connect() is asynchronous - the actual result arrives in the Listener::connectReturn() or the Listener::connectionErrorReturn() callback
if (!mLoadBalancingClient.connect(ExitGames::LoadBalancing::AuthenticationValues().setUserID(ExitGames::Common::JString() + GETTIMEMS()), playerName))
EGLOG(ExitGames::Common::DebugLevel::ERRORS, L"Could not connect.");
}
void NetworkSystem::Update()
{
mLoadBalancingClient.service(); // needs to be called regularly!
}
void NetworkSystem::OnDestroy()
{
Disconnect();
}
void NetworkSystem::Disconnect(void)
{
mLoadBalancingClient.disconnect(); // disconnect() is asynchronous - the actual result arrives in the Listener::disconnectReturn() callback
}
//シーン変更するだけのクラス
class SceneChanger : public ComponentEngine::AttachableComponent
{
void Update() override
{
GetGameObject().lock()->GetScene().lock()->GetSceneManager()->ChangeScene("Title");
}
};
} // namespace ComponentEngine::Photon
| 30.444444 | 158 | 0.663777 | mak1a |
e40d1bd6f22363279ad1910e69bb856c7eff6349 | 4,113 | cpp | C++ | Samples/Win7Samples/winui/shell/appplatform/UsingImageFactory/ImageFactorySample.cpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/winui/shell/appplatform/UsingImageFactory/ImageFactorySample.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/winui/shell/appplatform/UsingImageFactory/ImageFactorySample.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | //////////////////////////////////////////////////////////////////////////////
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <shobjidl.h> //For IShellItemImageFactory
#include <stdio.h>
#include "resource.h"
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
int LookUp(PCWSTR pwszArg)
{
int nSize = 0;
// The possbile sizes for the image that is requested
struct
{
PCWSTR pwszSize;
int nSize;
} const sizeTable[] = { {L"small", 16}, {L"medium", 48}, {L"large", 96}, {L"extralarge", 256} };
for (int i = 0; i < ARRAYSIZE(sizeTable); i++)
{
if (CSTR_EQUAL == CompareStringOrdinal(pwszArg, -1, sizeTable[i].pwszSize, -1, TRUE))
{
nSize = sizeTable[i].nSize;
break;
}
}
return nSize;
}
void DisplayUsage()
{
wprintf(L"Usage:\n");
wprintf(L"IShellItemImageFactory.exe <size> <Absolute Path to file>\n");
wprintf(L"size - small, medium, large, extralarge\n");
wprintf(L"e.g. ImageFactorySample.exe medium c:\\HelloWorld.jpg \n");
}
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
INT_PTR nReturn = FALSE;
switch (message)
{
case WM_INITDIALOG:
SendDlgItemMessage(hDlg, IDC_STATIC1, STM_SETIMAGE , IMAGE_BITMAP, (LPARAM)lParam);
nReturn = TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
nReturn = TRUE;
}
break;
}
return nReturn;
}
int wmain(int argc, wchar_t *argv[])
{
if (argc != 3)
{
DisplayUsage();
}
else
{
int nSize = LookUp(argv[1]);
if (!nSize)
{
DisplayUsage();
}
else
{
PCWSTR pwszError = NULL;
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr))
{
// Getting the IShellItemImageFactory interface pointer for the file.
IShellItemImageFactory *pImageFactory;
hr = SHCreateItemFromParsingName(argv[2], NULL, IID_PPV_ARGS(&pImageFactory));
if (SUCCEEDED(hr))
{
SIZE size = { nSize, nSize };
//sz - Size of the image, SIIGBF_BIGGERSIZEOK - GetImage will stretch down the bitmap (preserving aspect ratio)
HBITMAP hbmp;
hr = pImageFactory->GetImage(size, SIIGBF_BIGGERSIZEOK, &hbmp);
if (SUCCEEDED(hr))
{
DialogBoxParamW(NULL, MAKEINTRESOURCEW(IDD_DIALOG1), NULL, DialogProc, (LPARAM)hbmp);
DeleteObject(hbmp);
}
else
{
pwszError = L"IShellItemImageFactory::GetImage failed with error code %x";
}
pImageFactory->Release();
}
else
{
pwszError = L"SHCreateItemFromParsingName failed with error %x";
}
CoUninitialize();
}
else
{
pwszError = L"CoInitializeEx failed with error code %x";
}
if (FAILED(hr))
{
wprintf(pwszError, hr);
}
}
}
return 0;
} | 30.924812 | 195 | 0.508145 | windows-development |
e40d874a80a9001fb4d44742f76cb84c3fd81d85 | 13,816 | cpp | C++ | src/backends/miniaudio/AudioDevice_Miniaudio.cpp | xioxin/LabSound | 3e2568fcee9d0b07a91750380daec6305c20855e | [
"BSD-2-Clause"
] | 43 | 2015-02-11T15:52:38.000Z | 2020-01-08T18:19:27.000Z | src/backends/miniaudio/AudioDevice_Miniaudio.cpp | xioxin/LabSound | 3e2568fcee9d0b07a91750380daec6305c20855e | [
"BSD-2-Clause"
] | 2 | 2015-04-05T18:33:13.000Z | 2015-06-11T05:16:19.000Z | src/backends/miniaudio/AudioDevice_Miniaudio.cpp | xioxin/LabSound | 3e2568fcee9d0b07a91750380daec6305c20855e | [
"BSD-2-Clause"
] | 3 | 2015-02-22T09:10:51.000Z | 2015-08-09T22:49:22.000Z | // SPDX-License-Identifier: BSD-2-Clause
// Copyright (C) 2020, The LabSound Authors. All rights reserved.
#define LABSOUND_ENABLE_LOGGING
#include "AudioDevice_Miniaudio.h"
#include "internal/Assertions.h"
#include "internal/VectorMath.h"
#include "LabSound/core/AudioDevice.h"
#include "LabSound/core/AudioHardwareDeviceNode.h"
#include "LabSound/core/AudioNode.h"
#include "LabSound/extended/Logging.h"
//#define MA_DEBUG_OUTPUT
#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"
namespace lab
{
////////////////////////////////////////////////////
// Platform/backend specific static functions //
////////////////////////////////////////////////////
const float kLowThreshold = -1.0f;
const float kHighThreshold = 1.0f;
const int kRenderQuantum = AudioNode::ProcessingSizeInFrames;
/// @TODO - the AudioDeviceInfo wants to support specific sample rates, but miniaudio only tells min and max
/// miniaudio also has a concept of minChannels, which LabSound ignores
namespace
{
ma_context g_context;
static std::vector<AudioDeviceInfo> g_devices;
static bool g_must_init = true;
void init_context()
{
if (g_must_init)
{
LOG_TRACE("[LabSound] init_context() must_init");
if (ma_context_init(NULL, 0, NULL, &g_context) != MA_SUCCESS)
{
LOG_ERROR("[LabSound] init_context(): Failed to initialize miniaudio context");
return;
}
LOG_TRACE("[LabSound] init_context() succeeded");
g_must_init = false;
}
}
}
void PrintAudioDeviceList()
{
if (!g_devices.size())
LOG_INFO("No devices detected");
else
for (auto & device : g_devices)
{
LOG_INFO("[%d] %s\n----------------------\n", device.index, device.identifier.c_str());
LOG_INFO(" ins:%d outs:%d default_in:%s default:out:%s\n", device.num_input_channels, device.num_output_channels, device.is_default_input?"yes":"no", device.is_default_output?"yes":"no");
LOG_INFO(" nominal samplerate: %f\n", device.nominal_samplerate);
for (float f : device.supported_samplerates)
LOG_INFO(" %f\n", f);
}
}
std::vector<AudioDeviceInfo> AudioDevice::MakeAudioDeviceList()
{
init_context();
static bool probed = false;
if (probed)
return g_devices;
probed = true;
ma_result result;
ma_device_info * pPlaybackDeviceInfos;
ma_uint32 playbackDeviceCount;
ma_device_info * pCaptureDeviceInfos;
ma_uint32 captureDeviceCount;
ma_uint32 iDevice;
result = ma_context_get_devices(&g_context, &pPlaybackDeviceInfos, &playbackDeviceCount, &pCaptureDeviceInfos, &captureDeviceCount);
if (result != MA_SUCCESS)
{
LOG_ERROR("Failed to retrieve audio device information.\n");
return {};
}
for (iDevice = 0; iDevice < playbackDeviceCount; ++iDevice)
{
AudioDeviceInfo lab_device_info;
lab_device_info.index = (int32_t) g_devices.size();
lab_device_info.identifier = pPlaybackDeviceInfos[iDevice].name;
if (ma_context_get_device_info(&g_context, ma_device_type_playback,
&pPlaybackDeviceInfos[iDevice].id, ma_share_mode_shared, &pPlaybackDeviceInfos[iDevice])
!= MA_SUCCESS)
continue;
lab_device_info.num_output_channels = pPlaybackDeviceInfos[iDevice].maxChannels;
lab_device_info.num_input_channels = 0;
lab_device_info.supported_samplerates.push_back(static_cast<float>(pPlaybackDeviceInfos[iDevice].minSampleRate));
lab_device_info.supported_samplerates.push_back(static_cast<float>(pPlaybackDeviceInfos[iDevice].maxSampleRate));
lab_device_info.nominal_samplerate = static_cast<float>(pPlaybackDeviceInfos[iDevice].maxSampleRate);
lab_device_info.is_default_output = iDevice == 0;
lab_device_info.is_default_input = false;
g_devices.push_back(lab_device_info);
}
for (iDevice = 0; iDevice < captureDeviceCount; ++iDevice)
{
AudioDeviceInfo lab_device_info;
lab_device_info.index = (int32_t) g_devices.size();
lab_device_info.identifier = pCaptureDeviceInfos[iDevice].name;
if (ma_context_get_device_info(&g_context, ma_device_type_capture,
&pPlaybackDeviceInfos[iDevice].id, ma_share_mode_exclusive, &pPlaybackDeviceInfos[iDevice])
!= MA_SUCCESS)
continue;
lab_device_info.num_output_channels = 0;
lab_device_info.num_input_channels = 2; // pCaptureDeviceInfos[iDevice].maxChannels;
lab_device_info.supported_samplerates.push_back(static_cast<float>(pCaptureDeviceInfos[iDevice].minSampleRate));
lab_device_info.supported_samplerates.push_back(static_cast<float>(pCaptureDeviceInfos[iDevice].maxSampleRate));
lab_device_info.nominal_samplerate = 48000.f; // static_cast<float>(pCaptureDeviceInfos[iDevice].maxSampleRate);
lab_device_info.is_default_output = false;
lab_device_info.is_default_input = iDevice == 0;
g_devices.push_back(lab_device_info);
}
return g_devices;
}
AudioDeviceIndex AudioDevice::GetDefaultOutputAudioDeviceIndex() noexcept
{
auto devices = MakeAudioDeviceList();
size_t c = devices.size();
for (uint32_t i = 0; i < c; ++i)
if (devices[i].is_default_output)
return {i, true};
return {0, false};
}
AudioDeviceIndex AudioDevice::GetDefaultInputAudioDeviceIndex() noexcept
{
auto devices = MakeAudioDeviceList();
size_t c = devices.size();
for (uint32_t i = 0; i < c; ++i)
if (devices[i].is_default_input)
return {i, true};
return {0, false};
}
namespace
{
void outputCallback(ma_device * pDevice, void * pOutput, const void * pInput, ma_uint32 frameCount)
{
// Buffer is nBufferFrames * channels, interleaved
float * fBufOut = (float *) pOutput;
AudioDevice_Miniaudio * ad = reinterpret_cast<AudioDevice_Miniaudio *>(pDevice->pUserData);
memset(fBufOut, 0, sizeof(float) * frameCount * ad->outputConfig.desired_channels);
ad->render(frameCount, pOutput, const_cast<void *>(pInput));
}
}
AudioDevice * AudioDevice::MakePlatformSpecificDevice(AudioDeviceRenderCallback & callback,
const AudioStreamConfig outputConfig, const AudioStreamConfig inputConfig)
{
return new AudioDevice_Miniaudio(callback, outputConfig, inputConfig);
}
AudioDevice_Miniaudio::AudioDevice_Miniaudio(AudioDeviceRenderCallback & callback,
const AudioStreamConfig _outputConfig, const AudioStreamConfig _inputConfig)
: _callback(callback)
, outputConfig(_outputConfig)
, inputConfig(_inputConfig)
{
auto device_list = AudioDevice::MakeAudioDeviceList();
PrintAudioDeviceList();
//ma_device_config deviceConfig = ma_device_config_init(ma_device_type_duplex);
ma_device_config deviceConfig = ma_device_config_init(ma_device_type_playback);
deviceConfig.playback.format = ma_format_f32;
deviceConfig.playback.channels = outputConfig.desired_channels;
deviceConfig.sampleRate = static_cast<int>(outputConfig.desired_samplerate);
deviceConfig.capture.format = ma_format_f32;
deviceConfig.capture.channels = inputConfig.desired_channels;
deviceConfig.dataCallback = outputCallback;
deviceConfig.performanceProfile = ma_performance_profile_low_latency;
deviceConfig.pUserData = this;
#ifdef __WINDOWS_WASAPI__
deviceConfig.wasapi.noAutoConvertSRC = true;
#endif
if (ma_device_init(&g_context, &deviceConfig, &_device) != MA_SUCCESS)
{
LOG_ERROR("Unable to open audio playback device");
return;
}
authoritativeDeviceSampleRateAtRuntime = outputConfig.desired_samplerate;
samplingInfo.epoch[0] = samplingInfo.epoch[1] = std::chrono::high_resolution_clock::now();
_ring = new cinder::RingBufferT<float>();
_ring->resize(static_cast<int>(authoritativeDeviceSampleRateAtRuntime)); // ad hoc. hold one second
_scratch = reinterpret_cast<float *>(malloc(sizeof(float) * kRenderQuantum * inputConfig.desired_channels));
}
AudioDevice_Miniaudio::~AudioDevice_Miniaudio()
{
stop();
ma_device_uninit(&_device);
ma_context_uninit(&g_context);
g_must_init = true;
delete _renderBus;
delete _inputBus;
delete _ring;
if (_scratch)
free(_scratch);
}
void AudioDevice_Miniaudio::backendReinitialize()
{
auto device_list = AudioDevice::MakeAudioDeviceList();
PrintAudioDeviceList();
//ma_device_config deviceConfig = ma_device_config_init(ma_device_type_duplex);
ma_device_config deviceConfig = ma_device_config_init(ma_device_type_playback);
deviceConfig.playback.format = ma_format_f32;
deviceConfig.playback.channels = outputConfig.desired_channels;
deviceConfig.sampleRate = static_cast<int>(outputConfig.desired_samplerate);
deviceConfig.capture.format = ma_format_f32;
deviceConfig.capture.channels = inputConfig.desired_channels;
deviceConfig.dataCallback = outputCallback;
deviceConfig.performanceProfile = ma_performance_profile_low_latency;
deviceConfig.pUserData = this;
#ifdef __WINDOWS_WASAPI__
deviceConfig.wasapi.noAutoConvertSRC = true;
#endif
if (ma_device_init(&g_context, &deviceConfig, &_device) != MA_SUCCESS)
{
LOG_ERROR("Unable to open audio playback device");
return;
}
}
void AudioDevice_Miniaudio::start()
{
ASSERT(authoritativeDeviceSampleRateAtRuntime != 0.f); // something went very wrong
if (ma_device_start(&_device) != MA_SUCCESS)
{
LOG_ERROR("Unable to start audio device");
}
}
void AudioDevice_Miniaudio::stop()
{
if (ma_device_stop(&_device) != MA_SUCCESS)
{
LOG_ERROR("Unable to stop audio device");
}
}
bool AudioDevice_Miniaudio::isRunning() const
{
return ma_device_is_started(&_device);
}
// Pulls on our provider to get rendered audio stream.
void AudioDevice_Miniaudio::render(int numberOfFrames_, void * outputBuffer, void * inputBuffer)
{
int numberOfFrames = numberOfFrames_;
if (!_renderBus)
{
_renderBus = new AudioBus(outputConfig.desired_channels, kRenderQuantum, true);
_renderBus->setSampleRate(authoritativeDeviceSampleRateAtRuntime);
}
if (!_inputBus && inputConfig.desired_channels)
{
_inputBus = new AudioBus(inputConfig.desired_channels, kRenderQuantum, true);
_inputBus->setSampleRate(authoritativeDeviceSampleRateAtRuntime);
}
float * pIn = static_cast<float *>(inputBuffer);
float * pOut = static_cast<float *>(outputBuffer);
int in_channels = inputConfig.desired_channels;
int out_channels = outputConfig.desired_channels;
if (pIn && numberOfFrames * in_channels)
_ring->write(pIn, numberOfFrames * in_channels);
while (numberOfFrames > 0)
{
if (_remainder > 0)
{
// copy samples to output buffer. There might have been some rendered frames
// left over from the previous numberOfFrames, so start by moving those into
// the output buffer.
// miniaudio expects interleaved data, this loop leverages the vclip operation
// to copy, interleave, and clip in one pass.
int samples = _remainder < numberOfFrames ? _remainder : numberOfFrames;
for (int i = 0; i < out_channels; ++i)
{
int src_stride = 1; // de-interleaved
int dst_stride = out_channels; // interleaved
AudioChannel * channel = _renderBus->channel(i);
VectorMath::vclip(channel->data() + kRenderQuantum - _remainder, src_stride,
&kLowThreshold, &kHighThreshold,
pOut + i, dst_stride, samples);
}
pOut += out_channels * samples;
numberOfFrames -= samples; // deduct samples actually copied to output
_remainder -= samples; // deduct samples remaining from last render() invocation
}
else
{
if (in_channels)
{
// miniaudio provides the input data in interleaved form, vclip is used here to de-interleave
_ring->read(_scratch, in_channels * kRenderQuantum);
for (int i = 0; i < in_channels; ++i)
{
int src_stride = in_channels; // interleaved
int dst_stride = 1; // de-interleaved
AudioChannel * channel = _inputBus->channel(i);
VectorMath::vclip(_scratch + i, src_stride,
&kLowThreshold, &kHighThreshold,
channel->mutableData(), dst_stride, kRenderQuantum);
}
}
// Update sampling info for use by the render graph
const int32_t index = 1 - (samplingInfo.current_sample_frame & 1);
const uint64_t t = samplingInfo.current_sample_frame & ~1;
samplingInfo.sampling_rate = authoritativeDeviceSampleRateAtRuntime;
samplingInfo.current_sample_frame = t + kRenderQuantum + index;
samplingInfo.current_time = samplingInfo.current_sample_frame / static_cast<double>(samplingInfo.sampling_rate);
samplingInfo.epoch[index] = std::chrono::high_resolution_clock::now();
// generate new data
_callback.render(_inputBus, _renderBus, kRenderQuantum, samplingInfo);
_remainder = kRenderQuantum;
}
}
}
} // namespace lab
| 37.441734 | 201 | 0.672192 | xioxin |
e40dd9b4b23482132dae1631b2d553188fdb3406 | 2,075 | cpp | C++ | CSC-210/Chapter 4 & 5/C3P3_Credits.cpp | FrancesCoronel/cs-hu | ecd103a525fd312146d3b6c69ee7c1452548c5e2 | [
"MIT"
] | 2 | 2016-12-05T06:15:34.000Z | 2016-12-15T10:56:50.000Z | CSC-210/Chapter 4 & 5/C3P3_Credits.cpp | fvcproductions/CS-HU | ecd103a525fd312146d3b6c69ee7c1452548c5e2 | [
"MIT"
] | null | null | null | CSC-210/Chapter 4 & 5/C3P3_Credits.cpp | fvcproductions/CS-HU | ecd103a525fd312146d3b6c69ee7c1452548c5e2 | [
"MIT"
] | 3 | 2019-04-06T01:45:54.000Z | 2020-04-24T16:55:32.000Z | /*
FVCproductions
1-29-15
In-Class 03 - Part 3
Develop a C++ program that will determine whether a department-store customer has exceeded the credit limit ona charge account.
For each customer, the following facts are available:
(a) Account number (an integer)
(b) Balance at the beginning of the month
(c) Total of all items charged by this
customer this month
(d) Total of all credits applied to this
customer's account this month
(e) Allowed credit limit
The program should use a while statement to input each of these facts,
- calculate the new balance(= beginning balance + charges – credits) and
- determine whether the new balance exceeds the customer’s credit limit.
For those customers whose credit limit is exceeded, the program should display the customer's account number, credit limit, new balance and the message “Credit Limit Exceeded.”
*/
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
double calcBalance(double startBalance, double charges, double credits);
int main ()
{
int accountNumber = 0;
double startBalance;
double charges;
double credits;
double creditLimit;
do
{
cout << "Enter Account Number (or -1 to quit): ";
cin >> accountNumber;
if (accountNumber == -1)
{
break;
}
cout << "Enter beginning balance: ";
cin >> startBalance;
cout << "Enter total charges: ";
cin >> charges;
cout << "Enter total credits: ";
cin >> credits;
cout << "Enter credit limit: ";
cin >> creditLimit;
double newBalance = calcBalance(startBalance, charges, credits);
cout << "New balance is $" << newBalance << endl;
if (newBalance >= creditLimit)
{
cout << "Account: \t" << accountNumber << endl;
cout << "Credit limit: \t" << creditLimit << endl;
cout << "Balance: \t" << newBalance << endl;
cout << "Credit Limit Exceeded." << endl;
}
cout << "\n";
} while (accountNumber != -1);
return 0;
}
double calcBalance(double startBalance, double charges, double credits)
{
return (startBalance + charges) - credits;
}
| 23.314607 | 176 | 0.686747 | FrancesCoronel |
e410b4e798793c61d0895a2d8c7f9213d380578c | 2,242 | cpp | C++ | CCF/CCSP/2017/3-serial/brute.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | 1 | 2019-05-04T10:28:32.000Z | 2019-05-04T10:28:32.000Z | CCF/CCSP/2017/3-serial/brute.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | null | null | null | CCF/CCSP/2017/3-serial/brute.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | 3 | 2020-12-31T04:36:38.000Z | 2021-07-25T07:39:31.000Z | #include <bits/stdc++.h>
using namespace std;
const int N = 20011, M = 20011, E = 40011 * 2 + 1;
int n, m, pcnt, qcnt, pedge, head[M], idx[M];
struct Last {
int id, tk;
} lastW[N];
vector<Last> lastR[N];
struct Edge {
int ver, next;
} edges[E];
priority_queue<int> que;
struct BitSet {
const static int N = M / 32 + 5;
unsigned data[N];
unsigned& operator[](int a) { return data[a]; }
const unsigned& operator[](int a) const { return data[a]; }
bool get(int a) { return (data[a >> 5] >> (a & 31)) & 1; }
void set(int a) { data[a >> 5] |= 1 << (a & 31); }
void unset(int a) { data[a >> 5] &= ~(1 << (a & 31)); }
BitSet& operator|=(const BitSet& a) {
for (int i = 0; i < N; ++i)
data[i] |= a[i];
return *this;
}
} used[M];
void ins(int a, int b) {
if (!a || a == b)
return;
++idx[b];
edges[++pedge] = (Edge){b, head[a]};
head[a] = pedge;
}
void init() {
scanf("%d%d%d%d", &n, &m, &pcnt, &qcnt);
for (int i = 1; i <= pcnt; ++i) {
int op, xk, tk;
scanf("%d%d%d", &op, &xk, &tk);
if (op == 0) {
ins(lastW[xk].tk, tk);
lastR[xk].push_back((Last){i, tk});
} else {
if (!lastR[xk].empty()) {
for (auto i = lastR[xk].begin(); i != lastR[xk].end(); ++i)
ins(i->tk, tk);
lastR[xk].clear();
} else
ins(lastW[xk].tk, tk);
lastW[xk] = (Last){i, tk};
}
}
}
void solve() {
for (int i = 1; i <= m; ++i)
used[i].set(i);
for (int i = 1; i <= m; ++i)
if (!idx[i])
que.push(-i);
for (int i = 1; i <= m; ++i) {
int cur = -que.top();
que.pop();
printf("%d%c", cur, i == m ? '\n' : ' ');
for (int j = head[cur]; j; j = edges[j].next) {
if (!--idx[edges[j].ver])
que.push(-edges[j].ver);
used[edges[j].ver] |= used[cur];
}
}
for (int i = 1; i <= qcnt; ++i) {
int x, y;
scanf("%d%d", &x, &y);
printf("%s\n", !used[x].get(y) ? "YES" : "NO");
}
}
int main() {
init();
solve();
fclose(stdout);
return 0;
} | 22.877551 | 75 | 0.421499 | cnsteven |
e41225ed0d98e9c6a1a0560af664d9b53adf5468 | 16,505 | cpp | C++ | heekscad/src/OrientationModifier.cpp | JohnyEngine/CNC | e4c77250ab2b749d3014022cbb5eb9924e939993 | [
"Apache-2.0"
] | null | null | null | heekscad/src/OrientationModifier.cpp | JohnyEngine/CNC | e4c77250ab2b749d3014022cbb5eb9924e939993 | [
"Apache-2.0"
] | null | null | null | heekscad/src/OrientationModifier.cpp | JohnyEngine/CNC | e4c77250ab2b749d3014022cbb5eb9924e939993 | [
"Apache-2.0"
] | null | null | null |
#include "stdafx.h"
#include "OrientationModifier.h"
#include "../interface/PropertyChoice.h"
#include "../interface/PropertyInt.h"
#include "../interface/PropertyCheck.h"
#include "HeeksConfig.h"
void COrientationModifierParams::set_initial_values()
{
HeeksConfig config;
config.Read(_T("OrientationModifier_m_spacing"), (int *) &m_spacing, int(eNormalSpacing));
config.Read(_T("OrientationModifier_number_of_rotations"), (int *) &m_number_of_rotations, 0);
config.Read(_T("OrientationModifier_sketch_rotates_text"), &m_sketch_rotates_text, false);
config.Read(_T("OrientationModifier_justification"), (int *) &m_justification, int(eLeftJustified));
}
void COrientationModifierParams::write_values_to_config()
{
// We always want to store the parameters in mm and convert them back later on.
HeeksConfig config;
// These values are in mm.
config.Write(_T("OrientationModifier_m_spacing"), (int)m_spacing);
config.Write(_T("OrientationModifier_number_of_rotations"), m_number_of_rotations);
config.Write(_T("OrientationModifier_sketch_rotates_text"), m_sketch_rotates_text);
config.Write(_T("OrientationModifier_justification"), (int)m_justification);
}
static void on_set_justification(int zero_based_choice, HeeksObj* object, bool from_undo_redo)
{
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eJustification_t(zero_based_choice);
if (((COrientationModifier*) object)->SketchIsClosed())
{
switch (zero_based_choice)
{
case 0:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eLeftJustified;
break;
case 1:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eRightJustified;
break;
case 2:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eTopJustified;
break;
case 3:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eBottomJustified;
break;
}
}
else
{
switch (zero_based_choice)
{
case 0:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eLeftJustified;
break;
case 1:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eCentreJustified;
break;
case 2:
((COrientationModifier*)object)->m_params.m_justification = COrientationModifierParams::eRightJustified;
break;
}
}
((COrientationModifier*)object)->m_params.write_values_to_config();
}
static void on_set_spacing(int zero_based_choice, HeeksObj* object, bool from_undo_redo)
{
((COrientationModifier*)object)->m_params.m_spacing = COrientationModifierParams::eSpacing_t(zero_based_choice);
((COrientationModifier*)object)->m_params.write_values_to_config();
}
static void on_set_number_of_rotations(int number_of_rotations, HeeksObj* object)
{
((COrientationModifier*)object)->m_params.m_number_of_rotations = number_of_rotations;
((COrientationModifier*)object)->m_params.write_values_to_config();
}
static void on_set_sketch_rotates_text(bool value, HeeksObj* object)
{
((COrientationModifier*)object)->m_params.m_sketch_rotates_text = value;
((COrientationModifier*)object)->m_params.write_values_to_config();
}
void COrientationModifierParams::GetProperties(COrientationModifier * parent, std::list<Property *> *list)
{
{
int choice = int(m_spacing);
std::list< wxString > choices;
choices.push_back( wxString(_("Normally spaced")) );
list->push_back(new PropertyChoice(_("Spacing"), choices, choice, parent, on_set_spacing));
}
list->push_back(new PropertyInt(_("Number of Rotations (negative for reverse direction)"), m_number_of_rotations, parent, on_set_number_of_rotations));
list->push_back(new PropertyCheck(_("Sketch rotates text"), m_sketch_rotates_text, parent, on_set_sketch_rotates_text));
{
int choice = int(m_justification);
std::list< wxString > choices;
if (parent->SketchIsClosed() == false)
{
choices.push_back( wxString(_("Left")) ); if (m_justification == COrientationModifierParams::eLeftJustified) choice = 0;
choices.push_back( wxString(_("Centre")) ); if (m_justification == COrientationModifierParams::eCentreJustified) choice = 1;
choices.push_back( wxString(_("Right")) ); if (m_justification == COrientationModifierParams::eRightJustified) choice = 2;
}
else
{
choices.push_back( wxString(_("Left")) ); if (m_justification == COrientationModifierParams::eLeftJustified) choice = 0;
choices.push_back( wxString(_("Right")) ); if (m_justification == COrientationModifierParams::eRightJustified) choice = 1;
choices.push_back( wxString(_("Top")) ); if (m_justification == COrientationModifierParams::eTopJustified) choice = 2;
choices.push_back( wxString(_("Bottom")) ); if (m_justification == COrientationModifierParams::eBottomJustified) choice = 3;
}
list->push_back(new PropertyChoice(_("Justification"), choices, choice, parent, on_set_justification));
}
}
bool COrientationModifier::SketchIsClosed()
{
HeeksObj *child = GetFirstChild();
if (child == NULL) return(false);
switch (((CSketch *) child)->m_order)
{
case SketchOrderTypeCloseCW:
case SketchOrderTypeCloseCCW:
case SketchOrderHasCircles:
return(true);
default:
return(false);
} // End switch
}
void COrientationModifierParams::WriteXMLAttributes(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "params" );
root->LinkEndChild( element );
element->SetAttribute("m_spacing", int(m_spacing));
element->SetAttribute("m_number_of_rotations", int(m_number_of_rotations));
element->SetAttribute("m_sketch_rotates_text", m_sketch_rotates_text);
element->SetAttribute("m_justification", int(m_justification));
}
void COrientationModifierParams::ReadParametersFromXMLElement(TiXmlElement* pElem)
{
if (pElem->Attribute("m_spacing")) pElem->Attribute("m_spacing", (int *) &m_spacing);
if (pElem->Attribute("m_number_of_rotations")) pElem->Attribute("m_number_of_rotations", (int *) &m_number_of_rotations);
if (pElem->Attribute("m_sketch_rotates_text"))
{
int flag = 0;
pElem->Attribute("m_sketch_rotates_text", (int *) &flag);
m_sketch_rotates_text = (flag != 0);
}
else
{
m_sketch_rotates_text = false;
}
if (pElem->Attribute("m_justification")) pElem->Attribute("m_justification", (int *) &m_justification);
}
COrientationModifier::COrientationModifier( const COrientationModifier & rhs ) : ObjList(rhs)
{
m_params = rhs.m_params;
}
COrientationModifier & COrientationModifier::operator= ( const COrientationModifier & rhs )
{
if (this != &rhs)
{
m_params = rhs.m_params;
ObjList::operator=(rhs);
}
return(*this);
}
const wxBitmap &COrientationModifier::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/text.png")));
return *icon;
}
void COrientationModifier::glCommands(bool select, bool marked, bool no_color)
{
ObjList::glCommands( select, marked, no_color );
}
HeeksObj *COrientationModifier::MakeACopy(void)const
{
COrientationModifier *new_object = new COrientationModifier(*this);
return(new_object);
}
void COrientationModifier::CopyFrom(const HeeksObj* object)
{
if (object->GetType() == OrientationModifierType)
{
*this = *((COrientationModifier *) object);
}
}
bool COrientationModifier::CanAddTo(HeeksObj* owner)
{
return((owner != NULL) && (owner->GetType() == TextType));
}
bool COrientationModifier::CanAdd(HeeksObj* object)
{
if (object == NULL) return(false);
// We only want a single sketch. Make sure we don't already have one.
if (GetNumChildren() > 0)
{
// Don't popup a warning as this code gets called by the Undo engine
// when the file is initially read in as well.
/*
wxString message;
message << _("Only a single sketch is supported");
wxMessageBox(message);
*/
return(false);
}
switch (object->GetType())
{
case SketchType:
return(true);
default:
return(false);
} // End switch
}
void COrientationModifier::GetProperties(std::list<Property *> *list)
{
m_params.GetProperties( this, list );
ObjList::GetProperties(list);
}
void COrientationModifier::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
ObjList::GetTools( t_list, p );
}
void COrientationModifier::WriteXML(TiXmlNode *root)
{
TiXmlElement * element = new TiXmlElement( "OrientationModifier" );
root->LinkEndChild( element );
m_params.WriteXMLAttributes(element);
WriteBaseXML(element);
}
// static member function
HeeksObj* COrientationModifier::ReadFromXMLElement(TiXmlElement* element)
{
COrientationModifier* new_object = new COrientationModifier();
std::list<TiXmlElement *> elements_to_remove;
// read point and circle ids
for(TiXmlElement* pElem = TiXmlHandle(element).FirstChildElement().Element(); pElem; pElem = pElem->NextSiblingElement())
{
std::string name(pElem->Value());
if(name == "params"){
new_object->m_params.ReadParametersFromXMLElement(pElem);
elements_to_remove.push_back(pElem);
}
}
for (std::list<TiXmlElement*>::iterator itElem = elements_to_remove.begin(); itElem != elements_to_remove.end(); itElem++)
{
element->RemoveChild(*itElem);
}
new_object->ReadBaseXML(element);
return new_object;
}
void COrientationModifier::ReloadPointers()
{
ObjList::ReloadPointers();
}
/**
Accumulate a list of TopoDS_Edge objects along with their lengths. We will use
this repeatedly while we're rendering this text string. We don't want to re-aquire
this information for every point of every character. Cache it here. This method
should be called once before each rendering session for the text string.
*/
void COrientationModifier::InitializeFromSketch()
{
m_edges.clear();
m_total_edge_length = 0.0;
if (GetNumChildren() > 0)
{
std::list<TopoDS_Shape> wires;
if (::ConvertSketchToFaceOrWire( GetFirstChild(), wires, false))
{
// Aggregate a list of TopoDS_Edge objects and each of their lengths. We can
// use this list to skip through edges that we're not interested in. i.e. the
// text won't sit on top of them.
for (std::list<TopoDS_Shape>::iterator itWire = wires.begin(); itWire != wires.end(); itWire++)
{
TopoDS_Wire wire(TopoDS::Wire(*itWire));
for(BRepTools_WireExplorer expEdge(TopoDS::Wire(wire)); expEdge.More(); expEdge.Next())
{
TopoDS_Edge edge(TopoDS_Edge(expEdge.Current()));
BRepAdaptor_Curve curve(edge);
double edge_length = GCPnts_AbscissaPoint::Length(curve);
m_edges.push_back( std::make_pair(edge,edge_length) );
m_total_edge_length += edge_length;
} // End for
} // End for
} // End if - then
} // End if - then
}
/**
take the input point
move it 'distance' back along X
determine the overall sketch length
determine the distance along the sketch for this character based on the distance along the text as well as the justification
find the point along the sketch for this character
find the angle of rotation at this point along the sketch
rotate the point about this character's origin
translate the point to align it with the point along the sketch.
return this adjusted point location.
*/
gp_Pnt & COrientationModifier::Transform(gp_Trsf existing_transformation, const double _distance, gp_Pnt & point, const float width )
{
double tolerance = wxGetApp().m_geom_tol;
gp_Pnt original_location(point);
if (m_edges.size() == 0)
{
// No children so no modification of position.
point = original_location;
return(point);
}
// The text is formatted as though the characters start at the origin (0,0,0) and move
// to the right by the character and/or word spacing as subsequent characters are rendered.
// This step moves this character so that its origin is at the (0,0,0) location so that
// we rotate just this character about its origin. We can use the _distance value as
// the offset along the X axis at which point this character's origin is located.
gp_Pnt origin(0.0, 0.0, 0.0);
gp_Trsf move_to_origin;
move_to_origin.SetTranslation(origin, gp_Pnt(-1.0 * _distance, 0.0, 0.0));
point.Transform(move_to_origin);
// Make sure it's positive.
double distance(_distance);
if (distance < 0) distance *= -1.0;
// Now adjust the distance based on a combination of the justification and how far through
// the text string we are.
double distance_remaining = distance;
switch (m_params.m_justification)
{
case COrientationModifierParams::eLeftJustified:
if (SketchIsClosed())
{
// Centre the text on the left edge. NOTE: This assumes that it's a circle with
// the starting location in the positive X axis.
distance_remaining = (m_total_edge_length / 2.0) - (width / 2.0) + distance;
}
else
{
distance_remaining = distance; // No special adjustment required.
}
break;
case COrientationModifierParams::eRightJustified:
if (SketchIsClosed())
{
distance_remaining = m_total_edge_length - (width / 2.0) + distance;
}
else
{
distance_remaining = m_total_edge_length - width + distance;
}
break;
case COrientationModifierParams::eCentreJustified:
distance_remaining = (m_total_edge_length / 2.0) - (width / 2.0) + distance;
break;
case COrientationModifierParams::eTopJustified:
distance_remaining = (m_total_edge_length / 4.0) - (width / 2.0) + distance;
break;
case COrientationModifierParams::eBottomJustified:
distance_remaining = (m_total_edge_length * 3.0 / 4.0) - (width / 2.0) + distance;
break;
} // End switch
while ((distance_remaining > tolerance) && (m_edges.size() > 0))
{
for (Edges_t::iterator itEdge = m_edges.begin(); itEdge != m_edges.end(); itEdge++)
{
double edge_length = itEdge->second;
if (edge_length < distance_remaining)
{
distance_remaining -= edge_length;
}
else
{
// The point we're after is along this edge somewhere. Find the point and
// the first derivative at that point. The vector returned will allow us to
// find out what angle the sketch is at this point. We can use this angle
// to rotate the character.
BRepAdaptor_Curve curve(itEdge->first);
gp_Pnt p;
gp_Vec vec;
double proportion = distance_remaining / edge_length;
Standard_Real U = ((curve.LastParameter() - curve.FirstParameter()) * proportion) + curve.FirstParameter();
curve.D1(U, p, vec);
double angle = 0.0;
if (m_params.m_sketch_rotates_text)
{
// Measure the angle with respect to the positive X axis (when looking down from the top)
gp_Vec x_axis(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0));
gp_Vec from_top_down( gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(0.0, 0.0, 1.0));
angle = x_axis.AngleWithRef(vec, from_top_down);
}
// If the user wants each character given an extra quarter turn (or more)
// then add this in now.
if (m_params.m_number_of_rotations > 0)
{
for (int i=0; i<m_params.m_number_of_rotations; i++)
{
angle += (M_PI / 2.0);
}
}
else
{
for (int i=m_params.m_number_of_rotations; i<0; i++)
{
angle -= (M_PI / 2.0);
}
}
// Rotate the point around the origin.
angle *= -1.0;
gp_Trsf transformation;
transformation.SetRotation( gp_Ax1(origin, gp_Vec(0,0,-1)), angle );
point.Transform( transformation );
// And then translate the point from the origin to the point along the sketch.
gp_Trsf around;
around.SetTranslation(origin, p);
point.Transform(around);
return(point);
}
} // End for
} // End while
return(point);
}
| 32.173489 | 152 | 0.68864 | JohnyEngine |
e415f963b78d16ab5d2fe0e7607b8bb0e4cfa703 | 77 | cpp | C++ | engine/plyMaker.cpp | heyday665/symmetrical-pancake | 4e3bb710923dc7162d0562185ee9ba76b0c46bf5 | [
"MIT"
] | null | null | null | engine/plyMaker.cpp | heyday665/symmetrical-pancake | 4e3bb710923dc7162d0562185ee9ba76b0c46bf5 | [
"MIT"
] | null | null | null | engine/plyMaker.cpp | heyday665/symmetrical-pancake | 4e3bb710923dc7162d0562185ee9ba76b0c46bf5 | [
"MIT"
] | null | null | null | #include "plyMaker.h"
PLYMAKER::PLYMAKER()
{
}
PLYMAKER::~PLYMAKER()
{
}
| 6.416667 | 21 | 0.623377 | heyday665 |
e418edc7d82c1ae5708e1ad9437358504f09ebe9 | 2,254 | cpp | C++ | libs/MPILib/src/utilities/CircularDistribution.cpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 13 | 2015-09-15T17:28:25.000Z | 2022-03-22T20:26:47.000Z | libs/MPILib/src/utilities/CircularDistribution.cpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 41 | 2015-08-25T07:50:55.000Z | 2022-03-21T16:20:37.000Z | libs/MPILib/src/utilities/CircularDistribution.cpp | dekamps/miind | 4b321c62c2bd27eb0d5d8336a16a9e840ba63856 | [
"MIT"
] | 9 | 2015-09-14T20:52:07.000Z | 2022-03-08T12:18:18.000Z | // Copyright (c) 2005 - 2012 Marc de Kamps
// 2012 David-Matthias Sichau
// 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 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//#include <MPILib/config.hpp>
#include <MPILib/include/utilities/CircularDistribution.hpp>
#include <MPILib/include/utilities/MPIProxy.hpp>
using namespace MPILib::utilities;
CircularDistribution::CircularDistribution() {
}
CircularDistribution::~CircularDistribution() throw(){
}
bool CircularDistribution::isLocalNode(MPILib::NodeId nodeId) const {
return getResponsibleProcessor(nodeId) == utilities::MPIProxy().getRank();
}
int CircularDistribution::getResponsibleProcessor(MPILib::NodeId nodeId) const {
return nodeId % utilities::MPIProxy().getSize();
}
bool CircularDistribution::isMaster() const {
return utilities::MPIProxy().getRank() == 0;
}
| 47.957447 | 162 | 0.777728 | dekamps |
e41c20061d618e55c21ad1e8605c6c1b03dedfb9 | 12,355 | cpp | C++ | source/utility_parse.cpp | DynasticSponge/Frederick2 | 410ad4a3ca43547d645248e13d27497e6c5b5f26 | [
"MIT"
] | null | null | null | source/utility_parse.cpp | DynasticSponge/Frederick2 | 410ad4a3ca43547d645248e13d27497e6c5b5f26 | [
"MIT"
] | null | null | null | source/utility_parse.cpp | DynasticSponge/Frederick2 | 410ad4a3ca43547d645248e13d27497e6c5b5f26 | [
"MIT"
] | null | null | null | //
// utility_parse.cpp
// ~~~~~~~~~~~~~~~~~
//
// Author: Joseph Adomatis
// Copyright (c) 2020 Joseph R Adomatis (joseph dot adomatis at gmail dot com)
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <exception>
#include <sstream>
#include <string>
#include "../headers/frederick2_namespace.hpp"
#include "../headers/utility_parse.hpp"
namespace utility = frederick2::utility;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// global variable definitions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// global function definitions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities member definitions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////
utility::parseUtilities::parseUtilities()
{
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::dqExtract
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::dqExtract(const std::string& original, std::string& revised, bool escape)
{
size_t dqueFoundS{original.find_first_of('\"')};
if(dqueFoundS != std::string::npos)
{
///////////////////////////////////////////////////////////////////////////////
// double quoted string should have DQUOTE as first and last char
///////////////////////////////////////////////////////////////////////////////
size_t dqueFoundE{original.find_last_of('\"')};
if(dqueFoundS != 0 || dqueFoundE != (original.size() - 1))
{
return(false);
}
else
{
///////////////////////////////////////////////////////////////////////////////
// DQUOTE are first and last char
// extract out the string between them
// if escape = true then run the escapeReplace on the extracted string
///////////////////////////////////////////////////////////////////////////////
std::string extractInit{original.substr(1, original.size() - 2)};
if(escape)
{
std::string extractFinal;
this->escapeReplace(extractInit, extractFinal);
revised = std::move(extractFinal);
}
else
{
revised = std::move(extractInit);
}
}
}
else
{
///////////////////////////////////////////////////////////////////////////////
// no DQUOTE found in string.. just set revised = original
///////////////////////////////////////////////////////////////////////////////
revised = original;
}
return(true);
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::escapeReplace
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::escapeReplace(const std::string& original, std::string& revised)
{
std::string bldStr;
size_t maxBound{original.size()};
size_t maxSlashBound{(original.size() - 1)};
for(size_t i = 0; i < maxBound; i++)
{
char c0{original[i]};
if (c0 == '\\')
{
if(i < maxSlashBound)
{
///////////////////////////////////////////////////////////////////////////////
// '\' not the last char
// get next char
///////////////////////////////////////////////////////////////////////////////
char c1{original[i+1]};
bldStr.append(1, c1);
i += 1;
}
else
{
///////////////////////////////////////////////////////////////////////////////
// '\' is last char..
// return false
///////////////////////////////////////////////////////////////////////////////
return(false);
}
}
else
{
///////////////////////////////////////////////////////////////////////////////
// target char isnt a '\'
// just append it to bldStr
///////////////////////////////////////////////////////////////////////////////
bldStr.append(1, c0);
}
}
///////////////////////////////////////////////////////////////////////////////
// move contents of bldStr back into supplied string ref
///////////////////////////////////////////////////////////////////////////////
revised = std::move(bldStr);
return(true);
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::isHex
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::isHex(char c)
{
return((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::pctDecode
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::pctDecode(const std::string& original, std::string& revised)
{
bool returnValue{true};
std::string bldStr;
size_t maxBound{original.size()};
size_t maxHexBound{(original.size() - 2)};
for(size_t i = 0; i < maxBound; i++)
{
char c0{original[i]};
if(c0 == '+')
{
///////////////////////////////////////////////////////////////////////////////
// '+' decodes to space
///////////////////////////////////////////////////////////////////////////////
bldStr.append(1, ' ');
}
else if (c0 == '%')
{
if(i < maxHexBound)
{
///////////////////////////////////////////////////////////////////////////////
// '%' not one of the last two chars
// check next 2 chars to ensure they are potential hex values
///////////////////////////////////////////////////////////////////////////////
char c1{original[i+1]};
char c2{original[i+2]};
if(this->isHex(c1) && this->isHex(c2))
{
///////////////////////////////////////////////////////////////////////////////
// next 2 chars are hex, use stoi base 16 to convert them to int
// then static cast into to unsigned char
///////////////////////////////////////////////////////////////////////////////
unsigned int numVal = std::stoi(original.substr(i+1, 2), 0, 16);
unsigned char outChar{(unsigned char)numVal};
///////////////////////////////////////////////////////////////////////////////
// add decoded char to bldStr
// because the next 2 chars were part of this single encoded char
// manual increment i 2 more spaces to skip evaluating them individually
///////////////////////////////////////////////////////////////////////////////
bldStr.append(1, outChar);
i += 2;
}
else
{
///////////////////////////////////////////////////////////////////////////////
// 1 or both of the chars after '%' was not a hex val
// go ahead and add '%' to bldStr and report invalid URI
///////////////////////////////////////////////////////////////////////////////
returnValue = false;
bldStr.append(1, c0);
}
}
else
{
///////////////////////////////////////////////////////////////////////////////
// '%' is one of the last 2 chars..
// go ahead and add to bldStr and report invalid URI
///////////////////////////////////////////////////////////////////////////////
returnValue = false;
bldStr.append(1, c0);
}
}
else
{
///////////////////////////////////////////////////////////////////////////////
// target char isnt a special character...
// just append it to bldStr
///////////////////////////////////////////////////////////////////////////////
bldStr.append(1, c0);
}
}
///////////////////////////////////////////////////////////////////////////////
// move contents of bldStr back into supplied string ref
///////////////////////////////////////////////////////////////////////////////
revised = std::move(bldStr);
return(returnValue);
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::pctEncode
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::pctEncode(const std::string& original, std::string& revised)
{
bool returnValue{true};
return(returnValue);
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::replace
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::replace(std::string& src, const std::string& sPre, const std::string& sPost)
{
bool returnValue{true};
size_t sPreSize = sPre.size();
size_t sPreFound{src.find(sPre)};
while(sPreFound != std::string::npos)
{
src.replace(sPreFound, sPreSize, sPost);
sPreFound = src.find(sPre);
}
return(returnValue);
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::toHex
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::toHex(const size_t& original, std::string& revised)
{
bool opSuccess{true};
revised.clear();
std::stringstream ss;
ss << std::hex << original;
ss >> revised;
return(opSuccess);
}
///////////////////////////////////////////////////////////////////////////////
// frederick2::utility::parseUtilities::toLower
///////////////////////////////////////////////////////////////////////////////
bool utility::parseUtilities::toLower(const std::string& original, std::string& revised)
{
bool opSuccess{true};
std::string str{original};
try
{
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){return(std::tolower(c));});
}
catch(const std::exception& e)
{
opSuccess = false;
}
if(opSuccess)
{
revised = std::move(str);
}
else
{
revised = original;
}
return(opSuccess);
}
///////////////////////////////////////////////////////////////////////////////
// Deconstructor
///////////////////////////////////////////////////////////////////////////////
utility::parseUtilities::~parseUtilities()
{
} | 38.132716 | 119 | 0.299555 | DynasticSponge |
e4219840a75fd304bcd009ff8726b4b73a3bb05c | 14,312 | cpp | C++ | TVTest_0.7.23_Src/NetworkRemocon.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | TVTest_0.7.23_Src/NetworkRemocon.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | TVTest_0.7.23_Src/NetworkRemocon.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | #include "stdafx.h"
#include "TVTest.h"
#include "AppMain.h"
#include "NetworkRemocon.h"
#include "resource.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#pragma comment(lib,"Ws2_32.lib")
class CSendStringInfo {
public:
CNetworkRemocon *m_pRemocon;
char *m_pBuffer;
int m_Length;
CNetworkRemoconReceiver *m_pReceiver;
CSendStringInfo(CNetworkRemocon *pRemocon,const char *pBuffer,int Length,
CNetworkRemoconReceiver *pReceiver) {
m_pRemocon=pRemocon;
m_pBuffer=new char[Length+1];
CopyMemory(m_pBuffer,pBuffer,Length);
m_pBuffer[Length]='\0';
m_Length=Length;
m_pReceiver=pReceiver;
}
~CSendStringInfo() {
delete [] m_pBuffer;
}
};
CNetworkRemocon::CNetworkRemocon()
{
m_fInitialized=false;
m_Address=INADDR_NONE;
m_Port=0;
m_hThread=NULL;
m_Socket=INVALID_SOCKET;
m_fConnected=false;
}
CNetworkRemocon::~CNetworkRemocon()
{
if (m_fInitialized) {
Shutdown();
WSACleanup();
}
}
bool CNetworkRemocon::Init(LPCSTR pszAddress,WORD Port)
{
int Err;
if (!m_fInitialized) {
Err=WSAStartup(MAKEWORD(2,0),&m_WSAData);
if (Err!=0)
return false;
m_fInitialized=true;
} else {
if (m_Address==inet_addr(pszAddress) && m_Port==Port)
return true;
Shutdown();
}
m_Address=inet_addr(pszAddress);
if (m_Address==INADDR_NONE)
return false;
m_Port=Port;
return true;
}
bool CNetworkRemocon::Shutdown()
{
if (m_fInitialized) {
if (m_hThread!=NULL) {
if (WaitForSingleObject(m_hThread,5000)==WAIT_TIMEOUT)
TerminateThread(m_hThread,FALSE);
CloseHandle(m_hThread);
m_hThread=NULL;
}
if (m_Socket!=INVALID_SOCKET) {
shutdown(m_Socket,1);
closesocket(m_Socket);
m_Socket=INVALID_SOCKET;
}
}
return true;
}
DWORD CNetworkRemocon::SendProc(LPVOID pParam)
{
CSendStringInfo *pInfo=(CSendStringInfo*)pParam;
int Result;
char Buffer[4096];
if (pInfo->m_pRemocon->m_Socket==INVALID_SOCKET) {
pInfo->m_pRemocon->m_Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (pInfo->m_pRemocon->m_Socket==INVALID_SOCKET)
return FALSE;
}
if (!pInfo->m_pRemocon->m_fConnected) {
struct sockaddr_in sockaddri;
sockaddri.sin_family=AF_INET;
sockaddri.sin_port=htons(pInfo->m_pRemocon->m_Port);
sockaddri.sin_addr.S_un.S_addr=pInfo->m_pRemocon->m_Address;
ZeroMemory(sockaddri.sin_zero,sizeof(sockaddri.sin_zero));
Result=connect(pInfo->m_pRemocon->m_Socket,
(struct sockaddr*)&sockaddri,sizeof(sockaddr_in));
if (Result!=0) {
delete pInfo;
return FALSE;
}
pInfo->m_pRemocon->m_fConnected=true;
}
Result=send(pInfo->m_pRemocon->m_Socket,pInfo->m_pBuffer,pInfo->m_Length,0);
if (Result==SOCKET_ERROR) {
closesocket(pInfo->m_pRemocon->m_Socket);
pInfo->m_pRemocon->m_Socket=INVALID_SOCKET;
pInfo->m_pRemocon->m_fConnected=false;
return FALSE;
}
Result=recv(pInfo->m_pRemocon->m_Socket,Buffer,sizeof(Buffer)-1,0);
if (Result!=SOCKET_ERROR && pInfo->m_pReceiver!=NULL) {
Buffer[Result]='\0';
pInfo->m_pReceiver->OnReceive(Buffer);
}
if (Result==SOCKET_ERROR || Result==0) {
closesocket(pInfo->m_pRemocon->m_Socket);
pInfo->m_pRemocon->m_Socket=INVALID_SOCKET;
pInfo->m_pRemocon->m_fConnected=false;
delete pInfo;
return Result==SOCKET_ERROR;
}
delete pInfo;
return TRUE;
}
bool CNetworkRemocon::Send(const char *pBuffer,int Length,
CNetworkRemoconReceiver *pReceiver)
{
DWORD ThreadID;
CSendStringInfo *pInfo;
if (!m_fInitialized)
return false;
if (m_hThread!=NULL) {
if (WaitForSingleObject(m_hThread,0)==WAIT_TIMEOUT)
return false;
CloseHandle(m_hThread);
}
pInfo=new CSendStringInfo(this,pBuffer,Length,pReceiver);
m_hThread=CreateThread(NULL,0,SendProc,pInfo,0,&ThreadID);
if (m_hThread==NULL) {
delete pInfo;
return false;
}
return true;
}
bool CNetworkRemocon::SetChannel(int ChannelNo)
{
char szText[16];
int Length;
if (m_ChannelList.NumChannels()>0) {
int i;
for (i=0;i<m_ChannelList.NumChannels();i++) {
if (m_ChannelList.GetChannelNo(i)==ChannelNo+1) {
Length=wsprintfA(szText,"SetCh:%d",i);
return Send(szText,Length);
}
}
} else {
Length=wsprintfA(szText,"SetCh:%d",ChannelNo);
return Send(szText,Length);
}
return false;
}
class CGetChannelReceiver : public CNetworkRemoconReceiver {
public:
CNetworkRemoconReceiver *m_pReceiver;
void OnReceive(LPCSTR pszText);
};
void CGetChannelReceiver::OnReceive(LPCSTR pszText)
{
LPCSTR p;
char szChannel[16];
int i;
p=pszText;
while (*p!='\t') {
if (*p=='\0')
return;
p++;
}
p++;
for (i=0;*p>='0' && *p<='9';i++) {
if (i==sizeof(szChannel))
return;
szChannel[i]=*p++;
}
if (i==0)
return;
szChannel[i]='\0';
m_pReceiver->OnReceive(szChannel);
}
bool CNetworkRemocon::GetChannel(CNetworkRemoconReceiver *pReceiver)
{
static CGetChannelReceiver Receiver;
Receiver.m_pReceiver=pReceiver;
return Send("GetChList",9,&Receiver);
}
bool CNetworkRemocon::SetService(int Service)
{
char szText[16];
int Length;
Length=wsprintfA(szText,"SetService:%d",Service);
return Send(szText,Length);
}
bool CNetworkRemocon::GetDriverList(CNetworkRemoconReceiver *pReceiver)
{
return Send("GetBonList",10,pReceiver);
}
bool CNetworkRemocon::LoadChannelText(LPCTSTR pszFileName,
const CChannelList *pChannelList)
{
HANDLE hFile;
DWORD FileSize,Read;
char *pszText,*p;
hFile=CreateFile(pszFileName,GENERIC_READ,FILE_SHARE_READ,NULL,
OPEN_EXISTING,0,NULL);
if (hFile==INVALID_HANDLE_VALUE)
return false;
FileSize=GetFileSize(hFile,NULL);
if (FileSize==INVALID_FILE_SIZE || FileSize==0) {
CloseHandle(hFile);
return false;
}
pszText=new char[FileSize+1];
if (!ReadFile(hFile,pszText,FileSize,&Read,NULL) || Read!=FileSize) {
CloseHandle(hFile);
return false;
}
pszText[FileSize]='\0';
CloseHandle(hFile);
m_ChannelList.Clear();
p=pszText;
while (*p!='\0') {
char *pszName;
int Space,Channel;
while (*p=='\r' || *p=='\n')
p++;
if (*p==';') { // Comment
while (*p!='\r' && *p!='\n' && *p!='\0')
p++;
continue;
}
pszName=p;
while (*p!='\t' && *p!='\0')
p++;
if (*p=='\0')
break;
*p++='\0';
Space=0;
while (*p>='0' && *p<='9') {
Space=Space*10+(*p-'0');
p++;
}
if (*p!='\t')
break;
p++;
Channel=0;
while (*p>='0' && *p<='9') {
Channel=Channel*10+(*p-'0');
p++;
}
int i;
for (i=0;i<pChannelList->NumChannels();i++) {
const CChannelInfo *pChInfo=pChannelList->GetChannelInfo(i);
if (pChInfo->GetSpace()==Space && pChInfo->GetChannelIndex()==Channel) {
m_ChannelList.AddChannel(*pChInfo);
break;
}
}
if (i==pChannelList->NumChannels()) {
TCHAR szName[MAX_CHANNEL_NAME];
MultiByteToWideChar(CP_ACP,0,pszName,-1,szName,MAX_CHANNEL_NAME);
m_ChannelList.AddChannel(
CChannelInfo(Space,Channel,
pChannelList->NumChannels()==0?m_ChannelList.NumChannels()+1:Channel+1,
szName));
}
while (*p!='\r' && *p!='\n' && *p!='\0')
p++;
}
delete [] pszText;
return true;
}
CNetworkRemoconOptions::CNetworkRemoconOptions()
{
m_fUseNetworkRemocon=false;
::lstrcpyA(m_szAddress,"127.0.0.1");
m_Port=1334;
m_szChannelFileName[0]='\0';
m_szDefaultChannelFileName[0]='\0';
m_fTempEnable=false;
m_TempPort=0;
}
CNetworkRemoconOptions::~CNetworkRemoconOptions()
{
Destroy();
}
bool CNetworkRemoconOptions::ReadSettings(CSettings &Settings)
{
TCHAR szText[16];
Settings.Read(TEXT("UseNetworkRemocon"),&m_fUseNetworkRemocon);
if (Settings.Read(TEXT("NetworkRemoconAddress"),szText,lengthof(szText)))
::WideCharToMultiByte(CP_ACP,0,szText,-1,
m_szAddress,lengthof(m_szAddress),NULL,NULL);
Settings.Read(TEXT("NetworkRemoconPort"),&m_Port);
Settings.Read(TEXT("NetworkRemoconChFile"),
m_szChannelFileName,lengthof(m_szChannelFileName));
return true;
}
bool CNetworkRemoconOptions::WriteSettings(CSettings &Settings)
{
Settings.Write(TEXT("UseNetworkRemocon"),m_fUseNetworkRemocon);
WCHAR szAddress[16];
::MultiByteToWideChar(CP_ACP,0,m_szAddress,-1,szAddress,lengthof(szAddress));
Settings.Write(TEXT("NetworkRemoconAddress"),szAddress);
Settings.Write(TEXT("NetworkRemoconPort"),m_Port);
Settings.Write(TEXT("NetworkRemoconChFile"),m_szChannelFileName);
return true;
}
bool CNetworkRemoconOptions::Create(HWND hwndOwner)
{
return CreateDialogWindow(hwndOwner,
GetAppClass().GetResourceInstance(),MAKEINTRESOURCE(IDD_OPTIONS_NETWORKREMOCON));
}
bool CNetworkRemoconOptions::SetTempEnable(bool fEnable)
{
m_fTempEnable=fEnable;
return true;
}
bool CNetworkRemoconOptions::SetTempPort(unsigned int Port)
{
if (m_fUseNetworkRemocon || m_fTempEnable)
m_TempPort=Port;
return true;
}
bool CNetworkRemoconOptions::SetDefaultChannelFileName(LPCTSTR pszFileName)
{
::lstrcpy(m_szDefaultChannelFileName,pszFileName);
return true;
}
bool CNetworkRemoconOptions::IsEnable() const
{
return m_fUseNetworkRemocon || m_fTempEnable;
}
bool CNetworkRemoconOptions::IsSettingValid() const
{
return m_Port>0;
}
bool CNetworkRemoconOptions::CreateNetworkRemocon(CNetworkRemocon **ppNetworkRemocon)
{
*ppNetworkRemocon=new CNetworkRemocon;
if (!(*ppNetworkRemocon)->Init(m_szAddress,m_TempPort>0?m_TempPort:m_Port)) {
delete *ppNetworkRemocon;
*ppNetworkRemocon=NULL;
}
return true;
}
bool CNetworkRemoconOptions::InitNetworkRemocon(CNetworkRemocon **ppNetworkRemocon,
const CCoreEngine *pCoreEngine,CChannelManager *pChannelManager) const
{
if ((m_fUseNetworkRemocon || m_fTempEnable)
&& pCoreEngine->IsNetworkDriver()) {
TCHAR szChannelFile[MAX_PATH];
if (!GetChannelFilePath(szChannelFile))
return false;
if (*ppNetworkRemocon==NULL)
*ppNetworkRemocon=new CNetworkRemocon;
if ((*ppNetworkRemocon)->LoadChannelText(szChannelFile,
pChannelManager->GetFileAllChannelList())) {
pChannelManager->SetNetworkRemoconMode(true,
&(*ppNetworkRemocon)->GetChannelList());
pChannelManager->SetNetworkRemoconCurrentChannel(-1);
}
(*ppNetworkRemocon)->Init(m_szAddress,m_TempPort>0?m_TempPort:m_Port);
} else {
if (*ppNetworkRemocon!=NULL) {
delete *ppNetworkRemocon;
*ppNetworkRemocon=NULL;
}
}
return true;
}
bool CNetworkRemoconOptions::FindChannelFile(LPCTSTR pszDriverName,LPTSTR pszFileName) const
{
TCHAR szMask[MAX_PATH];
HANDLE hFind;
WIN32_FIND_DATA wfd;
::SHGetSpecialFolderPath(NULL,szMask,CSIDL_PERSONAL,FALSE);
::PathAppend(szMask,TEXT("EpgTimerBon\\*(*).ChSet.txt"));
hFind=::FindFirstFile(szMask,&wfd);
if (hFind==INVALID_HANDLE_VALUE)
return false;
bool fFound=false;
do {
LPCTSTR p;
TCHAR szName[MAX_PATH];
int i;
p=wfd.cFileName;
while (*p!='(')
p++;
p++;
for (i=0;*p!=')';i++)
szName[i]=*p++;
szName[i]='\0';
if (::lstrcmpi(szName,pszDriverName)==0) {
::lstrcpy(pszFileName,wfd.cFileName);
fFound=true;
break;
}
} while (::FindNextFile(hFind,&wfd));
::FindClose(hFind);
return fFound;
}
bool CNetworkRemoconOptions::GetChannelFilePath(LPTSTR pszPath) const
{
if (m_szChannelFileName[0]=='\0' || ::PathIsFileSpec(m_szChannelFileName)) {
::SHGetSpecialFolderPath(NULL,pszPath,CSIDL_PERSONAL,FALSE);
::PathAppend(pszPath,TEXT("EpgTimerBon"));
if (m_szChannelFileName[0]!='\0') {
::PathAppend(pszPath,m_szChannelFileName);
} else if (m_szDefaultChannelFileName[0]!='\0') {
::PathAppend(pszPath,m_szDefaultChannelFileName);
} else {
TCHAR szMask[MAX_PATH];
HANDLE hFind;
WIN32_FIND_DATA fd;
::lstrcpy(szMask,pszPath);
::PathAppend(szMask,TEXT("BonDriver_*(*).ChSet.txt"));
hFind=::FindFirstFile(szMask,&fd);
if (hFind==INVALID_HANDLE_VALUE)
return false;
::FindClose(hFind);
::PathAppend(pszPath,fd.cFileName);
}
} else {
::lstrcpy(pszPath,m_szChannelFileName);
}
return true;
}
INT_PTR CNetworkRemoconOptions::DlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch (uMsg) {
case WM_INITDIALOG:
{
::CheckDlgButton(hDlg,IDC_NETWORKREMOCON_USE,
m_fUseNetworkRemocon?BST_CHECKED:
m_fTempEnable?BST_INDETERMINATE:BST_UNCHECKED);
::SetDlgItemTextA(hDlg,IDC_NETWORKREMOCON_ADDRESS,m_szAddress);
::SetDlgItemInt(hDlg,IDC_NETWORKREMOCON_PORT,m_Port,FALSE);
{
TCHAR szFileMask[MAX_PATH];
HANDLE hFind;
WIN32_FIND_DATA wfd;
::SendDlgItemMessage(hDlg,IDC_NETWORKREMOCON_CHANNELFILE,CB_LIMITTEXT,MAX_PATH-1,0);
::SHGetSpecialFolderPath(NULL,szFileMask,CSIDL_PERSONAL,FALSE);
::PathAppend(szFileMask,TEXT("EpgTimerBon\\*(*).ChSet.txt"));
hFind=::FindFirstFile(szFileMask,&wfd);
if (hFind!=INVALID_HANDLE_VALUE) {
do {
::SendDlgItemMessage(hDlg,IDC_NETWORKREMOCON_CHANNELFILE,
CB_ADDSTRING,0,
reinterpret_cast<LPARAM>(wfd.cFileName));
} while (::FindNextFile(hFind,&wfd));
::FindClose(hFind);
}
::SetDlgItemText(hDlg,IDC_NETWORKREMOCON_CHANNELFILE,m_szChannelFileName);
}
}
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_NETWORKREMOCON_USE:
::CheckDlgButton(hDlg,IDC_NETWORKREMOCON_USE,
::IsDlgButtonChecked(hDlg,IDC_NETWORKREMOCON_USE)==BST_CHECKED?
BST_UNCHECKED:BST_CHECKED);
return TRUE;
}
return TRUE;
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code) {
case PSN_APPLY:
{
int State;
char szAddress[16];
unsigned int Port;
TCHAR szChannelFile[MAX_PATH];
State=::IsDlgButtonChecked(hDlg,IDC_NETWORKREMOCON_USE);
::GetDlgItemTextA(hDlg,IDC_NETWORKREMOCON_ADDRESS,szAddress,
lengthof(szAddress));
Port=::GetDlgItemInt(hDlg,IDC_NETWORKREMOCON_PORT,NULL,FALSE);
::GetDlgItemText(hDlg,IDC_NETWORKREMOCON_CHANNELFILE,
szChannelFile,lengthof(szChannelFile));
bool fUpdate=false;
if (State!=BST_INDETERMINATE
&& (State==BST_CHECKED)!=(m_fUseNetworkRemocon || m_fTempEnable)) {
m_fUseNetworkRemocon=State==BST_CHECKED;
m_fTempEnable=false;
fUpdate=true;
} else if (m_fUseNetworkRemocon || m_fTempEnable) {
if (m_Port!=Port
|| ::lstrcmpiA(m_szAddress,szAddress)!=0
|| ::lstrcmpi(m_szChannelFileName,szChannelFile)!=0) {
fUpdate=true;
}
}
m_Port=Port;
::lstrcpyA(m_szAddress,szAddress);
::lstrcpy(m_szChannelFileName,szChannelFile);
if (fUpdate)
SetUpdateFlag(UPDATE_NETWORKREMOCON);
m_fChanged=true;
}
return TRUE;
}
break;
}
return FALSE;
}
| 23.462295 | 92 | 0.712759 | mark10als |
e424c4bbe7e1da7cd4fc349e2cca6f7099b9ad70 | 11,594 | cpp | C++ | src/proposal.cpp | OpenIKEv2/libopenikev2 | 9d91225e5917cbc9afc83db37dfe4905c5501d01 | [
"Apache-2.0"
] | 7 | 2017-02-27T17:52:26.000Z | 2021-12-15T06:03:26.000Z | src/proposal.cpp | David-WL/libopenikev2 | 9d91225e5917cbc9afc83db37dfe4905c5501d01 | [
"Apache-2.0"
] | 5 | 2017-03-02T20:16:41.000Z | 2017-11-04T08:23:13.000Z | src/proposal.cpp | David-WL/libopenikev2 | 9d91225e5917cbc9afc83db37dfe4905c5501d01 | [
"Apache-2.0"
] | 3 | 2017-04-12T00:25:25.000Z | 2021-09-23T09:13:27.000Z | /***************************************************************************
* Copyright (C) 2005 by *
* Pedro J. Fernandez Ruiz pedroj@um.es *
* Alejandro Perez Mendez alex@um.es *
* *
* This software may be modified and distributed under the terms *
* of the Apache license. See the LICENSE file for details. *
***************************************************************************/
#include "proposal.h"
#include "utils.h"
#include "exception.h"
#include <string.h>
namespace openikev2 {
Proposal::Proposal( Enums::PROTOCOL_ID protocol_id ) {
// assigns the proposal number
this->proposal_number = 0;
// Assigns protocol id
this->protocol_id = protocol_id;
// The SPI value is 0-length until it was assigned using setIkeSpi() or setIpsecSpi()
if ( protocol_id == Enums::PROTO_IKE ) {
this->spi.reset ( new ByteArray( 8 ) );
}
else if ( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP ) {
this->spi.reset ( new ByteArray( 4 ) );
}
else
assert( 0 );
}
Proposal::Proposal( Enums::PROTOCOL_ID protocol_id, auto_ptr<ByteArray> spi ) {
// Checks if spi size agrees with protocol id
if ( protocol_id == Enums::PROTO_IKE && spi->size() != 8 && spi->size() != 0 )
throw ParsingException( "Proposal and SPI size don't match." );
else if ( ( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP ) && spi->size() != 4 )
throw ParsingException( "Proposal and SPI size don't match." );
this->protocol_id = protocol_id;
this->spi = spi;
this->proposal_number = 0;
}
auto_ptr<Proposal> Proposal::parse( ByteBuffer& byte_buffer ) {
// Pointer to the begin of the Proposal
uint8_t * proposal_begin = byte_buffer.getReadPosition() - 2;
// reads the proposal length
uint32_t proposal_length = byte_buffer.readInt16();
// Size must be at least size of fixed header
if ( proposal_length < 8 )
throw ParsingException( "Proposal length cannot be < 8 bytes. len=[" + intToString( proposal_length ) + "]" );
// reads the proposal number
uint8_t proposal_number = byte_buffer.readInt8();
if ( proposal_number == 0 )
throw ParsingException( "Proposal number cannot be 0" );
// Reads protocol id from buffer
Enums::PROTOCOL_ID protocol_id = ( Enums::PROTOCOL_ID ) byte_buffer.readInt8();
// Reads spi size from buffer
uint8_t spi_size = byte_buffer.readInt8();
// Reads transform count
uint8_t transform_count = byte_buffer.readInt8();
// Reads spi value and stores it in the internal variable
auto_ptr<ByteArray> spi = byte_buffer.readByteArray( spi_size );
// Creates the Proposal
auto_ptr<Proposal> result ( new Proposal( protocol_id, spi ) );
result->proposal_number = proposal_number;
// Reads transforms from buffer
for ( int i = 0; i < transform_count; i++ ) {
// reads has more transforms byte
uint8_t has_more_transforms = byte_buffer.readInt8();
// Checks if this is the last transform
if ( i == transform_count - 1 && has_more_transforms )
throw ParsingException( "Transform count field is lower than real transform number." );
if ( i < transform_count - 1 && !has_more_transforms )
throw ParsingException( "Transform count field is higher than real transform number." );
// reads RESERVED byte
byte_buffer.readInt8();
// Reads Transform and adds to the collection (without fixed header of size 4)
auto_ptr<Transform> transform = Transform::parse( byte_buffer );
// adds this transform the the transform collection
result->addTransform( transform );
}
// checks the size
if ( byte_buffer.getReadPosition() != proposal_begin + proposal_length )
throw ParsingException( "Proposal has different length than indicated in the header" );
return result;
}
Proposal::~Proposal() {}
auto_ptr<Proposal> Proposal::clone() const {
auto_ptr<Proposal> result ( new Proposal( this->protocol_id ) );
result->spi = this->spi->clone();
for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ )
result->addTransform( ( *it ) ->clone() );
return result;
}
void Proposal::addTransform( auto_ptr<Transform> transform ) {
assert ( transform.get() != NULL );
switch ( this->protocol_id ) {
case Enums::PROTO_AH:
if ( transform->type == Enums::ENCR )
throw ProposalException( "AH protocol has ENCR transform" );
if ( transform->type == Enums::PRF )
throw ProposalException( "AH protocol has PRF transform" );
break;
case Enums::PROTO_ESP:
if ( transform->type == Enums::PRF )
throw ProposalException( "ESP protocol has PRF transform" );
break;
case Enums::PROTO_IKE:
if ( transform->type == Enums::ESN )
throw ProposalException( "IKE protocol has ESN transform" );
break;
}
this->transforms->push_back( transform.release() );
}
void Proposal::getBinaryRepresentation( ByteBuffer& byte_buffer ) const {
// ASSERT: transform count must fits in uint8_t (octet)
assert( this->transforms->size() > 0 && this->transforms->size() < 256 );
// pointer to the beginning of the proposal
uint8_t* proposal_begin = byte_buffer.getWritePosition();
// writes a dummy value for the proposal length
byte_buffer.writeInt16( 0 );
// writes the proposal number
byte_buffer.writeInt8( this->proposal_number );
// Writes protocol id
byte_buffer.writeInt8( this->protocol_id );
// Writes spi size
byte_buffer.writeInt8( this->spi->size() );
// Writes transform count
byte_buffer.writeInt8( this->transforms->size() );
// Writes spi value
byte_buffer.writeByteArray( *this->spi );
// Writes each transform in the collection
for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) {
// Writes last transform flags (0=last, 3=more)
if ( *it == this->transforms->back() )
byte_buffer.writeInt8( 0 );
else
byte_buffer.writeInt8( 3 );
// Fills RESERVED field with 0s
byte_buffer.writeInt8( 0 );
// Writes transform
( *it ) ->getBinaryRepresentation( byte_buffer );
}
// pointer to the end of the proposal
uint8_t* proposal_end = byte_buffer.getWritePosition();
// writes the real proposal length value
byte_buffer.setWritePosition( proposal_begin );
byte_buffer.writeInt16( proposal_end - proposal_begin + 2 );
byte_buffer.setWritePosition( proposal_end );
}
Transform * Proposal::getFirstTransformByType( Enums::TRANSFORM_TYPE type ) const {
for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ )
if ( ( *it ) ->type == type )
return ( *it );
return NULL;
}
string Proposal::toStringTab( uint8_t tabs ) const {
ostringstream oss;
oss << Printable::generateTabs( tabs ) << "<PROPOSAL> {\n";
oss << Printable::generateTabs( tabs + 1 ) << "proposal_number=" << ( int ) proposal_number << "\n";
oss << Printable::generateTabs( tabs + 1 ) << "protocol_id=" << Enums::PROTOCOL_ID_STR( this->protocol_id ) << "\n";
oss << Printable::generateTabs( tabs + 1 ) << "spi=" << this->spi->toStringTab( tabs + 1 ) + "\n";
for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ )
oss << ( *it ) ->toStringTab( tabs + 1 );
oss << Printable::generateTabs( tabs ) << "}\n";
return oss.str();
}
void Proposal::deleteTransformsByType( Enums::TRANSFORM_TYPE type ) {
vector<Transform*>::iterator it = this->transforms->begin();
while ( it != this->transforms->end() ) {
if ( ( *it ) ->type == type ) {
delete ( *it );
it = this->transforms->erase( it );
}
else {
it++;
}
}
}
bool Proposal::hasTransform( const Transform & transform ) const {
for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) {
Transform* current_transform = ( *it );
if ( *current_transform == transform )
return true;
}
return false;
}
auto_ptr< Proposal > Proposal::intersection( const Proposal & proposal1, const Proposal & proposal2 ) {
assert ( proposal1.protocol_id == proposal2.protocol_id );
auto_ptr<Proposal> result ( new Proposal( proposal1.protocol_id ) );
result->spi = proposal1.spi->clone();
// for all the transform in the proposal1
for ( vector<Transform*>::const_iterator it = proposal1.transforms->begin(); it != proposal1.transforms->end(); it++ ) {
Transform* current_transform = ( *it );
// if the proposal2 has the same transform type and id, then adds it to the result
if ( proposal2.hasTransform( *current_transform ) )
result->addTransform( current_transform->clone() );
}
return result;
}
bool Proposal::hasTheSameTransformTypes( const Proposal & other ) const {
for ( vector<Transform*>::const_iterator it = this->transforms->begin(); it != this->transforms->end(); it++ ) {
Transform* current_transform = ( *it );
if ( other.getFirstTransformByType( current_transform->type ) == NULL )
return false;
}
return true;
}
void Proposal::setIkeSpi( uint64_t spi ) {
assert ( protocol_id == Enums::PROTO_IKE );
this->spi.reset ( new ByteArray( &spi, 8 ) );
}
void Proposal::setIpsecSpi( uint32_t spi ) {
assert( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP );
auto_ptr<ByteBuffer> spi_value ( new ByteBuffer( 4 ) );
spi_value->writeInt32( spi );
this->spi = spi_value;
}
uint64_t Proposal::getIkeSpi( ) {
assert ( protocol_id == Enums::PROTO_IKE );
assert ( this->spi->size() == 8 );
uint64_t spi = 0;
memcpy( &spi, this->spi->getRawPointer(), 8 );
return spi;
}
uint32_t Proposal::getIpsecSpi( ) {
assert( protocol_id == Enums::PROTO_AH || protocol_id == Enums::PROTO_ESP );
assert ( this->spi->size() == 4 );
uint32_t spi = 0;
ByteBuffer spi_value ( *this->spi );
return spi_value.readInt32();
}
}
| 36.574132 | 128 | 0.568829 | OpenIKEv2 |
e4255dbc4c4cc6663e965218e9e9126f37c2c60c | 13,319 | cpp | C++ | PongCommon/PlayerSlot.cpp | Higami69/Leviathan | 90f68f9f6e5506d6133bcefcf35c8e84f158483b | [
"BSL-1.0"
] | 16 | 2018-12-22T02:09:05.000Z | 2022-03-09T20:38:59.000Z | PongCommon/PlayerSlot.cpp | Higami69/Leviathan | 90f68f9f6e5506d6133bcefcf35c8e84f158483b | [
"BSL-1.0"
] | 46 | 2018-04-02T11:06:01.000Z | 2019-12-14T11:16:04.000Z | PongCommon/PlayerSlot.cpp | Higami69/Leviathan | 90f68f9f6e5506d6133bcefcf35c8e84f158483b | [
"BSL-1.0"
] | 14 | 2018-04-09T02:26:15.000Z | 2021-09-11T03:12:15.000Z | // ------------------------------------ //
#ifndef PONG_PLAYERSLOT
#include "PlayerSlot.h"
#endif
#include "Iterators/StringIterator.h"
#include "Networking/NetworkServerInterface.h"
#include "Utility/ComplainOnce.h"
#include "Entities/Components.h"
#include "CommonPong.h"
#ifdef PONG_VERSION
#include "PongGame.h"
#include "PongNetHandler.h"
#endif //PONG_VERSION
#include "GameInputController.h"
using namespace Pong;
using namespace Leviathan;
// ------------------------------------ //
Pong::PlayerSlot::PlayerSlot(int slotnumber, PlayerList* owner) :
Slot(slotnumber), PlayerType(PLAYERTYPE_CLOSED), PlayerNumber(0), ControlType(PLAYERCONTROLS_NONE),
ControlIdentifier(0), PlayerControllerID(0), Colour(Float4::GetColourWhite()), Score(0),
MoveState(0), PaddleObject(0), GoalAreaObject(0), TrackObject(0), SplitSlot(nullptr),
ParentSlot(nullptr), InputObj(nullptr), SlotsPlayer(NULL), PlayerID(-1), NetworkedInputID(-1),
Parent(owner)
{
}
Pong::PlayerSlot::~PlayerSlot(){
_ResetNetworkInput();
SAFE_DELETE(SplitSlot);
}
// ------------------------------------ //
void Pong::PlayerSlot::Init(PLAYERTYPE type /*= PLAYERTYPE_EMPTY*/, int PlayerNumber /*= 0*/,
PLAYERCONTROLS controltype /*= PLAYERCONTROLS_NONE*/, int ctrlidentifier /*= 0*/, int playercontrollerid /*= -1*/,
const Float4 &playercolour /*= Float4::GetColourWhite()*/)
{
PlayerType = type;
PlayerNumber = PlayerNumber;
ControlType = controltype;
ControlIdentifier = ctrlidentifier;
Colour = playercolour;
PlayerControllerID = playercontrollerid;
}
// ------------------------------------ //
void Pong::PlayerSlot::SetPlayer(PLAYERTYPE type, int identifier){
PlayerType = type;
PlayerNumber = identifier;
}
Pong::PLAYERTYPE Pong::PlayerSlot::GetPlayerType(){
return PlayerType;
}
int Pong::PlayerSlot::GetPlayerNumber(){
return PlayerNumber;
}
// ------------------------------------ //
void Pong::PlayerSlot::SetControls(PLAYERCONTROLS type, int identifier){
ControlType = type;
ControlIdentifier = identifier;
}
Pong::PLAYERCONTROLS Pong::PlayerSlot::GetControlType(){
return ControlType;
}
int Pong::PlayerSlot::GetControlIdentifier(){
return ControlIdentifier;
}
// ------------------------------------ //
int Pong::PlayerSlot::GetSlotNumber(){
return Slot;
}
// ------------------------------------ //
int Pong::PlayerSlot::GetSplitCount(){
return SplitSlot != NULL ? 1+SplitSlot->GetSplitCount(): 0;
}
void Pong::PlayerSlot::PassInputAction(CONTROLKEYACTION actiontoperform, bool active){
GUARD_LOCK();
// if this is player 0 or 3 flip inputs //
if(Slot == 0 || Slot == 2){
switch(actiontoperform){
case CONTROLKEYACTION_LEFT: actiontoperform = CONTROLKEYACTION_POWERUPUP; break;
case CONTROLKEYACTION_POWERUPDOWN: actiontoperform = CONTROLKEYACTION_RIGHT; break;
case CONTROLKEYACTION_RIGHT: actiontoperform = CONTROLKEYACTION_POWERUPDOWN; break;
case CONTROLKEYACTION_POWERUPUP: actiontoperform = CONTROLKEYACTION_LEFT; break;
}
}
// set control state //
if(active){
if(actiontoperform == CONTROLKEYACTION_LEFT){
MoveState = 1;
} else if(actiontoperform == CONTROLKEYACTION_RIGHT){
MoveState = -1;
}
} else {
if(actiontoperform == CONTROLKEYACTION_LEFT && MoveState == 1){
MoveState = 0;
} else if(actiontoperform == CONTROLKEYACTION_RIGHT && MoveState == -1){
MoveState = 0;
}
}
try{
DEBUG_BREAK;
//auto& track = BasePongParts::Get()->GetGameWorld()->GetComponent<TrackController>(
// TrackObject);
//// Set the track speed based on move direction //
//track.ChangeSpeed = MoveState*INPUT_TRACK_ADVANCESPEED;
//track.Marked = true;
} catch(const NotFound&){
Logger::Get()->Warning("PlayerSlot has a TrackObject that has no TrackController "
"component, object: "+Convert::ToString(TrackObject));
}
}
void Pong::PlayerSlot::InputDisabled(){
// Reset control state //
MoveState = 0;
if(TrackObject == 0)
return;
// Set apply force to zero //
try{
DEBUG_BREAK;
//auto& track = BasePongParts::Get()->GetGameWorld()->GetComponent<TrackController>(
// TrackObject);
//// Set the track speed based on move direction //
//track.ChangeSpeed = 0;
//track.Marked = true;
} catch(const NotFound&){
}
}
int Pong::PlayerSlot::GetScore(){
return Score;
}
// ------------------------------------ //
void Pong::PlayerSlot::AddEmptySubSlot(){
SplitSlot = new PlayerSlot(this->Slot, Parent);
// Set this as the parent //
SplitSlot->ParentSlot = this;
}
bool Pong::PlayerSlot::IsVerticalSlot(){
return Slot == 0 || Slot == 2;
}
float Pong::PlayerSlot::GetTrackProgress(){
try{
DEBUG_BREAK;
//auto& track = BasePongParts::Get()->GetGameWorld()->GetComponent<TrackController>(
// TrackObject);
//return track.NodeProgress;
} catch(const NotFound&){
}
return 0.f;
}
bool Pong::PlayerSlot::DoesPlayerNumberMatchThisOrParent(int number){
if(number == PlayerNumber)
return true;
// Recurse to parent, if one exists //
if(ParentSlot)
return ParentSlot->DoesPlayerNumberMatchThisOrParent(number);
return false;
}
// ------------------------------------ //
void Pong::PlayerSlot::AddDataToPacket(sf::Packet &packet){
GUARD_LOCK();
// Write all our data to the packet //
packet << Slot << (int)PlayerType << PlayerNumber << NetworkedInputID << ControlIdentifier
<< (int)ControlType << PlayerControllerID
<< Colour;
packet << PaddleObject << GoalAreaObject << TrackObject;
packet << PlayerID << Score << (bool)(SplitSlot != NULL);
if(SplitSlot){
// Add our sub slot data //
SplitSlot->AddDataToPacket(packet);
}
}
void Pong::PlayerSlot::UpdateDataFromPacket(sf::Packet &packet, Lock &listlock){
GUARD_LOCK();
int tmpival;
// Get our data from it //
packet >> Slot >> tmpival;
PlayerType = static_cast<PLAYERTYPE>(tmpival);
packet >> PlayerNumber >> NetworkedInputID >> ControlIdentifier >> tmpival;
ControlType = static_cast<PLAYERCONTROLS>(tmpival);
packet >> PlayerControllerID;
packet >> Colour;
packet >> PaddleObject >> GoalAreaObject >> TrackObject;
packet >> PlayerID >> Score;
bool wantedsplit;
packet >> wantedsplit;
if(!packet)
throw InvalidArgument("packet format for PlayerSlot is invalid");
// Check do we need to change split //
if(wantedsplit && !SplitSlot){
AddEmptySubSlot();
} else if(!wantedsplit && SplitSlot){
SAFE_DELETE(SplitSlot);
}
// Update split value //
if(wantedsplit){
SplitSlot->UpdateDataFromPacket(packet, listlock);
}
#ifdef PONG_VERSION
// Update everything related to input //
if(PlayerID == PongGame::Get()->GetInterface().GetOurID()){
// Create new one only if there isn't one already created //
if(!InputObj){
// Skip if it is an AI slot //
if(ControlType != PLAYERCONTROLS_AI){
Logger::Get()->Info("Creating input for our player id, NetworkedInputID: "+Convert::ToString(
NetworkedInputID));
// Hook a networked input receiver to the server //
DEBUG_BREAK;
//PongGame::Get()->GetInputController()->RegisterNewLocalGlobalReflectingInputSource(
// PongGame::GetInputFactory()->CreateNewInstanceForLocalStart(guard,
// NetworkedInputID, true));
}
} else {
if(ControlType == PLAYERCONTROLS_AI){
// Destroy out input if there is an AI //
_ResetNetworkInput(guard);
} else {
// Update the existing one //
InputObj->UpdateSettings(ControlType);
Logger::Get()->Info("Updated our control type: "+Convert::ToString(ControlType));
}
}
}
#endif //PONG_VERSION
}
int Pong::PlayerSlot::GetPlayerControllerID(){
return PlayerControllerID;
}
void Pong::PlayerSlot::SlotJoinPlayer(Leviathan::ConnectedPlayer* ply, int uniqnumber){
SlotsPlayer = ply;
PlayerID = SlotsPlayer->GetID();
PlayerNumber = uniqnumber;
PlayerType = PLAYERTYPE_HUMAN;
}
void Pong::PlayerSlot::AddServerAI(int uniquenumber, int aitype /*= 2*/){
// TODO: properly kick //
SlotsPlayer = NULL;
PlayerNumber = uniquenumber;
PlayerType = PLAYERTYPE_COMPUTER;
ControlType = PLAYERCONTROLS_AI;
ControlIdentifier = aitype;
}
void Pong::PlayerSlot::SlotLeavePlayer(){
SlotsPlayer = NULL;
ControlType = PLAYERCONTROLS_NONE;
PlayerType = PLAYERTYPE_EMPTY;
}
void Pong::PlayerSlot::SetInputThatSendsControls(Lock &guard, PongNInputter* input){
if(InputObj && input != InputObj){
Logger::Get()->Info("PlayerSlot: destroying old networked input");
_ResetNetworkInput(guard);
}
InputObj = input;
}
void PlayerSlot::InputDeleted(Lock &guard){
InputObj = nullptr;
}
void Pong::PlayerSlot::_ResetNetworkInput(Lock &guard){
if(InputObj){
InputObj->StopSendingInput(this);
}
InputObj = NULL;
}
// ------------------ PlayerList ------------------ //
Pong::PlayerList::PlayerList(std::function<void (PlayerList*)> callback, size_t playercount
/*= 4*/) :
SyncedResource("PlayerList"), GamePlayers(4), CallbackFunc(callback)
{
// Fill default player data //
for(int i = 0; i < 4; i++){
GamePlayers[i] = new PlayerSlot(i, this);
}
}
Pong::PlayerList::~PlayerList(){
SAFE_DELETE_VECTOR(GamePlayers);
}
// ------------------------------------ //
void Pong::PlayerList::UpdateCustomDataFromPacket(Lock &guard, sf::Packet &packet){
sf::Int32 vecsize;
if(!(packet >> vecsize)){
throw InvalidArgument("packet format for PlayerSlot is invalid");
}
if(vecsize != static_cast<int>(GamePlayers.size())){
// We need to resize //
int difference = vecsize-GamePlayers.size();
if(difference < 0){
// Loop and delete items //
int deleted = 0;
while(deleted < difference){
SAFE_DELETE(GamePlayers[GamePlayers.size()-1]);
GamePlayers.pop_back();
deleted++;
}
} else {
// We need to add items //
for(int i = 0; i < difference; i++){
GamePlayers.push_back(new PlayerSlot(GamePlayers.size(), this));
}
}
}
// Update the data //
auto end = GamePlayers.end();
for(auto iter = GamePlayers.begin(); iter != end; ++iter){
(*iter)->UpdateDataFromPacket(packet, guard);
}
}
void Pong::PlayerList::SerializeCustomDataToPacket(Lock &guard, sf::Packet &packet){
// First put the size //
packet << static_cast<sf::Int32>(GamePlayers.size());
// Loop through them and add them //
for(auto iter = GamePlayers.begin(); iter != GamePlayers.end(); ++iter){
// Serialize it //
(*iter)->AddDataToPacket(packet);
}
}
void Pong::PlayerList::OnValueUpdated(Lock &guard){
// Call our callback //
CallbackFunc(this);
}
PlayerSlot* Pong::PlayerList::GetSlot(size_t index){
if(index >= GamePlayers.size())
throw InvalidArgument("player index is out of range");
return GamePlayers[index];
}
// ------------------------------------ //
void Pong::PlayerList::ReportPlayerInfoToLog() const{
GUARD_LOCK();
Logger::Get()->Write("PlayerList:::: size "+Convert::ToString(GamePlayers.size()));
for(auto iter = GamePlayers.begin(); iter != GamePlayers.end(); ++iter){
(*iter)->WriteInfoToLog(1);
}
}
void Pong::PlayerSlot::WriteInfoToLog(int depth /*= 0*/) const{
string prefix;
if(depth >= 0)
prefix.reserve(depth*4);
for(int i = 0; i < depth; i++)
prefix += " ";
Logger::Get()->Write(prefix+"----PlayerSlot "+Convert::ToString(Slot));
#define PUT_FIELD(x) Logger::Get()->Write(prefix+ #x +" "+Convert::ToString(x));
PUT_FIELD(PlayerType);
PUT_FIELD(PlayerNumber);
PUT_FIELD(ControlType);
PUT_FIELD(ControlIdentifier);
PUT_FIELD(PlayerControllerID);
PUT_FIELD(Colour);
PUT_FIELD(Score);
PUT_FIELD(MoveState);
Logger::Get()->Write(prefix+"PaddleObject "+Convert::ToString(PaddleObject));
Logger::Get()->Write(prefix + "GoalAreaObject "+Convert::ToString(GoalAreaObject));
Logger::Get()->Write(prefix+"TrackObject "+Convert::ToString(TrackObject));
Logger::Get()->Write(prefix+"InputObj "+Convert::ToString(InputObj));
Logger::Get()->Write(prefix+"SlotsPlayer "+Convert::ToString(SlotsPlayer));
PUT_FIELD(PlayerID);
PUT_FIELD(NetworkedInputID);
if(SplitSlot){
Logger::Get()->Write(prefix+"====Split:");
SplitSlot->WriteInfoToLog(depth+1);
}
Logger::Get()->Write(prefix+"----");
}
| 26.426587 | 118 | 0.611908 | Higami69 |
e4293959199c064d4c22a04c770f3ba6c842728f | 654 | hh | C++ | seed/include/ActionInitialization.hh | MeighenBergerS/fennel | c2e4640ef34e0ed88c0c50e5dde36c7d9fa39db6 | [
"MIT"
] | null | null | null | seed/include/ActionInitialization.hh | MeighenBergerS/fennel | c2e4640ef34e0ed88c0c50e5dde36c7d9fa39db6 | [
"MIT"
] | null | null | null | seed/include/ActionInitialization.hh | MeighenBergerS/fennel | c2e4640ef34e0ed88c0c50e5dde36c7d9fa39db6 | [
"MIT"
] | null | null | null | /// \file ActionInitialization.hh
/// \brief Definition of the ActionInitialization class
#ifndef ActionInitialization_h
#define ActionInitialization_h 1
#include "G4VUserActionInitialization.hh"
class DetectorConstruction;
/// Action initialization class.
class ActionInitialization : public G4VUserActionInitialization
{
public:
ActionInitialization(DetectorConstruction*);
virtual ~ActionInitialization();
virtual void BuildForMaster() const;
virtual void Build() const;
private:
DetectorConstruction* fDetConstruction;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
| 20.4375 | 80 | 0.746177 | MeighenBergerS |
e42ac5221712acf84be31ce12b0274982cc7a749 | 1,008 | cc | C++ | tests/mpi.lib/sanity.cc | PyreFramework/pyre | 345c7449a3416eea1c1affa74fb32faff30a6aaa | [
"BSD-3-Clause"
] | null | null | null | tests/mpi.lib/sanity.cc | PyreFramework/pyre | 345c7449a3416eea1c1affa74fb32faff30a6aaa | [
"BSD-3-Clause"
] | null | null | null | tests/mpi.lib/sanity.cc | PyreFramework/pyre | 345c7449a3416eea1c1affa74fb32faff30a6aaa | [
"BSD-3-Clause"
] | null | null | null | // -*- coding: utf-8 -*-
//
// michael a.g. aïvázis
// orthologue
// (c) 1998-2022 all rights reserved
//
// for the build system
#include <portinfo>
// access to the raw mpi routines
#include <pyre/mpi.h>
// and the journal
#include <pyre/journal.h>
// main program
int main(int argc, char *argv[]) {
// initialize {mpi}
MPI_Init(&argc, &argv);
// initialize the journal
pyre::journal::init(argc, argv);
// build a handle to the world communicator
pyre::mpi::communicator_t world(MPI_COMM_WORLD, true);
// compute the size of the world group
int wsize = world.size();
// and my rank
int wrank = world.rank();
// make a channel
pyre::journal::info_t channel("mpi.sanity");
// but silence it
channel.deactivate();
// and say something
channel
<< "[" << wrank << "/" << wsize << "]: hello world!"
<< pyre::journal::endl(__HERE__);
// finalize mpi
MPI_Finalize();
// all done
return 0;
}
// end of file
| 19.764706 | 60 | 0.60119 | PyreFramework |
e42af3e405ca379249fb4f38ca9ca44c78dbe1e5 | 7,373 | cxx | C++ | GPU/GPUTracking/Base/opencl2/GPUReconstructionOCL2.cxx | chengtt0406/AliRoot | c1d89b133b433f608b2373112d3608d8cec26095 | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | GPU/GPUTracking/Base/opencl2/GPUReconstructionOCL2.cxx | chengtt0406/AliRoot | c1d89b133b433f608b2373112d3608d8cec26095 | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | GPU/GPUTracking/Base/opencl2/GPUReconstructionOCL2.cxx | chengtt0406/AliRoot | c1d89b133b433f608b2373112d3608d8cec26095 | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //**************************************************************************\
//* This file is property of and copyright by the ALICE Project *\
//* ALICE Experiment at CERN, All rights reserved. *\
//* *\
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\
//* for The ALICE HLT Project. *\
//* *\
//* Permission to use, copy, modify and distribute this software and its *\
//* documentation strictly for non-commercial purposes is hereby granted *\
//* without fee, provided that the above copyright notice appears in all *\
//* copies and that both the copyright notice and this permission notice *\
//* appear in the supporting documentation. The authors make no claims *\
//* about the suitability of this software for any purpose. It is *\
//* provided "as is" without express or implied warranty. *\
//**************************************************************************
/// \file GPUReconstructionOCL2.cxx
/// \author David Rohr
#define GPUCA_GPUTYPE_OPENCL
#define __OPENCL_HOST__
#include "GPUReconstructionOCL2.h"
#include "GPUReconstructionOCL2Internals.h"
#include "GPUReconstructionIncludes.h"
using namespace GPUCA_NAMESPACE::gpu;
#include <cstring>
#include <unistd.h>
#include <typeinfo>
#include <cstdlib>
#ifdef OPENCL2_ENABLED_AMD
extern "C" char _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd[];
extern "C" unsigned int _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd_size;
#endif
#ifdef OPENCL2_ENABLED_SPIRV
extern "C" char _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv[];
extern "C" unsigned int _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv_size;
#endif
extern "C" char _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src[];
extern "C" unsigned int _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src_size;
GPUReconstruction* GPUReconstruction_Create_OCL2(const GPUSettingsDeviceBackend& cfg) { return new GPUReconstructionOCL2(cfg); }
GPUReconstructionOCL2Backend::GPUReconstructionOCL2Backend(const GPUSettingsDeviceBackend& cfg) : GPUReconstructionOCL(cfg)
{
}
template <class T, int I, typename... Args>
int GPUReconstructionOCL2Backend::runKernelBackend(krnlSetup& _xyz, const Args&... args)
{
cl_kernel k = _xyz.y.num > 1 ? getKernelObject<cl_kernel, T, I, true>() : getKernelObject<cl_kernel, T, I, false>();
return runKernelBackendCommon(_xyz, k, args...);
}
template <class S, class T, int I, bool MULTI>
S& GPUReconstructionOCL2Backend::getKernelObject()
{
static unsigned int krnl = FindKernel<T, I>(MULTI ? 2 : 1);
return mInternals->kernels[krnl].first;
}
int GPUReconstructionOCL2Backend::GetOCLPrograms()
{
char platform_version[64] = {}, platform_vendor[64] = {};
clGetPlatformInfo(mInternals->platform, CL_PLATFORM_VERSION, sizeof(platform_version), platform_version, nullptr);
clGetPlatformInfo(mInternals->platform, CL_PLATFORM_VENDOR, sizeof(platform_vendor), platform_vendor, nullptr);
float ver = 0;
sscanf(platform_version, "OpenCL %f", &ver);
cl_int return_status[1] = {CL_SUCCESS};
cl_int ocl_error;
#ifdef OPENCL2_ENABLED_AMD
if (strcmp(platform_vendor, "Advanced Micro Devices, Inc.") == 0) {
size_t program_sizes[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd_size};
char* program_binaries[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_amd};
mInternals->program = clCreateProgramWithBinary(mInternals->context, 1, &mInternals->device, program_sizes, (const unsigned char**)program_binaries, return_status, &ocl_error);
} else
#endif
#ifdef OPENCL2_ENABLED_SPIRV // clang-format off
if (ver >= 2.2) {
mInternals->program = clCreateProgramWithIL(mInternals->context, _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv, _makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_spirv_size, &ocl_error);
} else
#endif // clang-format on
{
size_t program_sizes[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src_size};
char* programs_sources[1] = {_makefile_opencl_program_Base_opencl_GPUReconstructionOCL2_cl_src};
mInternals->program = clCreateProgramWithSource(mInternals->context, (cl_uint)1, (const char**)&programs_sources, program_sizes, &ocl_error);
}
if (GPUFailedMsgI(ocl_error)) {
GPUError("Error creating OpenCL program from binary");
return 1;
}
if (GPUFailedMsgI(return_status[0])) {
GPUError("Error creating OpenCL program from binary (device status)");
return 1;
}
if (GPUFailedMsgI(clBuildProgram(mInternals->program, 1, &mInternals->device, GPUCA_M_STR(OCL_FLAGS), nullptr, nullptr))) {
cl_build_status status;
if (GPUFailedMsgI(clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_STATUS, sizeof(status), &status, nullptr)) == 0 && status == CL_BUILD_ERROR) {
size_t log_size;
clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG, 0, nullptr, &log_size);
std::unique_ptr<char[]> build_log(new char[log_size + 1]);
clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG, log_size, build_log.get(), nullptr);
build_log[log_size] = 0;
GPUError("Build Log:\n\n%s\n", build_log.get());
}
return 1;
}
#define GPUCA_KRNL(x_class, x_attributes, x_arguments, x_forward) \
GPUCA_KRNL_WRAP(GPUCA_KRNL_LOAD_, x_class, x_attributes, x_arguments, x_forward)
#define GPUCA_KRNL_LOAD_single(x_class, x_attributes, x_arguments, x_forward) \
if (AddKernel<GPUCA_M_KRNL_TEMPLATE(x_class)>(false)) { \
return 1; \
}
#define GPUCA_KRNL_LOAD_multi(x_class, x_attributes, x_arguments, x_forward) \
if (AddKernel<GPUCA_M_KRNL_TEMPLATE(x_class)>(true)) { \
return 1; \
}
#include "GPUReconstructionKernels.h"
#undef GPUCA_KRNL
#undef GPUCA_KRNL_LOAD_single
#undef GPUCA_KRNL_LOAD_multi
return 0;
}
bool GPUReconstructionOCL2Backend::CheckPlatform(unsigned int i)
{
char platform_version[64] = {}, platform_vendor[64] = {};
clGetPlatformInfo(mInternals->platforms[i], CL_PLATFORM_VERSION, sizeof(platform_version), platform_version, nullptr);
clGetPlatformInfo(mInternals->platforms[i], CL_PLATFORM_VENDOR, sizeof(platform_vendor), platform_vendor, nullptr);
float ver1 = 0;
sscanf(platform_version, "OpenCL %f", &ver1);
if (ver1 >= 2.2f) {
if (mProcessingSettings.debugLevel >= 2) {
GPUInfo("OpenCL 2.2 capable platform found");
}
return true;
}
if (strcmp(platform_vendor, "Advanced Micro Devices, Inc.") == 0 && ver1 >= 2.0f) {
float ver2 = 0;
const char* pos = strchr(platform_version, '(');
if (pos) {
sscanf(pos, "(%f)", &ver2);
}
if ((ver1 >= 2.f && ver2 >= 2000.f) || ver1 >= 2.1f) {
if (mProcessingSettings.debugLevel >= 2) {
GPUInfo("AMD ROCm OpenCL Platform found");
}
return true;
}
}
return false;
}
| 44.957317 | 224 | 0.696731 | chengtt0406 |
e42afc9d488b84f0dff903ff4f851b4f804214fe | 3,141 | cpp | C++ | cpgf/test/temp/test_temp.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | null | null | null | cpgf/test/temp/test_temp.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | null | null | null | cpgf/test/temp/test_temp.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | null | null | null | #include "../unittestbase.h"
#include "luabind_common.h"
#include "cpgf/gmetaclass.h"
#include "cpgf/gmetadefine.h"
#include "cpgf/goutmain.h"
#include <iostream>
namespace Test_Temp { namespace {
using namespace cpgf;
using namespace std;
class TestOperator
{
public:
TestOperator() : value(0) {
}
TestOperator(int value) : value(value) {
}
TestOperator(const TestOperator & other) : value(other.value) {
}
#define M(OP, RET) \
RET operator OP (int other) const { return this->value OP other; } \
RET operator OP (const TestOperator & other) const { return this->value OP other.value; }
M(+, TestOperator)
M(-, TestOperator)
M(*, TestOperator)
M(/, TestOperator)
M(%, TestOperator)
M(==, bool)
M(<, bool)
M(<=, bool)
#undef M
TestOperator operator - () const {
return -this->value;
}
TestOperator operator () (const std::string & s, int n) const {
return this->value + (int)s.length() + n * 2;
}
int operator () (const cpgf::GMetaVariadicParam * params) const {
int total = this->value;
for(size_t i = 0; i < params->paramCount; ++i) {
total += cpgf::fromVariant<int>(*(params->params[i]));
}
return total;
}
GVariant getVar() const { return 38; }
void testParam(int * & param) const {
param = nullptr;
}
int testCallback(const GCallback<int (int a, int b)> & cb) {
return cb(3, 8);
}
public:
int value;
};
void TestScriptBindMetaData3()
{
GDefineMetaClass<TestOperator>
::define("testscript::TestOperator")
._constructor<void * (const TestOperator &)>()
._constructor<void * (int)>()
._field("value", &TestOperator::value)
._method("getVar", &TestOperator::getVar)
._method("testParam", &TestOperator::testParam)
// ._method("testCallback", &TestOperator::testCallback)
._operator<TestOperator (const GMetaSelf)>(-mopHolder)
._operator<TestOperator (const std::string &, int)>(mopHolder(mopHolder), GMetaPolicyCopyAllConstReference())
._operator<int (const GMetaVariadicParam *)>(mopHolder(mopHolder))
#define M(OP, RET) \
._operator<RET (const GMetaSelf, int)>(mopHolder OP mopHolder) \
._operator<RET (const GMetaSelf, const TestOperator &)>(mopHolder OP mopHolder) \
// ._operator<RET (const GMetaSelf, const TestObject &)>(mopHolder OP mopHolder)
M(+, TestOperator)
M(-, TestOperator)
M(*, TestOperator)
M(/, TestOperator)
M(%, TestOperator)
M(==, bool)
M(<, bool)
M(<=, bool)
#undef M
;
}
typedef int (*&FuncPtr)();
void doIt(const GVariant & b)
{
cout << b.refData().typeData.vt << " " << fromVariant<int>(b) << endl;
}
GTEST(TestTemp)
{
GVariant a = createTypedVariant(GVariant(38), createMetaType<int>());
doIt(fromVariantData<const GVariant &, VarantCastCopyConstRef>(a.refData()));
return;
TestLuaContext context;
GScopedInterface<IMetaClass> metaClass(context.getService()->findClassByName("testscript::TestOperator"));
context.getBinding()->setValue("TestOperator", GScriptValue::fromClass(metaClass.get()));
context.doString("a = TestOperator(99)");
context.doString("b = a.getVar()");
context.doString("print(b)");
}
G_AUTO_RUN_BEFORE_MAIN()
{
TestScriptBindMetaData3();
}
} }
| 22.119718 | 111 | 0.682904 | mousepawmedia |
e42e39811d115bc810ffd4b7f6a704411adc14c2 | 4,798 | cpp | C++ | Practice/2019.1.18/BZOJ3159.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2019.1.18/BZOJ3159.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2019.1.18/BZOJ3159.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define Max(x,y) x=max(x,y)
#define Min(x,y) x=min(x,y)
#define ll long long
const int maxN=50500;
const int maxM=maxN<<1;
class Treap
{
public:
int ls,rs,sz;
ll sum,mx,mn,pls,rev,key;
};
int n,m,root;
int edgecnt=0,Head[maxN],Next[maxM],V[maxM],dep[maxN];
int Sz[maxN],Hs[maxN],Fa[maxN],Top[maxN],Rt[maxN],nodecnt;
Treap T[maxN];
void Add_Edge(int u,int v);
void dfs1(int u,int fa);
void dfs2(int u,int top);
void Build(int &x,int l,int r);
void Plus(int x,int k);
void Reverse(int x);
void PushDown(int x);
void Update(int x);
void Split(int u,int k,int &x,int &y);
int Merge(int u,int v);
int Split(int x,int y);
void Pushback(int rt,int x,int y);
int main()
{
scanf("%d%d%d",&n,&m,&root);
mem(Head,-1);
for (int i=1; i<n; i++) {
int u,v;
scanf("%d%d",&u,&v);
Add_Edge(u,v);
Add_Edge(v,u);
}
dfs1(root,0);
dfs2(root,root);
while (m--) {
char ipt[10];
int x,y;
scanf("%s%d%d",ipt,&x,&y);
int rt=Split(x,y);
if (ipt[0]=='I'&&ipt[2]=='c') {
int w;
scanf("%d",&w);
Plus(rt,w);
}
if (ipt[0]=='S') printf("%lld\n",T[rt].sum);
if (ipt[0]=='M'&&ipt[1]=='a') printf("%lld\n",T[rt].mx);
if (ipt[0]=='M'&&ipt[1]=='i') printf("%lld\n",T[rt].mn);
if (ipt[0]=='I'&&ipt[2]=='v') Reverse(rt);
Pushback(rt,x,y);
}
return 0;
}
void Add_Edge(int u,int v)
{
Next[++edgecnt]=Head[u];
Head[u]=edgecnt;
V[edgecnt]=v;
return;
}
void dfs1(int u,int fa)
{
dep[u]=dep[fa]+1;
Sz[u]=1;
Fa[u]=fa;
for (int i=Head[u]; i!=-1; i=Next[i])
if (V[i]!=fa) {
dfs1(V[i],u);
Sz[u]+=Sz[V[i]];
if (Sz[V[i]]>Sz[Hs[u]]) Hs[u]=V[i];
}
return;
}
void dfs2(int u,int top)
{
Top[u]=top;
if (Hs[u]==0) {
Build(Rt[top],dep[top],dep[u]);
return;
}
dfs2(Hs[u],top);
for (int i=Head[u]; i!=-1; i=Next[i])
if (V[i]!=Fa[u]&&V[i]!=Hs[u]) dfs2(V[i],V[i]);
return;
}
void Build(int &x,int l,int r)
{
x=++nodecnt;
T[x].sz=r-l+1;
int mid=(l+r)>>1;
if (l<mid) Build(T[x].ls,l,mid-1);
if (mid<r) Build(T[x].rs,mid+1,r);
return;
}
void Plus(int x,int k)
{
T[x].pls+=k;
T[x].sum+=k*T[x].sz;
T[x].mn+=k;
T[x].mx+=k;
T[x].key+=k;
return;
}
void Reverse(int x)
{
T[x].rev^=1;
swap(T[x].ls,T[x].rs);
return;
}
void PushDown(int x)
{
if (T[x].rev) {
if (T[x].ls) Reverse(T[x].ls);
if (T[x].rs) Reverse(T[x].rs);
T[x].rev=0;
}
if (T[x].pls) {
if (T[x].ls) Plus(T[x].ls,T[x].pls);
if (T[x].rs) Plus(T[x].rs,T[x].pls);
T[x].pls=0;
}
return;
}
void Update(int x)
{
T[x].sz=T[T[x].ls].sz+T[T[x].rs].sz+1;
T[x].sum=T[T[x].ls].sum+T[T[x].rs].sum+T[x].key;
T[x].mn=T[x].mx=T[x].key;
if (T[x].ls) Min(T[x].mn,T[T[x].ls].mn),Max(T[x].mx,T[T[x].ls].mx);
if (T[x].rs) Min(T[x].mn,T[T[x].rs].mn),Max(T[x].mx,T[T[x].rs].mx);
return;
}
void Split(int u,int k,int &x,int &y)
{
if (u==0) {
x=y=0;
return;
}
PushDown(u);
if (T[T[u].ls].sz>=k) y=u,Split(T[u].ls,k,x,T[y].ls),Update(y);
else x=u,Split(T[u].rs,k-T[T[u].ls].sz-1,T[u].rs,y),Update(x);
return;
}
int Merge(int u,int v)
{
if (!u||!v) return u+v;
PushDown(u);
PushDown(v);
if (rand()%(T[u].sz+T[v].sz)+1<=T[u].sz) {
T[u].rs=Merge(T[u].rs,v);
Update(u);
return u;
} else {
T[v].ls=Merge(u,T[v].ls);
Update(v);
return v;
}
}
int Split(int x,int y)
{
int rt1=0,rt2=0;
while (Top[x]!=Top[y]) {
if (dep[Top[x]]>=dep[Top[y]]) {
int left,right;
Split(Rt[Top[x]],dep[x]-dep[Top[x]]+1,left,right);
Rt[Top[x]]=right;
rt1=Merge(left,rt1);
x=Fa[Top[x]];
} else {
int left,right;
Split(Rt[Top[y]],dep[y]-dep[Top[y]]+1,left,right);
Rt[Top[y]]=right;
rt2=Merge(left,rt2);
y=Fa[Top[y]];
}
}
if (dep[x]<=dep[y]) {
int a,b,c;
Split(Rt[Top[x]],dep[y]-dep[Top[x]]+1,a,c);
Split(a,dep[x]-dep[Top[x]],a,b);
Rt[Top[x]]=Merge(a,c);
rt2=Merge(b,rt2);
} else {
int a,b,c;
Split(Rt[Top[x]],dep[x]-dep[Top[x]]+1,a,c);
Split(a,dep[y]-dep[Top[x]],a,b);
Rt[Top[x]]=Merge(a,c);
rt1=Merge(b,rt1);
}
if (rt1) Reverse(rt1);
return Merge(rt1,rt2);
}
void Pushback(int rt,int x,int y)
{
while (Top[x]!=Top[y]) {
if (dep[Top[x]]>=dep[Top[y]]) {
int push;
Split(rt,dep[x]-dep[Top[x]]+1,push,rt);
Reverse(push);
Rt[Top[x]]=Merge(push,Rt[Top[x]]);
x=Fa[Top[x]];
} else {
int push;
Split(rt,T[rt].sz-(dep[y]-dep[Top[y]]+1),rt,push);
Rt[Top[y]]=Merge(push,Rt[Top[y]]);
y=Fa[Top[y]];
}
}
if (dep[x]<=dep[y]) {
int a,b;
Split(Rt[Top[x]],dep[x]-dep[Top[x]],a,b);
Rt[Top[x]]=Merge(Merge(a,rt),b);
} else {
int a,b;
Reverse(rt);
Split(Rt[Top[x]],dep[y]-dep[Top[x]],a,b);
Rt[Top[y]]=Merge(Merge(a,rt),b);
}
return;
}
/*
5 8 1
1 2
2 3
3 4
4 5
Sum 2 4
Increase 3 5 3
Minor 1 4
Sum 4 5
Invert 1 3
Major 1 2
Increase 1 5 2
Sum 1 5
//*/
| 18.964427 | 68 | 0.544185 | SYCstudio |
e42eb46eea87f0a320c6b9b590bce4e6b8df866f | 757 | hpp | C++ | src/estd/memory.hpp | hvellyr/sairy | 3b7b797c71384222d58b67bded24ee5b5cc6aa2a | [
"BSD-3-Clause"
] | null | null | null | src/estd/memory.hpp | hvellyr/sairy | 3b7b797c71384222d58b67bded24ee5b5cc6aa2a | [
"BSD-3-Clause"
] | null | null | null | src/estd/memory.hpp | hvellyr/sairy | 3b7b797c71384222d58b67bded24ee5b5cc6aa2a | [
"BSD-3-Clause"
] | 1 | 2018-01-29T10:57:09.000Z | 2018-01-29T10:57:09.000Z | // Copyright (c) 2020 Gregor Klinke
#pragma once
#include "config.hpp"
#include "estd/type_traits.hpp"
#include <memory>
#include <type_traits>
#include <utility>
namespace eyestep {
namespace estd {
#if !defined(TEXTBOOK_HAVE_STD_MAKE_UNIQUE)
template <class T, class... Args>
auto make_unique(Args&&... args)
-> enable_if_t<!std::is_array<T>::value, std::unique_ptr<T>> {
return std::unique_ptr<T>{new T(std::forward<Args>(args)...)};
}
template <class T>
auto make_unique(std::size_t size)
-> enable_if_t<std::is_array<T>::value, std::unique_ptr<T>> {
return std::unique_ptr<T>{new typename std::remove_extent<T>::type[size]()};
}
#else
using std::make_unique;
#endif
} // namespace estd
} // namespace eyestep
| 19.410256 | 80 | 0.681638 | hvellyr |
e42f22e4ef0939ef4e4a2703d3fea7caf55d8581 | 1,806 | hpp | C++ | src/fd_stencils.hpp | JLRipley314/spherically-symmetric-Z2-edgb | c2311a79d2ec08073541c98f6b06b6f54fbb58e4 | [
"MIT"
] | null | null | null | src/fd_stencils.hpp | JLRipley314/spherically-symmetric-Z2-edgb | c2311a79d2ec08073541c98f6b06b6f54fbb58e4 | [
"MIT"
] | null | null | null | src/fd_stencils.hpp | JLRipley314/spherically-symmetric-Z2-edgb | c2311a79d2ec08073541c98f6b06b6f54fbb58e4 | [
"MIT"
] | 2 | 2021-07-06T01:45:19.000Z | 2021-07-30T18:35:09.000Z | #ifndef _FD_STENCILS_H_
#define _FD_STENCILS_H_
#include <vector>
#include <string>
/*===========================================================================*/
void KO_filter(
const int exc_i, const int nx,
const std::string type, std::vector<double> &vec);
/*===========================================================================*/
inline double Dx_ptm1_4th(
const double vp1, const double v0, const double vm1,
const double vm2, const double vm3,
const double dx)
{
return (
(1./4.)* vp1
+ (5./6.)* v0
+ (-3./2.)* vm1
+ (1./2.)* vm2
+ (-1./12.)*vm3
)/dx
;
}
/*===========================================================================*/
inline double Dx_ptc_4th(
const double vp2, const double vp1, const double vm1, const double vm2,
const double dx)
{
return (
(-1./12.)*vp2
+ (2./3.)* vp1
+ (-2./3.)* vm1
+ (1./12.)* vm2
)/dx
;
}
/*===========================================================================*/
inline double Dx_ptp1_4th(
const double vp3, const double vp2, const double vp1,
const double v0, const double vm1,
const double dx)
{
return (
(1./12.)*vp3
+ (-1./2.)*vp2
+ (3./2.)* vp1
+ (-5./6.)*v0
+ (-1./4.)*vm1
)/dx
;
}
/*===========================================================================*/
inline double Dx_ptp0_4th(
const double vp4, const double vp3, const double vp2,
const double vp1, const double v0,
const double dx)
{
return (
(-1./4.)* vp4
+ (4./3.)* vp3
+ (-3.)* vp2
+ (4.)* vp1
+ (-25./12.)*v0
)/dx
;
}
/*===========================================================================*/
inline double make_Dx_zero(
const double vp4, const double vp3, const double vp2,
const double vp1)
{
return (
(-1./4.)* vp4
+ (4./3.)* vp3
+ (-3.)* vp2
+ (4.)* vp1
)*(12./25.)
;
}
#endif
| 21.5 | 79 | 0.43577 | JLRipley314 |
e4300d3f74ace6d68c727f6de690a5e6e1e618fa | 623 | cc | C++ | packages/mccomponents/mccomponentsbpmodule/wrap_DGSSXResPixel.cc | mcvine/mcvine | 42232534b0c6af729628009bed165cd7d833789d | [
"BSD-3-Clause"
] | 5 | 2017-01-16T03:59:47.000Z | 2020-06-23T02:54:19.000Z | packages/mccomponents/mccomponentsbpmodule/wrap_DGSSXResPixel.cc | mcvine/mcvine | 42232534b0c6af729628009bed165cd7d833789d | [
"BSD-3-Clause"
] | 293 | 2015-10-29T17:45:52.000Z | 2022-01-07T16:31:09.000Z | packages/mccomponents/mccomponentsbpmodule/wrap_DGSSXResPixel.cc | mcvine/mcvine | 42232534b0c6af729628009bed165cd7d833789d | [
"BSD-3-Clause"
] | 1 | 2019-05-25T00:53:31.000Z | 2019-05-25T00:53:31.000Z | // -*- C++ -*-
//
//
#include "mccomponents/homogeneous_scatterer/AbstractScatteringKernel.h"
#include "mccomponents/homogeneous_scatterer/DGSSXResPixel.h"
#include "mccomposite/boostpython_binding/wrap_scatterer.h"
namespace wrap_mccomponents {
void wrap_DGSSXResPixel()
{
using namespace mccomposite::boostpython_binding;
typedef mccomponents::DGSSXResPixel w_t;
scatterer_wrapper<w_t>::wrap
("DGSSXResPixel",
init<
double, double,
const mccomponents::AbstractShape &
>
()
[with_custodian_and_ward<1,4>()]
)
;
}
}
// End of file
| 18.323529 | 72 | 0.667737 | mcvine |
e433bad26c6094b8709f4fa172a436ad7efdce4d | 7,978 | cpp | C++ | src/SysProcess.cpp | Yhgenomics/maraton-framework | 9044321d8c252c635a197a5c32512cb0538688f1 | [
"MIT"
] | 4 | 2015-11-12T03:51:46.000Z | 2015-11-13T03:29:04.000Z | src/SysProcess.cpp | Yhgenomics/maraton-framework | 9044321d8c252c635a197a5c32512cb0538688f1 | [
"MIT"
] | null | null | null | src/SysProcess.cpp | Yhgenomics/maraton-framework | 9044321d8c252c635a197a5c32512cb0538688f1 | [
"MIT"
] | null | null | null | #include "SysProcess.h"
#include <thread>
#include <string.h>
#include <memory>
#include <thread>
#include "maraton.h"
#ifdef _WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif
SysProcess::~SysProcess()
{
if ( this->file_ != NULL )
{
delete this->file_;
this->file_ = NULL;
}
if ( this->args_ != NULL )
{
delete this->args_;
this->args_ = NULL;
}
if ( this->directory_ != NULL )
{
delete this->directory_;
this->directory_ = NULL;
}
}
void SysProcess::desctroy( SysProcess ** process )
{
if ( process != nullptr && *process != nullptr )
{
delete *process;
*process = nullptr;
}
}
SysProcess * SysProcess::create( std::string file , std::string args ,
std::string directry ,
prceoss_callback_t on_finish )
{
auto ret = new SysProcess( file , args , directry , on_finish );
return ret;
}
SysProcess * SysProcess::create( std::string file , std::string args ,
prceoss_callback_t on_finish )
{
auto ret = new SysProcess( file , args , on_finish );
return ret;
}
SysProcess * SysProcess::create( std::string file ,
prceoss_callback_t on_finish )
{
auto ret = new SysProcess( file , on_finish );
return ret;
}
void SysProcess::uv_process_exit_callback( uv_process_t * process ,
int64_t exit_status ,
int term_signal )
{
SysProcess* instance = static_cast< SysProcess* >( process->data );
uv_close( ( uv_handle_t* )process , SysProcess::uv_process_close_callback );
instance->callback( instance , exit_status );
}
void SysProcess::uv_process_close_callback( uv_handle_t * handle )
{
SysProcess* instance = static_cast< SysProcess* >( handle->data );
SAFE_DELETE( instance );
}
void SysProcess::uv_process_alloc_buffer( uv_handle_t * handle ,
size_t suggested_size ,
uv_buf_t * buf )
{
*buf = uv_buf_init( ( char* )malloc( suggested_size ) , suggested_size );
}
void SysProcess::uv_prcoess_read_stream( uv_stream_t * stream ,
ssize_t nread ,
const uv_buf_t * buf )
{
SysProcess* inst = static_cast< SysProcess* > ( stream->data );
if ( nread < 0 )
{
if ( nread == UV_EOF )
{
// end of file
uv_close( ( uv_handle_t * )&inst->pipe_ , NULL );
}
return;
}
inst->std_out_ = std::string( buf->base , nread );
if ( buf->base )
delete buf->base;
}
SysProcess::SysProcess()
{
//uv_sem_init( &this->sem , 0 );
}
SysProcess::SysProcess( std::string file, std::string args,
std::string directry,
prceoss_callback_t on_finish )
: SysProcess()
{
std::string newArgs = args;
this->file_ = new char[this->STR_LENGTH];
this->args_ = new char[this->STR_LENGTH];
this->directory_ = new char[this->STR_LENGTH];
memset( this->file_, 0, this->STR_LENGTH );
memset( this->args_, 0, this->STR_LENGTH );
memset( this->directory_, 0, this->STR_LENGTH );
memcpy( this->file_, file.c_str() , file.length() );
memcpy( this->args_, newArgs.c_str(), newArgs.length() );
memcpy( this->directory_, directry.c_str(), directry.length() );
this->callback = on_finish;
}
SysProcess::SysProcess( std::string file, std::string args,
prceoss_callback_t on_finish )
: SysProcess()
{
std::string newArgs = args;
this->file_ = new char[this->STR_LENGTH];
this->args_ = new char[this->STR_LENGTH];
memset( this->file_, 0, this->STR_LENGTH );
memset( this->args_, 0, this->STR_LENGTH );
memcpy( this->file_, file.c_str(), file.length() );
memcpy( this->args_, newArgs.c_str(), newArgs.length() );
this->callback = on_finish;
}
SysProcess::SysProcess( std::string file, prceoss_callback_t on_finish )
: SysProcess()
{
this->file_ = new char[this->STR_LENGTH];
memset( this->file_, 0, this->STR_LENGTH );
memcpy( this->file_, file.c_str(), file.length() );
this->callback = on_finish;
}
void SysProcess::invoke()
{
int r;
char** args = NULL;
//if ( this->directory_ == nullptr )
//{
// char path[512] = { 0 };
// getcwd( path , 512 );
// int path_len = strlen( path );
// this->directory_ = new char[path_len + 1];
// memset( this->directory_ , 0 , path_len + 1 );
// memcpy( this->directory_ , path , strlen( path ) );
//}
printf( "File:%s\r\n" , this->file_ );
if ( args_ == nullptr )
{
//char path[512] = { 0 };
//getcwd( path , 512 );
//args = new char*[2];
//args[0] = ' ';
//args[1] = NULL;
//args[0] = new char[strlen( path ) + 1];
//memset( args[0] , 0 , strlen( path ) + 1 );
//memcpy( args[0] , path , strlen( path ) );
//args[1] = NULL;
}
else
{
args = new char*[64];
for ( size_t i = 0; i < 64; i++ )
{
args[i] = new char[512];
memset( args[i] , 0 , 512 );
args[i][0] = ' ';
}
auto raw_args = this->args_;
size_t len = strlen( this->args_ );
int start_pos = 0;
#ifdef _WIN32
int row = 0;
#else
int row = 0;
#endif
int col = 0;
bool has_dot = false;
for ( int e = start_pos; e < len; e++ )
{
if ( raw_args[e] == '\'')
{
if ( has_dot )
has_dot = false;
else
has_dot = true;
}
if ( raw_args[e] == ' ' && !has_dot)
{
printf( "Args:%s\r\n", args[row] );
col = 0;
row++;
args[row][col] = ' ';
col = 1;
}
else
{
args[row][col] = raw_args[e];
col++;
}
}
printf( "Args:%s\r\n" , args[row] );
args[row+1] = NULL;
}
auto loop = uv_default_loop();
this->pipe_ = { 0 };
r = uv_pipe_init( loop , &this->pipe_ , 0 );
this->pipe_.data = this;
this->options.exit_cb = SysProcess::uv_process_exit_callback;
this->options.file = this->file_;
this->options.args = args;
this->options.cwd = this->directory_;
this->child_req.data = this;
this->options.stdio_count = 3;
uv_stdio_container_t child_stdio[3];
// ( uv_stdio_flags )( UV_CREATE_PIPE | UV_READABLE_PIPE );
child_stdio[0].flags = UV_IGNORE;
child_stdio[1].flags = ( uv_stdio_flags )( UV_CREATE_PIPE | UV_WRITABLE_PIPE );
child_stdio[1].data.stream = ( uv_stream_t* )&this->pipe_;
child_stdio[2].flags = UV_IGNORE;
this->options.stdio = child_stdio;
r = uv_spawn( loop , &this->child_req , &this->options );
if ( r != 0 )
{
printf( "uv_spawn: %s\r\n" , uv_strerror( r ) );
}
r = uv_read_start( ( uv_stream_t* )&this->pipe_ ,
SysProcess::uv_process_alloc_buffer ,
SysProcess::uv_prcoess_read_stream );
if ( r != 0 )
{
printf( "uv_read_start: %s\r\n" , uv_strerror( r ) );
}
delete[] args;
}
size_t SysProcess::wait_for_exit()
{
// uv_sem_wait( &this->sem );
//uv_sem_destroy( &this->sem );
return this->result;
}
void SysProcess::start()
{
this->invoke();
}
void SysProcess::kill()
{
uv_process_kill( &this->child_req , 1 );
#ifdef _WIN32
//TerminateProcess( this->pi_.hProcess, -1 );
#else
pclose( p_stream );
#endif // _WIN32
}
| 25.488818 | 83 | 0.526573 | Yhgenomics |
e4347b57eaec58c9042fa7ed21d13af0ca311db5 | 2,692 | hpp | C++ | Engine/Source/ThirdParty/mtlpp/mtlpp-master-7efad47/src/compute_command_encoder.hpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/ThirdParty/mtlpp/mtlpp-master-7efad47/src/compute_command_encoder.hpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/ThirdParty/mtlpp/mtlpp-master-7efad47/src/compute_command_encoder.hpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | /*
* Copyright 2016-2017 Nikolay Aleksiev. All rights reserved.
* License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE
*/
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
// Modifications for Unreal Engine
#pragma once
#include "defines.hpp"
#include "ns.hpp"
#include "command_encoder.hpp"
#include "texture.hpp"
#include "command_buffer.hpp"
#include "fence.hpp"
namespace mtlpp
{
class ComputeCommandEncoder : public CommandEncoder
{
public:
ComputeCommandEncoder() { }
ComputeCommandEncoder(const ns::Handle& handle) : CommandEncoder(handle) { }
void SetComputePipelineState(const ComputePipelineState& state);
void SetBytes(const void* data, uint32_t length, uint32_t index) MTLPP_AVAILABLE(10_11, 8_3);
void SetBuffer(const Buffer& buffer, uint32_t offset, uint32_t index);
void SetBufferOffset(uint32_t offset, uint32_t index) MTLPP_AVAILABLE(10_11, 8_3);
void SetBuffers(const Buffer* buffers, const uint32_t* offsets, const ns::Range& range);
void SetTexture(const Texture& texture, uint32_t index);
void SetTextures(const Texture* textures, const ns::Range& range);
void SetSamplerState(const SamplerState& sampler, uint32_t index);
void SetSamplerStates(const SamplerState* samplers, const ns::Range& range);
void SetSamplerState(const SamplerState& sampler, float lodMinClamp, float lodMaxClamp, uint32_t index);
void SetSamplerStates(const SamplerState* samplers, const float* lodMinClamps, const float* lodMaxClamps, const ns::Range& range);
void SetThreadgroupMemory(uint32_t length, uint32_t index);
void SetStageInRegion(const Region& region) MTLPP_AVAILABLE(10_12, 10_0);
void DispatchThreadgroups(const Size& threadgroupsPerGrid, const Size& threadsPerThreadgroup);
void DispatchThreadgroupsWithIndirectBuffer(const Buffer& indirectBuffer, uint32_t indirectBufferOffset, const Size& threadsPerThreadgroup) MTLPP_AVAILABLE(10_11, 9_0);
void DispatchThreads(const Size& threadsPerGrid, const Size& threadsPerThreadgroup) MTLPP_AVAILABLE(10_13, 11_0);
void UpdateFence(const Fence& fence) MTLPP_AVAILABLE(10_13, 10_0);
void WaitForFence(const Fence& fence) MTLPP_AVAILABLE(10_13, 10_0);
void UseResource(const Resource& resource, ResourceUsage usage) MTLPP_AVAILABLE(10_13, 11_0);
void UseResources(const Resource* resource, uint32_t count, ResourceUsage usage) MTLPP_AVAILABLE(10_13, 11_0);
void UseHeap(const Heap& heap) MTLPP_AVAILABLE(10_13, 11_0);
void UseHeaps(const Heap* heap, uint32_t count) MTLPP_AVAILABLE(10_13, 11_0);
}
MTLPP_AVAILABLE(10_11, 8_0);
}
| 53.84 | 176 | 0.753715 | windystrife |
e43793741d62a54bd63c15b5236573d181bb4bf8 | 5,325 | cpp | C++ | lib/Transforms/Loop/PartialAffineLoopTile.cpp | Luke-Jacobs/scalehls | 76e3980b9ddd1f8f01606d1bf53ef03eb3a8e502 | [
"Apache-2.0"
] | 60 | 2021-07-30T03:30:35.000Z | 2022-03-27T20:00:41.000Z | lib/Transforms/Loop/PartialAffineLoopTile.cpp | Luke-Jacobs/scalehls | 76e3980b9ddd1f8f01606d1bf53ef03eb3a8e502 | [
"Apache-2.0"
] | 13 | 2021-08-02T16:13:04.000Z | 2022-03-30T23:43:45.000Z | lib/Transforms/Loop/PartialAffineLoopTile.cpp | Luke-Jacobs/scalehls | 76e3980b9ddd1f8f01606d1bf53ef03eb3a8e502 | [
"Apache-2.0"
] | 14 | 2021-07-30T12:55:01.000Z | 2022-03-04T14:29:39.000Z | //===----------------------------------------------------------------------===//
//
// Copyright 2020-2021 The ScaleHLS Authors.
//
//===----------------------------------------------------------------------===//
#include "mlir/Analysis/LoopAnalysis.h"
#include "mlir/Analysis/Utils.h"
#include "mlir/Dialect/Affine/Utils.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/LoopUtils.h"
#include "scalehls/Transforms/Passes.h"
#include "scalehls/Transforms/Utils.h"
using namespace mlir;
using namespace scalehls;
static IntegerSet simplify(IntegerSet set) { return simplifyIntegerSet(set); }
/// Performs basic affine map simplifications.
static AffineMap simplify(AffineMap map) {
MutableAffineMap mMap(map);
mMap.simplify();
return mMap.getAffineMap();
}
/// Utility to simplify an affine attribute and update its entry in the parent
/// operation if necessary.
template <typename AttrT>
static void
simplifyAndUpdateAttr(Operation *op, Identifier name, AttrT attr,
DenseMap<Attribute, Attribute> &simplifiedAttrs) {
auto &simplified = simplifiedAttrs[attr];
if (simplified == attr)
return;
// This is a newly encountered attribute.
if (!simplified) {
// Try to simplify the value of the attribute.
auto value = attr.getValue();
auto simplifiedValue = simplify(value);
if (simplifiedValue == value) {
simplified = attr;
return;
}
simplified = AttrT::get(simplifiedValue);
}
// Simplification was successful, so update the attribute.
op->setAttr(name, simplified);
}
static void simplifyAffineStructures(Block &block) {
auto context = block.front().getContext();
DenseMap<Attribute, Attribute> simplifiedAttrs;
RewritePatternSet patterns(context);
AffineApplyOp::getCanonicalizationPatterns(patterns, context);
AffineForOp::getCanonicalizationPatterns(patterns, context);
AffineIfOp::getCanonicalizationPatterns(patterns, context);
FrozenRewritePatternSet frozenPatterns(std::move(patterns));
// The simplification of affine attributes will likely simplify the op. Try to
// fold/apply canonicalization patterns when we have affine dialect ops.
SmallVector<Operation *> opsToSimplify;
block.walk([&](Operation *op) {
for (auto attr : op->getAttrs()) {
if (auto mapAttr = attr.second.dyn_cast<AffineMapAttr>())
simplifyAndUpdateAttr(op, attr.first, mapAttr, simplifiedAttrs);
else if (auto setAttr = attr.second.dyn_cast<IntegerSetAttr>())
simplifyAndUpdateAttr(op, attr.first, setAttr, simplifiedAttrs);
}
if (isa<AffineForOp, AffineIfOp, AffineApplyOp>(op))
opsToSimplify.push_back(op);
});
applyOpPatternsAndFold(opsToSimplify, frozenPatterns, /*strict=*/true);
}
/// Apply loop tiling to the input loop band and sink all intra-tile loops to
/// the innermost loop with the original loop order. Return the location of the
/// innermost tile-space loop.
Optional<unsigned> scalehls::applyLoopTiling(AffineLoopBand &band,
TileList tileList, bool simplify) {
if (!isPerfectlyNested(band))
return Optional<unsigned>();
// Loop tiling.
auto bandSize = band.size();
AffineLoopBand tiledBand;
if (failed(tilePerfectlyNested(band, tileList, &tiledBand)))
return Optional<unsigned>();
if (simplify) {
band.clear();
unsigned simplifiedBandSize = 0;
for (unsigned i = 0, e = tiledBand.size(); i < e; ++i) {
auto loop = tiledBand[i];
normalizeAffineFor(loop);
if (loop) {
band.push_back(loop);
if (i < bandSize)
++simplifiedBandSize;
}
}
simplifyAffineStructures(*band.front().getBody());
return simplifiedBandSize - 1;
} else {
band = tiledBand;
return bandSize - 1;
}
}
namespace {
struct PartialAffineLoopTile
: public PartialAffineLoopTileBase<PartialAffineLoopTile> {
void runOnOperation() override {
AffineLoopBands targetBands;
getTileableBands(getOperation(), &targetBands);
for (auto &band : targetBands) {
TileList sizes;
unsigned remainTileSize = tileSize;
// Calculate the tiling size of each loop level.
for (auto loop : band) {
if (auto optionalTripCount = getConstantTripCount(loop)) {
auto tripCount = optionalTripCount.getValue();
auto size = tripCount;
if (remainTileSize >= tripCount)
remainTileSize = (remainTileSize + tripCount - 1) / tripCount;
else if (remainTileSize > 1) {
size = 1;
while (size < remainTileSize || tripCount % size != 0) {
++size;
}
remainTileSize = 1;
} else
size = 1;
sizes.push_back(size);
} else
sizes.push_back(1);
}
auto tileLoc = applyLoopTiling(band, sizes).getValue();
band.resize(tileLoc + 1);
// TODO: canonicalize here to eliminate affine.apply ops.
if (applyOrderOpt)
applyAffineLoopOrderOpt(band);
if (applyPipeline)
applyLoopPipelining(band, tileLoc, (unsigned)1);
}
}
};
} // namespace
std::unique_ptr<Pass> scalehls::createPartialAffineLoopTilePass() {
return std::make_unique<PartialAffineLoopTile>();
}
| 31.886228 | 80 | 0.659155 | Luke-Jacobs |
e43b025db5216ecde8d795491dda551f8852a178 | 666 | cpp | C++ | src/graphics/gl/buffer.cpp | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | src/graphics/gl/buffer.cpp | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | src/graphics/gl/buffer.cpp | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | #include "buffer.h"
#include <algorithm>
namespace TankGame
{
Buffer::Buffer(size_t size, const void* data, GLbitfield flags)
{
GLuint buffer;
glCreateBuffers(1, &buffer);
SetID(buffer);
glNamedBufferStorage(buffer, size, data, flags);
}
void DeleteBuffer(GLuint id)
{
glDeleteBuffers(1, &id);
}
static size_t uniformBufferOffsetAlignment = 0;
size_t GetUniformBufferOffsetAlignment()
{
if (uniformBufferOffsetAlignment == 0)
{
GLint value;
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &value);
uniformBufferOffsetAlignment = static_cast<size_t>(std::max(value, 0));
}
return uniformBufferOffsetAlignment;
}
}
| 19.028571 | 74 | 0.728228 | Eae02 |
e43cc6b2590bdc1557387cde4511362ac74c96c4 | 5,036 | cpp | C++ | src/tests/unit/cpu/shape_inference_test/gather_shape_inference.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2022-03-09T08:11:10.000Z | 2022-03-09T08:11:10.000Z | src/tests/unit/cpu/shape_inference_test/gather_shape_inference.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | src/tests/unit/cpu/shape_inference_test/gather_shape_inference.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2020-12-13T22:16:54.000Z | 2020-12-13T22:16:54.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include <gather_shape_inference.hpp>
#include <openvino/op/gather.hpp>
#include <openvino/op/ops.hpp>
#include <openvino/op/parameter.hpp>
#include <utils/shape_inference/shape_inference.hpp>
#include <utils/shape_inference/static_shape.hpp>
using namespace ov;
TEST(StaticShapeInferenceTest, GatherV1Test) {
auto P = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1});
auto I = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1, -1});
auto A = op::v0::Constant::create(element::i64, Shape{}, {0});
auto G = std::make_shared<op::v1::Gather>(P, I, A);
// Test StaticShape
std::vector<StaticShape> static_input_shapes = {StaticShape{3, 2}, StaticShape{2, 2}, StaticShape{1}},
static_output_shapes = {StaticShape{}};
shape_inference(G.get(), static_input_shapes, static_output_shapes);
ASSERT_EQ(static_output_shapes[0], (StaticShape{2, 2, 2}));
}
TEST(StaticShapeInferenceTest, GatherV1TestNonConstantA) {
auto P = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1});
auto I = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1, -1});
auto A = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
auto G = std::make_shared<op::v1::Gather>(P, I, A);
auto hostTensor = std::make_shared<HostTensor>(element::i32, Shape{});
int32_t val_a = 1;
hostTensor->write(&val_a, sizeof(int32_t));
// Test StaticShape
std::vector<StaticShape> static_input_shapes = {StaticShape{3, 2}, StaticShape{2, 2}, StaticShape{}},
static_output_shapes = {StaticShape{}};
shape_inference(G.get(), static_input_shapes, static_output_shapes, {{2, hostTensor}});
ASSERT_EQ(static_output_shapes[0], (StaticShape{3, 2, 2}));
}
TEST(StaticShapeInferenceTest, GatherV7Test) {
auto P = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1});
auto I = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1, -1});
auto A = op::v0::Constant::create(element::i64, Shape{}, {0});
auto G = std::make_shared<op::v7::Gather>(P, I, A);
// Test StaticShape
std::vector<StaticShape> static_input_shapes = {StaticShape{3, 2}, StaticShape{2, 2}, StaticShape{1}},
static_output_shapes = {StaticShape{}};
shape_inference(G.get(), static_input_shapes, static_output_shapes);
ASSERT_EQ(static_output_shapes[0], (StaticShape{2, 2, 2}));
}
TEST(StaticShapeInferenceTest, GatherV7TestNonConstantA) {
auto P = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1});
auto I = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1, -1});
auto A = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
auto G = std::make_shared<op::v7::Gather>(P, I, A);
auto hostTensor = std::make_shared<HostTensor>(element::i32, Shape{});
int32_t val_a = 0;
hostTensor->write(&val_a, sizeof(int32_t));
// Test StaticShape
std::vector<StaticShape> static_input_shapes = {StaticShape{3, 2}, StaticShape{2, 2}, StaticShape{}},
static_output_shapes = {StaticShape{}};
shape_inference(G.get(), static_input_shapes, static_output_shapes, {{2, hostTensor}});
ASSERT_EQ(static_output_shapes[0], (StaticShape{2, 2, 2}));
}
TEST(StaticShapeInferenceTest, GatherV8Test) {
auto P = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1});
auto I = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1, -1});
auto A = op::v0::Constant::create(element::i64, Shape{}, {0});
auto G = std::make_shared<op::v8::Gather>(P, I, A);
// Test StaticShape
std::vector<StaticShape> static_input_shapes = {StaticShape{3, 2}, StaticShape{2, 2}, StaticShape{1}},
static_output_shapes = {StaticShape{}};
shape_inference(G.get(), static_input_shapes, static_output_shapes);
ASSERT_EQ(static_output_shapes[0], (StaticShape{2, 2, 2}));
}
TEST(StaticShapeInferenceTest, GatherV8TestNonConstantA) {
auto P = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1});
auto I = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1, -1});
auto A = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
auto G = std::make_shared<op::v8::Gather>(P, I, A);
auto hostTensor = std::make_shared<HostTensor>(element::i32, Shape{});
int32_t val_a = 0;
hostTensor->write(&val_a, sizeof(int32_t));
// Test StaticShape
std::vector<StaticShape> static_input_shapes = {StaticShape{3, 2}, StaticShape{2, 2}, StaticShape{}},
static_output_shapes = {StaticShape{}};
shape_inference(G.get(), static_input_shapes, static_output_shapes, {{2, hostTensor}});
ASSERT_EQ(static_output_shapes[0], (StaticShape{2, 2, 2}));
} | 53.010526 | 106 | 0.673153 | ryanloney |
e43cff509538b2ed8441f84f7de5a62451e5cde4 | 6,474 | cc | C++ | source/jones/cartridge/mapper/mapper_mmc1.cc | JonForShort/nes-emulator | 513d00a0f1774a262d8a879367db8d3c2a69fbc1 | [
"MIT"
] | 2 | 2018-01-24T01:18:07.000Z | 2018-12-29T05:17:32.000Z | source/jones/cartridge/mapper/mapper_mmc1.cc | JonForShort/nes-emulator | 513d00a0f1774a262d8a879367db8d3c2a69fbc1 | [
"MIT"
] | null | null | null | source/jones/cartridge/mapper/mapper_mmc1.cc | JonForShort/nes-emulator | 513d00a0f1774a262d8a879367db8d3c2a69fbc1 | [
"MIT"
] | null | null | null | //
// MIT License
//
// Copyright 2019
//
// 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 <boost/static_assert.hpp>
#include "configuration.hh"
#include "mapper_mmc1.hh"
using namespace jones;
namespace jc = jones::configuration;
mapper_mmc1::mapper_mmc1(mapper_view const &mapper_view)
: mapper(mapper_view), shift_register_(0x10) {
auto const &cartridge = mapper_view.cartridge();
prg_rom_size_ = cartridge.header()->prgrom_size();
if (prg_rom_size_ > 0) {
prg_rom_ = cartridge.address() + cartridge.header()->prgrom_offset();
}
chr_rom_size_ = cartridge.header()->chrrom_size();
if (chr_rom_size_ > 0) {
chr_rom_ = cartridge.address() + cartridge.header()->chrrom_offset();
} else {
chr_ram_.resize(8192);
chr_rom_size_ = 8192;
chr_rom_ = &chr_ram_[0];
}
sram_.resize(0x2000);
std::fill(sram_.begin(), sram_.end(), 0);
prg_offsets_[1] = get_prg_bank_offset(-1);
mapper_view.cpu_memory().map(std::make_unique<memory_mappable_component<mapper_mmc1>>(this, "mapper_mmc1", 0x6000, 0xFFFF));
mapper_view.ppu_memory().map(std::make_unique<memory_mappable_component<mapper_mmc1>>(this, "mapper_mmc1", 0x0000, 0x1FFF));
}
auto mapper_mmc1::get_prg_bank_offset(int const index) const -> uint16_t {
auto adjusted_index = index;
if (adjusted_index >= 0x80) {
adjusted_index -= 0x100;
}
adjusted_index %= prg_rom_size_ / 0x4000;
auto offset = adjusted_index * 0x4000;
if (offset < 0) {
offset += prg_rom_size_;
}
return offset;
}
auto mapper_mmc1::get_chr_bank_offset(int const index) const -> uint16_t {
auto adjusted_index = index;
if (adjusted_index >= 0x80) {
adjusted_index -= 0x100;
}
adjusted_index %= chr_rom_size_ / 0x1000;
auto offset = adjusted_index * 0x1000;
if (offset < 0) {
offset += chr_rom_size_;
}
return offset;
}
auto mapper_mmc1::update_offsets() -> void {
switch (prg_mode_) {
case 0:
case 1: {
prg_offsets_[0] = get_prg_bank_offset(prg_bank_ & 0xFEU);
prg_offsets_[1] = get_prg_bank_offset(prg_bank_ | 0x01U);
break;
}
case 2: {
prg_offsets_[0] = 0;
prg_offsets_[1] = get_prg_bank_offset(prg_bank_);
break;
}
case 3: {
prg_offsets_[0] = get_prg_bank_offset(prg_bank_);
prg_offsets_[1] = get_prg_bank_offset(-1);
break;
}
}
switch (chr_mode_) {
case 0: {
chr_offsets_[0] = get_chr_bank_offset(chr_bank_[0] & 0xFEU);
chr_offsets_[1] = get_chr_bank_offset(chr_bank_[0] | 0x01U);
break;
}
case 1: {
chr_offsets_[0] = get_chr_bank_offset(chr_bank_[0]);
chr_offsets_[1] = get_chr_bank_offset(chr_bank_[1]);
break;
}
}
}
auto mapper_mmc1::peek(uint16_t const address) const -> uint8_t {
return read(address);
}
auto mapper_mmc1::read(uint16_t const address) const -> uint8_t {
if (address < 0x2000) {
auto const bank = address / 0x1000;
auto const offset = address % 0x1000;
auto const chr_offset = chr_offsets_[bank] + offset;
return chr_rom_[chr_offset];
}
if (address >= 0x8000) {
auto const adjusted_address = address - 0x8000;
auto const bank = adjusted_address / 0x4000;
auto const offset = adjusted_address % 0x4000;
auto const prg_offset = prg_offsets_[bank] + offset;
return prg_rom_[prg_offset];
}
if (address >= 0x6000) {
auto const adjusted_address = address - 0x6000;
return sram_[adjusted_address];
}
BOOST_STATIC_ASSERT("unexpected read for mmc1 mapper");
return 0;
}
auto mapper_mmc1::write(uint16_t const address, uint8_t const data) -> void {
if (address < 0x2000) {
auto const bank = address / 0x1000;
auto const offset = address % 0x1000;
auto const chr_offset = chr_offsets_[bank] + offset;
chr_rom_[chr_offset] = data;
}
if (address >= 0x8000) {
load_register(address, data);
}
if (address >= 0x6000) {
auto const adjusted_address = address - 0x6000;
sram_[adjusted_address] = data;
}
BOOST_STATIC_ASSERT("unexpected read for mmc1 mapper");
}
auto mapper_mmc1::load_register(uint16_t const address, uint8_t const data) -> void {
if ((data & 0x80U) == 0x80U) {
shift_register_ = 0x10U;
write_control_register(control_register_ | 0x0CU);
} else {
auto const is_register_complete = (shift_register_ & 1) == 1;
shift_register_ >>= 1U;
shift_register_ |= (data & 1U) << 4;
if (is_register_complete) {
write_register(address, shift_register_);
shift_register_ = 0x10;
}
}
}
auto mapper_mmc1::write_register(uint16_t const address, uint8_t const data) -> void {
if (address <= 0x9FFF) {
write_control_register(data);
} else if (address <= 0xBFFF) {
write_chr_bank_zero(data);
} else if (address <= 0xDFFF) {
write_chr_bank_one(data);
} else {
write_prg_bank(data);
}
}
auto mapper_mmc1::write_chr_bank_zero(const uint8_t data) -> void {
chr_bank_[0] = data;
update_offsets();
}
auto mapper_mmc1::write_chr_bank_one(const uint8_t data) -> void {
chr_bank_[1] = data;
update_offsets();
}
auto mapper_mmc1::write_prg_bank(const uint8_t data) -> void {
prg_bank_ = data & 0x0FU;
}
auto mapper_mmc1::write_control_register(const uint8_t data) -> void {
control_register_ = data;
chr_mode_ = (data >> 4U) & 1U;
prg_mode_ = (data >> 2U) & 3U;
auto const mirror_mode = jc::get_mirror_mode(data & 3U);
jc::configuration::instance().set<uint8_t>(jc::property::PROPERTY_MIRROR_MODE, mirror_mode);
update_offsets();
}
| 30.394366 | 126 | 0.700958 | JonForShort |
e43ee07a179e9a0ecad7a3794d5dd19de8d227e9 | 859 | cpp | C++ | SlatebackAppCLI/src/commands/ChangeRoll.cpp | filmbrood/Slateback | b512df3b3f13ba152bcf0801c2ad36676d57d2e2 | [
"MIT"
] | null | null | null | SlatebackAppCLI/src/commands/ChangeRoll.cpp | filmbrood/Slateback | b512df3b3f13ba152bcf0801c2ad36676d57d2e2 | [
"MIT"
] | 2 | 2020-09-22T09:19:48.000Z | 2020-09-22T09:28:57.000Z | SlatebackAppCLI/src/commands/ChangeRoll.cpp | filmbrood/Slateback | b512df3b3f13ba152bcf0801c2ad36676d57d2e2 | [
"MIT"
] | 1 | 2020-09-22T09:23:44.000Z | 2020-09-22T09:23:44.000Z | #include "sltcli_pch.h"
void ChangeRoll::OnInit()
{
SetInput("changeroll");
SetDesc("Change the active camera roll.");
}
void ChangeRoll::OnUpdate()
{
LoadSltProjXML("No projects created");
Camera& activeCamera = Controller::Get().GetActiveCamera();
std::cout << "Change active roll to: " << std::endl;
for (unsigned int i = 0; i < activeCamera.GetRollCount(); i++)
std::cout << i << " - " << activeCamera.GetRoll(i).GetID() << std::endl;
std::string userinput;
UserPrompt(userinput, "");
for (unsigned int i = 0; i < activeCamera.GetRollCount(); i++)
{
if (userinput == std::to_string(i))
{
Controller::Get().ChangeActiveRoll(i);
std::cout << "Active roll changed to " << Controller::Get().GetActiveRoll().GetID() << std::endl;
Serializer::Get().SerializeProjectVector(Controller::Get().GetProjectVector());
break;
}
}
}
| 26.030303 | 100 | 0.66007 | filmbrood |
e4405cb598f66ec3b8d127f361e2be5e4b876a5b | 14,457 | cpp | C++ | tests/collection/test_download_data.cpp | adrianghc/HEMS | 94ffd85a050211efc6ef785b873ee39e906a8b78 | [
"MIT"
] | 4 | 2021-06-05T22:32:21.000Z | 2022-03-15T11:05:13.000Z | tests/collection/test_download_data.cpp | adrianghc/HEMS | 94ffd85a050211efc6ef785b873ee39e906a8b78 | [
"MIT"
] | 4 | 2021-06-06T10:23:28.000Z | 2021-06-06T10:42:24.000Z | tests/collection/test_download_data.cpp | adrianghc/HEMS | 94ffd85a050211efc6ef785b873ee39e906a8b78 | [
"MIT"
] | 1 | 2021-08-25T13:20:34.000Z | 2021-08-25T13:20:34.000Z | /*
* Copyright (c) 2020-2021 Adrian Georg Herrmann
*
* These are unit tests for the Measurement Collection Module.
*/
#include <cstdlib>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "../test.hpp"
#include "../extras/dummy_logger.hpp"
#include "hems/modules/collection/collection.h"
#include "hems/messages/storage.h"
#include "hems/common/modules.h"
#include "hems/common/types.h"
namespace hems { namespace modules { namespace collection {
using boost::posix_time::ptime;
using boost::posix_time::time_from_string;
using hems::types::id_t;
/**
* @brief This class exists to provide access to private members of `hems_collection`.
*/
class collection_test : public hems_collection {
public:
collection_test() : hems_collection(true) {};
int download_energy_production_(ptime time) {
return download_energy_production(time);
}
// int download_energy_consumption_(ptime time, id_t appliance) {
// return download_energy_consumption(time, appliance);
// }
int download_weather_data_(ptime time, id_t station) {
return download_weather_data(time, station);
}
enum response_code {
SUCCESS = 0x00,
INVALID_DATA,
UNREACHABLE_SOURCE,
INVALID_RESPONSE_SOURCE,
DATA_STORAGE_MODULE_ERR
};
};
int handler_set_energy_production_success(text_iarchive& ia, text_oarchive* oa) {
return 0;
}
int handler_set_energy_production_fail(text_iarchive& ia, text_oarchive* oa) {
return 1;
}
int handler_del_energy_production(text_iarchive& ia, text_oarchive* oa) {
return 0;
}
int handler_set_weather_success(text_iarchive& ia, text_oarchive* oa) {
return 0;
}
int handler_set_weather_fail(text_iarchive& ia, text_oarchive* oa) {
return 1;
}
int handler_del_weather(text_iarchive& ia, text_oarchive* oa) {
return 0;
}
pid_t start_source_server(std::string path) {
const char* argv[] = { path.c_str(), (char*) nullptr };
switch (pid_t pid = fork()) {
case -1:
return 0;
break;
case 0:
execv(path.c_str(), const_cast<char* const*>(argv));
/* `exec` only returns if something failed, so if the next line is ever
reached, something went wrong. We use `std::exit()` directly here
because we don't want a fork of the launcher module to call its destructor
as well. */
std::exit(EXIT_FAILURE);
break;
default:
return pid;
break;
}
}
bool init_test(
collection_test* this_instance, messenger* messenger_storage, const messenger::msg_handler_map& handler_map
) {
hems::logger::this_logger = new hems::dummy_logger();
/* Open message queues. */
struct mq_attr attr = {
mq_flags : 0,
mq_maxmsg : 10,
mq_msgsize : sizeof(messenger::msg_t),
mq_curmsgs : 0
};
mq_close(mq_open(
messenger::mq_names.at(modules::type::STORAGE).c_str(), O_RDWR | O_CLOEXEC | O_CREAT, 0666, &attr
));
mq_close(mq_open(
messenger::mq_res_names.at(modules::type::STORAGE).c_str(), O_RDWR | O_CLOEXEC | O_CREAT, 0666, &attr
));
mq_close(mq_open(
messenger::mq_names.at(modules::type::COLLECTION).c_str(), O_RDWR | O_CLOEXEC | O_CREAT, 0666, &attr
));
mq_close(mq_open(
messenger::mq_res_names.at(modules::type::COLLECTION).c_str(), O_RDWR | O_CLOEXEC | O_CREAT, 0666, &attr
));
/* Start listen loop for fake Data Storage Module. */
messenger_storage = new hems::messenger(modules::type::STORAGE, true);
if (!messenger_storage->listen(handler_map)) {
std::cout << "Starting listen loop failed.\n";
return false;
}
messenger_storage->start_handlers();
/* Construct Measurement Collection Module. */
try {
this_instance = new collection_test();
} catch (int err) {
std::cout <<
"Constructing Data Storage Module threw an exception " + std::to_string(err) + ", test failed.\n";
return false;
}
return true;
}
void end_test(collection_test* this_instance, messenger* messenger_storage) {
delete messenger_storage;
delete this_instance;
mq_unlink(messenger::mq_names.at(modules::type::COLLECTION).c_str());
mq_unlink(messenger::mq_names.at(modules::type::STORAGE).c_str());
delete logger::this_logger;
}
bool test_energy_production() {
const messenger::msg_handler_map handler_map_fail = {
{ messages::storage::MSG_SET_ENERGY_PRODUCTION, &handler_set_energy_production_fail },
{ messages::storage::MSG_DEL_ENERGY_PRODUCTION, &handler_del_energy_production },
};
const messenger::msg_handler_map handler_map_success = {
{ messages::storage::MSG_SET_ENERGY_PRODUCTION, &handler_set_energy_production_success },
{ messages::storage::MSG_DEL_ENERGY_PRODUCTION, &handler_del_energy_production },
};
bool success = true;
int res;
collection_test* this_instance = nullptr;
messenger* messenger_storage = nullptr;
if (!init_test(this_instance, messenger_storage, handler_map_fail)) {
return false;
}
/* Test unreachable source server. */
res = this_instance->download_energy_production_(time_from_string("9999-01-01 00:00:00.000"));
if (res != collection_test::response_code::UNREACHABLE_SOURCE) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::UNREACHABLE_SOURCE) +
" returned " + std::to_string(res) + " instead.\n";
success = false;
}
/* Start source server. */
pid_t pid = start_source_server("collection/energy_production_provider/run.sh");
if (!pid) {
std::cout << "Could not start source server.\n";
return false;
}
sleep(2);
/* Test invalid values. */
std::vector<std::string> time_strings_1 = {
"2020-02-20 20:00:00.123",
"2020-02-20 20:00:20.000",
"2020-02-20 20:20:00.000"
};
for (const auto& time_string : time_strings_1) {
res = this_instance->download_energy_production_(time_from_string(time_string));
if (res != collection_test::response_code::INVALID_DATA) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::INVALID_DATA) + " returned " +
std::to_string(res) + " instead.\n";
success = false;
}
}
/* Test valid value, invalid response from source server. */
res = this_instance->download_energy_production_(time_from_string("9999-01-01 00:00:00.000"));
if (res != collection_test::response_code::INVALID_RESPONSE_SOURCE) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::INVALID_RESPONSE_SOURCE) +
" returned " + std::to_string(res) + " instead.\n";
success = false;
}
/* Test valid value, error from Data Storage Module. */
res = this_instance->download_energy_production_(time_from_string("2020-02-20 20:00:00.000"));
if (res != collection_test::response_code::DATA_STORAGE_MODULE_ERR) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::DATA_STORAGE_MODULE_ERR) +
" returned " + std::to_string(res) + " instead.\n";
success = false;
}
end_test(this_instance, messenger_storage);
/* Test valid value, no errors. */
if (!init_test(this_instance, messenger_storage, handler_map_success)) {
return false;
}
res = this_instance->download_energy_production_(time_from_string("2020-02-20 20:00:00.000"));
if (res != collection_test::response_code::SUCCESS) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::SUCCESS) + " returned " +
std::to_string(res) + " instead.\n";
success = false;
}
end_test(this_instance, messenger_storage);
kill(pid, SIGKILL);
return success;
}
bool test_weather() {
const messenger::msg_handler_map handler_map_fail = {
{ messages::storage::MSG_SET_WEATHER, &handler_set_weather_fail },
{ messages::storage::MSG_DEL_WEATHER, &handler_del_weather },
};
const messenger::msg_handler_map handler_map_success = {
{ messages::storage::MSG_SET_WEATHER, &handler_set_weather_success },
{ messages::storage::MSG_DEL_WEATHER, &handler_del_weather },
};
bool success = true;
int res;
collection_test* this_instance = nullptr;
messenger* messenger_storage = nullptr;
if (!init_test(this_instance, messenger_storage, handler_map_fail)) {
return false;
}
double longitude_valid = 13.296937;
double latitude_valid = 52.455864;
double timezone_valid = 1;
std::string time_string_valid = "2020-02-20 20:00:00.000";
id_t station_valid = 1;
types::settings_t settings = {
longitude : longitude_valid,
latitude : latitude_valid,
timezone : timezone_valid,
pv_uri : "",
station_intervals : { {1, 15}, {2, 30} },
station_uris : {},
interval_energy_production : 10,
interval_energy_consumption : 20,
interval_automation : 36
};
current_settings = settings;
/* Test unreachable source server. */
res = this_instance->download_weather_data_(
time_from_string("9999-01-01 00:00:00.000"), station_valid
);
if (res != collection_test::response_code::UNREACHABLE_SOURCE) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::UNREACHABLE_SOURCE) +
" returned " + std::to_string(res) + " instead.\n";
success = false;
}
/* Start source server. */
pid_t pid = start_source_server("collection/weather_provider/run.sh");
if (!pid) {
std::cout << "Could not start source server.\n";
return false;
}
sleep(2);
/* Test invalid values (time). */
std::vector<std::string> time_strings_1 = {
"2020-02-20 20:00:00.123",
"2020-02-20 20:00:20.000",
"2020-02-20 20:33:00.000"
};
for (const auto& time_string : time_strings_1) {
res = this_instance->download_weather_data_(
time_from_string(time_string), station_valid
);
if (res != collection_test::response_code::INVALID_DATA) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::INVALID_DATA) + " returned " +
std::to_string(res) + " instead.\n";
success = false;
}
}
/* Test valid value, invalid response from source server. */
res = this_instance->download_weather_data_(
time_from_string("9999-01-01 00:00:00.000"), station_valid
);
if (res != collection_test::response_code::INVALID_RESPONSE_SOURCE) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::INVALID_RESPONSE_SOURCE) +
" returned " + std::to_string(res) + " instead.\n";
success = false;
}
/* Test valid value, error from Data Storage Module. */
res = this_instance->download_weather_data_(
time_from_string("2020-02-20 20:00:00.000"), station_valid
);
if (res != collection_test::response_code::DATA_STORAGE_MODULE_ERR) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::DATA_STORAGE_MODULE_ERR) +
" returned " + std::to_string(res) + " instead.\n";
success = false;
}
end_test(this_instance, messenger_storage);
/* Test valid value, no errors. */
if (!init_test(this_instance, messenger_storage, handler_map_success)) {
return false;
}
res = this_instance->download_weather_data_(
time_from_string("2020-02-20 20:00:00.000"), station_valid
);
if (res != collection_test::response_code::SUCCESS) {
std::cout <<
"Call that should have returned " +
std::to_string(collection_test::response_code::SUCCESS) + " returned " +
std::to_string(res) + " instead.\n";
success = false;
}
end_test(this_instance, messenger_storage);
kill(pid, SIGKILL);
return success;
}
}}}
int main() {
return run_tests({
{
"01 Collection: Download energy production data test",
&hems::modules::collection::test_energy_production
},
{
"02 Collection: Download weather data test",
&hems::modules::collection::test_weather
}
});
}
| 35.784653 | 116 | 0.578682 | adrianghc |
e440c186df9c4351018a6ca10a5d689216c71b4a | 188 | cpp | C++ | set_matrix_zeroes.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | null | null | null | set_matrix_zeroes.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | 1 | 2020-12-17T07:54:03.000Z | 2020-12-17T08:00:22.000Z | set_matrix_zeroes.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | null | null | null | /**
* https://leetcode-cn.com/problems/set-matrix-zeroes/
*
* @author spencercjh
*/
class SetMatrixZeroes {
public:
void setZeroes(vector<vector<int>>& matrix) {
}
}
| 14.461538 | 54 | 0.62234 | spencercjh |
e4487fad43edde1a1fe15e3acce8c27d474fe4ba | 33,669 | cpp | C++ | retrace/daemon/glframe_state_override.cpp | devcode1981/apitrace | cf11139d6a05688b55c3ab08844a4c9c3c736ea2 | [
"MIT"
] | 1 | 2021-03-05T10:49:37.000Z | 2021-03-05T10:49:37.000Z | retrace/daemon/glframe_state_override.cpp | MarcelRaschke/apitrace | cf11139d6a05688b55c3ab08844a4c9c3c736ea2 | [
"MIT"
] | null | null | null | retrace/daemon/glframe_state_override.cpp | MarcelRaschke/apitrace | cf11139d6a05688b55c3ab08844a4c9c3c736ea2 | [
"MIT"
] | 1 | 2018-10-05T03:09:13.000Z | 2018-10-05T03:09:13.000Z | // Copyright (C) Intel Corp. 2017. All Rights Reserved.
// 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 (including the
// next paragraph) 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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.
// **********************************************************************/
// * Authors:
// * Mark Janes <mark.a.janes@intel.com>
// **********************************************************************/
// **********************************************************************/
// Checklist for enabling state overrides:
// - in dispatch/glframe_glhelper.hpp
// - add entry point for required GL calls in the header
// - glframe_glhelper.cpp
// - declare static pointer to GL function
// - look up function pointer in ::Init
// - implement entry point to call GL function at the pointer
// - in glframe_state_enums.cpp:
// - for overrides with choices, add all possibilities to
// state_name_to_choices (including true/false state)
// - add all enum values in state_name_to_enum
// - add all enum values in state_enum_to_name
// - if state item has multiple values (eg ClearColor value is
// RGBA), define the indices that should be displayed for each
// value in state_name_to_indices.
// - in glframe_state_override.cpp
// - add entries to ::interpret_value, which converts a string
// representation of the items value into the bytes sent to the
// GL. Internally, StateOverride holds the data as uint32_t, and
// converts them to the appropriate type before calling the GL.
// - add entries to ::state_type, which indicates which GL call
// retrieves the current state of the item, and converting into
// bytes uint32_t.
// - add entries to ::enact_state, which calls the GL to set state
// according to what is stored in StateOverride. Convert the
// bytes from uint32_t to whatever is required by the GL api
// before calling the GL entry point.
// - add entries to ::onState, which queries current state from the
// GL and makes the onState callback to pass data back to the UI.
// For each entry, choose a hierarchical path to help organize
// the state in the UI.
// **********************************************************************/
#include "glframe_state_override.hpp"
#include <stdio.h>
#include <map>
#include <string>
#include <vector>
#include "glframe_glhelper.hpp"
#include "glframe_state_enums.hpp"
using glretrace::ExperimentId;
using glretrace::OnFrameRetrace;
using glretrace::RenderId;
using glretrace::SelectionId;
using glretrace::StateOverride;
using glretrace::StateKey;
union IntFloat {
uint32_t i;
float f;
};
void
StateOverride::setState(const StateKey &item,
int offset,
const std::string &value) {
auto &i = m_overrides[item];
if (i.empty()) {
// save the prior state so we can restore it
getState(item, &i);
m_saved_state[item] = i;
}
const uint32_t data_value = interpret_value(item, value);
// for GL4, front and back face are latched
if (item.name == "GL_POLYGON_MODE") {
GlFunctions::PolygonMode(GL_FRONT, m_saved_state[item][0]);
// if glPolygonMode reports error, then it only accepts
// GL_FRONT_AND_BACK
GLenum err = GL::GetError();
if (err != GL_NO_ERROR) {
// set all offsets to the new value
for (auto &face : i)
face = data_value;
return;
}
}
i[offset] = data_value;
}
// The UI uses strings for all state values. The override model
// stores all data types in a vector of uint32_t.
uint32_t
StateOverride::interpret_value(const StateKey &item,
const std::string &value) {
switch (state_name_to_enum(item.name)) {
// enumeration values
// true/false values
case GL_BLEND:
case GL_BLEND_DST:
case GL_BLEND_DST_ALPHA:
case GL_BLEND_DST_RGB:
case GL_BLEND_EQUATION_ALPHA:
case GL_BLEND_EQUATION_RGB:
case GL_BLEND_SRC:
case GL_BLEND_SRC_ALPHA:
case GL_BLEND_SRC_RGB:
case GL_COLOR_WRITEMASK:
case GL_CULL_FACE:
case GL_CULL_FACE_MODE:
case GL_LINE_SMOOTH:
case GL_DEPTH_FUNC:
case GL_DEPTH_TEST:
case GL_DEPTH_WRITEMASK:
case GL_DITHER:
case GL_FRONT_FACE:
case GL_POLYGON_MODE:
case GL_POLYGON_OFFSET_FILL:
case GL_SAMPLE_COVERAGE_INVERT:
case GL_SCISSOR_TEST:
case GL_STENCIL_BACK_FAIL:
case GL_STENCIL_BACK_FUNC:
case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_PASS:
case GL_STENCIL_FAIL:
case GL_STENCIL_FUNC:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_TEST:
return state_name_to_enum(value);
// float values
case GL_BLEND_COLOR:
case GL_COLOR_CLEAR_VALUE:
case GL_DEPTH_CLEAR_VALUE:
case GL_DEPTH_RANGE:
case GL_LINE_WIDTH:
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_UNITS:
case GL_SAMPLE_COVERAGE_VALUE:
{
IntFloat i_f;
i_f.f = std::stof(value);
return i_f.i;
}
// int values
case GL_SCISSOR_BOX:
return std::stoi(value);
// hex values
case GL_STENCIL_BACK_REF:
case GL_STENCIL_BACK_VALUE_MASK:
case GL_STENCIL_BACK_WRITEMASK:
case GL_STENCIL_CLEAR_VALUE:
case GL_STENCIL_REF:
case GL_STENCIL_VALUE_MASK:
case GL_STENCIL_WRITEMASK:
return std::stoul(value, 0, 16);
default:
assert(false);
return 0;
}
}
enum StateCategory {
kStateEnabled,
kStateBoolean,
kStateBoolean4,
kStateInteger,
kStateInteger2,
kStateInteger4,
kStateFloat,
kStateFloat2,
kStateFloat4,
kStateInvalid
};
StateCategory
state_type(uint32_t state) {
switch (state) {
case GL_BLEND:
case GL_CULL_FACE:
case GL_DEPTH_TEST:
case GL_DITHER:
case GL_LINE_SMOOTH:
case GL_POLYGON_OFFSET_FILL:
case GL_SCISSOR_TEST:
case GL_STENCIL_TEST:
return kStateEnabled;
case GL_BLEND_DST:
case GL_BLEND_DST_ALPHA:
case GL_BLEND_DST_RGB:
case GL_BLEND_EQUATION_ALPHA:
case GL_BLEND_EQUATION_RGB:
case GL_BLEND_SRC:
case GL_BLEND_SRC_ALPHA:
case GL_BLEND_SRC_RGB:
case GL_CULL_FACE_MODE:
case GL_DEPTH_FUNC:
case GL_FRONT_FACE:
case GL_STENCIL_BACK_FAIL:
case GL_STENCIL_BACK_FUNC:
case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_PASS:
case GL_STENCIL_BACK_REF:
case GL_STENCIL_BACK_VALUE_MASK:
case GL_STENCIL_BACK_WRITEMASK:
case GL_STENCIL_CLEAR_VALUE:
case GL_STENCIL_FAIL:
case GL_STENCIL_FUNC:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_REF:
case GL_STENCIL_VALUE_MASK:
case GL_STENCIL_WRITEMASK:
return kStateInteger;
case GL_COLOR_WRITEMASK:
return kStateBoolean4;
case GL_DEPTH_WRITEMASK:
case GL_SAMPLE_COVERAGE_INVERT:
return kStateBoolean;
case GL_BLEND_COLOR:
case GL_COLOR_CLEAR_VALUE:
return kStateFloat4;
case GL_DEPTH_CLEAR_VALUE:
case GL_LINE_WIDTH:
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_UNITS:
case GL_SAMPLE_COVERAGE_VALUE:
return kStateFloat;
case GL_DEPTH_RANGE:
return kStateFloat2;
case GL_SCISSOR_BOX:
return kStateInteger4;
case GL_POLYGON_MODE:
return kStateInteger2;
}
assert(false);
return kStateInvalid;
}
void
StateOverride::getState(const StateKey &item,
std::vector<uint32_t> *data) {
const auto n = state_name_to_enum(item.name);
data->clear();
switch (state_type(n)) {
case kStateEnabled: {
data->resize(1);
get_enabled_state(n, data);
break;
}
case kStateInteger: {
data->resize(1);
get_integer_state(n, data);
break;
}
case kStateBoolean4: {
data->resize(4);
get_bool_state(n, data);
break;
}
case kStateBoolean: {
data->resize(1);
get_bool_state(n, data);
break;
}
case kStateFloat4: {
data->resize(4);
get_float_state(n, data);
break;
}
case kStateFloat: {
data->resize(1);
get_float_state(n, data);
break;
}
case kStateFloat2: {
data->resize(2);
get_float_state(n, data);
break;
}
case kStateInteger2: {
data->resize(2);
get_integer_state(n, data);
break;
}
case kStateInteger4: {
data->resize(4);
get_integer_state(n, data);
break;
}
case kStateInvalid:
assert(false);
break;
}
}
void
StateOverride::get_enabled_state(GLint k,
std::vector<uint32_t> *data) {
GL::GetError();
assert(data->size() == 1);
(*data)[0] = GlFunctions::IsEnabled(k);
assert(!GL::GetError());
}
void
StateOverride::get_integer_state(GLint k,
std::vector<uint32_t> *data) {
GL::GetError();
GlFunctions::GetIntegerv(k, reinterpret_cast<GLint*>(data->data()));
assert(!GL::GetError());
}
void
StateOverride::get_bool_state(GLint k,
std::vector<uint32_t> *data) {
GL::GetError();
std::vector<GLboolean> b(data->size());
GlFunctions::GetBooleanv(k, b.data());
auto d = data->begin();
for (auto v : b) {
*d = v ? 1 : 0;
++d;
}
assert(!GL::GetError());
}
void
StateOverride::get_float_state(GLint k, std::vector<uint32_t> *data) {
GL::GetError();
GlFunctions::GetFloatv(k, reinterpret_cast<GLfloat*>(data->data()));
assert(!GL::GetError());
}
void
StateOverride::overrideState() const {
enact_state(m_overrides);
}
void
StateOverride::restoreState() const {
enact_state(m_saved_state);
}
void
StateOverride::enact_enabled_state(GLint setting, bool v) const {
if (v)
GlFunctions::Enable(setting);
else
GlFunctions::Disable(setting);
assert(GL::GetError() == GL_NO_ERROR);
}
void
StateOverride::enact_state(const KeyMap &m) const {
GL::GetError();
for (auto i : m) {
GL::GetError();
const auto n = state_name_to_enum(i.first.name);
switch (n) {
case GL_BLEND:
case GL_CULL_FACE:
case GL_DEPTH_TEST:
case GL_DITHER:
case GL_LINE_SMOOTH:
case GL_POLYGON_OFFSET_FILL:
case GL_SCISSOR_TEST:
case GL_STENCIL_TEST: {
enact_enabled_state(n, i.second[0]);
break;
}
case GL_BLEND_COLOR: {
std::vector<float> f(4);
IntFloat u;
for (int j = 0; j < 4; ++j) {
u.i = i.second[j];
f[j] = u.f;
}
GlFunctions::BlendColor(f[0], f[1], f[2], f[3]);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_BLEND_EQUATION_ALPHA:
case GL_BLEND_EQUATION_RGB: {
GLint modeRGB, modeAlpha;
GlFunctions::GetIntegerv(GL_BLEND_EQUATION_RGB, &modeRGB);
GlFunctions::GetIntegerv(GL_BLEND_EQUATION_ALPHA, &modeAlpha);
GlFunctions::BlendEquationSeparate(
n == GL_BLEND_EQUATION_RGB ? i.second[0] : modeRGB,
n == GL_BLEND_EQUATION_ALPHA ? i.second[0] : modeAlpha);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_BLEND_SRC:
case GL_BLEND_DST: {
GLint src, dst;
GlFunctions::GetIntegerv(GL_BLEND_DST, &dst);
GlFunctions::GetIntegerv(GL_BLEND_SRC, &src);
assert(GL::GetError() == GL_NO_ERROR);
GlFunctions::BlendFunc(
n == GL_BLEND_SRC ? i.second[0] : src,
n == GL_BLEND_DST ? i.second[0] : dst);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_BLEND_DST_ALPHA:
case GL_BLEND_DST_RGB:
case GL_BLEND_SRC_ALPHA:
case GL_BLEND_SRC_RGB: {
GLint src_rgb, dst_rgb, src_alpha, dst_alpha;
GlFunctions::GetIntegerv(GL_BLEND_SRC_RGB, &src_rgb);
GlFunctions::GetIntegerv(GL_BLEND_DST_RGB, &dst_rgb);
GlFunctions::GetIntegerv(GL_BLEND_SRC_ALPHA, &src_alpha);
GlFunctions::GetIntegerv(GL_BLEND_DST_ALPHA, &dst_alpha);
GlFunctions::BlendFuncSeparate(
n == GL_BLEND_SRC_RGB ? i.second[0] : src_rgb,
n == GL_BLEND_DST_RGB ? i.second[0] : dst_rgb,
n == GL_BLEND_SRC_ALPHA ? i.second[0] : src_alpha,
n == GL_BLEND_DST_ALPHA ? i.second[0] : dst_alpha);
break;
}
case GL_COLOR_CLEAR_VALUE: {
std::vector<float> f(4);
IntFloat u;
for (int j = 0; j < 4; ++j) {
u.i = i.second[j];
f[j] = u.f;
}
GlFunctions::ClearColor(f[0], f[1], f[2], f[3]);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_COLOR_WRITEMASK: {
GlFunctions::ColorMask(i.second[0],
i.second[1],
i.second[2],
i.second[3]);
break;
}
case GL_CULL_FACE_MODE: {
GlFunctions::CullFace(i.second[0]);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_DEPTH_CLEAR_VALUE: {
IntFloat u;
u.i = i.second[0];
GlFunctions::ClearDepthf(u.f);
break;
}
case GL_DEPTH_FUNC: {
GlFunctions::DepthFunc(i.second[0]);
break;
}
case GL_LINE_WIDTH: {
assert(i.second.size() == 1);
IntFloat u;
u.i = i.second[0];
GlFunctions::LineWidth(u.f);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_DEPTH_RANGE: {
assert(i.second.size() == 2);
IntFloat _near, _far;
_near.i = i.second[0];
_far.i = i.second[1];
GlFunctions::DepthRangef(_near.f, _far.f);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_DEPTH_WRITEMASK: {
GlFunctions::DepthMask(i.second[0]);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_FRONT_FACE: {
GlFunctions::FrontFace(i.second[0]);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_POLYGON_MODE: {
GlFunctions::PolygonMode(GL_FRONT, i.second[0]);
GlFunctions::PolygonMode(GL_BACK, i.second[1]);
GLenum err = GL::GetError();
if (err != GL_NO_ERROR)
GlFunctions::PolygonMode(GL_FRONT_AND_BACK, i.second[0]);
break;
}
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_UNITS: {
GLfloat factor, units;
GlFunctions::GetFloatv(GL_POLYGON_OFFSET_FACTOR, &factor);
GlFunctions::GetFloatv(GL_POLYGON_OFFSET_UNITS, &units);
IntFloat convert;
convert.i = i.second[0];
GlFunctions::PolygonOffset(
n == GL_POLYGON_OFFSET_FACTOR ? convert.f : factor,
n == GL_POLYGON_OFFSET_UNITS ? convert.f : units);
assert(GL::GetError() == GL_NO_ERROR);
break;
}
case GL_SAMPLE_COVERAGE_INVERT:
case GL_SAMPLE_COVERAGE_VALUE: {
GLfloat value;
GLboolean invert;
GlFunctions::GetFloatv(GL_SAMPLE_COVERAGE_VALUE, &value);
GlFunctions::GetBooleanv(GL_SAMPLE_COVERAGE_INVERT, &invert);
IntFloat convert;
convert.i = i.second[0];
GlFunctions::SampleCoverage(
n == GL_SAMPLE_COVERAGE_VALUE ? convert.f : value,
n == GL_SAMPLE_COVERAGE_INVERT ? i.second[0] : invert);
break;
}
case GL_SCISSOR_BOX: {
GlFunctions::Scissor(i.second[0], i.second[1],
i.second[2], i.second[3]);
break;
}
case GL_STENCIL_BACK_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_PASS: {
GLint sfail = 0, dpfail = 0, dppass = 0;
GlFunctions::GetIntegerv(GL_STENCIL_BACK_FAIL, &sfail);
GlFunctions::GetIntegerv(
GL_STENCIL_BACK_PASS_DEPTH_FAIL, &dpfail);
GlFunctions::GetIntegerv(
GL_STENCIL_BACK_PASS_DEPTH_PASS, &dppass);
GlFunctions::StencilOpSeparate(
GL_BACK,
n == GL_STENCIL_BACK_FAIL ? i.second[0] : sfail,
n == GL_STENCIL_BACK_PASS_DEPTH_FAIL ? i.second[0] : dpfail,
n == GL_STENCIL_BACK_PASS_DEPTH_PASS ? i.second[0] : dppass);
break;
}
case GL_STENCIL_BACK_FUNC:
case GL_STENCIL_BACK_REF:
case GL_STENCIL_BACK_VALUE_MASK: {
GLint func = 0, ref = 0, mask = 0;
GlFunctions::GetIntegerv(GL_STENCIL_BACK_FUNC, &func);
GlFunctions::GetIntegerv(GL_STENCIL_BACK_REF, &ref);
GlFunctions::GetIntegerv(GL_STENCIL_BACK_VALUE_MASK, &mask);
GlFunctions::StencilFuncSeparate(
GL_BACK,
n == GL_STENCIL_BACK_FUNC ? i.second[0] : func,
n == GL_STENCIL_BACK_REF ? i.second[0] : ref,
n == GL_STENCIL_BACK_VALUE_MASK ? i.second[0] : mask);
break;
}
case GL_STENCIL_FAIL:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS: {
GLint sfail, dpfail, dppass;
GlFunctions::GetIntegerv(GL_STENCIL_FAIL, &sfail);
GlFunctions::GetIntegerv(
GL_STENCIL_PASS_DEPTH_FAIL, &dpfail);
GlFunctions::GetIntegerv(
GL_STENCIL_PASS_DEPTH_PASS, &dppass);
GlFunctions::StencilOpSeparate(
GL_FRONT,
n == GL_STENCIL_FAIL ? i.second[0] : sfail,
n == GL_STENCIL_PASS_DEPTH_FAIL ? i.second[0] : dpfail,
n == GL_STENCIL_PASS_DEPTH_PASS ? i.second[0] : dppass);
break;
}
case GL_STENCIL_FUNC:
case GL_STENCIL_REF:
case GL_STENCIL_VALUE_MASK: {
GLint func = 0, ref = 0, mask = 0;
GlFunctions::GetIntegerv(GL_STENCIL_FUNC, &func);
GlFunctions::GetIntegerv(GL_STENCIL_REF, &ref);
GlFunctions::GetIntegerv(GL_STENCIL_VALUE_MASK, &mask);
GlFunctions::StencilFuncSeparate(
GL_FRONT,
n == GL_STENCIL_FUNC ? i.second[0] : func,
n == GL_STENCIL_REF ? i.second[0] : ref,
n == GL_STENCIL_VALUE_MASK ? i.second[0] : mask);
break;
}
case GL_STENCIL_WRITEMASK:
case GL_STENCIL_BACK_WRITEMASK: {
GlFunctions::StencilMaskSeparate(
n == GL_STENCIL_WRITEMASK ? GL_FRONT : GL_BACK,
i.second[0]);
break;
}
case GL_STENCIL_CLEAR_VALUE: {
GlFunctions::ClearStencil(i.second[0]);
break;
}
case GL_INVALID_ENUM:
default:
assert(false);
break;
}
}
}
void floatStrings(const std::vector<uint32_t> &i,
std::vector<std::string> *s) {
s->clear();
IntFloat u;
for (auto d : i) {
u.i = d;
s->push_back(std::to_string(u.f));
}
}
void intStrings(const std::vector<uint32_t> &i,
std::vector<std::string> *s) {
s->clear();
for (auto d : i) {
s->push_back(std::to_string(d));
}
}
void floatString(const uint32_t i,
std::string *s) {
IntFloat u;
u.i = i;
*s = std::to_string(u.f);
}
void hexString(const uint32_t i,
std::string *s) {
std::vector<char> hexstr(11);
snprintf(hexstr.data(), hexstr.size(), "0x%08x", i);
*s = hexstr.data();
}
bool
is_supported(uint32_t state) {
glretrace::GL::GetError();
std::vector<uint32_t> data(4);
switch (state_type(state)) {
case kStateEnabled:
glretrace::GL::IsEnabled(state);
break;
case kStateInteger:
case kStateInteger2:
case kStateInteger4:
glretrace::GL::GetIntegerv(state, reinterpret_cast<GLint*>(data.data()));
break;
case kStateBoolean:
case kStateBoolean4:
glretrace::GL::GetBooleanv(state,
reinterpret_cast<GLboolean*>(data.data()));
break;
case kStateFloat:
case kStateFloat2:
case kStateFloat4:
glretrace::GL::GetFloatv(state, reinterpret_cast<GLfloat*>(data.data()));
break;
case kStateInvalid:
assert(false);
return false;
}
return(glretrace::GL::GetError() == false);
}
void
StateOverride::onState(SelectionId selId,
ExperimentId experimentCount,
RenderId renderId,
OnFrameRetrace *callback) {
std::vector<uint32_t> data;
// these entries are roughly in the order of the items in the glGet
// man page:
// https://www.khronos.org/registry/OpenGL-Refpages/es3.1/html/glGet.xhtml
if (is_supported(GL_CULL_FACE)) {
StateKey k("Primitive/Cull", "GL_CULL_FACE");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_CULL_FACE_MODE)) {
StateKey k("Primitive/Cull", "GL_CULL_FACE_MODE");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND)) {
StateKey k("Fragment/Blend", "GL_BLEND");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_BLEND_SRC)) {
StateKey k("Fragment/Blend", "GL_BLEND_SRC");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_SRC_ALPHA)) {
StateKey k("Fragment/Blend", "GL_BLEND_SRC_ALPHA");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_SRC_RGB)) {
StateKey k("Fragment/Blend", "GL_BLEND_SRC_RGB");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_DST)) {
StateKey k("Fragment/Blend", "GL_BLEND_DST");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_DST_ALPHA)) {
StateKey k("Fragment/Blend", "GL_BLEND_DST_ALPHA");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_DST_RGB)) {
StateKey k("Fragment/Blend", "GL_BLEND_DST_RGB");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_COLOR)) {
StateKey k("Fragment/Blend", "GL_BLEND_COLOR");
getState(k, &data);
std::vector<std::string> color;
floatStrings(data, &color);
callback->onState(selId, experimentCount, renderId, k, color);
}
if (is_supported(GL_LINE_WIDTH)) {
StateKey k("Primitive/Line", "GL_LINE_WIDTH");
getState(k, &data);
std::string value;
floatString(data[0], &value);
callback->onState(selId, experimentCount, renderId, k, {value});
}
if (is_supported(GL_LINE_SMOOTH)) {
StateKey k("Primitive/Line", "GL_LINE_SMOOTH");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_BLEND_EQUATION_RGB)) {
StateKey k("Fragment/Blend", "GL_BLEND_EQUATION_RGB");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_BLEND_EQUATION_ALPHA)) {
StateKey k("Fragment/Blend", "GL_BLEND_EQUATION_ALPHA");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_COLOR_CLEAR_VALUE)) {
StateKey k("Framebuffer", "GL_COLOR_CLEAR_VALUE");
getState(k, &data);
std::vector<std::string> color;
floatStrings(data, &color);
callback->onState(selId, experimentCount, renderId, k, color);
}
if (is_supported(GL_COLOR_WRITEMASK)) {
StateKey k("Framebuffer/Mask", "GL_COLOR_WRITEMASK");
getState(k, &data);
callback->onState(selId, experimentCount, renderId, k,
{data[0] ? "true" : "false",
data[1] ? "true" : "false",
data[2] ? "true" : "false",
data[3] ? "true" : "false"});
}
if (is_supported(GL_DEPTH_CLEAR_VALUE)) {
StateKey k("Fragment/Depth", "GL_DEPTH_CLEAR_VALUE");
getState(k, &data);
std::string value;
floatString(data[0], &value);
callback->onState(selId, experimentCount, renderId, k, {value});
}
if (is_supported(GL_DEPTH_FUNC)) {
StateKey k("Fragment/Depth", "GL_DEPTH_FUNC");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_DEPTH_RANGE)) {
StateKey k("Fragment/Depth", "GL_DEPTH_RANGE");
getState(k, &data);
std::vector<std::string> range;
floatStrings(data, &range);
callback->onState(selId, experimentCount, renderId,
k, range);
}
if (is_supported(GL_DEPTH_TEST)) {
StateKey k("Fragment/Depth", "GL_DEPTH_TEST");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_DEPTH_WRITEMASK)) {
StateKey k("Framebuffer/Mask", "GL_DEPTH_WRITEMASK");
getState(k, &data);
callback->onState(selId, experimentCount, renderId, k,
{data[0] ? "true" : "false"});
}
if (is_supported(GL_DITHER)) {
StateKey k("Framebuffer", "GL_DITHER");
getState(k, &data);
callback->onState(selId, experimentCount, renderId, k,
{data[0] ? "true" : "false"});
}
if (is_supported(GL_FRONT_FACE)) {
StateKey k("Primitive", "GL_FRONT_FACE");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_POLYGON_MODE)) {
StateKey k("Primitive/Polygon", "GL_POLYGON_MODE");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0]),
state_enum_to_name(data[1])});
}
if (is_supported(GL_POLYGON_OFFSET_FACTOR)) {
StateKey k("Primitive/Polygon", "GL_POLYGON_OFFSET_FACTOR");
getState(k, &data);
std::string value;
floatString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_POLYGON_OFFSET_FILL)) {
StateKey k("Primitive/Polygon", "GL_POLYGON_OFFSET_FILL");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_POLYGON_OFFSET_UNITS)) {
StateKey k("Primitive/Polygon", "GL_POLYGON_OFFSET_UNITS");
getState(k, &data);
std::string value;
floatString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_SAMPLE_COVERAGE_VALUE)) {
StateKey k("Fragment/Multisample", "GL_SAMPLE_COVERAGE_VALUE");
getState(k, &data);
std::string value;
floatString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_SAMPLE_COVERAGE_INVERT)) {
StateKey k("Fragment/Multisample", "GL_SAMPLE_COVERAGE_INVERT");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_SCISSOR_TEST)) {
StateKey k("Fragment/Scissor", "GL_SCISSOR_TEST");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_SCISSOR_BOX)) {
StateKey k("Fragment/Scissor", "GL_SCISSOR_BOX");
getState(k, &data);
std::vector<std::string> box;
intStrings(data, &box);
callback->onState(selId, experimentCount, renderId,
k, box);
}
if (is_supported(GL_STENCIL_BACK_FAIL)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_FAIL");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_BACK_PASS_DEPTH_FAIL)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_PASS_DEPTH_FAIL");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_BACK_PASS_DEPTH_PASS)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_PASS_DEPTH_PASS");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_BACK_FUNC)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_FUNC");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_BACK_REF)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_REF");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_STENCIL_BACK_VALUE_MASK)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_VALUE_MASK");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_STENCIL_BACK_WRITEMASK)) {
StateKey k("Stencil/Back", "GL_STENCIL_BACK_WRITEMASK");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_STENCIL_FAIL)) {
StateKey k("Stencil/Front", "GL_STENCIL_FAIL");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_PASS_DEPTH_FAIL)) {
StateKey k("Stencil/Front", "GL_STENCIL_PASS_DEPTH_FAIL");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_PASS_DEPTH_PASS)) {
StateKey k("Stencil/Front", "GL_STENCIL_PASS_DEPTH_PASS");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_TEST)) {
StateKey k("Stencil", "GL_STENCIL_TEST");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {data[0] ? "true" : "false"});
}
if (is_supported(GL_STENCIL_FUNC)) {
StateKey k("Stencil/Front", "GL_STENCIL_FUNC");
getState(k, &data);
callback->onState(selId, experimentCount, renderId,
k, {state_enum_to_name(data[0])});
}
if (is_supported(GL_STENCIL_REF)) {
StateKey k("Stencil/Front", "GL_STENCIL_REF");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_STENCIL_VALUE_MASK)) {
StateKey k("Stencil/Front", "GL_STENCIL_VALUE_MASK");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_STENCIL_WRITEMASK)) {
StateKey k("Stencil/Front", "GL_STENCIL_WRITEMASK");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
if (is_supported(GL_STENCIL_CLEAR_VALUE)) {
StateKey k("Stencil", "GL_STENCIL_CLEAR_VALUE");
getState(k, &data);
std::string value;
hexString(data[0], &value);
callback->onState(selId, experimentCount, renderId,
k, {value});
}
}
void
StateOverride::revertExperiments() {
m_overrides.clear();
}
void
StateOverride::revertState(const StateKey &item) {
auto i = m_overrides.find(item);
if (i != m_overrides.end())
m_overrides.erase(i);
}
| 32.405197 | 79 | 0.623719 | devcode1981 |
e44a36b4ed211a2cfc08b5d47c38c4ef1139b106 | 2,722 | cpp | C++ | libyangrtc2/src/yangrtp/YangRtpFUAPayload2.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 23 | 2021-09-13T06:24:34.000Z | 2022-03-24T10:05:12.000Z | libyangrtc2/src/yangrtp/YangRtpFUAPayload2.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | null | null | null | libyangrtc2/src/yangrtp/YangRtpFUAPayload2.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 9 | 2021-09-13T06:27:44.000Z | 2022-03-02T00:23:17.000Z | #include <yangrtp/YangRtpFUAPayload2.h>
#include <yangrtp/YangRtpConstant.h>
#include <yangutil/sys/YangLog.h>
int32_t yang_parseFua2(YangBuffer* buf,YangFua2Packet* pkt){
if (!buf->require(2)) {
return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 2);
}
// FU indicator, @see https://tools.ietf.org/html/rfc6184#section-5.8
uint8_t v = buf->read_1bytes();
pkt->nri = YangAvcNaluType(v & (~kNalTypeMask));
// FU header, @see https://tools.ietf.org/html/rfc6184#section-5.8
v = buf->read_1bytes();
pkt->start = v & kStart;
pkt->end = v & kEnd;
pkt->nalu_type = YangAvcNaluType(v & kNalTypeMask);
if (!buf->require(1)) {
return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 1);
}
return Yang_Ok;
}
YangRtpFUAPayload2::YangRtpFUAPayload2() {
m_start = m_end = false;
m_nri = m_nalu_type = (YangAvcNaluType) 0;
}
YangRtpFUAPayload2::~YangRtpFUAPayload2() {
}
uint64_t YangRtpFUAPayload2::nb_bytes() {
return 2 + m_size;
}
bool YangRtpFUAPayload2::getStart(){
return m_start;
}
int32_t YangRtpFUAPayload2::encode(YangBuffer *buf) {
if (!buf->require(2 + m_size)) {
return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 1);
}
// Fast encoding.
char *p = buf->head();
// FU indicator, @see https://tools.ietf.org/html/rfc6184#section-5.8
uint8_t fu_indicate = kFuA;
fu_indicate |= (m_nri & (~kNalTypeMask));
*p++ = fu_indicate;
// FU header, @see https://tools.ietf.org/html/rfc6184#section-5.8
uint8_t fu_header = m_nalu_type;
if (m_start) {
fu_header |= kStart;
}
if (m_end) {
fu_header |= kEnd;
}
*p++ = fu_header;
// FU payload, @see https://tools.ietf.org/html/rfc6184#section-5.8
memcpy(p, m_payload, m_size);
// Consume bytes.
buf->skip(2 + m_size);
return Yang_Ok;
}
int32_t YangRtpFUAPayload2::decode(YangBuffer *buf) {
if (!buf->require(2)) {
return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 2);
}
// FU indicator, @see https://tools.ietf.org/html/rfc6184#section-5.8
uint8_t v = buf->read_1bytes();
m_nri = YangAvcNaluType(v & (~kNalTypeMask));
// FU header, @see https://tools.ietf.org/html/rfc6184#section-5.8
v = buf->read_1bytes();
m_start = v & kStart;
m_end = v & kEnd;
m_nalu_type = YangAvcNaluType(v & kNalTypeMask);
if (!buf->require(1)) {
return yang_error_wrap(ERROR_RTC_RTP_MUXER, "requires %d bytes", 1);
}
m_payload = buf->head();
m_size = buf->left();
buf->skip(m_size);
return Yang_Ok;
}
YangRtpPayloader* YangRtpFUAPayload2::copy() {
YangRtpFUAPayload2 *cp = new YangRtpFUAPayload2();
cp->m_nri = m_nri;
cp->m_start = m_start;
cp->m_end = m_end;
cp->m_nalu_type = m_nalu_type;
cp->m_payload = m_payload;
cp->m_size = m_size;
return cp;
}
| 24.522523 | 71 | 0.691403 | yangxinghai |
e44c41c4358c6a96c70c4c55d3437ed39b0675e6 | 8,978 | cpp | C++ | source/windows/brwindowsd3d.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/windows/brwindowsd3d.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/windows/brwindowsd3d.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
Shims for d3d9.dll or d3dx9_43.dll
Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brwindowstypes.h"
#if defined(BURGER_WINDOWS) || defined(DOXYGEN)
#if !defined(DOXYGEN)
//
// Handle some annoying defines that some windows SDKs may or may not have
//
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT 0x0501 // Windows XP
#endif
#include <Windows.h>
#include <d3d9.h>
#include <d3dx9math.h>
typedef IDirect3D9*(WINAPI* Direct3DCreate9Ptr)(UINT SDKVersion);
typedef int(WINAPI* D3DPERF_BeginEventPtr)(D3DCOLOR col, LPCWSTR wszName);
typedef int(WINAPI* D3DPERF_EndEventPtr)(void);
typedef void(WINAPI* D3DPERF_SetMarkerPtr)(D3DCOLOR col, LPCWSTR wszName);
typedef void(WINAPI* D3DPERF_SetRegionPtr)(D3DCOLOR col, LPCWSTR wszName);
typedef BOOL(WINAPI* D3DPERF_QueryRepeatFramePtr)(void);
typedef void(WINAPI* D3DPERF_SetOptionsPtr)(DWORD dwOptions);
typedef DWORD(WINAPI* D3DPERF_GetStatusPtr)(void);
typedef HRESULT(WINAPI* D3DXCreateMatrixStackPtr)(
DWORD Flags, LPD3DXMATRIXSTACK* ppStack);
// Unit tests for pointers
// Direct3DCreate9Ptr gDirect3DCreate9 = ::Direct3DCreate9;
// D3DPERF_BeginEventPtr gD3DPERF_BeginEvent = ::D3DPERF_BeginEvent;
// D3DPERF_EndEventPtr gD3DPERF_EndEvent = ::D3DPERF_EndEvent;
// D3DPERF_SetMarkerPtr gD3DPERF_SetMarker = ::D3DPERF_SetMarker;
// D3DPERF_SetRegionPtr gD3DPERF_SetRegion = ::D3DPERF_SetRegion;
// D3DPERF_QueryRepeatFramePtr gD3DPERF_QueryRepeatFrame =
// ::D3DPERF_QueryRepeatFrame;
// D3DPERF_SetOptionsPtr gD3DPERF_SetOptions = ::D3DPERF_SetOptions;
// D3DPERF_GetStatusPtr gD3DPERF_GetStatus = ::D3DPERF_GetStatus;
// D3DXCreateMatrixStackPtr gD3DXCreateMatrixStack = ::D3DXCreateMatrixStack;
#endif
//
// d3d9.dll
//
/*! ************************************
\brief Load in d3d9.dll and call Direct3DCreate9
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke Direct3DCreate9 if present.
\windowsonly
\param uSDKVersion Requested version of Direct3D 9
\return \ref NULL if DirectX 9 is not present. A valid Direct3D9 pointer
otherwise
***************************************/
IDirect3D9* BURGER_API Burger::Windows::Direct3DCreate9(uint_t uSDKVersion)
{
// Get the function pointer
void* pDirect3DCreate9 = LoadFunctionIndex(CALL_Direct3DCreate9);
IDirect3D9* pDirect3D9 = nullptr;
if (pDirect3DCreate9) {
pDirect3D9 =
static_cast<Direct3DCreate9Ptr>(pDirect3DCreate9)(uSDKVersion);
}
return pDirect3D9;
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_BeginEvent
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_BeginEvent if present.
\windowsonly
\param col The color of the event
\param wszName Pointer to UTF-16 string of the name of the event
\return Is the level starting from 0 in the hierarchy to start this event.
If an error occurs, the return value is negative.
***************************************/
int BURGER_API Burger::Windows::D3DPERF_BeginEvent(
uint32_t col, const uint16_t* wszName)
{
// Get the function pointer
void* pD3DPERF_BeginEvent = LoadFunctionIndex(CALL_D3DPERF_BeginEvent);
int iResult = -1;
if (pD3DPERF_BeginEvent) {
iResult = static_cast<D3DPERF_BeginEventPtr>(pD3DPERF_BeginEvent)(
col, static_cast<LPCWSTR>(static_cast<const void*>(wszName)));
}
return iResult;
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_EndEvent
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_EndEvent if present.
\windowsonly
\return Is the level starting from 0 in the hierarchy to start this event.
If an error occurs, the return value is negative.
***************************************/
int BURGER_API Burger::Windows::D3DPERF_EndEvent(void)
{
// Get the function pointer
void* pD3DPERF_EndEvent = LoadFunctionIndex(CALL_D3DPERF_EndEvent);
int iResult = -1;
if (pD3DPERF_EndEvent) {
iResult = static_cast<D3DPERF_EndEventPtr>(pD3DPERF_EndEvent)();
}
return iResult;
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_SetMarker
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_SetMarker if present.
\windowsonly
\param col The color of the event
\param wszName Pointer to UTF-16 string of the name of the marker
***************************************/
void BURGER_API Burger::Windows::D3DPERF_SetMarker(
uint32_t col, const uint16_t* wszName)
{
// Get the function pointer
void* pD3DPERF_SetMarker = LoadFunctionIndex(CALL_D3DPERF_SetMarker);
if (pD3DPERF_SetMarker) {
static_cast<D3DPERF_SetMarkerPtr>(pD3DPERF_SetMarker)(
col, static_cast<LPCWSTR>(static_cast<const void*>(wszName)));
}
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_SetRegion
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_SetRegion if present.
\windowsonly
\param col The color of the event
\param wszName Pointer to UTF-16 string of the name of the region
***************************************/
void BURGER_API Burger::Windows::D3DPERF_SetRegion(
uint32_t col, const uint16_t* wszName)
{
// Get the function pointer
void* pD3DPERF_SetRegion = LoadFunctionIndex(CALL_D3DPERF_SetRegion);
if (pD3DPERF_SetRegion) {
static_cast<D3DPERF_SetRegionPtr>(pD3DPERF_SetRegion)(
col, static_cast<LPCWSTR>(static_cast<const void*>(wszName)));
}
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_QueryRepeatFrame
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_QueryRepeatFrame if present.
\windowsonly
\return When the return value is \ref TRUE, the caller will need to repeat
the same sequence of calls. If \ref FALSE, the caller needs to move
forward.
***************************************/
int BURGER_API Burger::Windows::D3DPERF_QueryRepeatFrame(void)
{
// Get the function pointer
void* pD3DPERF_QueryRepeatFrame =
LoadFunctionIndex(CALL_D3DPERF_QueryRepeatFrame);
int iResult = FALSE;
if (pD3DPERF_QueryRepeatFrame) {
iResult = static_cast<D3DPERF_QueryRepeatFramePtr>(
pD3DPERF_QueryRepeatFrame)();
}
return iResult;
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_SetOptions
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_SetOptions if present.
\windowsonly
\param dwOptions Set to 1 if PIX should be turned off
***************************************/
void BURGER_API Burger::Windows::D3DPERF_SetOptions(uint32_t dwOptions)
{
// Get the function pointer
void* pD3DPERF_SetOptions = LoadFunctionIndex(CALL_D3DPERF_SetOptions);
if (pD3DPERF_SetOptions) {
static_cast<D3DPERF_SetOptionsPtr>(pD3DPERF_SetOptions)(dwOptions);
}
}
/*! ************************************
\brief Load in d3d9.dll and call D3DPERF_GetStatus
To allow maximum compatibility, this function will manually load
d3d9.dll and then invoke D3DPERF_GetStatus if present.
\windowsonly
\return Non-zero if profiled by PIX. 0 if PIX is not present.
***************************************/
uint_t BURGER_API Burger::Windows::D3DPERF_GetStatus(void)
{
// Get the function pointer
void* pD3DPERF_GetStatus = LoadFunctionIndex(CALL_D3DPERF_GetStatus);
uint_t uResult = 0;
if (pD3DPERF_GetStatus) {
uResult = static_cast<D3DPERF_GetStatusPtr>(pD3DPERF_GetStatus)();
}
return uResult;
}
//
// d3dx9_43.dll
//
/*! ************************************
\brief Load in d3dx9.dll and call D3DXCreateMatrixStack
To allow maximum compatibility, this function will manually load
d3dx9.dll if needed and then invoke D3DXCreateMatrixStack.
\windowsonly
\param uFlags Requested version of Direct3D 9
\param ppStack Pointer to a pointer to receive the created ID3DXMatrixStack
\return S_OK if the call succeeded. Windows error if otherwise
***************************************/
uint_t BURGER_API Burger::Windows::D3DXCreateMatrixStack(
uint_t uFlags, ID3DXMatrixStack** ppStack)
{
// Clear in case of error
if (ppStack) {
ppStack[0] = nullptr;
}
// Get the function pointer
void* pD3DXCreateMatrixStack =
LoadFunctionIndex(CALL_D3DXCreateMatrixStack);
HRESULT uResult = D3DERR_NOTFOUND;
if (pD3DXCreateMatrixStack) {
uResult = static_cast<D3DXCreateMatrixStackPtr>(pD3DXCreateMatrixStack)(
uFlags, ppStack);
}
return static_cast<uint_t>(uResult);
}
#endif
| 28.683706 | 77 | 0.712631 | Olde-Skuul |
e44c687e571f61f4ae181974bb3198e26edecb8d | 36,768 | cpp | C++ | simulator/mips/t/mips64_test.cpp | M-ximus/mipt-mips | ea0b131e3b70273a58311c6921998b6be4549b9c | [
"MIT"
] | null | null | null | simulator/mips/t/mips64_test.cpp | M-ximus/mipt-mips | ea0b131e3b70273a58311c6921998b6be4549b9c | [
"MIT"
] | null | null | null | simulator/mips/t/mips64_test.cpp | M-ximus/mipt-mips | ea0b131e3b70273a58311c6921998b6be4549b9c | [
"MIT"
] | null | null | null | /* MIPS Instruction unit tests
* @author: Pavel Kryukov, Vsevolod Pukhov, Egor Bova
* Copyright (C) MIPT-MIPS 2017-2019
*/
#include <mips/mips.h>
#include <mips/mips_instr.h>
#include <catch.hpp>
#include <memory/memory.h>
class MIPS64Instr : public BaseMIPSInstr<uint64>
{
public:
explicit MIPS64Instr( uint32 bytes) : BaseMIPSInstr<uint64>( MIPSVersion::v64, Endian::little, bytes, 0) { }
explicit MIPS64Instr( std::string_view str_opcode) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::little, 0, 0xc000) { }
MIPS64Instr( std::string_view str_opcode, uint32 immediate) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::little, immediate, 0xc000) { }
};
class MIPS64BEInstr : public BaseMIPSInstr<uint64>
{
public:
explicit MIPS64BEInstr( uint32 bytes) : BaseMIPSInstr<uint64>( MIPSVersion::v64, Endian::big, bytes, 0) { }
explicit MIPS64BEInstr( std::string_view str_opcode) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::big, 0, 0xc000) { }
MIPS64BEInstr( std::string_view str_opcode, uint32 immediate) : BaseMIPSInstr<uint64>( MIPSVersion::v64, str_opcode, Endian::big, immediate, 0xc000) { }
};
static auto get_plain_memory_with_data()
{
auto memory = FuncMemory::create_plain_memory(15);
memory->write<uint32, Endian::little>( 0xABCD'1234, 0x1000);
memory->write<uint32, Endian::little>( 0xBADC'5678, 0x1004);
return memory;
}
static_assert( std::is_base_of_v<MIPS64::FuncInstr, MIPS64Instr>);
TEST_CASE( "MIPS64_instr: addiu two zeroes")
{
CHECK(MIPS64Instr(0x253104d2).get_disasm() == "addiu $s1, $t1, 1234");
CHECK(MIPS64Instr(0x2531fb2e).get_disasm() == "addiu $s1, $t1, -1234");
MIPS64Instr instr( "addiu");
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: addiu 0 and 1")
{
MIPS64Instr instr( "addiu", 1);
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: addiu 1 and -1")
{
MIPS64Instr instr( "addiu", 0xffff);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: addiu overflow")
{
MIPS64Instr instr( "addiu", 2);
instr.set_v_src( 0x7fffffff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x80000001);
CHECK( instr.has_trap() == false);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dclo zero")
{
CHECK(MIPS64Instr(0x71208825).get_disasm() == "dclo $s1, $t1");
MIPS64Instr instr( "dclo");
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dclo -1")
{
MIPS64Instr instr( "dclo");
instr.set_v_src( 0xffffffffffffffff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 64);
}
TEST_CASE( "MIPS64_instr: dclo ffe002200011000a")
{
MIPS64Instr instr( "dclo");
instr.set_v_src( 0xffe002200011000a, 0);
instr.execute();
CHECK( instr.get_v_dst() == 11);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dclz zero")
{
CHECK(MIPS64Instr(0x71208824).get_disasm() == "dclz $s1, $t1");
MIPS64Instr instr( "dclz");
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 64);
}
TEST_CASE( "MIPS64_instr: dclz -1")
{
MIPS64Instr instr( "dclz");
instr.set_v_src( 0xffffffffffffffff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dclz 0x02ffaa00cc720000")
{
MIPS64Instr instr( "dclz");
instr.set_v_src( 0x02ffaa00cc720000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 6);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsllv 0xaaaaaaaafee1dead by 0")
{
CHECK(MIPS64Instr(0x03298814).get_disasm() == "dsllv $s1, $t1, $t9");
MIPS64Instr instr( "dsllv");
instr.set_v_src( 0xaaaaaaaafee1dead, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xaaaaaaaafee1dead);
}
TEST_CASE( "MIPS64_instr: dsllv 2 by 1")
{
MIPS64Instr instr( "dsllv");
instr.set_v_src( 2, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst() == 4);
}
TEST_CASE( "MIPS64_instr: dsllv 1 by 32")
{
MIPS64Instr instr( "dsllv");
instr.set_v_src( 1, 0);
instr.set_v_src( 32, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0x100000000);
}
TEST_CASE( "MIPS64_instr: dsllv 1 by 64 (shift-variable overflow)")
{
MIPS64Instr instr( "dsllv");
instr.set_v_src( 1, 0);
instr.set_v_src( 64, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dsllv 1 by 128 (shift-variable overflow)")
{
MIPS64Instr instr( "dsllv");
instr.set_v_src( 1, 0);
instr.set_v_src( 128, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dsrav 0xfeedabcd by 0")
{
CHECK(MIPS64Instr(0x03298817).get_disasm() == "dsrav $s1, $t1, $t9");
MIPS64Instr instr( "dsrav");
instr.set_v_src( 0xfeedabcd, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xfeedabcd);
}
TEST_CASE( "MIPS64_instr: dsrav 0xab by 0xff")
{
MIPS64Instr instr( "dsrav");
instr.set_v_src( 0xab, 0);
instr.set_v_src( 0xff, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dsrav 0x123400000000 by 4")
{
MIPS64Instr instr( "dsrav");
instr.set_v_src( 0x123400000000, 0);
instr.set_v_src( 4, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0x012340000000);
}
TEST_CASE( "MIPS64_instr: dsrav 0xffab000000000000 by 4")
{
MIPS64Instr instr( "dsrav");
instr.set_v_src( 0xffab000000000000, 0);
instr.set_v_src( 4, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xfffab00000000000);
}
TEST_CASE( "MIPS64_instr: dsrav 1 by 64 (shift-variable overflow)")
{
MIPS64Instr instr( "dsrav");
instr.set_v_src( 1, 0);
instr.set_v_src( 64, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dsrlv 0xdeadbeef by 0")
{
CHECK(MIPS64Instr(0x03298816).get_disasm() == "dsrlv $s1, $t1, $t9");
MIPS64Instr instr( "dsrlv");
instr.set_v_src( 0xdeadbeef, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xdeadbeef);
}
TEST_CASE( "MIPS64_instr: dsrlv 1 by 1")
{
MIPS64Instr instr( "dsrlv");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dsrlv 0x01a00000 by 8")
{
MIPS64Instr instr( "dsrlv");
instr.set_v_src( 0x01a00000, 0);
instr.set_v_src( 8, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0x0001a000);
}
TEST_CASE( "MIPS64_instr: dsrlv 0x8765432000000011 by 16")
{
MIPS64Instr instr( "dsrlv");
instr.set_v_src( 0x8765432000000011, 0);
instr.set_v_src( 16, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0x0000876543200000);
}
TEST_CASE( "MIPS64_instr: dsrlv 1 by 64 (shift-variable overflow)")
{
MIPS64Instr instr( "dsrlv");
instr.set_v_src( 1, 0);
instr.set_v_src( 64, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: ld")
{
CHECK(MIPS64Instr(0xdd3104d2).get_disasm() == "ld $s1, 0x4d2($t1)");
CHECK(MIPS64Instr(0xdd31fb2e).get_disasm() == "ld $s1, 0xfb2e($t1)");
MIPS64Instr instr( "ld", 0x0fff);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_mem_addr() == 0x1000);
get_plain_memory_with_data()->load_store( &instr);
CHECK( instr.get_v_dst() == 0xBADC'5678'ABCD'1234);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: ldl")
{
CHECK(MIPS64Instr(0x693104d2).get_disasm() == "ldl $s1, 0x4d2($t1)");
CHECK(MIPS64Instr(0x6931fb2e).get_disasm() == "ldl $s1, 0xfb2e($t1)");
MIPS64Instr instr( "ldl", 0x0ffd);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_mem_addr() == 0x0ffe);
get_plain_memory_with_data()->load_store( &instr);
CHECK( instr.get_v_dst() == 0x5678'ABCD'1234'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: ldr")
{
CHECK(MIPS64Instr(0x6d3104d2).get_disasm() == "ldr $s1, 0x4d2($t1)");
CHECK(MIPS64Instr(0x6d31fb2e).get_disasm() == "ldr $s1, 0xfb2e($t1)");
MIPS64Instr instr( "ldr", 0x0ffd);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_mem_addr() == 0x0ffe);
get_plain_memory_with_data()->load_store( &instr);
CHECK( instr.get_v_dst() == 0x5678'ABCD'1234'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: sd 0xdead'beef'fee1'dead")
{
CHECK(MIPS64Instr(0xfd3104d2).get_disasm() == "sd $s1, 0x4d2($t1)");
CHECK(MIPS64Instr(0xfd31fb2e).get_disasm() == "sd $s1, 0xfb2e($t1)");
MIPS64Instr instr( "sd", 0x1000);
instr.set_v_src( 0, 0);
instr.set_v_src( 0xdead'beef'fee1'dead, 1);
instr.execute();
CHECK( instr.get_mem_addr() == 0x1000);
auto memory = get_plain_memory_with_data();
memory->load_store( &instr);
auto value = memory->read<uint64, Endian::little>( 0x1000);
CHECK( value == 0xdead'beef'fee1'dead);
}
////////////////////////////////////////////////////////////////////////////////
//Instructions sdl and sdr are not implemented
TEST_CASE( "MIPS64_instr: sdl 0xdead'beef'fee1'dead")
{
CHECK(MIPS64Instr(0xb13104d2).get_disasm() == "sdl $s1, 0x4d2($t1)");
CHECK(MIPS64Instr(0xb131fb2e).get_disasm() == "sdl $s1, 0xfb2e($t1)");
MIPS64Instr instr( "sdl", 0x1000);
instr.set_v_src( 0, 0);
instr.set_v_src( 0xdead'beef'fee1'dead, 1);
instr.execute();
CHECK( instr.get_mem_addr() == 0x1000);
auto memory = get_plain_memory_with_data();
memory->load_store( &instr);
auto value = memory->read<uint64, Endian::little>( 0x1000);
CHECK( value == 0xdead'beef'fee1'dead);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: sdr 0xdead'beef'fee1'dead")
{
CHECK(MIPS64Instr(0xb53104d2).get_disasm() == "sdr $s1, 0x4d2($t1)");
CHECK(MIPS64Instr(0xb531fb2e).get_disasm() == "sdr $s1, 0xfb2e($t1)");
MIPS64Instr instr( "sdr", 0x1000);
instr.set_v_src( 0, 0);
instr.set_v_src( 0xdead'beef'fee1'dead, 1);
instr.execute();
CHECK( instr.get_mem_addr() == 0x1000);
auto memory = get_plain_memory_with_data();
memory->load_store( &instr);
auto value = memory->read<uint64, Endian::little>( 0x1000);
CHECK( value == 0xdead'beef'fee1'dead);
}
TEST_CASE( "MIPS64_instr: nor 0 and 0")
{
CHECK(MIPS64Instr(0x01398827).get_disasm() == "nor $s1, $t1, $t9");
MIPS64Instr instr( "nor");
instr.set_v_src( 0, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xffffffffffffffff);
}
TEST_CASE( "MIPS64_instr: nor 1 and 1")
{
MIPS64Instr instr( "nor");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xfffffffffffffffe);
}
TEST_CASE( "MIPS64_instr: nor 1 and -1")
{
MIPS64Instr instr( "nor");
instr.set_v_src( 1, 0);
instr.set_v_src( 0xffffffffffffffff, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE ( "MIPS64_instr: sll 100 by 0")
{
CHECK(MIPS64Instr(0x00098cc0).get_disasm() == "sll $s1, $t1, 19");
MIPS64Instr instr( "sll", 0);
instr.set_v_src( 100, 0);
instr.execute();
CHECK( instr.get_v_dst() == 100);
}
TEST_CASE ( "MIPS64_instr: sll 3 by 2")
{
MIPS64Instr instr( "sll", 2);
instr.set_v_src( 3, 0);
instr.execute();
CHECK( instr.get_v_dst() == 12);
}
TEST_CASE ( "MIPS64_instr: sll 1 by 16")
{
MIPS64Instr instr( "sll", 16);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x10000);
}
TEST_CASE ( "MIPS64_instr: sll 1 by 31")
{
MIPS64Instr instr( "sll", 31);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'8000'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: sllv by 64 (shift-variable ovreflow)")
{
MIPS64Instr instr( "sllv");
instr.set_v_src( 1, 0);
instr.set_v_src( 64, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: sra 0xdeadc0dde by 0")
{
CHECK(MIPS64Instr(0x00098cc3).get_disasm() == "sra $s1, $t1, 19");
MIPS64Instr instr( "sra", 0);
instr.set_v_src( 0xdeadc0de, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'dead'c0de);
}
TEST_CASE( "MIPS64_instr: sra 0x0fffffff by 2")
{
MIPS64Instr instr( "sra", 2);
instr.set_v_src( 0x0fffffff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x03ffffff);
}
TEST_CASE( "MIPS64_instr: sra 0xdead by 4")
{
MIPS64Instr instr( "sra", 4);
instr.set_v_src( 0xdead, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x0dea);
}
TEST_CASE( "MIPS64_instr: sra 0xf1234567 by 16")
{
MIPS64Instr instr( "sra", 16);
instr.set_v_src( 0xf1234567, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'f123);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: srav 24 by 0")
{
CHECK(MIPS64Instr(0x03298807).get_disasm() == "srav $s1, $t1, $t9");
MIPS64Instr instr( "srav");
instr.set_v_src( 24, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 24);
}
TEST_CASE( "MIPS64_instr: srav 10 by 1")
{
MIPS64Instr instr( "srav");
instr.set_v_src( 10, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst() == 5);
}
TEST_CASE( "MIPS64_instr: srav 0x000a by 4")
{
MIPS64Instr instr( "srav");
instr.set_v_src( 0x000a, 0);
instr.set_v_src( 4, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: srav 0xff000000 by 4")
{
MIPS64Instr instr( "srav");
instr.set_v_src( 0xff000000, 0);
instr.set_v_src( 4, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'fff0'0000);
}
TEST_CASE( "MIPS64_instr: srav 0xffff0000 by 32 (shift-variable overflow)")
{
MIPS64Instr instr( "srav");
instr.set_v_src( 0xffff0000, 0);
instr.set_v_src( 32, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'0000);
}
TEST_CASE( "MIPS64_instr: srlv 0x11 by 0x00000a00 (shift-variable overflow)")
{
MIPS64Instr instr( "srlv");
instr.set_v_src( 0x11, 0);
instr.set_v_src( 0x00000a00, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0x11);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//-------------------------MIPS64Instr unit-tests-----------------------------//
static bool not_a_mips32_instruction( std::string_view name)
{
class MIPS32Instr : public BaseMIPSInstr<uint32>
{
public:
explicit MIPS32Instr( std::string_view str_opcode) : BaseMIPSInstr<uint32>( MIPSVersion::v32, str_opcode, Endian::little, 0, 0xc000) { }
};
MIPS32Instr instr( name);
instr.execute();
return instr.trap_type() == Trap::UNKNOWN_INSTRUCTION;
}
TEST_CASE ( "MIPS64_instr: dadd two zeroes")
{
CHECK(MIPS64Instr(0x0139882C).get_disasm() == "dadd $s1, $t1, $t9");
CHECK( not_a_mips32_instruction("dadd"));
MIPS64Instr instr( "dadd");
instr.set_v_src( 0, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE ( "MIPS64_instr: dadd 0 and 1")
{
MIPS64Instr instr( "dadd");
instr.set_v_src( 0, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE ( "MIPS64_instr: dadd 1 and -1")
{
MIPS64Instr instr( "dadd");
instr.set_v_src( 1, 0);
instr.set_v_src( 0xffffffffffffffff, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE ( "MIPS64_instr: dadd overflow")
{
MIPS64Instr instr( "dadd");
instr.set_v_src( 0x7fffffffffffffff, 0);
instr.set_v_src( 0x7fffffffffffffff, 1);
instr.execute();
CHECK( instr.get_v_dst() == NO_VAL32);
CHECK( instr.trap_type() != Trap::NO_TRAP);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: daddi two zeroes")
{
CHECK(MIPS64Instr(0x613104d2).get_disasm() == "daddi $s1, $t1, 1234");
CHECK(MIPS64Instr(0x6131fb2e).get_disasm() == "daddi $s1, $t1, -1234");
CHECK( not_a_mips32_instruction("daddi"));
MIPS64Instr instr( "daddi", 0);
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: daddi 0 and 1")
{
MIPS64Instr instr( "daddi", 1);
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: daddi 1 and -1")
{
MIPS64Instr instr( "daddi", 0xffff);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: daddi overflow")
{
MIPS64Instr instr( "daddi", 1);
instr.set_v_src( 0x7fffffffffffffff, 0);
instr.execute();
CHECK( instr.get_v_dst() == NO_VAL32);
CHECK( instr.trap_type() != Trap::NO_TRAP);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: daddiu two zeroes")
{
CHECK(MIPS64Instr(0x653104d2).get_disasm() == "daddiu $s1, $t1, 1234");
CHECK(MIPS64Instr(0x6531fb2e).get_disasm() == "daddiu $s1, $t1, -1234");
CHECK( not_a_mips32_instruction("daddiu"));
MIPS64Instr instr( "daddiu", 0);
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: daddiu 0 and 1")
{
MIPS64Instr instr( "daddiu", 1);
instr.set_v_src( 0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: daddiu 1 and -1")
{
MIPS64Instr instr( "daddiu", 0xffff);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: daddiu overflow")
{
MIPS64Instr instr( "daddiu", 1);
instr.set_v_src( 0x7fffffffffffffff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x8000000000000000);
CHECK( instr.trap_type() == Trap::NO_TRAP);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE ( "MIPS64_instr: daddu two zeroes")
{
CHECK(MIPS64Instr(0x0139882D).get_disasm() == "daddu $s1, $t1, $t9");
CHECK( not_a_mips32_instruction("daddu"));
MIPS64Instr instr( "daddu");
instr.set_v_src( 0, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE ( "MIPS64_instr: daddu 0 and 1")
{
MIPS64Instr instr( "daddu");
instr.set_v_src( 0, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE ( "MIPS64_instr: daddu 1 and -1")
{
MIPS64Instr instr( "daddu");
instr.set_v_src( 1, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE ( "MIPS64_instr: daddu overflow")
{
MIPS64Instr instr( "daddu");
instr.set_v_src( 0x7fff'ffff'ffff'ffff, 0);
instr.set_v_src( 0x7fff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'fffe);
CHECK( instr.has_trap() == false);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: ddiv 1 by 1")
{
CHECK(MIPS64Instr(0x0229001e).get_disasm() == "ddiv $s1, $t1");
CHECK(MIPS64Instr(0x0229001e).is_divmult());
CHECK(MIPS64Instr( "ddiv").is_divmult());
CHECK( not_a_mips32_instruction( "ddiv"));
MIPS64Instr instr( "ddiv");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: ddiv -1 by 1")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff);
}
TEST_CASE( "MIPS64_instr: ddiv -1 by -1")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: ddiv 1 by -1")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 1, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff);
}
TEST_CASE( "MIPS64_instr: ddiv 0 by 1")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 0, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddiv 1 by 0")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 1, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddiv 0x8000'0000'0000'0000 by -1")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 0x8000'0000'0000'0000, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddiv 0x4c4b'4000'0000'0000 by 0x1dcd'6500'0000'0000")
{
MIPS64Instr instr( "ddiv");
instr.set_v_src( 0x4c4b'4000'0000'0000, 0);
instr.set_v_src( 0x1dcd'6500'0000'0000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0x10b0'7600'0000'0000);
CHECK( instr.get_v_dst() == 2);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: ddivu 1 by 1")
{
CHECK(MIPS64Instr(0x0229001f).get_disasm() == "ddivu $s1, $t1");
CHECK(MIPS64Instr(0x0229001f).is_divmult());
CHECK(MIPS64Instr( "ddivu").is_divmult());
CHECK( not_a_mips32_instruction( "ddivu"));
MIPS64Instr instr( "ddivu");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: ddivu -1 by 1")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff);
}
TEST_CASE( "MIPS64_instr: ddivu -1 by -1")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: ddivu 1 by -1")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 1, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 1);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddivu 0 by 1")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 0, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddivu 1 by 0")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 1, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddivu 0x8000'0000'0000'0000 by -1")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 0x8000'0000'0000'0000, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0x8000'0000'0000'0000);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: ddivu 0x4c4b'4000'0000'0000 by 0x1dcd'6500'0000'0000")
{
MIPS64Instr instr( "ddivu");
instr.set_v_src( 0x4c4b'4000'0000'0000, 0);
instr.set_v_src( 0x1dcd'6500'0000'0000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0x10b0'7600'0000'0000);
CHECK( instr.get_v_dst() == 2);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dmult 0 by 0")
{
CHECK(MIPS64Instr(0x0229001c).get_disasm() == "dmult $s1, $t1");
CHECK(MIPS64Instr(0x0229001c).is_divmult());
CHECK(MIPS64Instr("dmult").is_divmult());
CHECK( not_a_mips32_instruction("dmult"));
MIPS64Instr instr( "dmult");
instr.set_v_src( 0, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dmult 1 by 1")
{
MIPS64Instr instr( "dmult");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dmult -1 by -1")
{
MIPS64Instr instr( "dmult");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dmult -1 by 1")
{
MIPS64Instr instr( "dmult");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0xffff'ffff'ffff'ffff);
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff);
}
TEST_CASE( "MIPS64_instr: dmult 0x100000000 by 0x100000000")
{
MIPS64Instr instr( "dmult");
instr.set_v_src( 0x100000000, 0);
instr.set_v_src( 0x100000000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 1);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dmult 0x8000'0000'0000'0000 by 0x8000'0000'0000'0000")
{
MIPS64Instr instr( "dmult");
instr.set_v_src( 0x8000'0000'0000'0000, 0);
instr.set_v_src( 0x8000'0000'0000'0000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0x4000'0000'0000'0000);
CHECK( instr.get_v_dst() == 0);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dmultu 0 by 0")
{
CHECK(MIPS64Instr(0x0229001d).get_disasm() == "dmultu $s1, $t1");
CHECK(MIPS64Instr(0x0229001d).is_divmult());
CHECK(MIPS64Instr("dmultu").is_divmult());
CHECK( not_a_mips32_instruction("dmultu"));
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dmultu 1 by 1")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dmultu -1 by -1")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 0xffff'ffff'ffff'ffff, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0xffff'ffff'ffff'fffe);
CHECK( instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dmultu -1 by 0")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dmultu -1 by 1")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0xffff'ffff'ffff'ffff, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0);
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffff);
}
TEST_CASE( "MIPS64_instr: dmultu 0x100000000 by 0x100000000")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0x100000000, 0);
instr.set_v_src( 0x100000000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 1);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dmultu 0x8000'0000'0000'0000 by 0x8000'0000'0000'0000")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0x8000'0000'0000'0000, 0);
instr.set_v_src( 0x8000'0000'0000'0000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0x4000'0000'0000'0000);
CHECK( instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dmultu 0xcecb'8f27'0000'0000 by 0xfd87'b5f2'0000'0000")
{
MIPS64Instr instr( "dmultu");
instr.set_v_src( 0xcecb'8f27'0000'0000, 0);
instr.set_v_src( 0xfd87'b5f2'0000'0000, 1);
instr.execute();
CHECK( instr.get_v_dst2() == 0xcccc'cccb'7134'e5de);
CHECK( instr.get_v_dst() == 0);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE ( "MIPS64_instr: dsll 0xaaaa'aaaa'0009'8cc0 by 0")
{
CHECK(MIPS64Instr(0x00098cf8).get_disasm() == "dsll $s1, $t1, 19");
CHECK( not_a_mips32_instruction("dsll"));
MIPS64Instr instr( "dsll", 0);
instr.set_v_src( 0xaaaa'aaaa'0009'8cc0, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xaaaa'aaaa'0009'8cc0);
}
TEST_CASE ( "MIPS64_instr: dsll 51 by 1")
{
MIPS64Instr instr( "dsll", 1);
instr.set_v_src( 51, 0);
instr.execute();
CHECK( instr.get_v_dst() == 102);
}
TEST_CASE ( "MIPS64_instr: dsll 0x8899'aabb'ccdd'eeff by 8")
{
MIPS64Instr instr( "dsll", 8);
instr.set_v_src( 0x8899'aabb'ccdd'eeff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x99aa'bbcc'ddee'ff00);
}
TEST_CASE ( "MIPS64_instr: dsll 1 by 63")
{
MIPS64Instr instr( "dsll", 63);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x8000'0000'0000'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsll32 0xaaaa'aaaa'0009'8ccf by 0")
{
CHECK(MIPS64Instr(0x00098cfc).get_disasm() == "dsll32 $s1, $t1, 19");
CHECK( not_a_mips32_instruction("dsll32"));
MIPS64Instr instr( "dsll32", 0);
instr.set_v_src( 0xaaaa'aaaa'0009'8ccf, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x0009'8ccf'0000'0000);
}
TEST_CASE ( "MIPS64_instr: dsll32 0x8899'aabb'ccdd'eeff by 8")
{
MIPS64Instr instr( "dsll32", 8);
instr.set_v_src( 0x8899'aabb'ccdd'eeff, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xddee'ff00'0000'0000);
}
TEST_CASE( "MIPS64_instr: dsll32 1 by 31")
{
MIPS64Instr instr( "dsll32", 31);
instr.set_v_src( 1, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x8000'0000'0000'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsra 0xabcd'1234'abcd'1234 by 0")
{
CHECK(MIPS64Instr(0x00098cfb).get_disasm() == "dsra $s1, $t1, 19");
CHECK( not_a_mips32_instruction("dsra"));
MIPS64Instr instr( "dsra", 0);
instr.set_v_src( 0xabcd'1234'abcd'1234, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xabcd'1234'abcd'1234);
}
TEST_CASE( "MIPS64_instr: dsra 49 by 1")
{
MIPS64Instr instr( "dsra", 1);
instr.set_v_src( 49, 0);
instr.execute();
CHECK( instr.get_v_dst() == 24);
}
TEST_CASE( "MIPS64_instr: dsra 0x1000 by 4")
{
MIPS64Instr instr( "dsra", 4);
instr.set_v_src( 0x1000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x100);
}
TEST_CASE( "MIPS64_instr: dsra 0xffa0'0000'0000'0000 by 16")
{
MIPS64Instr instr( "dsra", 16);
instr.set_v_src( 0xffa0'0000'0000'0000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffa0'0000'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsra32 0xabcd'1234'abcd'1234 by 0")
{
CHECK(MIPS64Instr(0x00098cff).get_disasm() == "dsra32 $s1, $t1, 19");
CHECK( not_a_mips32_instruction("dsra32"));
MIPS64Instr instr( "dsra32", 0);
instr.set_v_src( 0xabcd'1234'abcd'1234, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'abcd'1234);
}
TEST_CASE( "MIPS64_instr: dsra32 0x1000'0000'0000 by 4")
{
MIPS64Instr instr( "dsra32", 4);
instr.set_v_src( 0x1000'0000'0000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x100);
}
TEST_CASE( "MIPS64_instr: dsra32 0xffa0'0000'0000'0000 by 16")
{
MIPS64Instr instr( "dsra32", 16);
instr.set_v_src( 0xffa0'0000'0000'0000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffff'ffff'ffff'ffa0);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsrl 0xabcd'1234'abcd'1234 by 0")
{
CHECK(MIPS64Instr(0x00098cfa).get_disasm() == "dsrl $s1, $t1, 19");
CHECK( not_a_mips32_instruction("dsrl"));
MIPS64Instr instr( "dsrl", 0);
instr.set_v_src( 0xabcd'1234'abcd'1234, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xabcd'1234'abcd'1234);
}
TEST_CASE( "MIPS64_instr: dsrl 49 by 1")
{
MIPS64Instr instr( "dsrl", 1);
instr.set_v_src( 49, 0);
instr.execute();
CHECK( instr.get_v_dst() == 24);
}
TEST_CASE( "MIPS64_instr: dsrl 0x1000 by 4")
{
MIPS64Instr instr( "dsrl", 4);
instr.set_v_src( 0x1000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x100);
}
TEST_CASE( "MIPS64_instr: dsrl 0xffa0'0000'0000'0000 by 16")
{
MIPS64Instr instr( "dsrl", 16);
instr.set_v_src( 0xffa0'0000'0000'0000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffa0'0000'0000);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsrl32 0xabcd'1234'abcd'1234 by 0")
{
CHECK(MIPS64Instr(0x00098cfe).get_disasm() == "dsrl32 $s1, $t1, 19");
CHECK( not_a_mips32_instruction("dsrl32"));
MIPS64Instr instr( "dsrl32", 0);
instr.set_v_src( 0xabcd'1234'abcd'1234, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xabcd1234);
}
TEST_CASE( "MIPS64_instr: dsrl32 0x1000'0000'0000 by 4")
{
MIPS64Instr instr( "dsrl32", 4);
instr.set_v_src( 0x1000'0000'0000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0x100);
}
TEST_CASE( "MIPS64_instr: dsrl32 0xffa0'0000'0000'0000 by 16")
{
MIPS64Instr instr( "dsrl32", 16);
instr.set_v_src( 0xffa0'0000'0000'0000, 0);
instr.execute();
CHECK( instr.get_v_dst() == 0xffa0);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsub 1 from 1")
{
CHECK(MIPS64Instr(0x0139882e).get_disasm() == "dsub $s1, $t1, $t9");
CHECK( not_a_mips32_instruction("dsub"));
MIPS64Instr instr( "dsub");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK(instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dsub 1 from 10")
{
MIPS64Instr instr( "dsub");
instr.set_v_src( 10, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK(instr.get_v_dst() == 9);
}
TEST_CASE( "MIPS64_instr: dsub 0 from 1")
{
MIPS64Instr instr( "dsub");
instr.set_v_src( 1, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK(instr.get_v_dst() == 1);
}
TEST_CASE( "MIPS64_instr: dsub overflow")
{
MIPS64Instr instr( "dsub");
instr.set_v_src( 0x8000000000000000, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK(instr.get_v_dst() == NO_VAL32);
CHECK(instr.trap_type() == Trap::INTEGER_OVERFLOW);
}
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "MIPS64_instr: dsubu 1 from 1")
{
CHECK(MIPS64Instr(0x0139882f).get_disasm() == "dsubu $s1, $t1, $t9");
CHECK( not_a_mips32_instruction("dsubu"));
MIPS64Instr instr( "dsubu");
instr.set_v_src( 1, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK(instr.get_v_dst() == 0);
}
TEST_CASE( "MIPS64_instr: dsubu 1 from 10")
{
MIPS64Instr instr( "dsubu");
instr.set_v_src( 10, 0);
instr.set_v_src( 1, 1);
instr.execute();
CHECK(instr.get_v_dst() == 9);
}
TEST_CASE( "MIPS64_instr: dsubu 0 from 1")
{
MIPS64Instr instr( "dsubu");
instr.set_v_src( 1, 0);
instr.set_v_src( 0, 1);
instr.execute();
CHECK(instr.get_v_dst() == 1);
}
////////////////////////////////////////////////////////////////////////////////
| 28.067176 | 157 | 0.597068 | M-ximus |
e44cb9dac8125d1ce0238dc4653c56447bbd7131 | 74,202 | cpp | C++ | src/rpc/walletdump.cpp | Ankh-Trust/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 2 | 2019-10-31T11:56:31.000Z | 2019-11-02T08:48:45.000Z | src/rpc/walletdump.cpp | Ankh-fdn/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 2 | 2019-11-22T18:49:20.000Z | 2020-10-06T11:44:46.000Z | src/rpc/walletdump.cpp | Ankh-fdn/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 1 | 2020-06-09T16:15:27.000Z | 2020-06-09T16:15:27.000Z | // Copyright (c) 2016-2019 Duality Blockchain Solutions Developers
// Copyright (c) 2014-2019 The Dash Core Developers
// Copyright (c) 2009-2019 The Bitcoin Developers
// Copyright (c) 2009-2019 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "bdap/domainentry.h"
#include "bdap/domainentrydb.h"
#include "bdap/utils.h"
#include "bip39.h"
#include "chain.h"
#include "core_io.h"
#include "init.h"
#include "merkleblock.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include "util.h"
#include "utiltime.h"
#include "validation.h"
#include "wallet/wallet.h"
#include <univalue.h>
#include <libtorrent/hex.hpp> // for to_hex and from_hex
#include <fstream>
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/foreach.hpp>
void EnsureWalletIsUnlocked();
bool EnsureWalletIsAvailable(bool avoidException);
std::string static EncodeDumpTime(int64_t nTime)
{
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
int64_t static DecodeDumpTime(const std::string& str)
{
static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
static const std::locale loc(std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time())
return 0;
return (ptime - epoch).total_seconds();
}
std::string static EncodeDumpString(const std::string& str)
{
std::stringstream ret;
BOOST_FOREACH (unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string& str)
{
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos + 2 < str.length()) {
c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) |
((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15));
pos += 2;
}
ret << c;
}
return ret.str();
}
UniValue importprivkey(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
"importprivkey \"creditprivkey\" ( \"label\" ) ( rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n"
"1. \"creditprivkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nDump a private key\n" +
HelpExampleCli("dumpprivkey", "\"myaddress\"") +
"\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") +
"\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
"\nImport using default blank label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
"\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false"));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string strSecret = request.params[0].get_str();
std::string strLabel = "";
if (request.params.size() > 1)
strLabel = request.params[1].get_str();
bool isskip = false;
// Whether to perform rescan after import
bool fRescan = false;
if (request.params.size() > 2)
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
CCreditSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
{
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, strLabel, "receive");
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress)) {
isskip = true;
} else {
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
pwalletMain->GenerateEdandStealthKey(key);
// whenever a key is imported, we need to scan the whole chain
pwalletMain->UpdateTimeFirstKey(1);
}
if (fRescan || !isskip) {
pwalletMain->SetUpdateKeyPoolsAndLinks();
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
}
return NullUniValue;
}
UniValue importstealthaddress(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
throw std::runtime_error(
"importstealthaddress \"scan private key\" \"spend private key\" ( \"prefix bits\" ) ( \"prefix number\" ) \n"
"\nAdds a stealth address (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n"
"1. \"scan private key\" (string, required) The stealth scan private key (see dumpprivkey)\n"
"2. \"spend private key\" (string, required) The stealth spend private key (see dumpprivkey)\n"
"3. \"prefix bits\" (int, optional, default=0)\n"
"4. \"prefix number\" (int, optional) If prefix number is not specified the prefix will be selected deterministically.\n"
"\nNote: This call can take minutes to complete because it rescans the chain for transactions.\n"
"\nExamples:\n"
"\nDump stealth address private keys\n" +
HelpExampleCli("importstealthaddress", "\"scan_key\" \"spend_key\"") +
HelpExampleRpc("importstealthaddress", "\"scan_key\" \"spend_key\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string strScanKey = request.params[0].get_str();
std::string strSpendKey = request.params[1].get_str();
uint8_t prefix_bits = 0;
if (request.params.size() > 2)
prefix_bits = request.params[2].get_int();
uint32_t prefix_number = 0;
if (request.params.size() > 3)
prefix_number = request.params[3].get_int();
CCreditSecret vchScanSecret, vchSpendSecret;
bool fGood = vchScanSecret.SetString(strScanKey);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scan private key encoding");
fGood = vchSpendSecret.SetString(strSpendKey);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid spend private key encoding");
CKey keyScan = vchScanSecret.GetKey();
if (!keyScan.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Scan private key outside allowed range");
CKey keySpend = vchSpendSecret.GetKey();
if (!keySpend.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Spend private key outside allowed range");
CPubKey pubkeyScan = keyScan.GetPubKey();
assert(keyScan.VerifyPubKey(pubkeyScan));
CPubKey pubkeySpend = keySpend.GetPubKey();
assert(keySpend.VerifyPubKey(pubkeySpend));
CKeyID scanID = pubkeyScan.GetID();
CKeyID spendID = pubkeySpend.GetID();
{
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(scanID, "", "receive");
pwalletMain->SetAddressBook(spendID, "", "receive");
// Don't throw error in case a key is already there
if (!pwalletMain->HaveKey(scanID)) {
pwalletMain->mapKeyMetadata[scanID].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(keyScan, pubkeyScan))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding scan key to wallet");
}
if (!pwalletMain->HaveKey(spendID)) {
pwalletMain->mapKeyMetadata[spendID].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(keySpend, pubkeySpend))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding spend key to wallet");
}
CStealthAddress sxAddr(keyScan, keySpend, prefix_bits, prefix_number);
if (!pwalletMain->HaveStealthAddress(spendID)) {
if (!pwalletMain->AddStealthAddress(sxAddr)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding spend key to wallet");
}
else {
// whenever a key is imported, we need to scan the whole chain
pwalletMain->UpdateTimeFirstKey(1);
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
}
}
return NullUniValue;
}
UniValue importbdapkeys(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 4 || request.params.size() > 5)
throw std::runtime_error(
"importbdapkeys \"account id\" \"wallet privkey\" \"link privkey\" \"DHT privkey\" \"rescan\"\n"
"\nAdds a private keys (as returned by dumpbdapkeys) to your wallet.\n"
"\nArguments:\n"
"1. \"account id\" (string, required) The BDAP account id (see dumpbdapkeys)\n"
"2. \"wallet privkey\" (string, required) The BDAP account wallet private key (see dumpbdapkeys)\n"
"3. \"link privkey\" (string, required) The BDAP account link address private key (see dumpbdapkeys)\n"
"4. \"DHT privkey\" (string, required) The BDAP account DHT private key (see dumpbdapkeys)\n"
"5. \"rescan\" (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nDump a private key\n"
+ HelpExampleCli("dumpbdapkeys", "\"account id\" \"wallet_key\" \"link_key\" \"dht_key\" false") +
"\nImport the private key with rescan\n"
+ HelpExampleCli("importbdapkeys", "\"account id\" \"wallet_key\" \"link_key\" \"dht_key\"") +
"\nImport using a label and without rescan\n"
+ HelpExampleCli("importbdapkeys", "\"account id\" \"wallet_key\" \"link_key\" \"dht_key\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importbdapkeys", "\"account id\" \"wallet_key\" \"link_key\" \"dht_key\" false")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string vchObjectID = request.params[0].get_str();
std::string strWalletPrivKey = request.params[1].get_str();
std::string strLinkPrivKey = request.params[2].get_str();
std::string strDHTPrivKey = request.params[3].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (request.params.size() > 4)
fRescan = request.params[2].get_bool();
CDomainEntry entry;
entry.DomainComponent = vchDefaultDomainName;
entry.OrganizationalUnit = vchDefaultPublicOU;
entry.ObjectID = vchFromString(vchObjectID);
if (!pDomainEntryDB->GetDomainEntryInfo(entry.vchFullObjectPath(), entry)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Can not find BDAP entry " + entry.GetFullObjectPath());
}
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
// Wallet address
CCreditSecret vchWalletSecret;
bool fGood = vchWalletSecret.SetString(strWalletPrivKey);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid wallet private key encoding");
CKey keyWallet = vchWalletSecret.GetKey();
if (!keyWallet.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Wallet private key outside allowed range");
CPubKey pubkeyWallet = keyWallet.GetPubKey();
assert(keyWallet.VerifyPubKey(pubkeyWallet));
CKeyID vchWalletAddress = pubkeyWallet.GetID();
// TODO (BDAP): Check if wallet address matches BDAP entry
// Link address
CCreditSecret vchLinkSecret;
fGood = vchLinkSecret.SetString(strLinkPrivKey);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid link private key encoding");
CKey keyLink = vchLinkSecret.GetKey();
if (!keyLink.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Link private key outside allowed range");
CPubKey pubkeyLink = keyLink.GetPubKey();
assert(keyLink.VerifyPubKey(pubkeyLink));
CKeyID vchLinkAddress = pubkeyLink.GetID();
// TODO (BDAP): Check if link address matches BDAP entry
// DHT key
std::array<char, ED25519_PRIVATE_SEED_BYTE_LENGTH> arrDHTPrivSeedKey;
libtorrent::aux::from_hex(strDHTPrivKey, arrDHTPrivSeedKey.data());
CKeyEd25519 privDHTKey(arrDHTPrivSeedKey);
std::vector<unsigned char> vchDHTPubKey = privDHTKey.GetPubKey();
CKeyID dhtKeyID(Hash160(vchDHTPubKey.begin(), vchDHTPubKey.end()));
// Add keys to local wallet database
{
pwalletMain->MarkDirty();
if (!pwalletMain->HaveDHTKey(dhtKeyID)) {
pwalletMain->SetAddressBook(privDHTKey.GetID(), vchObjectID, "bdap-dht-key");
if (!pwalletMain->AddDHTKey(privDHTKey, vchDHTPubKey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding BDAP DHT key to wallet database");
}
pwalletMain->mapKeyMetadata[dhtKeyID].nCreateTime = 1;
}
// Don't throw error in case all keys already already there
if (pwalletMain->HaveKey(vchWalletAddress) && pwalletMain->HaveKey(vchLinkAddress))
return NullUniValue;
// TODO (BDAP): What is nCreateTime used for?
pwalletMain->mapKeyMetadata[vchWalletAddress].nCreateTime = 1;
pwalletMain->mapKeyMetadata[vchLinkAddress].nCreateTime = 1;
if (!pwalletMain->HaveKey(vchWalletAddress)) {
pwalletMain->SetAddressBook(vchWalletAddress, vchObjectID, "bdap-wallet");
if (!pwalletMain->AddKeyPubKey(keyWallet, pubkeyWallet))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding BDAP wallet key to wallet database");
}
if (!pwalletMain->HaveKey(vchLinkAddress)) {
pwalletMain->SetAddressBook(vchLinkAddress, vchObjectID, "bdap-link");
if (!pwalletMain->AddKeyPubKey(keyLink, pubkeyLink))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding BDAP link key to wallet database");
}
// whenever a key is imported, we need to scan the whole chain
pwalletMain->UpdateTimeFirstKey(1);
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
}
return NullUniValue;
}
void ImportAddress(const CCreditAddress& address, const std::string& strLabel);
void ImportScript(const CScript& script, const std::string& strLabel, bool isRedeemScript)
{
if (!isRedeemScript && ::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE)
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(script) && !pwalletMain->AddWatchOnly(script, 0 /* nCreateTime */))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
if (isRedeemScript) {
if (!pwalletMain->HaveCScript(script) && !pwalletMain->AddCScript(script))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
ImportAddress(CCreditAddress(CScriptID(script)), strLabel);
} else {
CTxDestination destination;
if (ExtractDestination(script, destination)) {
pwalletMain->SetAddressBook(destination, strLabel, "receive");
}
}
}
void ImportAddress(const CCreditAddress& address, const std::string& strLabel)
{
CScript script = GetScriptForDestination(address.Get());
ImportScript(script, strLabel, false);
// add to address book or update label
if (address.IsValid())
pwalletMain->SetAddressBook(address.Get(), strLabel, "receive");
}
UniValue importaddress(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"importaddress \"address\" ( \"label\" rescan p2sh )\n"
"\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n"
"1. \"script\" (string, required) The hex-encoded script (or address)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"If you have the full public key, you should call importpubkey instead of this.\n"
"\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
"as change, and not show up in many RPCs.\n"
"\nExamples:\n"
"\nImport a script with rescan\n" +
HelpExampleCli("importaddress", "\"myscript\"") +
"\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") +
"\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false"));
std::string strLabel = "";
if (request.params.size() > 1)
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (request.params.size() > 2)
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
// Whether to import a p2sh version, too
bool fP2SH = false;
if (request.params.size() > 3)
fP2SH = request.params[3].get_bool();
LOCK2(cs_main, pwalletMain->cs_wallet);
CCreditAddress address(request.params[0].get_str());
if (address.IsValid()) {
if (fP2SH)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
ImportAddress(address, strLabel);
} else if (IsHex(request.params[0].get_str())) {
std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
ImportScript(CScript(data.begin(), data.end()), strLabel, fP2SH);
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Credit address or script");
}
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importprunedfunds(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"importprunedfunds\n"
"\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n"
"\nArguments:\n"
"1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n"
"2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n");
CMutableTransaction tx;
if (!DecodeHexTx(tx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
CWalletTx wtx(pwalletMain, MakeTransactionRef(std::move(tx)));
CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
//Search partial merkle tree in proof for our transaction and index in valid block
std::vector<uint256> vMatch;
std::vector<unsigned int> vIndex;
unsigned int txnIndex = 0;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
std::vector<uint256>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx)) == vMatch.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
}
txnIndex = vIndex[it - vMatch.begin()];
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
}
wtx.nIndex = txnIndex;
wtx.hashBlock = merkleBlock.header.GetHash();
LOCK2(cs_main, pwalletMain->cs_wallet);
if (pwalletMain->IsMine(tx)) {
pwalletMain->AddToWallet(wtx, false);
return NullUniValue;
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
}
UniValue removeprunedfunds(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"removeprunedfunds \"txid\"\n"
"\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will effect wallet balances.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n"
"\nExamples:\n" +
HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
"\nAs a JSON-RPC call\n" + HelpExampleRpc("removprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(request.params[0].get_str());
std::vector<uint256> vHash;
vHash.push_back(hash);
std::vector<uint256> vHashOut;
if (pwalletMain->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not properly delete the transaction.");
}
if (vHashOut.empty()) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction does not exist in wallet.");
}
return NullUniValue;
}
UniValue importpubkey(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"importpubkey \"pubkey\" ( \"label\" rescan )\n"
"\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n"
"1. \"pubkey\" (string, required) The hex-encoded public key\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nImport a public key with rescan\n" +
HelpExampleCli("importpubkey", "\"mypubkey\"") +
"\nImport using a label without rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
"\nAs a JSON-RPC call\n" + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false"));
std::string strLabel = "";
if (request.params.size() > 1)
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (request.params.size() > 2)
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
if (!IsHex(request.params[0].get_str()))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
CPubKey pubKey(data.begin(), data.end());
if (!pubKey.IsFullyValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
LOCK2(cs_main, pwalletMain->cs_wallet);
ImportAddress(CCreditAddress(pubKey.GetID()), strLabel);
ImportScript(GetScriptForRawPubKey(pubKey), strLabel, false);
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importwallet(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
"importwallet \"filename\"\n"
"\nImports keys from a wallet dump file (see dumpwallet).\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The wallet file\n"
"2. forcerescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nExamples:\n"
"\nDump the wallet\n" +
HelpExampleCli("dumpwallet", "\"test\"") +
"\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") +
"\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\""));
if (fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::ifstream file;
file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
bool neednotRescan = true;
bool forcerescan = false;
if (!request.params[1].isNull())
forcerescan = request.params[1].get_bool();
int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
bool fGood = true;
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
while (file.good()) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CCreditSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CCreditAddress(keyid).ToString());
continue;
}
neednotRescan=false;
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", CCreditAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBook(keyid, strLabel, "receive");
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
if (forcerescan || !neednotRescan) {
pwalletMain->UpdateTimeFirstKey(nTimeBegin);
CBlockIndex* pindex = chainActive.FindEarliestAtLeast(nTimeBegin - 7200);
LogPrintf("Rescanning last %i blocks\n", pindex ? chainActive.Height() - pindex->nHeight + 1 : 0);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->MarkDirty();
}
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue importelectrumwallet(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"importelectrumwallet \"filename\" index\n"
"\nImports keys from an Electrum wallet export file (.csv or .json)\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The Electrum wallet export file, should be in csv or json format\n"
"2. index (numeric, optional, default=0) Rescan the wallet for transactions starting from this block index\n"
"\nExamples:\n"
"\nImport the wallet\n" +
HelpExampleCli("importelectrumwallet", "\"test.csv\"") + HelpExampleCli("importelectrumwallet", "\"test.json\"") +
"\nImport using the json rpc call\n" + HelpExampleRpc("importelectrumwallet", "\"test.csv\"") + HelpExampleRpc("importelectrumwallet", "\"test.json\""));
if (fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::ifstream file;
std::string strFileName = request.params[0].get_str();
size_t nDotPos = strFileName.find_last_of(".");
if (nDotPos == std::string::npos)
throw JSONRPCError(RPC_INVALID_PARAMETER, "File has no extension, should be .json or .csv");
std::string strFileExt = strFileName.substr(nDotPos + 1);
if (strFileExt != "json" && strFileExt != "csv")
throw JSONRPCError(RPC_INVALID_PARAMETER, "File has wrong extension, should be .json or .csv");
file.open(strFileName.c_str(), std::ios::in | std::ios::ate);
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open Electrum wallet export file");
bool fGood = true;
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
if (strFileExt == "csv") {
while (file.good()) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line == "address,private_key")
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(","));
if (vstr.size() < 2)
continue;
CCreditSecret vchSecret;
if (!vchSecret.SetString(vstr[1]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CCreditAddress(keyid).ToString());
continue;
}
LogPrintf("Importing %s...\n", CCreditAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
}
} else {
// json
char* buffer = new char[nFilesize];
file.read(buffer, nFilesize);
UniValue data(UniValue::VOBJ);
if (!data.read(buffer))
throw JSONRPCError(RPC_TYPE_ERROR, "Cannot parse Electrum wallet export file");
delete[] buffer;
std::vector<std::string> vKeys = data.getKeys();
for (size_t i = 0; i < data.size(); i++) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, int(i * 100 / data.size()))));
if (!data[vKeys[i]].isStr())
continue;
CCreditSecret vchSecret;
if (!vchSecret.SetString(data[vKeys[i]].get_str()))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CCreditAddress(keyid).ToString());
continue;
}
LogPrintf("Importing %s...\n", CCreditAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
}
}
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
// Whether to perform rescan after import
int nStartHeight = 0;
if (request.params.size() > 1)
nStartHeight = request.params[1].get_int();
if (chainActive.Height() < nStartHeight)
nStartHeight = chainActive.Height();
// Assume that electrum wallet was created at that block
int nTimeBegin = chainActive[nStartHeight]->GetBlockTime();
pwalletMain->UpdateTimeFirstKey(nTimeBegin);
LogPrintf("Rescanning %i blocks\n", chainActive.Height() - nStartHeight + 1);
pwalletMain->ScanForWalletTransactions(chainActive[nStartHeight], true);
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue importmnemonic(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp)) {
return NullUniValue;
}
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue entry(UniValue::VOBJ);
if (request.fHelp || request.params.size() > 6 || request.params.size() == 0)
throw std::runtime_error(
"importmnemonic \"mnemonic\"\n"
"\nImports mnemonic\n"
"\nArguments:\n"
"1. \"mnemonic\" (string, required) mnemonic delimited by the dash charactor (-) or space\n"
"2. \"language\" (english|french|chinesesimplified|chinesetraditional|italian|japanese|korean|spanish, optional)\n"
"3. \"passphrase\" (string, optional) mnemonic passphrase used as the 13th or 25th word\n"
"\nExamples:\n"
"\nImports mnemonic\n"
+ HelpExampleCli("importmnemonic", "\"inflict-witness-off-property-target-faint-gather-match-outdoor-weapon-wide-mix\"")
);
if (fPruneMode)
throw std::runtime_error(std::string(__func__) + ": Importing wallets is disabled in pruned mode");
std::string strMnemonic = "", strMnemonicPassphrase = "";
if (!request.params[0].isNull())
strMnemonic = request.params[0].get_str();
// Mnemonic can be delimited by dash ('-') or space(' ') character
std::replace(strMnemonic.begin(), strMnemonic.end(), '-', ' ');
if (strMnemonic.size() > 512) //RESTRICTION REMOVED: was 256
throw std::runtime_error(std::string(__func__) + ": Mnemonic must be less than 256 charactors");
SecureString strSecureMnemonic(strMnemonic.begin(), strMnemonic.end());
CMnemonic mnemonic;
CMnemonic::Language selectLanguage = CMnemonic::Language::ENGLISH; //default language is ENGLISH
std::string compareLanguage = "english"; //default language is ENGLISH
if (!request.params[1].isNull()) {
compareLanguage = request.params[1].get_str();
selectLanguage = CMnemonic::getLanguageEnumFromLabel(compareLanguage);
} //if language
if (!mnemonic.Check(strSecureMnemonic,selectLanguage))
throw std::runtime_error(std::string(__func__) + ": Mnemonic check failed.");
SecureVector vchMnemonic(strMnemonic.begin(), strMnemonic.end());
if (!request.params[2].isNull()) {
strMnemonicPassphrase = request.params[2].get_str();
}
if (strMnemonicPassphrase.size() > 24)
throw std::runtime_error(std::string(__func__) + ": Mnemonic passphase must be 24 charactors or less");
pwalletMain->ShowProgress(_("Importing... Wallet will restart when complete."), 0); // show progress dialog in GUI
pwalletMain->ShowProgress("", 25); //show we're working in the background...
//CREATE BACKUP OF WALLET before importing mnemonic and swapping files
//wallat.dat.before-mnemonic-import.isodate
std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M-%S", GetTime());
boost::filesystem::path backupFile = GetDataDir() / ("wallet.dat.before-mnemonic-import" + dateTimeStr);
pwalletMain->BackupWallet(backupFile.string());
ForceSetArg("-mnemonic", strMnemonic);
ForceSetArg("-mnemonicpassphrase", strMnemonicPassphrase);
ForceSetArg("-mnemoniclanguage", compareLanguage);
SoftSetBoolArg("-importmnemonic", true);
SoftSetBoolArg("-skipmnemoniccheck", true);
CWallet* const pwallet = pwalletMain->CreateWalletFromFile(DEFAULT_WALLET_DAT_MNEMONIC,true);
pwalletMain = pwallet;
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
StartMnemonicRestart();
entry.push_back(Pair("Done", "Stopping daemon... Please restart credit..."));
//cleanup
ForceRemoveArg("-mnemonic");
ForceRemoveArg("-importmnemonic");
ForceRemoveArg("-mnemoniclanguage");
ForceRemoveArg("-skipmnemoniccheck");
return entry;
}
UniValue dumpprivkey(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpprivkey \"creditaddress\"\n"
"\nReveals the private key corresponding to 'creditaddress'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"creditaddress\" (string, required) The credit address for the private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n" +
HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string strAddress = request.params[0].get_str();
CTxDestination dest = DecodeDestination(strAddress);
if (!IsValidDestination(dest))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address " + strAddress);
if (dest.type() == typeid(CStealthAddress)) {
CStealthAddress sxAddr = boost::get<CStealthAddress>(dest);
if (!pwalletMain->GetStealthAddress(sxAddr.GetSpendKeyID(), sxAddr))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
UniValue result(UniValue::VOBJ);
result.push_back(Pair("scan_private_key", CCreditSecret(sxAddr.scan_secret).ToString()));
CKey vchSpendSecret;
if (!pwalletMain->GetKey(sxAddr.spend_secret_id, vchSpendSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for spend address " + CCreditAddress(sxAddr.spend_secret_id).ToString() + " is not known");
result.push_back(Pair("spend_private_key", CCreditSecret(vchSpendSecret).ToString()));
result.push_back(Pair("prefix_number_bits", (int)sxAddr.prefix_number_bits));
result.push_back(Pair("prefix_bitfield", (int)sxAddr.prefix_bitfield));
return result;
} else {
CCreditAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Credit address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CCreditSecret(vchSecret).ToString();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type: " + strAddress + " Must be a standard or stealth address.");
}
UniValue dumpbdapkeys(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpbdapkeys \"account id\"\n"
"\nReveals the private key corresponding to 'BDAP account'.\n"
"Then the importbdapkeys can be used with this output\n"
"\nArguments:\n"
"1. \"account id\" (string, required) The BDAP id for the private keys\n"
"\nResult:\n"
"\"wallet_address\" (string) The wallet address\n"
"\"wallet_privkey\" (string) The wallet address private key\n"
"\"link_address\" (string) The link address\n"
"\"link_privkey\" (string) The link address private keys\n"
"\"dht_publickey\" (string) The DHT public key\n"
"\"dht_privkey\" (string) The DHT private key\n"
"\nExamples:\n"
+ HelpExampleCli("dumpbdapkeys", "\"Alice\"")
+ HelpExampleRpc("dumpbdapkeys", "\"Alice\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue result(UniValue::VOBJ);
EnsureWalletIsUnlocked();
CharString vchObjectID = vchFromValue(request.params[0]);
ToLowerCase(vchObjectID);
CDomainEntry entry;
entry.DomainComponent = vchDefaultDomainName;
entry.OrganizationalUnit = vchDefaultPublicOU;
entry.ObjectID = vchObjectID;
if (!pDomainEntryDB->GetDomainEntryInfo(entry.vchFullObjectPath(), entry)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Can not find BDAP entry " + entry.GetFullObjectPath());
}
// Get wallet address private key from wallet db.
CKeyID walletKeyID;
CCreditAddress address = entry.GetWalletAddress();
if (!address.GetKeyID(walletKeyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key " + address.ToString());
CKey vchWalletSecret;
if (!pwalletMain->GetKey(walletKeyID, vchWalletSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + address.ToString() + " is not known");
std::string strWalletPrivKey = CCreditSecret(vchWalletSecret).ToString();
// Get link address private key from wallet db.
CKeyID linkKeyID;
CCreditAddress linkAddress = entry.GetLinkAddress();
if (!linkAddress.GetKeyID(linkKeyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Link address does not refer to a key" + linkAddress.ToString());
CKey vchLinkSecret;
if (!pwalletMain->GetKey(linkKeyID, vchLinkSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + linkAddress.ToString() + " is not known");
std::string strLinkPrivKey = CCreditSecret(vchLinkSecret).ToString();
// Get DHT private key from wallet db.
CKeyEd25519 keyDHT;
std::vector<unsigned char> vchDHTPubKey = vchFromString(entry.DHTPubKeyString());
CKeyID dhtKeyID(Hash160(vchDHTPubKey.begin(), vchDHTPubKey.end()));
if (pwalletMain && !pwalletMain->GetDHTKey(dhtKeyID, keyDHT)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error getting ed25519 private key for " + entry.DHTPubKeyString());
}
std::string strDHTPrivKey = keyDHT.GetPrivSeedString();
result.push_back(Pair("wallet_address", address.ToString()));
result.push_back(Pair("wallet_privkey", strWalletPrivKey));
result.push_back(Pair("link_address", linkAddress.ToString()));
result.push_back(Pair("link_privkey", strLinkPrivKey));
result.push_back(Pair("dht_publickey", entry.DHTPubKeyString()));
result.push_back(Pair("dht_privkey", strDHTPrivKey));
return result;
}
UniValue dumphdinfo(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"dumphdinfo\n"
"Returns an object containing sensitive private info about this HD wallet.\n"
"\nResult:\n"
"{\n"
" \"hdseed\": \"seed\", (string) The HD seed (bip32, in hex)\n"
" \"mnemonic\": \"words\", (string) The mnemonic for this HD wallet (bip39, english words) \n"
" \"mnemonicpassphrase\": \"passphrase\", (string) The mnemonic passphrase for this HD wallet (bip39)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("dumphdinfo", "") + HelpExampleRpc("dumphdinfo", ""));
LOCK(pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
CHDChain hdChainCurrent;
if (!pwalletMain->GetHDChain(hdChainCurrent))
throw JSONRPCError(RPC_WALLET_ERROR, "This wallet is not a HD wallet.");
if (!pwalletMain->GetDecryptedHDChain(hdChainCurrent))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot decrypt HD seed");
SecureString ssMnemonic;
SecureString ssMnemonicPassphrase;
hdChainCurrent.GetMnemonic(ssMnemonic, ssMnemonicPassphrase);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("hdseed", HexStr(hdChainCurrent.GetSeed())));
obj.push_back(Pair("mnemonic", ssMnemonic.c_str()));
obj.push_back(Pair("mnemonicpassphrase", ssMnemonicPassphrase.c_str()));
return obj;
}
UniValue dumpwallet(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename\n"
"\nExamples:\n" +
HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::ofstream file;
file.open(request.params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CTxDestination, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (const auto& entry : mapKeyBirth) {
if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test
vKeyBirth.push_back(std::make_pair(entry.second, *keyID));
}
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by Credit %s\n", CLIENT_BUILD);
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("creditversion", CLIENT_BUILD));
obj.push_back(Pair("lastblockheight", chainActive.Height()));
obj.push_back(Pair("lastblockhash", chainActive.Tip()->GetBlockHash().ToString()));
obj.push_back(Pair("lastblocktime", EncodeDumpTime(chainActive.Tip()->GetBlockTime())));
// add the base58check encoded extended master if the wallet uses HD
CHDChain hdChainCurrent;
if (pwalletMain->GetHDChain(hdChainCurrent)) {
if (!pwalletMain->GetDecryptedHDChain(hdChainCurrent))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot decrypt HD chain");
SecureString ssMnemonic;
SecureString ssMnemonicPassphrase;
hdChainCurrent.GetMnemonic(ssMnemonic, ssMnemonicPassphrase);
file << "# mnemonic: " << ssMnemonic << "\n";
file << "# mnemonic passphrase: " << ssMnemonicPassphrase << "\n\n";
SecureVector vchSeed = hdChainCurrent.GetSeed();
file << "# HD seed: " << HexStr(vchSeed) << "\n\n";
CExtKey masterKey;
masterKey.SetMaster(&vchSeed[0], vchSeed.size());
CCreditExtKey b58extkey;
b58extkey.SetKey(masterKey);
file << "# extended private masterkey: " << b58extkey.ToString() << "\n";
CExtPubKey masterPubkey;
masterPubkey = masterKey.Neuter();
CCreditExtPubKey b58extpubkey;
b58extpubkey.SetKey(masterPubkey);
file << "# extended public masterkey: " << b58extpubkey.ToString() << "\n\n";
for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i) {
CHDAccount acc;
if (hdChainCurrent.GetAccount(i, acc)) {
file << "# external chain counter: " << acc.nExternalChainCounter << "\n";
file << "# internal chain counter: " << acc.nInternalChainCounter << "\n\n";
} else {
file << "# WARNING: ACCOUNT " << i << " IS MISSING!"
<< "\n\n";
}
}
}
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID& keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CCreditAddress(keyid).ToString();
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
file << strprintf("%s %s ", CCreditSecret(key).ToString(), strTime);
if (pwalletMain->mapAddressBook.count(keyid)) {
file << strprintf("label=%s", EncodeDumpString(pwalletMain->mapAddressBook[keyid].name));
} else if (setKeyPool.count(keyid)) {
file << "reserve=1";
} else {
file << "change=1";
}
file << strprintf(" # addr=%s%s\n", strAddr, (pwalletMain->mapHdPubKeys.count(keyid) ? " hdkeypath=" + pwalletMain->mapHdPubKeys[keyid].GetKeyPath() : ""));
}
}
file << "\n";
file << "# End of dump\n";
file.close();
std::string strWarning = strprintf(_("%s file contains all private keys from this wallet. Do not share it with anyone!"), request.params[0].get_str().c_str());
obj.push_back(Pair("keys", int(vKeyBirth.size())));
obj.push_back(Pair("file", request.params[0].get_str().c_str()));
obj.push_back(Pair("warning", strWarning));
return obj;
}
UniValue ProcessImport(const UniValue& data, const int64_t timestamp)
{
try {
bool success = false;
// Required fields.
const UniValue& scriptPubKey = data["scriptPubKey"];
// Should have script or JSON with "address".
if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey");
}
// Optional fields.
const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
const bool& internal = data.exists("internal") ? data["internal"].get_bool() : false;
const bool& watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
bool isScript = scriptPubKey.getType() == UniValue::VSTR;
bool isP2SH = strRedeemScript.length() > 0;
const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
// Parse the output.
CScript script;
CCreditAddress address;
if (!isScript) {
address = CCreditAddress(output);
script = GetScriptForDestination(address.Get());
} else {
if (!IsHex(output)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey");
}
std::vector<unsigned char> vData(ParseHex(output));
script = CScript(vData.begin(), vData.end());
}
// Watchonly and private keys
if (watchOnly && keys.size()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys");
}
// Internal + Label
if (internal && data.exists("label")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label");
}
// Not having Internal + Script
if (!internal && isScript) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey");
}
// Keys / PubKeys size check.
if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey
throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address");
}
// Invalid P2SH redeemScript
if (isP2SH && !IsHex(strRedeemScript)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script");
}
// Process. //
// P2SH
if (isP2SH) {
// Import redeem script.
std::vector<unsigned char> vData(ParseHex(strRedeemScript));
CScript redeemScript = CScript(vData.begin(), vData.end());
// Invalid P2SH address
if (!script.IsPayToScriptHash()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(redeemScript) && !pwalletMain->AddWatchOnly(redeemScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (!pwalletMain->HaveCScript(redeemScript) && !pwalletMain->AddCScript(redeemScript)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
}
CCreditAddress redeemAddress = CCreditAddress(CScriptID(redeemScript));
CScript redeemDestination = GetScriptForDestination(redeemAddress.Get());
if (::IsMine(*pwalletMain, redeemDestination) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(redeemDestination) && !pwalletMain->AddWatchOnly(redeemDestination, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
// add to address book or update label
if (address.IsValid()) {
pwalletMain->SetAddressBook(address.Get(), label, "receive");
}
// Import private keys.
if (keys.size()) {
for (size_t i = 0; i < keys.size(); i++) {
const std::string& privkey = keys[i].get_str();
CCreditSecret vchSecret;
bool fGood = vchSecret.SetString(privkey);
if (!fGood) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
CKey key = vchSecret.GetKey();
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
}
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, label, "receive");
if (pwalletMain->HaveKey(vchAddress)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key");
}
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwalletMain->UpdateTimeFirstKey(timestamp);
}
}
success = true;
} else {
// Import public keys.
if (pubKeys.size() && keys.size() == 0) {
const std::string& strPubKey = pubKeys[0].get_str();
if (!IsHex(strPubKey)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
}
std::vector<unsigned char> data(ParseHex(strPubKey));
CPubKey pubKey(data.begin(), data.end());
if (!pubKey.IsFullyValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
}
CCreditAddress pubKeyAddress = CCreditAddress(pubKey.GetID());
// Consistency check.
if (!isScript && !(pubKeyAddress.Get() == address.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
// Consistency check.
if (isScript) {
CCreditAddress scriptAddress;
CTxDestination destination;
if (ExtractDestination(script, destination)) {
scriptAddress = CCreditAddress(destination);
if (!(scriptAddress.Get() == pubKeyAddress.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
}
}
CScript pubKeyScript = GetScriptForDestination(pubKeyAddress.Get());
if (::IsMine(*pwalletMain, pubKeyScript) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(pubKeyScript) && !pwalletMain->AddWatchOnly(pubKeyScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
// add to address book or update label
if (pubKeyAddress.IsValid()) {
pwalletMain->SetAddressBook(pubKeyAddress.Get(), label, "receive");
}
// TODO Is this necessary?
CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
if (::IsMine(*pwalletMain, scriptRawPubKey) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(scriptRawPubKey) && !pwalletMain->AddWatchOnly(scriptRawPubKey, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
success = true;
}
// Import private keys.
if (keys.size()) {
const std::string& strPrivkey = keys[0].get_str();
// Checks.
CCreditSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
if (!fGood) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
CKey key = vchSecret.GetKey();
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
}
CPubKey pubKey = key.GetPubKey();
assert(key.VerifyPubKey(pubKey));
CCreditAddress pubKeyAddress = CCreditAddress(pubKey.GetID());
// Consistency check.
if (!isScript && !(pubKeyAddress.Get() == address.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
// Consistency check.
if (isScript) {
CCreditAddress scriptAddress;
CTxDestination destination;
if (ExtractDestination(script, destination)) {
scriptAddress = CCreditAddress(destination);
if (!(scriptAddress.Get() == pubKeyAddress.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
}
}
CKeyID vchAddress = pubKey.GetID();
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, label, "receive");
if (pwalletMain->HaveKey(vchAddress)) {
return false;
}
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
if (!pwalletMain->AddKeyPubKey(key, pubKey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwalletMain->UpdateTimeFirstKey(timestamp);
success = true;
}
// Import scriptPubKey only.
if (pubKeys.size() == 0 && keys.size() == 0) {
if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(script) && !pwalletMain->AddWatchOnly(script, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (scriptPubKey.getType() == UniValue::VOBJ) {
// add to address book or update label
if (address.IsValid()) {
pwalletMain->SetAddressBook(address.Get(), label, "receive");
}
}
success = true;
}
}
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(success));
return result;
} catch (const UniValue& e) {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", e);
return result;
} catch (...) {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
return result;
}
}
int64_t GetImportTimestamp(const UniValue& data, int64_t now)
{
if (data.exists("timestamp")) {
const UniValue& timestamp = data["timestamp"];
if (timestamp.isNum()) {
return timestamp.get_int64();
} else if (timestamp.isStr() && timestamp.get_str() == "now") {
return now;
}
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
}
throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
}
UniValue importmulti(const JSONRPCRequest& mainRequest)
{
// clang-format off
if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
throw std::runtime_error(
"importmulti \"requests\" \"options\"\n\n"
"Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options).\n\n"
"Arguments:\n"
"1. requests (array, required) Data to be imported\n"
" [ (array of json objects)\n"
" {\n"
" \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n"
" \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n"
" or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
" key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
" \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
" 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
" creation time of all keys being imported by the importmulti call will be scanned.\n"
" \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
" \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
" \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
" \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be be treated as not incoming payments\n"
" \"watchonly\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be considered watched even when they're not spendable, only allowed if keys are empty\n"
" \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
" }\n"
" ,...\n"
" ]\n"
"2. options (json, optional)\n"
" {\n"
" \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n"
" }\n"
"\nExamples:\n" +
HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
"{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") +
"\nResponse is an array with the same size as the input that has the execution result :\n"
" [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n");
// clang-format on
if (!EnsureWalletIsAvailable(mainRequest.fHelp)) {
return NullUniValue;
}
RPCTypeCheck(mainRequest.params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ));
const UniValue& requests = mainRequest.params[0];
//Default options
bool fRescan = true;
if (mainRequest.params.size() > 1) {
const UniValue& options = mainRequest.params[1];
if (options.exists("rescan")) {
fRescan = options["rescan"].get_bool();
}
}
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
// Verify all timestamps are present before importing any keys.
const int64_t now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0;
for (const UniValue& data : requests.getValues()) {
GetImportTimestamp(data, now);
}
bool fRunScan = false;
const int64_t minimumTimestamp = 1;
int64_t nLowestTimestamp = 0;
if (fRescan && chainActive.Tip()) {
nLowestTimestamp = chainActive.Tip()->GetBlockTime();
} else {
fRescan = false;
}
UniValue response(UniValue::VARR);
BOOST_FOREACH (const UniValue& data, requests.getValues()) {
const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
const UniValue result = ProcessImport(data, timestamp);
response.push_back(result);
if (!fRescan) {
continue;
}
// If at least one request was successful then allow rescan.
if (result["success"].get_bool()) {
fRunScan = true;
}
// Get the lowest timestamp.
if (timestamp < nLowestTimestamp) {
nLowestTimestamp = timestamp;
}
}
if (fRescan && fRunScan && requests.size()) {
CBlockIndex* pindex = nLowestTimestamp > minimumTimestamp ? chainActive.FindEarliestAtLeast(std::max<int64_t>(nLowestTimestamp - 7200, 0)) : chainActive.Genesis();
CBlockIndex* scannedRange = nullptr;
if (pindex) {
scannedRange = pwalletMain->ScanForWalletTransactions(pindex, true);
pwalletMain->ReacceptWalletTransactions();
}
if (!scannedRange || scannedRange->nHeight > pindex->nHeight) {
std::vector<UniValue> results = response.getValues();
response.clear();
response.setArray();
size_t i = 0;
for (const UniValue& request : requests.getValues()) {
// If key creation date is within the successfully scanned
// range, or if the import result already has an error set, let
// the result stand unmodified. Otherwise replace the result
// with an error message.
if (GetImportTimestamp(request, now) - 7200 >= scannedRange->GetBlockTimeMax() || results.at(i).exists("error")) {
response.push_back(results.at(i));
} else {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, strprintf("Failed to rescan before time %d, transactions may be missing.", scannedRange->GetBlockTimeMax())));
response.push_back(std::move(result));
}
++i;
}
}
}
return response;
}
| 43.241259 | 328 | 0.616533 | Ankh-Trust |
e44e4c4347d86fc185952146b58e3a2663aa2efa | 641 | cpp | C++ | demo/main.cpp | Gustafsson88/lr_06 | 12c4c2651c577478331cd81bb2d07bf7ec133d5b | [
"MIT"
] | null | null | null | demo/main.cpp | Gustafsson88/lr_06 | 12c4c2651c577478331cd81bb2d07bf7ec133d5b | [
"MIT"
] | null | null | null | demo/main.cpp | Gustafsson88/lr_06 | 12c4c2651c577478331cd81bb2d07bf7ec133d5b | [
"MIT"
] | null | null | null | #include <header.hpp>
#include <mutex>
int main(int argc, char *argv[]) {
std::mutex mut;
Create_HASH::logging();
unsigned int thread_count;
if (argc >= 2)
{
thread_count = boost::lexical_cast<int unsigned>(argv[1]);
}
else thread_count = std::thread::hardware_concurrency();
std::cout << "Thread count: "<< thread_count << std::endl;
std::vector<std::thread> threads;
threads.reserve(thread_count);
for (unsigned i = 0; i < thread_count; i++) {
threads.emplace_back(Create_HASH::create_hash, std::ref(mut));
}
for (std::thread &thr : threads) {
thr.join();
}
Create_HASH::exit_f();
return 0;
}
| 24.653846 | 66 | 0.650546 | Gustafsson88 |
e44ff1593cdbb90d2f8be668979fef4b31dded58 | 4,149 | hpp | C++ | ZarroKey/UiMainWindow.hpp | MariusOlteanu/ZarroKey | d6bdedaa5ca1c5ffa531cbcc35af0a3b6aa7715d | [
"MIT"
] | null | null | null | ZarroKey/UiMainWindow.hpp | MariusOlteanu/ZarroKey | d6bdedaa5ca1c5ffa531cbcc35af0a3b6aa7715d | [
"MIT"
] | null | null | null | ZarroKey/UiMainWindow.hpp | MariusOlteanu/ZarroKey | d6bdedaa5ca1c5ffa531cbcc35af0a3b6aa7715d | [
"MIT"
] | null | null | null | //
// Copyright(c) 2022 Marius Olteanu olteanu.marius@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this softwareand 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 noticeand this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include "Utils.hpp"
#include "RegistryData.hpp"
class IoSymulator;
class UiMainWindow
{
public:
static UiMainWindow* CreateMainWindow(HINSTANCE instance, IoSymulator* _symulator, const wchar_t* registryPath)
{
static UiMainWindow window;
UiMainWindow::mainWindow = &window;
UiMainWindow::mainWindow->symulator = _symulator;
UiMainWindow::mainWindow->UiRegisterClass(instance);
UiMainWindow::mainWindow->registryData.Init(registryPath);
UiMainWindow::mainWindow->CreateMainWindow();
return UiMainWindow::mainWindow;
}
constexpr operator HWND() const noexcept { return this->window; }
void Run();
protected:
UiMainWindow();
void Update(uint32_t position);
void UpdateAll();
void UpdateProfileName();
RegistryData registryData;
windows_ptr<HFONT, decltype(&::DeleteObject)> font { ::DeleteObject };
windows_ptr<HFONT, decltype(&::DeleteObject)> fontText { ::DeleteObject };
windows_ptr<HFONT, decltype(&::DeleteObject)> fontSmall { ::DeleteObject };
windows_ptr<HBRUSH, decltype(&::DeleteObject)> backgroundColor { ::DeleteObject };
windows_ptr<HBRUSH, decltype(&::DeleteObject)> backgroundColorList { ::DeleteObject };
windows_ptr<HBRUSH, decltype(&::DeleteObject)> transparentColor { ::DeleteObject };
IoSymulator* symulator;
HINSTANCE instance;
HWND window;
HWND list;
HWND editList;
HWND edit[RegistryData::maxData];
bool init = false;
inline static UiMainWindow* mainWindow = nullptr;
private:
void UiRegisterClass(HINSTANCE _instance);
void CreateMainWindow();
__forceinline LRESULT MainWindow(HWND window, UINT message, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK MainWindowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam);
bool dragWindow = false;
POINT clickedPosition;
constexpr static uint32_t BUTTON_INFO_ID = 1;
constexpr static uint32_t BUTTON_ABOUT_ID = 2;
constexpr static uint32_t PICTURE_ID = 5;
constexpr static uint32_t COPYRIGHT_ID = 10;
constexpr static uint32_t TRANSPARENT_ID = 11;
constexpr static uint32_t LISTBOX_ID = 15;
constexpr static uint32_t EDITBOX_LIST_ID = 16;
constexpr static uint32_t EDITBOX_ID[RegistryData::maxData] =
{
21,
22,
23,
24,
25,
26
};
constexpr static uint32_t CHECKBOX_ID[RegistryData::maxData] =
{
31,
32,
33,
34,
35,
36
};
constexpr static wchar_t ZarroWindowName[] = L"Zarro Key Symulater";
constexpr static wchar_t ZarroClassName[] = L"ZarroClass";
constexpr static COLORREF TransparentColor = RGB(0x41, 0x51, 0x61);
constexpr static int32_t XWindowSize = 575;
constexpr static int32_t YWindowSize = 142;
};
| 31.431818 | 116 | 0.689082 | MariusOlteanu |
e4517071e0a1e791d4b33e2844e3b65937a674ad | 1,111 | hpp | C++ | include/polarai/utils/string/String.hpp | alexbatashev/athena | eafbb1e16ed0b273a63a20128ebd4882829aa2db | [
"MIT"
] | 2 | 2020-07-16T06:42:27.000Z | 2020-07-16T06:42:28.000Z | include/polarai/utils/string/String.hpp | PolarAI/polarai-framework | c5fd886732afe787a06ebf6fb05fc38069257457 | [
"MIT"
] | null | null | null | include/polarai/utils/string/String.hpp | PolarAI/polarai-framework | c5fd886732afe787a06ebf6fb05fc38069257457 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// Copyright (c) 2020 PolarAI. All rights reserved.
//
// Licensed under MIT 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.
//===----------------------------------------------------------------------===//
#pragma once
#include <polar_utils_export.h>
#include <polarai/utils/allocator/Allocator.hpp>
#include <cstddef>
namespace polarai::utils {
class POLAR_UTILS_EXPORT String {
public:
String();
String(const char* string, Allocator<byte> allocator = Allocator<byte>());
String(const String&);
String(String&&) noexcept;
~String();
[[nodiscard]] const char* getString() const;
[[nodiscard]] size_t getSize() const;
private:
size_t mSize;
Allocator<byte> mAllocator;
const char* mData;
};
} // namespace polarai::utils
| 30.027027 | 80 | 0.629163 | alexbatashev |
e45b2d1f7bd8756914f85113de8f1d8e07cd547e | 2,411 | hpp | C++ | dev/so_5/disp/prio_one_thread/quoted_round_robin/h/quotes.hpp | eao197/so-5-5 | fa0c31c84d2637dce04e13a155040150d505fbbd | [
"BSL-1.0"
] | 76 | 2016-03-25T15:22:03.000Z | 2022-02-03T15:11:43.000Z | dev/so_5/disp/prio_one_thread/quoted_round_robin/h/quotes.hpp | eao197/so-5-5 | fa0c31c84d2637dce04e13a155040150d505fbbd | [
"BSL-1.0"
] | 19 | 2017-03-09T19:21:53.000Z | 2021-02-24T13:02:18.000Z | dev/so_5/disp/prio_one_thread/quoted_round_robin/h/quotes.hpp | eao197/so-5-5 | fa0c31c84d2637dce04e13a155040150d505fbbd | [
"BSL-1.0"
] | 21 | 2016-09-23T10:01:09.000Z | 2020-08-31T12:01:10.000Z | /*
* SObjectizer-5
*/
/*!
* \since
* v.5.5.8
*
* \file
* \brief A storage of quotes for priorities.
*/
#pragma once
#include <so_5/h/priority.hpp>
#include <so_5/h/exception.hpp>
#include <so_5/h/ret_code.hpp>
#include <algorithm>
#include <iterator>
namespace so_5 {
namespace disp {
namespace prio_one_thread {
namespace quoted_round_robin {
/*!
* \since 5.5.8
* \brief A storage of quotes for priorities.
*
* A usage example:
\code
using namespace so_5::disp::prio_one_thread::quoted_round_robin;
quotes_t quotes{ 150 }; // Default value for all priorities.
quotes.set( so_5::prio::p7, 350 ); // New quote for p7.
quotes.set( so_5::prio::p6, 250 ); // New quote for p6.
// All other quotes will be 150.
...
create_private_disp( env, quotes );
\endcode
Another example:
\code
using namespace so_5::disp::prio_one_thread::quoted_round_robin;
create_private_disp( env,
quotes_t{ 150 } // Default value for all priorites.
.set( so_5::prio::p7, 350 ) // New quote for p7.
.set( so_5::prio::p6, 250 ) // New quote for p6
);
\endcode
* \attention Value of 0 is illegal. An exception will be throw on
* attempt of setting 0 as a quote value.
*/
class quotes_t
{
public :
//! Initializing constructor sets the default value for
//! every priority.
quotes_t( std::size_t default_value )
{
ensure_quote_not_zero( default_value );
std::fill( std::begin(m_quotes), std::end(m_quotes), default_value );
}
//! Set a new quote for a priority.
quotes_t &
set(
//! Priority to which a new quote to be set.
priority_t prio,
//! Quote value.
std::size_t quote )
{
ensure_quote_not_zero( quote );
m_quotes[ to_size_t( prio ) ] = quote;
return *this;
}
//! Get the quote for a priority.
size_t
query( priority_t prio ) const
{
return m_quotes[ to_size_t( prio ) ];
}
private :
//! Quotes for every priority.
std::size_t m_quotes[ so_5::prio::total_priorities_count ];
static void
ensure_quote_not_zero( std::size_t value )
{
if( !value )
SO_5_THROW_EXCEPTION( rc_priority_quote_illegal_value,
"quote for a priority cannot be zero" );
}
};
} /* namespace quoted_round_robin */
} /* namespace prio_one_thread */
} /* namespace disp */
} /* namespace so_5 */
| 21.918182 | 74 | 0.636251 | eao197 |
e45cd53c74a73fa804416f878ee5dfd9801baa74 | 6,047 | cpp | C++ | apps/LkDemo/LkDemo.cpp | hcl3210/opencv | b34b1c3540716a3dadfd2b9e3bbc4253774c636d | [
"BSD-3-Clause"
] | 1 | 2016-05-09T11:42:00.000Z | 2016-05-09T11:42:00.000Z | apps/LkDemo/LkDemo.cpp | hcl3210/opencv | b34b1c3540716a3dadfd2b9e3bbc4253774c636d | [
"BSD-3-Clause"
] | null | null | null | apps/LkDemo/LkDemo.cpp | hcl3210/opencv | b34b1c3540716a3dadfd2b9e3bbc4253774c636d | [
"BSD-3-Clause"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/// LkDemo.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "LkDemo.h"
#include "MainFrm.h"
#include "LkDemoDoc.h"
#include "LkDemoView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CLkDemoApp
BEGIN_MESSAGE_MAP(CLkDemoApp, CWinApp)
//{{AFX_MSG_MAP(CLkDemoApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLkDemoApp construction
CLkDemoApp::CLkDemoApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CLkDemoApp object
CLkDemoApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CLkDemoApp initialization
BOOL CLkDemoApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views.
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CLkDemoDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CLkDemoView));
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it.
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
// No message handlers
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// App command to run the dialog
void CLkDemoApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
/////////////////////////////////////////////////////////////////////////////
// CLkDemoApp message handlers
| 31.494792 | 90 | 0.680172 | hcl3210 |
e45ce52bd7a604b9356c17d9b009ceb92cc069bb | 1,445 | cpp | C++ | Userland/Applications/PixelPaint/ProjectLoader.cpp | qeeg/serenity | 587048dea7465f387b0ef8bbe439060c448bd996 | [
"BSD-2-Clause"
] | 6 | 2021-07-05T15:01:19.000Z | 2022-03-24T04:42:43.000Z | Userland/Applications/PixelPaint/ProjectLoader.cpp | qeeg/serenity | 587048dea7465f387b0ef8bbe439060c448bd996 | [
"BSD-2-Clause"
] | 2 | 2022-01-11T13:08:35.000Z | 2022-01-12T19:27:53.000Z | Userland/Applications/PixelPaint/ProjectLoader.cpp | qeeg/serenity | 587048dea7465f387b0ef8bbe439060c448bd996 | [
"BSD-2-Clause"
] | 1 | 2020-03-16T21:37:46.000Z | 2020-03-16T21:37:46.000Z | /*
* Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "ProjectLoader.h"
#include "Image.h"
#include "Layer.h"
#include <AK/JsonObject.h>
#include <AK/Result.h>
#include <AK/String.h>
#include <LibCore/File.h>
#include <LibCore/MappedFile.h>
#include <LibImageDecoderClient/Client.h>
namespace PixelPaint {
ErrorOr<void> ProjectLoader::try_load_from_fd_and_close(int fd, StringView path)
{
auto file = Core::File::construct();
file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No);
if (file->has_error())
return Error::from_errno(file->error());
auto contents = file->read_all();
auto json_or_error = JsonValue::from_string(contents);
if (json_or_error.is_error()) {
m_is_raw_image = true;
auto mapped_file = TRY(Core::MappedFile::map_from_fd_and_close(fd, path));
// FIXME: Find a way to avoid the memory copy here.
auto bitmap = TRY(Image::try_decode_bitmap(mapped_file->bytes()));
auto image = TRY(Image::try_create_from_bitmap(move(bitmap)));
m_image = image;
return {};
}
close(fd);
auto& json = json_or_error.value().as_object();
auto image = TRY(Image::try_create_from_pixel_paint_json(json));
if (json.has("guides"))
m_json_metadata = json.get("guides").as_array();
m_image = image;
return {};
}
}
| 26.759259 | 88 | 0.672664 | qeeg |
e45ceedbcac69101a3ee07122f37e6a76eac6bfd | 6,577 | cpp | C++ | irrlicht/examples/IrrlichtML/main.cpp | ousttrue/onibi | 016550c040182dbdc2b13fb0cef5f442c58bd8f4 | [
"FTL"
] | 1 | 2021-02-23T07:43:45.000Z | 2021-02-23T07:43:45.000Z | irrlicht/examples/IrrlichtML/main.cpp | ousttrue/onibi | 016550c040182dbdc2b13fb0cef5f442c58bd8f4 | [
"FTL"
] | null | null | null | irrlicht/examples/IrrlichtML/main.cpp | ousttrue/onibi | 016550c040182dbdc2b13fb0cef5f442c58bd8f4 | [
"FTL"
] | 1 | 2020-04-28T01:15:47.000Z | 2020-04-28T01:15:47.000Z | /*
* Irrlicht FreeType Demo
*/
#include <irrlicht.h>
#include <stdio.h>
#include "driverChoice.h"
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;
// Change your favorite settings
#define SIZE_FONT_NORMAL 12
#define SIZE_FONT_BIG 24
#ifdef _IRR_WINDOWS_
#define FONTPATH1 L"C:\\Windows\\Fonts\\arial.ttf"
#define FONTPATH2 L"C:\\Windows\\Fonts\\times.ttf"
#define FONTPATH3 L"C:\\Windows\\Fonts\\msgothic.ttc"
#else // for Linux (Ubuntu)
#define FONTPATH1 L"/usr/share/fonts/truetype/freefont/FreeSans.ttf"
#define FONTPATH2 L"/usr/share/fonts/truetype/freefont/FreeSerif.ttf"
#define FONTPATH3 L"/usr/share/fonts/truetype/ttf-japanese-gothic.ttf"
#endif
IrrlichtDevice *Device;
s32 cnt = 0;
s32 lang = 0;
IGUIListBox* listbox = 0;
IGUIListBox* lstLang = 0;
IGUIStaticText* txtTrans = 0;
IGUIStaticText* txtLog = 0;
IGUIButton *btnQuit = 0;
IGUIButton *btnNew = 0;
IGUIButton *btnFile = 0;
IGUIEditBox *edtName = 0;
IGUIEditBox *edtMemo = 0;
IGUIFont *fonts[6],*font,*font2;
IGUISkin* skin;
/*
* Japanese Texts
*/
wchar_t jtxtTrans[] = {0x900f,0x660e,0x5ea6,0x8a2d,0x5b9a,0x003a,0};
wchar_t jtxtQuit[] = {0x7d42,0x308f,0x308b,0};
wchar_t jtxtNew[] = {0x65b0,0x898f,0x30a6,0x30a3,0x30f3,0x30c9,0x30a6,0};
wchar_t jtxtFile[] = {0x30d5,0x30a1,0x30a4,0x30eb,0x3092,0x958b,0x304f,0};
wchar_t jtxtLog[] = {0x64cd,0x4f5c,0x30ed,0x30b0,0};
wchar_t jtxtTfont[] = {0x900f,0x904e,0x30d5,0x30a9,0x30f3,0x30c8,0};
wchar_t jtxtHello[] = {0x3053,0x3093,0x306b,0x3061,0x306f,0x30c8,0x30a5,0x30eb,0x30fc,0x30bf,0x30a4,0x30d7,0};
void ChangeCaption(s32 newlang){
lang = newlang;
switch(lang){
case 0: // English
txtTrans->setText(L"Transparency:");
btnQuit->setText(L"Quit");
btnNew->setText(L"New Window");
btnFile->setText(L"Open File");
txtLog->setText(L"Logging ListBox:");
break;
case 1: // Japanese
txtTrans->setText(jtxtTrans);
btnQuit->setText(jtxtQuit);
btnNew->setText(jtxtNew);
btnFile->setText(jtxtFile);
txtLog->setText(jtxtLog);
break;
}
}
class MyEventReceiver : public IEventReceiver
{
public:
virtual bool OnEvent(const SEvent& event)
{
if (event.EventType == EET_GUI_EVENT)
{
s32 id = event.GUIEvent.Caller->getID();
IGUIEnvironment* env = Device->getGUIEnvironment();
switch(event.GUIEvent.EventType)
{
case EGET_SCROLL_BAR_CHANGED:
if (id == 104)
{
s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos();
for (s32 i=0; i<EGDC_COUNT ; ++i)
{
SColor col = env->getSkin()->getColor((EGUI_DEFAULT_COLOR)i);
col.setAlpha(pos);
env->getSkin()->setColor((EGUI_DEFAULT_COLOR)i, col);
}
}
break;
case EGET_BUTTON_CLICKED:
if (id == 101)
{
Device->closeDevice();
return true;
}
if (id == 102)
{
listbox->addItem(L"Window created");
cnt += 30;
if (cnt > 200)
cnt = 0;
IGUIWindow* window = env->addWindow(
rect<s32>(100 + cnt, 100 + cnt, 300 + cnt, 200 + cnt),
false, // modal?
L"Test window");
env->addStaticText(L"Please close me",
rect<s32>(35,35,140,50),
true, // border?
false, // wordwrap?
window);
return true;
}
if (id == 103)
{
listbox->addItem(L"File open");
env->addFileOpenDialog(L"Please choose a file.");
return true;
}
break;
case EGET_LISTBOX_CHANGED:
case EGET_LISTBOX_SELECTED_AGAIN:
if (id == 120){
int sel = lstLang->getSelected();
font = fonts[sel * 2];
font2 = fonts[sel * 2 + 1];
skin->setFont(font);
if (sel == 2){
ChangeCaption(1);
} else {
ChangeCaption(0);
}
}
break;
}
}
return false;
}
};
int main()
{
// ask user for driver
video::E_DRIVER_TYPE driverType=driverChoiceConsole();
if (driverType==video::EDT_COUNT)
return 1;
// create device and exit if creation failed
Device = createDevice(driverType, core::dimension2d<u32>(640, 480));
if(Device == NULL)
return 1;
IVideoDriver *Driver = Device->getVideoDriver();
IGUIEnvironment* env = Device->getGUIEnvironment();
ISceneManager *Scene = Device->getSceneManager();
Scene->addCameraSceneNode(0, vector3df(0,10,-40), vector3df(0,0,0));
MyEventReceiver receiver;
Device->setEventReceiver(&receiver);
// Load fonts
fonts[0] = env->getFont(FONTPATH1);
fonts[1] = env->getFont(FONTPATH1);
fonts[2] = env->getFont(FONTPATH2);
fonts[3] = env->getFont(FONTPATH2);
fonts[4] = env->getFont(FONTPATH3);
fonts[5] = env->getFont(FONTPATH3);
font = fonts[0];
font2 = fonts[1];
skin = env->getSkin();
skin->setFont(font);
txtTrans = env->addStaticText(L"Transparency:", rect<s32>(50,20,250,40), true);
IGUIScrollBar* scrollbar = env->addScrollBar(true, rect<s32>(50, 45, 250, 60), 0, 104);
scrollbar->setMax(255);
SColor col = env->getSkin()->getColor((EGUI_DEFAULT_COLOR)0);
scrollbar->setPos(col.getAlpha());
txtLog = env->addStaticText(L"Logging ListBox:", rect<s32>(50,80,250,100), true);
listbox = env->addListBox(rect<s32>(50, 110, 250, 180));
btnQuit = env->addButton(rect<s32>(10,210,100,240), 0, 101, L"Quit");
btnNew = env->addButton(rect<s32>(10,250,100,290), 0, 102, L"New Window");
btnFile = env->addButton(rect<s32>(10,300,100,340), 0, 103, L"Open File");
edtName = env->addEditBox(L"",rect<s32>(300,60,580,80));
edtName->setMax(40);
edtMemo = env->addEditBox(L"",rect<s32>(300,100,580,450));
edtMemo->setMultiLine(true);
edtMemo->setTextAlignment(EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
lstLang = env->addListBox(rect<s32>(10, 400, 250, 470),0,120);
lstLang->addItem(L"Arial");
lstLang->addItem(L"Times Roman");
lstLang->addItem(L"MS-Gothic(Japanese)");
lstLang->setSelected(0);
int lastFPS = -1;
while(Device->run())
{
Driver->beginScene(true, true, SColor(0,64,64,128));
Scene->drawAll();
if (!lang){
font2->draw(L"Hello TrueType",rect<s32>(250,20,640,100),SColor(255,255,64,64),true);
} else {
font2->draw(jtxtHello,rect<s32>(250,20,640,100),SColor(255,255,64,64),true);
}
env->drawAll();
Driver->endScene();
int fps = Driver->getFPS();
if (lastFPS != fps)
{
wchar_t tmp[1024];
//snwprintf(tmp, 1024, L"Irrlicht TrueType Demo (fps:%d)", fps);
swprintf(tmp, L"Irrlicht TrueType Demo (fps:%d)", fps);
Device->setWindowCaption(tmp);
lastFPS = fps;
}
}
#if !defined(_IRR_COMPILE_WITH_CGUITTFONT_)
for(int i= 0; i < 6; i++)
{
if(fonts[i] != NULL)
fonts[i]->drop();
}
#endif
Device->drop();
return 0;
}
| 25.296154 | 110 | 0.661092 | ousttrue |
e46a0b2a3c212927e5af453de8023340be0d349c | 6,220 | cpp | C++ | source/shared/cpp/AdaptiveCardsSharedModel/AdaptiveCardsSharedModelUnitTest/SemanticVersionTest.cpp | chienjchienj/AdaptiveCards | 949dc9b472cad9c34e8bb10e0c290eccbff56a92 | [
"MIT"
] | 1 | 2021-03-26T11:27:18.000Z | 2021-03-26T11:27:18.000Z | source/shared/cpp/AdaptiveCardsSharedModel/AdaptiveCardsSharedModelUnitTest/SemanticVersionTest.cpp | chienjchienj/AdaptiveCards | 949dc9b472cad9c34e8bb10e0c290eccbff56a92 | [
"MIT"
] | 12 | 2022-02-14T13:41:37.000Z | 2022-02-27T17:34:28.000Z | source/shared/cpp/AdaptiveCardsSharedModel/AdaptiveCardsSharedModelUnitTest/SemanticVersionTest.cpp | chienjchienj/AdaptiveCards | 949dc9b472cad9c34e8bb10e0c290eccbff56a92 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "SemanticVersion.h"
#include "AdaptiveCardParseException.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace AdaptiveCards;
namespace AdaptiveCardsSharedModelUnitTest
{
TEST_CLASS(SemanticVersionTests)
{
public:
TEST_METHOD(PositiveTest)
{
{
SemanticVersion version("1");
Assert::AreEqual(1U, version.GetMajor());
Assert::AreEqual(0U, version.GetMinor());
Assert::AreEqual(0U, version.GetBuild());
Assert::AreEqual(0U, version.GetRevision());
}
{
SemanticVersion version("10.2");
Assert::AreEqual(10U, version.GetMajor());
Assert::AreEqual(2U, version.GetMinor());
Assert::AreEqual(0U, version.GetBuild());
Assert::AreEqual(0U, version.GetRevision());
}
{
SemanticVersion version("100.20.3");
Assert::AreEqual(100U, version.GetMajor());
Assert::AreEqual(20U, version.GetMinor());
Assert::AreEqual(3U, version.GetBuild());
Assert::AreEqual(0U, version.GetRevision());
}
{
SemanticVersion version("1000.200.30.4");
Assert::AreEqual(1000U, version.GetMajor());
Assert::AreEqual(200U, version.GetMinor());
Assert::AreEqual(30U, version.GetBuild());
Assert::AreEqual(4U, version.GetRevision());
}
{
SemanticVersion version("1000.200.30.40");
Assert::AreEqual(1000U, version.GetMajor());
Assert::AreEqual(200U, version.GetMinor());
Assert::AreEqual(30U, version.GetBuild());
Assert::AreEqual(40U, version.GetRevision());
}
}
TEST_METHOD(NegativeTest)
{
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version(""); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("text"); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1234567890123456789012345678901234567890"); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1."); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1.2."); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1.2.3."); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1.2.3.4."); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version(" 1.0"); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1.0 "); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("-1"); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("0xF"); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("F"); });
Assert::ExpectException<AdaptiveCardParseException>([&]() { SemanticVersion version("1.c"); });
}
TEST_METHOD(CompareTest)
{
{
SemanticVersion lhs("1");
SemanticVersion rhs("1.000000.0000000.0000000");
Assert::IsTrue(lhs == rhs);
Assert::IsFalse(lhs != rhs);
Assert::IsFalse(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsTrue(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
{
SemanticVersion lhs("1.1");
SemanticVersion rhs("1.001");
Assert::IsTrue(lhs == rhs);
Assert::IsFalse(lhs != rhs);
Assert::IsFalse(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsTrue(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
{
SemanticVersion lhs("1.0");
SemanticVersion rhs("1.1");
Assert::IsFalse(lhs == rhs);
Assert::IsTrue(lhs != rhs);
Assert::IsTrue(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsFalse(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
{
SemanticVersion lhs("1.0");
SemanticVersion rhs("1.0.1");
Assert::IsFalse(lhs == rhs);
Assert::IsTrue(lhs != rhs);
Assert::IsTrue(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsFalse(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
{
SemanticVersion lhs("1.1.2");
SemanticVersion rhs("1.1.3");
Assert::IsFalse(lhs == rhs);
Assert::IsTrue(lhs != rhs);
Assert::IsTrue(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsFalse(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
{
SemanticVersion lhs("1.1.3.100");
SemanticVersion rhs("1.1.4.1");
Assert::IsFalse(lhs == rhs);
Assert::IsTrue(lhs != rhs);
Assert::IsTrue(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsFalse(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
{
SemanticVersion lhs("1.3.1");
SemanticVersion rhs("1.10.2");
Assert::IsFalse(lhs == rhs);
Assert::IsTrue(lhs != rhs);
Assert::IsTrue(lhs < rhs);
Assert::IsFalse(lhs > rhs);
Assert::IsFalse(lhs >= rhs);
Assert::IsTrue(lhs <= rhs);
}
}
};
}
| 40.129032 | 144 | 0.505145 | chienjchienj |
e46a7f445a57e19c8f5f3a74eb0717ac01e3e3c6 | 2,633 | cpp | C++ | solutions/LeetCode/C++/872.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/872.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/872.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 4 ms submission
static int speedup = []() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
vector<int> t1, t2;
void preOrder(TreeNode* root)
{
if (root == NULL)
return;
preOrder(root->left);
if(root->left == NULL && root->right == NULL)
t1.push_back(root->val);
preOrder(root->right);
}
int cnt = 0;
bool preOrder1(TreeNode* root)
{
if (root == NULL)
return true;
if (preOrder1(root->left) == false)
return false;
if (root->left == NULL && root->right == NULL)
{
if (root->val != t1[cnt])
return false;
cnt++;
}
if (preOrder1(root->right) == false)
return false;
return true;
}
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
cnt = 0;
t1.clear();
preOrder(root1);
return preOrder1(root2);
}
};
__________________________________________________________________________________________________
sample 13432 kb submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
bool isLeaf(TreeNode* node) {
return node->left==NULL && node->right==NULL;
}
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL && root2 == NULL) {
return true;
}
if (root1 == NULL || root2 == NULL) {
return false;
}
stack<TreeNode*> s1, s2;
s1.push(root1);
s2.push(root2);
while (!s1.empty() && !s2.empty()) {
TreeNode *r1=s1.top(), *r2=s2.top();
s1.pop();
if (r1->right!=NULL) {
s1.push(r1->right);
}
if (r1->left!=NULL) {
s1.push(r1->left);
}
s2.pop();
if (r2->right!=NULL) {
s2.push(r2->right);
}
if (r2->left!=NULL) {
s2.push(r2->left);
}
if (isLeaf(r1) && isLeaf(r2)) {
if (r1->val != r2->val) {
return false;
}
}
if (isLeaf(r1) && !isLeaf(r2)) {
s1.push(r1);
}
if (!isLeaf(r1) && isLeaf(r2)) {
s2.push(r2);
}
}
return (s1.empty() && s2.empty());
}
};
__________________________________________________________________________________________________
| 22.698276 | 98 | 0.533992 | timxor |
e46f80ba3cc7d93993b02fc35d12cf51659b828c | 2,523 | cpp | C++ | daemon/SummaryBuffer.cpp | rossburton/gator | 9d8d75fa08352470c51abc23fe3b314879bd8b78 | [
"BSD-3-Clause"
] | 118 | 2015-03-24T16:09:42.000Z | 2022-03-21T09:01:59.000Z | daemon/SummaryBuffer.cpp | rossburton/gator | 9d8d75fa08352470c51abc23fe3b314879bd8b78 | [
"BSD-3-Clause"
] | 26 | 2016-03-03T23:24:08.000Z | 2022-03-21T10:24:43.000Z | daemon/SummaryBuffer.cpp | rossburton/gator | 9d8d75fa08352470c51abc23fe3b314879bd8b78 | [
"BSD-3-Clause"
] | 73 | 2015-06-09T09:44:06.000Z | 2021-12-30T09:49:00.000Z | /* Copyright (C) 2013-2020 by Arm Limited. All rights reserved. */
#define BUFFER_USE_SESSION_DATA
#include "SummaryBuffer.h"
#include "BufferUtils.h"
#include "Logging.h"
#include "SessionData.h"
#include <cstring>
SummaryBuffer::SummaryBuffer(const int size, sem_t & readerSem) : buffer(size, readerSem)
{
// fresh buffer will always have room for header
// so no need to check space
buffer.beginFrame(FrameType::SUMMARY);
}
void SummaryBuffer::write(ISender & sender)
{
buffer.write(sender);
}
int SummaryBuffer::bytesAvailable() const
{
return buffer.bytesAvailable();
}
void SummaryBuffer::flush()
{
buffer.endFrame();
buffer.flush();
buffer.waitForSpace(IRawFrameBuilder::MAX_FRAME_HEADER_SIZE);
buffer.beginFrame(FrameType::SUMMARY);
}
void SummaryBuffer::summary(const int64_t timestamp,
const int64_t uptime,
const int64_t monotonicDelta,
const char * const uname,
const long pageSize,
const bool nosync,
const std::map<std::string, std::string> & additionalAttributes)
{
// This is only called when buffer is empty so no need to wait for space
// we assume the additional attributes won't overflow the buffer??
buffer.packInt(static_cast<int32_t>(MessageType::SUMMARY));
buffer.writeString(NEWLINE_CANARY);
buffer.packInt64(timestamp);
buffer.packInt64(uptime);
buffer.packInt64(monotonicDelta);
buffer.writeString("uname");
buffer.writeString(uname);
buffer.writeString("PAGESIZE");
char buf[32];
snprintf(buf, sizeof(buf), "%li", pageSize);
buffer.writeString(buf);
if (nosync) {
buffer.writeString("nosync");
buffer.writeString("");
}
for (const auto & pair : additionalAttributes) {
if (!pair.first.empty()) {
buffer.writeString(pair.first.c_str());
buffer.writeString(pair.second.c_str());
}
}
buffer.writeString("");
}
void SummaryBuffer::coreName(const int core, const int cpuid, const char * const name)
{
waitForSpace(3 * buffer_utils::MAXSIZE_PACK32 + 0x100);
buffer.packInt(static_cast<int32_t>(MessageType::CORE_NAME));
buffer.packInt(core);
buffer.packInt(cpuid);
buffer.writeString(name);
}
void SummaryBuffer::waitForSpace(int bytes)
{
if (bytes < buffer.bytesAvailable()) {
flush();
}
buffer.waitForSpace(bytes);
}
| 29 | 92 | 0.650416 | rossburton |
e470a5bea09fc55a1ad16c9b67faa6cad0f85501 | 1,882 | cpp | C++ | EightQueen.cpp | chenshiyang/Algorithm-C- | fc0f6c005b773d07ce03861c0f4f0f5411fc84c5 | [
"Apache-2.0"
] | null | null | null | EightQueen.cpp | chenshiyang/Algorithm-C- | fc0f6c005b773d07ce03861c0f4f0f5411fc84c5 | [
"Apache-2.0"
] | null | null | null | EightQueen.cpp | chenshiyang/Algorithm-C- | fc0f6c005b773d07ce03861c0f4f0f5411fc84c5 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std;
const int NUM = 8;
void print_table(vector<vector<bool>> &table) {
cout << "A valid solution: " << endl;
for(int i = 0; i != NUM; ++ i) {
for(int j = 0; j != NUM; ++ j) {
cout << (table[i][j] ? "Q " : "+ ");
}
cout << "\n";
}
cout << endl;
}
bool dangerous(vector<bool> &row, vector<bool> &col, vector<bool> &left_slant, vector<bool> &right_slant, int i, int j) {
return (row[i] || col[j] || left_slant[i + j] || right_slant[i + NUM - 1 - j]);
}
void backtrack(vector<vector<bool>> &table, vector<bool> &row, vector<bool> &col, vector<bool> &left_slant, vector<bool> &right_slant, int index) {
if(index == NUM) {
print_table(table);
return;
}
for(int j = 0; j != NUM; ++ j) {
if(!dangerous(row, col, left_slant, right_slant, index, j)) {
table[index][j] = true;;
row[index] = true;
col[j] = true;
left_slant[index + j] = true;
right_slant[index - j + NUM - 1] = true;
backtrack(table, row, col, left_slant, right_slant, index + 1);
table[index][j] = false;
row[index] = false;
col[j] = false;
left_slant[index + j] = false;
right_slant[index - j + NUM - 1] = false;
}
}
}
void solve(vector<vector<bool>> &table) {
vector<bool> row(NUM, false);
vector<bool> col(NUM, false);
vector<bool> left_slant(2 * NUM - 1, false);
vector<bool> right_slant(2 * NUM - 1, false);
backtrack(table, row, col, left_slant, right_slant, 0);
}
int main() {
vector<vector<bool>> table;
vector<bool> line(NUM, false);
for(int i = 0; i != NUM; ++ i) {
table.push_back(line);
}
solve(table);
}
| 29.873016 | 148 | 0.517003 | chenshiyang |
e47244b6c2aaadac557db5eb7b6e585c3abc4b4b | 1,353 | cc | C++ | third_party/blink/renderer/platform/context_lifecycle_notifier.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/platform/context_lifecycle_notifier.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/platform/context_lifecycle_notifier.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/context_lifecycle_notifier.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/context_lifecycle_observer.h"
namespace blink {
ContextLifecycleNotifier::~ContextLifecycleNotifier() {
#if DCHECK_IS_ON()
// `NotifyContextDestroyed()` must be called prior to destruction.
DCHECK(did_notify_observers_);
#endif
}
void ContextLifecycleNotifier::AddContextLifecycleObserver(
ContextLifecycleObserver* observer) {
observers_.AddObserver(observer);
}
void ContextLifecycleNotifier::RemoveContextLifecycleObserver(
ContextLifecycleObserver* observer) {
DCHECK(observers_.HasObserver(observer));
observers_.RemoveObserver(observer);
}
void ContextLifecycleNotifier::NotifyContextDestroyed() {
ScriptForbiddenScope forbid_script;
observers_.ForEachObserver([](ContextLifecycleObserver* observer) {
observer->NotifyContextDestroyed();
});
observers_.Clear();
#if DCHECK_IS_ON()
did_notify_observers_ = true;
#endif
}
void ContextLifecycleNotifier::Trace(Visitor* visitor) const {
visitor->Trace(observers_);
}
} // namespace blink
| 28.787234 | 80 | 0.796009 | zealoussnow |
e4730746fa0db58c2f1a3ad1f4d248d95224ebba | 696 | cpp | C++ | Topology.cpp | TheHolyBell/Hardware3D | 1879c498645dfec874ab25497d1c830482bbf0c7 | [
"MIT"
] | null | null | null | Topology.cpp | TheHolyBell/Hardware3D | 1879c498645dfec874ab25497d1c830482bbf0c7 | [
"MIT"
] | null | null | null | Topology.cpp | TheHolyBell/Hardware3D | 1879c498645dfec874ab25497d1c830482bbf0c7 | [
"MIT"
] | null | null | null | #include "Topology.h"
#include "BindableCodex.h"
namespace Bind
{
Topology::Topology(Graphics& gfx, D3D11_PRIMITIVE_TOPOLOGY topology)
: m_Topology(topology)
{
}
void Topology::Bind(Graphics& gfx) noxnd
{
GetContext(gfx)->IASetPrimitiveTopology(m_Topology);
}
std::string Topology::GetUID() const noexcept
{
return GenerateUID(m_Topology);
}
std::shared_ptr<Topology> Topology::Resolve(Graphics& gfx, D3D11_PRIMITIVE_TOPOLOGY topology)
{
return Codex::Resolve<Topology>(gfx, topology);
}
std::string Topology::GenerateUID(D3D11_PRIMITIVE_TOPOLOGY topology)
{
using namespace std::string_literals;
return typeid(Topology).name() + "#"s + std::to_string(topology);
}
} | 24 | 94 | 0.747126 | TheHolyBell |